file_path
stringlengths 32
153
| content
stringlengths 0
3.14M
|
---|---|
omniverse-code/kit/include/carb/extras/Semaphore.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../cpp/Semaphore.h"
namespace carb
{
namespace extras
{
class CARB_DEPRECATED("Deprecated: carb::extras::binary_semaphore has moved to carb::cpp::binary_semaphore") binary_semaphore
: public carb::cpp::binary_semaphore
{
public:
constexpr explicit binary_semaphore(ptrdiff_t desired) : carb::cpp::binary_semaphore(desired)
{
}
};
template <ptrdiff_t least_max_value = carb::cpp::detail::kSemaphoreValueMax>
class CARB_DEPRECATED("Deprecated: carb::extras::counting_semaphore has moved to carb::cpp::counting_semaphore")
counting_semaphore : public carb::cpp::counting_semaphore<least_max_value>
{
public:
constexpr explicit counting_semaphore(ptrdiff_t desired) : carb::cpp::counting_semaphore<least_max_value>(desired)
{
}
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/EnvironmentVariable.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Provides a helper class for getting, setting, and restoring environment variables.
//
#pragma once
#include "../Defines.h"
#include "../cpp/Optional.h"
#include <cstring>
#include <string>
#include <utility>
#if CARB_PLATFORM_LINUX
# include <cstdlib>
#endif
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
# include "../../omni/extras/ScratchBuffer.h"
# include "Unicode.h"
# include <vector>
#endif
namespace carb
{
namespace extras
{
/**
* Defines an environment variable class that allows one to get, set, and restore value on destruction.
*/
class EnvironmentVariable final
{
CARB_PREVENT_COPY(EnvironmentVariable);
template <typename T>
using optional = ::carb::cpp::optional<T>;
public:
EnvironmentVariable() = delete;
/**
* Create instance from environment variable called @p name.
*
* @param name name of the environment variable
*/
EnvironmentVariable(std::string name)
: m_name(std::move(name)), m_restore(false), m_restoreValue(carb::cpp::nullopt)
{
CARB_ASSERT(!m_name.empty());
}
/**
* Create instance from environment variable called @p name, setting it's value to @p value, to be restored to
* it's original value on destruction.
*
* @param name name of the environment variable
* @param value optional value to set variable, if not set (nullopt) then unset the variable
*/
EnvironmentVariable(std::string name, const optional<const std::string>& value)
: m_name(std::move(name)), m_restore(false), m_restoreValue(carb::cpp::nullopt)
{
CARB_ASSERT(!m_name.empty());
// attempt to get and store current value
std::string currentValue;
if (getValue(m_name.c_str(), currentValue))
{
m_restoreValue = currentValue;
}
// attempt to set to new value
if (setValue(m_name.c_str(), value ? value->c_str() : nullptr))
{
m_restore = true;
}
}
~EnvironmentVariable()
{
if (m_restore)
{
bool ret = setValue(m_name.c_str(), m_restoreValue ? m_restoreValue->c_str() : nullptr);
CARB_ASSERT(ret);
CARB_UNUSED(ret);
}
}
/** move constructor */
EnvironmentVariable(EnvironmentVariable&& other)
: m_name(std::move(other.m_name)),
m_restore(std::exchange(other.m_restore, false)),
m_restoreValue(std::move(other.m_restoreValue))
{
}
/** move operator */
EnvironmentVariable& operator=(EnvironmentVariable&& other)
{
m_name = std::move(other.m_name);
m_restore = std::exchange(other.m_restore, false);
m_restoreValue = std::move(other.m_restoreValue);
return *this;
}
/**
* Get the environment variable name
*
* @return environment variable name
*/
const std::string& getName() const noexcept
{
return m_name;
}
/**
* Get the environment variable current value
*
* @return environment variable current value
*/
optional<const std::string> getValue() const noexcept
{
optional<const std::string> result;
std::string value;
if (getValue(m_name.c_str(), value))
{
result = value;
}
return result;
}
/**
* Sets new environment value for a variable.
*
* @param name Environment variable string that we want to get the value for.
* @param value The value of environment variable to get (MAX 256 characters).
* Can be nullptr - which means the variable should be unset.
*
* @return true if the operation was successful.
*/
static bool setValue(const char* name, const char* value)
{
bool result;
// Set the new value
#if CARB_PLATFORM_WINDOWS
std::wstring nameWide = convertUtf8ToWide(name);
if (value)
{
std::wstring valueWide = convertUtf8ToWide(value);
result = (SetEnvironmentVariableW(nameWide.c_str(), valueWide.c_str()) != 0);
}
else
{
result = (SetEnvironmentVariableW(nameWide.c_str(), nullptr) != 0);
}
#else
if (value)
{
result = (setenv(name, value, /*overwrite=*/1) == 0);
}
else
{
result = (unsetenv(name) == 0);
}
#endif
return result;
}
/**
* Static helper to get the value of the current environment variable.
*
* @param name Environment variable string that we want to get the value for.
* @param value The value of environment variable to get.
*
* @return true if the variable exists
*/
static bool getValue(const char* name, std::string& value)
{
#if CARB_PLATFORM_WINDOWS
std::wstring nameWide = convertUtf8ToWide(name);
omni::extras::ScratchBuffer<wchar_t> buffer;
while (true)
{
DWORD count = GetEnvironmentVariableW(nameWide.c_str(), buffer.data(), static_cast<DWORD>(buffer.size()));
if (count == 0)
{
if (GetLastError() == 0)
{
// no error but no count means we got an empty env var
value = "";
return true;
}
else
{
// the error case here means the env var does not exist
return false;
}
}
else if (count < buffer.size())
{
// success case
value = convertWideToUtf8(buffer.data());
return true;
}
else
{
// env var is too large for the current buffer -- grow it and try again
buffer.resize(count + 1U); // include null termination
continue;
}
}
#else
const char* buffer = getenv(name);
if (buffer == nullptr)
{
return false;
}
value = buffer; // Copy string
#endif
return true;
}
private:
std::string m_name;
bool m_restore;
optional<const std::string> m_restoreValue;
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Guid.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include <cstdio>
#include <string>
CARB_IGNOREWARNING_MSC_WITH_PUSH(4996) // disable complaint about _sscanf etc. on Windows, which hurts portability
namespace carb
{
namespace extras
{
/**
* A Global Unique Identifier (GUID)
*/
struct Guid
{
uint32_t data1;
uint16_t data2;
uint16_t data3;
uint8_t data4[8];
};
/**
* Converts string to GUID.
*
* @param src A reference to the source string to be converted to GUID. This string may
* optionally be surrounded with curly braces (ie: "{}").
* @param guid A pointer to the output Guid.
* @returns nothing
*/
inline bool stringToGuid(const std::string& src, Guid* guid)
{
const char* fmtString = "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx";
if (src[0] == '{')
fmtString = "{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}";
return sscanf(src.c_str(), fmtString, &guid->data1, &guid->data2, &guid->data3, &guid->data4[0], &guid->data4[1],
&guid->data4[2], &guid->data4[3], &guid->data4[4], &guid->data4[5], &guid->data4[6],
&guid->data4[7]) == 11;
}
/**
* Converts GUID to string format.
*
* @param guid A pointer to the input GUID to be converted to string.
* @param src A reference to the output string.
* @returns nothing
*/
inline void guidToString(const Guid* guid, std::string& strDst)
{
char guidCstr[39]; // 32 chars + 4 dashes + 1 null termination
snprintf(guidCstr, sizeof(guidCstr), "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", guid->data1, guid->data2,
guid->data3, guid->data4[0], guid->data4[1], guid->data4[2], guid->data4[3], guid->data4[4],
guid->data4[5], guid->data4[6], guid->data4[7]);
strDst = guidCstr;
}
constexpr bool operator==(const Guid& lhs, const Guid& rhs)
{
return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4[0] == rhs.data4[0] &&
lhs.data4[1] == rhs.data4[1] && lhs.data4[2] == rhs.data4[2] && lhs.data4[3] == rhs.data4[3] &&
lhs.data4[4] == rhs.data4[4] && lhs.data4[5] == rhs.data4[5] && lhs.data4[6] == rhs.data4[6] &&
lhs.data4[7] == rhs.data4[7];
}
} // namespace extras
} // namespace carb
namespace std
{
template <>
struct hash<carb::extras::Guid>
{
using argument_type = carb::extras::Guid;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const noexcept
{
// split into two 64 bit words
uint64_t a = s.data1 | (uint64_t(s.data2) << 32) | (uint64_t(s.data3) << 48);
uint64_t b = s.data4[0] | (uint64_t(s.data4[1]) << 8) | (uint64_t(s.data4[2]) << 16) |
(uint64_t(s.data4[3]) << 24) | (uint64_t(s.data4[4]) << 32) | (uint64_t(s.data4[5]) << 40) |
(uint64_t(s.data4[6]) << 48) | (uint64_t(s.data4[6]) << 56);
// xor together
return a ^ b;
}
};
inline std::string to_string(const carb::extras::Guid& s)
{
std::string str;
guidToString(&s, str);
return str;
}
} // namespace std
#define CARB_IS_EQUAL_GUID(rguid1, rguid2) (!memcmp(&(rguid1), &(rguid2), sizeof(carb::extras::Guid)))
CARB_IGNOREWARNING_MSC_POP
|
omniverse-code/kit/include/carb/extras/StringUtils.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "Utf8Parser.h"
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
namespace carb
{
namespace extras
{
/**
* Checks if the string begins with the given prefix.
*
* @param[in] str a non-null pointer to the 0-terminated string.
* @param[in] prefix a non-null pointer to the 0-terminated prefix.
*
* @return true if the string begins with provided prefix, false otherwise.
*/
inline bool startsWith(const char* str, const char* prefix)
{
CARB_ASSERT(str != nullptr);
CARB_ASSERT(prefix != nullptr);
if (0 == *str)
{
// empty string vs empty (or not) prefix
return (0 == *prefix);
}
else if (0 == *prefix)
{
// non empty string with empty prefix
return true;
}
size_t n2 = strlen(prefix);
return (0 == strncmp(str, prefix, n2));
}
/**
* Checks if the string begins with the given prefix.
*
* @param[in] str a non-null pointer to the 0-terminated string.
* @param[in] prefix a const reference the std::string prefix.
*
* @return true if the string begins with provided prefix, false otherwise.
*/
inline bool startsWith(const char* str, const std::string& prefix)
{
CARB_ASSERT(str != nullptr);
if (0 == *str)
{
// empty string vs empty (or not) prefix
return (prefix.empty());
}
else if (prefix.empty())
{
// non empty string with empty prefix
return true;
}
std::string::size_type n2 = prefix.length();
std::string::size_type n1 = strnlen(str, static_cast<size_t>(n2 + 1));
if (n1 < n2)
{
// string is shorter than prefix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == prefix.compare(0, n2, str, n2));
}
/**
* Checks if the string begins with the given prefix.
*
* @param[in] str a const reference to the std::string object.
* @param[in] prefix a non-null pointer to the 0-terminated prefix.
*
* @return true if the string begins with provided prefix, false otherwise.
*/
inline bool startsWith(const std::string& str, const char* prefix)
{
CARB_ASSERT(prefix != nullptr);
if (str.empty())
{
// empty string vs empty (or not) prefix
return (0 == *prefix);
}
else if (0 == *prefix)
{
// non empty string with empty prefix
return true;
}
std::string::size_type n2 = strlen(prefix);
std::string::size_type n1 = str.length();
if (n1 < n2)
{
// string is shorter than prefix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == str.compare(0, n2, prefix));
}
/**
* Checks if the string begins with the given prefix.
*
* @param[in] str a const reference to the std::string object.
* @param[in] prefix a const reference to the std::string prefix.
*
* @return true if the string begins with provided prefix, false otherwise.
*/
inline bool startsWith(const std::string& str, const std::string& prefix)
{
if (str.empty())
{
// empty string vs empty (or not) prefix
return prefix.empty();
}
else if (prefix.empty())
{
// non empty string with empty prefix
return true;
}
std::string::size_type n2 = prefix.length();
std::string::size_type n1 = str.length();
if (n1 < n2)
{
// string is shorter than prefix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == str.compare(0, n2, prefix));
}
/**
* Checks if the string ends with the given suffix.
*
* @param[in] str a non-null pointer to the 0-terminated string.
* @param[in] suffix a non-null pointer to the 0-terminated suffix.
*
* @return true if the string ends with provided suffix, false otherwise.
*/
inline bool endsWith(const char* str, const char* suffix)
{
CARB_ASSERT(str != nullptr);
CARB_ASSERT(suffix != nullptr);
if (0 == *str)
{
// empty string vs empty (or not) suffix
return (0 == *suffix);
}
else if (0 == *suffix)
{
// non empty string with empty suffix
return true;
}
size_t n2 = strlen(suffix);
size_t n1 = strlen(str);
if (n1 < n2)
{
// string is shorter than suffix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == memcmp(str + n1 - n2, suffix, n2));
}
/**
* Checks if the string ends with the given suffix.
*
* @param[in] str a non-null pointer to the 0-terminated string.
* @param[in] suffix a const reference to the std::string suffix.
*
* @return true if the string ends with provided suffix, false otherwise.
*/
inline bool endsWith(const char* str, const std::string& suffix)
{
CARB_ASSERT(str != nullptr);
if (0 == *str)
{
// empty string vs empty (or not) suffix
return (suffix.empty());
}
else if (suffix.empty())
{
// non empty string with empty suffix
return true;
}
std::string::size_type n2 = suffix.length();
std::string::size_type n1 = strlen(str);
if (n1 < n2)
{
// string is shorter than suffix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == suffix.compare(0, n2, str + n1 - n2, n2));
}
/**
* Checks if the string ends with the given suffix.
*
* @param[in] str a const reference to the std::string object.
* @param[in] suffix a non-null pointer to the 0-terminated suffix.
*
* @return true if the string ends with provided suffix, false otherwise.
*/
inline bool endsWith(const std::string& str, const char* suffix)
{
CARB_ASSERT(suffix != nullptr);
if (str.empty())
{
// empty string vs empty (or not) suffix
return (0 == *suffix);
}
else if (0 == *suffix)
{
// non empty string with empty suffix
return true;
}
std::string::size_type n2 = strlen(suffix);
std::string::size_type n1 = str.length();
if (n1 < n2)
{
// string is shorter than suffix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == str.compare(n1 - n2, n2, suffix));
}
/**
* Checks if the string ends with the given suffix.
*
* @param[in] str a const reference to the std::string object.
* @param[in] suffix a const reference to the std::string suffix.
*
* @return true if the string ends with provided suffix, false otherwise.
*/
inline bool endsWith(const std::string& str, const std::string& suffix)
{
if (str.empty())
{
// empty string vs empty (or not) prefix
return suffix.empty();
}
else if (suffix.empty())
{
// non empty string with empty prefix
return true;
}
std::string::size_type n2 = suffix.length();
std::string::size_type n1 = str.length();
if (n1 < n2)
{
// string is shorter than suffix
return false;
}
CARB_ASSERT(n2 > 0 && n1 >= n2);
return (0 == str.compare(n1 - n2, n2, suffix));
}
/**
* Trims start of the provided string from the whitespace characters as classified by the
* currently installed C locale in-place
*
* @param[in,out] str for trimming
*/
inline void trimStringStartInplace(std::string& str)
{
// Note: using cast of val into `unsigned char` as std::isspace expects unsigned char values
// https://en.cppreference.com/w/cpp/string/byte/isspace
str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](std::string::value_type val) {
return !std::isspace(static_cast<unsigned char>(val));
}));
}
/**
* Trims end of the provided string from the whitespace characters as classified by the
* currently installed C locale in-place
*
* @param[in,out] str for trimming
*/
inline void trimStringEndInplace(std::string& str)
{
// Note: using cast of val into `unsigned char` as std::isspace expects unsigned char values
// https://en.cppreference.com/w/cpp/string/byte/isspace
str.erase(std::find_if(str.rbegin(), str.rend(),
[](std::string::value_type val) { return !std::isspace(static_cast<unsigned char>(val)); })
.base(),
str.end());
}
/**
* Trims start and end of the provided string from the whitespace characters as classified by the
* currently installed C locale in-place
*
* @param[in,out] str for trimming
*/
inline void trimStringInplace(std::string& str)
{
trimStringStartInplace(str);
trimStringEndInplace(str);
}
/**
* Creates trimmed (as classified by the currently installed C locale)
* from the start copy of the provided string
*
* @param[in] str string for trimming
*
* @return trimmed from the start copy of the provided string
*/
inline std::string trimStringStart(std::string str)
{
trimStringStartInplace(str);
return str;
}
/**
* Creates trimmed (as classified by the currently installed C locale)
* from the end copy of the provided string
*
* @param[in] str string for trimming
*
* @return trimmed from the end copy of the provided string
*/
inline std::string trimStringEnd(std::string str)
{
trimStringEndInplace(str);
return str;
}
/**
* Creates trimmed (as classified by the currently installed C locale)
* from the start and the end copy of the provided string
*
* @param[in] str string for trimming
*
* @return trimmed from the start and the end copy of the provided string
*/
inline std::string trimString(std::string str)
{
trimStringInplace(str);
return str;
}
/**
* Trims start of the provided valid utf-8 string from the whitespace characters in-place
*
* @param[inout] str The UTF-8 string to be trimmed.
*/
inline void trimStringStartInplaceUtf8(std::string& str)
{
if (str.empty())
{
return;
}
Utf8Parser::CodePoint decodedCodePoint = 0;
const Utf8Parser::CodeByte* nonWhitespacePos = str.data();
while (true)
{
const Utf8Parser::CodeByte* nextPos = Utf8Parser::nextCodePoint(
nonWhitespacePos, Utf8Parser::kNullTerminated, &decodedCodePoint, Utf8Parser::fDecodeUseDefault);
// If walked through the whole string and non-whitespace encountered then the whole string is just whitespace
if (!nextPos)
{
str.clear();
return;
}
if (Utf8Parser::isSpaceCodePoint(decodedCodePoint))
{
// If encountered a whitespace character then proceed to the next code point
nonWhitespacePos = nextPos;
continue;
}
// Not a whitespace, stop checking
break;
}
const size_t removedCharsCount = nonWhitespacePos - str.data();
if (removedCharsCount)
{
str.erase(0, removedCharsCount);
}
}
/**
* Trims end of the provided valid utf-8 string from the whitespace characters in-place
*
* @param[inout] str The string to be trimmed.
*/
inline void trimStringEndInplaceUtf8(std::string& str)
{
if (str.empty())
{
return;
}
const Utf8Parser::CodeByte* dataBufStart = str.data();
const Utf8Parser::CodeByte* dataBufEnd = dataBufStart + str.size();
// Walking the provided string data in codepoints in reverse
// Note: `Utf8Parser::lastCodePoint` checks the provided data from back to front thus the search of whitespace is
// in linear time
Utf8Parser::CodePoint decodedCodePoint{};
const Utf8Parser::CodeByte* curSearchPosAtEnd =
Utf8Parser::lastCodePoint(dataBufStart, str.size(), &decodedCodePoint);
const Utf8Parser::CodeByte* prevSearchPosAtEnd = dataBufEnd;
while (curSearchPosAtEnd != nullptr)
{
if (!Utf8Parser::isSpaceCodePoint(decodedCodePoint))
{
// Non-space code point was found
// Remove all symbols starting with the previous codepoint
if (prevSearchPosAtEnd < dataBufEnd)
{
str.erase(prevSearchPosAtEnd - dataBufStart);
}
return;
}
prevSearchPosAtEnd = curSearchPosAtEnd;
curSearchPosAtEnd = Utf8Parser::lastCodePoint(dataBufStart, curSearchPosAtEnd - dataBufStart, &decodedCodePoint);
}
// Either the whole string consists from space characters or an invalid sequence was encountered
str.clear();
}
/**
* Trims start and end of the provided valid utf-8 string from the whitespace characters in-place
*
* @param[inout] str The UTF-8 string to be trimmed.
*/
inline void trimStringInplaceUtf8(std::string& str)
{
trimStringStartInplaceUtf8(str);
trimStringEndInplaceUtf8(str);
}
/**
* Creates trimmed from the start copy of the provided valid utf-8 string
*
* @param[in] str The UTF-8 string to be trimmed.
*
* @return trimmed from the start copy of the provided string
*/
inline std::string trimStringStartUtf8(std::string str)
{
trimStringStartInplaceUtf8(str);
return str;
}
/**
* Creates trimmed from the end copy of the provided valid utf-8 string
*
* @param[in] str The UTF-8 string to be trimmed.
*
* @return trimmed from the end copy of the provided string
*/
inline std::string trimStringEndUtf8(std::string str)
{
trimStringEndInplaceUtf8(str);
return str;
}
/**
* Creates trimmed from the start and the end copy of the provided valid utf-8 string
*
* @param[in] str The UTF-8 string to be trimmed.
*
* @return trimmed from the start and the end copy of the provided string
*/
inline std::string trimStringUtf8(std::string str)
{
trimStringInplaceUtf8(str);
return str;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/DomainSocket.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#if CARB_PLATFORM_LINUX
# include "../logging/Log.h"
# include <poll.h>
# include <sys/socket.h>
# include <sys/un.h>
# include <sys/wait.h>
# include <string>
# include <unistd.h>
# define CARB_INVALID_SOCKET (-1)
namespace carb
{
namespace extras
{
class DomainSocket
{
public:
DomainSocket()
{
}
~DomainSocket()
{
closeSocket();
}
/**
* Sends a list of FDs (file descriptors) to another process using Unix domain socket.
*
* @param fds A list of file descriptors to send.
* @param fdCount The number of file descriptors to send.
*
* @return true if FD was sent successfully.
*/
bool sendFd(const int* fds, int fdCount)
{
size_t fdSize = fdCount * sizeof(int);
msghdr msg = {};
cmsghdr* cmsg;
size_t bufLen = CMSG_SPACE(fdSize);
char* buf;
char dup[s_iovLen] = "dummy payload";
iovec iov = {};
iov.iov_base = &dup;
iov.iov_len = strlen(dup);
buf = reinterpret_cast<char*>(alloca(bufLen));
memset(buf, 0, bufLen);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = buf;
msg.msg_controllen = bufLen;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(fdSize);
memcpy(CMSG_DATA(cmsg), fds, fdSize);
if (sendmsg(m_socket, &msg, 0) == (-1))
{
CARB_LOG_ERROR("sendmsg failed, errno=%d/%s", errno, strerror(errno));
return false;
}
return true;
}
/**
* Receives a list of FDs (file descriptors) from another process using Unix domain socket.
*
* @param fds A list of file descriptors to be received.
* @param fdCount The number of file descriptors to be received.
*
* @return true if FD was received successfully.
*/
bool receiveFd(int* fds, int fdCount)
{
size_t fdSize = fdCount * sizeof(int);
msghdr msg = {};
cmsghdr* cmsg;
size_t bufLen = CMSG_SPACE(fdSize);
char* buf;
char dup[s_iovLen];
iovec iov = {};
iov.iov_base = &dup;
iov.iov_len = sizeof(dup);
buf = reinterpret_cast<char*>(alloca(bufLen));
memset(buf, 0, bufLen);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = buf;
msg.msg_controllen = bufLen;
int result = recvmsg(m_socket, &msg, 0);
if (result == (-1) || result == 0)
{
CARB_LOG_ERROR("recvmsg failed, errno=%d/%s", errno, strerror(errno));
return false;
}
cmsg = CMSG_FIRSTHDR(&msg);
memcpy(fds, CMSG_DATA(cmsg), fdSize);
return true;
}
/**
* Starts client to connect to a server.
*
* @param socketPath The name or the path of the socket.
* @return true if the client was started successfully, and it is connected to a server connection.
*
* @remark Example of socketPath: "/tmp/fd-pass.socket"
*/
bool startClient(const char* socketPath)
{
m_socket = socket(AF_UNIX, SOCK_STREAM, 0);
if (m_socket == CARB_INVALID_SOCKET)
{
CARB_LOG_ERROR("Failed to create socket, errno=%d/%s", errno, strerror(errno));
return false;
}
sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketPath);
if (connect(m_socket, (const struct sockaddr*)&addr, sizeof(addr)) == -1)
{
CARB_LOG_ERROR("Failed to connect to socket %s, errno=%d/%s", addr.sun_path, errno, strerror(errno));
return false;
}
return true;
}
/**
* Closes the connection and socket.
*
* @return nothing
*/
void closeSocket()
{
if (m_socket != CARB_INVALID_SOCKET)
{
close(m_socket);
}
m_socket = CARB_INVALID_SOCKET;
m_socketPath.clear();
}
/**
* Starts server to listen for a socket.
*
* @param socketPath The name or the path of the socket.
* @param backlog The maximum number of the allowed pending connections.
*
* @return true if the server was started successfully, and the client accepted the connection.
*/
bool startServer(const char* socketPath, int backlog = 10)
{
m_socket = socket(AF_UNIX, SOCK_STREAM, 0);
if (m_socket == CARB_INVALID_SOCKET)
{
CARB_LOG_ERROR("Failed to create server socket, errno=%d/%s", errno, strerror(errno));
return false;
}
// try closing any previous socket
if (unlink(socketPath) == -1 && errno != ENOENT)
{
CARB_LOG_ERROR("unlinking socket failed, errno=%d/%s", errno, strerror(errno));
return false;
}
sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketPath);
if (bind(m_socket, (const struct sockaddr*)&addr, sizeof(addr)) == -1)
{
CARB_LOG_ERROR("Failed to bind the socket, errno=%d/%s", errno, strerror(errno));
return false;
}
if (listen(m_socket, backlog) == -1)
{
CARB_LOG_ERROR("Failed to listen on socket, errno=%d/%s", errno, strerror(errno));
return false;
}
CARB_LOG_INFO("DomainSocket: stream server started at %s", socketPath);
return true;
}
/**
* Check for incoming connection and accept it if any.
*
* @param server The listening DomainSocket.
*
* @return true if connection was accepted.
*/
bool acceptConnection(DomainSocket& server)
{
struct pollfd fds;
int rc;
fds.fd = server.m_socket;
fds.events = POLLIN | POLLPRI;
fds.revents = 0;
rc = poll(&fds, 1, 0);
if (rc == -1)
{
CARB_LOG_ERROR("an error on the server socket, errno=%d/%s", errno, strerror(errno));
return false;
}
else if (rc == 0)
{
// nothing happened
return false;
}
sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
socklen_t addrsize = sizeof(addr);
m_socket = accept(server.m_socket, (struct sockaddr*)&addr, &addrsize);
if (m_socket == CARB_INVALID_SOCKET)
{
CARB_LOG_ERROR("accepting connection failed, errno=%d/%s", errno, strerror(errno));
return false;
}
// Copy the socket path
m_socketPath = addr.sun_path;
CARB_LOG_INFO("DomainSocket: accepted connection on %s", addr.sun_path);
return true;
}
private:
int m_socket = CARB_INVALID_SOCKET; ///< socket descriptor
std::string m_socketPath; ///< socket path or name
static const size_t s_iovLen = 256; ///< The length of I/O data in bytes (dummy)
};
} // namespace extras
} // namespace carb
#endif
|
omniverse-code/kit/include/carb/extras/TestEnvironment.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides helper functions to check the platform a process is running on.
*/
#pragma once
#include "Library.h"
#if CARB_PLATFORM_LINUX
# include "StringSafe.h"
#endif
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
/**
* Queries whether the calling process is the Carbonite unit tests.
*
* @note This requires the symbol "g_carbUnitTests" defined
* in the unittest module. on linux, if the symbol is declared in
* the executable and not in a shared library, the executable must
* be linked with -rdynamic or -Wl,--export-dynamic, otherwise
* getLibrarySymbol() will fail. typical usage would be to define
* g_carbUnitTests near the unittest module's main(), for example:
*
* \code{.cpp}
* #include <carb/Defines.h>
*
* CARB_EXPORT int32_t g_carbUnitTests;
* int32_t g_carbUnitTests = 1;
*
* int main(int, char**) {
* // unittest driver
* return 0;
* }
* \endcode
*
* @returns `true` if the calling process is the Carbonite unit tests.
* @returns `false` otherwise.
*/
inline bool isTestEnvironment()
{
LibraryHandle module;
void* symbol;
module = loadLibrary(nullptr);
if (module == nullptr)
return false;
symbol = getLibrarySymbol<void*>(module, "g_carbUnitTests");
unloadLibrary(module);
return symbol != nullptr;
}
/** Retrieves the platform distro name.
*
* @returns On Linux, the name of the distro the process is running under as seen in the "ID"
* tag in the '/etc/os-release' file if it can be found. On MacOS, the name of the
* OS code name that the process is running on is returned if it can be found. On
* Windows, this returns the name "Windows".
* @returns On Linux, the name "Linux" if the '/etc/os-release' file cannot be accessed or the
* "ID" tag cannot be found in it. On Windows, there is no failure path.
* @returns On MacOS, the name "MacOS" if the distro name cannot be found or the appropriate
* tag in it cannot be found.
*/
inline const char* getDistroName()
{
#if CARB_POSIX
static char distroName[64] = { 0 };
auto searchFileForTag = [](const char* filename, const char* tag, char* out, size_t length, bool atStart) -> bool {
FILE* fp = fopen(filename, "r");
char buffer[1024];
if (fp == nullptr)
return false;
out[0] = 0;
while (!feof(fp) && !ferror(fp))
{
char* ptr;
size_t len;
ptr = fgets(buffer, CARB_COUNTOF32(buffer), fp);
if (ptr == nullptr)
break;
// clear whitespace from the end of the line.
len = strlen(buffer);
while (len > 0 && (buffer[len - 1] == '\r' || buffer[len - 1] == '\n' || buffer[len - 1] == ' ' ||
buffer[len - 1] == '\t' || buffer[len - 1] == '\"'))
{
len--;
}
buffer[len] = 0;
ptr = strstr(buffer, tag);
if (ptr == nullptr || (atStart && ptr != buffer))
continue;
ptr += strlen(tag);
if (ptr[0] == '\"')
ptr++;
copyStringSafe(out, length, ptr);
break;
}
fclose(fp);
return out[0] != 0;
};
if (distroName[0] == 0)
{
# if CARB_PLATFORM_LINUX
// try to retrieve the distro name from the official OS info file.
if (!searchFileForTag("/etc/os-release", "ID=", distroName, CARB_COUNTOF(distroName), true))
{
copyStringSafe(distroName, CARB_COUNTOF(distroName), "Linux");
}
# elif CARB_PLATFORM_MACOS
// MacOS doesn't have an official way to retrieve this information either on command line
// or in C/C++/ObjC. There are two common suggestions for how to get this from research:
// * use a hard coded map from version numbers to OS code names.
// * scrape the OS code name from the OS software license agreement HTML file.
//
// Both seem like terrible ideas and are highly subject to change at Apple's Whim. For
// now though, scraping the license agreement text seems to be the most reliable.
constexpr const char* filename =
"/System/Library/CoreServices/Setup Assistant.app/Contents/"
"Resources/en.lproj/OSXSoftwareLicense.html";
if (!searchFileForTag(filename, "SOFTWARE LICENSE AGREEMENT FOR ", distroName, CARB_COUNTOF(distroName), false))
{
copyStringSafe(distroName, CARB_COUNTOF(distroName), "MacOS");
}
else
{
char* ptr = strchr(distroName, '<');
if (ptr != nullptr)
ptr[0] = 0;
}
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
}
return distroName;
#elif CARB_PLATFORM_WINDOWS
return "Windows";
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/** Checks whether the calling process is running on CentOS.
*
* @returns `true` if the current platform is CentOS.
* @returns `false` if the current platform is not running CentOS.
*/
inline bool isRunningOnCentos()
{
return strcmp(getDistroName(), "centos") == 0;
}
/** Checks whether the calling process is running on Ubuntu.
*
* @returns `true` if the current platform is Ubuntu.
* @returns `false` if the current platform is not running Ubuntu.
*/
inline bool isRunningOnUbuntu()
{
return strcmp(getDistroName(), "ubuntu") == 0;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Errors.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Carbonite error handling utilities
#pragma once
#include "../Defines.h"
#include "../logging/Log.h"
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
# include "Unicode.h"
# include <memory>
#elif CARB_POSIX
// Nothing needed for now
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
#include <cerrno>
#include <string.h>
#include <string>
namespace carb
{
namespace extras
{
//! The decayed type of `errno`
//!
//! Defined as `std::decay_t<decltype(errno)>`
using ErrnoType = std::decay_t<decltype(errno)>;
#if defined(DOXYGEN_BUILD) || CARB_PLATFORM_WINDOWS
//! (Windows only) The type of value returned from `GetLastError()`
using WinApiErrorType = unsigned long;
#endif
/**
* Returns the last value of errno.
*
* @return the last value of errno.
*/
inline ErrnoType getLastErrno() noexcept
{
return errno;
}
/**
* Returns a human-readable string for a given errno value
*
* On Windows, this value is created from <a
* href="https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strerror-s-strerror-s-wcserror-s-wcserror-s?view=msvc-170">strerror_s()</a>.
* On other platforms, <a href="https://linux.die.net/man/3/strerror_r">strerror_r()</a> is used instead. If the GNU
* version is available it is used, otherwise the XSI-compliant version is used.
*
* @warning This function does not make any guarantees about the current value of `errno` or attempts to keep `errno`
* set at the same value; `errno` may be modified by this function.
*
* @param errorCode the error code read from `errno`
* @return text message corresponding to the error code; an \p errorCode of 0 returns an empty string
*/
inline std::string convertErrnoToMessage(ErrnoType errorCode)
{
if (errorCode == 0)
return {};
char buffer[1024];
constexpr size_t bufferSize = carb::countOf(buffer);
#if CARB_PLATFORM_WINDOWS
if (CARB_LIKELY(strerror_s(buffer, bufferSize, errorCode) == 0))
return buffer;
return ("Error code " + std::to_string(errorCode)) + " failed to format";
#elif CARB_PLATFORM_MACOS || CARB_PLATFORM_LINUX
// strerror_r implementation switch
# if CARB_PLATFORM_MACOS || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE)
// XSI-compliant strerror_r
if (CARB_LIKELY(strerror_r(errorCode, buffer, bufferSize) == 0))
return buffer;
return ("Error code " + std::to_string(errorCode)) + " failed to format";
# else
// GNU-specific strerror_r
// We always get some result in this implementation for a valid buffer
return strerror_r(errorCode, buffer, bufferSize);
# endif // end of strerror_r implementation switch
#else
CARB_UNSUPPORTED_PLATFORM();
#endif // end of platform switch
}
/**
* Reads the current value of `errno` and returns a human-readable string for the errno value.
*
* @note Unlike \ref convertErrnoToMessage(), this function ensures that `errno` remains consistent by setting `errno`
* to the same value after creating the string.
* @see getLastErrno() convertErrnoToMessage()
* @param[out] out If not `nullptr`, receives the value of `errno`.
* @return string value from \ref convertErrnoToMessage()
*/
inline std::string getLastErrnoMessage(ErrnoType* out = nullptr)
{
const ErrnoType errorCode = getLastErrno();
if (out)
*out = errorCode;
auto str = convertErrnoToMessage(errorCode);
errno = errorCode;
return str;
}
///////////////////////////////////
/// Platform specific functions ///
///////////////////////////////////
#if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD)
/**
* (Windows only) Returns the value of the GetLastError() Win32 API function
*
* @return the value of the GetLastError Win API function.
*/
inline WinApiErrorType getLastWinApiErrorCode() noexcept
{
return ::GetLastError();
}
/**
* (Windows only) Converts a Win32 API error code into a human-readable string.
*
* This function translates a Win32 API error code into a human-readable string using the `FormatMessageA` function.
*
* @note In some cases, the returned string may have UTF-8 encoding or format specifiers. Use caution when printing
* this string. For instance, `ERROR_BAD_EXE_FORMAT` contains `"%1"`.
*
* @warning This function does not make any guarantees about the current value of `GetLastError()` or attempts to keep
* `GetLastError()` set at the same value; `GetLastError()` may be modified by this function.
*
* @param errorCode the code of the Win API error
* @return a human-readable message based on the error code; an \p errorCode of 0 produces an empty string
*/
inline std::string convertWinApiErrorCodeToMessage(WinApiErrorType errorCode)
{
if (errorCode == CARBWIN_ERROR_SUCCESS)
{
return {};
}
LPWSTR resultMessageBuffer = nullptr;
const DWORD kFormatFlags = CARBWIN_FORMAT_MESSAGE_ALLOCATE_BUFFER | CARBWIN_FORMAT_MESSAGE_FROM_SYSTEM |
CARBWIN_FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD dwFormatResultCode = FormatMessageW(kFormatFlags, nullptr, errorCode,
CARBWIN_MAKELANGID(CARBWIN_LANG_NEUTRAL, CARBWIN_SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&resultMessageBuffer), 0, nullptr);
if (dwFormatResultCode == 0 || !resultMessageBuffer)
{
return ("Error code " + std::to_string(errorCode)) + " failed to format";
}
struct Deleter
{
void operator()(LPWSTR str)
{
::LocalFree(str);
}
};
std::unique_ptr<WCHAR, Deleter> systemBuffKeeper(resultMessageBuffer);
return carb::extras::convertWideToUtf8(resultMessageBuffer);
}
/**
* (Windows only) Reads the value of `GetLastError()` and converts it to a human-readable string.
*
* @note Unlike \ref convertWinApiErrorCodeToMessage(), this function will keep the same error code consistent. A call
* to `GetLastError()` after calling this function will return the same value as prior to calling this function.
*
* @return the string from \ref convertWinApiErrorCodeToMessage()
*/
inline std::string getLastWinApiErrorMessage()
{
const WinApiErrorType errorCode = getLastWinApiErrorCode();
auto str = convertWinApiErrorCodeToMessage(errorCode);
SetLastError(errorCode);
return str;
}
#endif // #if CARB_PLATFORM_WINDOWS
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/VariableSetup.h | // Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides helper functions to retrieve setup variable values.
*/
#pragma once
#include "../Framework.h"
#include "../filesystem/IFileSystem.h"
#include "EnvironmentVariable.h"
#include "Path.h"
#include <map>
#include <string>
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
/**
* Helper function that reads string value form the string map or the environment variable, if map doesn't hold such
* key.
*
* @param stringMapKey Key that should be present in the map.
* @param stringMap String map containing values indexed by string key.
* @param envVarName Environment variable name.
* @return String value. Can be empty if neither string map value nor env contain the value.
*/
inline std::string getStringFromMapOrEnvVar(const char* stringMapKey,
const std::map<std::string, std::string>& stringMap,
const char* envVarName)
{
std::string value;
// Check if variable is specified in the command line arguments first, and otherwise -
// try to read the environment variable.
const auto stringMapIt = stringMap.find(stringMapKey);
if (stringMapIt != stringMap.cend())
{
value = stringMapIt->second;
}
else
{
extras::EnvironmentVariable::getValue(envVarName, value);
}
return value;
}
/**
* Determines application path and name. Priority (for path and name separately):
* 1. String map (cmd arg)
* 2. Env var
* 3. Executable path/name (filesystem)
*
* @param stringMap String map - e.g. parsed args as output from the CmdLineParser.
* @param appPath Resulting application path.
* @param appName Resulting application name.
*/
inline void getAppPathAndName(const std::map<std::string, std::string>& stringMap,
std::string& appPath,
std::string& appName)
{
Framework* f = getFramework();
filesystem::IFileSystem* fs = f->acquireInterface<filesystem::IFileSystem>();
// Initialize application path and name to the executable path and name,
extras::Path execPathModified(fs->getExecutablePath());
#if CARB_PLATFORM_WINDOWS
// Remove .exe extension on Windows
execPathModified.replaceExtension("");
#endif
appPath = execPathModified.getParent();
appName = execPathModified.getFilename();
// Override application name and path if command line argument or environment variables
// are present.
std::string appPathOverride = getStringFromMapOrEnvVar("app/path", stringMap, "CARB_APP_PATH");
if (!appPathOverride.empty())
{
extras::Path normalizedAppPathOverride(appPathOverride);
appPath = normalizedAppPathOverride.getNormalized();
}
std::string appNameOverride = getStringFromMapOrEnvVar("app/name", stringMap, "CARB_APP_NAME");
if (!appNameOverride.empty())
{
appName = appNameOverride;
}
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Debugging.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides some helper functions that check the state of debuggers for the calling
* process.
*/
#pragma once
#include "../Defines.h"
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
extern "C"
{
// Forge doesn't define these functions, and it can be included before CarbWindows.h in some cases
// So ensure that they're defined here.
__declspec(dllimport) BOOL __stdcall IsDebuggerPresent(void);
__declspec(dllimport) void __stdcall DebugBreak(void);
// Undocumented function from ntdll.dll, only present in ntifs.h from the Driver Development Kit
__declspec(dllimport) unsigned short __stdcall RtlCaptureStackBackTrace(unsigned long,
unsigned long,
void**,
unsigned long*);
}
// Some things define vsnprintf (pyerrors.h, for example)
# ifdef vsnprintf
# undef vsnprintf
# endif
#elif CARB_POSIX
# include <chrono>
# include <execinfo.h>
# include <signal.h>
# include <stdint.h>
# include <string.h>
# include <fcntl.h>
# include <sys/types.h>
# include <unistd.h>
# if CARB_PLATFORM_MACOS
# include <sys/sysctl.h>
# include <mach/mach.h>
# include <mach/vm_map.h>
# include <pthread/stack_np.h>
# endif
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
#include <cstdio>
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
# if CARB_PLATFORM_MACOS
namespace detail
{
inline bool getVMInfo(uint8_t const* const addr, uint8_t** top, uint8_t** bot) noexcept
{
vm_address_t address = (vm_address_t)addr;
vm_size_t size = 0;
vm_region_basic_info_data_64_t region{};
mach_msg_type_number_t regionSize = VM_REGION_BASIC_INFO_COUNT_64;
mach_port_t obj{};
kern_return_t ret = vm_region_64(
mach_task_self(), &address, &size, VM_REGION_BASIC_INFO_64, (vm_region_info_t)®ion, ®ionSize, &obj);
if (ret != KERN_SUCCESS)
return false;
*bot = (uint8_t*)address;
*top = *bot + size;
return true;
}
# define INSTACK(a) ((a) >= stackbot && (a) <= stacktop)
# if defined(__x86_64__)
# define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 0)
# elif defined(__i386__)
# define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 8)
# elif defined(__arm__) || defined(__arm64__)
# define ISALIGNED(a) ((((uintptr_t)(a)) & 0x1) == 0)
# endif
// Use the ol' static-functions-in-a-template-class to prevent the linker complaining about duplicated symbols.
template <class T = void>
struct Utils
{
__attribute__((noinline)) static void internalBacktrace(
vm_address_t* buffer, size_t maxCount, size_t* nb, size_t skip, void* startfp) noexcept
{
uint8_t *frame, *next;
pthread_t self = pthread_self();
uint8_t* stacktop = static_cast<uint8_t*>(pthread_get_stackaddr_np(self));
uint8_t* stackbot = stacktop - pthread_get_stacksize_np(self);
*nb = 0;
// Rely on the fact that our caller has an empty stackframe (no local vars)
// to determine the minimum size of a stackframe (frame ptr & return addr)
frame = static_cast<uint8_t*>(__builtin_frame_address(0));
next = reinterpret_cast<uint8_t*>(pthread_stack_frame_decode_np((uintptr_t)frame, nullptr));
/* make sure return address is never out of bounds */
stacktop -= ((uintptr_t)next - (uintptr_t)frame);
if (!INSTACK(frame) || !ISALIGNED(frame))
{
// Possibly running as a fiber, get the region info for the memory in question
if (!getVMInfo(frame, &stacktop, &stackbot))
return;
if (!INSTACK(frame) || !ISALIGNED(frame))
return;
}
while (startfp || skip--)
{
if (startfp && startfp < next)
break;
if (!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
next = reinterpret_cast<uint8_t*>(pthread_stack_frame_decode_np((uintptr_t)frame, nullptr));
}
while (maxCount--)
{
uintptr_t retaddr;
next = reinterpret_cast<uint8_t*>(pthread_stack_frame_decode_np((uintptr_t)frame, &retaddr));
buffer[*nb] = retaddr;
(*nb)++;
if (!INSTACK(next) || !ISALIGNED(next) || next <= frame)
return;
frame = next;
}
}
__attribute__((disable_tail_calls)) static void backtrace(
vm_address_t* buffer, size_t maxCount, size_t* nb, size_t skip, void* startfp) noexcept
{
// callee relies upon no tailcall and no local variables
internalBacktrace(buffer, maxCount, nb, skip + 1, startfp);
}
};
# undef INSTACK
# undef ISALIGNED
} // namespace detail
# endif
#endif
/**
* Checks if a debugger is attached to the calling process.
*
* @returns `true` if a user-mode debugger is currently attached to the calling process.
* @returns `false` if the calling process does not have a debugger attached.
*
* @remarks This checks if a debugger is currently attached to the calling process. This will
* query the current state of the debugger so that a process can disable some debug-
* only checks at runtime if the debugger is ever detached. If a debugger is attached
* to a running process, this will start returning `true` again.
*
* @note On Linux and related platforms, the debugger check is a relatively expensive
* operation. To avoid unnecessary overhead explicitly checking this state each time,
* the last successfully queried state will be cached for a short period. Future calls
* within this period will simply return the cached state instead of querying again.
*/
inline bool isDebuggerAttached(void)
{
#if CARB_PLATFORM_WINDOWS
return IsDebuggerPresent();
#elif CARB_PLATFORM_LINUX
// the maximum amount of time in milliseconds that the cached debugger state is valid for.
// If multiple calls to isDebuggerAttached() are made within this period, a cached state
// will be returned instead of re-querying. Outside of this period however, a new call
// to check the debugger state with isDebuggerAttached() will cause the state to be
// refreshed.
static constexpr uint64_t kDebugUtilsDebuggerCheckPeriod = 500;
static bool queried = false;
static bool state = false;
static std::chrono::high_resolution_clock::time_point lastCheckTime = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::time_point t = std::chrono::high_resolution_clock::now();
uint64_t millisecondsElapsed =
std::chrono::duration_cast<std::chrono::duration<uint64_t, std::milli>>(t - lastCheckTime).count();
if (!queried || millisecondsElapsed > kDebugUtilsDebuggerCheckPeriod)
{
// on Android and Linux we can check the '/proc/self/status' file for the line
// "TracerPid:" to check if the associated value is *not* 0. Note that this is
// not a cheap check so we'll cache its result and only re-query once every few
// seconds.
// fopen() and fgets() can use the heap, and we may be called from the crashreporter, so avoid using those
// functions to avoid heap usage.
int fd = open("/proc/self/status", 0, O_RDONLY);
if (fd < 0)
return false;
lastCheckTime = t;
queried = true;
char data[256];
constexpr static char TracerPid[] = "TracerPid:";
for (;;)
{
// Read some bytes from the file
ssize_t bytes = CARB_RETRY_EINTR(read(fd, data, CARB_COUNTOF(data) - 1));
if (bytes <= 0)
{
// Reached the end without finding the line, shouldn't happen
CARB_ASSERT(0);
close(fd);
state = false;
break;
}
data[bytes] = '\0';
// Look for the 'T' in "TracerPid"
auto p = strchr(data, 'T');
if (!p)
continue;
// Can we see the whole line?
auto cr = strchr(p, '\n');
if (!cr)
{
if (p == data)
// This line is too long; skip the 'T' and try again
lseek(fd, -off_t(bytes - 1), SEEK_CUR);
else
// Cannot see the whole line. Back up to where we found the 'T'
lseek(fd, -off_t(data + bytes - p), SEEK_CUR);
continue;
}
// Back up to the next line for the next read
lseek(fd, -off_t(data + bytes - (cr + 1)), SEEK_CUR);
// TracerPid line?
if (strncmp(p, TracerPid, CARB_COUNTOF(TracerPid) - 1) != 0)
// Nope, on to the next line
continue;
// Yep, get the result.
p += (CARB_COUNTOF(TracerPid) - 1);
while (p != cr && (*p == '0' || isspace(*p)))
++p;
// If we find any characters other than space or zero, we have a tracer
state = p != cr;
close(fd);
break;
}
}
return state;
#elif CARB_PLATFORM_MACOS
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid(),
};
struct kinfo_proc info = {};
size_t size = sizeof(info);
// Ignore the return value. It'll return false if this fails.
sysctl(mib, CARB_COUNTOF(mib), &info, &size, nullptr, 0);
return (info.kp_proc.p_flag & P_TRACED) != 0;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Performs a software breakpoint if a debugger is currently attached to this process.
*
* @returns No return value.
*
* @remarks This performs a software breakpoint. If a debugger is attached, this will cause the
* breakpoint to be caught and the debugger will take over the process' state. If no
* debugger is attached, this will be ignored. This can be thought of as a more dynamic
* version of CARB_ASSERT(0) where the existence of a debugger is explicitly checked
* at runtime instead of at compile time.
*
* @note This should really only be used for local debugging purposes. The debugger check
* that is used in here (isDebuggerAttached()) could potentially be expensive on some
* platforms, so this should only be called when it is well known that a problem that
* needs immediate debugging attention has already occurred.
*/
inline void debuggerBreak(void)
{
if (!isDebuggerAttached())
return;
#if CARB_PLATFORM_WINDOWS
DebugBreak();
#elif CARB_POSIX
// NOTE: the __builtin_trap() call is the more 'correct and portable' way to do this. However
// that unfortunately raises a SIGILL signal which is not continuable (at least not in
// MSVC Android or GDB) so its usefulness in a debugger is limited. Directly raising a
// SIGTRAP signal instead still gives the desired behavior and is also continuable.
raise(SIGTRAP);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Attempts to capture the callstack for the current thread.
*
* @note Non-debug code and lack of symbols can cause this function to be unable to capture stack frames. Function
* inlining and tail-calls may result in functions being absent from the backtrace.
*
* @param skipFrames The number of callstack frames to skip from the start (current call point) of the backtrace.
* @param array The array of pointers that is populated with the backtrace. The caller allocates this array.
* @param count The number of pointers that @p array can hold; the maximum size of the captured backtrace.
*
* @return The number of backtrace frames captured in @p array
*/
inline size_t debugBacktrace(size_t skipFrames, void** array, size_t count) noexcept
{
#if CARB_PLATFORM_WINDOWS
// Apparently RtlCaptureStackBackTrace() can "fail" (i.e. not write anything and return 0) without setting any
// error for GetLastError(). Try a few times in a loop.
constexpr static int kRetries = 3;
for (int i = 0; i != kRetries; ++i)
{
unsigned short frames =
::RtlCaptureStackBackTrace((unsigned long)skipFrames, (unsigned long)count, array, nullptr);
if (frames)
return frames;
}
// Failed
return 0;
#elif CARB_PLATFORM_LINUX
void** target = array;
if (skipFrames)
{
target = CARB_STACK_ALLOC(void*, count + skipFrames);
}
size_t captured = (size_t)::backtrace(target, int(count + skipFrames));
if (captured <= skipFrames)
return 0;
if (skipFrames)
{
captured -= skipFrames;
memcpy(array, target + skipFrames, sizeof(void*) * captured);
}
return captured;
#elif CARB_PLATFORM_MACOS
size_t num_frames;
detail::Utils<>::backtrace(reinterpret_cast<vm_address_t*>(array), count, &num_frames, skipFrames, nullptr);
while (num_frames >= 1 && array[num_frames - 1] == nullptr)
num_frames -= 1;
return num_frames;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Prints a formatted string to debug output. On Windows this means, OutputDebugString; on Linux, this just prints to
* the console.
*
* @note This should never be used in production code!
*
* On Windows, the Sysinternals DebugView utility can be used to view the debug strings outside of a debugger.
* @param fmt The printf-style format string
*/
void debugPrint(const char* fmt, ...) CARB_PRINTF_FUNCTION(1, 2);
inline void debugPrint(const char* fmt, ...)
{
#if CARB_PLATFORM_WINDOWS
va_list va, va2;
va_start(va, fmt);
va_copy(va2, va);
int count = vsnprintf(nullptr, 0, fmt, va2);
va_end(va2);
if (count > 0)
{
char* buffer = CARB_STACK_ALLOC(char, size_t(count) + 1);
vsnprintf(buffer, size_t(count + 1), fmt, va);
::OutputDebugStringA(buffer);
}
va_end(va);
#else
va_list va;
va_start(va, fmt);
vfprintf(stdout, fmt, va);
va_end(va);
#endif
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Uuid.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief UUIDv4 utilities
#pragma once
#include "../Defines.h"
#include "../cpp/StringView.h"
#include "../cpp/Bit.h"
#include "StringSafe.h"
#include "StringUtils.h"
#include <array>
#include <cctype>
#include <cinttypes>
#include <cstring>
#include <functional>
#include <iostream>
#include <random>
#include <string>
#include <type_traits>
namespace carb
{
namespace extras
{
/**
* UUIDv4 Unique Identifier (RFC 4122)
*/
class Uuid final
{
public:
using value_type = std::array<uint8_t, 16>; ///< UUID raw bytes
/**
* Initialize empty UUID, 00000000-0000-0000-0000-000000000000
*/
Uuid() noexcept : m_data{ 0U }
{
}
/**
* Convert a string to a Uuid using UUID format.
*
* Accepts the following formats:
* 00000000-0000-0000-0000-000000000000
* {00000000-0000-0000-0000-000000000000}
* urn:uuid:00000000-0000-0000-0000-000000000000
*
* @param uuidStr string to try and convert to Uuid from
*/
Uuid(const std::string& uuidStr) noexcept : m_data{ 0U }
{
std::array<uint8_t, 16> data{ 0U };
carb::cpp::string_view uuidView;
if (uuidStr[0] == '{' && uuidStr.size() == 38)
{
uuidView = carb::cpp::string_view(uuidStr.c_str(), uuidStr.size()).substr(1, uuidStr.size() - 2);
}
else if (startsWith(uuidStr.c_str(), "urn:uuid:") && uuidStr.size() == 45) // RFC 4122
{
uuidView = carb::cpp::string_view(uuidStr.c_str(), uuidStr.size()).substr(9, uuidStr.size());
}
else if (uuidStr.size() == 36)
{
uuidView = carb::cpp::string_view(uuidStr.c_str(), uuidStr.size());
}
if (!uuidView.empty())
{
CARB_ASSERT(uuidView.size() == 36);
size_t i = 0;
size_t j = 0;
while (i < uuidView.size() - 1 && j < data.size())
{
if ((i == 8) || (i == 13) || (i == 18) || (i == 23))
{
if (uuidView[i] == '-')
{
++i;
continue;
}
}
if (std::isxdigit(uuidView[i]) && std::isxdigit(uuidView[i + 1]))
{
char buf[3] = { uuidView[i], uuidView[i + 1], '\0' };
data[j++] = static_cast<uint8_t>(std::strtoul(buf, nullptr, 16));
i += 2;
}
else
{
// error parsing, unknown character
break;
}
}
// if we parsed the entire view and filled the entire array, copy it
if (i == uuidView.size() && j == data.size())
{
m_data = data;
}
}
}
/**
* Create UUIDv4 DCE compatible universally unique identifier.
*/
static Uuid createV4() noexcept
{
Uuid uuidv4;
std::random_device rd;
for (size_t i = 0; i < uuidv4.m_data.size(); i += 4)
{
// use the entire 32-bits returned by random device
uint32_t rdata = rd();
uuidv4.m_data[i + 0] = (rdata >> 0) & 0xff;
uuidv4.m_data[i + 1] = (rdata >> 8) & 0xff;
uuidv4.m_data[i + 2] = (rdata >> 16) & 0xff;
uuidv4.m_data[i + 3] = (rdata >> 24) & 0xff;
}
uuidv4.m_data[6] = (uuidv4.m_data[6] & 0x0f) | 0x40; // RFC 4122 for UUIDv4
uuidv4.m_data[8] = (uuidv4.m_data[8] & 0x3f) | 0x80; // RFC 4122 for UUIDv4
return uuidv4;
}
/**
* Check if Uuid is empty
*
* @return true if Uuid is empty; otherwise, false
*/
bool isEmpty() const noexcept
{
auto data = m_data.data();
return *data == 0 && memcmp(data, data + 1, m_data.size() - 1) == 0;
}
/**
* Access the binary data of the UUID
*
* @return array of UUID data
*/
const value_type& data() const noexcept
{
return m_data;
}
/**
* Compare two UUIDs for equality
*
* @param rhs right hand side of ==
* @return true if uuids are equal; otherwise false
*/
bool operator==(const Uuid& rhs) const noexcept
{
return !memcmp(m_data.data(), rhs.m_data.data(), m_data.size());
}
/**
* Compare two UUIDs for inequality
*
* @param rhs right hand side of !=
* @return true if uuids are not equal; otherwise false
*/
bool operator!=(const Uuid& rhs) const noexcept
{
return !(*this == rhs);
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* Convert Uuid to string.
*
* @return string of Uuid, empty string if failed to convert
*/
friend std::string to_string(const Uuid& uuid) noexcept
{
// UUID format 00000000-0000-0000-0000-000000000000
static constexpr char kFmtString[] =
"%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8
"-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8;
// 32 chars + 4 dashes + 1 null termination
char strBuffer[37];
formatString(strBuffer, CARB_COUNTOF(strBuffer), kFmtString, uuid.m_data[0], uuid.m_data[1], uuid.m_data[2],
uuid.m_data[3], uuid.m_data[4], uuid.m_data[5], uuid.m_data[6], uuid.m_data[7], uuid.m_data[8],
uuid.m_data[9], uuid.m_data[10], uuid.m_data[11], uuid.m_data[12], uuid.m_data[13],
uuid.m_data[14], uuid.m_data[15]);
return std::string(strBuffer);
}
/**
* Overload operator<< for easy use with std streams
*
* @param os output stream
* @param uuid uuid to stream
* @return output stream
*/
friend std::ostream& operator<<(std::ostream& os, const Uuid& uuid)
{
return os << to_string(uuid);
}
#endif // DOXYGEN_SHOULD_SKIP_THIS
private:
value_type m_data;
};
CARB_ASSERT_INTEROP_SAFE(Uuid);
static_assert(std::is_trivially_move_assignable<Uuid>::value, "Uuid must be move assignable");
static_assert(sizeof(Uuid) == 16, "Uuid must be exactly 16 bytes");
} // namespace extras
} // namespace carb
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace std
{
template <>
struct hash<carb::extras::Uuid>
{
using argument_type = carb::extras::Uuid;
using result_type = std::size_t;
result_type operator()(argument_type const& uuid) const noexcept
{
// uuid is random bytes, so just XOR
// bit_cast() won't compile unless sizes match
auto parts = carb::cpp::bit_cast<std::array<result_type, 2>>(uuid.data());
return parts[0] ^ parts[1];
}
};
} // namespace std
#endif // DOXYGEN_SHOULD_SKIP_THIS
|
omniverse-code/kit/include/carb/extras/Barrier.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../cpp/Barrier.h"
namespace carb
{
namespace extras
{
template <class CompletionFunction = carb::cpp::detail::NullFunction>
class CARB_DEPRECATED("Deprecated: carb::extras::binary_semaphore has moved to carb::cpp::binary_semaphore") barrier
: public carb::cpp::barrier<CompletionFunction>
{
public:
constexpr explicit barrier(ptrdiff_t desired, CompletionFunction f = CompletionFunction())
: carb::cpp::barrier<CompletionFunction>(desired, std::move(f))
{
}
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Utf8Parser.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides helper classes to parse and convert UTF-8 strings to and from Unicode.
*/
#pragma once
#include "../Defines.h"
#include "../../omni/extras/ScratchBuffer.h"
#include <cstdint>
#include <algorithm>
#include <cmath>
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
/** Static helper class to allow for the processing of UTF-8 strings. This can walk individual
* codepoints in a string, decode and encode codepoints, and count the number of codepoints in
* a UTF-8 string. Minimal error checking is done in general and there is a common assumption
* that the input string is valid. The only failure points that will be checked are ones that
* prevent further decoding (ie: not enough space left in a buffer, unexpected sequences,
* misaligned strings, etc).
*/
class Utf8Parser
{
public:
/** The base type for a single Unicode codepoint value. This represents a decoded UTF-8
* codepoint.
*/
using CodePoint = char32_t;
/** The base type for a single UTF-16 Unicode codepoint value. This represents a decoded
* UTF-8 codepoint that fits in 16 bits, or a single member of a surrogate pair.
*/
using Utf16CodeUnit = char16_t;
/** The base type for a point in a UTF-8 string. Ideally these values should point to the
* start of an encoded codepoint in a string.
*/
using CodeByte = char;
/** Base type for flags to various encoding and decoding functions. */
using Flags = uint32_t;
/** Names to classify a decoded codepoint's membership in a UTF-16 surrogate pair. The
* UTF-16 encoding allows a single Unicode codepoint to be represented using two 16-bit
* codepoints. These two codepoints are referred to as the 'high' and 'low' codepoints.
* The high codepoint always comes first in the pair, and the low codepoint is expected
* to follow immediately after. The high codepoint is always in the range 0xd800-0xdbff.
* The low codepoint is always in the range 0xdc00-0xdfff. These ranges are reserved
* in the Unicode set specifically for the encoding of UTF-16 surrogate pairs and will
* never appear in an encoded UTF-8 string that contains UTF-16 encoded pairs.
*/
enum class SurrogateMember
{
/** The codepoint is not part of a UTF-16 surrogate pair. This codepoint is outside
* the 0xd800-0xdfff range and is either represented directly in UTF-8 or is small
* enough to not require a UTF-16 encoding.
*/
eNone,
/** The codepoint is a high value in the surrogate pair. This must be in the range
* reserved for UTF-16 high surrogate pairs (ie: 0xd800-0xdbff). This codepoint must
* come first in the pair.
*/
eHigh,
/** The codepoint is a low value in the surrogate pair. This must be in the range
* reserved for UTF-16 low surrogate pairs (ie: 0xdc00-0xdfff). This codepoint must
* come second in the pair.
*/
eLow,
};
/** Flag to indicate that the default codepoint should be returned instead of just a
* zero when attempting to decode an invalid UTF-8 sequence.
*/
static constexpr Flags fDecodeUseDefault = 0x00000001;
/** Flag to indicate that invalid code bytes should be skipped over in a string when searching
* for the start of the next codepoint. The default behavior is to fail the operation when
* an invalid sequence is encountered.
*/
static constexpr Flags fDecodeSkipInvalid = 0x00000002;
/** Flag to indicate that UTF-16 surrogate pairs should be used when encoding large codepoints
* instead of directly representing them in UTF-8. Using this flag makes UTF-8 strings more
* friendly to other UTF-8 systems on Windows (though Windows decoding facilities would still
* be able to decode the directly stored codepoints as well).
*/
static constexpr Flags fEncodeUseUtf16 = 0x00000004;
/** Flag for nextCodePoint() which tells the function to ignore surrogate pairs when decoding
* and just return both elements of the pair as code points.
* This exists mainly for internal use.
*/
static constexpr Flags fEncodeIgnoreSurrogatePairs = 0x00000008;
/** The string buffer is effectively null terminated. This allows the various decoding
* functions to bypass some range checking with the assumption that there is a null
* terminating character at some point in the buffer.
*/
static constexpr size_t kNullTerminated = ~0ull;
/** An invalid Unicode codepoint. */
static constexpr CodePoint kInvalidCodePoint = ~0u;
/** The minimum buffer size that is guaranteed to be large enough to hold an encoded UTF-8
* codepoint. This does not include space for a null terminator codepoint.
*/
static constexpr size_t kMaxSequenceLength = 7;
/** The codepoint reserved in the Unicode standard to represent the decoded result of an
* invalid UTF-8 sequence.
*/
static constexpr CodePoint kDefaultCodePoint = 0x0000fffd;
/** Finds the start of the next UTF-8 codepoint in a string.
*
* @param[in] str The UTF-8 string to find the next codepoint in. This may not
* be `nullptr`. This is assumed to be a valid UTF-8 encoded
* string and the passed in address is assumed to be the start
* of another codepoint. If the @ref fDecodeSkipInvalid flag is
* used in @p flags, an attempt will be made to find the start of
* the next valid codepoint in the string before failing. If a
* valid lead byte is found within the bounds of the string, that
* will be returned instead of failing in this case.
* @param[in] lengthInBytes The remaining number of bytes in the string. This may be
* @ref kNullTerminated if the string is well known to be null
* terminated. This operation will not walk the string beyond
* this number of bytes. Note that the operation may still end
* before this many bytes have been scanned if a null terminator
* is encountered.
* @param[out] codepoint Receives the decoded codepoint. This may be `nullptr` if the
* decoded codepoint is not needed. If this is `nullptr`, none of
* the work to decode the codepoint will be done. If the next
* UTF-8 codepoint is part of a UTF-16 surrogate pair, the full
* codepoint will be decoded.
* @param[in] flags Flags to control the behavior of this operation. This may be
* 0 or one or more of the fDecode* flags.
* @returns The address of the start of the next codepoint in the string if one is found.
* @returns `nullptr` if the string is empty, a null terminator is found, or there are no more
* bytes remaining in the string.
*
* @remarks This attempts to walk a UTF-8 encoded string to find the start of the next valid
* codepoint. This can be used to walk from one codepoint to another and modify
* the string as needed, or to just count its length in codepoints.
*/
static const CodeByte* nextCodePoint(const CodeByte* str,
size_t lengthInBytes = kNullTerminated,
CodePoint* codepoint = nullptr,
Flags flags = 0)
{
// retrieve the next code point
CodePoint high = 0;
const CodeByte* next = nullptr;
bool r = parseUtf8(str, &next, &high, lengthInBytes, flags);
if (codepoint != nullptr)
{
*codepoint = high;
}
// parsing failed => just fail out
if (!r)
{
return next;
}
// it's a surrogate pair (and we're allowed to parse those) => parse out the full pair
if ((flags & fEncodeIgnoreSurrogatePairs) == 0 && classifyUtf16SurrogateMember(high) == SurrogateMember::eHigh)
{
// figure out the new length if it's not null terminated
const size_t newLen = (lengthInBytes == kNullTerminated) ? kNullTerminated : (lengthInBytes - (next - str));
// parse out the next code point
CodePoint low = 0;
r = parseUtf8(next, &next, &low, newLen, flags);
// invalid surrogate pair => fail
if (!r || classifyUtf16SurrogateMember(low) != SurrogateMember::eLow)
{
if (codepoint != nullptr)
{
*codepoint = getFailureCodepoint(flags);
}
return next;
}
// valid surrogate pair => calculate the code point
if (codepoint != nullptr)
{
*codepoint = (((high & kSurrogateMask) << kSurrogateBits) | (low & kSurrogateMask)) + kSurrogateBias;
}
return next;
}
return next;
}
/** Finds the start of the last UTF-8 codepoint in a string.
*
* @param[in] str The UTF-8 string to find the last codepoint in.
* This is assumed to be a valid UTF-8 encoded
* string and the passed in address is assumed to be the start
* of another codepoint. If the @ref fDecodeSkipInvalid flag is
* used in @p flags, an attempt will be made to find the start of
* the last valid codepoint in the string before failing. If a
* valid lead byte is found within the bounds of the string, that
* will be returned instead of failing in this case.
* @param[in] lengthInBytes The remaining number of bytes in the string. This may be
* @ref kNullTerminated if the string is well known to be null
* terminated. This operation will not walk the string beyond
* this number of bytes. Note that the operation may still end
* before this many bytes have been scanned if a null terminator
* is encountered.
* @param[out] codepoint Receives the decoded codepoint. This may be `nullptr` if the
* decoded codepoint is not needed. If this is `nullptr`, none of
* the work to decode the codepoint will be done. If the last
* UTF-8 codepoint is part of a UTF-16 surrogate pair, the full
* codepoint will be decoded.
* @param[in] flags Flags to control the behavior of this operation. This may be
* 0 or one or more of the fDecode* flags.
* @returns The address of the start of the last codepoint in the string if one is found.
* @returns `nullptr` if the string is empty, a null terminator is found, or there are no more
* bytes remaining in the string.
*
* @remarks This function attempts to walk a UTF-8 encoded string to find the start of the last
* valid codepoint.
*/
static const CodeByte* lastCodePoint(const CodeByte* str,
size_t lengthInBytes = kNullTerminated,
CodePoint* codepoint = nullptr,
Flags flags = fDecodeUseDefault)
{
// Prepare error value result
if (codepoint != nullptr)
{
*codepoint = getFailureCodepoint(flags);
}
// Check if it's a null or empty string
if (!str || *str == 0)
{
return nullptr;
}
if (lengthInBytes == kNullTerminated)
{
lengthInBytes = std::strlen(str);
}
// Make sure no unexpected flags pass into used `nextCodePoint` function
constexpr Flags kErrorHandlingMask = fDecodeSkipInvalid | fDecodeUseDefault;
const Flags helperParserFlags = (flags & kErrorHandlingMask);
size_t curCodePointSize = 0; // Keeps max number of bytes for a decoding attempt with `nextCodePoint`
const bool skipInvalid = (flags & fDecodeSkipInvalid) != 0;
// Walk the string backwards to find the start of the last CodePoint and decode it
// Note: it can be a single byte or a sequence, also if not searching for the last valid CodePoint
// the maximum number of bytes to check is just last `kMaxSequenceLength` bytes instead of the full string
const CodeByte* const rIterBegin = str - 1 + lengthInBytes;
const CodeByte* const rIterEnd =
(flags & fDecodeSkipInvalid) ? str - 1 : CARB_MAX(str - 1, rIterBegin - kMaxSequenceLength);
for (const CodeByte* rIter = rIterBegin; rIter != rIterEnd; --rIter)
{
const uint8_t curByte = static_cast<uint8_t>(*rIter);
++curCodePointSize;
// Check if the current code byte is a direct ASCII character
if (curByte < k7BitLimit)
{
// If parsed more than one byte then it's an error
if (curCodePointSize > 1 && !skipInvalid)
{
return nullptr;
}
if (codepoint != nullptr)
{
*codepoint = curByte;
}
return rIter;
}
// The current code byte is a continuation byte so step further
if (curByte < kMinLeadByte)
{
continue;
}
// The current code byte is a lead byte, decode the sequence and check that all bytes were used
CodePoint cp{};
const CodeByte* next = nextCodePoint(rIter, curCodePointSize, &cp, helperParserFlags);
if (!next)
{
if (skipInvalid)
{
curCodePointSize = 0;
continue;
}
return nullptr;
}
// Validate that all bytes till the end were used if expecting no invalid bytes
// Ex: "\xce\xa6\xa6" is a 2 byte sequence "\xce\xa6" for a 0x03A6 code point followed by excessive
// follow up byte "\xa6". The first 2 bytes will be decoded by the `nextCodePoint` properly
// and `next` will be pointing at the last "\xa6" byte
if (!skipInvalid && curCodePointSize != static_cast<size_t>(next - rIter))
{
return nullptr;
}
const SurrogateMember surrogateType = classifyUtf16SurrogateMember(cp);
// Encountered the high surrogate part first which is an error
if (CARB_UNLIKELY(surrogateType == SurrogateMember::eHigh))
{
if (skipInvalid)
{
// Just skip it and search further
curCodePointSize = 0;
continue;
}
return nullptr;
}
// Found the low part of a surrogate pair, need to continue parsing to get the high part
else if (CARB_UNLIKELY(surrogateType == SurrogateMember::eLow))
{
constexpr int kSurrogatePartSize = 3;
constexpr int kFullSurrogatePairSize = 2 * kSurrogatePartSize;
// To prepare for possible continuation of parsing if skipping invalid bytes and no high surrogate is
// found reset the possible CodePoint size
curCodePointSize = 0;
// For a valid UTF-8 string there are must be high surrogate (3 bytes) preceding low surrogate (3 bytes)
if (rIter <= rIterEnd + kSurrogatePartSize)
{
if (skipInvalid)
{
// Skip the low surrogate data and continue to check the preceding byte
continue;
}
return nullptr;
}
// Step 3 bytes preceding the low surrogate
const CodeByte* const possibleHighSurStart = rIter - kSurrogatePartSize;
// Check if it starts with a lead byte
if (static_cast<uint8_t>(*possibleHighSurStart) < kMinLeadByte)
{
if (skipInvalid)
{
continue;
}
return nullptr;
}
// Try to parse 6 bytes (full surrogate pair size) to get the whole CodePoint without skipping invalid
// bytes
const CodeByte* const decodedPairEnd =
nextCodePoint(possibleHighSurStart, kFullSurrogatePairSize, &cp, 0);
if (!decodedPairEnd)
{
if (skipInvalid)
{
continue;
}
return nullptr;
}
// Check if used all 6 bytes (as expected from a surrogate pair)
if (decodedPairEnd - possibleHighSurStart != kFullSurrogatePairSize)
{
if (skipInvalid)
{
continue;
}
return nullptr;
}
// A proper surrogate pair was parsed into the `cp`
// and only the `rIter` has invalid value at this point
rIter = possibleHighSurStart;
// Just exit the block so the code below reports the result
}
if (codepoint)
{
*codepoint = cp;
}
// Everything is fine thus return start of the sequence
return rIter;
}
// Didn't find start of a valid CodePoint
return nullptr;
}
/** Calculates the length of a UTF-8 string in codepoints.
*
* @param[in] str The string to count the number of codepoints in. This may not
* be `nullptr`. This is expected to be a valid UTF-8 string.
* @param[in] maxLengthInBytes The maximum number of bytes to parse in the string. This can
* be @ref kNullTerminated if the string is well known to be null
* terminated.
* @param[in] flags Flags to control the behavior of this operation. This may be
* 0 or @ref fDecodeSkipInvalid.
* @returns The number of valid codepoints in the given UTF-8 string.
* @returns `0` if the string is empty or no valid codepoints are found.
*
* @remarks This can be used to count the number of codepoints in a UTF-8 string. The count
* will only include valid codepoints that are found in the string. It will not
* include a count for any invalid code bytes that are skipped over when the
* @ref fDecodeSkipInvalid flag is used. This means that it's not necessarily safe
* to use this result (when the flag is used) to allocate a decode buffer, then
* decode the codepoints in the string with getCodePoint() using the
* @ref fDecodeUseDefault flag.
*/
static size_t getLengthInCodePoints(const CodeByte* str, size_t maxLengthInBytes = kNullTerminated, Flags flags = 0)
{
const CodeByte* current;
const CodeByte* next;
size_t count = 0;
// get the second codepoint in the string.
current = str;
next = nextCodePoint(str, maxLengthInBytes, nullptr, flags);
// empty or invalid string => fail.
if (next == nullptr)
return 0;
if (maxLengthInBytes != kNullTerminated)
{
maxLengthInBytes -= next - current;
}
count++;
do
{
current = next;
next = nextCodePoint(current, maxLengthInBytes, nullptr, flags);
if (next == nullptr)
return count;
if (maxLengthInBytes != kNullTerminated)
{
maxLengthInBytes -= next - current;
}
count++;
} while (maxLengthInBytes > 0);
return count;
}
/** Calculates the length of a Unicode string in UTF-8 code bytes.
*
* @param[in] str The string to count the number of code bytes that will
* be required to store it in UTF-8. This may not be
* `nullptr`. This is expected to be a valid Unicode
* string.
* @param[in] maxLengthInCodePoints The maximum number of codepoints to parse in the
* string. This can be @ref kNullTerminated if the
* string is well known to be null terminated.
* @param[in] flags Flags to control the behavior of this operation.
* This may be 0 or @ref fEncodeUseUtf16.
* @returns The number of UTF-8 code bytes required to encode this Unicode string, not
* including the null terminator.
* @returns `0` if the string is empty or no valid codepoints are found.
*
* @remarks This can be used to count the number of UTF-8 code bytes required to encode
* the given Unicode string. The count will only include valid codepoints that
* are found in the string. Note that if the @ref fEncodeUseUtf16 flag is not
* used here to calculate the size of a buffer, it should also not be used when
* converting codepoints. Otherwise the buffer could overflow.
*
* @note For the 32-bit codepoint variant of this function, it is assumed that UTF-16
* surrogate pairs do not exist in the source string. In the 16-bit codepoint
* variant, surrogate pairs are supported.
*/
static size_t getLengthInCodeBytes(const CodePoint* str,
size_t maxLengthInCodePoints = kNullTerminated,
Flags flags = 0)
{
size_t count = 0;
size_t largeCodePointSize = 4;
if ((flags & fEncodeUseUtf16) != 0)
largeCodePointSize = 6;
for (size_t i = 0; str[i] != 0 && i < maxLengthInCodePoints; i++)
{
if (str[i] < getMaxCodePoint(0))
count++;
else if (str[i] < getMaxCodePoint(1))
count += 2;
else if (str[i] < getMaxCodePoint(2))
count += 3;
else if (str[i] < getMaxCodePoint(3))
count += largeCodePointSize;
else if (str[i] < getMaxCodePoint(4))
count += 5;
else if (str[i] < getMaxCodePoint(5))
count += 6;
else
count += 7;
}
return count;
}
/** @copydoc getLengthInCodeBytes */
static size_t getLengthInCodeBytes(const Utf16CodeUnit* str,
size_t maxLengthInCodePoints = kNullTerminated,
Flags flags = 0)
{
size_t count = 0;
size_t largeCodePointSize = 4;
if ((flags & fEncodeUseUtf16) != 0)
largeCodePointSize = 6;
for (size_t i = 0; str[i] != 0 && i < maxLengthInCodePoints; i++)
{
if (str[i] < getMaxCodePoint(0))
count++;
else if (str[i] < getMaxCodePoint(1))
count += 2;
else
{
// found a surrogate pair in the string -> both of these codepoints will decode to
// a single UTF-32 codepoint => skip the low surrogate and add the size of a
// single encoded codepoint.
if (str[i] >= kSurrogateBaseHigh && str[i] < kSurrogateBaseLow && i + 1 < maxLengthInCodePoints &&
str[i + 1] >= kSurrogateBaseLow && str[i + 1] <= kSurrogateMax)
{
i++;
count += largeCodePointSize;
}
// not part of a UTF-16 surrogate pair => this will encode to 3 bytes in UTF-8.
else
count += 3;
}
}
return count;
}
/** Decodes a single codepoint from a UTF-8 string.
*
* @param[in] str The string to decode the first codepoint from. This may not
* be `nullptr`. The string is expected to be aligned to the start
* of a valid codepoint.
* @param[in] lengthInBytes The number of bytes remaining in the string. This can be set
* to @ref kNullTerminated if the string is well known to be null
* terminated.
* @param[in] flags Flags to control the behavior of this operation. This may be
* `0` or @ref fDecodeUseDefault.
* @returns The decoded codepoint if successful.
* @returns `0` if the end of the string is encountered, the string is empty, or there are not
* enough bytes left in the string to decode a full codepoint, and the @p flags
* parameter is zero.
* @retval kDefaultCodePoint if the end of the string is encountered, the string is
* empty, or there are not enough bytes left in the string to decode a full
* codepoint, and the @ref fDecodeUseDefault flag is used.
*
* @remarks This decodes the next codepoint in a UTF-8 string. The returned codepoint may be
* part of a UTF-16 surrogate pair. The classifyUtf16SurrogateMember() function can
* be used to determine if this is the case. If this is part of a surrogate pair,
* the caller should decode the next codepoint then decode the full pair into a
* single codepoint using decodeUtf16CodePoint().
*/
static CodePoint getCodePoint(const CodeByte* str, size_t lengthInBytes = kNullTerminated, Flags flags = 0)
{
char32_t c = 0;
nextCodePoint(str, lengthInBytes, &c, flags);
return c;
}
/** Encodes a single Unicode codepoint to UTF-8.
*
* @param[in] cp The codepoint to be encoded into UTF-8. This may be any valid
* Unicode codepoint.
* @param[out] str Receives the encoded UTF-8 codepoint. This may not be `nullptr`.
* This could need to be up to seven bytes to encode any possible
* Unicode codepoint.
* @param[in] lengthInBytes The size of the output buffer in bytes. No more than this many
* bytes will be written to the @p str buffer.
* @param[out] bytesWritten Receives the number of bytes that were written to the output
* buffer. This may not be `nullptr`.
* @param[in] flags Flags to control the behavior of this operation. This may be
* `0` or @ref fEncodeUseUtf16.
* @returns The output buffer if the codepoint is successfully encoded.
* @returns `nullptr` if the output buffer was not large enough to hold the encoded codepoint.
*/
static CodeByte* getCodeBytes(CodePoint cp, CodeByte* str, size_t lengthInBytes, size_t* bytesWritten, Flags flags = 0)
{
size_t sequenceLength = 0;
size_t continuationLength = 0;
size_t codePointCount = 1;
CodePoint codePoint[2] = { cp, 0 };
CodeByte* result;
// not enough room in the buffer => fail.
if (lengthInBytes == 0)
{
*bytesWritten = 0;
return nullptr;
}
// a 7-bit ASCII character -> this can be directly stored => store and return.
if (codePoint[0] < k7BitLimit)
{
str[0] = (codePoint[0] & 0xff);
*bytesWritten = 1;
return str;
}
// at this point we know that the encoding for the codepoint is going to require at least
// two bytes. We need to calculate the sequence length and encode the bytes.
// allowing a UTF-16 surrogate pair encoding in the string and the codepoint is above the
// range where a surrogate pair is necessary => calculate the low and high codepoints
// for the pair and set the sequence length.
if ((flags & fEncodeUseUtf16) != 0 && codePoint[0] >= kSurrogateBias)
{
sequenceLength = 3;
continuationLength = 2;
codePointCount = 2;
codePoint[0] -= kSurrogateBias;
codePoint[1] = kSurrogateBaseLow | (codePoint[0] & kSurrogateMask);
codePoint[0] = kSurrogateBaseHigh | ((codePoint[0] >> kSurrogateBits) & kSurrogateMask);
}
// not using a UTF-16 surrogate pair => search for the required length of the sequence.
else
{
// figure out the required sequence length for the given for this codepoint.
for (size_t i = 1; i < kMaxSequenceBytes; i++)
{
if (codePoint[0] < getMaxCodePoint(i))
{
sequenceLength = i + 1;
continuationLength = i;
break;
}
}
// failed to find a sequence length for the given codepoint (?!?) => fail (this should
// never happen).
if (sequenceLength == 0)
{
*bytesWritten = 0;
return nullptr;
}
}
// not enough space in the buffer to store the entire sequence => fail.
if (lengthInBytes < sequenceLength * codePointCount)
{
*bytesWritten = 0;
return nullptr;
}
result = str;
// write out each of the codepoints. If UTF-16 encoding is not being used, there will only
// be one codepoint and this loop will exit after the first iteration.
for (size_t j = 0; j < codePointCount; j++)
{
cp = codePoint[j];
// write out the lead byte.
*str = getLeadByte(continuationLength) |
((cp >> (continuationLength * kContinuationShift)) & getLeadMask(continuationLength));
str++;
// write out the continuation bytes.
for (size_t i = 0; i < continuationLength; i++)
{
*str = kContinuationBits |
((cp >> ((continuationLength - i - 1) * kContinuationShift)) & kContinuationMask);
str++;
}
}
*bytesWritten = sequenceLength * codePointCount;
return result;
}
/** Classifies a codepoint as being part of a UTF-16 surrogate pair or otherwise.
*
* @param[in] cp The codepoint to classify. This may be any valid Unicode codepoint.
* @retval SurrogateMember::eNone if the codepoint is not part of a UTF-16 surrogate
* pair.
* @retval SurrogateMember::eHigh if the codepoint is a 'high' UTF-16 surrogate pair
* codepoint.
* @retval SurrogateMember::eLow if the codepoint is a 'low' UTF-16 surrogate pair
* codepoint.
*/
static SurrogateMember classifyUtf16SurrogateMember(CodePoint cp)
{
if (cp >= kSurrogateBaseHigh && cp < kSurrogateBaseLow)
return SurrogateMember::eHigh;
if (cp >= kSurrogateBaseLow && cp <= kSurrogateMax)
return SurrogateMember::eLow;
return SurrogateMember::eNone;
}
/** Decodes a UTF-16 surrogate pair to a Unicode codepoint.
*
* @param[in] high The codepoint for the 'high' member of the UTF-16 surrogate pair.
* @param[in] low The codepoint for the 'low' member of the UTF-16 surrogate pair.
* @returns The decoded codepoint if the two input codepoints were a UTF-16 surrogate pair.
* @returns `0` if either of the input codepoints were not part of a UTF-16 surrogate pair.
*/
static CodePoint decodeUtf16CodePoint(CodePoint high, CodePoint low)
{
CodePoint cp;
// the high and low codepoints are out of the surrogate pair range -> cannot decode => fail.
if (high < kSurrogateBaseHigh || high >= kSurrogateBaseLow || low < kSurrogateBaseLow || low > kSurrogateMax)
return 0;
// decode the surrogate pair into a single Unicode codepoint.
cp = (((high & kSurrogateMask) << kSurrogateBits) | (low & kSurrogateMask)) + kSurrogateBias;
return cp;
}
/** Encodes a Unicode codepoint into a UTF-16 codepoint.
*
* @param[in] cp The UTF-32 codepoint to encode. This may be any valid codepoint.
* @param[out] out Receives the equivalent codepoint encoded in UTF-16. This will either be
* a single UTF-32 codepoint if its value is less than the UTF-16 encoding
* size of 16 bits, or it will be a UTF-16 surrogate pair for codepoint
* values larger than 16 bits. In the case of a single codepoint being
* written, it will occupy the lower 16 bits of this buffer. If two
* codepoints are written, the 'high' surrogate pair member will be in
* the lower 16 bits, and the 'low' surrogate pair member will be in the
* upper 16 bits. This is suitable for use as a UTF-16 buffer to pass to
* other functions that expect a surrogate pair. The number of codepoints
* written can be differentiated by the return value of this function. This
* may be `nullptr` if the encoded UTF-16 codepoint is not needed but only the
* number of codepoints is of interest. This may safely be the same buffer
* as @p cp.
* @returns `1` if the requested codepoint was small enough for a direct encoding into UTF-16.
* This can be interpreted as a single codepoint being written to the output
* codepoint buffer.
* @returns `2` if the requested codepoint was too big for direct encoding in UTF-16 and had
* to be encoded as a surrogate pair. This can be interpreted as two codepoints
* being written to the output codepoint buffer.
*/
static size_t encodeUtf16CodePoint(CodePoint cp, CodePoint* out)
{
CodePoint high;
CodePoint low;
// small enough for a direct encoding => just store it.
if (cp < kSurrogateBias)
{
if (out != nullptr)
*out = cp;
return 1;
}
// too big for direct encoding => convert it to a surrogate pair and store both in the
// output buffer.
cp -= kSurrogateBias;
low = kSurrogateBaseLow | (cp & kSurrogateMask);
high = kSurrogateBaseHigh | ((cp >> kSurrogateBits) & kSurrogateMask);
if (out != nullptr)
*out = high | (low << 16);
return 2;
}
/** Checks if the provided code point corresponds to a whitespace character
*
* @param[in] cp The UTF-32 codepoint to check
*
* @returns true if the codepoint is a whitespace character, false otherwise
*/
inline static bool isSpaceCodePoint(CodePoint cp)
{
// Taken from https://en.wikipedia.org/wiki/Whitespace_character
// Note: sorted to allow binary search
static constexpr CodePoint kSpaceCodePoints[] = {
0x0009, // character tabulation
0x000A, // line feed
0x000B, // line tabulation
0x000C, // form feed
0x000D, // carriage return
0x0020, // space
0x0085, // next line
0x00A0, // no-break space
0x1680, // ogham space mark
0x180E, // Mongolian vowel separator
0x2000, // en quad
0x2001, // em quad
0x2002, // en space
0x2003, // em space
0x2004, // three-per-em space
0x2005, // four-per-em space
0x2006, // six-per-em space
0x2007, // figure space
0x2008, // punctuation space
0x2009, // thin space
0x200A, // hair space
0x200B, // zero width space
0x200C, // zero width non-joiner
0x200D, // zero width joiner
0x2028, // line separator
0x2029, // paragraph separator
0x202F, // narrow no-break space
0x205F, // medium mathematical space
0x2060, // word joiner
0x3000, // ideograph space
0xFEFF, // zero width non-breaking space
};
constexpr size_t kSpaceCodePointsCount = CARB_COUNTOF(kSpaceCodePoints);
constexpr const CodePoint* const kSpaceCodePointsEnd = kSpaceCodePoints + kSpaceCodePointsCount;
return std::binary_search(kSpaceCodePoints, kSpaceCodePointsEnd, cp);
}
private:
/** The number of valid codepoint bits in the lead byte of a UTF-8 codepoint. This table is
* indexed by the continuation length of the sequence. The first entry represents a sequence
* length of 1 (ie: continuation length of 0). This table supports up to seven byte UTF-8
* sequences. Currently the UTF-8 standard only requires support for four byte sequences
* since that covers the full defined Unicode set. The extra bits allows for future UTF-8
* expansion without needing to change the parser. Note that seven bytes is the theoretical
* limit for a single UTF-8 sequence with the current algorithm. This allows for 36 bits of
* codepoint information (which would already require a new codepoint representation anyway).
* The most feasible decoding limit is a six byte sequence which allows for up to 31 bits of
* codepoint information.
*/
static constexpr uint8_t s_leadBits[] = { 7, 5, 4, 3, 2, 1, 0 };
/** The maximum decoded codepoint currently set for the UTF-8 and Unicode standards. This
* full range is representable with a four byte UTF-8 sequence. When the Unicode standard
* expands beyond this limit, longer UTF-8 sequences will be required to fully encode the
* new range.
*/
static constexpr CodePoint kMaxCodePoint = 0x0010ffff;
/** The number of bits of valid codepoint information in the low bits of each continuation
* byte in a sequence.
*/
static constexpr uint32_t kContinuationShift = 6;
/** The lead bits of a continuation byte. Each continuation byte starts with the high
* bit set followed by a clear bit, then the remaining bits contribute to the codepoint.
*/
static constexpr uint8_t kContinuationBits = 0x80;
/** The mask of bits in each continuation byte that contribute to the codepoint. */
static constexpr uint8_t kContinuationMask = (1u << kContinuationShift) - 1;
/** The base and bias value for a UTF-16 surrogate pair value. When encoding a surrogate
* pair, this is subtracted from the original codepoint so that only 20 bits of relevant
* information remain. These 20 bits are then split across the two surrogate pair values.
* When decoding, this value is added to the decoded 20 bits that are extracted from the
* code surrogate pair to get the final codepoint value.
*/
static constexpr CodePoint kSurrogateBias = 0x00010000;
/** The lowest value that a UTF-16 surrogate pair codepoint can have. This will be the
* low end of the range for the 'high' member of the pair.
*/
static constexpr CodePoint kSurrogateBaseHigh = 0x0000d800;
/** The middle value that a UTF-16 surrogate pair codepoint can have. This will be the
* low end of the range for the 'low' member of the pair, and one larger than the high
* end of the range for the 'high' member of the pair.
*/
static constexpr CodePoint kSurrogateBaseLow = 0x0000dc00;
/** The lowest value that any UTF-16 surrogate pair codepoint can have. */
static constexpr CodePoint kSurrogateMin = 0x0000d800;
/** The highest value that any UTF-16 surrogate pair codepoint can have. This will be the
* high end of the range for the 'low' member of the pair.
*/
static constexpr CodePoint kSurrogateMax = 0x0000dfff;
/** The number of bits of codepoint information that is extracted from each member of the
* UTF-16 surrogate pair. These will be the lowest bits of each of the two codepoints.
*/
static constexpr uint32_t kSurrogateBits = 10;
/** The mask of the bits of codepoint information in each of the UTF-16 surrogate pair
* members.
*/
static constexpr CodePoint kSurrogateMask = ((1 << kSurrogateBits) - 1);
/** The maximum number of bytes that a UTF-8 codepoint sequence can have. This is the
* mathematical limit of the algorithm. The current standard only supports up to four
* byte sequences right now. A four byte sequence covers the full Unicode codepoint
* set up to and including 0x10ffff.
*/
static constexpr size_t kMaxSequenceBytes = 7;
/** The limit of a directly representable ASCII character in a UTF-8 sequence. All values
* below this are simply directly stored in the UTF-8 sequence and can be trivially decoded
* as well.
*/
static constexpr uint8_t k7BitLimit = 0x80;
/** The minimum value that could possibly represent a lead byte in a multi-byte UTF-8
* sequence. All values below this are either directly representable in UTF-8 or indicate
* a continuation byte for the sequence. Note that some byte values above this range
* could still indicate an invalid sequence. See @a getContinuationLength() for more
* information on this.
*/
static constexpr uint8_t kMinLeadByte = 0xc0;
/** Retrieves the continuation length of a UTF-8 sequence for a given lead byte.
*
* @param[in] leadByte The lead byte of a UTF-8 sequence to retrieve the continuation
* length for. This must be greater than or equal to the value of
* @a kMinLeadByte. The results are undefined if the lead byte
* is less than @a kMinLeadByte.
* @returns The number of continuation bytes in the sequence for the given lead byte.
*
* @remarks This provides a lookup helper to retrieve the expected continuation length for
* a given lead byte in a UTF-8 sequence. A return value of 0 indicates an invalid
* sequence (either an overlong sequence or an invalid lead byte). The lead byte
* values 0xc0 and 0xc1 for example represent an overlong sequence (ie: one that
* unnecessarily encodes a single byte codepoint using multiple bytes). The lead
* byte 0xff represents an invalid lead byte since it violates the rules of the
* UTF-8 encoding. Each other value represents the number bytes that follow the
* lead byte (not including the lead byte) to encode the codepoint.
*/
static constexpr uint8_t getContinuationLength(size_t leadByte)
{
constexpr uint8_t s_continuationSize[] = {
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xc0 - 0xcf */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xd0 - 0xdf */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xe0 - 0xef */
3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 0, /* 0xf0 - 0xff */
};
return s_continuationSize[leadByte - kMinLeadByte];
}
/** Retrieves the lead byte mask for a given sequence continuation length.
*
* @param[in] continuationLength The continuation length for the sequence. This must be
* less than @ref kMaxSequenceLength.
* @returns The mask of bits in the lead byte that contribute to the decoded codepoint.
*
* @remarks This provides a lookup for the lead byte mask that determines which bits will
* contribute to the codepoint. Each multi-byte sequence lead byte starts with as
* many high bits set as the length of the sequence in bytes, followed by a clear
* bit. The remaining bits in the lead byte contribute directly to the highest
* bits of the decoded codepoint.
*/
static constexpr uint8_t getLeadMask(size_t continuationLength)
{
constexpr uint8_t s_leadMasks[] = { (1u << s_leadBits[0]) - 1, (1u << s_leadBits[1]) - 1,
(1u << s_leadBits[2]) - 1, (1u << s_leadBits[3]) - 1,
(1u << s_leadBits[4]) - 1, (1u << s_leadBits[5]) - 1,
(1u << s_leadBits[6]) - 1 };
return s_leadMasks[continuationLength];
}
/** Retrieves the lead byte bits that indicate the sequence length.
*
* @param[in] continuationLength The continuation length for the sequence. This must
* be less than @ref kMaxSequenceLength.
* @returns The high bits of the lead bytes with the given sequence length.
*
* @remarks This provides a lookup for the lead byte bits that indicate the sequence length
* for a UTF-8 codepoint. This is used when encoding a Unicode codepoint into
* UTF-8.
*/
static constexpr uint8_t getLeadByte(size_t continuationLength)
{
constexpr uint8_t s_leadBytes[] = {
(0xffu << (s_leadBits[0] + 1)) & 0xff, (0xffu << (s_leadBits[1] + 1)) & 0xff,
(0xffu << (s_leadBits[2] + 1)) & 0xff, (0xffu << (s_leadBits[3] + 1)) & 0xff,
(0xffu << (s_leadBits[4] + 1)) & 0xff, (0xffu << (s_leadBits[5] + 1)) & 0xff,
(0xffu << (s_leadBits[6] + 1)) & 0xff
};
return s_leadBytes[continuationLength];
}
/** Retrieves the maximum codepoint that can be represented by a given continuation length.
*
* @param[in] continuationLength The continuation length for the sequence. This must
* be less than @ref kMaxSequenceLength.
* @returns The maximum codepoint value that can be represented by the given continuation
* length. This covers up to sequences with seven bytes.
*
* @remarks This provides a lookup for the maximum codepoint that can be represented by
* a UTF-8 sequence of a given continuation length. This can be used to find the
* required length for a sequence when encoding. Note that the limit for a seven
* byte encoding is not currently fully representable here because it can hold
* between 32 and 36 bits of codepoint information.
*/
static constexpr CodePoint getMaxCodePoint(size_t continuationLength)
{
constexpr CodePoint s_maxCodePoint[] = { 0x00000080, 0x00000800, 0x00010000, 0x00200000,
0x04000000, 0x80000000, 0xffffffff };
return s_maxCodePoint[continuationLength];
}
/** Helper function to decode a single UTF-8 continuation byte.
*
* @param[in] byte The continuation byte to be decoded.
* @param[in] continuationLength The number of continuation bytes remaining in the sequence
* including the current continuation byte @p byte.
* @returns The decoded codepoint bits shifted to their required position. This value should
* be bitwise OR'd with the results of the previously decoded bytes in the sequence.
*/
inline static CodePoint decodeContinuationByte(uint8_t byte, size_t continuationLength)
{
return (byte & kContinuationMask) << ((continuationLength - 1) * kContinuationShift);
}
/** Helper function to retrieve the codepoint in a failure case.
*
* @param[in] flags The flags passed into the original function. Only the
* @ref fDecodeUseDefault flag will be checked.
* @returns `0` if the @ref fDecodeUseDefault flag is not used.
* @retval kDefaultCodePoint if the flag is used.
*/
static constexpr CodePoint getFailureCodepoint(Flags flags)
{
return (flags & fDecodeUseDefault) != 0 ? kDefaultCodePoint : 0;
}
/** @brief Parse the next UTF-8 code point.
* @param[in] str The UTF-8 input string to parse.
* @param[out] outNext The pointer to the start of the next UTF-8
* character in the string.
* This pointer will be set to `nullptr` if there
* is no next character this string can point to
* (e.g. if the string ended).
* This will also be set to `nullptr` if the UTF-8
* character is invalid and @p flags does not contain
* @ref fDecodeSkipInvalid.
* This must not be `nullptr`.
* @param[out] outCodePoint The code point that was parsed out of the UTF-8 string.
* If the call fails, this will be set to a
* default value depending on @p flags.
* @param[in] lengthInBytes The remaining number of bytes in the string. This may be
* @ref kNullTerminated if the string is well known to be null
* terminated. This operation will not walk the string beyond
* this number of bytes. Note that the operation may still end
* before this many bytes have been scanned if a null terminator
* is encountered.
* @param[in] flags Flags to control the behavior of this operation. This may be
* 0 or one or more of the fDecode* flags.
*
* @returns This returns `true` if the next UTF-8 character was parsed successfully
* and `false` if the UTF-8 sequence was invalid.
* `false` will also be returned if @p lengthInBytes is 0.
* `true` will be returned for a null terminating character.
*
* @note This will not parse UTF-16 surrogate pairs. If one is encountered,
* both code points will be returned in subsequent calls.
*/
static bool parseUtf8(const CodeByte* str,
const CodeByte** outNext,
CodePoint* outCodePoint,
size_t lengthInBytes = kNullTerminated,
Flags flags = 0)
{
auto fail = [&]() -> bool {
// we weren't asked to attempt to skip over invalid code sequences => just fail out
if ((flags & fDecodeSkipInvalid) == 0)
{
return false;
}
// walk the rest of the string skipping over continuation bytes and invalid lead bytes.
// Note that we've already tested and rejected the first byte so we just need to continue
// the search starting at the next byte.
for (size_t i = 1; i < lengthInBytes; i++)
{
const auto b = static_cast<uint8_t>(str[i]);
// continuation byte => skip it.
if ((b & ~kContinuationMask) == kContinuationBits)
continue;
// invalid lead byte => skip it.
if (b >= kMinLeadByte && getContinuationLength(b) == 0)
continue;
// invalid range of bytes
if (b >= k7BitLimit && b < kMinLeadByte)
continue;
*outNext = str + i;
return false;
}
// We've hit the end of the string. This mean that the sequence is
// either invalid, misaligned, or an illegal overlong sequence was
// used. We aren't able to write out the next character pointer if
// we hit this point.
return false;
};
// initialize to failure values;
*outCodePoint = getFailureCodepoint(flags);
*outNext = nullptr;
// the string doesn't have any more bytes in it -> no more codepoints => fail.
if (lengthInBytes == 0)
{
return false;
}
const auto byte = static_cast<uint8_t>(*str);
// the current code byte is at the null terminator -> no more codepoints => finish.
if (byte == '\0')
{
*outCodePoint = byte;
return true;
}
// the current code byte is a direct ASCII character => finish.
if (byte < k7BitLimit)
{
*outCodePoint = byte;
*outNext = str + 1;
return true;
}
if (byte < kMinLeadByte)
{
return fail();
}
// the current code byte is a lead byte => calculate the sequence length and return the
// start of the next codepoint.
const size_t continuationLength = getContinuationLength(byte);
const size_t sequenceLength = continuationLength + 1;
// not enough bytes left in the string to complete this codepoint => fail.
// continuationLength of 0 is invalid => fail
if (lengthInBytes < sequenceLength || continuationLength == 0)
{
return fail();
}
// decode the codepoint.
{
CodePoint cp = (byte & getLeadMask(continuationLength)) << (continuationLength * kContinuationShift);
for (size_t i = 0; i < continuationLength; i++)
{
// validate the continuation byte so we don't walk past the
// end of a null terminated string
if ((uint8_t(str[i + 1]) & ~kContinuationMask) != kContinuationBits)
{
return fail();
}
cp |= decodeContinuationByte(str[i + 1], continuationLength - i);
}
*outCodePoint = cp;
*outNext = str + sequenceLength;
return true;
}
}
};
/** A simple iterator class for walking a UTF-8 string. This is built on top of the UTF8Parser
* static class and uses its functionality. Strings can only be walked forward. Random access
* to codepoints in the string is not possible. If needed, the pointer to the start of the
* next codepoint or the codepoint index can be retrieved.
*/
class Utf8Iterator
{
public:
/** Reference the types used in Utf8Parser for more convenient use locally.
* @{
*/
/** @copydoc Utf8Parser::CodeByte */
using CodeByte = Utf8Parser::CodeByte;
/** @copydoc Utf8Parser::CodePoint */
using CodePoint = Utf8Parser::CodePoint;
/** @copydoc Utf8Parser::Flags */
using Flags = Utf8Parser::Flags;
/** @} */
// Reference the special length value used for null terminated strings.
/** @copydoc Utf8Parser::kNullTerminated */
static constexpr size_t kNullTerminated = Utf8Parser::kNullTerminated;
Utf8Iterator()
: m_prev(nullptr), m_string(nullptr), m_length(kNullTerminated), m_flags(0), m_lastCodePoint(0), m_index(0)
{
}
/** Constructor: initializes a new iterator for a given string.
*
* @param[in] string The string to walk. This should be a UTF-8 encoded string.
* This can be `nullptr`, but the iterator will not be valid if so.
* @param[in] lengthInBytes The maximum number of bytes to walk in the string. This may
* be kNullTerminated if the string is null terminated. If the
* string is unterminated or only a portion of it needs to be
* iterated over, this may be the size of the buffer in bytes.
* @param[in] flags Flags to control the behavior of the UTF-8 parser. This may
* be zero or more of the Utf8Parser::fDecode* flags.
* @returns No return value.
*/
Utf8Iterator(const CodeByte* string, size_t lengthInBytes = kNullTerminated, Flags flags = 0)
: m_prev(nullptr), m_string(string), m_length(lengthInBytes), m_flags(flags), m_lastCodePoint(0), m_index(0)
{
next();
}
/** Copy constructor: copies another iterator into this one.
*
* @param[in] it The iterator to be copied. Note that if @p it is invalid, this iterator
* will also become invalid.
* @returns No return value.
*/
Utf8Iterator(const Utf8Iterator& it)
{
copy(it);
}
/** Checks if this iterator is still valid.
*
* @returns `true` if this iterator still has at least one more codepoint to walk.
* @returns `false` if there is no more string data to walk and decode.
*/
operator bool() const
{
return isValid();
}
/** Check is this iterator is invalid.
*
* @returns `true` if there is no more string data to walk and decode.
* @returns `false` if this iterator still has at least one more codepoint to walk.
*/
bool operator!() const
{
return !isValid();
}
/** Retrieves the codepoint at this iterator's current location.
*
* @returns The codepoint at the current location in the string. Calling this multiple
* times does not cause the decoding work to be done multiple times. The decoded
* codepoint is cached once decoded.
* @returns `0` if there are no more codepoints to walk in the string.
*/
CodePoint operator*() const
{
return m_lastCodePoint;
}
/** Retrieves the address of the start of the current codepoint.
*
* @returns The address of the start of the current codepoint for this iterator. This can be
* used as a way of copying, editing, or reworking the string during iteration. It
* is the caller's responsibility to ensure the string is still properly encoded after
* any change.
* @returns `nullptr` if there is no more string data to walk.
*/
const CodeByte* operator&() const
{
return m_prev;
}
/** Pre increment operator: walk to the next codepoint in the string.
*
* @returns A reference to this iterator. Note that if the end of the string is reached, the
* new state of this iterator will first point to the null terminator in the string
* (for null terminated strings), then after another increment will return the
* address `nullptr` from the '&' operator. For length limited strings, reaching the
* end will immediately return `nullptr` from the '&' operator.
*/
Utf8Iterator& operator++()
{
next();
return *this;
}
/** Post increment operator: walk to the next codepoint in the string.
*
* @returns A new iterator object representing the state of this object before the increment
* operation.
*/
Utf8Iterator operator++(int32_t)
{
Utf8Iterator tmp = (*this);
next();
return tmp;
}
/** Increment operator: skip over zero or more codepoints in the string.
*
* @param[in] count The number of codepoints to skip over. This may be zero or larger.
* Negative values will be ignored and the iterator will not advance.
* @returns A reference to this iterator.
*/
template <typename T>
Utf8Iterator& operator+=(T count)
{
for (T i = 0; i < count && m_prev != nullptr; i++)
next();
return *this;
}
/** Addition operator: create a new iterator that skips zero or more codepoints.
*
* @param[in] count The number of codepoints to skip over. This may be zero or larger.
* Negative values will be ignored and the iterator will not advance.
* @returns A new iterator that has skipped over the next @p count codepoints in the string
* starting from the location of this iterator.
*/
template <typename T>
Utf8Iterator operator+(T count) const
{
Utf8Iterator tmp = *this;
return (tmp += count);
}
/** Comparison operators.
*
* @param[in] it The iterator to compare this one to.
* @returns `true` if the string position represented by @p it satisfies the requested
* comparison versus this object.
* @returns `false` if the string position represented by @p it does not satisfy the requested
* comparison versus this object.
*
* @remarks This object is treated as the left side of the comparison. Only the offset into
* the string contributes to this result. It is the caller's responsibility to
* ensure both iterators refer to the same string otherwise the results are
* undefined.
*/
bool operator==(const Utf8Iterator& it) const
{
return m_string == it.m_string;
}
/** @copydoc operator== */
bool operator!=(const Utf8Iterator& it) const
{
return m_string != it.m_string;
}
/** @copydoc operator== */
bool operator<(const Utf8Iterator& it) const
{
return m_string < it.m_string;
}
/** @copydoc operator== */
bool operator<=(const Utf8Iterator& it) const
{
return m_string <= it.m_string;
}
/** @copydoc operator== */
bool operator>(const Utf8Iterator& it) const
{
return m_string > it.m_string;
}
/** @copydoc operator== */
bool operator>=(const Utf8Iterator& it) const
{
return m_string >= it.m_string;
}
/** Copy assignment operator: copies another iterator into this one.
*
* @param[in] it The iterator to copy.
* @returns A reference to this object.
*/
Utf8Iterator& operator=(const Utf8Iterator& it)
{
// Note: normally we'd check for an identity assignment in this operator overload and
// ignore. Unfortunately we can't do that here since we also override the '&'
// operator above. Since this copy operation should still be safe for an identity
// assignment, we'll just let it proceed.
copy(it);
return *this;
}
/** String assignment operator: resets this iterator to the start of a new string.
*
* @param[in] str The new string to start walking. This must be a null terminated string.
* If this is `nullptr`, the iterator will become invalid. Any previous flags
* and length limits on this iterator will be cleared out.
* @returns A reference to this object.
*/
Utf8Iterator& operator=(const CodeByte* str)
{
m_prev = nullptr;
m_string = str;
m_length = kNullTerminated;
m_lastCodePoint = 0;
m_flags = 0;
m_index = 0;
next();
return *this;
}
/** Retrieves the current codepoint index of the iterator.
*
* @returns The number of codepoints that have been walked so far by this iterator in the
* current string. This will always start at 0 and will only increase when a
* new codepoint is successfully decoded.
*/
size_t getIndex() const
{
return m_index - 1;
}
/** Retrieves the size of the current codepoint in bytes.
*
* @returns The size of the current codepoint (ie: the one returned with the '*' operator)
* in bytes. This can be used along with the results of the '&' operator to copy
* this encoded codepoint into another buffer or modify the string in place.
*/
size_t getCodepointSize() const
{
if (m_string == nullptr)
return m_prev == nullptr ? 0 : 1;
return m_string - m_prev;
}
private:
/** Copies another iterator into this one.
*
* @param[in] it The iterator to copy from.
* @returns No return value.
*/
void copy(const Utf8Iterator& it)
{
m_prev = it.m_prev;
m_string = it.m_string;
m_length = it.m_length;
m_flags = it.m_flags;
m_lastCodePoint = it.m_lastCodePoint;
m_index = it.m_index;
}
/** Checks whether this iterator is still valid and has more work to do.
*
* @returns `true` if this iterator still has at least one more codepoint to walk.
* @returns `false` if there is no more string data to walk and decode.
*/
bool isValid() const
{
return m_string != nullptr && m_lastCodePoint != 0;
}
/** Walks to the start of the next codepoint.
*
* @returns No return value.
*
* @remarks This walks this iterator to the start of the next codepoint. The codepoint
* will be decoded and cached so that it can be retrieved. The length limit
* will also be decremented to reflect the amount of string data left to parse.
*/
void next()
{
const CodeByte* ptr;
if (m_string == nullptr)
{
m_prev = nullptr;
return;
}
if (m_length == 0)
{
m_string = nullptr;
m_prev = nullptr;
m_lastCodePoint = 0;
return;
}
ptr = Utf8Parser::nextCodePoint(m_string, m_length, &m_lastCodePoint, m_flags);
if (m_length != kNullTerminated)
m_length -= ptr - m_string;
m_prev = m_string;
m_string = ptr;
m_index++;
}
/** A pointer to the start of the codepoint that was last decoded. This will be the codepoint
* that has been cached in @a m_lastCodePoint. The size of this codepoint can be
* calculated by subtracting this address from @a m_string.
*/
const CodeByte* m_prev;
/** A pointer to the start of the next codepoint to be decoded. This will be `nullptr` if the
* full string has been decoded.
*/
const CodeByte* m_string;
/** The number of bytes remaining in the string or kNullTerminated. */
size_t m_length;
/** Flags to control how the codepoints in the string will be decoded. */
Flags m_flags;
/** The last codepoint that was successfully decoded. This is cached to prevent the need to
* decode it multiple times.
*/
CodePoint m_lastCodePoint;
/** The current codepoint index in the string. This is incremented each time a codepoint is
* successfully decoded.
*/
size_t m_index;
};
// implementation details used for string conversions - ignore this!
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
/** @brief A generic conversion between text formats.
* @tparam T The type of the input string.
* @tparam O The type of the output string.
* @tparam toCodePoint A function that converts a null terminated string of
* type T into a UTF-32 code point.
* This will return a pair where the first member is the
* length of the input consumed and the second is the
* UTF-32 code point that was calculated.
* Returning a 0 length will be treated as an error and
* input parsing will stop.
* @tparam fromCodePoint A function that converts a UTF-32 code point into
* a string of type O.
* This returns the length written to the ``out``.
* This should return 0 if there is not enough space
* in the output buffer; a partial character should
* not be written to the output.
* ``outLen`` is the amount of space available for
* writing ``out``.
* @param[in] str The input string to convert. This may not be `nullptr`.
* @param[out] out The output buffer to hold the converted data.
* This must be at least @p outLen in length, in elements.
* This can be `nullptr` to calculate the required
* output buffer length.
* The output string written to @p out will always be
* null terminated (unless @p outLen is 0), even if the
* string had to be truncated.
* @param[in] outLen The length of @p out, in elements.
* This should be 1 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of characters
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*/
template <typename T,
typename O,
std::pair<size_t, char32_t>(toCodePoint)(const T*),
size_t(fromCodePoint)(char32_t c, O* out, size_t outLen)>
inline size_t convertBetweenUnicodeFormatsRaw(const T* str, O* out, size_t outLen)
{
// the last element written to the output
O* prev = nullptr;
size_t prevLen = 0;
size_t written = 0;
size_t read = 0;
bool fullyRead = false;
if (str == nullptr)
{
return 0;
}
// no output => ignore outLen in the loop
if (out == nullptr)
{
outLen = SIZE_MAX;
}
if (outLen == 0)
{
return 0;
}
for (;;)
{
size_t len;
// decode the input to UTF-32
std::pair<size_t, char32_t> decoded = toCodePoint(str + read);
// decode failed
if (decoded.first == 0)
{
break;
}
// encode from UTF-32 to the output format
len = fromCodePoint(decoded.second, (out == nullptr) ? nullptr : out + written, outLen - written);
// out of buffer space
if (len == 0)
{
break;
}
// store the last written character
if (out != nullptr)
{
prev = out + written;
}
prevLen = len;
// advance the indices
written += len;
read += decoded.first;
// hit the null terminator => finished
if (decoded.second == '\0')
{
fullyRead = true;
break;
}
}
// if the string was truncated, we need to cut out the last character
// from the written count
if (!fullyRead)
{
if (written == outLen)
{
written -= prevLen;
written += 1;
if (out != nullptr)
{
*prev = '\0';
}
}
else
{
if (out != nullptr)
{
out[written] = '\0';
}
written++;
}
}
return written;
}
inline std::pair<size_t, char32_t> utf8ToCodePoint(const char* str)
{
char32_t c = 0;
const char* p = Utf8Parser::nextCodePoint(str, Utf8Parser::kNullTerminated, &c, Utf8Parser::fDecodeUseDefault);
if (c == '\0')
{
return std::pair<size_t, char32_t>(1, '\0');
}
else if (p == nullptr)
{
// invalid character, skip it
return std::pair<size_t, char32_t>(1, c);
}
else
{
return std::pair<size_t, char32_t>(p - str, c);
}
}
inline size_t utf32FromCodePoint(char32_t c, char32_t* out, size_t outLen)
{
if (outLen == 0)
{
return 0;
}
else
{
if (out != nullptr)
{
out[0] = c;
}
return 1;
}
};
inline std::pair<size_t, char32_t> utf32ToCodePoint(const char32_t* str)
{
return std::pair<size_t, char32_t>(1, *str);
}
inline size_t utf8FromCodePoint(char32_t c, char* out, size_t outLen)
{
char dummy[8];
size_t len = 0;
char* p;
if (out == nullptr)
{
out = dummy;
outLen = CARB_MIN(outLen, CARB_COUNTOF(dummy));
}
p = Utf8Parser::getCodeBytes(c, out, outLen, &len);
if (p == nullptr)
{
return 0;
}
else
{
return len;
}
}
inline std::pair<size_t, char32_t> utf16ToCodePoint(const char16_t* str)
{
char32_t c;
switch (Utf8Parser::classifyUtf16SurrogateMember(str[0]))
{
case Utf8Parser::SurrogateMember::eHigh:
c = Utf8Parser::decodeUtf16CodePoint(str[0], str[1]);
if (c == 0) // invalid surrogate pair
{
break;
}
return std::pair<size_t, char32_t>(2, c);
// a stray low surrogate is invalid
case Utf8Parser::SurrogateMember::eLow:
break;
default:
return std::pair<size_t, char32_t>(1, str[0]);
}
// failed to parse => just return the invalid character code point
constexpr static auto kDefaultCodePoint_ = Utf8Parser::kDefaultCodePoint; // CC-1110
return std::pair<size_t, char32_t>(1, kDefaultCodePoint_);
}
inline size_t utf16FromCodePoint(char32_t c, char16_t* out, size_t outLen)
{
char32_t mangled = 0;
size_t len;
len = Utf8Parser::encodeUtf16CodePoint(c, &mangled);
if (outLen < len)
{
return 0;
}
if (out != nullptr)
{
switch (len)
{
default:
break;
case 1:
out[0] = char16_t(mangled);
break;
case 2:
out[0] = char16_t(mangled & 0xFFFF);
out[1] = char16_t(mangled >> 16);
break;
}
}
return len;
}
/** @brief Helper to perform a conversion using a string.
* @tparam T The type of the input string.
* @tparam O The type of the output string.
* @tparam conv The function that will convert the input type to the output
* type using raw pointers.
* This should be a wrapped call to convertBetweenUnicodeFormatsRaw().
* @param[in] str The null terminated input string to convert.
* @returns @p str converted to the desired output format.
*/
template <typename T, typename O, size_t conv(const T* str, O* out, size_t outLen)>
inline std::basic_string<O> convertBetweenUnicodeFormats(const T* str)
{
omni::extras::ScratchBuffer<O, 4096> buffer;
size_t len = conv(str, nullptr, 0);
if (len == 0 || !buffer.resize(len))
{
return std::basic_string<O>();
}
conv(str, buffer.data(), buffer.size());
return std::basic_string<O>(buffer.data(), buffer.data() + len - 1);
}
} // namespace detail
#endif
/** Convert a UTF-8 encoded string to UTF-32.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @param[out] out The output buffer to hold the UTF-32 data.
* This must be at least @p outLen in length, in elements.
* This can be `nullptr` to calculate the required output buffer length.
* The output string written to @p out will always be null terminated
* (unless @p outLen is 0), even if the string had to be truncated.
* @param[in] outLen The length of @p out, in elements.
* This should be 0 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of UTF-32 characters
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*/
inline size_t convertUtf8StringToUtf32(const char* str, char32_t* out, size_t outLen) noexcept
{
return detail::convertBetweenUnicodeFormatsRaw<char, char32_t, detail::utf8ToCodePoint, detail::utf32FromCodePoint>(
str, out, outLen);
}
/** Convert a UTF-8 encoded string to UTF-32.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @returns @p str converted to UTF-32.
*/
inline std::u32string convertUtf8StringToUtf32(const char* str)
{
return detail::convertBetweenUnicodeFormats<char, char32_t, convertUtf8StringToUtf32>(str);
}
/** Convert a UTF-8 encoded string to UTF-32.
* @param[in] str The input UTF-8 string to convert.
* @returns @p str converted to UTF-32.
*/
inline std::u32string convertUtf8StringToUtf32(std::string str)
{
return convertUtf8StringToUtf32(str.c_str());
}
/** Convert a UTF-32 encoded string to UTF-8.
* @param[in] str The input UTF-32 string to convert. This may not be `nullptr`.
* @param[out] out The output buffer to hold the UTF-8 data.
* This must be at least @p outLen bytes in length.
* This can be `nullptr` to calculate the required output buffer length.
* The output string written to @p out will always be null terminated
* (unless @p outLen is 0), even if the string had to be truncated.
* @param[in] outLen The length of @p out, in bytes.
* This should be 0 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of UTF-8 bytes
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*/
inline size_t convertUtf32StringToUtf8(const char32_t* str, char* out, size_t outLen)
{
return detail::convertBetweenUnicodeFormatsRaw<char32_t, char, detail::utf32ToCodePoint, detail::utf8FromCodePoint>(
str, out, outLen);
}
/** Convert a UTF-32 encoded string to UTF-8.
* @param[in] str The input UTF-32 string to convert. This may not be `nullptr`.
* @returns @p str converted to UTF-8.
*/
inline std::string convertUtf32StringToUtf8(const char32_t* str)
{
return detail::convertBetweenUnicodeFormats<char32_t, char, convertUtf32StringToUtf8>(str);
}
/** Convert a UTF-8 encoded string to UTF-32.
* @param[in] str The input UTF-8 string to convert.
* @returns @p str converted to UTF-32.
*/
inline std::string convertUtf32StringToUtf8(std::u32string str)
{
return convertUtf32StringToUtf8(str.c_str());
}
/** Convert a UTF-16 encoded string to UTF-8.
* @param[in] str The input UTF-16 string to convert. This may not be `nullptr`.
* @param[out] out The output buffer to hold the UTF-8 data.
* This must be at least @p outLen bytes in length.
* This can be `nullptr` to calculate the required output buffer length.
* The output string written to @p out will always be null terminated
* (unless @p outLen is 0), even if the string had to be truncated.
* @param[in] outLen The length of @p out, in bytes.
* This should be 0 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of UTF-8 bytes
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*/
inline size_t convertUtf16StringToUtf8(const char16_t* str, char* out, size_t outLen)
{
return detail::convertBetweenUnicodeFormatsRaw<char16_t, char, detail::utf16ToCodePoint, detail::utf8FromCodePoint>(
str, out, outLen);
}
/** Convert a UTF-16 encoded string to UTF-8.
* @param[in] str The input UTF-16 string to convert. This may not be `nullptr`.
* @returns @p str converted to UTF-8.
*/
inline std::string convertUtf16StringToUtf8(const char16_t* str)
{
return detail::convertBetweenUnicodeFormats<char16_t, char, convertUtf16StringToUtf8>(str);
}
/** Convert a UTF-8 encoded string to UTF-32.
* @param[in] str The input UTF-8 string to convert.
* @returns @p str converted to UTF-32.
*/
inline std::string convertUtf16StringToUtf8(std::u16string str)
{
return convertUtf16StringToUtf8(str.c_str());
}
/** Convert a UTF-8 encoded string to UTF-16.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @param[out] out The output buffer to hold the UTF-16 data.
* This must be at least @p outLen in length, in elements.
* This can be `nullptr` to calculate the required output buffer length.
* The output string written to @p out will always be null terminated
* (unless @p outLen is 0), even if the string had to be truncated.
* @param[in] outLen The length of @p out, in elements.
* This should be 1 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of UTF-32 characters
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*/
inline size_t convertUtf8StringToUtf16(const char* str, char16_t* out, size_t outLen) noexcept
{
return detail::convertBetweenUnicodeFormatsRaw<char, char16_t, detail::utf8ToCodePoint, detail::utf16FromCodePoint>(
str, out, outLen);
}
/** Convert a UTF-8 encoded string to UTF-16.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @returns @p str converted to UTF-16.
*/
inline std::u16string convertUtf8StringToUtf16(const char* str)
{
return detail::convertBetweenUnicodeFormats<char, char16_t, convertUtf8StringToUtf16>(str);
}
/** Convert a UTF-8 encoded string to UTF-16.
* @param[in] str The input UTF-8 string to convert.
* @returns @p str converted to UTF-16.
*/
inline std::u16string convertUtf8StringToUtf16(std::string str)
{
return convertUtf8StringToUtf16(str.c_str());
}
/** Convert a UTF-8 encoded string to wide string.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @param[out] out The output buffer to hold the wide data.
* This must be at least @p outLen in length, in elements.
* This can be `nullptr` to calculate the required output buffer length.
* The output string written to @p out will always be null terminated
* (unless @p outLen is 0), even if the string had to be truncated.
* @param[in] outLen The length of @p out, in elements.
* This should be 1 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of wide characters
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*
* @note This is provided for interoperability with older systems that still use
* wide strings. Please use UTF-8 or UTF-32 for new systems.
*/
inline size_t convertUtf8StringToWide(const char* str, wchar_t* out, size_t outLen) noexcept
{
#if CARB_PLATFORM_WINDOWS
static_assert(sizeof(*out) == sizeof(char16_t), "unexpected wchar_t type");
return detail::convertBetweenUnicodeFormatsRaw<char, char16_t, detail::utf8ToCodePoint, detail::utf16FromCodePoint>(
str, reinterpret_cast<char16_t*>(out), outLen);
#else
static_assert(sizeof(*out) == sizeof(char32_t), "unexpected wchar_t type");
return detail::convertBetweenUnicodeFormatsRaw<char, char32_t, detail::utf8ToCodePoint, detail::utf32FromCodePoint>(
str, reinterpret_cast<char32_t*>(out), outLen);
#endif
}
/** Convert a UTF-8 encoded string to wide.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @returns @p str converted to wide.
*
* @note This is provided for interoperability with older systems that still use
* wide strings. Please use UTF-8 or UTF-32 for new systems.
*/
inline std::wstring convertUtf8StringToWide(const char* str)
{
return detail::convertBetweenUnicodeFormats<char, wchar_t, convertUtf8StringToWide>(str);
}
/** Convert a UTF-8 encoded string to UTF-16.
* @param[in] str The input UTF-8 string to convert.
* @returns @p str converted to UTF-16.
*
* @note This is provided for interoperability with older systems that still use
* wide strings. Please use UTF-8 or UTF-32 for new systems.
*/
inline std::wstring convertUtf8StringToWide(std::string str)
{
return convertUtf8StringToWide(str.c_str());
}
/** Convert a wide encoded string to UTF-8 string.
* @param[in] str The input wide string to convert to UTF-8. This may not be `nullptr`.
* @param[out] out The output buffer to hold the wide data.
* This must be at least @p outLen in length, in elements.
* This can be `nullptr` to calculate the required output buffer length.
* The output string written to @p out will always be null terminated
* (unless @p outLen is 0), even if the string had to be truncated.
* @param[in] outLen The length of @p out, in elements.
* This should be 1 if @p out is `nullptr`.
* @returns If @p out is not `nullptr`, this returns the number of wide characters
* written to @p out. This includes the null terminating character.
* @returns If @p out is `nullptr`, this returns the required buffer length to
* store the output string.
*
* @note This is provided for interoperability with older systems that still use
* wide strings. Please use UTF-8 or UTF-32 for new systems.
*/
inline size_t convertWideStringToUtf8(const wchar_t* str, char* out, size_t outLen) noexcept
{
#if CARB_PLATFORM_WINDOWS
static_assert(sizeof(*str) == sizeof(char16_t), "unexpected wchar_t type");
return detail::convertBetweenUnicodeFormatsRaw<char16_t, char, detail::utf16ToCodePoint, detail::utf8FromCodePoint>(
reinterpret_cast<const char16_t*>(str), out, outLen);
#else
static_assert(sizeof(*str) == sizeof(char32_t), "unexpected wchar_t type");
return detail::convertBetweenUnicodeFormatsRaw<char32_t, char, detail::utf32ToCodePoint, detail::utf8FromCodePoint>(
reinterpret_cast<const char32_t*>(str), out, outLen);
#endif
}
/** Convert a UTF-8 encoded string to wide.
* @param[in] str The input UTF-8 string to convert. This may not be `nullptr`.
* @returns @p str converted to wide.
*
* @note This is provided for interoperability with older systems that still use
* wide strings. Please use UTF-8 or UTF-32 for new systems.
*/
inline std::string convertWideStringToUtf8(const wchar_t* str)
{
return detail::convertBetweenUnicodeFormats<wchar_t, char, convertWideStringToUtf8>(str);
}
/** Convert a UTF-8 encoded string to UTF-16.
* @param[in] str The input UTF-8 string to convert.
* @returns @p str converted to UTF-16.
*
* @note This is provided for interoperability with older systems that still use
* wide strings. Please use UTF-8 or UTF-32 for new systems.
*/
inline std::string convertWideStringToUtf8(std::wstring str)
{
return convertWideStringToUtf8(str.c_str());
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/StringProcessor.h | // Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "EnvironmentVariable.h"
#include "../logging/Log.h"
namespace carb
{
namespace extras
{
/**
* Search for env vars like ${SOME_VAR} in a string and replace them with actual env var value
*/
inline std::string replaceEnvironmentVariables(const std::string& text)
{
// At least '${}' is needed for that function to do processing
if (text.size() < 3)
return text;
std::string result;
result.reserve(text.size());
size_t lastPatternIndex = 0;
for (size_t i = 0; i < text.size() - 1; i++)
{
if (text[i] == '$' && text[i + 1] == '{')
{
result.append(text.substr(lastPatternIndex, i - lastPatternIndex));
size_t pos = text.find('}', i + 1);
if (pos != std::string::npos)
{
const std::string envVarName = text.substr(i + 2, pos - i - 2);
std::string var;
if (!envVarName.empty() && extras::EnvironmentVariable::getValue(envVarName.c_str(), var))
{
result.append(var);
}
else
{
CARB_LOG_ERROR("Environment variable: %s was not found.", envVarName.c_str());
}
lastPatternIndex = pos + 1;
i = pos;
}
}
};
result.append(text.substr(lastPatternIndex, text.size() - lastPatternIndex));
return result;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/MemoryUsage.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Helper to get the memory characteristics of a program.
*/
#pragma once
#include "../Defines.h"
#include "../logging/Log.h"
#if CARB_PLATFORM_LINUX
# include <sys/sysinfo.h>
# include <stdio.h>
# include <unistd.h>
# include <sys/time.h>
# include <sys/resource.h>
#elif CARB_PLATFORM_MACOS
# include <mach/task.h>
# include <mach/mach_init.h>
# include <mach/mach_host.h>
# include <os/proc.h>
# include <sys/resource.h>
#elif CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#endif
namespace carb
{
namespace extras
{
/** The type of memory to query. */
enum class MemoryQueryType
{
eAvailable, /**< The available memory on the system. */
eTotal, /**< The total memory on the system. */
};
size_t getPhysicalMemory(MemoryQueryType type); // forward declare
/** Retrieve the physical memory usage by the current process.
* @returns The memory usage for the current process.
* @returns 0 if the operation failed.
*/
inline size_t getCurrentProcessMemoryUsage()
{
#if CARB_PLATFORM_LINUX
unsigned long rss = 0;
long pageSize;
pageSize = sysconf(_SC_PAGESIZE);
if (pageSize < 0)
{
CARB_LOG_ERROR("failed to retrieve the page size");
return 0;
}
// fopen() and fgets() can use the heap, and we may be called from the crashreporter, so avoid using those
// functions to avoid heap usage.
auto fd = open("/proc/self/statm", 0, O_RDONLY);
if (fd < 0)
{
CARB_LOG_ERROR("failed to open /proc/self/statm");
return 0;
}
char line[256];
auto readBytes = CARB_RETRY_EINTR(read(fd, line, CARB_COUNTOF(line) - 1));
if (readBytes > 0)
{
char* endp;
// Skip the first, read the second
strtoul(line, &endp, 10);
rss = strtoul(endp, nullptr, 10);
}
close(fd);
return rss * pageSize;
#elif CARB_PLATFORM_WINDOWS
CARBWIN_PROCESS_MEMORY_COUNTERS mem;
mem.cb = sizeof(mem);
if (!K32GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&mem, sizeof(mem)))
{
CARB_LOG_ERROR("GetProcessMemoryInfo failed");
return 0;
}
return mem.WorkingSetSize;
#elif CARB_PLATFORM_MACOS
mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
task_basic_info info = {};
kern_return_t r = task_info(mach_task_self(), TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&info), &count);
if (r != KERN_SUCCESS)
{
CARB_LOG_ERROR("task_info() failed (%d)", int(r));
return 0;
}
return info.resident_size;
#else
# warning "getMemoryUsage() has no implementation"
return 0;
#endif
}
/** Retrieves the peak memory usage information for the calling process.
*
* @returns The maximum process memory usage level in bytes.
*/
inline size_t getPeakProcessMemoryUsage()
{
#if CARB_PLATFORM_WINDOWS
CARBWIN_PROCESS_MEMORY_COUNTERS mem;
mem.cb = sizeof(mem);
if (!K32GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&mem, sizeof(mem)))
{
CARB_LOG_ERROR("GetProcessMemoryInfo failed");
return 0;
}
return mem.PeakWorkingSetSize;
#elif CARB_POSIX
rusage usage_data;
size_t scale;
getrusage(RUSAGE_SELF, &usage_data);
# if CARB_PLATFORM_LINUX
scale = 1024; // Linux provides this value in kilobytes.
# elif CARB_PLATFORM_MACOS
scale = 1; // MacOS provides this value in bytes.
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
// convert to bytes.
return usage_data.ru_maxrss * scale;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/** Stores information about memory in the system. All values are in bytes. */
struct SystemMemoryInfo
{
/** The total available physical RAM in bytes. This may be reported as slightly less than
* the expected amount due to some small amount of space being reserved for the OS. This
* is often negligible, but when displaying the memory amount to the user, it is good to
* round to the nearest mebibyte or gibibyte.
*/
uint64_t totalPhysical;
/** The available physical RAM in bytes. This is not memory that is necessarily available
* to the calling process, but rather the amount of physical RAM that the OS is not
* actively using for all running processes at the moment.
*/
uint64_t availablePhysical;
/** The total amount of page file space available to the system in bytes. When physical RAM
* is filled, this space will be used to provide a backup space for memory pages of lower
* priority, inactive, or background processes so that RAM can be freed up for more active
* or demanding processes.
*/
uint64_t totalPageFile;
/** The available amount of page file space in bytes. This is the unused portion of the page
* file that the system can still make use of to keep foreground processes from starving.
*/
uint64_t availablePageFile;
/** The total amount of virtual memory available to the calling process in bytes. This is
* the maximum amount of addressable space and the maximum memory address that can be used.
* On Windows this value should be consistent, but on Linux, this value can change depending
* on the owner of the process if the administrator has set differing limits for users.
*/
uint64_t totalVirtual;
/** The available amount of virtual memory in bytes still usable by the calling process. This
* is the amount of memory that can still be allocated by the process. That said however,
* the process may not be able to actually use all of that memory if the system's resources
* are exhausted. Since virtual memory space is generally much larger than the amount of
* available RAM and swap space on 64 bit processes, the process will still be in an out
* of memory situation if all of the system's physical RAM and swap space have been consumed
* by the process's demands. When looking at out of memory situations, it is also important
* to consider virtual memory space along with physical and swap space.
*/
uint64_t availableVirtual;
};
#if CARB_PLATFORM_LINUX
/** Retrieves the memory size multiplier from a value suffix.
*
* @param[in] str The string containing the memory size suffix. This may not be `nullptr`.
* @returns The multiplier to use to convert the memory value to bytes. Returns 1 if the
* memory suffix is not recognized. Supported suffixes are 'KB', 'MB', 'GB', 'TB',
* 'PB', 'EB', and bytes. All unknown suffixes will be treated as bytes.
*/
inline size_t getMemorySizeMultiplier(const char* str)
{
size_t multiplier = 1;
// strip leading whitespace.
while (*str == ' ' || *str == '\t')
str++;
// check the prefix of the multiplier string (ie: "kB", "gB", etc).
switch (tolower(*str))
{
case 'e':
multiplier *= 1024ull; // fall through...
CARB_FALLTHROUGH;
case 'p':
multiplier *= 1024ull; // fall through...
CARB_FALLTHROUGH;
case 't':
multiplier *= 1024ull; // fall through...
CARB_FALLTHROUGH;
case 'g':
multiplier *= 1024ull; // fall through...
CARB_FALLTHROUGH;
case 'm':
multiplier *= 1024ull; // fall through...
CARB_FALLTHROUGH;
case 'k':
multiplier *= 1024ull; // fall through...
CARB_FALLTHROUGH;
default:
break;
}
return multiplier;
}
/** Retrieves a memory value by its key name in '/proc/meminfo' or other.
*
* @param[in] filename The name of the pseudo file to parse the information from. This may be
* `nullptr` to use the default of '/proc/meminfo' instead.
* @param[in] name The name of the key to search for. This may not be `nullptr`.
* @param[in] nameLen The length of the key name in characters. If set to 0, the length
* of the string will be calculated.
* @returns The value associated with the given key name if found. Returns 0 otherwise.
*/
inline size_t getMemoryValueByName(const char* filename, const char* name, size_t nameLen = 0)
{
constexpr static char kProcMemInfo[] = "/proc/meminfo";
size_t bytes = 0;
char line[256];
size_t nameLength = nameLen;
if (filename == nullptr)
filename = kProcMemInfo;
if (nameLength == 0)
nameLength = strlen(name);
// fopen() and fgets() can use the heap, and we may be called from the crashreporter, so avoid using those
// functions to avoid heap usage.
auto fd = open(filename, 0, O_RDONLY);
if (fd < 0)
return 0;
ssize_t readBytes;
while ((readBytes = CARB_RETRY_EINTR(read(fd, line, CARB_COUNTOF(line) - 1))) > 0)
{
line[readBytes] = '\0';
auto lf = strchr(line, '\n');
if (lf)
{
*lf = '\0';
// Seek back to the start of the next line for the next read
lseek(fd, -off_t(line + readBytes - lf) + 1, SEEK_CUR);
}
if (strncmp(line, name, nameLength) == 0)
{
// Found the key that we're looking for => parse its value in Kibibytes and succeed.
char* endp;
bytes = strtoull(line + nameLength, &endp, 10);
bytes *= getMemorySizeMultiplier(endp);
break;
}
}
close(fd);
return bytes;
}
#endif
/** Retrieves the memory usage information for the system.
*
* @param[out] out Receives the memory totals and availability information for the system.
* @returns `true` if the memory information is successfully collected. Returns `false`
* otherwise.
*/
inline bool getSystemMemoryInfo(SystemMemoryInfo& out)
{
#if CARB_PLATFORM_LINUX
struct sysinfo info = {};
struct rlimit limit = {};
int result;
size_t bytes;
// collect the total memory counts.
result = sysinfo(&info);
if (result != 0)
{
CARB_LOG_WARN("sysinfo() returned %d", result);
// retrieve the values from '/proc/meminfo' instead.
out.totalPhysical = getMemoryValueByName(nullptr, "MemTotal:", sizeof("MemTotal:") - 1);
out.totalPageFile = getMemoryValueByName(nullptr, "SwapTotal:", sizeof("SwapTotal:") - 1);
}
else
{
out.totalPhysical = (uint64_t)info.totalram * info.mem_unit;
out.totalPageFile = (uint64_t)info.totalswap * info.mem_unit;
}
// get the virtual memory info.
if (getrlimit(RLIMIT_AS, &limit) == 0)
{
out.totalVirtual = limit.rlim_cur;
out.availableVirtual = 0;
// retrieve the total VM usage for the calling process.
bytes = getMemoryValueByName("/proc/self/status", "VmSize:", sizeof("VmSize:") - 1);
if (bytes != 0)
{
if (bytes > out.totalVirtual)
{
CARB_LOG_WARN(
"retrieved a larger VM size than total VM space (!?) {bytes = %zu, "
"totalVirtual = %" PRIu64 "}",
bytes, out.totalVirtual);
}
else
out.availableVirtual = out.totalVirtual - bytes;
}
}
else
{
CARB_LOG_WARN("failed to retrieve the total address space {errno = %d/%s}", errno, strerror(errno));
out.totalVirtual = 0;
out.availableVirtual = 0;
}
// collect the available RAM as best we can. The values in '/proc/meminfo' are typically
// more accurate than what sysinfo() gives us due to the 'mem_unit' value.
bytes = getMemoryValueByName(nullptr, "MemAvailable:", sizeof("MemAvailable:") - 1);
if (bytes != 0)
out.availablePhysical = bytes;
else
out.availablePhysical = (uint64_t)info.freeram * info.mem_unit;
// collect the available swap space as best we can.
bytes = getMemoryValueByName(nullptr, "SwapFree:", sizeof("SwapFree:") - 1);
if (bytes != 0)
out.availablePageFile = bytes;
else
out.availablePageFile = (uint64_t)info.freeswap * info.mem_unit;
return true;
#elif CARB_PLATFORM_WINDOWS
CARBWIN_MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
if (!GlobalMemoryStatusEx((LPMEMORYSTATUSEX)&status))
{
CARB_LOG_ERROR("GlobalMemoryStatusEx() failed {error = %d}", GetLastError());
return false;
}
out.totalPhysical = (uint64_t)status.ullTotalPhys;
out.totalPageFile = (uint64_t)status.ullTotalPageFile;
out.totalVirtual = (uint64_t)status.ullTotalVirtual;
out.availablePhysical = (uint64_t)status.ullAvailPhys;
out.availablePageFile = (uint64_t)status.ullAvailPageFile;
out.availableVirtual = (uint64_t)status.ullAvailVirtual;
return true;
#elif CARB_PLATFORM_MACOS
int mib[2];
size_t length;
mach_msg_type_number_t count;
kern_return_t r;
xsw_usage swap = {};
task_basic_info info = {};
struct rlimit limit = {};
// get the system's swap usage
mib[0] = CTL_HW, mib[1] = VM_SWAPUSAGE;
length = sizeof(swap);
if (sysctl(mib, CARB_COUNTOF(mib), &swap, &length, nullptr, 0) != 0)
{
CARB_LOG_ERROR("sysctl() for VM_SWAPUSAGE failed (errno = %d)", errno);
return false;
}
count = TASK_BASIC_INFO_COUNT;
r = task_info(mach_task_self(), TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&info), &count);
if (r != KERN_SUCCESS)
{
CARB_LOG_ERROR("task_info() failed (result = %d, errno = %d)", int(r), errno);
return false;
}
// it's undocumented but RLIMIT_AS is supported
if (getrlimit(RLIMIT_AS, &limit) != 0)
{
CARB_LOG_ERROR("getrlimit(RLIMIT_AS) failed (errno = %d)", errno);
return false;
}
out.totalVirtual = limit.rlim_cur;
out.availableVirtual = out.totalVirtual - info.virtual_size;
out.totalPhysical = getPhysicalMemory(MemoryQueryType::eTotal);
out.availablePhysical = getPhysicalMemory(MemoryQueryType::eAvailable);
out.totalPageFile = swap.xsu_total;
out.availablePageFile = swap.xsu_avail;
return true;
#else
# warning "getSystemMemoryInfo() has no implementation"
return 0;
#endif
}
/** Retrieve the physical memory available on the system.
* @param[in] type The type of memory to query.
* @returns The physical memory available on the system.
* @returns 0 if the operation failed.
* @note On Linux, disk cache memory doesn't count as available memory, so
* allocations may still succeed if available memory is near 0, but it
* will contribute to system slowdown if it's using disk cache space.
*/
inline size_t getPhysicalMemory(MemoryQueryType type)
{
#if CARB_PLATFORM_LINUX
// this is a linux-specific system call
struct sysinfo info;
int result;
const char* search;
size_t searchLength;
size_t bytes;
// attempt to read the available memory from '/proc/meminfo' first.
if (type == MemoryQueryType::eTotal)
{
search = "MemTotal:";
searchLength = sizeof("MemTotal:") - 1;
}
else
{
search = "MemAvailable:";
searchLength = sizeof("MemAvailable:") - 1;
}
bytes = getMemoryValueByName(nullptr, search, searchLength);
if (bytes != 0)
return bytes;
// fall back to sysinfo() to get the amount of free RAM if it couldn't be found in
// '/proc/meminfo'.
result = sysinfo(&info);
if (result != 0)
{
CARB_LOG_ERROR("sysinfo() returned %d", result);
return 0;
}
if (type == MemoryQueryType::eTotal)
return info.totalram * info.mem_unit;
else
return info.freeram * info.mem_unit;
#elif CARB_PLATFORM_WINDOWS
CARBWIN_MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
if (!GlobalMemoryStatusEx((LPMEMORYSTATUSEX)&status))
{
CARB_LOG_ERROR("GlobalMemoryStatusEx failed");
return 0;
}
if (type == MemoryQueryType::eTotal)
return status.ullTotalPhys;
else
return status.ullAvailPhys;
#elif CARB_PLATFORM_MACOS
int mib[2];
size_t memSize = 0;
size_t length;
if (type == MemoryQueryType::eTotal)
{
mib[0] = CTL_HW, mib[1] = HW_MEMSIZE;
length = sizeof(memSize);
if (sysctl(mib, CARB_COUNTOF(mib), &memSize, &length, nullptr, 0) != 0)
{
CARB_LOG_ERROR("sysctl() for HW_MEMSIZE failed (errno = %d)", errno);
return false;
}
}
else
{
mach_msg_type_number_t count;
kern_return_t r;
vm_statistics_data_t vm = {};
size_t pageSize = getpagesize();
count = HOST_VM_INFO_COUNT;
r = host_statistics(mach_host_self(), HOST_VM_INFO, reinterpret_cast<host_info_t>(&vm), &count);
if (r != KERN_SUCCESS)
{
CARB_LOG_ERROR("host_statistics() failed (%d)", int(r));
return false;
}
memSize = (vm.free_count + vm.inactive_count) * pageSize;
}
return memSize;
#else
# warning "getPhysicalMemoryAvailable() has no implementation"
return 0;
#endif
}
/** Names for the different types of common memory scales. This covers both binary
* (ie: Mebibytes = 1,048,576 bytes) and decimal (ie: Megabytes = 1,000,000 bytes)
* size scales.
*/
enum class MemoryScaleType
{
/** Name for the binary memory size scale. This is commonly used in operating systems
* and software. All scale names are powers of 1024 bytes and typically use the naming
* convention of using the suffix "bibytes" and the first two letters of the prefix of
* its decimal counterpart. For example, "mebibytes" instead of "megabytes".
*/
eBinaryScale,
/** Name for the decimal memory size scale. This is commonly used in hardware size
* descriptions. All scale names are powers of 1000 byes and typically use the Greek
* size prefix followed by "Bytes". For example, "megabytes", "petabytes", "kilobytes",
* etc.
*/
eDecimalScale,
};
/** Retrieves a friendly memory size and scale suffix for a given number of bytes.
*
* @param[in] bytes The number of bytes to convert to a friendly memory size.
* @param[out] suffix Receives the name of the suffix to the converted memory size amount.
* This is suitable for displaying to a user.
* @param[in] scale Whether the conversion should be done using a decimal or binary scale.
* This defaults to @ref MemoryScaleType::eBinaryScale.
* @returns The given memory size value @p bytes converted to the next lowest memory scale value
* (ie: megabytes, kilobytes, etc). The appropriate suffix string is returned through
* @p suffix.
*/
inline double getFriendlyMemorySize(size_t bytes, const char** suffix, MemoryScaleType scale = MemoryScaleType::eBinaryScale)
{
constexpr size_t kEib = 1024ull * 1024 * 1024 * 1024 * 1024 * 1024;
constexpr size_t kPib = 1024ull * 1024 * 1024 * 1024 * 1024;
constexpr size_t kTib = 1024ull * 1024 * 1024 * 1024;
constexpr size_t kGib = 1024ull * 1024 * 1024;
constexpr size_t kMib = 1024ull * 1024;
constexpr size_t kKib = 1024ull;
constexpr size_t kEb = 1000ull * 1000 * 1000 * 1000 * 1000 * 1000;
constexpr size_t kPb = 1000ull * 1000 * 1000 * 1000 * 1000;
constexpr size_t kTb = 1000ull * 1000 * 1000 * 1000;
constexpr size_t kGb = 1000ull * 1000 * 1000;
constexpr size_t kMb = 1000ull * 1000;
constexpr size_t kKb = 1000ull;
constexpr size_t limits[2][6] = { { kEib, kPib, kTib, kGib, kMib, kKib }, { kEb, kPb, kTb, kGb, kMb, kKb } };
constexpr const char* suffixes[2][6] = { { "EiB", "PiB", "TiB", "GiB", "MiB", "KiB" },
{ "EB", "PB", "TB", "GB", "MB", "KB" } };
if (scale != MemoryScaleType::eBinaryScale && scale != MemoryScaleType::eDecimalScale)
{
*suffix = "bytes";
return (double)bytes;
}
for (size_t i = 0; i < CARB_COUNTOF(limits[(size_t)scale]); i++)
{
size_t limit = limits[(size_t)scale][i];
if (bytes >= limit)
{
*suffix = suffixes[(size_t)scale][i];
return bytes / (double)limit;
}
}
*suffix = "bytes";
return (double)bytes;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Options.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides a set of helper functions to manage the processing of command line arguments.
*/
#pragma once
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Namespace for the options processing helper functions. */
namespace options
{
/** The possible result codes of parsing a single option. */
enum class ParseResult
{
eSuccess, ///< Parsing was successful and the option was consumed.
eInvalidValue, ///< A token or name was expected but not found.
};
/** Type names for values passed to the parser functions. */
enum class ValueType
{
eIgnore = -1, ///< Ignore arguments of this type.
eNone, ///< No type or data.
eString, ///< Value is a string (ie: const char*).
eLong, ///< Value is a signed long integer (ie: long).
eLongLong, ///< Value is a signed long long integer (ie: long long).
eFloat, ///< Value is a single precision floating point number (ie: float).
eDouble, ///< Value is a double precision floating point number (ie: double).
};
/** Special failure value for getArgString() indicating that an expected argument was missing. */
constexpr int kArgFailExpectedArgument = -1;
/** Special failure value for getArgString() indicating that an argument's value started with
* a single or double quotation mark but did not end with the matching quotation or the ending
* quotation mark was missing.
*/
constexpr int kArgFailExpectedQuote = -2;
/** Converts a string to a number.
*
* @param[in] string The string to convert.
* @param[out] value Receives the converted value of the string if successful.
* @returns `true` if the string is successfully converted to a number.
* @returns `false` if the string could not be fully converted to a number.
*/
template <typename T>
inline bool stringToNumber(const char* string, T* value)
{
char* endp = nullptr;
*value = strtoull(string, &endp, 10);
return endp == nullptr || endp[0] == 0;
}
/** @copydoc stringToNumber(const char*,T*) */
template <>
inline bool stringToNumber(const char* string, long* value)
{
char* endp = nullptr;
*value = strtol(string, &endp, 10);
return endp == nullptr || endp[0] == 0;
}
/** @copydoc stringToNumber(const char*,T*) */
template <>
inline bool stringToNumber(const char* string, float* value)
{
char* endp = nullptr;
*value = strtof(string, &endp);
return endp == nullptr || endp[0] == 0;
}
/** @copydoc stringToNumber(const char*,T*) */
template <>
inline bool stringToNumber(const char* string, double* value)
{
char* endp = nullptr;
*value = strtod(string, &endp);
return endp == nullptr || endp[0] == 0;
}
/** A multi-value type. This contains a single value of a specific type. The
* value can only be retrieved if it can be safely converted to the requested
* type.
*/
class Value
{
public:
/** Constructor: initializes an object with no specific value in it. */
Value()
{
clear();
}
/** Clears the value in this object.
*
* @returns No return value.
*/
void clear()
{
m_type = ValueType::eNone;
m_value.string = nullptr;
}
/** Sets the value and type in this object.
*
* @param[in] value The value to set in this object. The value's type is implied
* from the setter that is used.
* @returns No return value.
*/
void set(const char* value)
{
m_type = ValueType::eString;
m_value.string = value;
}
/** @copydoc set(const char*) */
void set(long value)
{
m_type = ValueType::eLong;
m_value.integer = value;
}
/** @copydoc set(const char*) */
void set(long long value)
{
m_type = ValueType::eLongLong;
m_value.longInteger = value;
}
/** @copydoc set(const char*) */
void set(float value)
{
m_type = ValueType::eFloat;
m_value.floatValue = value;
}
/** @copydoc set(const char*) */
void set(double value)
{
m_type = ValueType::eDouble;
m_value.doubleValue = value;
}
/** Retrieves the type of the value in this object.
*
* @returns A type name for the value in this object.
*/
ValueType getType() const
{
return m_type;
}
/** Retrieves the value in this object.
*
* @returns The value converted into the requested format if possible.
*/
const char* getString() const
{
if (m_type != ValueType::eString)
return nullptr;
return m_value.string;
}
/** @copydoc getString() */
long getLong() const
{
return getNumber<long>();
}
/** @copydoc getString() */
long long getLongLong() const
{
return getNumber<long long>();
}
/** @copydoc getString() */
float getFloat() const
{
return getNumber<float>();
}
/** @copydoc getString() */
double getDouble() const
{
return getNumber<double>();
}
private:
template <typename T>
T getNumber() const
{
switch (m_type)
{
default:
case ValueType::eString:
return 0;
case ValueType::eLong:
return static_cast<T>(m_value.integer);
case ValueType::eLongLong:
return static_cast<T>(m_value.longInteger);
case ValueType::eFloat:
return static_cast<T>(m_value.floatValue);
case ValueType::eDouble:
return static_cast<T>(m_value.doubleValue);
}
}
ValueType m_type; ///< The type of the value in this object.
/** The value contained in this object. */
union
{
const char* string;
long integer;
long long longInteger;
float floatValue;
double doubleValue;
} m_value;
};
/** Receives the results of parsing an options string. This represents the base class that
* specific option parsers should inherit from.
*/
class Options
{
public:
/** The original argument count from the caller. */
int argc = 0;
/** The original argument list from the caller. */
char** argv = nullptr;
/** The index of the first argument that was not consumed as a parsed option. */
int firstCommandArgument = -1;
/** Helper function to cast the @a args parameter to a parser function.
*
* @returns This object cast to the requested type.
*/
template <typename T>
T* cast()
{
return reinterpret_cast<T*>(this);
}
};
/** Prototype of a parser function to handle a single option.
*
* @param[in] name The name of the option being parsed. If the name and value was in a
* pair separated by an equal sign ('='), both the name and value will
* be present in the string. This will not be `nullptr`.
* @param[in] value The value of the option if one is expected, or `nullptr` if no option
* is expected. This will be the value to be passed in with the option.
* @param[out] args Receives the results of parsing the option. It is the handler's
* responsibility to ensure this object is filled in or initialized
* properly.
* @returns A @ref ParseResult result code indicating whether the parsing was successful.
*/
using ArgParserFunc = ParseResult (*)(const char* name, const Value* value, Options* args);
/** Information about a single option and its parser. */
struct Option
{
/** The short name for the option. This is usually a one letter option preceded by
* a dash character.
*/
const char* shortName;
/** The long name for the option. This is usually a multi-word option preceded by
* two dash characters.
*/
const char* longName;
/** The number of arguments to be expected associated with this option. This should
* either be 0 or 1.
*/
int expectedArgs;
/** The expected argument type. */
ValueType expectedType;
/** The parser function that will handle consuming the option and its argument. */
ArgParserFunc parser;
/** Documentation for this option. This string should be formatted to fit on a 72
* character line. Each line of text should end with a newline character ('\n').
* The last line of text must also end in a newline character otherwise it will
* be omitted from any documentation output.
*/
const char* documentation;
};
/** Retrieves a single argument value from the next argument.
*
* @param[in] argc The number of arguments in the argument vector. This must be at least 1.
* @param[in] argv The full argument vector to parse. This may not be `nullptr`.
* @param[in] argIndex The zero-based index of the argument to parse.
* @param[out] value Receives the start of the value's string.
* @returns The number of arguments that were consumed. This may be 0 or 1.
* @returns `-1` if no value could be found for the option.
*
* @remarks This parses a single option's value from the argument list. The value may either
* be in the same argument as the option name itself, separated by an equal sign ('='),
* or in the following argument in the list. If an argument cannot be found (ie:
* no arguments remain and an equal sign is not found), this will fail.
*
* @note If the argument's value is quoted (single or double quotes), the entry in the original
* argument string will be modified to strip off the terminating quotation mark character.
* If the argument's value is not quoted, nothing will be modified in the argument string.
*/
inline int getArgString(int argc, char** argv, int argIndex, const char** value)
{
char* equal;
int argsConsumed = 0;
char* valueOut;
equal = strchr(argv[argIndex], '=');
// the argument is of the form "name=value" => parse the number from the arg itself.
if (equal != nullptr)
valueOut = equal + 1;
// the argument is of the form "name value" => parse the number from the next arg.
else if (argIndex + 1 < argc)
{
valueOut = argv[argIndex + 1];
argsConsumed = 1;
}
// not enough args given => fail.
else
{
fprintf(stderr, "expected another argument after '%s'.\n", argv[argIndex]);
return kArgFailExpectedArgument;
}
if (valueOut[0] == '\"' || valueOut[0] == '\'')
{
char openQuote = valueOut[0];
size_t len = strlen(valueOut);
if (valueOut[len - 1] != openQuote)
return kArgFailExpectedQuote;
valueOut[len - 1] = 0;
valueOut++;
}
*value = valueOut;
return argsConsumed;
}
/** Parses a set of options from an argument vector.
*
* @param[in] supportedArgs The table of options that will be used to parse the program
* arguments. This table must be terminated by an empty entry
* in the list (ie: all values `nullptr` or `0`). This may not
* be `nullptr`.
* @param[in] argc The argument count for the program. This must be at least 1.
* @param[in] argv The vector of arguments to e be parsed. This must not be `nullptr`.
* @param[out] args Receives the parsed option state. It is the caller's
* responsibility to ensure this is appropriately initialized before
* calling. This object must inherit from the @ref Options class.
* @returns `true` if all arguments are successfully parsed.
* @returns `false` if an option fails to be parsed.
*/
inline bool parseOptions(const Option* supportedArgs, int argc, char** argv, Options* args)
{
const char* valueStr;
bool handled;
int argsConsumed;
ParseResult result;
Value value;
Value* valueToSend;
auto argMatches = [](const char* string, const char* arg, bool terminated) {
size_t len = strlen(arg);
if (!terminated)
return strncmp(string, arg, len) == 0;
return strncmp(string, arg, len) == 0 && (string[len] == 0 || string[len] == '=');
};
for (int i = 1; i < argc; i++)
{
handled = false;
for (size_t j = 0; supportedArgs[j].parser != nullptr; j++)
{
bool checkTermination = supportedArgs[j].expectedType != ValueType::eIgnore;
if ((supportedArgs[j].shortName != nullptr &&
argMatches(argv[i], supportedArgs[j].shortName, checkTermination)) ||
(supportedArgs[j].longName != nullptr && argMatches(argv[i], supportedArgs[j].longName, checkTermination)))
{
valueToSend = nullptr;
valueStr = nullptr;
argsConsumed = 0;
value.clear();
if (supportedArgs[j].expectedArgs > 0)
{
argsConsumed = getArgString(argc, argv, i, &valueStr);
if (argsConsumed < 0)
{
switch (argsConsumed)
{
case kArgFailExpectedArgument:
fprintf(
stderr, "ERROR-> expected an extra argument after argument %d ('%s').", i, argv[i]);
break;
case kArgFailExpectedQuote:
fprintf(
stderr,
"ERROR-> expected a matching quotation mark at the end of the argument value for argument %d ('%s').",
i, argv[i]);
break;
default:
break;
}
return false;
}
if (supportedArgs[j].expectedType == ValueType::eIgnore)
{
i += argsConsumed;
handled = true;
break;
}
#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
# define SETVALUE(value, str, type) \
do \
{ \
type convertedValue; \
if (!stringToNumber(str, &convertedValue)) \
{ \
fprintf(stderr, "ERROR-> expected a %s value after '%s'.\n", #type, argv[i]); \
return false; \
} \
value.set(convertedValue); \
} while (0)
#endif
switch (supportedArgs[j].expectedType)
{
default:
case ValueType::eString:
value.set(valueStr);
break;
case ValueType::eLong:
SETVALUE(value, valueStr, long);
break;
case ValueType::eLongLong:
SETVALUE(value, valueStr, long long);
break;
case ValueType::eFloat:
SETVALUE(value, valueStr, float);
break;
case ValueType::eDouble:
SETVALUE(value, valueStr, double);
break;
}
valueToSend = &value;
#undef SETVALUE
}
result = supportedArgs[j].parser(argv[i], valueToSend, args);
switch (result)
{
default:
case ParseResult::eSuccess:
break;
case ParseResult::eInvalidValue:
fprintf(stderr, "ERROR-> unknown or invalid value in '%s'.\n", argv[i]);
return false;
}
i += argsConsumed;
handled = true;
break;
}
}
if (!handled)
{
if (args->firstCommandArgument < 0)
args->firstCommandArgument = i;
break;
}
}
args->argc = argc;
args->argv = argv;
return true;
}
/** Prints out the documentation for an option table.
*
* @param[in] supportedArgs The table of options that this program can parse. This table
* must be terminated by an empty entry in the list (ie: all values
* `nullptr` or `0`). This may not be nullptr. The documentation
* for each of the options in this table will be written out to the
* selected stream.
* @param[in] helpString The help string describing this program, its command line
* syntax, and its commands. This should not include any
* documentation for the supported options.
* @param[in] stream The stream to output the documentation to. This may not be
* `nullptr`.
* @returns No return value.
*/
inline void printOptionUsage(const Option* supportedArgs, const char* helpString, FILE* stream)
{
const char* str;
const char* newline;
const char* argStr;
fputs(helpString, stream);
fputs("Supported options:\n", stream);
for (size_t i = 0; supportedArgs[i].parser != nullptr; i++)
{
str = supportedArgs[i].documentation;
argStr = "";
if (supportedArgs[i].expectedArgs > 0)
argStr = " [value]";
if (supportedArgs[i].shortName != nullptr)
fprintf(stream, " %s%s:\n", supportedArgs[i].shortName, argStr);
if (supportedArgs[i].longName != nullptr)
fprintf(stream, " %s%s:\n", supportedArgs[i].longName, argStr);
for (newline = strchr(str, '\n'); newline != nullptr; str = newline + 1, newline = strchr(str + 1, '\n'))
fprintf(stream, " %.*s\n", static_cast<int>(newline - str), str);
fputs("\n", stream);
}
fputs("\n", stream);
}
} // namespace options
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Library.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides helper functions to handle library loading and management.
*/
#pragma once
#include "../Defines.h"
#include "Path.h"
#include "StringSafe.h"
#include "../../omni/extras/ScratchBuffer.h"
#if CARB_POSIX
# if CARB_PLATFORM_LINUX
# include <link.h>
# elif CARB_PLATFORM_MACOS
# include <mach-o/dyld.h>
# endif
# include <dlfcn.h>
#elif CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
# include "Errors.h"
# include "WindowsPath.h"
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
/** Handle to a loaded library. */
#if CARB_POSIX || defined(DOXYGEN_BUILD)
//! A type representing a library handle.
using LibraryHandle = void*;
#elif CARB_PLATFORM_WINDOWS
using LibraryHandle = HMODULE;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
/** A value representing an invalid library handle. */
constexpr LibraryHandle kInvalidLibraryHandle = {};
/** Base type for the flags to control how libraries are loaded. */
using LibraryFlags = uint32_t;
/** Flag to indicate that only the module's base name was given and that the full name should
* be constructed using createLibraryNameForModule() before attempting to load the library.
* When this flag is used, it is assumed that neither the library's prefix (if any) nor
* file extension are present in the given filename. Path components leading up to the
* module name may be included as needed. This flag is ignored if the filename is either
* `nullptr` or an empty string (ie: "").
*/
constexpr LibraryFlags fLibFlagMakeFullLibName = 0x00000001;
/** Flag to indicate that the library should be fully loaded and linked immediately. This
* flag has no effect on Windows since it doesn't have the equivalent of Linux's lazy linker.
* This is equivalent to passing the `RTLD_NOW` flag to [dlopen](https://linux.die.net/man/3/dlopen) and will override
* any default lazy linking behavior.
*/
constexpr LibraryFlags fLibFlagNow = 0x00000002;
/** Flag to indicate that the symbols in the library being loaded should be linked to first
* and take precedence over global scope symbols of the same name from other libraries. This
* is only available on Linux and is ignored on other platforms. This is equivalent to passing
* the `RTLD_DEEPBIND` flag to [dlopen](https://linux.die.net/man/3/dlopen) on Linux.
*/
constexpr LibraryFlags fLibFlagDeepBind = 0x00000004;
/** Flag to indicate that a valid library handle should only be returned if the requested library
* was already loaded into the process. If the library was not already loaded in the process
* the call to loadLibrary() will fail and `nullptr` will be returned instead. When this flag
* is used, the returned handle (if found and non-nullptr) will always have its reference count
* incremented. The returned handle must still be passed to unloadLibrary() to ensure its
* reference is cleaned up when the handle is no longer needed.
*/
constexpr LibraryFlags fLibFlagLoadExisting = 0x00000008;
#if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD)
/** The default library file extension for the current platform.
* This string will always begin with a dot ('.').
* The extension will always be lower case.
* This version is provided as a macro so it can be added to string literals.
*/
# define CARB_LIBRARY_EXTENSION ".dll"
/** The default executable file extension for the current platform.
* This string will always begin with a dot ('.') where it is not an
* empty string. The extension will always be lower case. This is
* provided as a macro so it can be added to string literals.
*/
# define CARB_EXECUTABLE_EXTENSION ".exe"
#elif CARB_PLATFORM_LINUX
# define CARB_LIBRARY_EXTENSION ".so"
# define CARB_EXECUTABLE_EXTENSION ""
#elif CARB_PLATFORM_MACOS
# define CARB_LIBRARY_EXTENSION ".dylib"
# define CARB_EXECUTABLE_EXTENSION ""
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
/** Retrieves the default library file extension for the current platform.
*
* @returns The default library file extension for the platform. This string will always
* begin with a dot ('.'). The extension will always be lower case.
*/
constexpr const char* getDefaultLibraryExtension()
{
return CARB_LIBRARY_EXTENSION;
}
/** Retrieves the default library file prefix for the current platform.
* The prefix will always be lower case.
* This version is provided as a macro so it can be added to string literals.
*/
#if CARB_PLATFORM_WINDOWS
# define CARB_LIBRARY_PREFIX ""
#elif CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS
# define CARB_LIBRARY_PREFIX "lib"
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
/** Retrieves the default library file prefix for the current platform.
*
* @returns The default library file prefix for the platform. The prefix will always be
* lower case.
*/
constexpr const char* getDefaultLibraryPrefix()
{
return CARB_LIBRARY_PREFIX;
}
/** A macro to build a library file's name as a string literal.
* @param name A string literal name for the library.
*
* @remarks This will build the full platform-specific library file name;
* for example "carb" will be built into "carb.dll" on Windows,
* "libcarb.so" on Linux, etc.
*/
#define CARB_LIBRARY_GET_LITERAL_NAME(name) CARB_LIBRARY_PREFIX name CARB_LIBRARY_EXTENSION
/** Creates a full library name from a module's base name.
*
* @param[in] baseName The base name of the module to create the library name for. This
* base name should not include the file extension (ie: ".dll" or ".so")
* and should not include any prefix (ie: "lib"). Path components may be
* included and will also be present in the created filename. This must
* not be `nullptr`.
* @returns The name to use to load the named module on the current platform. This will neither
* check for the existence of the named module nor will it verify that a prefix or
* file extension already exists in the base name.
*/
inline std::string createLibraryNameForModule(const char* baseName)
{
const char* prefix;
const char* ext;
char* buffer;
size_t len = 0;
size_t pathLen = 0;
const char* sep[2] = {};
const char* name = baseName;
if (baseName == nullptr || baseName[0] == 0)
return {};
sep[0] = strrchr(baseName, '/');
#if CARB_PLATFORM_WINDOWS
// also handle mixed path separators on Windows.
sep[1] = strrchr(baseName, '\\');
if (sep[1] > sep[0])
sep[0] = sep[1];
#endif
if (sep[0] != nullptr)
{
pathLen = (sep[0] - baseName) + 1;
name = sep[0] + 1;
len += pathLen;
}
prefix = getDefaultLibraryPrefix();
ext = getDefaultLibraryExtension();
len += strlen(prefix) + strlen(ext);
len += strlen(name) + 1;
buffer = CARB_STACK_ALLOC(char, len);
carb::extras::formatString(buffer, len, "%.*s%s%s%s", (int)pathLen, baseName, prefix, name, ext);
return buffer;
}
/** Attempts to retrieve the address of a symbol from a loaded module.
*
* @param[in] libHandle The library to retrieve the symbol from. This should be a handle
* previously returned by loadLibrary().
* @param[in] name The name of the symbol to retrieve the address of. This must exactly
* match the module's exported name for the symbol including case.
* @returns The address of the loaded symbol if successfully found in the requested module.
* @returns `nullptr` if the symbol was not found in the requested module.
*
* @note The @p libHandle parameter may also be `nullptr` to achieve some special behavior when
* searching for symbols. However, note that this special behavior differs between
* Windows and Linux. On Windows, passing `nullptr` for the library handle will search
* for the symbol in the process's main module only. Since most main executable modules
* don't export anything, this is likely to return `nullptr`. On Linux however, passing
* `nullptr` for the library handle will search the process's entire symbol space starting
* from the main executable module.
*
* @note Calling this on Linux with the handle of a library that has been unloaded from memory
* is considered undefined behavior. It is the caller's responsibility to ensure the
* library handle is valid before attempting to call this. On Windows, passing in an
* invalid library handle will technically fail gracefully, however it is still considered
* undefined behavior since another library could be reloaded into the same space in
* memory at a later time.
*/
template <typename T>
T getLibrarySymbol(LibraryHandle libHandle, const char* name)
{
#if CARB_PLATFORM_WINDOWS
return reinterpret_cast<T>(::GetProcAddress(libHandle, name));
#elif CARB_POSIX
if (libHandle == nullptr || name == nullptr)
return nullptr;
return reinterpret_cast<T>(::dlsym(libHandle, name));
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
std::string getLibraryFilenameByHandle(LibraryHandle handle); // forward declare
#ifndef DOXYGEN_BUILD
namespace detail
{
struct FreeString
{
void operator()(char* p) noexcept
{
free(p);
}
};
using UniqueCharPtr = std::unique_ptr<char, FreeString>;
# if CARB_POSIX
struct FreePosixLib
{
void operator()(void* p) noexcept
{
dlclose(p);
}
};
using UniquePosixLib = std::unique_ptr<void, FreePosixLib>;
# endif
} // namespace detail
#endif
// clang-format off
/** Attempts to load a named library into the calling process.
*
* This attempts to dynamically load a named library into the calling process. If the library is already loaded, the
* reference count of the library is increased and a handle to it is returned. If the library was not already loaded,
* it is dynamically loaded and a handle to it is returned; its reference count will be one. Each call to this function
* should be balanced by a call to \ref unloadLibrary() when the library is no longer needed.
*
* Libraries that were loaded as part of the process's dependencies list will be 'pinned' and their reference count will
* not be changed by attempting to load them. It is still safe to \ref unloadLibrary() on handles for those libraries.
*
* \par Windows
* This function calls [LoadLibraryEx](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw)
* with `LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR` and `LOAD_LIBRARY_SEARCH_DEFAULT_DIRS` to load libraries. If this fails,
* the default search path is instead used. If `ERROR_FILENAME_EXCED_RANGE` is returned, the `LoadLibraryEx` call is
* repeated with the filepath preceded with a prefix to disable string parsing. If the module or a dependent module is
* not found, `GetLastError()` typically reports `ERROR_MOD_NOT_FOUND`. In order to determine which DLL library is
* missing there are a few options:
* * Enable [Show Loader Snaps](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/show-loader-snaps)
* with the *gflags* tool, which is available with
* [Debugging Tools for Windows](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools).
* Running the process in a debugger or with access to debug output will then show log messages from the Windows
* loader.
* * The same debug output can be enabled by setting the 32-bit value at `ntdll.dll!LdrpDebugFlags` to `0x1`. This
* value must be accessed in a debugger with symbols for *ntdll.dll*.
* * Alternately using a modern [Dependencies tool](https://github.com/lucasg/Dependencies) will reveal missing
* dependencies for a library without a debugger, although it may not show the actual error that led to `loadLibrary`
* failing.
*
* \par Linux
* This function calls [dlopen](https://linux.die.net/man/3/dlopen) with the `RTLD_LAZY` flag (or `RTLD_NOW` if
* \ref fLibFlagNow is specified). If \ref fLibFlagDeepBind is specified, `RTLD_DEEPBIND` is also used. It is possible
* for the underlying `dlopen()` call to succeed without a dependent library able to load. In this case, the dynamic
* loader destroys the link map, so symbol lookup on the module will fail. This condition is detected and treated as an
* error condition. To have dynamic loader debug output displayed, use the [LD_DEBUG](https://linux.die.net/man/8/ld.so)
* environment variable set to a value such as `files`, `libs` or `all`. Typically the output is printed to *stdout*,
* but the `LD_DEBUG_OUTPUT` can be set to the name of a file to instead log to the file. The
* [ldd](https://linux.die.net/man/1/ldd) command-line tool can be used to print the dependent libraries required by
* an executable or library.
*
* \par MacOS
* This function calls `dlopen` with the `RTLD_LAZY` flag (or `RTLD_NOW` if \ref fLibFlagNow is specified). To have the
* dynamic loader debug output displayed, use the [DYLD_PRINT_LIBRARIES](https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/LoggingDynamicLoaderEvents.html)
* environment variable. The `otool` command-line tool with the `-L` option will print out the dependent libraries
* required by an executable or library.
*
* \par MacOS
* If the requested library name is `nullptr`, the expectation from the caller is that the handle to the process'
* main executable image will be returned. Unfortunately on MacOS, the `RTLD_DEFAULT` symbol is returned instead
* as a pseudo-handle to the main executable module. This is valid to pass to other functions such as
* getLibrarySymbol() and getLibraryFilenameByHandle() however.
*
* @note A library may fail to load because of a dependent library, but the error message may seem like the *requested*
* library is causing the failure.
*
* @param[in] libraryName The name of the library to attempt to load. This may be either a
* relative or absolute path name. This should be a UTF-8 encoded
* path. If the @ref fLibFlagMakeFullLibName flag is used, the library
* name may omit any platform specific prefix or file extension. The
* appropriate platform specific name will be generated internally
* using createLibraryNameForModule(). If `nullptr` is provided, the executable module is
* retrieved instead. On Windows this handle need not be closed with \ref unloadLibrary() as
* it does not increment the reference count, but on MacOSX and Linux it increments the
* reference count and should therefore be passed to \ref unloadLibrary().
* @param[in] flags Flags to control the behavior of the operation. This defaults to 0.
* @returns A handle to the library if it was already loaded in the process. This handle should
* be cleaned up by unloadLibrary() when it is no longer necessary. `nullptr` is returned if the library
* could not be found, or loading fails for some reason (use \ref getLastLoadLibraryError()).
*/
// clang-format on
inline LibraryHandle loadLibrary(const char* libraryName, LibraryFlags flags = 0)
{
std::string fullLibName;
LibraryHandle handle;
// asked to construct a full library name => create the name and adjust the path as needed.
if (libraryName != nullptr && libraryName[0] != '\0' && (flags & fLibFlagMakeFullLibName) != 0)
{
fullLibName = createLibraryNameForModule(libraryName);
libraryName = fullLibName.c_str();
}
#if CARB_PLATFORM_WINDOWS
// retrieve the main executable module's handle.
if (libraryName == nullptr)
return ::GetModuleHandleW(nullptr);
// retrieve the handle of a specific module.
std::wstring widecharName = carb::extras::convertCarboniteToWindowsPath(libraryName);
// asked to only retrieve a library handle if it is already loaded. Note that this will
// still increment the library's ref count on return (unless it is pinned). It is always
// safe to call unloadLibrary() on the returned (non-nullptr) handle in this case.
if ((flags & fLibFlagLoadExisting) != 0)
{
return ::GetModuleHandleExW(0, widecharName.c_str(), &handle) ? handle : nullptr;
}
handle = ::LoadLibraryExW(widecharName.c_str(), nullptr,
CARBWIN_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
// Although convertCarboniteToWindowsPath will ensure that a path over MAX_PATH has the long-path prefix,
// LoadLibraryExW complains about strings slightly smaller than that. If we get that specific error then try
// again with the long-path prefix.
if (!handle && ::GetLastError() == CARBWIN_ERROR_FILENAME_EXCED_RANGE)
{
handle = ::LoadLibraryExW((L"\\\\?\\" + widecharName).c_str(), nullptr,
CARBWIN_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
}
// failed to load the loading the module from the 'default search dirs' => attempt to load
// it with the default system search path. Oddly enough, this is different from the search
// path provided by the flags used above - it includes the current working directory and
// the paths in $PATH. Another possible reason for the above failing is that the library
// name was a relative path. The CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS flag used above
// requires that an absolute path be used. To keep the behavior of this function on par
// with Linux's behavior, we'll attempt another load from the default paths instead.
if (handle == nullptr)
{
handle = ::LoadLibraryExW(widecharName.c_str(), nullptr, 0);
// As above, try again with the long-path prefix if we get a specific error response from LoadLibrary.
if (!handle && ::GetLastError() == CARBWIN_ERROR_FILENAME_EXCED_RANGE)
{
handle = ::LoadLibraryExW((L"\\\\?\\" + widecharName).c_str(), nullptr, 0);
}
}
#elif CARB_POSIX
int openFlags = RTLD_LAZY;
if ((flags & fLibFlagNow) != 0)
openFlags |= RTLD_NOW;
if ((flags & fLibFlagLoadExisting) != 0)
openFlags |= RTLD_NOLOAD;
# if CARB_PLATFORM_LINUX
if ((flags & fLibFlagDeepBind) != 0)
openFlags |= RTLD_DEEPBIND;
# endif
handle = dlopen(libraryName, openFlags);
// failed to get a module handle or load the module => check if this was a request to load the
// handle for the main executable module by its path name.
if (handle == nullptr && libraryName != nullptr && libraryName[0] != 0)
{
detail::UniqueCharPtr path(realpath(libraryName, nullptr));
if (path == nullptr)
{
// probably trying to load a library that doesn't exist
CARB_LOG_INFO("realpath(%s) failed (errno = %d)", libraryName, errno);
return nullptr;
}
std::string raw = getLibraryFilenameByHandle(nullptr);
CARB_FATAL_UNLESS(!raw.empty(), "getLibraryFilenameByHandle(nullptr) failed");
// use realpath() to ensure the paths can be compared
detail::UniqueCharPtr path2(realpath(raw.c_str(), nullptr));
CARB_FATAL_UNLESS(path2 != nullptr, "realpath(%s) failed (errno = %d)", raw.c_str(), errno);
// the two names match => retrieve the main executable module's handle for return.
if (strcmp(path.get(), path2.get()) == 0)
{
return dlopen(nullptr, openFlags);
}
}
# if CARB_PLATFORM_LINUX
if (handle != nullptr)
{
// Linux's dlopen() has a strange issue where it's possible to have the call succeed
// even though one or more of the library's dependencies fail to load. The dlopen()
// call succeeds because there are still references on the handle despite the module's
// link map having been destroyed (visible from the 'LD_DEBUG=all' output).
// Unfortunately, if the link map is destroyed, any attempt to retrieve a symbol from
// the library with dlsym() will fail. This causes some very confusing and misleading
// error messages or crashes (depending on usage) instead of just having the module load
// fail.
void* linkMap = nullptr;
const char* errorMsg = dlerror();
if (dlinfo(handle, RTLD_DI_LINKMAP, &linkMap) == -1 || linkMap == nullptr)
{
CARB_LOG_WARN("Library '%s' loaded with errors '%s' and no link map. The likely cause of this is that ",
libraryName, errorMsg);
CARB_LOG_WARN("a dependent library or symbol in the dependency chain is missing. Use the environment ");
CARB_LOG_WARN("variable 'LD_DEBUG=all' to diagnose.");
// close the bad library handle. Note that this may not actually unload the bad
// library since it may still have multiple references on it (part of the failure
// reason). However, we can only safely clean up one reference here.
dlclose(handle);
return nullptr;
}
}
# endif
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
return handle;
}
/** Retrieves a string explaining the most recent library load failure cause.
*
* @returns A string containing a message explaining the most recent failure from loadLibrary().
*/
inline std::string getLastLoadLibraryError()
{
#if CARB_PLATFORM_WINDOWS
return carb::extras::getLastWinApiErrorMessage();
#else
return dlerror();
#endif
}
/** Unloads a loaded library.
*
* @param[in] libraryHandle The handle to the library to unload. This should have been
* returned by a previous call to loadLibrary(). This may not be
* `nullptr`.
* @returns No return value.
*
* @remarks This unloads one reference to a library that was loaded by loadLibrary(). Note that
* this may not actually unload the library from the process if other references to it
* still exist. When the last reference to an unpinned library is removed, that library
* will be removed from the process's memory space.
*
* @note Once a library has been unloaded from memory, the handle to it cannot be safely used
* any more. Attempting to use it may result in undefined behavior. Effectively, as
* soon as a handle is passed in here, it should be discarded. Even though the module may
* remain in memory, the handle should be treated as though it has been freed upon return
* from here.
*/
inline void unloadLibrary(LibraryHandle libraryHandle)
{
if (libraryHandle)
{
#if CARB_PLATFORM_WINDOWS
if (!::FreeLibrary(libraryHandle))
{
DWORD err = ::GetLastError();
CARB_LOG_WARN("FreeLibrary for handle %p failed with error: %d/%s", libraryHandle, err,
convertWinApiErrorCodeToMessage(err).c_str());
}
#elif CARB_POSIX
if (::dlclose(libraryHandle) != 0)
{
CARB_LOG_WARN("Closing library handle %p failed with error: %s", libraryHandle, dlerror());
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
}
/** Attempts to retrieve a library's handle by its filename.
*
* @warning This function does not increment a library's reference count, so it is possible (though unlikely) that
* another thread could be unloading the library and the handle returned from this function is invalid. Only use this
* function for debugging, or when you know that the returned handle will still be valid.
*
* @thread_safety This function is safe to call simultaneously from multiple threads, but only as long as another thread
* is not attempting to unload the library found by this function.
*
* @param[in] libraryName The name of the library to retrieve the handle for. This may either
* be the full path for the module or just its base filename. This may
* be `nullptr` to retrieve the handle for the main executable module
* for the calling process. If the @ref fLibFlagMakeFullLibName flag is
* used, the library name may omit any platform specific prefix or file
* extension. The appropriate platform specific name will be generated
* internally using createLibraryNameForModule().
* @param[in] flags Flags to control the behavior of the operation. This defaults to 0.
* @returns The handle to the requested library if it is already loaded in the process. Returns
* `nullptr` if the library is not loaded. This will not load the library if it is not
* already present in the process. This can be used to test if a library is already
* loaded.
*/
inline LibraryHandle getLibraryHandleByFilename(const char* libraryName, LibraryFlags flags = 0)
{
std::string fullLibName;
if (libraryName != nullptr && libraryName[0] != '\0' && (flags & fLibFlagMakeFullLibName) != 0)
{
fullLibName = createLibraryNameForModule(libraryName);
libraryName = fullLibName.c_str();
}
#if CARB_PLATFORM_WINDOWS
if (libraryName == nullptr)
return ::GetModuleHandleW(nullptr);
std::wstring wideCharName = carb::extras::convertCarboniteToWindowsPath(libraryName);
return GetModuleHandleW(wideCharName.c_str());
#else
if (libraryName != nullptr && libraryName[0] == 0)
return nullptr;
// A successful dlopen() with RTLD_NOLOAD increments the reference count, so we dlclose() it to make sure that
// the reference count stays the same. This function is inherently racy as another thread could be unloading the
// library while we're trying to load it.
// Note that we can't use UniquePosixLib here because it causes clang to think that we're returning a freed
// pointer.
void* handle = ::dlopen(libraryName, RTLD_LAZY | RTLD_NOLOAD);
if (handle != nullptr) // dlclose(nullptr) crashes
{
dlclose(handle);
}
return handle;
#endif
}
/** Retrieves the path for a loaded library from its handle.
*
* @param[in] handle The handle to the library to retrieve the name for. This may be `nullptr`
* to retrieve the filename of the main executable module for the process.
* @returns A string containing the full path to the requested library.
* @returns An empty string if the module handle was invalid or the library is no longer loaded
* in the process.
*/
inline std::string getLibraryFilenameByHandle(LibraryHandle handle)
{
#if CARB_PLATFORM_WINDOWS
omni::extras::ScratchBuffer<wchar_t, CARBWIN_MAX_PATH> path;
// There's no way to verify the correct length, so we'll just double the buffer
// size every attempt until it fits.
for (;;)
{
DWORD res = GetModuleFileNameW(handle, path.data(), DWORD(path.size()));
if (res == 0)
{
// CARB_LOG_ERROR("GetModuleFileNameW(%p) failed (%d)", handle, GetLastError());
return "";
}
if (res < path.size())
{
break;
}
bool suc = path.resize(path.size() * 2);
OMNI_FATAL_UNLESS(suc, "failed to allocate %zu bytes", path.size() * 2);
}
return carb::extras::convertWindowsToCarbonitePath(path.data());
#elif CARB_PLATFORM_LINUX
struct link_map* map;
// requested the filename for the main executable module => dlinfo() will succeed on this case
// but will give an empty string for the path. To work around this, we'll simply read the
// path to the process's executable symlink.
if (handle == nullptr)
{
detail::UniqueCharPtr path(realpath("/proc/self/exe", nullptr));
CARB_FATAL_UNLESS(path != nullptr, "calling realpath(\"/proc/self/exe\") failed (%d)", errno);
return path.get();
}
int res = dlinfo(handle, RTLD_DI_LINKMAP, &map);
if (res != 0)
{
// CARB_LOG_ERROR("failed to retrieve the link map from library handle %p (%d)", handle, errno);
return "";
}
// for some reason, the link map doesn't provide a filename for the main executable module.
// This simply gets returned as an empty string. If we get that case, we'll try getting
// the main module's filename instead.
if (!map->l_name || map->l_name[0] == '\0')
{
// first make sure the handle passed in is for our main executable module.
auto binaryHandle = loadLibrary(nullptr);
if (binaryHandle)
{
unloadLibrary(binaryHandle);
}
if (binaryHandle != handle)
{
// CARB_LOG_ERROR("library had no filename in the link map but was not the main module");
return {};
}
// recursively call to get the main module's name
return getLibraryFilenameByHandle(nullptr);
}
return map->l_name;
#elif CARB_PLATFORM_MACOS
// dlopen(nullptr) gives a different (non-null) result than dlopen(path_to_exe), so
// we need to test against it as well.
if (handle == nullptr || detail::UniquePosixLib{ dlopen(nullptr, RTLD_LAZY | RTLD_NOLOAD) }.get() == handle)
{
omni::extras::ScratchBuffer<char, 4096> buffer;
uint32_t len = buffer.size();
int res = _NSGetExecutablePath(buffer.data(), &len);
if (res != 0)
{
bool succ = buffer.resize(len);
CARB_FATAL_UNLESS(succ, "failed to allocate %" PRIu32 " bytes", len);
res = _NSGetExecutablePath(buffer.data(), &len);
CARB_FATAL_UNLESS(res != 0, "_NSGetExecutablePath() failed");
}
detail::UniqueCharPtr path(realpath(buffer.data(), nullptr));
CARB_FATAL_UNLESS(path != nullptr, "realpath(%s) failed (errno = %d)", buffer.data(), errno);
return path.get();
}
// Look through all the currently loaded libraries for the our handle.
for (uint32_t i = 0;; i++)
{
const char* name = _dyld_get_image_name(i);
if (name == nullptr)
{
break;
}
// RTLD_NOLOAD is passed to avoid unnecessarily loading a library if it happened to be unloaded concurrently
// with this call. UniquePosixLib is used to release the reference that dlopen adds if successful.
if (detail::UniquePosixLib{ dlopen(name, RTLD_LAZY | RTLD_NOLOAD) }.get() == handle)
{
return name;
}
}
return {};
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/** Retrieves the path for a loaded library from an address or symbol within it.
*
* @param[in] symbolAddress The address of the symbol to find the library file name for.
* This may be a symbol returned from a previous call to
* getLibrarySymbol() or another known symbol in the library.
* This does not strictly need to be an exported symbol from the
* library, just an address within that library's memory space.
* @returns A string containing the name and path of the library that the symbol belongs to if
* found. This path components in this string will always be delimited by '/' and
* the string will always be UTF-8 encoded.
* @returns An empty string if the requested address is not a part of a loaded library.
*/
inline std::string getLibraryFilename(const void* symbolAddress)
{
#if CARB_PLATFORM_WINDOWS
HMODULE hm = NULL;
if (0 == GetModuleHandleExW(
CARBWIN_GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | CARBWIN_GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCWSTR)symbolAddress, &hm))
{
return {};
}
return getLibraryFilenameByHandle(hm);
#elif CARB_PLATFORM_LINUX
Dl_info info;
struct link_map* lm;
if (dladdr1(symbolAddress, &info, reinterpret_cast<void**>(&lm), RTLD_DL_LINKMAP))
{
if (info.dli_fname != nullptr && info.dli_fname[0] == '/')
return info.dli_fname;
else if (lm->l_name != nullptr && lm->l_name[0] == '/')
return lm->l_name;
else
{
// the main executable doesn't have a path set for it => retrieve it directly. This
// seems to be the expected behavior for the link map for the main module.
if (lm->l_name == nullptr || lm->l_name[0] == 0)
return getLibraryFilenameByHandle(nullptr);
// no info to retrieve the name from => fail.
if (info.dli_fname == nullptr || info.dli_fname[0] == 0)
return {};
// if this process was launched using a relative path, the returned name from dladdr()
// will also be a relative path => convert it to a fully qualified path before return.
// Note that for this to work properly, the working directory should not have
// changed since the process launched. This is not necessarily a valid assumption,
// but since we have no control over that behavior here, it is the best we can do.
// Note that we took all possible efforts above to minimize the cases where this
// step will be needed however.
detail::UniqueCharPtr path(realpath(info.dli_fname, nullptr));
if (path == nullptr)
return {};
return path.get();
}
}
return {};
#elif CARB_PLATFORM_MACOS
Dl_info info;
if (dladdr(symbolAddress, &info))
{
if (info.dli_fname == nullptr)
{
return getLibraryFilenameByHandle(nullptr);
}
else if (info.dli_fname[0] == '/')
{
// path is already absolute, just return it
return info.dli_fname;
}
else
{
detail::UniqueCharPtr path(realpath(info.dli_fname, nullptr));
CARB_FATAL_UNLESS(path != nullptr, "realpath(%s) failed (errno = %d)", info.dli_fname, errno);
return path.get();
}
}
return {};
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Retrieves the handle for a loaded library from an address or symbol within it.
*
* @note The library is not referenced as if @ref loadLibrary() was called for it. Do not call @ref unloadLibrary() to
* as this handle does not need to be released.
*
* @param[in] symbolAddress The address of the symbol to find the library handle for. This may be a symbol returned from
* a previous call to @ref getLibrarySymbol() or another known symbol in the library. This does not strictly need
* to be an exported symbol from the library, just an address within that library's memory space.
* @returns A @ref LibraryHandle representing the library that contains @p symbolAddress; @ref kInvalidLibraryHandle if
* the library containing the symbol could not be determined.
*/
inline LibraryHandle getLibraryHandle(const void* symbolAddress)
{
#if CARB_PLATFORM_WINDOWS
HMODULE hm = NULL;
if (0 == GetModuleHandleExW(
CARBWIN_GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | CARBWIN_GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCWSTR)symbolAddress, &hm))
{
return kInvalidLibraryHandle;
}
return hm;
#elif CARB_POSIX
std::string module = getLibraryFilename(symbolAddress);
if (!module.empty())
{
// loadLibrary increments the reference count, so decrement it immediately after.
auto handle = loadLibrary(module.c_str());
if (handle != kInvalidLibraryHandle)
{
unloadLibrary(handle);
}
return handle;
}
return kInvalidLibraryHandle;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/** Retrieves the parent directory of a library.
*
* @param[in] handle The handle to the loaded library to retrieve the directory for. This
* must be a handle that was previously returned from loadLibrary() and has
* not yet been unloaded. This may be `nullptr` to retrieve the directory of
* the process's main executable.
* @returns A string containing the name and path of the directory that contains the library
* that the symbol belongs to if found. This path components in this string will
* always be delimited by '/' and the string will always be UTF-8 encoded. The trailing
* path separator will always be removed.
* @returns An empty string if the requested address is not a part of a loaded library.
*/
inline std::string getLibraryDirectoryByHandle(LibraryHandle handle)
{
return carb::extras::getPathParent(getLibraryFilenameByHandle(handle));
}
/** Retrieves the parent directory of the library containing a given address or symbol.
*
* @param[in] symbolAddress The address of the symbol to find the library file name for.
* This may be a symbol returned from a previous call to
* getLibrarySymbol() or another known symbol in the library.
* This does not strictly need to be an exported symbol from the
* library, just an address within that library's memory space.
* @returns A string containing the name and path of the directory that contains the library
* that the symbol belongs to if found. This path components in this string will
* always be delimited by '/' and the string will always be UTF-8 encoded. The
* trailing path separator will always be removed.
* @returns An empty string if the requested address is not a part of a loaded library.
*/
inline std::string getLibraryDirectory(void* symbolAddress)
{
return carb::extras::getPathParent(getLibraryFilename(symbolAddress));
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Csv.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include <string>
#include <vector>
namespace carb
{
namespace extras
{
// These routines provide very basic non-optimal support for CSV files.
inline std::vector<std::string> fromCsvString(const char* string)
{
// The rules of CSV are pretty simple.
// ',''s '"''s and new lines should be encased in "'s
bool inQuote = false;
bool escaped = false;
std::string current;
std::vector<std::string> result;
while (*string)
{
if (escaped)
{
if (*string == 'n')
{
string += '\n';
}
current += *string;
escaped = false;
}
else if (*string == '\\')
{
escaped = true;
}
else if (inQuote)
{
if (*string == '\"')
{
if (*(string + 1) == '\"')
{
current += "\"";
string++;
}
else
{
inQuote = false;
}
}
else
{
current += *string;
}
}
else if (*string == ',')
{
result.emplace_back(std::move(current));
current.clear();
}
else
{
current += *string;
}
string++;
}
if (result.empty() && current.empty())
return result;
result.emplace_back(std::move(current));
return result;
}
inline std::string toCsvString(const std::vector<std::string>& columns)
{
std::string result;
for (size_t i = 0; i < columns.size(); i++)
{
if (i != 0)
result += ",";
auto& column = columns[i];
// Determine if the string has anything that needs escaping
bool needsEscaping = false;
for (auto c : column)
{
if (c == '\n' || c == '"' || c == ',')
{
needsEscaping = true;
}
}
if (!needsEscaping)
{
result += column;
}
else
{
result += "\"";
for (auto c : column)
{
if (c == '\n')
{
result += "\\n";
}
if (c == '"')
{
result += "\"\"";
}
else
{
result += c;
}
}
result += "\"";
}
}
return result;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Timer.h | // Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <chrono>
namespace carb
{
namespace extras
{
/**
* Timer class.
*/
class Timer
{
protected:
std::chrono::high_resolution_clock::time_point m_startTimePoint, m_stopTimePoint;
bool m_isRunning = false;
public:
enum class Scale
{
eSeconds,
eMilliseconds,
eMicroseconds,
eNanoseconds
};
/**
* Returns precision of the timer (minimal tick duration).
*/
double getPrecision()
{
return std::chrono::high_resolution_clock::period::num / (double)std::chrono::high_resolution_clock::period::den;
}
/**
* Starts timer.
*/
void start()
{
m_startTimePoint = std::chrono::high_resolution_clock::now();
m_isRunning = true;
}
/**
* Stops timer.
*/
void stop()
{
m_stopTimePoint = std::chrono::high_resolution_clock::now();
m_isRunning = false;
}
/**
* Gets elapsed time in a specified form, using specified time scale.
*
* @param timeScale Time scale that you want to get result in.
*
* @return Elapsed time between timer start, and timer stop events. If timer wasn't stopped before, returns elapsed
* time between timer start and this function call, timer will continue to tick. Template parameter allows to select
* between integral returned elapsed time (default), and floating point elapsed time, double precision recommended.
*/
template <typename ReturnType = int64_t>
ReturnType getElapsedTime(Scale timeScale = Scale::eMilliseconds)
{
std::chrono::high_resolution_clock::time_point stopTimePoint;
if (m_isRunning)
{
stopTimePoint = std::chrono::high_resolution_clock::now();
}
else
{
stopTimePoint = m_stopTimePoint;
}
auto elapsedTime = stopTimePoint - m_startTimePoint;
using dblSeconds = std::chrono::duration<ReturnType, std::ratio<1>>;
using dblMilliseconds = std::chrono::duration<ReturnType, std::milli>;
using dblMicroseconds = std::chrono::duration<ReturnType, std::micro>;
using dblNanoseconds = std::chrono::duration<ReturnType, std::nano>;
switch (timeScale)
{
case Scale::eSeconds:
return std::chrono::duration_cast<dblSeconds>(elapsedTime).count();
case Scale::eMilliseconds:
return std::chrono::duration_cast<dblMilliseconds>(elapsedTime).count();
case Scale::eMicroseconds:
return std::chrono::duration_cast<dblMicroseconds>(elapsedTime).count();
case Scale::eNanoseconds:
return std::chrono::duration_cast<dblNanoseconds>(elapsedTime).count();
default:
return std::chrono::duration_cast<dblMilliseconds>(elapsedTime).count();
}
}
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/CpuInfo.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Utilities for gathering information about the CPU
#pragma once
#include "../Defines.h"
#include <array>
#if CARB_X86_64
# if CARB_COMPILER_MSC
extern "C"
{
void __cpuid(int cpuInfo[4], int function_id);
}
# pragma intrinsic(__cpuid)
# elif CARB_COMPILER_GNUC
// for some strange reason, GCC's 'cpuid.h' header does not have an include guard of any
// kind. This leads to multiple definition errors when the header is included twice in
// a translation unit. To avoid this, we'll add our own external include guard here.
# ifndef CARB_CPUID_H_INCLUDED
# define CARB_CPUID_H_INCLUDED
# include "cpuid.h"
# endif
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
#endif
namespace carb
{
namespace extras
{
/**
* Helper class for gathering and querying CPU information for x86 and x64 CPUs
*
* On construction this class will query the CPU information provided by CPU ID and then provides helper methods for
* querying information about the CPU.
*/
class CpuInfo
{
public:
/**
* Constructor
*/
CpuInfo() : m_isValid(true)
{
#if CARB_X86_64
# if CARB_COMPILER_MSC
__cpuid(reinterpret_cast<int32_t*>(m_data.data()), kInfoType);
# else
// if __get_cpuid returns 0, the cpu information is not valid.
int result = __get_cpuid(kInfoType, &m_data[kEax], &m_data[kEbx], &m_data[kEcx], &m_data[kEdx]);
if (result == 0)
{
m_isValid = false;
}
# endif
#else
m_isValid = false;
#endif
}
/**
* Checks if the popcnt instruction is supported
*
* @return True if popcnt is supported, false if it is not supported, or the CPU information is not valid.
*/
bool popcntSupported()
{
return m_isValid && m_data[kEcx] & (1UL << kPopCountBit);
}
private:
static constexpr uint32_t kInfoType = 0x00000001;
static constexpr uint8_t kEax = 0;
static constexpr uint8_t kEbx = 1;
static constexpr uint8_t kEcx = 2;
static constexpr uint8_t kEdx = 3;
static constexpr uint8_t kPopCountBit = 23;
bool m_isValid;
std::array<uint32_t, 4> m_data;
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Latch.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../cpp/Latch.h"
namespace carb
{
namespace extras
{
class CARB_DEPRECATED("Deprecated: carb::extras::latch has moved to carb::cpp::latch") latch : public carb::cpp::latch
{
public:
constexpr explicit latch(ptrdiff_t expected) : carb::cpp::latch(expected)
{
}
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Tokens.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides helper functions to manage and evaluate token strings.
*/
#pragma once
#include "../tokens/TokensUtils.h"
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
/** Registers a new path string alias for replacement with resolvePathAliases().
*
* @param[in] alias The alias string to be replaced. This should not contain the replacement
* marker around the name "${}".
* @param[in] value The value to replace the alias string with.
* @returns No return value.
*/
inline void registerPathAlias(const char* alias, const char* value)
{
static carb::tokens::ITokens* tokens = carb::getFramework()->acquireInterface<carb::tokens::ITokens>();
tokens->setValue(alias, value);
}
/** Unregisters a path string alias.
*
* @param[in] alias The alias string to be removed. This should not contain the replacement
* marker around the name "${}". This should have been previously registered
* with registerPathAlias().
* @returns No return value.
*/
inline void unregisterPathAlias(const char* alias)
{
static carb::tokens::ITokens* tokens = carb::getFramework()->acquireInterface<carb::tokens::ITokens>();
tokens->removeToken(alias);
}
/** Replaces path alias markers in a path with the full names.
*
* @param[in] srcBuf The path to potentially replace path alias markers in. Any path
* alias markers in the string must be surrounded by "${" and "}" characters
* (ie: "${exampleMarker}/file.txt"). The markers will only be replaced if a
* path alias using the same marker name ("exampleMarker" in the previous
* example) is currently registered.
* @returns A string containing the resolved path if path alias markers were replaced.
* @returns A string containing the original path if no path alias markers were found or
* replaced.
*
* @remarks This resolves a path string by replacing path alias markers with their full
* paths. Markers must be registered with registerPathAlias() in order to be
* replaced. This will always return a new string, but not all of the markers
* may have been replaced in it is unregistered markers were found.
*
* @remarks A replaced path will never end in a trailing path separator. It is the caller's
* responsibility to ensure the marker(s) in the string are appropriately separated
* from other path components. This behavior does however allow for path aliases
* to be used to construct multiple path names by piecing together different parts
* of a name.
*
* @note This operation is always thread safe.
*/
inline std::string resolvePathAliases(const char* srcBuf)
{
static carb::tokens::ITokens* tokens = carb::getFramework()->acquireInterface<carb::tokens::ITokens>();
return carb::tokens::resolveString(tokens, srcBuf);
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/EnvironmentVariableUtils.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Provides a helper class for setting and restoring environment variables.
//
#pragma once
#include "../logging/Log.h"
#include <map>
#include <vector>
namespace carb
{
namespace extras
{
/**
* Resolves environment variable references in the source buffer
*
* @param sourceBuffer buffer of text to resolve
* @param sourceBufferLength length of source buffer
* @param envVariables map of name/value pairs of environment variables
* @return The resolved string is the first member of the returned pair
* the second bool member indicates if the resolve was without errors
*/
inline std::pair<std::string, bool> resolveEnvVarReferences(const char* sourceBuffer,
size_t sourceBufferLength,
const std::map<std::string, std::string>& envVariables) noexcept
{
std::pair<std::string, bool> result{};
if (!sourceBuffer)
{
CARB_LOG_ERROR("Null source buffer for resolving environment variable references.");
return result;
}
if (CARB_UNLIKELY(sourceBufferLength == 0))
{
result.second = true;
return result;
}
// Collecting the env vars references
struct EnvVarReference
{
const char* referenceStart;
const char* referenceEnd;
};
std::vector<EnvVarReference> envReferences;
constexpr const char kEnvVarPrefix[] = "$env{";
constexpr const size_t kEnvVarPrefixLength = carb::countOf(kEnvVarPrefix) - 1;
constexpr const char kEnvVarPostfix = '}';
constexpr const size_t kEnvVarPostfixLength = 1;
const char* endEnvPos = sourceBuffer;
for (const char* curReferencePos = std::strstr(endEnvPos, kEnvVarPrefix); curReferencePos != nullptr;
curReferencePos = std::strstr(endEnvPos, kEnvVarPrefix))
{
endEnvPos = std::strchr(curReferencePos, kEnvVarPostfix);
if (!endEnvPos)
{
CARB_LOG_ERROR("Couldn't find the end of the environment variable reference: '%s'", curReferencePos);
return result;
}
endEnvPos += kEnvVarPostfixLength;
envReferences.emplace_back(EnvVarReference{ curReferencePos, endEnvPos });
}
if (envReferences.empty())
{
result.first = std::string(sourceBuffer, sourceBufferLength);
result.second = true;
return result;
}
// return true if resolved all the env variables in the provided buffer
auto envVarResolver = [&](const char* buffer, const char* bufferEnd, size_t firstRefIndexToTry,
size_t& firstUnprocessedRefIndex, std::string& resolvedString) -> bool {
const char* curBufPos = buffer;
const size_t envReferencesSize = envReferences.size();
size_t curRefIndex = firstRefIndexToTry;
bool resolved = true;
while (curRefIndex < envReferencesSize && envReferences[curRefIndex].referenceStart < buffer)
{
++curRefIndex;
}
for (; curBufPos < bufferEnd && curRefIndex < envReferencesSize; ++curRefIndex)
{
const EnvVarReference& curRef = envReferences[curRefIndex];
if (curRef.referenceEnd > bufferEnd)
{
break;
}
// adding the part before env variable
if (curBufPos < curRef.referenceStart)
{
resolvedString.append(curBufPos, curRef.referenceStart);
}
// resolving the env variable
std::string varName(curRef.referenceStart + kEnvVarPrefixLength, curRef.referenceEnd - kEnvVarPostfixLength);
if (CARB_LIKELY(!varName.empty()))
{
auto searchResult = envVariables.find(varName);
if (searchResult != envVariables.end())
{
resolvedString.append(searchResult->second);
}
else
{
// Couldn't resolve the reference
resolved = false;
}
}
else
{
CARB_LOG_WARN("Found environment variable reference with empty name.");
}
curBufPos = curRef.referenceEnd;
}
firstUnprocessedRefIndex = curRefIndex;
// adding the rest of the string
if (curBufPos < bufferEnd)
{
resolvedString.append(curBufPos, bufferEnd);
}
return resolved;
};
// Check for the Elvis operator
constexpr const char* const kElvisOperator = "?:";
constexpr size_t kElvisOperatorLen = 2;
const char* const elvisPos = ::strstr(sourceBuffer, kElvisOperator);
const size_t leftPartSize = elvisPos ? elvisPos - sourceBuffer : sourceBufferLength;
size_t rightPartEnvRefFirstIndex = 0;
const bool allResolved =
envVarResolver(sourceBuffer, sourceBuffer + leftPartSize, 0, rightPartEnvRefFirstIndex, result.first);
// switch to using the right part if we couldn't resolve everything on the left part of the Elvis op
if (elvisPos && !allResolved)
{
result.first.clear();
envVarResolver(elvisPos + kElvisOperatorLen, sourceBuffer + sourceBufferLength, rightPartEnvRefFirstIndex,
rightPartEnvRefFirstIndex, result.first);
}
result.second = true;
return result;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/ScopeExit.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "../cpp/Exception.h"
#include <type_traits>
#include <utility>
//
// Inspired from Andrei Alexandrescu CppCon 2015 Talk: Declarative Control Flow
// https://github.com/CppCon/CppCon2015/tree/master/Presentations/
// https://www.youtube.com/watch?v=WjTrfoiB0MQ
//
// lambda executed on scope leaving scope
#define CARB_SCOPE_EXIT \
const auto CARB_ANONYMOUS_VAR(SCOPE_EXIT_STATE) = ::carb::extras::detail::ScopeGuardExit{} + [&]()
// lambda executed when leaving scope because an exception was thrown
#define CARB_SCOPE_EXCEPT \
const auto CARB_ANONYMOUS_VAR(SCOPE_EXCEPT_STATE) = ::carb::extras::detail::ScopeGuardOnFail{} + [&]()
// lambda executed when leaving scope and no exception was thrown
#define CARB_SCOPE_NOEXCEPT \
const auto CARB_ANONYMOUS_VAR(SCOPE_EXCEPT_STATE) = ::carb::extras::detail::ScopeGuardOnSuccess{} + [&]()
namespace carb
{
namespace extras
{
namespace detail
{
template <typename Fn>
class ScopeGuard final
{
CARB_PREVENT_COPY(ScopeGuard);
public:
explicit ScopeGuard(Fn&& fn) : m_fn(std::move(fn))
{
}
ScopeGuard(ScopeGuard&&) = default;
ScopeGuard& operator=(ScopeGuard&&) = default;
~ScopeGuard()
{
m_fn();
}
private:
Fn m_fn;
};
enum class ScopeGuardExit
{
};
template <typename Fn>
ScopeGuard<typename std::decay_t<Fn>> operator+(ScopeGuardExit, Fn&& fn)
{
return ScopeGuard<typename std::decay_t<Fn>>(std::forward<Fn>(fn));
}
class UncaughtExceptionCounter final
{
CARB_PREVENT_COPY(UncaughtExceptionCounter);
int m_exceptionCount;
public:
UncaughtExceptionCounter() noexcept : m_exceptionCount(::carb::cpp::uncaught_exceptions())
{
}
~UncaughtExceptionCounter() = default;
UncaughtExceptionCounter(UncaughtExceptionCounter&&) = default;
UncaughtExceptionCounter& operator=(UncaughtExceptionCounter&&) = default;
bool isNewUncaughtException() const noexcept
{
return ::carb::cpp::uncaught_exceptions() > m_exceptionCount;
}
};
template <typename Fn, bool execOnException>
class ScopeGuardForNewException
{
CARB_PREVENT_COPY(ScopeGuardForNewException);
Fn m_fn;
UncaughtExceptionCounter m_ec;
public:
explicit ScopeGuardForNewException(Fn&& fn) : m_fn(std::move(fn))
{
}
~ScopeGuardForNewException() noexcept(execOnException)
{
if (execOnException == m_ec.isNewUncaughtException())
{
m_fn();
}
}
ScopeGuardForNewException(ScopeGuardForNewException&&) = default;
ScopeGuardForNewException& operator=(ScopeGuardForNewException&&) = default;
};
enum class ScopeGuardOnFail
{
};
template <typename Fn>
ScopeGuardForNewException<typename std::decay_t<Fn>, true> operator+(ScopeGuardOnFail, Fn&& fn)
{
return ScopeGuardForNewException<typename std::decay_t<Fn>, true>(std::forward<Fn>(fn));
}
enum class ScopeGuardOnSuccess
{
};
template <typename Fn>
ScopeGuardForNewException<typename std::decay_t<Fn>, false> operator+(ScopeGuardOnSuccess, Fn&& fn)
{
return ScopeGuardForNewException<typename std::decay_t<Fn>, false>(std::forward<Fn>(fn));
}
} // namespace detail
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/FreeListAllocator.h | // Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include <cstring>
namespace carb
{
namespace extras
{
/**
* Defines a free list that can allocate/deallocate fast and in any order from identically sized blocks.
*
* As long as every deallocation matches every allocation. Both allocation and deallocation are O(1) and
* generally just a few instructions. The underlying memory allocator will allocate in large blocks,
* with multiple elements amortizing a more costly large allocation against lots of fast small element allocations.
*/
class FreeListAllocator
{
public:
static const size_t kMinimalAlignment = sizeof(void*);
/**
* Constructor.
*/
FreeListAllocator()
: m_top(nullptr),
m_end(nullptr),
m_activeBlocks(nullptr),
m_freeBlocks(nullptr),
m_freeElements(nullptr),
m_elementSize(0),
m_alignment(1),
m_blockSize(0),
m_blockAllocationSize(0)
{
}
/**
* Constructor.
*
* @param elementSize Size of an element(in bytes).
* @param alignment Alignment for elements in bytes, must be a power of 2
* @param elementsPerBlock The number of elements held in a single block
*/
FreeListAllocator(size_t elementSize, size_t alignment, size_t elementsPerBlock)
{
_initialize(elementSize, alignment, elementsPerBlock);
}
/**
* Destructor.
*/
~FreeListAllocator()
{
_deallocateBlocks(m_activeBlocks);
_deallocateBlocks(m_freeBlocks);
}
/**
* Initialize a free list allocator.
*
* If called on an already initialized heap, the heap will be deallocated.
*
* @param elementSize Size of an element in bytes
* @param alignment Alignment for elements in bytes, must be a power of 2.
* @param elementsPerBlock The amount of elements held in a single block
*/
void initialize(size_t elementSize, size_t alignment, size_t elementsPerBlock);
/**
* Determines if the data incoming is a valid allocation.
*
* @param data Pointer to be checked if is a valid allocation.
* @return true if the pointer is to a previously returned and active allocation.
*/
bool isValid(const void* data) const;
/**
* Allocates an element.
*
* @return The element allocated.
*/
void* allocate();
/**
* Deallocate a block that was previously allocated with allocate
*
* @param data Pointer previously gained by allocate.
*/
void deallocate(void* data);
/**
* Deallocates all elements
*/
void deallocateAll();
/**
* Resets and deallocates all blocks and frees any backing memory and resets memory blocks to initial state.
*/
void reset();
/**
* Gets the element size.
*
* @return The size of an element (in bytes).
*/
size_t getElementSize() const;
/**
* Gets the total size of each individual block allocation (in bytes).
*
* @return The size of each block (in bytes).
*/
size_t getBlockSize() const;
/**
* Gets the allocation alignment (in bytes).
*
* @return Allocation alignment (in bytes).
*/
size_t getAlignment() const;
private:
struct Element
{
Element* m_next;
};
struct Block
{
Block* m_next;
uint8_t* m_data;
};
FreeListAllocator(const FreeListAllocator& rhs) = delete;
void operator=(const FreeListAllocator& rhs) = delete;
void _initialize(size_t elementSize, size_t alignment, size_t elementsPerBlock)
{
// Alignment must be at least the size of a pointer, as when freed a pointer is stored in free blocks.
m_alignment = (alignment < kMinimalAlignment) ? kMinimalAlignment : alignment;
// Alignment must be a power of 2
CARB_ASSERT(((m_alignment - 1) & m_alignment) == 0);
// The elementSize must at least be the size of the alignment
m_elementSize = (elementSize >= m_alignment) ? elementSize : m_alignment;
// The elementSize must be an integral number of alignment/s
CARB_ASSERT((m_elementSize & (m_alignment - 1)) == 0);
m_blockSize = m_elementSize * elementsPerBlock;
// Calculate the block size need, correcting for alignment
const size_t alignedBlockSize = _calculateAlignedBlockSize(m_alignment);
// Make the block struct size aligned
m_blockAllocationSize = m_blockSize + alignedBlockSize;
m_top = nullptr;
m_end = nullptr;
m_activeBlocks = nullptr;
m_freeBlocks = nullptr;
m_freeElements = nullptr;
}
void* _allocateBlock()
{
Block* block = m_freeBlocks;
if (block)
{
// Remove from the free blocks
m_freeBlocks = block->m_next;
}
else
{
block = (Block*)CARB_MALLOC(m_blockAllocationSize);
if (!block)
{
return nullptr;
}
// Do the alignment
{
size_t fix = (size_t(block) + sizeof(Block) + m_alignment - 1) & ~(m_alignment - 1);
block->m_data = (uint8_t*)fix;
}
}
// Attach to the active blocks
block->m_next = m_activeBlocks;
m_activeBlocks = block;
// Set up top and end
m_end = block->m_data + m_blockSize;
// Return the first element
uint8_t* element = block->m_data;
m_top = element + m_elementSize;
return element;
}
void _deallocateBlocks(Block* block)
{
while (block)
{
Block* next = block->m_next;
CARB_FREE(block);
block = next;
}
}
static size_t _calculateAlignedBlockSize(size_t align)
{
return (sizeof(Block) + align - 1) & ~(align - 1);
}
uint8_t* m_top;
uint8_t* m_end;
Block* m_activeBlocks;
Block* m_freeBlocks;
Element* m_freeElements;
size_t m_elementSize;
size_t m_alignment;
size_t m_blockSize;
size_t m_blockAllocationSize;
};
inline void FreeListAllocator::initialize(size_t elementSize, size_t alignment, size_t elementsPerBlock)
{
_deallocateBlocks(m_activeBlocks);
_deallocateBlocks(m_freeBlocks);
_initialize(elementSize, alignment, elementsPerBlock);
}
inline bool FreeListAllocator::isValid(const void* data) const
{
uint8_t* checkedData = (uint8_t*)data;
Block* block = m_activeBlocks;
while (block)
{
uint8_t* start = block->m_data;
uint8_t* end = start + m_blockSize;
if (checkedData >= start && checkedData < end)
{
// Check it's aligned correctly
if ((checkedData - start) % m_elementSize)
{
return false;
}
// Non-allocated data is between top and end
if (checkedData >= m_top && data < m_end)
{
return false;
}
// It can't be in the free list
Element* element = m_freeElements;
while (element)
{
if (element == (Element*)data)
{
return false;
}
element = element->m_next;
}
return true;
}
block = block->m_next;
}
// It's not in an active block and therefore it cannot be a valid allocation
return false;
}
inline void* FreeListAllocator::allocate()
{
// Check if there are any previously deallocated elements, if so use these first
{
Element* element = m_freeElements;
if (element)
{
m_freeElements = element->m_next;
return element;
}
}
// If there is no space on current block, then allocate a new block and return first element
if (m_top >= m_end)
{
return _allocateBlock();
}
// We can use top
void* data = (void*)m_top;
m_top += m_elementSize;
return data;
}
inline void FreeListAllocator::deallocate(void* data)
{
Element* element = (Element*)data;
element->m_next = m_freeElements;
m_freeElements = element;
}
inline void FreeListAllocator::deallocateAll()
{
Block* block = m_activeBlocks;
if (block)
{
// Find the end block
while (block->m_next)
{
block = block->m_next;
}
// Attach to the freeblocks
block->m_next = m_freeBlocks;
// The list is now all freelists
m_freeBlocks = m_activeBlocks;
// There are no active blocks
m_activeBlocks = nullptr;
}
m_top = nullptr;
m_end = nullptr;
}
inline void FreeListAllocator::reset()
{
_deallocateBlocks(m_activeBlocks);
_deallocateBlocks(m_freeBlocks);
m_top = nullptr;
m_end = nullptr;
m_activeBlocks = nullptr;
m_freeBlocks = nullptr;
m_freeElements = nullptr;
}
inline size_t FreeListAllocator::getElementSize() const
{
return m_elementSize;
}
inline size_t FreeListAllocator::getBlockSize() const
{
return m_blockSize;
}
inline size_t FreeListAllocator::getAlignment() const
{
return m_alignment;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Hash.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
namespace carb
{
namespace extras
{
namespace detail
{
#if CARB_COMPILER_GNUC
using uint128_t = __uint128_t;
constexpr uint128_t fnv128init(uint64_t high, uint64_t low)
{
return (uint128_t(high) << 64) + low;
}
inline void fnv128xor(uint128_t& out, uint8_t b)
{
out ^= b;
}
inline void fnv128add(uint128_t& out, uint128_t in)
{
out += in;
}
inline void fnv128mul(uint128_t& out, uint128_t in)
{
out *= in;
}
#elif CARB_COMPILER_MSC
extern "C" unsigned __int64 _umul128(unsigned __int64, unsigned __int64, unsigned __int64*);
extern "C" unsigned char _addcarry_u64(unsigned char, unsigned __int64, unsigned __int64, unsigned __int64*);
# pragma intrinsic(_mul128)
# pragma intrinsic(_addcarry_u64)
struct uint128_t
{
uint64_t d[2];
};
constexpr uint128_t fnv128init(uint64_t high, uint64_t low)
{
return uint128_t{ low, high };
}
inline void fnv128xor(uint128_t& out, uint8_t b)
{
out.d[0] ^= b;
}
inline void fnv128add(uint128_t& out, uint128_t in)
{
uint8_t c = _addcarry_u64(0, out.d[0], in.d[0], &out.d[0]);
_addcarry_u64(c, out.d[1], in.d[1], &out.d[1]);
}
inline void fnv128mul(uint128_t& out, uint128_t in)
{
// 128-bit multiply with 64 bits is:
// place: 64 0
// A B (out)
// X C D (in)
// --------------------
// D*A D*B
// + C*B 0
uint64_t orig = out.d[0], temp;
out.d[0] = _umul128(orig, in.d[0], &temp);
out.d[1] = temp + (out.d[1] * in.d[0]) + (in.d[1] * orig);
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
// 0x0000000001000000000000000000013B
constexpr uint128_t kFnv128Prime = detail::fnv128init(0x0000000001000000, 0x000000000000013B);
} // namespace detail
struct hash128_t
{
uint64_t d[2];
};
// FNV-1a 128-bit basis: 0x6c62272e07bb014262b821756295c58d
constexpr static hash128_t kFnv128Basis = { 0x62b821756295c58d, 0x6c62272e07bb0142 };
inline hash128_t hash128FromHexString(const char* buffer, const char** end = nullptr)
{
union
{
detail::uint128_t u128 = { 0 };
hash128_t hash;
} ret;
constexpr static detail::uint128_t n16{ 16 };
// skip 0x if necessary
if (buffer[0] == '0' && buffer[1] == 'x')
buffer += 2;
while (*buffer)
{
detail::uint128_t num;
if (*buffer >= '0' && *buffer <= '9')
num = { unsigned(*buffer - '0') };
else if (*buffer >= 'a' && *buffer <= 'z')
num = { unsigned(*buffer - 'a' + 10) };
else if (*buffer >= 'A' && *buffer <= 'Z')
num = { unsigned(*buffer - 'A' + 10) };
else
{
// Error
CARB_ASSERT(0);
if (end)
*end = buffer;
return ret.hash;
}
detail::fnv128mul(ret.u128, n16);
detail::fnv128add(ret.u128, num);
++buffer;
}
if (end)
*end = buffer;
return ret.hash;
}
// Deprecated function
CARB_DEPRECATED("Use hash128FromHexString() instead") inline bool hashFromString(const char* buffer, hash128_t& hash)
{
const char* end;
hash = hash128FromHexString(buffer, &end);
return *end == '\0';
}
inline hash128_t fnv128hash(const uint8_t* data, size_t size, hash128_t seed = kFnv128Basis)
{
union U
{
detail::uint128_t u128;
hash128_t hash;
} u;
u.hash = seed;
const uint8_t* const end = data + size;
// Align
if (CARB_UNLIKELY(!!(size_t(data) & 0x7) && (end - data) >= 8))
{
do
{
detail::fnv128xor(u.u128, *(data++));
detail::fnv128mul(u.u128, detail::kFnv128Prime);
} while (!!(size_t(data) & 0x7));
}
// Unroll the loop
while ((end - data) >= 8)
{
uint64_t val = *reinterpret_cast<const uint64_t*>(data);
#define HASH_STEP(v) \
detail::fnv128xor(u.u128, uint8_t(v)); \
detail::fnv128mul(u.u128, detail::kFnv128Prime)
HASH_STEP(val);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
#undef HASH_STEP
data += 8;
}
// Handle remaining
while (data != end)
{
detail::fnv128xor(u.u128, *(data++));
detail::fnv128mul(u.u128, detail::kFnv128Prime);
}
return u.hash;
}
namespace detail
{
// this can't be a lambda because there's no consistent way to add this
// attribute to a lambda between GCC 7 and 9
CARB_ATTRIBUTE(no_sanitize_address) inline uint64_t read64(const void* data)
{
return *static_cast<const uint64_t*>(data);
}
} // namespace detail
inline hash128_t fnv128hashString(const char* data, hash128_t seed = kFnv128Basis)
{
union U
{
detail::uint128_t u128;
hash128_t hash;
} u;
u.hash = seed;
if (!!(size_t(data) & 0x7))
{
// Align
for (;;)
{
if (*data == '\0')
return u.hash;
detail::fnv128xor(u.u128, uint8_t(*(data++)));
detail::fnv128mul(u.u128, detail::kFnv128Prime);
if (!(size_t(data) & 0x7))
break;
}
}
// Use a bit trick often employed in strlen() implementations to return a non-zero value if any byte within a word
// is zero. This can sometimes be falsely positive for UTF-8 strings, so handle those
for (;;)
{
uint64_t val = ::carb::extras::detail::read64(data);
if (CARB_LIKELY(!((val - 0x0101010101010101) & 0x8080808080808080)))
{
// None of the next 8 bytes are zero
#define HASH_STEP(v) \
detail::fnv128xor(u.u128, uint8_t(v)); \
detail::fnv128mul(u.u128, detail::kFnv128Prime)
HASH_STEP(val);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
#undef HASH_STEP
}
else
{
uint8_t b;
// One of the next 8 bytes *might* be zero
#define HASH_STEP(v) \
b = uint8_t(v); \
if (CARB_UNLIKELY(!b)) \
return u.hash; \
detail::fnv128xor(u.u128, b); \
detail::fnv128mul(u.u128, detail::kFnv128Prime)
HASH_STEP(val);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
HASH_STEP(val >>= 8);
#undef HASH_STEP
}
data += 8;
}
}
constexpr bool operator==(const hash128_t& lhs, const hash128_t& rhs)
{
return lhs.d[0] == rhs.d[0] && lhs.d[1] == rhs.d[1];
}
constexpr bool operator!=(const hash128_t& lhs, const hash128_t& rhs)
{
return !(lhs == rhs);
}
constexpr bool operator<(const hash128_t& lhs, const hash128_t& rhs)
{
if (lhs.d[1] < rhs.d[1])
return true;
if (rhs.d[1] < lhs.d[1])
return false;
return lhs.d[0] < rhs.d[0];
}
constexpr bool operator>(const hash128_t& lhs, const hash128_t& rhs)
{
return rhs < lhs;
}
constexpr bool operator<=(const hash128_t& lhs, const hash128_t& rhs)
{
return !(lhs > rhs);
}
constexpr bool operator>=(const hash128_t& lhs, const hash128_t& rhs)
{
return !(lhs < rhs);
}
} // namespace extras
} // namespace carb
namespace std
{
template <>
struct hash<carb::extras::hash128_t>
{
using argument_type = carb::extras::hash128_t;
using result_type = std::size_t;
result_type operator()(argument_type const& s) const noexcept
{
return s.d[0] ^ s.d[1];
}
};
inline std::string to_string(const carb::extras::hash128_t& hash)
{
std::string strBuffer(32, '0');
constexpr static char nibbles[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
};
auto fill64 = [](char* buffer, uint64_t v) {
buffer += 16;
while (v != 0)
{
*(--buffer) = nibbles[v & 0xf];
v >>= 4;
}
};
fill64(std::addressof(strBuffer.at(16)), hash.d[0]);
fill64(std::addressof(strBuffer.at(0)), hash.d[1]);
return strBuffer;
}
} // namespace std
|
omniverse-code/kit/include/carb/extras/CmdLineParser.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "../cpp/StringView.h"
#include "../logging/Log.h"
#include "StringUtils.h"
#include "Unicode.h"
#include <algorithm>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#elif CARB_PLATFORM_LINUX
# include <argz.h>
# include <fstream>
#elif CARB_PLATFORM_MACOS
# include <crt_externs.h>
#endif
namespace carb
{
namespace extras
{
class CmdLineParser
{
public:
using Options = std::map<std::string, std::string>;
CmdLineParser(const char* prefix) : m_prefix(prefix)
{
}
void parse(char** argv, int argc)
{
if (argc > 0)
{
parseFromArgs(argv, argc);
}
else
{
parseFromCLI();
}
}
const Options& getOptions() const
{
return m_carbOptions;
}
private:
void parseFromCLI()
{
m_currentKey.clear();
#if CARB_PLATFORM_WINDOWS
LPWSTR* argv;
int argc;
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (nullptr == argv)
{
return;
}
parseFromArgs(argv, argc);
LocalFree(argv);
#elif CARB_PLATFORM_LINUX
std::string cmdLine;
std::getline(std::fstream("/proc/self/cmdline", std::ios::in), cmdLine);
int argc = argz_count(cmdLine.c_str(), cmdLine.size());
char** argv = static_cast<char**>(std::malloc((argc + 1) * sizeof(char*)));
argz_extract(cmdLine.c_str(), cmdLine.size(), argv);
parseFromArgs(argv, argc);
std::free(argv);
#elif CARB_PLATFORM_MACOS
int argc = *_NSGetArgc();
char** argv = *_NSGetArgv();
parseFromArgs(argv, argc);
#endif
}
void parseArg(const std::string& arg)
{
// Waiting value for a key?
if (!m_currentKey.empty())
{
std::string value = arg;
preprocessValue(value);
m_carbOptions[m_currentKey] = value;
m_currentKey.clear();
return;
}
// Process only keys starting with kCarbPrefix
if (strncmp(arg.c_str(), m_prefix.c_str(), m_prefix.size()) == 0)
{
// Split to key and value
std::size_t pos = arg.find("=");
if (pos != std::string::npos)
{
const std::string key = carb::extras::trimString(arg.substr(m_prefix.size(), pos - m_prefix.size()));
if (!key.empty())
{
std::string value = arg.substr(pos + 1, arg.size() - pos - 1);
preprocessValue(value);
carb::extras::trimStringInplace(value);
m_carbOptions[key] = value;
}
else
{
CARB_LOG_WARN("Encountered key-value pair with empty key in command line: %s", arg.c_str());
}
}
else
{
// Save key and wait for next value
m_currentKey = arg.substr(m_prefix.size(), arg.size() - m_prefix.size());
carb::extras::trimStringInplace(m_currentKey);
}
}
}
#if CARB_PLATFORM_WINDOWS
void parseFromArgs(wchar_t** argv, int argc)
{
if (argc < 0 || argv == nullptr)
return;
for (int i = 1; i < argc; ++i)
{
if (argv[i])
{
std::string arg = extras::convertWideToUtf8(argv[i]);
parseArg(arg);
}
}
}
#endif
void parseFromArgs(char** argv, int argc)
{
if (argc < 0 || argv == nullptr)
return;
for (int i = 1; i < argc; ++i)
{
if (argv[i])
{
std::string arg = argv[i];
parseArg(arg);
}
}
}
void preprocessValue(std::string& value)
{
// If surrounded by single quotes - replace them with double quotes for json compatibility
if (!value.empty() && value[0] == '\'' && value[value.size() - 1] == '\'')
{
value[0] = '"';
value[value.size() - 1] = '"';
}
}
private:
Options m_carbOptions;
std::string m_currentKey;
std::string m_prefix;
};
/**
* Converts an array of command-line arguments to a single command-line string.
*
* It handles spaces and quotes in the arguments.
*
* @param argv The array of command-line arguments.
* @param argc The number of arguments in the array.
* @return A string that represents the command-line arguments.
*/
inline std::string argvToCommandLine(const char* const* argv, size_t argc)
{
std::ostringstream os;
for (size_t i = 0; i < argc; ++i)
{
if (i > 0)
os << " ";
// quote this argument if it contains tabs, spaces, quotes, newlines, or carriage returns
cpp::string_view sv{ argv[i] };
if (sv.find_first_of(" \t\n\r\"", 0, 5) != std::string::npos)
{
os << "\"";
os << sv.data();
os << "\"";
}
else
{
os << sv.data();
}
}
return os.str();
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/AppConfig.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../dictionary/DictionaryUtils.h"
#include "EnvironmentVariableUtils.h"
#include "StringUtils.h"
#include "Path.h"
#include <map>
#include <string>
namespace carb
{
namespace extras
{
class ConfigLoadHelper
{
public:
using CmdLineOptionsMap = std::map<std::string, std::string>;
using PathwiseEnvOverridesMap = std::map<std::string, std::string>;
using EnvVariablesMap = std::map<std::string, std::string>;
// If the dict item is a special raw string then it returns pointer to the buffer past the special raw string marker
// In all other cases it returns nullptr
static inline const char* getRawStringFromItem(carb::dictionary::IDictionary* dictInterface,
const carb::dictionary::Item* item)
{
static constexpr char kSpecialRawStringMarker[] = "$raw:";
if (!dictInterface || !item)
{
return nullptr;
}
if (dictInterface->getItemType(item) != dictionary::ItemType::eString)
{
return nullptr;
}
const char* stringBuffer = dictInterface->getStringBuffer(item);
if (!stringBuffer)
{
return nullptr;
}
constexpr size_t kMarkerLen = carb::countOf(kSpecialRawStringMarker) - 1;
if (std::strncmp(stringBuffer, kSpecialRawStringMarker, kMarkerLen) != 0)
{
return nullptr;
}
return stringBuffer + kMarkerLen;
}
/**
* Helper function to resolve references to environment variables and Elvis operators
*/
static inline void resolveEnvVarReferencesInDict(dictionary::IDictionary* dictInterface,
dictionary::Item* dict,
const EnvVariablesMap* envVariables)
{
if (!dict || !envVariables)
{
return;
}
const auto itemResolver = [&](dictionary::Item* item, uint32_t elementData, void* userData) {
CARB_UNUSED(elementData, userData);
// Working only on string items
if (dictInterface->getItemType(item) != dictionary::ItemType::eString)
{
return 0;
}
// Skipping raw strings
if (getRawStringFromItem(dictInterface, item) != nullptr)
{
return 0;
}
const char* stringBuffer = dictInterface->getStringBuffer(item);
const size_t stringBufferLen = std::strlen(stringBuffer);
// We have an empty string, no reason to resolve it
if (stringBufferLen == 0)
{
return 0;
}
std::pair<std::string, bool> resolveResult =
extras::resolveEnvVarReferences(stringBuffer, stringBufferLen, *envVariables);
if (!resolveResult.second)
{
CARB_LOG_ERROR("Error while resolving environment variable references for '%s'", stringBuffer);
return 0;
}
const std::string& resolvedString = resolveResult.first;
if (!resolvedString.empty())
{
dictInterface->setString(item, resolvedString.c_str());
}
else
{
dictInterface->destroyItem(item);
}
return 0;
};
const auto getChildByIndexMutable = [](dictionary::IDictionary* dict, dictionary::Item* item, size_t index) {
return dict->getItemChildByIndexMutable(item, index);
};
dictionary::walkDictionary(dictInterface, dictionary::WalkerMode::eIncludeRoot, dict, 0, itemResolver, nullptr,
getChildByIndexMutable);
}
using GetItemFullPathFuncPtr = std::string (*)(dictionary::IDictionary* dictInterface, const dictionary::Item* item);
struct UpdaterData
{
dictionary::IDictionary* dictInterface;
const char* loadedDictPath;
GetItemFullPathFuncPtr getItemFullPathFunc;
};
static dictionary::UpdateAction onDictUpdateReporting(const dictionary::Item* dstItem,
dictionary::ItemType dstItemType,
const dictionary::Item* srcItem,
dictionary::ItemType srcItemType,
void* userData)
{
CARB_UNUSED(dstItemType, srcItem, srcItemType);
const UpdaterData* updaterData = static_cast<const UpdaterData*>(userData);
if (updaterData->getItemFullPathFunc)
{
std::string itemPath = updaterData->getItemFullPathFunc(updaterData->dictInterface, dstItem);
CARB_LOG_VERBOSE("Replacing the '%s' item current value by the value from '%s' config.", itemPath.c_str(),
updaterData->loadedDictPath);
}
if (!dstItem)
{
return dictionary::UpdateAction::eOverwrite;
}
if (updaterData->dictInterface->getItemFlag(srcItem, dictionary::ItemFlag::eUnitSubtree))
{
return dictionary::UpdateAction::eReplaceSubtree;
}
return dictionary::UpdateAction::eOverwrite;
};
static inline GetItemFullPathFuncPtr getFullPathFunc()
{
return logging::getLogging()->getLevelThreshold() == logging::kLevelVerbose ? dictionary::getItemFullPath :
nullptr;
}
static dictionary::Item* resolveAndMergeNewDictIntoTarget(dictionary::IDictionary* dictInterface,
dictionary::Item* targetDict,
dictionary::Item* newDict,
const char* newDictSource,
const EnvVariablesMap* envVariablesMap)
{
if (!newDict)
{
return targetDict;
}
extras::ConfigLoadHelper::resolveEnvVarReferencesInDict(dictInterface, newDict, envVariablesMap);
if (!targetDict)
{
return newDict;
}
UpdaterData updaterData = { dictInterface, newDictSource ? newDictSource : "Unspecified source",
getFullPathFunc() };
dictInterface->update(targetDict, nullptr, newDict, nullptr, onDictUpdateReporting, &updaterData);
dictInterface->destroyItem(newDict);
return targetDict;
};
/** Retrieve the standardized user config folder for a given system.
* @param[in] envVariablesMap The environment variables to query for the
* config folder path.
* This may not be nullptr.
* @param[in] configSubFolderName The folder name within the config directory
* to append to the path.
* This may be nullptr to have the returned
* path be the config directory.
* @returns The path to the config directory that should be used.
* @returns An empty path if the required environment variables were not
* set. Note that this can't happen on Linux unless a user has
* explicitly broken their env vars.
*/
static extras::Path getConfigUserFolder(const EnvVariablesMap* envVariablesMap,
const char* configSubFolderName = "nvidia")
{
#if CARB_PLATFORM_WINDOWS
const char* kUserFolderEnvVar = "USERPROFILE";
#elif CARB_PLATFORM_LINUX
const char* kUserFolderEnvVar = "XDG_CONFIG_HOME";
#elif CARB_PLATFORM_MACOS
const char* kUserFolderEnvVar = "HOME";
#endif
extras::Path userFolder;
if (envVariablesMap)
{
// Resolving user folder
auto searchResult = envVariablesMap->find(kUserFolderEnvVar);
if (searchResult != envVariablesMap->end())
userFolder = searchResult->second;
#if CARB_PLATFORM_LINUX
// The XDG standard says that if XDG_CONFIG_HOME is undefined,
// $HOME/.config is used
if (userFolder.isEmpty())
{
auto searchResult = envVariablesMap->find("HOME");
if (searchResult != envVariablesMap->end())
{
userFolder = searchResult->second;
userFolder /= ".config";
}
}
#elif CARB_PLATFORM_MACOS
if (!userFolder.isEmpty())
{
userFolder /= "Library/Application Support";
}
#endif
if (!userFolder.isEmpty() && configSubFolderName != nullptr)
userFolder /= configSubFolderName;
}
return userFolder;
}
static dictionary::Item* applyPathwiseEnvOverrides(dictionary::IDictionary* dictionaryInterface,
dictionary::Item* combinedConfig,
const PathwiseEnvOverridesMap* pathwiseEnvOverridesMap,
const EnvVariablesMap* envVariablesMap)
{
if (pathwiseEnvOverridesMap)
{
dictionary::Item* pathwiseConfig = dictionaryInterface->createItem(
nullptr, "<pathwise env override config>", dictionary::ItemType::eDictionary);
if (pathwiseConfig)
{
dictionary::setDictionaryFromStringMapping(dictionaryInterface, pathwiseConfig, *pathwiseEnvOverridesMap);
return extras::ConfigLoadHelper::resolveAndMergeNewDictIntoTarget(
dictionaryInterface, combinedConfig, pathwiseConfig, "environment variables override",
envVariablesMap);
}
CARB_LOG_ERROR("Couldn't process environment variables overrides");
}
return combinedConfig;
}
/**
* Adds to the "targetDictionary" element at path "elementPath" as dictionary created from parsing elementValue as
* JSON data
*
* @param [in] jsonSerializerInterface non-null pointer to the JSON ISerializer interface
* @param [in] dictionaryInterface non-null pointer to the IDictionary interface
* @param [in,out] targetDictionary dictionary into which element will be added
* @param [in] elementPath path to the element in the dictionary
* @param [in] elementValue JSON data
*/
static void addCmdLineJSONElementToDict(dictionary::ISerializer* jsonSerializerInterface,
dictionary::IDictionary* dictionaryInterface,
dictionary::Item* targetDictionary,
const std::string& elementPath,
const std::string& elementValue)
{
if (elementPath.empty())
{
return;
}
CARB_ASSERT(elementValue.size() >= 2 && elementValue.front() == '{' && elementValue.back() == '}');
// Parse provided JSON data
dictionary::Item* parsedDictionary =
jsonSerializerInterface->createDictionaryFromStringBuffer(elementValue.c_str(), elementValue.length());
if (!parsedDictionary)
{
CARB_LOG_ERROR("Couldn't parse as JSON data command-line argument '%s'", elementPath.c_str());
return;
}
// Merge result into target dictionary
dictionaryInterface->update(targetDictionary, elementPath.c_str(), parsedDictionary, nullptr,
dictionary::overwriteOriginalWithArrayHandling, dictionaryInterface);
// Release allocated resources
dictionaryInterface->destroyItem(parsedDictionary);
}
/**
* Merges values set in the command line into provided configuration dictionary
*
* @param [in] dictionaryInterface non-null pointer to the IDictionary interface
* @param [in,out] combinedConfig configuration dictionary into which parameters set in the command line will be
* merged
* @param [in] cmdLineOptionsMap map of parameters set in the command line
* @param [in] envVariablesMap map of the parameters set in the environment variables. Used for resolving references
* in the values of cmdLineOptionsMap
*
* @return "combinedConfig" with merged parameters set in the command line
*/
static dictionary::Item* applyCmdLineOverrides(dictionary::IDictionary* dictionaryInterface,
dictionary::Item* combinedConfig,
const CmdLineOptionsMap* cmdLineOptionsMap,
const EnvVariablesMap* envVariablesMap)
{
if (cmdLineOptionsMap)
{
dictionary::Item* cmdLineOptionsConfig = dictionaryInterface->createItem(
nullptr, "<cmd line override config>", dictionary::ItemType::eDictionary);
if (cmdLineOptionsConfig)
{
dictionary::ISerializer* jsonSerializer = nullptr;
bool checkedJsonSerializer = false;
for (const auto& kv : *cmdLineOptionsMap)
{
const std::string& trimmedValue = carb::extras::trimString(kv.second);
// First checking if there is enough symbols to check for array/JSON parameter
if (trimmedValue.size() >= 2)
{
// Check if value is "[ something ]" then we consider it to be an array
if (trimmedValue.front() == '[' && trimmedValue.back() == ']')
{
// Processing the array value
setDictionaryArrayElementFromStringValue(
dictionaryInterface, cmdLineOptionsConfig, kv.first, trimmedValue);
continue;
}
// Check if value is "{ something }" then we consider it to be JSON data
else if (trimmedValue.front() == '{' && trimmedValue.back() == '}')
{
// First check if the JsonSerializer was created already
if (!checkedJsonSerializer)
{
checkedJsonSerializer = true;
jsonSerializer = getFramework()->tryAcquireInterface<dictionary::ISerializer>(
"carb.dictionary.serializer-json.plugin");
if (!jsonSerializer)
{
CARB_LOG_ERROR(
"Couldn't acquire JSON serializer for processing command line arguments");
}
}
if (jsonSerializer)
{
// Processing the JSON value
addCmdLineJSONElementToDict(
jsonSerializer, dictionaryInterface, cmdLineOptionsConfig, kv.first, trimmedValue);
}
else
{
CARB_LOG_ERROR("No JSON serializer acquired. Cannot process command line parameter '%s'",
kv.first.c_str());
}
continue;
}
}
// Processing as string representation of a dictionary value
dictionary::setDictionaryElementAutoType(
dictionaryInterface, cmdLineOptionsConfig, kv.first, kv.second);
}
return extras::ConfigLoadHelper::resolveAndMergeNewDictIntoTarget(
dictionaryInterface, combinedConfig, cmdLineOptionsConfig, "command line override", envVariablesMap);
}
else
{
CARB_LOG_ERROR("Couldn't process command line overrides");
}
}
return combinedConfig;
}
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/HandleDatabase.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief HandleDatabase definition file.
#pragma once
#include "../Defines.h"
#include "../container/LocklessQueue.h"
#include "../logging/Log.h"
#include "../math/Util.h"
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <stack>
#include <vector>
CARB_IGNOREWARNING_MSC_WITH_PUSH(4201) // nonstandard extension used: nameless struct/union
namespace carb
{
namespace extras
{
template <class Mapped, class Handle, class Allocator>
struct HandleRef;
template <class Mapped, class Handle, class Allocator>
struct ConstHandleRef;
/**
* Provides an OS-style mapping of a Handle to a Resource.
*
* Essentially HandleDatabase is a fast thread-safe reference-counted associative container.
*
* @thread_safety Unless otherwise mentioned, HandleDatabase functions may be called simultaneously from multiple
* threads.
*
* A given Handle value is typically never reused, however, it is possible for a handle value to be reused if billions
* of handles are requested.
*
* The HandleDatabase can store at most `(2^31)-1` items, or 2,147,483,647 items simultaneously, provided the memory
* exists to support it.
*
* Implementation Details:
*
* HandleDatabase achieves its speed and thread-safety by having a fixed-size base array (`m_database`) where each
* element is an array of size 2^(base array index). As such, these arrays double the size of the previous index array.
* These base arrays are never freed, simplifying thread safety and allowing HandleDatabase to be mostly lockless.
* This array-of-arrays forms a non-contiguous indexable array where the base array and offset can be computed from a
* 32-bit index value (see `indexToBucketAndOffset`).
*
* The Handle is a 64-bit value composed of two 32-bit values. The least-significant 32 bits is the index value into the
* array-of-arrays described above. The most-significant 32 bits is a lifecycle counter. Every time a new Mapped object
* is constructed, the lifecycle counter is incremented. This value forms a contract between a handle and the Mapped
* object at the index indicated by the Handle. If the lifecycle counter doesn't match, the Handle is invalid. As this
* lifecycle counter is incremented, there is the possibility of rollover after 2^31 handles are generated at a given
* index. The most significant bit will then be set as a rollover flag so that handleWasValid() continues to operate
* correctly. The handleWasValid() function returns `true` for any Handle where the lifecycle counter at the given index
* is greater-than-or-equal to the Handle's lifecycle counter, or if the rollover flag is set.
*
* @tparam Mapped The "value" type that is associated with a Handle.
* @tparam Handle The "key" type. Must be an unsigned integer or pointer type and 64-bit. This is an opaque type that
* cannot be dereferenced.
* @tparam Allocator The allocator that will be used to allocate memory. Must be capable of allocating large contiguous
* blocks of memory.
*/
template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>>
class CARB_VIZ HandleDatabase
{
public:
//! An alias to Mapped; the mapped value type.
using MappedType = Mapped;
//! An alias to Handle; the key type used to associate a mapped value type.
using HandleType = Handle;
//! An alias to Allocator; the allocator used to allocate memory.
using AllocatorType = Allocator;
//! An alias to the HandleRef for this HandleDatabase.
using HandleRefType = HandleRef<Mapped, Handle, Allocator>;
//! An alias to the ConstHandleRef for this HandleDatabase.
using ConstHandleRefType = ConstHandleRef<Mapped, Handle, Allocator>;
//! @a Deprecated: Use HandleRefType instead.
using scoped_handle_ref_type = HandleRefType;
/**
* Constructor.
* @thread_safety The constructor must complete in a single thread before any other functions may be called on
* `*this`.
*/
constexpr HandleDatabase() noexcept;
/**
* Destructor.
* @thread_safety All other functions on `*this` must be finished before the destructor can be called.
*/
~HandleDatabase();
/**
* Checks to see if a handle is valid or was ever valid in the past.
* @param handle The Handle to check.
* @returns `true` if a @p handle is currently valid or was valid in the past and has since been released; `false`
* otherwise.
*/
bool handleWasValid(Handle handle) const;
/**
* Creates a new Mapped type with the given arguments.
* @param args The arguments to pass to the Mapped constructor.
* @returns A `std::pair` of the Handle that can uniquely identify the new Mapped type, and a pointer to the newly
* constructed Mapped type.
*/
template <class... Args>
std::pair<Handle, Mapped*> createHandle(Args&&... args);
/**
* Attempts to find the Mapped type represented by @p handle.
* @thread_safety Not thread-safe as the Mapped type could be destroyed if another thread calls release().
* @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely
* result in a `nullptr` result without an assert or any other side-effects.
* @returns A pointer to a valid Mapped type if the handle was valid; `nullptr` otherwise.
*/
Mapped* getValueFromHandle(Handle handle) const;
/**
* Retrieves the Handle representing @p mapped.
* @warning Providing @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions
* is undefined.
* @param mapped A Mapped type previously created with createHandle().
* @returns The Handle representing @p mapped.
*/
Handle getHandleFromValue(const Mapped* mapped) const;
/**
* Atomically attempts to add a reference for the given Handle.
* @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely
* result in a `nullptr` result without an assert or any other side-effects.
* @returns A pointer to a valid Mapped type if a reference could be added; `nullptr` otherwise.
*/
Mapped* tryAddRef(Handle handle);
/**
* Atomically adds a reference for the given Handle; fatal if @p handle is invalid.
* @param handle A valid handle previously returned from createHandle(). Invalid or previously-valid handles will
* result in `std::terminate()` being called.
*/
void addRef(Handle handle);
/**
* Atomically adds a reference for the Handle representing @p mapped.
* @warning Providing @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions
* is undefined.
* @param mapped A Mapped type previously created with createHandle().
*/
void addRef(Mapped* mapped);
/**
* Atomically releases a reference for the given Handle, potentially freeing the associated Mapped type.
* @param handle A valid handle previously returned from createHandle(). Invalid or previously-valid handles will
* result in an assert in Debug builds, but return `false` with no side effects in Release builds.
* @returns `true` if the last reference was released and @p handle is no longer valid; `false` if Handle is not
* valid or is previously-valid or a non-final reference was released.
*/
bool release(Handle handle);
/**
* Atomically releases a reference for the Handle representing @p mapped.
* @warning Provided @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions
* is undefined.
* @param mapped A Mapped type previously created with createHandle().
* @returns `true` if the last reference was released and @p mapped is no longer valid; `false` if a reference other
* than the last reference was released.
*/
bool release(Mapped* mapped);
/**
* Atomically releases a reference if and only if it's the last reference.
* @param handle A valid handle previously returned from createHandle(). Invalid or previously-valid handles will
* result in an assert in Debug builds, but return `false` with no side effects in Release builds.
* @returns `true` if the last reference was released and @p handle is no longer valid; `false` otherwise.
*/
bool releaseIfLastRef(Handle handle);
/**
* Atomically releases a reference if and only if it's the last reference.
* @warning Provided @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions
* is undefined.
* @param mapped A Mapped type previously created with createHandle().
* @returns `true` if the last reference was released and @p mapped is no longer valid; `false` otherwise.
*/
bool releaseIfLastRef(Mapped* mapped);
/**
* Attempts to atomically add a reference to @p handle, and returns a HandleRef to @p handle.
* @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely
* result in an empty \ref HandleRef result without an assert or any other side-effects.
* @returns If \ref tryAddRef() would return a valid Mapped type for @p handle, then a \ref HandleRef that manages
* the reference is returned; otherwise an empty \ref HandleRef is returned.
*/
HandleRefType makeScopedRef(Handle handle);
/**
* Attempts to atomically add a reference to @p handle, and returns a ConstHandleRef to @p handle.
* @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely
* result in an empty \ref ConstHandleRef result without an assert or any other side-effects.
* @returns If \ref tryAddRef() would return a valid Mapped type for @p handle, then a \ref ConstHandleRef that
* manages the reference is returned; otherwise an empty \ref ConstHandleRef is returned.
*/
ConstHandleRefType makeScopedRef(Handle handle) const;
/**
* Calls the provided `Func` invocable object for each valid handle and its associated mapped type.
* @thread_safety This function is not safe to call if any other thread would be calling releaseIfLastRef() or
* release() to release the last reference of a Handle. Other threads calling createHandle() when this function is
* called may result in handles being skipped.
* @param f An invocable object with signature `void(Handle, Mapped*)`.
*/
template <class Func>
void forEachHandle(Func&& f) const;
/**
* Iterates over all valid handles and sets their reference counts to zero, destroying the associated mapped type.
* @thread_safety This function is NOT safe to call if any other thread is calling ANY other HandleDatabase function
* except for clear() or handleWasValid().
* @returns The number of handles that were released to zero.
*/
size_t clear();
private:
CARB_VIZ static constexpr uint32_t kBuckets = sizeof(uint32_t) * 8 - 1; ///< Number of buckets
static constexpr uint32_t kMaxSize = (1U << kBuckets) - 1; ///< Maximum size ever
// NOTE: Making *any* change to how rollover works should enable HANDLE_DATABASE_EXTENDED_TESTS in TestExtras.cpp
static constexpr uint32_t kRolloverFlag = 0x80000000u;
static constexpr uint32_t kLifecycleMask = 0x7fffffffu;
// A struct for mapping type Handle into its basic components of index and lifecycle
struct HandleUnion
{
union
{
Handle handle;
struct
{
uint32_t index;
uint32_t lifecycle;
};
};
constexpr HandleUnion(Handle h) noexcept : handle(h)
{
}
constexpr HandleUnion(uint32_t idx, uint32_t life) noexcept : index(idx), lifecycle(life & kLifecycleMask)
{
}
};
// A struct for tracking the refcount and lifecycle.
struct alignas(uint64_t) Metadata
{
uint32_t refCount{ 0 };
CARB_VIZ uint32_t lifecycle{ 0 };
constexpr Metadata() noexcept = default;
};
struct HandleData
{
// This union will either be the free link and index, or the constructed mapped type
union
{
struct
{
container::LocklessQueueLink<HandleData> link;
uint32_t index;
};
// This `val` is only constructed when the HandleData is in use
Mapped val;
};
// Metadata, but the union allows us to access the refCount atomically, separately.
union
{
CARB_VIZ std::atomic<Metadata> metadata;
std::atomic_uint32_t refCount; // Must share memory address with metadata.refCount
};
constexpr HandleData(uint32_t idx) noexcept : index(idx), metadata{}
{
}
// Empty destructor, required because of the union with non-trivial types
~HandleData() noexcept
{
}
};
static_assert(alignof(HandleData) >= alignof(Mapped),
"Invalid assumption: HandleData alignment should meet or exceed Mapped alignment");
static_assert(sizeof(Handle) == sizeof(uint64_t), "Handle should be 64-bit");
using HandleDataAllocator = typename std::allocator_traits<Allocator>::template rebind_alloc<HandleData>;
using AllocatorTraits = std::allocator_traits<HandleDataAllocator>;
static void indexToBucketAndOffset(uint32_t index, uint32_t& bucket, uint32_t& offset);
HandleData* expandDatabase();
HandleData* getHandleData(uint32_t index) const;
HandleData* getHandleData(const Mapped* mapped) const;
HandleData* getDbIndex(size_t index, std::memory_order = std::memory_order_seq_cst) const;
// m_database is fixed size and written atomically in expandDatabase(). It never contracts and therefore
// does not require a mutex
CARB_VIZ std::atomic<HandleData*> m_database[kBuckets] = {};
struct Members : HandleDataAllocator
{
// The "tasking timing" test performs much better with m_free as a queue instead of a stack.
container::LocklessQueue<HandleData, &HandleData::link> m_free;
} m_emo;
};
/**
* A smart-reference class for a Handle associated with a HandleDatabase.
*
* When HandleRef is destroyed, the associated handle is released with the HandleDatabase.
*/
template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>>
struct ConstHandleRef
{
public:
//! An alias to Mapped; the mapped value type.
using MappedType = const Mapped;
//! An alias to `const Mapped&`.
using ReferenceType = const Mapped&;
//! An alias to `const Mapped*`.
using PointerType = const Mapped*;
//! An alias to Handle; the key type used to associate a mapped value type.
using HandleType = Handle;
//! An alias to Allocator; the allocator used to allocate memory.
using AllocatorType = Allocator;
//! The type specification for the associated HandleDatabase.
using Database = HandleDatabase<Mapped, Handle, Allocator>;
//! @a Deprecated: Use MappedType instead.
using element_type = MappedType;
//! @a Deprecated: Use HandleType instead.
using handle_type = HandleType;
/**
* Default constructor. Produces an empty HandleRef.
*/
ConstHandleRef() = default;
/**
* Attempts to atomically reference a Handle from the given @p database.
* @param database The HandleDatabase containing @p handle.
* @param handle The handle previously returned from HandleDatabase::createHandle(). Providing an invalid or
* previously-valid handle results in an empty HandleRef.
*/
ConstHandleRef(Database& database, Handle handle) noexcept : m_mapped(database.tryAddRef(handle))
{
if (m_mapped)
{
m_database = std::addressof(database);
m_handle = handle;
}
}
/**
* Destructor. If `*this` is non-empty, releases the associated Handle with the associated HandleDatabase.
*/
~ConstHandleRef() noexcept
{
reset();
}
/**
* Move-constructor. Post-condition: @p other is an empty HandleRef.
* @param other The other HandleRef to move a reference from.
*/
ConstHandleRef(ConstHandleRef&& other) noexcept
{
swap(other);
}
/**
* Move-assign operator. Swaps state with @p other.
* @param other The other HandleRef to move a reference from.
*/
ConstHandleRef& operator=(ConstHandleRef&& other) noexcept
{
swap(other);
return *this;
}
// Specifically non-Copyable in order to reduce implicit usage.
// Use the explicit `clone()` function if a copy is desired
CARB_PREVENT_COPY(ConstHandleRef);
/**
* Explicitly adds a reference to any referenced handle and returns a HandleRef.
* @returns A HandleRef holding its own reference for the contained handle. May be empty if `*this` is empty.
*/
ConstHandleRef clone() const noexcept
{
if (m_mapped)
m_database->addRef(m_mapped);
return ConstHandleRef{ m_database, m_handle, m_mapped };
}
/**
* Dereferences and returns a pointer to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A pointer to the mapped type.
*/
PointerType operator->() noexcept
{
return get();
}
/**
* Dereferences and returns a const pointer to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A const pointer to the mapped type.
*/
PointerType operator->() const noexcept
{
return get();
}
/**
* Dereferences and returns a reference to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A reference to the mapped type.
*/
ReferenceType operator*() noexcept
{
CARB_ASSERT(get());
return *get();
}
/**
* Dereferences and returns a const reference to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A const reference to the mapped type.
*/
ReferenceType operator*() const noexcept
{
CARB_ASSERT(get());
return *get();
}
/**
* Returns a pointer to the mapped type, or `nullptr` if empty.
* @returns A pointer to the mapped type or `nullptr` if empty.
*/
PointerType get() noexcept
{
return this->m_mapped;
}
/**
* Returns a const pointer to the mapped type, or `nullptr` if empty.
* @returns A const pointer to the mapped type or `nullptr` if empty.
*/
PointerType get() const noexcept
{
return this->m_mapped;
}
/**
* Returns the Handle referenced by `*this`.
* @returns The Handle referenced by `*this`.
*/
Handle handle() const noexcept
{
return this->m_handle;
}
/**
* Tests if `*this` contains a valid reference.
* @returns `true` if `*this` maintains a valid reference; `false` if `*this` is empty.
*/
explicit operator bool() const noexcept
{
return get() != nullptr;
}
/**
* Releases any associated reference and resets `*this` to empty.
*/
void reset()
{
if (auto mapped = std::exchange(m_mapped, nullptr))
m_database->release(mapped);
m_database = nullptr;
m_handle = HandleType{};
}
/**
* Swaps state with another HandleRef.
*/
void swap(ConstHandleRef& rhs)
{
std::swap(m_database, rhs.m_database);
std::swap(m_handle, rhs.m_handle);
std::swap(m_mapped, rhs.m_mapped);
}
protected:
Database* m_database{}; ///< Handle database this reference points into.
Handle m_handle{}; ///< Handle that this reference currently represents.
Mapped* m_mapped{}; ///< The mapped value for this reference.
/**
* Protected constructor. Not to be used externally.
*/
ConstHandleRef(Database* db, Handle h, Mapped* m) noexcept : m_database(db), m_handle(h), m_mapped(m)
{
}
};
/**
* A smart-reference class for a Handle associated with a HandleDatabase.
*
* When HandleRef is destroyed, the associated handle is released with the HandleDatabase.
*/
template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>>
struct HandleRef : public ConstHandleRef<Mapped, Handle, Allocator>
{
/** Base type used for this container. */
using BaseType = ConstHandleRef<Mapped, Handle, Allocator>;
public:
//! An alias to Mapped; the mapped value type.
using MappedType = Mapped;
//! An alias to `Mapped&`.
using ReferenceType = Mapped&;
//! An alias to `Mapped*`.
using PointerType = Mapped*;
//! An alias to Handle; the key type used to associate a mapped value type.
using HandleType = Handle;
//! An alias to Allocator; the allocator used to allocate memory.
using AllocatorType = Allocator;
//! The type specification for the associated HandleDatabase.
using Database = HandleDatabase<Mapped, Handle, Allocator>;
//! @a Deprecated: Use MappedType instead.
using element_type = MappedType;
//! @a Deprecated: Use HandleType instead.
using handle_type = HandleType;
/**
* Default constructor. Produces an empty HandleRef.
*/
HandleRef() = default;
/**
* Attempts to atomically reference a Handle from the given @p database.
* @param database The HandleDatabase containing @p handle.
* @param handle The handle previously returned from HandleDatabase::createHandle(). Providing an invalid or
* previously-valid handle results in an empty HandleRef.
*/
HandleRef(Database& database, Handle handle) noexcept : BaseType(database, handle)
{
}
/**
* Explicitly adds a reference to any referenced handle and returns a HandleRef.
* @returns A HandleRef holding its own reference for the contained handle. May be empty if `*this` is empty.
*/
HandleRef clone() const noexcept
{
if (this->m_mapped)
this->m_database->addRef(this->m_mapped);
return HandleRef{ this->m_database, this->m_handle, this->m_mapped };
}
/**
* Dereferences and returns a pointer to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A pointer to the mapped type.
*/
PointerType operator->() noexcept
{
return get();
}
/**
* Dereferences and returns a const pointer to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A const pointer to the mapped type.
*/
PointerType operator->() const noexcept
{
return get();
}
/**
* Dereferences and returns a reference to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A reference to the mapped type.
*/
ReferenceType operator*() noexcept
{
CARB_ASSERT(get());
return *get();
}
/**
* Dereferences and returns a const reference to the mapped type.
* @warning Undefined behavior if `*this` is empty.
* @returns A const reference to the mapped type.
*/
ReferenceType operator*() const noexcept
{
CARB_ASSERT(get());
return *get();
}
/**
* Returns a pointer to the mapped type, or `nullptr` if empty.
* @returns A pointer to the mapped type or `nullptr` if empty.
*/
PointerType get() noexcept
{
return this->m_mapped;
}
/**
* Returns a const pointer to the mapped type, or `nullptr` if empty.
* @returns A const pointer to the mapped type or `nullptr` if empty.
*/
PointerType get() const noexcept
{
return this->m_mapped;
}
/**
* Swaps state with another HandleRef.
*/
void swap(HandleRef& rhs)
{
BaseType::swap(rhs);
}
private:
HandleRef(Database* db, Handle h, Mapped* m) noexcept : BaseType(db, h, m)
{
}
};
/**
* @a Deprecated: Use HandleRef instead.
*/
template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>>
using ScopedHandleRef = HandleRef<Mapped, Handle, Allocator>;
template <class Mapped, class Handle, class Allocator>
inline constexpr HandleDatabase<Mapped, Handle, Allocator>::HandleDatabase() noexcept
{
}
template <class Mapped, class Handle, class Allocator>
inline HandleDatabase<Mapped, Handle, Allocator>::~HandleDatabase()
{
// Make sure everything is removed from the free list before we destroy it
m_emo.m_free.popAll();
size_t leaks = 0;
for (size_t i = 0; i < CARB_COUNTOF(m_database); i++)
{
HandleData* handleData = m_database[i].exchange(nullptr, std::memory_order_relaxed);
if (!handleData)
break;
// Go through each entry and destruct any outstanding ones with a non-zero refcount
size_t const kBucketSize = size_t(1) << i;
for (size_t j = 0; j != kBucketSize; ++j)
{
Metadata meta = handleData[j].metadata.load(std::memory_order_relaxed);
if (meta.refCount != 0)
{
handleData[j].val.~Mapped();
++leaks;
}
AllocatorTraits::destroy(m_emo, handleData + j);
}
AllocatorTraits::deallocate(m_emo, handleData, kBucketSize);
}
if (leaks != 0)
{
CARB_LOG_WARN("%s: had %zu outstanding handle(s) at shutdown", CARB_PRETTY_FUNCTION, leaks);
}
}
template <class Mapped, class Handle, class Allocator>
inline auto HandleDatabase<Mapped, Handle, Allocator>::getHandleData(uint32_t index) const -> HandleData*
{
uint32_t bucketIndex, offsetInBucket;
indexToBucketAndOffset(index, bucketIndex, offsetInBucket);
if (bucketIndex >= CARB_COUNTOF(m_database))
{
return nullptr;
}
auto bucket = getDbIndex(bucketIndex, std::memory_order_acquire);
return bucket ? bucket + offsetInBucket : nullptr;
}
template <class Mapped, class Handle, class Allocator>
inline auto HandleDatabase<Mapped, Handle, Allocator>::getHandleData(const Mapped* mapped) const -> HandleData*
{
// HandleData must have val as the first member. This would prevent us from casting
// mapped to HandleData without using ugly pointer math otherwise.
// static assert using offsetof() is not possible due to HandleData having a non-standard-layout type.
auto pHandleData = reinterpret_cast<HandleData*>(const_cast<Mapped*>(mapped));
CARB_ASSERT(reinterpret_cast<intptr_t>(&pHandleData->val) - reinterpret_cast<intptr_t>(pHandleData) == 0);
return pHandleData;
}
template <class Mapped, class Handle, class Allocator>
inline auto HandleDatabase<Mapped, Handle, Allocator>::getDbIndex(size_t index, std::memory_order order) const
-> HandleData*
{
static HandleData* const kLocked = reinterpret_cast<HandleData*>(size_t(-1));
CARB_ASSERT(index < kBuckets);
// Spin briefly if the entry is locked
HandleData* bucket = m_database[index].load(order);
while (CARB_UNLIKELY(bucket == kLocked))
{
CARB_HARDWARE_PAUSE();
bucket = m_database[index].load(order);
}
return bucket;
}
template <class Mapped, class Handle, class Allocator>
inline bool HandleDatabase<Mapped, Handle, Allocator>::handleWasValid(Handle handle) const
{
HandleUnion hu(handle);
HandleData* pHandleData = getHandleData(hu.index);
if (pHandleData == nullptr)
{
return false;
}
Metadata meta = pHandleData->metadata.load(std::memory_order_acquire);
// The zero lifecycle count isn't used
if (hu.lifecycle == 0 || meta.lifecycle == 0)
{
return false;
}
// The kRolloverFlag value is always unset in hu, but possibly present in meta.lifecycle. However, this is still a
// valid comparison because if the kRolloverFlag is set in meta.lifecycle, it means that every possible value has
// been a valid handle at one point and the expression will always result in `true`.
return hu.lifecycle <= meta.lifecycle;
}
template <class Mapped, class Handle, class Allocator>
template <class... Args>
inline std::pair<Handle, Mapped*> HandleDatabase<Mapped, Handle, Allocator>::createHandle(Args&&... args)
{
HandleData* handleData = m_emo.m_free.pop();
if (!handleData)
handleData = expandDatabase();
CARB_ASSERT(handleData);
Metadata meta = handleData->metadata.load(std::memory_order_acquire);
CARB_ASSERT(((void*)std::addressof(handleData->metadata) == (void*)std::addressof(handleData->refCount)) &&
offsetof(Metadata, refCount) == 0);
meta.refCount = 1;
// Don't allow the 0 lifecycle.
meta.lifecycle++;
if ((meta.lifecycle & kLifecycleMask) == 0)
{
meta.lifecycle = 1 | kRolloverFlag;
}
uint32_t indexToAllocateFrom = handleData->index;
Mapped* p = new (std::addressof(handleData->val)) Mapped(std::forward<Args>(args)...);
handleData->metadata.store(meta, std::memory_order_release);
HandleUnion hu(indexToAllocateFrom, meta.lifecycle);
return std::make_pair(hu.handle, p);
}
template <class Mapped, class Handle, class Allocator>
inline Mapped* HandleDatabase<Mapped, Handle, Allocator>::tryAddRef(Handle handle)
{
HandleUnion hu(handle);
HandleData* pHandleData = getHandleData(hu.index);
if (pHandleData == nullptr)
{
return nullptr;
}
Metadata meta = pHandleData->metadata.load(std::memory_order_acquire);
for (;;)
{
if (meta.refCount == 0 || (meta.lifecycle & kLifecycleMask) != hu.lifecycle)
{
return nullptr;
}
Metadata desired = meta;
desired.refCount++;
if (pHandleData->metadata.compare_exchange_weak(
meta, desired, std::memory_order_release, std::memory_order_relaxed))
{
return std::addressof(pHandleData->val);
}
}
}
template <class Mapped, class Handle, class Allocator>
inline void HandleDatabase<Mapped, Handle, Allocator>::addRef(Handle handle)
{
Mapped* mapped = tryAddRef(handle);
CARB_FATAL_UNLESS(mapped != nullptr, "Attempt to addRef released handle");
}
template <class Mapped, class Handle, class Allocator>
inline void HandleDatabase<Mapped, Handle, Allocator>::addRef(Mapped* mapped)
{
HandleData* pHandleData = getHandleData(mapped);
// We're working with the Mapped type here, so if it's not valid we're in UB.
uint32_t prev = pHandleData->refCount.fetch_add(1, std::memory_order_relaxed);
CARB_CHECK((prev + 1) > 1); // no resurrection and no rollover
}
template <class Mapped, class Handle, class Allocator>
inline bool HandleDatabase<Mapped, Handle, Allocator>::release(Handle handle)
{
HandleUnion hu(handle);
HandleData* pHandleData = getHandleData(hu.index);
CARB_ASSERT(pHandleData);
if (pHandleData == nullptr)
{
return false;
}
Metadata meta = pHandleData->metadata.load(std::memory_order_acquire);
for (;;)
{
if (meta.refCount == 0 || (meta.lifecycle & kLifecycleMask) != hu.lifecycle)
{
CARB_ASSERT(0);
return false;
}
Metadata desired = meta;
bool released = --desired.refCount == 0;
if (CARB_LIKELY(pHandleData->metadata.compare_exchange_weak(
meta, desired, std::memory_order_release, std::memory_order_relaxed)))
{
if (released)
{
std::atomic_thread_fence(std::memory_order_acquire);
pHandleData->val.~Mapped();
pHandleData->index = hu.index;
m_emo.m_free.push(pHandleData);
}
return released;
}
}
}
template <class Mapped, class Handle, class Allocator>
inline bool HandleDatabase<Mapped, Handle, Allocator>::release(Mapped* mapped)
{
HandleData* pHandleData = getHandleData(mapped);
// We're working with the Mapped type here, so if it's not valid we're in UB.
uint32_t prev = pHandleData->refCount.fetch_sub(1, std::memory_order_release);
CARB_CHECK(prev >= 1); // No underflow
if (prev == 1)
{
// Released
std::atomic_thread_fence(std::memory_order_acquire);
pHandleData->val.~Mapped();
pHandleData->index = HandleUnion(getHandleFromValue(mapped)).index;
m_emo.m_free.push(pHandleData);
return true;
}
return false;
}
template <class Mapped, class Handle, class Allocator>
inline bool HandleDatabase<Mapped, Handle, Allocator>::releaseIfLastRef(Handle handle)
{
HandleUnion hu(handle);
HandleData* pHandleData = getHandleData(hu.index);
CARB_ASSERT(pHandleData);
if (pHandleData == nullptr)
{
return false;
}
Metadata meta = pHandleData->metadata.load(std::memory_order_acquire);
for (;;)
{
if (meta.refCount == 0 || (meta.lifecycle & kLifecycleMask) != hu.lifecycle)
{
CARB_ASSERT(0);
return false;
}
if (meta.refCount > 1)
{
return false;
}
Metadata desired = meta;
desired.refCount = 0;
if (CARB_LIKELY(pHandleData->metadata.compare_exchange_weak(
meta, desired, std::memory_order_release, std::memory_order_relaxed)))
{
std::atomic_thread_fence(std::memory_order_acquire);
pHandleData->val.~Mapped();
pHandleData->index = hu.index;
m_emo.m_free.push(pHandleData);
return true;
}
}
}
template <class Mapped, class Handle, class Allocator>
inline bool HandleDatabase<Mapped, Handle, Allocator>::releaseIfLastRef(Mapped* mapped)
{
HandleData* pHandleData = getHandleData(mapped);
// We're working with the Mapped type here, so if it's not valid we're in UB.
uint32_t refCount = pHandleData->refCount.load(std::memory_order_acquire);
for (;;)
{
CARB_CHECK(refCount != 0);
if (refCount > 1)
{
return false;
}
if (CARB_LIKELY(pHandleData->refCount.compare_exchange_weak(
refCount, 0, std::memory_order_release, std::memory_order_relaxed)))
{
std::atomic_thread_fence(std::memory_order_acquire);
pHandleData->val.~Mapped();
pHandleData->index = HandleUnion(getHandleFromValue(mapped)).index;
m_emo.m_free.push(pHandleData);
return true;
}
}
}
template <class Mapped, class Handle, class Allocator>
inline Mapped* HandleDatabase<Mapped, Handle, Allocator>::getValueFromHandle(Handle handle) const
{
HandleUnion hu(handle);
HandleData* pHandleData = getHandleData(hu.index);
if (pHandleData == nullptr)
{
return nullptr;
}
Metadata meta = pHandleData->metadata.load(std::memory_order_acquire);
return (meta.refCount != 0 && (meta.lifecycle & kLifecycleMask) == hu.lifecycle) ? std::addressof(pHandleData->val) :
nullptr;
}
template <class Mapped, class Handle, class Allocator>
inline Handle HandleDatabase<Mapped, Handle, Allocator>::getHandleFromValue(const Mapped* mapped) const
{
// Resolve mapped to the handle data
// We're working with the Mapped type here, so if it's not valid we're in UB.
HandleData* pHandleData = getHandleData(mapped);
// Start setting up the handle, but we don't know the index yet.
uint32_t lifecycle = pHandleData->metadata.load(std::memory_order_acquire).lifecycle;
// Find the index by searching all of the buckets.
for (uint32_t i = 0; i < kBuckets; ++i)
{
HandleData* p = getDbIndex(i, std::memory_order_acquire);
if (!p)
break;
size_t offset = size_t(pHandleData - p);
if (offset < (size_t(1) << i))
{
// Found the index!
uint32_t index = (uint32_t(1) << i) - 1 + uint32_t(offset);
return HandleUnion(index, lifecycle).handle;
}
}
// Given mapped doesn't exist in this HandleDatabase
CARB_CHECK(0);
return Handle{};
}
template <class Mapped, class Handle, class Allocator>
inline void HandleDatabase<Mapped, Handle, Allocator>::indexToBucketAndOffset(uint32_t index,
uint32_t& bucket,
uint32_t& offset)
{
// Bucket id
bucket = 31 - math::numLeadingZeroBits(index + 1);
offset = index + 1 - (1 << CARB_MIN(31u, bucket));
}
template <class Mapped, class Handle, class Allocator>
inline auto HandleDatabase<Mapped, Handle, Allocator>::expandDatabase() -> HandleData*
{
static HandleData* const kLocked = reinterpret_cast<HandleData*>(size_t(-1));
// Scan (right now O(n), but this is rare and n is small) for the first empty database.
size_t bucketToAllocateFrom;
for (bucketToAllocateFrom = 0; bucketToAllocateFrom != CARB_COUNTOF(m_database); bucketToAllocateFrom++)
{
HandleData* mem = m_database[bucketToAllocateFrom].load(std::memory_order_acquire);
for (;;)
{
while (mem == kLocked)
{
// Another thread is trying to allocate this. Try to pull from the free list until it stabilizes.
mem = m_emo.m_free.pop();
if (mem)
return mem;
mem = m_database[bucketToAllocateFrom].load(std::memory_order_acquire);
}
if (!mem)
{
// Try to lock it
if (m_database[bucketToAllocateFrom].compare_exchange_strong(
mem, kLocked, std::memory_order_release, std::memory_order_relaxed))
{
// Successfully locked
break;
}
// Continue if another thread has locked it
if (mem == kLocked)
continue;
// Failed to lock, but it's not locked anymore, so see if there's a free entry now
HandleData* hd = m_emo.m_free.pop();
if (hd)
return hd;
}
CARB_ASSERT(mem != kLocked);
break;
}
if (!mem)
break;
}
CARB_FATAL_UNLESS(bucketToAllocateFrom < CARB_COUNTOF(m_database), "Out of handles!");
uint32_t const allocateCount = 1 << bucketToAllocateFrom;
uint32_t const offset = allocateCount - 1;
HandleData* handleData = AllocatorTraits::allocate(m_emo, allocateCount);
// Set the indexes
for (uint32_t i = 0; i < allocateCount; ++i)
{
AllocatorTraits::construct(m_emo, handleData + i, offset + i);
}
// Add entries (after the first) to the free list
m_emo.m_free.push(handleData + 1, handleData + allocateCount);
// Overwrite the lock with the actual pointer now
HandleData* expect = m_database[bucketToAllocateFrom].exchange(handleData, std::memory_order_release);
CARB_ASSERT(expect == kLocked);
CARB_UNUSED(expect);
// Return the first entry that we reserved for the caller
AllocatorTraits::construct(m_emo, handleData, offset);
return handleData;
}
template <class Mapped, class Handle, class Allocator>
template <class Func>
inline void HandleDatabase<Mapped, Handle, Allocator>::forEachHandle(Func&& f) const
{
for (uint32_t i = 0; i < kBuckets; ++i)
{
// We are done once we encounter a null pointer
HandleData* data = getDbIndex(i, std::memory_order_acquire);
if (!data)
break;
uint32_t const bucketSize = 1 << i;
for (uint32_t j = 0; j != bucketSize; ++j)
{
Metadata meta = data[j].metadata.load(std::memory_order_acquire);
if (meta.refCount != 0)
{
// Valid handle
HandleUnion hu((bucketSize - 1) + j, meta.lifecycle);
// Call the functor
f(hu.handle, std::addressof(data[j].val));
}
}
}
}
template <class Mapped, class Handle, class Allocator>
inline size_t HandleDatabase<Mapped, Handle, Allocator>::clear()
{
size_t count = 0;
for (uint32_t i = 0; i != kBuckets; ++i)
{
HandleData* data = getDbIndex(i, std::memory_order_acquire);
if (!data)
break;
uint32_t const bucketSize = 1u << i;
for (uint32_t j = 0; j != bucketSize; ++j)
{
if (data[j].refCount.exchange(0, std::memory_order_release) != 0)
{
// Successfully set the refcount to 0. Destroy and add to the free list
std::atomic_thread_fence(std::memory_order_acquire);
++count;
data[j].val.~Mapped();
data[j].index = bucketSize - 1 + j;
m_emo.m_free.push(std::addressof(data[j]));
}
}
}
return count;
}
template <class Mapped, class Handle, class Allocator>
inline auto HandleDatabase<Mapped, Handle, Allocator>::makeScopedRef(Handle handle) -> HandleRefType
{
return HandleRef<Mapped, Handle, Allocator>(*this, handle);
}
template <class Mapped, class Handle, class Allocator>
inline auto HandleDatabase<Mapped, Handle, Allocator>::makeScopedRef(Handle handle) const -> ConstHandleRefType
{
return ConstHandleRef<Mapped, Handle, Allocator>(const_cast<HandleDatabase&>(*this), handle);
}
// Global operators.
/**
* Tests equality between HandleRef and `nullptr`.
* @param ref The HandleRef to test.
* @returns `true` if @p ref is empty; `false` otherwise.
*/
template <class Mapped, class Handle, class Allocator>
inline bool operator==(const HandleRef<Mapped, Handle, Allocator>& ref, std::nullptr_t)
{
return ref.get() == nullptr;
}
/**
* Tests equality between HandleRef and `nullptr`.
* @param ref The HandleRef to test.
* @returns `true` if @p ref is empty; `false` otherwise.
*/
template <class Mapped, class Handle, class Allocator>
inline bool operator==(std::nullptr_t, const HandleRef<Mapped, Handle, Allocator>& ref)
{
return ref.get() == nullptr;
}
/**
* Tests inequality between HandleRef and `nullptr`.
* @param ref The HandleRef to test.
* @returns `true` if @p ref is not empty; `false` otherwise.
*/
template <class Mapped, class Handle, class Allocator>
inline bool operator!=(const HandleRef<Mapped, Handle, Allocator>& ref, std::nullptr_t)
{
return ref.get() != nullptr;
}
/**
* Tests inequality between HandleRef and `nullptr`.
* @param ref The HandleRef to test.
* @returns `true` if @p ref is not empty; `false` otherwise.
*/
template <class Mapped, class Handle, class Allocator>
inline bool operator!=(std::nullptr_t, const HandleRef<Mapped, Handle, Allocator>& ref)
{
return ref.get() != nullptr;
}
} // namespace extras
} // namespace carb
CARB_IGNOREWARNING_MSC_POP
|
omniverse-code/kit/include/carb/extras/ArenaAllocator.h | // Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "FreeListAllocator.h"
#include <cstring>
namespace carb
{
namespace extras
{
/**
* Defines arena allocator where allocations are made very quickly, but that deallocations
* can only be performed in reverse order, or with the client code knowing a previous deallocation (say with
* deallocateAllFrom), automatically deallocates everything after it.
*
* @note Though named "ArenaAllocator", this is really more of a block/sequential allocator, not an arena allocator. If
* you desire to actually use an arena, see @ref carb::memory::ArenaAllocator. This class may be renamed in the future.
*
* It works by allocating large blocks and then cutting out smaller pieces as requested. If a piece of memory is
* deallocated, it either MUST be in reverse allocation order OR the subsequent allocations are implicitly
* deallocated too, and therefore accessing their memory is now undefined behavior. Allocations are made
* contiguously from the current block. If there is no space in the current block, the
* next block (which is unused) if available is checked. If that works, an allocation is made from the next block.
* If not a new block is allocated that can hold at least the allocation with required alignment.
*
* All memory allocated can be deallocated very quickly and without a client having to track any memory.
* All memory allocated will be freed on destruction - or with reset.
*
* A memory arena can have requests larger than the block size. When that happens they will just be allocated
* from the heap. As such 'oversized blocks' are seen as unusual and potentially wasteful they are deallocated
* when deallocateAll is called, whereas regular size blocks will remain allocated for fast subsequent allocation.
*
* It is intentional that blocks information is stored separately from the allocations that store the
* user data. This is so that alignment permitting, block allocations sizes can be passed directly to underlying
* allocator. For large power of 2 backing allocations this might mean a page/pages directly allocated by the OS for
* example. Also means better cache coherency when traversing blocks -> as generally they will be contiguous in memory.
*
* Also note that allocateUnaligned can be used for slightly faster aligned allocations. All blocks allocated internally
* are aligned to the blockAlignment passed to the constructor. If subsequent allocations (of any type) sizes are of
* that alignment or larger then no alignment fixing is required (because allocations are contiguous) and so
* 'allocateUnaligned' will return allocations of blockAlignment alignment.
*/
class ArenaAllocator
{
public:
/**
* The minimum alignment of the backing memory allocator.
*/
static const size_t kMinAlignment = sizeof(void*);
/**
* Constructor.
*/
ArenaAllocator()
{
// Mark as invalid so any alloc call will fail
m_blockAlignment = 0;
m_blockSize = 0;
// Set up as empty
m_blocks = nullptr;
_setCurrentBlock(nullptr);
m_blockFreeList.initialize(sizeof(Block), sizeof(void*), 16);
}
/**
* Constructor.
*
* @param blockSize The minimum block size (in bytes).
* @param blockAlignment The power 2 block alignment that all blocks must have.
*/
explicit ArenaAllocator(size_t blockSize, size_t blockAlignment = kMinAlignment)
{
_initialize(blockSize, blockAlignment);
}
/**
* ArenaAllocator is not copy-constructible.
*/
ArenaAllocator(const ArenaAllocator& rhs) = delete;
/**
* ArenaAllocator is not copyable.
*/
void operator=(const ArenaAllocator& rhs) = delete;
/**
* Destructor.
*/
~ArenaAllocator()
{
_deallocateBlocks();
}
/**
* Initialize the arena with specified block size and alignment.
*
* If the arena has been previously initialized will free and deallocate all memory.
*
* @param blockSize The minimum block size (in bytes).
* @param blockAlignment The power 2 block alignment that all blocks must have.
*/
void initialize(size_t blockSize, size_t blockAlignment = kMinAlignment);
/**
* Determines if an allocation is consistent with an allocation from this arena.
* The test cannot say definitively if this was such an allocation, because the exact details
* of each allocation is not kept.
*
* @param alloc The start of the allocation
* @param sizeInBytes The size of the allocation
* @return true if allocation could have been from this Arena
*/
bool isValid(const void* alloc, size_t sizeInBytes) const;
/**
* Allocate some memory of at least size bytes without having any specific alignment.
*
* Can be used for slightly faster *aligned* allocations if caveats in class description are met. The
* Unaligned, means the method will not enforce alignment - but a client call to allocateUnaligned can control
* subsequent allocations alignments via it's size.
*
* @param size The size of the allocation requested (in bytes and must be > 0).
* @return The allocation. Can be nullptr if backing allocator was not able to request required memory
*/
void* allocate(size_t size);
/**
* Allocate some aligned memory of at least size bytes
*
* @param size Size of allocation wanted (must be > 0).
* @param alignment Alignment of allocation - must be a power of 2.
* @return The allocation (or nullptr if unable to allocate). Will be at least 'alignment' alignment or better.
*/
void* allocateAligned(size_t size, size_t alignment);
/**
* Allocates a null terminated string.
*
* @param str A null-terminated string
* @return A copy of the string held on the arena
*/
const char* allocateString(const char* str);
/**
* Allocates a null terminated string.
*
* @param chars Pointer to first character
* @param charCount The amount of characters NOT including terminating 0.
* @return A copy of the string held on the arena.
*/
const char* allocateString(const char* chars, size_t charCount);
/**
* Allocate an element of the specified type.
*
* Note: Constructor for type is not executed.
*
* @return An allocation with correct alignment/size for the specified type.
*/
template <typename T>
T* allocate();
/**
* Allocate an array of a specified type.
*
* Note: Constructor for type is not executed.
*
* @param count The number of elements in the array
* @return Returns an allocation with correct alignment/size for the specified type.
*/
template <typename T>
T* allocateArray(size_t count);
/**
* Allocate an array of a specified type.
*
* @param count The number of elements in the array
* @return An allocation with correct alignment/size for the specified type. Contents is all zeroed.
*/
template <typename T>
T* allocateArray(size_t count, bool zeroMemory);
/**
* Allocate an array of a specified type, and copy array passed into it.
*
* @param arr. The array to copy from.
* @param count. The number of elements in the array.
* @return An allocation with correct alignment/size for the specified type. Contents is all zeroed.
*/
template <typename T>
T* allocateArrayAndCopy(const T* arr, size_t count);
/**
* Deallocate the last allocation.
*
* If data is not from the last allocation then the behavior is undefined.
*
* @param data The data allocation to free.
*/
void deallocateLast(void* data);
/**
* Deallocate this allocation and all remaining after it.
*
* @param dataStart The data allocation to free from and all remaining.
*/
void deallocateAllFrom(void* dataStart);
/**
* Deallocates all allocated memory. That backing memory will generally not be released so
* subsequent allocation will be fast, and from the same memory. Note though that 'oversize' blocks
* will be deallocated.
*/
void deallocateAll();
/**
* Resets to the initial state when constructed (and all backing memory will be deallocated)
*/
void reset();
/**
* Adjusts such that the next allocate will be at least to the block alignment.
*/
void adjustToBlockAlignment();
/**
* Gets the block alignment that is passed at initialization otherwise 0 an invalid block alignment.
*
* @return the block alignment
*/
size_t getBlockAlignment() const;
private:
struct Block
{
Block* m_next;
uint8_t* m_alloc;
uint8_t* m_start;
uint8_t* m_end;
};
void _initialize(size_t blockSize, size_t blockAlignment)
{
// Alignment must be a power of 2
CARB_ASSERT(((blockAlignment - 1) & blockAlignment) == 0);
// Must be at least sizeof(void*) in size, as that is the minimum the backing allocator will be
blockAlignment = (blockAlignment < kMinAlignment) ? kMinAlignment : blockAlignment;
// If alignment required is larger then the backing allocators then
// make larger to ensure when alignment correction takes place it will be aligned
if (blockAlignment > kMinAlignment)
{
blockSize += blockAlignment;
}
m_blockSize = blockSize;
m_blockAlignment = blockAlignment;
m_blocks = nullptr;
_setCurrentBlock(nullptr);
m_blockFreeList.initialize(sizeof(Block), sizeof(void*), 16);
}
void* _allocateAligned(size_t size, size_t alignment)
{
CARB_ASSERT(size);
// Can't be space in the current block -> so we can either place in next, or in a new block
_newCurrentBlock(size, alignment);
uint8_t* const current = m_current;
// If everything has gone to plan, must be space here...
CARB_ASSERT(current + size <= m_end);
m_current = current + size;
return current;
}
void _deallocateBlocks()
{
Block* currentBlock = m_blocks;
while (currentBlock)
{
// Deallocate the block
CARB_FREE(currentBlock->m_alloc);
// next block
currentBlock = currentBlock->m_next;
}
// Can deallocate all blocks to
m_blockFreeList.deallocateAll();
}
void _setCurrentBlock(Block* block)
{
if (block)
{
m_end = block->m_end;
m_start = block->m_start;
m_current = m_start;
}
else
{
m_start = nullptr;
m_end = nullptr;
m_current = nullptr;
}
m_currentBlock = block;
}
Block* _newCurrentBlock(size_t size, size_t alignment)
{
// Make sure init has been called (or has been set up in parameterized constructor)
CARB_ASSERT(m_blockSize > 0);
// Alignment must be a power of 2
CARB_ASSERT(((alignment - 1) & alignment) == 0);
// Alignment must at a minimum be block alignment (such if reused the constraints hold)
alignment = (alignment < m_blockAlignment) ? m_blockAlignment : alignment;
const size_t alignMask = alignment - 1;
// First try the next block (if there is one)
{
Block* next = m_currentBlock ? m_currentBlock->m_next : m_blocks;
if (next)
{
// Align could be done from the actual allocation start, but doing so would mean a pointer which
// didn't hit the constraint of being between start/end
// So have to align conservatively using start
uint8_t* memory = (uint8_t*)((size_t(next->m_start) + alignMask) & ~alignMask);
// Check if can fit block in
if (memory + size <= next->m_end)
{
_setCurrentBlock(next);
return next;
}
}
}
// The size of the block must be at least large enough to take into account alignment
size_t allocSize = (alignment <= kMinAlignment) ? size : (size + alignment);
// The minimum block size should be at least m_blockSize
allocSize = (allocSize < m_blockSize) ? m_blockSize : allocSize;
// Allocate block
Block* block = (Block*)m_blockFreeList.allocate();
if (!block)
{
return nullptr;
}
// Allocate the memory
uint8_t* alloc = (uint8_t*)CARB_MALLOC(allocSize);
if (!alloc)
{
m_blockFreeList.deallocate(block);
return nullptr;
}
// Do the alignment on the allocation
uint8_t* const start = (uint8_t*)((size_t(alloc) + alignMask) & ~alignMask);
// Setup the block
block->m_alloc = alloc;
block->m_start = start;
block->m_end = alloc + allocSize;
block->m_next = nullptr;
// Insert block into list
if (m_currentBlock)
{
// Insert after current block
block->m_next = m_currentBlock->m_next;
m_currentBlock->m_next = block;
}
else
{
// Add to start of the list of the blocks
block->m_next = m_blocks;
m_blocks = block;
}
_setCurrentBlock(block);
return block;
}
Block* _findBlock(const void* alloc, Block* endBlock = nullptr) const
{
const uint8_t* ptr = (const uint8_t*)alloc;
Block* block = m_blocks;
while (block != endBlock)
{
if (ptr >= block->m_start && ptr < block->m_end)
{
return block;
}
block = block->m_next;
}
return nullptr;
}
Block* _findPreviousBlock(Block* block)
{
Block* currentBlock = m_blocks;
while (currentBlock)
{
if (currentBlock->m_next == block)
{
return currentBlock;
}
currentBlock = currentBlock->m_next;
}
return nullptr;
}
uint8_t* m_start;
uint8_t* m_end;
uint8_t* m_current;
size_t m_blockSize;
size_t m_blockAlignment;
Block* m_blocks;
Block* m_currentBlock;
FreeListAllocator m_blockFreeList;
};
inline void ArenaAllocator::initialize(size_t blockSize, size_t blockAlignment)
{
_deallocateBlocks();
m_blockFreeList.reset();
_initialize(blockSize, blockAlignment);
}
inline bool ArenaAllocator::isValid(const void* data, size_t size) const
{
CARB_ASSERT(size);
uint8_t* ptr = (uint8_t*)data;
// Is it in current
if (ptr >= m_start && ptr + size <= m_current)
{
return true;
}
// Is it in a previous block?
Block* block = _findBlock(data, m_currentBlock);
return block && (ptr >= block->m_start && (ptr + size) <= block->m_end);
}
inline void* ArenaAllocator::allocate(size_t size)
{
// Align with the minimum alignment
const size_t alignMask = kMinAlignment - 1;
uint8_t* mem = (uint8_t*)((size_t(m_current) + alignMask) & ~alignMask);
if (mem + size <= m_end)
{
m_current = mem + size;
return mem;
}
else
{
return _allocateAligned(size, kMinAlignment);
}
}
inline void* ArenaAllocator::allocateAligned(size_t size, size_t alignment)
{
// Alignment must be a power of 2
CARB_ASSERT(((alignment - 1) & alignment) == 0);
// Align the pointer
const size_t alignMask = alignment - 1;
uint8_t* memory = (uint8_t*)((size_t(m_current) + alignMask) & ~alignMask);
if (memory + size <= m_end)
{
m_current = memory + size;
return memory;
}
else
{
return _allocateAligned(size, alignment);
}
}
inline const char* ArenaAllocator::allocateString(const char* str)
{
size_t size = ::strlen(str);
if (size == 0)
{
return "";
}
char* dst = (char*)allocate(size + 1);
std::memcpy(dst, str, size + 1);
return dst;
}
inline const char* ArenaAllocator::allocateString(const char* chars, size_t charsCount)
{
if (charsCount == 0)
{
return "";
}
char* dst = (char*)allocate(charsCount + 1);
std::memcpy(dst, chars, charsCount);
// Add null-terminating zero
dst[charsCount] = 0;
return dst;
}
template <typename T>
T* ArenaAllocator::allocate()
{
return reinterpret_cast<T*>(allocateAligned(sizeof(T), CARB_ALIGN_OF(T)));
}
template <typename T>
T* ArenaAllocator::allocateArray(size_t count)
{
return (count > 0) ? reinterpret_cast<T*>(allocateAligned(sizeof(T) * count, CARB_ALIGN_OF(T))) : nullptr;
}
template <typename T>
T* ArenaAllocator::allocateArray(size_t count, bool zeroMemory)
{
if (count > 0)
{
const size_t totalSize = sizeof(T) * count;
void* ptr = allocateAligned(totalSize, CARB_ALIGN_OF(T));
if (zeroMemory)
{
std::memset(ptr, 0, totalSize);
}
return reinterpret_cast<T*>(ptr);
}
return nullptr;
}
template <typename T>
T* ArenaAllocator::allocateArrayAndCopy(const T* arr, size_t count)
{
if (count > 0)
{
const size_t totalSize = sizeof(T) * count;
void* ptr = allocateAligned(totalSize, CARB_ALIGN_OF(T));
std::memcpy(ptr, arr, totalSize);
return reinterpret_cast<T*>(ptr);
}
return nullptr;
}
inline void ArenaAllocator::deallocateLast(void* data)
{
// See if it's in current block
uint8_t* ptr = (uint8_t*)data;
if (ptr >= m_start && ptr < m_current)
{
// Then just go back
m_current = ptr;
}
else
{
// Only called if not in the current block. Therefore can only be in previous
Block* prevBlock = _findPreviousBlock(m_currentBlock);
if (prevBlock == nullptr || (!(ptr >= prevBlock->m_start && ptr < prevBlock->m_end)))
{
CARB_ASSERT(!"Allocation not found");
return;
}
// Make the previous block the current
_setCurrentBlock(prevBlock);
// Make the current the alloc freed
m_current = ptr;
}
}
inline void ArenaAllocator::deallocateAllFrom(void* data)
{
// See if it's in current block, and is allocated (ie < m_cur)
uint8_t* ptr = (uint8_t*)data;
if (ptr >= m_start && ptr < m_current)
{
// If it's in current block, then just go back
m_current = ptr;
return;
}
// Search all blocks prior to current block
Block* block = _findBlock(data, m_currentBlock);
CARB_ASSERT(block);
if (!block)
{
return;
}
// Make this current block
_setCurrentBlock(block);
// Move the pointer to the allocations position
m_current = ptr;
}
inline void ArenaAllocator::deallocateAll()
{
Block** prev = &m_blocks;
Block* block = m_blocks;
while (block)
{
if (size_t(block->m_end - block->m_alloc) > m_blockSize)
{
// Oversized block so we need to free it and remove from the list
Block* nextBlock = block->m_next;
*prev = nextBlock;
// Free the backing memory
CARB_FREE(block->m_alloc);
// Free the block
m_blockFreeList.deallocate(block);
// prev stays the same, now working on next tho
block = nextBlock;
}
else
{
// Onto next
prev = &block->m_next;
block = block->m_next;
}
}
// Make the first current (if any)
_setCurrentBlock(m_blocks);
}
inline void ArenaAllocator::reset()
{
_deallocateBlocks();
m_blocks = nullptr;
_setCurrentBlock(nullptr);
}
inline void ArenaAllocator::adjustToBlockAlignment()
{
const size_t alignMask = m_blockAlignment - 1;
uint8_t* ptr = (uint8_t*)((size_t(m_current) + alignMask) & ~alignMask);
// Alignment might push beyond end of block... if so allocate a new block
// This test could be avoided if we aligned m_end, but depending on block alignment that might waste some space
if (ptr > m_end)
{
// We'll need a new block to make this alignment
_newCurrentBlock(0, m_blockAlignment);
}
else
{
// Set the position
m_current = ptr;
}
CARB_ASSERT(size_t(m_current) & alignMask);
}
inline size_t ArenaAllocator::getBlockAlignment() const
{
return m_blockAlignment;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Unicode.h | // Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "Utf8Parser.h"
#include <cstdint>
#include <string>
#if CARB_PLATFORM_LINUX
# include <iconv.h>
#else
# include <codecvt>
# include <locale>
#endif
namespace carb
{
namespace extras
{
/**
* Collection of Unicode conversion utilities.
*
* UTF-8 encoding is used throughout this code base. However, there will be cases when you interact with OS (Windows)
* or third party libraries (like glfw) where you need to convert to/from another representation. In those cases use the
* conversion utilities offered here - *don't roll your own.* We know it's tempting to use std::codecvt but it's not
* portable to all the operating systems we support (Tegra) and it will throw exceptions on range errors (which are
* surprisingly common) if you use the default constructors (which is what everybody does).
*
* If you need a facility that isn't offered here then please add it to this collection. Read more about the
* Unicode strategy employed in this code base at docs/Unicode.md.
*/
/**
* Failure message returned from convertUtf32ToUtf8 code point function, usually because of invalid input code point
*/
const std::string kCodePointToUtf8Failure = "[?]";
/** Flags to alter the behavior of convertUtf32ToUtf8(). */
using ConvertUtf32ToUtf8Flags = uint32_t;
/** When this flag is passed to convertUtf32ToUtf8(), the string returned on
* conversion failure will be @ref kCodePointToUtf8Failure.
* If this is flag is not passed, the UTF-8 encoding of U+FFFD (the Unicode
* replacement character) will be returned on conversion failure.
*/
constexpr ConvertUtf32ToUtf8Flags fUseLegacyFailureString = 0x01;
/**
* Convert a UTF-32 code point to UTF-8 encoded string
*
* @param utf32CodePoint The code point to convert, in UTF-32 encoding
* @param flags These alter the behavior of this function.
* @return The UTF-8 encoded version of utf32CodePoint.
* @return If the codepoint could not be converted to UTF-8, the returned value
* depends on @p flags.
* If @p flags contains @ref fUseLegacyFailureString, then @ref
* kCodePointToUtf8Failure will be returned; otherwise, U+FFFD encoded
* in UTF-8 is returned.
*/
inline std::string convertUtf32ToUtf8(uint32_t codePointUtf32, ConvertUtf32ToUtf8Flags flags = fUseLegacyFailureString)
{
char32_t u32Str[] = { codePointUtf32, '\0' };
std::string out = convertUtf32StringToUtf8(u32Str);
// if conversion fails, the string will just end early.
if (out.empty() && codePointUtf32 != 0)
{
return (flags & fUseLegacyFailureString) != 0 ? kCodePointToUtf8Failure : u8"\uFFFD";
}
return out;
}
#if CARB_PLATFORM_WINDOWS
/** A value that was returned by a past version of convertWideToUtf8() on failure.
* Current versions will insert U+FFFD on characters that failed to parse.
*/
const std::string kUnicodeToUtf8Failure = "[failure-converting-to-utf8]";
/** A value that was returned by a past version of convertUtf8ToWide() on failure.
* Current versions will insert U+FFFD on characters that failed to parse.
*/
const std::wstring kUnicodeToWideFailure = L"[failure-converting-to-wide]";
/**
* Converts a Windows wide string to UTF-8 string
* Do not use this function for Windows file path conversion! Instead, use extras::convertWindowsToCarbonitePath(const
* std::wstring& pathW) function for proper slashes handling and long file path support.
*
* @param wide Input string to convert, in Windows UTF16 encoding.
* @note U+FFFD is returned if an invalid Unicode sequence is encountered.
*/
inline std::string convertWideToUtf8(const wchar_t* wide)
{
return convertWideStringToUtf8(wide);
}
inline std::string convertWideToUtf8(const std::wstring& wide)
{
return convertWideStringToUtf8(wide);
}
/**
* Converts a UTF-8 encoded string to Windows wide string
* Do not use this function for Windows file path conversion! Instead, use extras::convertCarboniteToWindowsPath(const
* std::string& path) function for proper slashes handling and long file path support.
*
* @param utf8 Input string to convert, in UTF-8 encoding.
* @note U+FFFD is returned if an invalid Unicode sequence is encountered.
*/
inline std::wstring convertUtf8ToWide(const char* utf8)
{
return convertUtf8StringToWide(utf8);
}
inline std::wstring convertUtf8ToWide(const std::string& utf8)
{
return convertUtf8StringToWide(utf8);
}
class LocaleWrapper
{
public:
LocaleWrapper(const char* localeName)
{
locale = _create_locale(LC_ALL, localeName);
}
~LocaleWrapper()
{
_free_locale(locale);
}
_locale_t getLocale()
{
return locale;
}
private:
_locale_t locale;
};
inline auto _getSystemDefaultLocale()
{
static LocaleWrapper s_localeWrapper("");
return s_localeWrapper.getLocale();
}
/**
* Performs a case-insensitive comparison of wide strings in Unicode (Windows native) using system default locale.
*
* @param string1 First input string.
* @param string2 Second input string.
* @return < 0 if string1 less than string2,
* 0 if string1 identical to string2,
* > 0 if string1 greater than string2,
* INT_MAX on error.
*/
inline int compareWideStringsCaseInsensitive(const wchar_t* string1, const wchar_t* string2)
{
return _wcsicmp_l(string1, string2, _getSystemDefaultLocale());
}
inline int compareWideStringsCaseInsensitive(const std::wstring& string1, const std::wstring& string2)
{
return compareWideStringsCaseInsensitive(string1.c_str(), string2.c_str());
}
/**
* Converts wide string in Unicode (Windows native) to uppercase using system default locale.
*
* @param string Input string.
* @return Uppercase string.
*/
inline std::wstring convertWideStringToUppercase(const std::wstring& string)
{
std::wstring result = string;
_wcsupr_s_l(&result[0], result.size() + 1, _getSystemDefaultLocale());
return result;
}
/**
* Converts wide string in Unicode (Windows native) to uppercase using system default locale, in-place version.
*
* @param string Input and output string.
*/
inline void convertWideStringToUppercaseInPlace(std::wstring& string)
{
_wcsupr_s_l(&string[0], string.size() + 1, _getSystemDefaultLocale());
}
/**
* Converts wide string in Unicode (Windows native) to lowercase using system default locale.
*
* @param string Input string.
* @return Lowercase string.
*/
inline std::wstring convertWideStringToLowercase(const std::wstring& string)
{
std::wstring result = string;
_wcslwr_s_l(&result[0], result.size() + 1, _getSystemDefaultLocale());
return result;
}
/**
* Converts wide string in Unicode (Windows native) to lowercase using system default locale, in-place version.
*
* @param string Input and output string.
*/
inline void convertWideStringToLowercaseInPlace(std::wstring& string)
{
_wcslwr_s_l(&string[0], string.size() + 1, _getSystemDefaultLocale());
}
#endif
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/EnvironmentVariableParser.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Parses environment variables into map of key/value pairs
//
#pragma once
#include "../Defines.h"
#include "StringUtils.h"
#include "Unicode.h"
#include <cstring>
#include <map>
#include <string>
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#else
# ifndef DOXYGEN_BUILD
extern "C"
{
extern char** environ;
}
# endif
#endif
namespace carb
{
namespace extras
{
/**
* Parses environment variables into program options or environment variables
*/
class EnvironmentVariableParser
{
public:
/**
* Construct an environment parser looking for variables starting with @p prefix
*/
EnvironmentVariableParser(const char* prefix) : m_prefix(prefix)
{
}
/**
* Parse the environment. Variables starting with prefix given to constructor are separated
* into program options, whereas all others are parsed as normal environment variables
*/
void parse()
{
m_pathwiseOverrides.clear();
CARB_MSC_ONLY(parseForMsvc());
CARB_NOT_MSC(parseForOthers());
}
//! key/value pairs of the parsed environment variables
using Options = std::map<std::string, std::string>;
/**
* The map of program options that matched prefix.
* @return map of key/value options
*/
const Options& getOptions()
{
return m_pathwiseOverrides;
}
/**
* The map of all environment variables that did not the prefix.
* @return map of key/value environment variables
*/
const Options& getEnvVariables()
{
return m_envVariables;
}
private:
#if CARB_COMPILER_MSC
void parseForMsvc()
{
class EnvVarsBlockWatchdog
{
public:
EnvVarsBlockWatchdog()
{
m_envsBlock = GetEnvironmentStringsW();
}
~EnvVarsBlockWatchdog()
{
if (m_envsBlock)
{
FreeEnvironmentStringsW(m_envsBlock);
}
}
const wchar_t* getEnvsBlock()
{
return m_envsBlock;
}
private:
wchar_t* m_envsBlock = nullptr;
};
EnvVarsBlockWatchdog envVarsBlovkWatchdog;
const wchar_t* envsBlock = envVarsBlovkWatchdog.getEnvsBlock();
if (!envsBlock)
{
return;
}
const wchar_t* var = (LPWSTR)envsBlock;
while (*var)
{
std::string varUtf8 = carb::extras::convertWideToUtf8(var);
size_t equalSignPos = 0;
size_t varLen = (size_t)lstrlenW(var);
while (equalSignPos < varLen && var[equalSignPos] != L'=')
{
++equalSignPos;
}
var += varLen + 1;
if (equalSignPos == 0 || equalSignPos == varLen)
{
continue;
}
std::string varNameUtf8(varUtf8.c_str(), equalSignPos);
_processAndAddOption(varNameUtf8.c_str(), varUtf8.c_str() + equalSignPos + 1);
}
}
#else
void parseForOthers()
{
char** envsBlock = environ;
if (!envsBlock || !*envsBlock)
{
return;
}
while (*envsBlock)
{
size_t equalSignPos = 0;
const char* var = *envsBlock;
size_t varLen = (size_t)strlen(var);
while (equalSignPos < varLen && var[equalSignPos] != '=')
{
++equalSignPos;
}
++envsBlock;
if (equalSignPos == 0 || equalSignPos == varLen)
{
continue;
}
std::string varName(var, equalSignPos);
_processAndAddOption(varName.c_str(), var + equalSignPos + 1);
}
}
#endif
void _processAndAddOption(const char* varName, const char* varValue)
{
if (!m_prefix.empty() && startsWith(varName, m_prefix))
{
std::string path = varName + m_prefix.size();
for (size_t i = 0, pathLen = path.length(); i < pathLen; ++i)
{
// TODO: WRONG, must be utf8-aware replacement
if (path[i] == '_')
path[i] = '/';
}
m_pathwiseOverrides.insert(std::make_pair(path.c_str(), varValue));
}
else
{
CARB_ASSERT(varName);
CARB_ASSERT(varValue);
m_envVariables[varName] = varValue;
}
}
// Path-wise overrides
Options m_pathwiseOverrides;
// Explicit env variables
Options m_envVariables;
std::string m_prefix;
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/Path.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Path interpretation utilities.
#pragma once
#include "../Defines.h"
#include "../logging/Log.h"
#include "../../omni/String.h"
#include <functional>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace carb
{
namespace extras
{
// Forward declarations
class Path;
inline Path operator/(const Path& left, const Path& right);
inline Path operator+(const Path& left, const Path& right);
inline Path operator+(const Path& left, const char* right);
inline Path operator+(const Path& left, const std::string& right);
inline Path operator+(const Path& left, const omni::string& right);
inline Path operator+(const char* left, const Path& right);
inline Path operator+(const std::string& left, const Path& right);
inline Path operator+(const omni::string& left, const Path& right);
/**
* Path objects are used for filesystem path manipulations.
*
* All paths are UTF-8 encoded using forward slash as path separator.
*
* Note: the class supports implicit casting to a "std::string" and explicit cast to
* a "const char *" pointer
*/
class Path
{
public:
//! A special value depending on the context, such as "all remaining characters".
static constexpr size_t npos = std::string::npos;
static_assert(npos == size_t(-1), "Invalid assumption");
//--------------------------------------------------------------------------------------
// Constructors/destructor and assignment operations
/**
* Default constructor.
*/
Path() = default;
/**
* Constructs a Path from a counted char array containing a UTF-8 encoded string.
*
* The Path object converts all backslashes to forward slashes.
*
* @param path a pointer to the UTF-8 string data
* @param pathLen the size of \p path in bytes
*/
Path(const char* path, size_t pathLen)
{
if (path && pathLen)
{
m_pathString.assign(path, pathLen);
_sanitizePath();
}
}
/**
* Constructs a Path from a NUL-terminated char buffer containing a UTF-8 encoded string.
*
* The Path object converts all backslashes to forward slashes.
*
* @param path a pointer to the UTF-8 string data
*/
Path(const char* path)
{
if (path)
{
m_pathString = path;
}
_sanitizePath();
}
/**
* Constructs a Path from a `std::string` containing a UTF-8 encoded string.
*
* The Path object converts all backslashes to forward slashes.
*
* @param path The source string
*/
Path(std::string path) : m_pathString(std::move(path))
{
_sanitizePath();
}
/**
* Constructs a Path from an \ref omni::string containing a UTF-8 encoded string.
*
* The Path object converts all backslashes to forward slashes.
*
* @param path The source string
*/
Path(const omni::string& path) : m_pathString(path.c_str(), path.length())
{
_sanitizePath();
}
/**
* Copy constructor. Copies a Path from another Path.
*
* @param other The other path to copy from
*/
Path(const Path& other) : m_pathString(other.m_pathString)
{
}
/**
* Move constructor. Moves a Path from another Path, which is left in a valid but unspecified state.
*
* @param other The other path to move from
*/
Path(Path&& other) noexcept : m_pathString(std::move(other.m_pathString))
{
}
/**
* Copy-assign operator. Copies another Path into *this.
*
* @param other The other path to copy from
* @returns `*this`
*/
Path& operator=(const Path& other)
{
m_pathString = other.m_pathString;
return *this;
}
/**
* Move-assign operator. Moves another Path into *this and leaves the other path in a valid but unspecified state.
*
* @param other The other path to move from
* @returns `*this`
*/
Path& operator=(Path&& other) noexcept
{
m_pathString = std::move(other.m_pathString);
return *this;
}
/**
* Destructor
*/
~Path() = default;
//--------------------------------------------------------------------------------------
// Getting a string representation of the internal data
/**
* Gets the string representation of the path.
*
* @returns a copy of the UTF-8 string representation of the internal data
*/
std::string getString() const
{
return m_pathString;
}
/**
* Implicit conversion operator to a string representation.
*
* @returns a copy of the UTF-8 string representation of the internal data
*/
operator std::string() const
{
return m_pathString;
}
/**
* Gets the string data owned by this Path.
*
* @warning the return value from this function should not be retained, and may be dangling after `*this` is
* modified in any way.
*
* @return pointer to the start of the path data
*/
const char* c_str() const noexcept
{
return m_pathString.c_str();
}
/**
* Gets the string data owned by this Path.
*
* @warning the return value from this function should not be retained, and may be dangling after `*this` is
* modified in any way.
*
* @return pointer to the start of the path data
*/
const char* getStringBuffer() const noexcept
{
return m_pathString.c_str();
}
/**
* Enables outputting this Path to a stream object.
*
* @param os the stream to output to
* @param path the Path to output
*/
CARB_NO_DOC(friend) // Sphinx 3.5.4 complains that this is an invalid C++ declaration, so ignore `friend` for docs.
std::ostream& operator<<(std::ostream& os, const Path& path)
{
os << path.m_pathString;
return os;
}
/**
* Explicit conversion operator to get the string data owned by this Path.
*
* @warning the return value from this function should not be retained, and may be dangling after `*this` is
* modified in any way.
*
* @return pointer to the start of the path data
*/
explicit operator const char*() const noexcept
{
return getStringBuffer();
}
//--------------------------------------------------------------------------------------
// Path operations
// Compare operations
/**
* Equality comparison
* @param other a Path to compare against `*this` for equality
* @returns `true` if `*this` and \p other are equal; `false` otherwise
*/
bool operator==(const Path& other) const noexcept
{
return m_pathString == other.m_pathString;
}
/**
* Equality comparison
* @param other a `std::string` to compare against `*this` for equality
* @returns `true` if `*this` and \p other are equal; `false` otherwise
*/
bool operator==(const std::string& other) const noexcept
{
return m_pathString == other;
}
/**
* Equality comparison
* @param other a NUL-terminated char buffer to compare against `*this` for equality
* @returns `true` if `*this` and \p other are equal; `false` otherwise (or if \p other is `nullptr`)
*/
bool operator==(const char* other) const noexcept
{
if (other == nullptr)
{
return false;
}
return m_pathString == other;
}
/**
* Inequality comparison
* @param other a Path to compare against `*this` for inequality
* @returns `true` if `*this` and \p other are not equal; `false` otherwise
*/
bool operator!=(const Path& other) const noexcept
{
return !(*this == other);
}
/**
* Inequality comparison
* @param other a `std::string` to compare against `*this` for inequality
* @returns `true` if `*this` and \p other are not equal; `false` otherwise
*/
bool operator!=(const std::string& other) const noexcept
{
return !(*this == other);
}
/**
* Inequality comparison
* @param other a NUL-terminated char buffer to compare against `*this` for inequality
* @returns `true` if `*this` and \p other are not equal; `false` otherwise (or if \p other is `nullptr`)
*/
bool operator!=(const char* other) const noexcept
{
return !(*this == other);
}
/**
* Gets the length of the path
*
* @returns the length of the path string data in bytes
*/
size_t getLength() const noexcept
{
return m_pathString.size();
}
/**
* Gets the length of the path
*
* @returns the length of the path string data in bytes
*/
size_t length() const noexcept
{
return m_pathString.size();
}
/**
* Gets the length of the path
*
* @returns the length of the path string data in bytes
*/
size_t size() const noexcept
{
return m_pathString.size();
}
/**
* Clears current path
*
* @returns `*this`
*/
Path& clear()
{
m_pathString.clear();
return *this;
}
/**
* Checks if the path is an empty string
*
* @returns `true` if the path contains at least one character; `false` otherwise
*/
bool isEmpty() const noexcept
{
return m_pathString.empty();
}
/**
* Checks if the path is an empty string
*
* @returns `true` if the path contains at least one character; `false` otherwise
*/
bool empty() const noexcept
{
return m_pathString.empty();
}
/**
* Returns the filename component of the path, or an empty path object if there is no filename.
*
* Example: given `C:/foo/bar.txt`, this function would return `bar.txt`.
*
* @return The path object representing the filename
*/
Path getFilename() const
{
size_t offset = _getFilenameOffset();
if (offset == npos)
return {};
return Path(Sanitized, m_pathString.substr(offset));
}
/**
* Returns the extension of the filename component of the path, including period (.), or an empty path object.
*
* Example: given `C:/foo/bar.txt`, this function would return `.txt`.
*
* @return The path object representing the extension
*/
Path getExtension() const
{
size_t ext = _getExtensionOffset();
if (ext == npos)
return {};
return Path(Sanitized, m_pathString.substr(ext));
}
/**
* Returns the path to the parent directory, or an empty path object if there is no parent.
*
* Example: given `C:/foo/bar.txt`, this function would return `C:/foo`.
*
* @return The path object representing the parent directory
*/
Path getParent() const;
/**
* Returns the filename component of the path stripped of the extension, or an empty path object if there is no
* filename.
*
* Example: given `C:/foo/bar.txt`, this function would return `bar`.
*
* @return The path object representing the stem
*/
Path getStem() const
{
size_t offset = _getFilenameOffset();
if (offset == npos)
return {};
size_t ext = _getExtensionOffset();
CARB_ASSERT(ext == npos || ext >= offset);
// If ext is npos, `ext - offset` results in the full filename since there is no extension
return Path(Sanitized, m_pathString.substr(offset, ext - offset));
}
/**
* Returns the root name in the path.
*
* Example: given `C:/foo/bar.txt`, this function would return `C:`.
* Example: given `//server/share`, this function would return `//server`.
*
* @return The path object representing the root name
*/
Path getRootName() const
{
size_t rootNameEnd = _getRootNameEndOffset();
if (rootNameEnd == npos)
{
return {};
}
return Path(Sanitized, m_pathString.substr(0, rootNameEnd));
}
/**
* Returns the relative part of the path (the part after optional root name and root directory).
*
* Example: given `C:/foo/bar.txt`, this function would return `foo/bar.txt`.
* Example: given `//server/share/foo.txt`, this function would return `share/foo.txt`.
*
* @return The path objects representing the relative part of the path
*/
Path getRelativePart() const
{
size_t relativePart = _getRelativePartOffset();
if (relativePart == npos)
{
return {};
}
return Path(Sanitized, m_pathString.substr(relativePart));
}
/**
* Returns the root directory if it's present in the path.
*
* Example: given `C:/foo/bar.txt`, this function would return `/`.
* Example: given `foo/bar.txt`, this function would return `` (empty Path).
*
* @note This function will only ever return an empty path or a forward slash.
*
* @return The path object representing the root directory
*/
Path getRootDirectory() const
{
constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110
return hasRootDirectory() ? Path(Sanitized, std::string(&kForwardSlashChar_, 1)) : Path();
}
/**
* Checks if the path has a root directory
*
* @return `true` if \ref getRootDirectory() would return `/`; `false` if \ref getRootDirectory() would return an
* empty string.
*/
bool hasRootDirectory() const noexcept
{
size_t rootDirectoryEnd = _getRootDirectoryEndOffset();
if (rootDirectoryEnd == npos)
{
return false;
}
size_t rootNameEnd = _getRootNameEndOffset();
if (rootNameEnd == rootDirectoryEnd)
{
return false;
}
return true;
}
/**
* Returns the root of the path: the root name and root directory if they are present.
*
* Example: given `C:/foo/bar.txt`, this function would return `C:/`.
*
* @return The path object representing the root of the path
*/
Path getRoot() const
{
size_t rootDirectoryEnd = _getRootDirectoryEndOffset();
if (rootDirectoryEnd == npos)
{
return {};
}
return Path(Sanitized, m_pathString.substr(0, rootDirectoryEnd));
}
/**
* A helper function to append another path after *this and return as a new object.
*
* @note Unlike \ref join(), this function concatenates two Path objects without a path separator between them.
*
* @param toAppend the Path to append to `*this`
* @return a new Path object that has `*this` appended with \p toAppend.
*/
Path concat(const Path& toAppend) const
{
if (isEmpty())
{
return toAppend;
}
if (toAppend.isEmpty())
{
return *this;
}
std::string total;
total.reserve(m_pathString.length() + toAppend.m_pathString.length());
total.append(m_pathString);
total.append(toAppend.m_pathString);
return Path(Sanitized, std::move(total));
}
/**
* A helper function to append another path after *this with a separator if necessary and return as a new object.
*
* @param toJoin the Path object to append to `*this`
* @returns a new Path object that has `*this` followed by a separator (if one is not already present at the end of
* `*this` or the beginning of \p toJoin), followed by \p toJoin
*/
Path join(const Path& toJoin) const;
/**
* Appends a path to *this with a separator if necessary.
*
* @note Unlike \ref join(), `*this` is modified by this function.
*
* @param path the Path to append to `*this`
* @returns `*this`
*/
Path& operator/=(const Path& path)
{
return *this = *this / path;
}
/**
* Appends a path to *this without adding a separator.
*
* @note Unlike \ref concat(), `*this` is modified by this function.
*
* @param path The Path to append to `*this`
* @returns `*this`
*/
Path& operator+=(const Path& path)
{
return *this = *this + path;
}
/**
* Replaces the current file extension with the given extension.
*
* @param newExtension the new extension to use
*
* @returns `*this`
*/
Path& replaceExtension(const Path& newExtension);
/**
* Normalizes *this as an absolute path and returns as a new Path object.
*
* @warning This function does NOT make an absolute path using the CWD as a root. You need to use
* \ref carb::filesystem::IFileSystem to get the current working directory and pass it to this function if desired.
*
* @note If `*this` is already an absolute path as determined by \ref isAbsolute(), \p root is ignored.
*
* @param root The root Path to prepend to `*this`
* @return A new Path object representing the constructed absolute path
*/
Path getAbsolute(const Path& root = Path()) const
{
if (isAbsolute() || root.isEmpty())
{
return this->getNormalized();
}
return root.join(*this).getNormalized();
}
/**
* Returns the result of the normalization of the current path as a new path
*
* Example: given `C:/foo/./bar/../bat.txt`, this function would return `C:/foo/bat.txt`.
*
* @return A new Path object representing the normalized current path
*/
Path getNormalized() const;
/**
* Normalizes current path in place
*
* @note Unlike \ref getNormalized(), `*this` is modified by this function.
*
* Example: given `C:/foo/./bar/../bat.txt`, this function would change `*this` to contain `C:/foo/bat.txt`.
*
* @returns `*this`
*/
Path& normalize()
{
return *this = getNormalized();
}
/**
* Checks if the current path is an absolute path.
*
* @returns `true` if the current path is an absolute path; `false` otherwise.
*/
bool isAbsolute() const noexcept;
/**
* Checks if the current path is a relative path.
*
* Effectively, `!isAbsolute()`.
*
* @return `true` if the current path is a relative path; `false` otherwise.
*/
bool isRelative() const
{
return !isAbsolute();
}
/**
* Returns current path made relative to a given base as a new Path object.
*
* @note The paths are not normalized prior to the operation.
*
* @param base the base path
*
* @return an empty path if it's impossible to match roots (different root names, different states of being
* relative/absolute with a base path, not having a root directory while the base has it), otherwise a non-empty
* relative path
*/
Path getRelative(const Path& base) const noexcept;
private:
static constexpr char kDotChar = '.';
static constexpr char kForwardSlashChar = '/';
static constexpr char kColonChar = ':';
struct Sanitized_t
{
};
constexpr static Sanitized_t Sanitized{};
Path(Sanitized_t, std::string s) : m_pathString(std::move(s))
{
// Pre-sanitized, so no need to do it again
}
enum class PathTokenType
{
Slash,
RootName,
Dot,
DotDot,
Name
};
// Helper function to parse next path token from `[bufferStart, bufferEnd)` (bufferEnd is an off-the-end pointer).
// On success returns pointer immediately after the token data and returns token type in the
// resultType. On failure returns nullptr and `resultType` is unchanged.
// Note: it doesn't determine if a Name is a RootName. (RootName is added to enum for convenience)
static const char* _getTokenEnd(const char* bufferBegin, const char* bufferEnd, PathTokenType& resultType)
{
if (bufferBegin == nullptr || bufferEnd == nullptr || bufferEnd <= bufferBegin)
{
return nullptr;
}
// Trying to find the next slash
constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110
const char* tokenEnd = std::find(bufferBegin, bufferEnd, kForwardSlashChar_);
// If found a slash as the first symbol then return pointer to the data after it
if (tokenEnd == bufferBegin)
{
resultType = PathTokenType::Slash;
return tokenEnd + 1;
}
// If no slash found we consider all passed data as a single token
if (!tokenEnd)
{
tokenEnd = bufferEnd;
}
const size_t tokenSize = tokenEnd - bufferBegin;
if (tokenSize == 1 && *bufferBegin == kDotChar)
{
resultType = PathTokenType::Dot;
}
else if (tokenSize == 2 && bufferBegin[0] == kDotChar && bufferBegin[1] == kDotChar)
{
resultType = PathTokenType::DotDot;
}
else
{
resultType = PathTokenType::Name;
}
return tokenEnd;
}
/**
* Helper function to find the pointer to the start of the filename
*/
size_t _getFilenameOffset() const noexcept
{
if (isEmpty())
{
return npos;
}
// Find the last slash
size_t offset = m_pathString.rfind(kForwardSlashChar);
if (offset == npos)
{
// Not empty, so no slash means only filename
return 0;
}
// If the slash is the end, no filename
if ((offset + 1) == m_pathString.length())
{
return npos;
}
return offset + 1;
}
/**
* Helper function to find the pointer to the start of the extension
*/
size_t _getExtensionOffset() const noexcept
{
size_t filename = _getFilenameOffset();
if (filename == npos)
{
return npos;
}
size_t dot = m_pathString.rfind(kDotChar);
// No extension if:
// - No dot in filename portion (dot not found or last dot proceeds filename)
// - filename ends with a dot
if (dot == npos || dot < filename || dot == (m_pathString.length() - 1))
{
return npos;
}
// If the only dot found starts the filename, we don't consider that an extension
return dot == filename ? npos : dot;
}
/**
* Helper function to find the pointer to the end of the root name (the pointer just after the end of the root name)
*/
size_t _getRootNameEndOffset() const noexcept
{
if (isEmpty())
{
return npos;
}
if (m_pathString.length() < 2)
{
return 0;
}
#if CARB_PLATFORM_WINDOWS
// Check if the path starts with a drive letter and colon (e.g. "C:/...")
if (m_pathString.at(1) == kColonChar && std::isalpha(m_pathString.at(0)))
{
return 2;
}
#endif
// Check if the path is a UNC path (e.g. "//server/location/...")
// This simple check is two slashes and not a slash
if (m_pathString.length() >= 3 && m_pathString.at(0) == kForwardSlashChar &&
m_pathString.at(1) == kForwardSlashChar && m_pathString.at(2) != kForwardSlashChar)
{
// Find the next slash
size_t offset = m_pathString.find(kForwardSlashChar, 3);
return offset == npos ? m_pathString.length() : offset;
}
return 0;
}
/**
* Helper function to get the pointer to the start of the relative part of the path
*/
size_t _getRelativePartOffset(size_t rootNameEnd = npos) const noexcept
{
size_t offset = rootNameEnd != npos ? rootNameEnd : _getRootNameEndOffset();
if (offset == npos)
return npos;
// Find the first non-slash character
constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110
return m_pathString.find_first_not_of(&kForwardSlashChar_, offset, 1);
}
/**
* Helper function to find the pointer to the end of the root directory (the pointer just after the end of the root
* directory)
*/
size_t _getRootDirectoryEndOffset() const noexcept
{
size_t rootNameEnd = _getRootNameEndOffset();
size_t relativePart = _getRelativePartOffset(rootNameEnd);
if (relativePart != rootNameEnd)
{
if (rootNameEnd >= m_pathString.length())
{
return rootNameEnd;
}
return rootNameEnd + 1;
}
return rootNameEnd;
}
// Patching paths in the constructors (using external string data) if needed
void _sanitizePath()
{
#if CARB_PLATFORM_WINDOWS
constexpr char kBackwardSlashChar = '\\';
// changing the backward slashes for Windows to forward ones
for (char& c : m_pathString)
{
if (c == kBackwardSlashChar)
{
c = kForwardSlashChar;
}
}
#endif
}
std::string m_pathString;
};
/**
* Concatenation operator
* @see Path::concat()
* @param left a Path
* @param right a Path
* @returns `left.concat(right)`
*/
inline Path operator+(const Path& left, const Path& right)
{
return left.concat(right);
}
/**
* Concatenation operator
* @see Path::concat()
* @param left a Path
* @param right a NUL-terminated char buffer representing a path
* @returns `left.concat(right)`
*/
inline Path operator+(const Path& left, const char* right)
{
return left.concat(right);
}
/**
* Concatenation operator
* @see Path::concat()
* @param left a Path
* @param right a `std::string` representing a path
* @returns `left.concat(right)`
*/
inline Path operator+(const Path& left, const std::string& right)
{
return left.concat(right);
}
/**
* Concatenation operator
* @see Path::concat()
* @param left a Path
* @param right an \ref omni::string representing a path
* @returns `left.concat(right)`
*/
inline Path operator+(const Path& left, const omni::string& right)
{
return left.concat(right);
}
/**
* Concatenation operator
* @see Path::concat()
* @param left a NUL-terminated char buffer representing a path
* @param right a Path
* @returns `Path(left).concat(right)`
*/
inline Path operator+(const char* left, const Path& right)
{
return Path(left).concat(right);
}
/**
* Concatenation operator
* @see Path::concat()
* @param left a `std::string` representing a path
* @param right a Path
* @returns `Path(left).concat(right)`
*/
inline Path operator+(const std::string& left, const Path& right)
{
return Path(left).concat(right);
}
/**
* Concatenation operator
* @see Path::concat()
* @param left an \ref omni::string representing a path
* @param right a Path
* @returns `Path(left).concat(right)`
*/
inline Path operator+(const omni::string& left, const Path& right)
{
return Path(left).concat(right);
}
/**
* Join operator
*
* Performs a Path::join() operation on two Path paths.
* @param left a Path
* @param right a Path
* @returns `left.join(right)`
*/
inline Path operator/(const Path& left, const Path& right)
{
return left.join(right);
}
/**
* Helper function to get a Path object representing parent directory for the provided string representation of a path.
* @see Path::getParent()
* @param path a `std::string` representation of a path
* @returns `Path(path).getParent()`
*/
inline Path getPathParent(std::string path)
{
return Path(std::move(path)).getParent();
}
/**
* Helper function to get a Path object representing the extension part of the provided string representation of a path.
* @see Path::getExtension()
* @param path a `std::string` representation of a path
* @returns `Path(path).getExtension()`
*/
inline Path getPathExtension(std::string path)
{
return Path(std::move(path)).getExtension();
}
/**
* Helper function to get a Path object representing the stem part of the provided string representation of a path.
* @see Path::getStem()
* @param path a `std::string` representation of a path
* @returns `Path(path).getStem()`
*/
inline Path getPathStem(std::string path)
{
return Path(std::move(path)).getStem();
}
/**
* Helper function to calculate a relative path from a provided path and a base path.
* @see Path::getRelative()
* @param path a `std::string` representation of a path
* @param base a `std::string` representation of the base path
* @returns `Path(path).getRelative(base)`
*/
inline Path getPathRelative(std::string path, std::string base)
{
return Path(std::move(path)).getRelative(Path(std::move(base)));
}
/**
* Equality operator.
* @param left a `std::string` representation of a Path
* @param right a Path
* @returns `true` if the paths are equal; `false` otherwise
*/
inline bool operator==(const std::string& left, const Path& right)
{
return right == left;
}
/**
* Equality operator.
* @param left a NUL-terminated char buffer representation of a Path
* @param right a Path
* @returns `true` if the paths are equal; `false` otherwise
*/
inline bool operator==(const char* left, const Path& right)
{
return right == left;
}
/**
* Inequality operator.
* @param left a `std::string` representation of a Path
* @param right a Path
* @returns `true` if the paths are not equal; `false` otherwise
*/
inline bool operator!=(const std::string& left, const Path& right)
{
return right != left;
}
/**
* Inequality operator.
* @param left a NUL-terminated char buffer representation of a Path
* @param right a Path
* @returns `true` if the paths are not equal; `false` otherwise
*/
inline bool operator!=(const char* left, const Path& right)
{
return right != left;
}
////////////////////////////////////////////////////////////////////////////////////////////
// Implementations of large public functions
////////////////////////////////////////////////////////////////////////////////////////////
inline Path Path::getParent() const
{
size_t parentPathEnd = _getFilenameOffset();
if (parentPathEnd == npos)
parentPathEnd = m_pathString.length();
size_t slashesDataStart = 0;
if (hasRootDirectory())
{
slashesDataStart += _getRootDirectoryEndOffset();
}
while (parentPathEnd > slashesDataStart && m_pathString.at(parentPathEnd - 1) == kForwardSlashChar)
{
--parentPathEnd;
}
if (parentPathEnd == 0)
{
return {};
}
return Path(Sanitized, m_pathString.substr(0, parentPathEnd));
}
inline Path Path::join(const Path& joinedPart) const
{
if (isEmpty())
{
return joinedPart;
}
if (joinedPart.isEmpty())
{
return *this;
}
const bool needSeparator =
(m_pathString.back() != kForwardSlashChar) && (joinedPart.m_pathString.front() != kForwardSlashChar);
std::string joined;
joined.reserve(m_pathString.length() + joinedPart.m_pathString.length() + (needSeparator ? 1 : 0));
joined.assign(m_pathString);
if (needSeparator)
joined.push_back(kForwardSlashChar);
joined.append(joinedPart.m_pathString);
return Path(Sanitized, std::move(joined));
}
inline Path& Path::replaceExtension(const Path& newExtension)
{
CARB_ASSERT(std::addressof(newExtension) != this);
// Erase the current extension
size_t ext = _getExtensionOffset();
if (ext != npos)
{
m_pathString.erase(ext);
}
// If the new extension is empty, we're done
if (newExtension.isEmpty())
{
return *this;
}
// Append a dot if there isn't one in the new extension
if (newExtension.m_pathString.front() != kDotChar)
{
m_pathString.push_back(kDotChar);
}
// Append new extension
m_pathString.append(newExtension.m_pathString);
return *this;
}
inline Path Path::getNormalized() const
{
if (isEmpty())
{
return {};
}
enum class NormalizePartType
{
Slash,
RootName,
RootSlash,
Dot,
DotDot,
Name,
Error
};
struct ParsedPathPartDescription
{
NormalizePartType type;
const char* data;
size_t size;
ParsedPathPartDescription(const char* partData, size_t partSize, PathTokenType partType)
: data(partData), size(partSize)
{
switch (partType)
{
case PathTokenType::Slash:
type = NormalizePartType::Slash;
break;
case PathTokenType::RootName:
type = NormalizePartType::RootName;
break;
case PathTokenType::Dot:
type = NormalizePartType::Dot;
break;
case PathTokenType::DotDot:
type = NormalizePartType::DotDot;
break;
case PathTokenType::Name:
type = NormalizePartType::Name;
break;
default:
type = NormalizePartType::Error;
CARB_LOG_ERROR("Invalid internal token state while normalizing a path");
CARB_ASSERT(false);
break;
}
}
ParsedPathPartDescription(const char* partData, size_t partSize, NormalizePartType partType)
: type(partType), data(partData), size(partSize)
{
}
};
std::vector<ParsedPathPartDescription> resultPathTokens;
size_t prevTokenEndOffset = _getRootDirectoryEndOffset();
const char* prevTokenEnd = prevTokenEndOffset == npos ? nullptr : m_pathString.data() + prevTokenEndOffset;
const char* pathDataStart = m_pathString.data();
const size_t pathDataLength = getLength();
if (prevTokenEnd && prevTokenEnd > pathDataStart)
{
// Adding the root name and the root directory as different elements
const char* possibleSlashPos = prevTokenEnd - 1;
if (*possibleSlashPos == kForwardSlashChar)
{
if (possibleSlashPos > pathDataStart)
{
resultPathTokens.emplace_back(
pathDataStart, static_cast<size_t>(possibleSlashPos - pathDataStart), PathTokenType::RootName);
}
constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110
resultPathTokens.emplace_back(&kForwardSlashChar_, 1, NormalizePartType::RootSlash);
}
else
{
resultPathTokens.emplace_back(
pathDataStart, static_cast<size_t>(prevTokenEnd - pathDataStart), PathTokenType::RootName);
}
}
else
{
prevTokenEnd = pathDataStart;
}
bool alreadyNormalized = true;
const char* bufferEnd = pathDataStart + pathDataLength;
PathTokenType curTokenType = PathTokenType::Name;
for (const char* curTokenEnd = _getTokenEnd(prevTokenEnd, bufferEnd, curTokenType); curTokenEnd != nullptr;
prevTokenEnd = curTokenEnd, curTokenEnd = _getTokenEnd(prevTokenEnd, bufferEnd, curTokenType))
{
switch (curTokenType)
{
case PathTokenType::Slash:
if (resultPathTokens.empty() || resultPathTokens.back().type == NormalizePartType::Slash ||
resultPathTokens.back().type == NormalizePartType::RootSlash)
{
// Skip if we already have a slash at the end
alreadyNormalized = false;
continue;
}
break;
case PathTokenType::Dot:
// Just skip it
alreadyNormalized = false;
continue;
case PathTokenType::DotDot:
if (resultPathTokens.empty())
{
break;
}
// Check if the previous element is a part of the root name (even without a slash) and skip dot-dot in
// such case
if (resultPathTokens.back().type == NormalizePartType::RootName ||
resultPathTokens.back().type == NormalizePartType::RootSlash)
{
alreadyNormalized = false;
continue;
}
if (resultPathTokens.size() > 1)
{
CARB_ASSERT(resultPathTokens.back().type == NormalizePartType::Slash);
const NormalizePartType tokenTypeBeforeSlash = resultPathTokens[resultPathTokens.size() - 2].type;
// Remove <name>/<dot-dot> pattern
if (tokenTypeBeforeSlash == NormalizePartType::Name)
{
resultPathTokens.pop_back(); // remove the last slash
resultPathTokens.pop_back(); // remove the last named token
alreadyNormalized = false;
continue; // and we skip the addition of the dot-dot
}
}
break;
case PathTokenType::Name:
// No special processing needed
break;
default:
CARB_LOG_ERROR("Invalid internal state while normalizing the path {%s}", getStringBuffer());
CARB_ASSERT(false);
alreadyNormalized = false;
continue;
}
resultPathTokens.emplace_back(prevTokenEnd, static_cast<size_t>(curTokenEnd - prevTokenEnd), curTokenType);
}
if (resultPathTokens.empty())
{
constexpr static auto kDotChar_ = kDotChar; // CC-1110
return Path(Sanitized, std::string(&kDotChar_, 1));
}
else if (resultPathTokens.back().type == NormalizePartType::Slash && resultPathTokens.size() > 1)
{
// Removing the trailing slash for special cases like "./" and "../"
const size_t indexOfTokenBeforeSlash = resultPathTokens.size() - 2;
const NormalizePartType typeOfTokenBeforeSlash = resultPathTokens[indexOfTokenBeforeSlash].type;
if (typeOfTokenBeforeSlash == NormalizePartType::Dot || typeOfTokenBeforeSlash == NormalizePartType::DotDot)
{
resultPathTokens.pop_back();
alreadyNormalized = false;
}
}
if (alreadyNormalized)
{
return *this;
}
size_t totalSize = 0;
for (auto& token : resultPathTokens)
totalSize += token.size;
std::string joined;
joined.reserve(totalSize);
for (auto& token : resultPathTokens)
joined.append(token.data, token.size);
return Path(Sanitized, std::move(joined));
}
inline bool Path::isAbsolute() const noexcept
{
#if CARB_POSIX
return !isEmpty() && m_pathString[0] == kForwardSlashChar;
#elif CARB_PLATFORM_WINDOWS
// Drive root (D:/abc) case. This is the only position where : is allowed on windows. Checking for separator is
// important, because D:temp.txt is a relative path on windows.
const char* pathDataStart = m_pathString.data();
const size_t pathDataLength = getLength();
if (pathDataLength > 2 && pathDataStart[1] == kColonChar && pathDataStart[2] == kForwardSlashChar)
return true;
// Drive letter (D:) case
if (pathDataLength == 2 && pathDataStart[1] == kColonChar)
return true;
// extended drive letter path (ie: prefixed with "//./D:").
if (pathDataLength > 4 && pathDataStart[0] == kForwardSlashChar && pathDataStart[1] == kForwardSlashChar &&
pathDataStart[2] == kDotChar && pathDataStart[3] == kForwardSlashChar)
{
// at least a drive name was specified.
if (pathDataLength > 6 && pathDataStart[5] == kColonChar)
{
// a drive plus an absolute path was specified (ie: "//./d:/abc") => succeed.
if (pathDataStart[6] == kForwardSlashChar)
return true;
// a drive and relative path was specified (ie: "//./d:temp.txt") => fail. We need to
// specifically fail here because this path would also get picked up by the generic
// special path check below and report success erroneously.
else
return false;
}
// requesting the full drive volume (ie: "//./d:") => report absolute to match behavior
// in the "d:" case above.
if (pathDataLength == 6 && pathDataStart[5] == kColonChar)
return true;
}
// check for special paths. This includes all windows paths that begin with "\\" (converted
// to Unix path separators for our purposes). This class of paths includes extended path
// names (ie: prefixed with "\\?\"), device names (ie: prefixed with "\\.\"), physical drive
// paths (ie: prefixed with "\\.\PhysicalDrive<n>"), removable media access (ie: "\\.\X:")
// COM ports (ie: "\\.\COM*"), and UNC paths (ie: prefixed with "\\servername\sharename\").
//
// Note that it is not necessarily sufficient to get absolute vs relative based solely on
// the "//" prefix here without needing to dig further into the specific name used and what
// it actually represents. For now, we'll just assume that device, drive, volume, and
// port names will not be used here and treat it as a UNC path. Since all extended paths
// and UNC paths must always be absolute, this should hold up at least for those. If a
// path for a drive, volume, or device is actually passed in here, it will still be treated
// as though it were an absolute path. The results of using such a path further may be
// undefined however.
if (pathDataLength > 2 && pathDataStart[0] == kForwardSlashChar && pathDataStart[1] == kForwardSlashChar &&
pathDataStart[2] != kForwardSlashChar)
return true;
return false;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
inline Path Path::getRelative(const Path& base) const noexcept
{
// checking if the operation is possible
if (isAbsolute() != base.isAbsolute() || (!hasRootDirectory() && base.hasRootDirectory()) ||
getRootName() != base.getRootName())
{
return {};
}
PathTokenType curPathTokenType = PathTokenType::RootName;
size_t curPathTokenEndOffset = _getRootDirectoryEndOffset();
const char* curPathTokenEnd = curPathTokenEndOffset == npos ? nullptr : m_pathString.data() + curPathTokenEndOffset;
const char* curPathTokenStart = curPathTokenEnd;
const char* curPathEnd = m_pathString.data() + m_pathString.length();
PathTokenType basePathTokenType = PathTokenType::RootName;
size_t basePathTokenEndOffset = base._getRootDirectoryEndOffset();
const char* basePathTokenEnd =
basePathTokenEndOffset == npos ? nullptr : base.m_pathString.data() + basePathTokenEndOffset;
const char* basePathEnd = base.m_pathString.data() + base.m_pathString.length();
// finding the first mismatch
for (;;)
{
curPathTokenStart = curPathTokenEnd;
curPathTokenEnd = _getTokenEnd(curPathTokenEnd, curPathEnd, curPathTokenType);
const char* baseTokenStart = basePathTokenEnd;
basePathTokenEnd = _getTokenEnd(basePathTokenEnd, basePathEnd, basePathTokenType);
if (!curPathTokenEnd || !basePathTokenEnd)
{
// Checking if both are null
if (curPathTokenEnd == basePathTokenEnd)
{
constexpr static auto kDotChar_ = kDotChar; // CC-1110
return Path(Sanitized, std::string(&kDotChar_, 1));
}
break;
}
if (curPathTokenType != basePathTokenType ||
!std::equal(curPathTokenStart, curPathTokenEnd, baseTokenStart, basePathTokenEnd))
{
break;
}
}
int requiredDotDotCount = 0;
while (basePathTokenEnd)
{
if (basePathTokenType == PathTokenType::DotDot)
{
--requiredDotDotCount;
}
else if (basePathTokenType == PathTokenType::Name)
{
++requiredDotDotCount;
}
basePathTokenEnd = _getTokenEnd(basePathTokenEnd, basePathEnd, basePathTokenType);
}
if (requiredDotDotCount < 0)
{
return {};
}
if (requiredDotDotCount == 0 && !curPathTokenEnd)
{
constexpr static auto kDotChar_ = kDotChar; // CC-1110
return Path(Sanitized, std::string(&kDotChar_, 1));
}
const size_t leftoverCurPathSymbols = curPathTokenEnd != nullptr ? curPathEnd - curPathTokenStart : 0;
constexpr static char kDotDotString[] = "..";
constexpr static size_t kDotDotStrlen = CARB_COUNTOF(kDotDotString) - 1;
const size_t requiredResultSize = ((1 /* '/' */) + (kDotDotStrlen)) * requiredDotDotCount + leftoverCurPathSymbols;
Path result;
result.m_pathString.reserve(requiredResultSize);
if (requiredDotDotCount > 0)
{
result.m_pathString.append(kDotDotString, kDotDotStrlen);
--requiredDotDotCount;
for (int i = 0; i < requiredDotDotCount; ++i)
{
result.m_pathString.push_back(kForwardSlashChar);
result.m_pathString.append(kDotDotString, kDotDotStrlen);
}
}
bool needsSeparator = !result.m_pathString.empty();
while (curPathTokenEnd)
{
if (curPathTokenType != PathTokenType::Slash)
{
if (CARB_LIKELY(needsSeparator))
{
result.m_pathString += kForwardSlashChar;
}
else
{
needsSeparator = true;
}
result.m_pathString.append(curPathTokenStart, curPathTokenEnd - curPathTokenStart);
}
curPathTokenStart = curPathTokenEnd;
curPathTokenEnd = _getTokenEnd(curPathTokenEnd, curPathEnd, curPathTokenType);
}
return result;
}
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/SharedMemory.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides a helper class to manage a block of shared memory.
*/
#pragma once
#include "../Defines.h"
#include "../Framework.h"
#include "../cpp/Optional.h"
#include "../extras/ScopeExit.h"
#include "../logging/Log.h"
#include "../process/Util.h"
#include "Base64.h"
#include "StringSafe.h"
#include "Unicode.h"
#include <cstddef>
#include <utility>
#if CARB_POSIX
# include <sys/file.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <sys/syscall.h>
# include <sys/types.h>
# include <cerrno>
# include <fcntl.h>
# include <semaphore.h>
# include <unistd.h>
# if CARB_PLATFORM_LINUX
# include <linux/limits.h> // NAME_MAX
# elif CARB_PLATFORM_MACOS
# include <sys/posix_shm.h>
# endif
#elif CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#endif
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Common namespace for extra helper functions and classes. */
namespace extras
{
#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
namespace detail
{
# if CARB_POSIX
constexpr int kAllReadWrite = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
inline constexpr const char* getGlobalSemaphoreName()
{
// Don't change this as it is completely ABI breaking to do so.
return "/carbonite-sharedmemory";
}
inline void probeSharedMemory()
{
// Probe with a shm_open() call prior to locking the mutex. If the object compiling this does not link librt.so
// then an abort can happen below, but while we have the semaphore locked. Since this is a system-wide
// semaphore, it can leave this code unable to run in the future. Run shm_open here to make sure that it is
// available; if not, an abort will occur but not while we have the system-wide semaphore locked.
shm_open("", 0, 0);
}
class NamedSemaphore
{
public:
NamedSemaphore(const char* name, bool unlinkOnClose = false) : m_name(name), m_unlinkOnClose(unlinkOnClose)
{
m_sema = sem_open(name, O_CREAT, carb::extras::detail::kAllReadWrite, 1);
CARB_FATAL_UNLESS(m_sema, "Failed to create/open shared semaphore {%d/%s}", errno, strerror(errno));
# if CARB_PLATFORM_LINUX
// sem_open() is masked by umask(), so force the permissions with chmod().
// NOTE: This assumes that named semaphores are under /dev/shm and are prefixed with sem. This is not ideal,
// but there does not appear to be any means to translate a sem_t* to a file descriptor (for fchmod())
// or a path.
// NOTE: sem_open() is also affected by umask() on mac, but unfortunately semaphores on mac are not backed
// by the filesystem and can therefore not have their permissions modified after creation.
size_t len = m_name.length() + 12;
char* buf = CARB_STACK_ALLOC(char, len + 1);
extras::formatString(buf, len + 1, "/dev/shm/sem.%s", name + 1); // Skip leading /
chmod(buf, detail::kAllReadWrite);
# endif
}
~NamedSemaphore()
{
int result = sem_close(m_sema);
CARB_ASSERT(result == 0, "Failed to close sema {%d/%s}", errno, strerror(errno));
CARB_UNUSED(result);
if (m_unlinkOnClose)
{
sem_unlink(m_name.c_str());
}
}
bool try_lock()
{
int val = CARB_RETRY_EINTR(sem_trywait(m_sema));
CARB_FATAL_UNLESS(val == 0 || errno == EAGAIN, "sem_trywait() failed {%d/%s}", errno, strerror(errno));
return val == 0;
}
void lock()
{
int result;
# if CARB_PLATFORM_LINUX
auto printMessage = [](const char* format, ...) {
va_list args;
char buffer[1024];
va_start(args, format);
formatStringV(buffer, CARB_COUNTOF(buffer), format, args);
va_end(args);
if (g_carbLogFn && g_carbLogLevel <= logging::kLevelWarn)
{
CARB_LOG_WARN("%s", buffer);
}
else
{
fputs(buffer, stderr);
}
};
constexpr int32_t kTimeoutInSeconds = 5;
struct timespec abstime;
clock_gettime(CLOCK_REALTIME, &abstime);
abstime.tv_sec += kTimeoutInSeconds;
// Since these are global semaphores and a process can crash with them in a bad state, wait for a period of time
// then log so that we have an entry of what's wrong.
result = CARB_RETRY_EINTR(sem_timedwait(m_sema, &abstime));
CARB_FATAL_UNLESS(result == 0 || errno == ETIMEDOUT, "sem_timedwait() failed {%d/%s}", errno, strerror(errno));
if (result == -1 && errno == ETIMEDOUT)
{
printMessage(
"Waiting on global named semaphore %s has taken more than 5 seconds. It may be in a stuck state. "
"You may have to delete /dev/shm/sem.%s and restart the application.",
m_name.c_str(), m_name.c_str() + 1);
CARB_FATAL_UNLESS(
CARB_RETRY_EINTR(sem_wait(m_sema)) == 0, "sem_wait() failed {%d/%s}", errno, strerror(errno));
}
# elif CARB_PLATFORM_MACOS
// mac doesn't support sem_timedwait() and doesn't offer any other named semaphore API
// either. For now we'll just do a blocking wait to attempt to acquire the semaphore.
// If needed, we can add support for the brief wait before warning of a potential hang
// like linux does. It would go something along these lines:
// * spawn a thread or schedule a task to send a SIGUSR2 signal to this thread after
// the given timeout.
// * start an infinite wait on this thread.
// * if SIGUSR2 arrives on this thread and interrupts the infinite wait, print the
// hang warning message then drop into another infinite wait like linux does.
//
// Spawning a new thread for each wait operation here is likely a little heavy handed
// though, especially if there ends up being a lot of contention on this semaphore.
// The alternative would be to have a single shared thread that could handle timeouts
// for multiple other threads.
result = CARB_RETRY_EINTR(sem_wait(m_sema)); // CC-641 to add hang detection
CARB_FATAL_UNLESS(result == 0, "sem_timedwait() failed {%d/%s}", errno, strerror(errno));
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
}
void unlock()
{
CARB_FATAL_UNLESS(CARB_RETRY_EINTR(sem_post(m_sema)) == 0, "sem_post() failed {%d/%s}", errno, strerror(errno));
}
CARB_PREVENT_COPY_AND_MOVE(NamedSemaphore);
private:
sem_t* m_sema;
std::string m_name;
bool m_unlinkOnClose;
};
# endif
} // namespace detail
#endif
/** A utility helper class to provide shared memory access to one or more processes. The shared
* memory area is named so that it can be opened by another process or component using the same
* name. Once created, views into the shared memory region can be created. Each successfully
* created view will unmap the mapped region once the view object is deleted. This object and
* any created view objects exist independently from each other - the ordering of destruction
* of each does not matter. The shared memory region will exist in the system until the last
* reference to it is released through destruction.
*
* A shared memory region must be mapped into a view before it can be accessed in memory. A
* new view can be created with the createView() function as needed. As long as one SharedMemory
* object still references the region, it can still be reopened by another call to open(). Each
* view object maps the region to a different location in memory. The view's mapped address will
* remain valid as long as the view object exists. Successfully creating a new view object
* requires that the mapping was successful and that the mapped memory is valid. The view object
* can be wrapped in a smart pointer such as std::unique_ptr<> if needed to manage its lifetime.
* A view object should never be copied (byte-wise or otherwise).
*
* A view can also be created starting at non-zero offsets into the shared memory region. This
* is useful for only mapping a small view of a very large shared memory region into the memory
* space. Multiple views of the same shared memory region may be created simultaneously.
*
* When opening a shared memory region, an 'open token' must be acquired first. This token can
* be retrieved from any other shared memory region object that either successfully created or
* opened the region using getOpenToken(). This token can then be transmitted to any other
* client through some means to be used to open the same region. The open token data can be
* retrieved as a base64 encoded string for transmission to other processes. The target process
* can then create its own local open token from the base64 string using the constructor for
* SharedMemory::OpenToken. Open tokens can also be passed around within the same process or
* through an existing shared memory region as needed by copying, moving, or assigning it to
* another object.
*
* @note On Linux, this requires that the host app be linked with the "rt" and "pthread" system
* libraries. This can be done by adding 'links { "rt", "pthread" }' to the premake script
* or adding the "-lrt -lpthread" option to the build command line.
*/
class SharedMemory
{
public:
/** An opaque token object used to open an existing SHM region or to retrieve from a newly
* created SHM region to pass to another client to open it. A token is only valid if it
* contains data for a shared memory region that is currently open. It will cause open()
* to fail if it is not valid however.
*/
class OpenToken
{
public:
/** Constructor: initializes an empty token. */
OpenToken() : m_data(nullptr), m_base64(nullptr), m_size(0)
{
}
/** Constructor: creates a new open token from a base64 encoded string.
*
* @param[in] base64 A base64 encoded data blob containing the open token information.
* This may be received through any means from another token. This
* string must be null terminated. This may not be `nullptr` or an
* empty string.
*
* @remarks This will create a new open token from a base64 encoded data blob received
* from another open token. Both the base64 and decoded representations will
* be stored. Only the base64 representation will be able to be retrieved
* later. No validation will be done on the token data until it is passed to
* SharedMemory::open().
*/
OpenToken(const char* base64) : m_data(nullptr), m_base64(nullptr), m_size(0)
{
Base64 converter(Base64::Variant::eFilenameSafe);
size_t size;
size_t inSize;
if (base64 == nullptr || base64[0] == 0)
return;
inSize = strlen(base64);
m_base64 = new (std::nothrow) char[inSize + 1];
if (m_base64 != nullptr)
memcpy(m_base64, base64, (inSize + 1) * sizeof(char));
size = converter.getDecodeOutputSize(inSize);
m_data = new (std::nothrow) uint8_t[size];
if (m_data != nullptr)
m_size = converter.decode(base64, inSize, m_data, size);
}
/** Copy constructor: copies an open token from another one.
*
* @param[in] token The open token to be copied. This does not necessarily need to
* be a valid token.
*/
OpenToken(const OpenToken& token) : m_data(nullptr), m_base64(nullptr), m_size(0)
{
*this = token;
}
/** Move constructor: moves an open token from another one to this one.
*
* @param[inout] token The open token to be moved from. The data in this token will
* be stolen into this object and the source token will be cleared
* out.
*/
OpenToken(OpenToken&& token) : m_data(nullptr), m_base64(nullptr), m_size(0)
{
*this = std::move(token);
}
~OpenToken()
{
clear();
}
/** Validity check operator.
*
* @returns `true` if this object contains token data.
* @returns `false` if this object was not successfully constructed or does not contain
* any actual token data.
*/
explicit operator bool() const
{
return isValid();
}
/** Validity check operator.
*
* @returns `true` if this object does not contain any token data.
* @returns `false` if this object contains token data.
*
*/
bool operator!() const
{
return !isValid();
}
/** Token equality comparison operator.
*
* @param[in] token The token to compare this one to.
* @returns `true` if the other token contains the same data this one does.
* @returns `false` if the other token contains different data from this one.
*/
bool operator==(const OpenToken& token) const
{
if (m_size == 0 && token.m_size == 0)
return true;
if (m_size != token.m_size)
return false;
if (m_data == nullptr || token.m_data == nullptr)
return false;
return memcmp(m_data, token.m_data, m_size) == 0;
}
/** Token inequality comparison operator.
*
* @param[in] token The token to compare this one to.
* @returns `true` if the other token contains different data from this one.
* @returns `false` if the other token contains the same data this one does.
*/
bool operator!=(const OpenToken& token) const
{
return !(*this == token);
}
/** Copy assignment operator.
*
* @param[in] token The token to be copied.
* @returns A reference to this object.
*/
OpenToken& operator=(const OpenToken& token)
{
if (this == &token)
return *this;
clear();
if (token.m_data == nullptr)
return *this;
m_data = new (std::nothrow) uint8_t[token.m_size];
if (m_data != nullptr)
{
memcpy(m_data, token.m_data, token.m_size);
m_size = token.m_size;
}
return *this;
}
/** Move assignment operator.
*
* @param[inout] token The token to be moved from. This source object will have its
* data token into this object, and the source will be cleared.
* @returns A reference to this object.
*/
OpenToken& operator=(OpenToken&& token)
{
if (this == &token)
return *this;
clear();
m_size = token.m_size;
m_data = token.m_data;
m_base64 = token.m_base64;
token.m_size = 0;
token.m_data = nullptr;
token.m_base64 = nullptr;
return *this;
}
/** Retrieves the token data in base64 encoding.
*
* @returns The token data encoded as a base64 string. This will always be null
* terminated. This token data string will be valid as long as this object
* still exists. If the caller needs the data to persist, the returned
* string must be copied.
* @returns `nullptr` if this token doesn't contain any data or memory could not be
* allocated to hold the base64 encoded string.
*/
const char* getBase64Token()
{
if (m_base64 != nullptr)
return m_base64;
if (m_size == 0)
return nullptr;
Base64 converter(Base64::Variant::eFilenameSafe);
size_t size;
size = converter.getEncodeOutputSize(m_size);
m_base64 = new (std::nothrow) char[size];
if (m_base64 == nullptr)
return nullptr;
converter.encode(m_data, m_size, m_base64, size);
return m_base64;
}
protected:
/** Constructor: initializes a new token with a specific data block.
*
* @param[in] tokenData The data to be copied into the new token. This may not be
* `nullptr`.
* @param[in] size The size of the @p tokenData block in bytes.
* @returns No return value.
*/
OpenToken(const void* tokenData, size_t size) : m_data(nullptr), m_base64(nullptr), m_size(0)
{
if (size == 0)
return;
m_data = new (std::nothrow) uint8_t[size];
if (m_data != nullptr)
{
memcpy(m_data, tokenData, size);
m_size = size;
}
}
/** Tests if this token is valid.
*
* @returns `true` if this token contains data. Returns `false` otherwise.
*/
bool isValid() const
{
return m_data != nullptr && m_size > 0;
}
/** Retrieves the specific token data from this object.
*
* @returns The token data contained in this object.
*/
uint8_t* getToken() const
{
return reinterpret_cast<uint8_t*>(m_data);
}
/** Retrieves the size in bytes of the token data in this object.
*
* @returns The size of the token data in bytes. Returns `0` if this object doesn't
* contain any token data.
*/
size_t getSize() const
{
return m_size;
}
/** Clears the contents of this token object.
*
* @returns No return value.
*
* @remarks This clears out the contents of this object. Upon return, the token will
* no longer be considered valid and can no longer be used to open an existing
* shared memory object.
*/
void clear()
{
if (m_data != nullptr)
delete[] m_data;
if (m_base64 != nullptr)
delete[] m_base64;
m_size = 0;
m_data = nullptr;
m_base64 = nullptr;
}
/** The raw binary data for the token. This will be `nullptr` if the token does not
* contain any data.
*/
uint8_t* m_data;
/** The base64 encoded version of this token's data. This will be `nullptr` if no base64
* data has been retrieved from this object and it was created from a source other than
* a base64 string.
*/
char* m_base64;
/** The size of the binary data blob @ref m_data in bytes. */
size_t m_size;
friend class SharedMemory;
};
/** Flag to indicate that a unique region name should be generated from the given base name
* in create(). This will allow the call to be more likely to succeed even if a region
* with the same base name already exists in the system. Note that using this flag will
* lead to a slightly longer open token being generated.
*/
static constexpr uint32_t fCreateMakeUnique = 0x00000001;
/**
* Flag to indicate that failure should not be reported as an error log.
*/
static constexpr uint32_t fQuiet = 0x00000002;
/**
* Flag to indicate that no mutexes should be locked during this operation.
* @warning Use of this flag could have interprocess and thread safety issues! Use with utmost caution!
* @note Currently only Linux is affected by this flag.
*/
static constexpr uint32_t fNoMutexLock = 0x00000004;
/** Names for the different ways a mapping region can be created and accessed. */
enum class AccessMode
{
/** Use the default memory access mode for the mapping. When this is specified to create
* a view, the same access permissions as were used when creating the shared memory
* region will be used. For example, if the SHM region is created as read-only, creating
* a view with the default memory access will also be read-only. The actual access mode
* that was granted can be retrieved from the View::getAccessMode() function after the
* view is created.
*/
eDefault,
/** Open or access the shared memory area as read-only. This access mode cannot be used
* to create a new SHM area. This can be used to create a view of any shared memory
* region however.
*/
eReadOnly,
/** Create, open, or access the shared memory area as read-write. This access mode must
* be used when creating a new shared memory region. It may also be used when opening
* a shared memory region, or creating a view of a shared memory region that was opened
* as read-write. If this is used to create a view on a SHM region that was opened as
* read-only, the creation will fail.
*/
eReadWrite,
};
/** Constructor: initializes a new shared memory manager object. This will not point to any
* block of memory.
*/
SharedMemory()
{
m_token = nullptr;
m_access = AccessMode::eDefault;
// collect the system page size and allocation granularity information.
#if CARB_PLATFORM_WINDOWS
m_handle.handleWin32 = nullptr;
CARBWIN_SYSTEM_INFO si;
GetSystemInfo((LPSYSTEM_INFO)&si);
m_pageSize = si.dwPageSize;
m_allocationGranularity = si.dwAllocationGranularity;
#elif CARB_POSIX
m_handle.handleFd = -1;
m_refCount = SEM_FAILED;
m_pageSize = getpagesize();
m_allocationGranularity = m_pageSize;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
~SharedMemory()
{
close();
}
//! Result from createOrOpen().
enum Result
{
eError, //!< An error occurred when attempting to create or open shared memory.
eCreated, //!< The call to createOrOpen() created the shared memory by name.
eOpened, //!< The call to createOrOpen() opened an existing shared memory by name.
};
/** Creates a new shared memory region.
*
* @param[in] name The name to give to the new shared memory region. This may not be
* `nullptr` or an empty string. This must not contain a slash ('/') or
* backslash ('\') character and must generally consist of filename safe
* ASCII characters. This will be used as the base name for the shared
* memory region that is created. This should be shorter than 250
* characters for the most portable behavior. Longer names are allowed
* but will be silently truncated to a platform specific limit. This
* truncation may lead to unintentional failures if two region names
* differ only by truncated characters.
* @param[in] size The requested size of the shared memory region in bytes. This may be
* any size. This will be silently rounded up to the next system
* supported region size. Upon creation, getSize() may be used to
* retrieve the actual size of the newly created region.
* @param[in] flags Flags to control behavior of creating the new shared memory region.
* This may be 0 for default behavior, or may be @ref fCreateMakeUnique
* to indicate that the name specified in @p name should be made into a
* more unique string so that creating a new region with the same base
* name as another region is more likely to succeed (note that it may
* still fail for a host of other reasons). This defaults to
* @ref fCreateMakeUnique.
* @returns `true` if the new shared memory region is successfully created. At this point,
* new views to the region may be created with createView(). When this region is
* no longer needed, it should be closed by either calling close() or by destroying
* this object. This same region may be opened by another client by retrieving its
* open token and passing that to the other client.
* @returns `false` if the new shared memory region could not be created as a new region. This
* can include failing because another shared memory region with the same name
* already exists or that the name was invalid (ie: contained invalid characters).
* @returns `false` if another shared memory region is currently open on this object. In this
* case, close() must be called before attempting to create a new region.
*
* @remarks This creates a new shared memory region in the system. If successful, this new
* region will be guaranteed to be different from all other shared memory regions
* in the system. The new region will always be opened for read and write access.
* New views into this shared memory region may be created upon successful creation
* using createView(). Any created view object will remain valid even if this
* object is closed or destroyed. Note however that other clients will only be
* able to open this same shared memory region if are least one SharedMemory object
* still has the region open in any process in the system. If all references to
* the region are closed, all existing views to it will remain valid, but no new
* clients will be able to open the same region by name. This is a useful way to
* 'lock down' a shared memory region once all expected client(s) have successfully
* opened it.
*
* @note On Linux it is possible to have region creation fail if the @ref fCreateMakeUnique
* flag is not used because the region objects were leaked on the filesystem by another
* potentially crashed process (or the region was never closed). This is also possible
* on Windows, however instead of failing to create the region, an existing region will
* be opened instead. In both cases, this will be detected as a failure since a new
* unique region could not be created as expected. It is best practice to always use
* the @ref fCreateMakeUnique flag here. Similarly, it is always best practice to
* close all references to a region after all necessary views have been created if it
* is intended to persist for the lifetime of the process. This will guarantee that
* all references to the region get released when the process exits (regardless of
* method).
*
* @note On Linux, some malware scanners such as rkhunter check for large shared memory
* regions and flag them as potential root kits. It is best practice to use a
* descriptive name for a shared memory region so that they can be easily dismissed
* as not a problem in a malware report log.
*/
bool create(const char* name, size_t size, uint32_t flags = fCreateMakeUnique)
{
return createAndOrOpen(name, size, flags, false, true) == eCreated;
}
/**
* Attempts to create a shared memory region, or if it could not be created, open an existing one by the same name.
*
* @see create() for more information.
*
* @note On Windows, the attempt to create or open is performed atomically within the operating system. On Linux,
* however, this is not possible. Instead a first attempt is made to create the shared memory region, and if that
* fails, an attempt is made to open the shared memory region.
*
* @note On Windows, if a mapping already exists under the given name and the requested @p size is larger than the
* size of the existing mapping, the process to open the mapping is aborted and Result::eError is returned. On
* Linux, if the requested @p size is larger than the size of the existing mapping, the mapping grows to accommodate
* the requested @p size. It is not possible to grow an existing mapping on Windows.
*
* @param name The name of the shared memory region. @see create() for more information.
* @param size The size of the shared memory region in bytes. @see create() for more information. If the region is
* opened, this parameter has different behavior between Windows and Linux. See note above.
* @param flags The flags provided to direct creation/opening of the shared memory region. @see create() for more
* information. If the region was originally created by passing fCreateMakeUnique to create(), this function will
* not be able to open the region as the name was decorated with a unique identifier. Instead use open() to open the
* shared memory region using the OpenToken.
* @returns A result for the operation.
*/
Result createOrOpen(const char* name, size_t size, uint32_t flags = 0)
{
return createAndOrOpen(name, size, flags, true, true);
}
/**
* Opens a shared memory region by name.
*
* @note On Windows, if a mapping already exists under the given name and the requested @p size is larger than the
* size of the existing mapping, the process to open the mapping is aborted and Result::eError is returned. On
* Linux, if the requested @p size is larger than the size of the existing mapping, the mapping grows to accommodate
* the requested @p size. It is not possible to grow an existing mapping on Windows.
*
* @param name The name of the shared memory region. @see create() for more information.
* @param size The required size of the shared memory region. This parameter has different behavior on Windows and
* Linux. See note above.
* @param flags The flags provided to direct opening the shared memory region.
* @returns `true` if the region was found by name and opened successfully; `false` otherwise.
*/
bool open(const char* name, size_t size, uint32_t flags = 0)
{
return createAndOrOpen(name, size, flags, true, false);
}
/** Opens a shared memory region by token.
*
* @param[in] openToken The open token to use when opening the shared memory region. This
* token contains all the information required to correctly open and
* map the same shared memory region. This open token is retrieved
* from another SharedMemory object that has the region open. This
* is retrieved with getOpenToken(). The token may be encoded into
* a base64 string for transmission to another process (ie: over a
* socket, pipe, environment variable, command line, etc). The
* specific transmission method is left as an exercise for the
* caller. Once received, a new open token object may be created
* in the target process by passing the base64 string to the
* OpenToken() constructor.
* @param[in] access The access mode to open the shared memory region in. This will
* default to @ref AccessMode::eReadWrite.
* @returns `true` if the shared memory region is successfully opened with the requested
* access permissions. Once successfully opened, new views may be created and the
* open token may also be retrieved from here to pass on to yet another client.
* Note that at least one SharedMemory object must still have the region open in
* order for the region to be opened in another client with the same open token.
* This object must either be closed with close() or destroyed in order to ensure
* the region is destroyed properly once all views are unmapped.
* @returns `false` if the region could not not be opened. This could include the open token
* being invalid or corrupt, the given region no longer being present in the system,
* or there being insufficient permission to access it from the calling process.
*/
bool open(const OpenToken& openToken, AccessMode access = AccessMode::eDefault)
{
OpenTokenImpl* token;
SharedHandle handle;
std::string mappingName;
if (m_token != nullptr)
{
CARB_LOG_ERROR(
"the previous SHM region has not been closed yet. Please close it before opening a new SHM region.");
return false;
}
// not a valid open token => fail.
if (!openToken.isValid())
return false;
token = reinterpret_cast<OpenTokenImpl*>(openToken.getToken());
// make sure the token information seems valid.
if (openToken.getSize() < offsetof(OpenTokenImpl, name) + token->nameLength + 1)
return false;
if (token->size == 0 || token->size % m_pageSize != 0)
return false;
if (access == AccessMode::eDefault)
access = AccessMode::eReadWrite;
token = reinterpret_cast<OpenTokenImpl*>(malloc(openToken.getSize()));
if (token == nullptr)
{
CARB_LOG_ERROR("failed to allocate memory for the open token for this SHM region.");
return false;
}
memcpy(token, openToken.getToken(), openToken.getSize());
mappingName = getPlatformMappingName(token->name);
#if CARB_PLATFORM_WINDOWS
std::wstring fname = carb::extras::convertUtf8ToWide(mappingName.c_str());
handle.handleWin32 =
OpenFileMappingW(getAccessModeFlags(access, FlagType::eFileFlags), CARBWIN_FALSE, fname.c_str());
if (handle.handleWin32 == nullptr)
{
CARB_LOG_ERROR("failed to open a file mapping object with the name '%s' {error = %" PRIu32 "}", token->name,
GetLastError());
free(token);
return false;
}
#elif CARB_POSIX
// create the reference count object. Note that this must already exist in the system
// since we are expecting another process to have already created the region.
if (!initRefCount(token->name, 0, true))
{
CARB_LOG_ERROR("failed to create the reference count object with the name '%s'.", token->name);
free(token);
return false;
}
handle.handleFd = shm_open(mappingName.c_str(), getAccessModeFlags(access, FlagType::eFileFlags), 0);
// failed to open the SHM region => fail.
if (handle.handleFd == -1)
{
CARB_LOG_ERROR("failed to open or create file mapping object with the name '%s' {errno = %d/%s}",
token->name, errno, strerror(errno));
destroyRefCount(token->name);
free(token);
return false;
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
m_token = token;
m_handle = handle;
m_access = access;
return true;
}
/** Represents a single mapped view into an open shared memory region. The region will
* remain mapped in memory and valid as long as this object exists. When this view
* object is destroyed, the region will be flushed and unmapped. All view objects are
* still valid even after the shared memory object that created them have been closed
* or destroyed.
*
* View objects may neither be copied nor manually constructed. They may however be
* moved with either a move constructor or move assignment. Note that for safety
* reasons, the moved view must be move assigned or move constructed immediately at
* declaration time. This eliminates the possibility of an unmapped from being
* acquired and prevents the need to check its validity at any given time. Once
* moved, the original view object will no longer be valid and should be immediately
* deleted. The moved view will not be unmapped by deleting the original view object.
*/
class View
{
public:
/** Move constructor: moves another view object into this one.
*
* @param[in] view The other object to move into this one.
*/
View(View&& view)
{
m_address = view.m_address;
m_size = view.m_size;
m_offset = view.m_offset;
m_pageOffset = view.m_pageOffset;
m_access = view.m_access;
view.init();
}
~View()
{
unmap();
}
/** Move assignment operator: moves another object into this one.
*
* @param[in] view The other object to move into this one.
* @returns A reference to this object.
*/
View& operator=(View&& view)
{
if (this == &view)
return *this;
unmap();
m_address = view.m_address;
m_size = view.m_size;
m_offset = view.m_offset;
m_pageOffset = view.m_pageOffset;
m_access = view.m_access;
view.init();
return *this;
}
/** Retrieves the mapped address of this view.
*
* @returns The address of the mapped region. This region will extend from this address
* through the following getSize() bytes minus 1. This address will always be
* aligned to the system page size.
*/
void* getAddress()
{
return reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(m_address) + m_pageOffset);
}
/** Retrieves the size of this mapped view.
*
* @returns The total size in bytes of this mapped view. This region will extend from
* the mapped address returned from getAddress(). This will always be aligned
* to the system page size. This size represents the number of bytes that are
* accessible in this view starting at the given offset (getOffset()) in the
* original shared memory region.
*/
size_t getSize() const
{
return m_size;
}
/** Retrieves the offset of this view into the original mapping object.
*
* @returns The offset of this view in bytes into the original shared memory region.
* This will always be aligned to the system page size. If this is 0, this
* indicates that this view starts at the beginning of the shared memory
* region that created it. If this is non-zero, this view only represents
* a portion of the original shared memory region.
*/
size_t getOffset() const
{
return m_offset;
}
/** Retrieves the access mode that was used to create this view.
*
* @returns The access mode used to create this view. This will always be a valid memory
* access mode and will never be @ref AccessMode::eDefault. This can be used
* to determine what the granted permission to the view is after creation if it
* originally asked for the @ref AccessMode::eDefault mode.
*/
AccessMode getAccessMode() const
{
return m_access;
}
protected:
// prevent new empty local declarations from being default constructed so that we don't
// need to worry about constantly checking for invalid views.
/** Constructor: protected default constructor.
* @remarks This initializes an empty view object. This is protected to prevent new
* empty local declarations from being default constructed so that we don't
* need to worry about constantly checking for invalid views.
*/
View()
{
init();
}
// remove these constructors and operators to prevent multiple copies of the same view
// from being created and copied. Doing so could cause other views to be invalidated
// unintentionally if a mapping address is reused (which is common).
View(const View&) = delete;
View& operator=(const View&) = delete;
View& operator=(const View*) = delete;
/** Maps a view of a shared memory region into this object.
*
* @param[in] handle The handle to the open shared memory region. This must be a
* valid handle to the region.
* @param[in] offset The offset in bytes into the shared memory region where the
* new mapped view should start. This must be aligned to the
* system page size.
* @param[in] size The size in bytes of the portion of the shared memory region
* that should be mapped into the view. This must not extend
* past the end of the original shared memory region once added
* to the offset. This must be aligned to the system page size.
* @param[in] access The requested memory access mode for the view. This must not
* be @ref AccessMode::eDefault. This may not specify greater
* permissions than the shared memory region itself allows (ie:
* requesting read-write on a read-only shared memory region).
* @param[in] allocGran The system allocation granularity in bytes.
* @returns `true` if the new view is successfully mapped.
* @returns `false` if the new view could not be mapped.
*/
bool map(SharedHandle handle, size_t offset, size_t size, AccessMode access, size_t allocGran)
{
void* mapPtr = nullptr;
#if CARB_PLATFORM_WINDOWS
size_t granOffset = offset & ~(allocGran - 1);
m_pageOffset = offset - granOffset;
mapPtr = MapViewOfFile(handle.handleWin32, getAccessModeFlags(access, FlagType::eFileFlags),
static_cast<DWORD>(granOffset >> 32), static_cast<DWORD>(granOffset),
static_cast<SIZE_T>(size + m_pageOffset));
if (mapPtr == nullptr)
{
CARB_LOG_ERROR(
"failed to map %zu bytes from offset %zu {error = %" PRIu32 "}", size, offset, GetLastError());
return false;
}
#elif CARB_POSIX
CARB_UNUSED(allocGran);
m_pageOffset = 0;
mapPtr = mmap(
nullptr, size, getAccessModeFlags(access, FlagType::ePageFlags), MAP_SHARED, handle.handleFd, offset);
if (mapPtr == MAP_FAILED)
{
CARB_LOG_ERROR(
"failed to map %zu bytes from offset %zu {errno = %d/%s}", size, offset, errno, strerror(errno));
return false;
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
m_address = mapPtr;
m_size = size;
m_offset = offset;
m_access = access;
return true;
}
/** Unmaps this view from memory.
*
* @returns No return value.
*
* @remarks This unmaps this view from memory. This should only be called on the
* destruction of this object.
*/
void unmap()
{
if (m_address == nullptr)
return;
#if CARB_PLATFORM_WINDOWS
if (UnmapViewOfFile(m_address) == CARBWIN_FALSE)
CARB_LOG_ERROR("failed to unmap the region at %p {error = %" PRIu32 "}", m_address, GetLastError());
#elif CARB_POSIX
if (munmap(m_address, m_size) == -1)
CARB_LOG_ERROR("failed to unmap the region at %p {errno = %d/%s}", m_address, errno, strerror(errno));
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
init();
}
/** Initializes this object to an empty state. */
void init()
{
m_address = nullptr;
m_size = 0;
m_offset = 0;
m_pageOffset = 0;
m_access = AccessMode::eDefault;
}
void* m_address; ///< The mapped address of this view.
size_t m_size; ///< The size of this view in bytes.
size_t m_offset; ///< The offset of this view in bytes into the shared memory region.
size_t m_pageOffset; ///< The page offset in bytes from the start of the mapping.
AccessMode m_access; ///< The granted access permissions for this view.
// The SharedMemory object that creates this view needs to be able to call into map().
friend class SharedMemory;
};
/** Creates a new view into this shared memory region.
*
* @param[in] offset The offset in bytes into the shared memory region where this view
* should start. This value should be aligned to the system page size.
* If this is not aligned to the system page size, it will be aligned
* to the start of the page that the requested offset is in. The actual
* mapped offset can be retrieved from the new view object with
* getOffset() if the view is successfully mapped. This defaults to 0
* bytes into the shared memory region (ie: the start of the region).
* @param[in] size The number of bytes of the shared memory region starting at the
* byte offset specified by @p offset to map into the new view. This
* should be a multiple of the system page size. If it is not a
* multiple of the system page size, it will be rounded up to the
* next page size during the mapping. This size will also be clamped
* to the size of the shared memory region (less the offset). This
* may be 0 to indicate that the remainder of the region starting at
* the given offset should be mapped into the new view. This defaults
* to 0.
* @param[in] access The access mode to use for the new view. This can be set to
* @ref AccessMode::eDefault to use the same permissions as were
* originally used to open the shared memory region. This will fail
* if the requested mode attempts to grant greater permissions to the
* shared memory region than were used to open it (ie: cannot create a
* read-write view of a read-only shared memory region). This defaults
* to @ref AccessMode::eDefault.
* @returns A new view object representing the mapped view of the shared memory region.
* This must be deleted when the mapped region is no longer needed.
* @returns `nullptr` if the new view cannot be created or if an invalid set of parameters is
* passed in.
*
* @remarks This creates a new view into this shared memory region. The default behavior
* (with no parameters) is to map the entire shared memory region into the new view.
* Multiple views into the same shared memory region can be created simultaneously.
* It is safe to close the shared memory region or delete the object after a new
* view is successfully created. In this case, the view object and the mapped
* memory will still remain valid as long as the view object still exists. This
* shared memory object can similarly also safely close and open a new region
* while views on the previous region still exist. The previous region will only
* be completely invalidated once all views are deleted and all other open
* references to the region are closed.
*
* @note On Windows, the @p offset parameter should be additionally aligned to the system's
* allocation granularity (ie: getSystemAllocationGranularity()). Under this object
* however, this additional alignment requirement is handled internally so that page
* alignment is provided to match Linux behavior. However, this does mean that
* additional pages may be mapped into memory that are just transparently skipped by
* the view object. When on Windows, it would be a best practice to align the view
* offsets to a multiple of the system allocation granularity (usually 64KB) instead
* of just the page size (usually 4KB). This larger offset granularity behavior
* will also work properly on Linux.
*/
View* createView(size_t offset = 0, size_t size = 0, AccessMode access = AccessMode::eDefault) const
{
View* view;
// no SHM region is open -> nothing to do => fail.
if (m_token == nullptr)
return nullptr;
// the requested offset is beyond the region => fail.
if (offset >= m_token->size)
return nullptr;
if (access == AccessMode::eDefault)
access = m_access;
// attempting to map a read/write region on a read-only mapping => fail.
else if (access == AccessMode::eReadWrite && m_access == AccessMode::eReadOnly)
return nullptr;
offset = alignPageFloor(offset);
if (size == 0)
size = m_token->size;
if (offset + size > m_token->size)
size = m_token->size - offset;
view = new (std::nothrow) View();
if (view == nullptr)
return nullptr;
if (!view->map(m_handle, offset, size, access, m_allocationGranularity))
{
delete view;
return nullptr;
}
return view;
}
/** Closes this shared memory region.
*
* @param forceUnlink @b Linux: If `true`, the shared memory region name is disassociated with the currently opened
* shared memory. If the shared memory is referenced by other processes (or other SharedMemory objects) it
* remains open and valid, but no additional SharedMemory instances will be able to open the same shared memory
* region by name. Attempts to open the shared memory by name will fail, and attempts to create the shared memory
* by name will create a new shared memory region. If `false`, the shared memory region will be unlinked when the
* final SharedMemory object using it has closed. @b Windows: this parameter is ignored.
*
* @remarks This closes the currently open shared memory region on this object. This will
* put the object back into a state where a new region can be opened. This call
* will be ignored if no region is currently open. This region can be closed even
* if views still exist on the current region. The existing views will not be
* closed, invalidated, or unmapped by closing this shared memory region.
*
* @note The current region will be automatically closed when this object is deleted.
*/
void close(bool forceUnlink = false)
{
if (m_token == nullptr)
return;
#if CARB_PLATFORM_WINDOWS
CARB_UNUSED(forceUnlink);
if (m_handle.handleWin32 != nullptr)
CloseHandle(m_handle.handleWin32);
m_handle.handleWin32 = nullptr;
#elif CARB_POSIX
if (m_handle.handleFd != -1)
::close(m_handle.handleFd);
m_handle.handleFd = -1;
// check that all references to the SHM region have been released before unlinking
// the named filesystem reference to it. The reference count semaphore can also
// be unlinked from the filesystem at this point.
if (releaseRef() || forceUnlink)
{
std::string mappingName = getPlatformMappingName(m_token->name);
shm_unlink(mappingName.c_str());
destroyRefCount(m_token->name);
}
// close our local reference to the ref count semaphore.
sem_close(m_refCount);
m_refCount = SEM_FAILED;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
free(m_token);
m_token = nullptr;
m_access = AccessMode::eDefault;
}
/**
* Indicates whether the SharedMemory object is currently open or not.
*
* @returns `true` if the SharedMemory object has a region open; `false` otherwise.
*/
bool isOpen() const
{
return m_token != nullptr;
}
/** Retrieves the token used to open this same SHM region elsewhere.
*
* @returns The open token object. This token is valid as long as the SharedMemory object
* that returned it has not been closed. If this object needs to persist, it should
* be copied to a caller owned buffer.
* @returns `nullptr` if no SHM region is currently open on this object.
*/
OpenToken getOpenToken()
{
if (m_token == nullptr)
return OpenToken();
return OpenToken(m_token, offsetof(OpenTokenImpl, name) + m_token->nameLength + 1);
}
/** Retrieves the total size of the current shared memory region in bytes.
*
* @returns The size in bytes of the currently open shared memory region. Note that this
* will be aligned to the system page size if the original value passed into the
* open() call was not aligned.
*/
size_t getSize() const
{
if (m_token == nullptr)
return 0;
return m_token->size;
}
/** The maximum access mode allowed for the current shared memory region.
*
* @returns The memory access mode that the current shared memory region was created with.
* This will never be @ref AccessMode::eDefault when this SHM region is valid.
* @retval AccessMode::eDefault if no SHM region is currently open on this object.
*/
AccessMode getAccessMode() const
{
if (m_token == nullptr)
return AccessMode::eDefault;
return m_access;
}
/** Retrieves the system memory page size.
*
* @returns The size of the system's memory page size in bytes.
*/
size_t getSystemPageSize() const
{
return m_pageSize;
}
/** Retrieves the system allocation granularity.
*
* @returns The system's allocation granularity in bytes.
*/
size_t getSystemAllocationGranularity() const
{
return m_allocationGranularity;
}
private:
/** An opaque token containing the information needed to open the SHM region that is created
* here. Note that this structure is tightly packed to avoid having to transfer extra data
* between clients. When a new token is returned, it will not include any extra padding
* space at the end of the object.
*/
CARB_IGNOREWARNING_MSC_WITH_PUSH(4200) // nonstandard extension used: zero-sized array in struct/union
#pragma pack(push, 1)
struct OpenTokenImpl
{
/** The creation time size of the SHM region in bytes. Note that this is not strictly
* needed on Windows since the size of a mapping object can be retrieved at any time
* with NtQuerySection(). However, since that is an ntdll level function and has a
* slim possibility of changing in a future Windows version, we'll just explicitly
* pass over the creation time size when retrieving the token.
*/
size_t size;
/** The length of the @a name string in characters. Note that this is limited to
* 16 bits (ie: 65535 characters). This is a system imposed limit on all named
* handle objects on Windows and is well beyond the supported length for filenames
* on Linux. This is reduced in range to save space in the size of the tokens
* that need to be transmitted to other clients that will open the same region.
* Also note that this length is present in the token so that the token's size
* can be validated for safety and correctness in open().
*/
uint16_t nameLength;
/** The name that was used to create the SHM region that will be opened using this
* token. This will always be null terminated and will contain exactly the number
* of characters specified in @a nameLength.
*/
char name[0];
};
#pragma pack(pop)
CARB_IGNOREWARNING_MSC_POP
/** Flags to indicate which type of flags to return from getAccessModeFlags(). */
enum class FlagType
{
eFileFlags, ///< Retrieve the file mapping flags.
ePageFlags, ///< Retrieve the page protection flags.
};
#if CARB_POSIX
struct SemLockGuard
{
sem_t* mutex_;
SemLockGuard(sem_t* mutex) : mutex_(mutex)
{
CARB_FATAL_UNLESS(
CARB_RETRY_EINTR(sem_wait(mutex_)) == 0, "sem_wait() failed {errno = %d/%s}", errno, strerror(errno));
}
~SemLockGuard()
{
CARB_FATAL_UNLESS(
CARB_RETRY_EINTR(sem_post(mutex_)) == 0, "sem_post() failed {errno = %d/%s}", errno, strerror(errno));
}
};
#endif
size_t alignPageCeiling(size_t size) const
{
size_t pageSize = getSystemPageSize();
return (size + (pageSize - 1)) & ~(pageSize - 1);
}
size_t alignPageFloor(size_t size) const
{
size_t pageSize = getSystemPageSize();
return size & ~(pageSize - 1);
}
std::string getPlatformMappingName(const char* name, size_t maxLength = 0)
{
std::string fname;
#if CARB_PLATFORM_WINDOWS
const char prefix[] = "Local\\";
// all named handle objects have a hard undocumented name length limit of 64KB. This is
// due to all ntdll strings using a WORD value as the length in the UNICODE_STRING struct
// that is always used for names at the ntdll level. Any names that are beyond this
// limit get silently truncated and used as-is. This length limit includes the prefix.
// Note that the name strings must still be null terminated even at the ntdll level.
if (maxLength == 0)
maxLength = (64 * 1024);
#elif CARB_POSIX
const char prefix[] = "/";
if (maxLength == 0)
{
# if CARB_PLATFORM_MACOS
// Mac OS limits the SHM name to this.
maxLength = PSHMNAMLEN;
# else
// This appears to be the specified length in POSIX.
maxLength = NAME_MAX;
# endif
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
fname = std::string(prefix) + name;
if (fname.length() > maxLength)
{
fname.erase(fname.begin() + maxLength, fname.end());
}
return fname;
}
std::string makeUniqueName(const char* name)
{
std::string str = name;
char buffer[256];
// create a unique name be appending the process ID and a random number to the given name.
// This should be sufficiently unique for our purposes. This should only add 3-8 new
// characters to the name.
extras::formatString(buffer, CARB_COUNTOF(buffer), "%" OMNI_PRIxpid "-%x", this_process::getId(), rand());
return std::string(str + buffer);
}
static constexpr uint32_t getAccessModeFlags(AccessMode access, FlagType type)
{
switch (access)
{
default:
case AccessMode::eDefault:
case AccessMode::eReadWrite:
#if CARB_PLATFORM_WINDOWS
return type == FlagType::eFileFlags ? CARBWIN_FILE_MAP_ALL_ACCESS : CARBWIN_PAGE_READWRITE;
#elif CARB_POSIX
return type == FlagType::eFileFlags ? O_RDWR : (PROT_READ | PROT_WRITE);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
case AccessMode::eReadOnly:
#if CARB_PLATFORM_WINDOWS
return type == FlagType::eFileFlags ? CARBWIN_FILE_MAP_READ : CARBWIN_PAGE_READONLY;
#elif CARB_POSIX
return type == FlagType::eFileFlags ? O_RDONLY : PROT_READ;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
}
Result createAndOrOpen(const char* name, size_t size, uint32_t flags, bool tryOpen, bool tryCreate)
{
std::string mappingName;
std::string rawName;
size_t extraSize = 0;
OpenTokenImpl* token;
SharedHandle handle;
bool quiet = !!(flags & fQuiet);
/****** check for bad calls and bad parameters ******/
if (m_token != nullptr)
{
CARB_LOG_WARN(
"the previous SHM region has not been closed yet. Please close it before creating a new SHM region.");
return eError;
}
// a valid name is needed => fail.
if (name == nullptr || name[0] == 0)
return eError;
// can't create a zero-sized SHM region => fail.
if (size == 0)
return eError;
// neither create nor open => fail.
if (!tryOpen && !tryCreate)
return eError;
/****** create the named mapping object ******/
bool const unique = (flags & fCreateMakeUnique) != 0;
if (unique)
rawName = makeUniqueName(name);
else
rawName = name;
// get the platform-specific name for the region using the given name as a template.
mappingName = getPlatformMappingName(rawName.c_str());
// make sure the mapping size is aligned to the next system page size.
size = alignPageCeiling(size);
// create the open token that will be used for other clients.
extraSize = rawName.length();
token = reinterpret_cast<OpenTokenImpl*>(malloc(sizeof(OpenTokenImpl) + extraSize + 1));
if (token == nullptr)
{
if (!quiet)
CARB_LOG_ERROR("failed to create a new open token for the SHM region '%s'.", name);
return eError;
}
// store the token information.
token->size = size;
token->nameLength = extraSize & 0xffff;
memcpy(token->name, rawName.c_str(), sizeof(name[0]) * (token->nameLength + 1));
#if CARB_PLATFORM_WINDOWS
std::wstring fname = carb::extras::convertUtf8ToWide(mappingName.c_str());
if (!tryCreate)
handle.handleWin32 = OpenFileMappingW(CARBWIN_PAGE_READWRITE, CARBWIN_FALSE, fname.c_str());
else
handle.handleWin32 =
CreateFileMappingW(CARBWIN_INVALID_HANDLE_VALUE, nullptr, CARBWIN_PAGE_READWRITE,
static_cast<DWORD>(size >> 32), static_cast<DWORD>(size), fname.c_str());
// the handle was opened successfully => make sure it didn't open an existing object.
if (handle.handleWin32 == nullptr || (!tryOpen && (GetLastError() == CARBWIN_ERROR_ALREADY_EXISTS)))
{
if (!quiet)
CARB_LOG_ERROR("failed to create and/or open a file mapping object with the name '%s' {error = %" PRIu32
"}",
name, GetLastError());
CloseHandle(handle.handleWin32);
free(token);
return eError;
}
bool const wasOpened = (GetLastError() == CARBWIN_ERROR_ALREADY_EXISTS);
if (wasOpened)
{
// We need to use an undocumented function (NtQuerySection) to read the size of the mapping object.
using PNtQuerySection = DWORD(__stdcall*)(HANDLE, int, PVOID, ULONG, PSIZE_T);
static PNtQuerySection pNtQuerySection =
(PNtQuerySection)::GetProcAddress(::GetModuleHandleW(L"ntdll.dll"), "NtQuerySection");
if (pNtQuerySection)
{
struct /*SECTION_BASIC_INFORMATION*/
{
PVOID BaseAddress;
ULONG AllocationAttributes;
CARBWIN_LARGE_INTEGER MaximumSize;
} sbi;
SIZE_T read;
if (pNtQuerySection(handle.handleWin32, 0 /*SectionBasicInformation*/, &sbi, sizeof(sbi), &read) >= 0)
{
if (size > (size_t)sbi.MaximumSize.QuadPart)
{
if (!quiet)
CARB_LOG_ERROR("mapping with name '%s' was opened but existing size %" PRId64
" is smaller than requested size %zu",
name, sbi.MaximumSize.QuadPart, size);
CloseHandle(handle.handleWin32);
free(token);
return eError;
}
}
}
}
#elif CARB_POSIX
// See the function for an explanation of why this is needed.
detail::probeSharedMemory();
// Lock a mutex (named semaphore) while we attempt to initialize the ref-count and shared memory objects. For
// uniquely-named objects we use a per-process semaphore, but for globally-named objects we use a global mutex.
cpp::optional<detail::NamedSemaphore> processMutex;
cpp::optional<std::lock_guard<detail::NamedSemaphore>> lock;
if (!(flags & fNoMutexLock))
{
if (unique)
{
// Always get the current process ID since we could fork() and our process ID could change.
// NOTE: Do not change this naming. Though PID is not a great unique identifier, it is considered an
// ABI break to change this.
std::string name = detail::getGlobalSemaphoreName();
name += '-';
name += std::to_string(this_process::getId());
processMutex.emplace(name.c_str(), true);
lock.emplace(processMutex.value());
}
else
{
lock.emplace(m_systemMutex);
}
}
// create the reference count object. Note that we don't make sure it's unique in the
// system because another process may have crashed or leaked it.
if (!tryCreate || !initRefCount(token->name, O_CREAT | O_EXCL, !tryOpen && !quiet))
{
// Couldn't create it exclusively. Something else must have created it, so just try to open existing.
if (!tryOpen || !initRefCount(token->name, 0, !quiet))
{
if (!quiet)
CARB_LOG_ERROR(
"failed to create/open the reference count object for the new region with the name '%s'.",
token->name);
free(token);
return eError;
}
}
handle.handleFd =
tryCreate ? shm_open(mappingName.c_str(), O_RDWR | O_CREAT | O_EXCL, detail::kAllReadWrite) : -1;
if (handle.handleFd != -1)
{
// We created the shared memory region. Since shm_open() is affected by the process umask, use fchmod() to
// set the file permissions to all users.
fchmod(handle.handleFd, detail::kAllReadWrite);
}
// failed to open the SHM region => fail.
bool wasOpened = false;
if (handle.handleFd == -1)
{
// Couldn't create exclusively. Perhaps it already exists to open.
if (tryOpen)
{
handle.handleFd = shm_open(mappingName.c_str(), O_RDWR, 0);
}
if (handle.handleFd == -1)
{
if (!quiet)
CARB_LOG_ERROR("failed to create/open SHM region '%s' {errno = %d/%s}", name, errno, strerror(errno));
destroyRefCount(token->name);
free(token);
return eError;
}
wasOpened = true;
// If the region is too small, extend it while we have the semaphore locked.
struct stat statbuf;
if (fstat(handle.handleFd, &statbuf) == -1)
{
if (!quiet)
CARB_LOG_ERROR("failed to stat SHM region '%s' {errno = %d, %s}", name, errno, strerror(errno));
::close(handle.handleFd);
free(token);
return eError;
}
if (size > size_t(statbuf.st_size) && ftruncate(handle.handleFd, size) != 0)
{
if (!quiet)
CARB_LOG_ERROR("failed to grow the size of the SHM region '%s' from %zu to %zu bytes {errno = %d/%s}",
name, size_t(statbuf.st_size), size, errno, strerror(errno));
::close(handle.handleFd);
free(token);
return eError;
}
}
// set the size of the region by truncating the file while we have the semaphore locked.
else if (ftruncate(handle.handleFd, size) != 0)
{
if (!quiet)
CARB_LOG_ERROR("failed to set the size of the SHM region '%s' to %zu bytes {errno = %d/%s}", name, size,
errno, strerror(errno));
::close(handle.handleFd);
shm_unlink(mappingName.c_str());
destroyRefCount(token->name);
free(token);
return eError;
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
/****** save the values for the SHM region ******/
m_token = token;
m_handle = handle;
m_access = AccessMode::eReadWrite;
return wasOpened ? eOpened : eCreated;
}
#if CARB_POSIX
bool initRefCount(const char* name, int flags, bool logError)
{
// build the name for the semaphore. This needs to start with a slash followed by up to
// 250 non-slash ASCII characters. This is the same format as for the SHM region, except
// for the maximum length. The name given here will need to be truncated if it is very
// long. The system adds "sem." to the name internally which explains why the limit is
// not NAME_MAX.
std::string mappingName = getPlatformMappingName(name, NAME_MAX - 4);
// create the semaphore that will act as the IPC reference count for the SHM region.
// Note that this will be created with an initial count of 0, not 1. This is intentional
// since we want the last reference to fail the wait operation so that we can atomically
// detect the case where the region's file (and the semaphore's) should be unlinked.
m_refCount = sem_open(mappingName.c_str(), flags, detail::kAllReadWrite, 0);
if (m_refCount == SEM_FAILED)
{
if (logError)
{
CARB_LOG_ERROR("failed to create or open a semaphore named \"%s\" {errno = %d/%s}", mappingName.c_str(),
errno, strerror(errno));
}
return false;
}
# if CARB_PLATFORM_LINUX
else if (flags & O_CREAT)
{
// sem_open() is masked by umask(), so force the permissions with chmod().
// NOTE: This assumes that named semaphores are under /dev/shm and are prefixed with sem. This is not ideal,
// but there does not appear to be any means to translate a sem_t* to a file descriptor (for fchmod()) or a
// path.
mappingName.replace(0, 1, "/dev/shm/sem.");
chmod(mappingName.c_str(), detail::kAllReadWrite);
}
# endif
// only add a new reference to the SHM region when opening the region, not when creating
// it. This will cause the last reference to fail the wait in releaseRef() to allow us
// to atomically detect the destruction case.
if ((flags & O_CREAT) == 0)
CARB_RETRY_EINTR(sem_post(m_refCount));
return true;
}
bool releaseRef()
{
int result;
// waiting on the semaphore will decrement its count by one. When it reaches zero, the
// wait will block. However since we're doing a 'try wait' here, that will fail with
// errno set to EAGAIN instead of blocking.
errno = -1;
result = CARB_RETRY_EINTR(sem_trywait(m_refCount));
return (result == -1 && errno == EAGAIN);
}
void destroyRefCount(const char* name)
{
std::string mappingName;
mappingName = getPlatformMappingName(name, NAME_MAX - 4);
sem_unlink(mappingName.c_str());
}
/** A semaphore used to handle a reference count to the SHM region itself. This will allow
* the SHM region to only be unlinked from the file system once the reference count has
* reached zero. This will leave the SHM region valid for other clients to open by name
* as long as at least one client still has it open.
*
* @note This intentionally isn't used as mutex to protect access to a ref count in shared
* memory since the semaphore would be necessary anyway in that situation, along with
* wasting a full page of shared memory just to contain the ref count and semaphore
* object. The semaphore itself already provides the required IPC safe counting
* mechanism that we need here.
*/
sem_t* m_refCount;
/**
* A semaphore used as a system-wide shared mutex to synchronize the process of creating
* ref-count objects and creating/opening existing shared memory objects.
*/
detail::NamedSemaphore m_systemMutex{ detail::getGlobalSemaphoreName() };
#endif
/** The information block used to open this mapping object. This can be retrieved to
* open the same SHM region elsewhere.
*/
OpenTokenImpl* m_token;
/** The locally opened handle to the SHM region. */
SharedHandle m_handle;
/** The original access mode used when the SHM region was created or opened. This will
* dictate the maximum allowed access permissions when mapping views of the region.
*/
AccessMode m_access;
/** The system page size in bytes. Note that this unfortunately cannot be a static member
* because that would lead to either missing symbol or multiple definition link errors
* depending on whether the symbol were also defined outside the class or not. We'll
* just retrieve it on construction instead.
*/
size_t m_pageSize;
/** The system allocation granularity in bytes. Note that this unfortunately cannot be
* a static member because that would lead to either missing symbol or multiple
* definition link errors depending on whether the symbol were also defined outside
* the class or not. We'll just retrieve it on construction instead.
*/
size_t m_allocationGranularity;
};
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/extras/WindowsPath.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Carbonite Windows path utilities
#pragma once
#include "../Defines.h"
#if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD)
# include "../CarbWindows.h"
# include "../Error.h"
# include "Unicode.h"
# include <algorithm>
# include <string>
namespace carb
{
namespace extras
{
/**
* (Windows only) Converts a UTF-8 file path to Windows system file path.
*
* Slashes are replaced with backslashes, and @ref fixWindowsPathPrefix() is called.
*
* @note Use of this function is discouraged. Use @ref carb::filesystem::IFileSystem for filesystem needs.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not cleared on success
* * @ref omni::core::kResultFail - UTF-8 to wide conversion failed
*
* @param path Input string to convert, in UTF-8 encoding.
* @return Wide string containing Windows system file path or empty string if conversion cannot be performed.
*/
std::wstring convertCarboniteToWindowsPath(const std::string& path);
/**
* (Windows only) Converts Windows system file path to a UTF-8 file path.
*
* Backslashes are replaced with slashes and the long path prefix is removed if present.
*
* @note Use of this function is discouraged. Use @ref carb::filesystem::IFileSystem for filesystem needs.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not cleared on success
* * @ref omni::core::kResultFail - UTF-8 to wide conversion failed
*
* @param pathW Input string to convert, in Unicode (Windows native) encoding.
* @return UTF-8 encoded file path or empty string if conversion cannot be performed.
*/
std::string convertWindowsToCarbonitePath(const std::wstring& pathW);
/**
* (Windows only) Performs fixup on a Windows file path by adding or removing the long path prefix as necessary.
*
* If the file path is too long and doesn't have long path prefix, the prefix is added.
* If the file path is short and has long path prefix, the prefix is removed.
* Otherwise, the path is not modified.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * None
*
* @param pathW Input string to convert, in Unicode (Windows native) encoding.
* @return Valid Windows system file path.
*/
std::wstring fixWindowsPathPrefix(const std::wstring& pathW);
/**
* (Windows only) Converts Windows path string into a canonical form.
*
* @note This uses Windows platform functions to canonicalize the path and is fairly costly.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not cleared on success
* * @ref omni::core::kResultFail - An error occurred
*
* @param pathW Windows system file path, in Unicode (Windows native) encoding.
* @return The canonical form of the input path. If an error occurs, @p pathW is returned without modifications. In
* order to determine if an error occurred, use @ref carb::ErrorApi. Since error state is not cleared on
* success, clear the error state before calling this function if you wish to make sure that it succeeds.
*/
std::wstring getWindowsCanonicalPath(const std::wstring& pathW);
/**
* (Windows only) Retrieves the full path and file name of the specified file.
*
* If it's not possible, original path is returned.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not cleared on success
* * @ref omni::core::kResultFail - An error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @param pathW Windows system file path, in Unicode (Windows native) encoding.
* @return The full path and file name of the input file. If an error occurs, @p pathW is returned without modification.
* In order to determine if an error occurred, use @ref carb::ErrorApi. Since the error state is not cleared on
* success, clear the error state before calling this function if you wish to make sure that it succeeds.
*/
std::wstring getWindowsFullPath(const std::wstring& pathW);
/**
* (Windows only) Sets the default DLL search directories for the application.
*
* This calls `SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)`. From the
* <a
* href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories">documentation</a>
* this value is the combination of three separate values which comprise the recommended maximum number of directories
* an application should include in its DLL search path:
* * The application directory
* * `%windows%\system32`
* * User directories: any path explicitly added by `AddDllDirectory()` or `SetDllDirectory()`.
*
* See also: <a href="https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order">DLL Search
* Order</a>
*
* @ref ErrorApi state is not changed by this function.
*/
void adjustWindowsDllSearchPaths();
//
// Implementations
//
inline std::wstring convertCarboniteToWindowsPath(const std::string& path)
{
std::wstring pathW = convertUtf8ToWide(path);
if (pathW == kUnicodeToWideFailure)
{
ErrorApi::instance().setError(kResultFail);
return L"";
}
std::replace(pathW.begin(), pathW.end(), L'/', L'\\');
return fixWindowsPathPrefix(pathW);
}
inline std::string convertWindowsToCarbonitePath(const std::wstring& pathW)
{
bool hasPrefix = (pathW.compare(0, 4, L"\\\\?\\") == 0);
std::string path = convertWideToUtf8(pathW.c_str() + (hasPrefix ? 4 : 0));
if (path == kUnicodeToUtf8Failure)
{
ErrorApi::instance().setError(kResultFail);
return "";
}
std::replace(path.begin(), path.end(), '\\', '/');
return path;
}
inline std::wstring fixWindowsPathPrefix(const std::wstring& pathW)
{
bool hasPrefix = (pathW.compare(0, 4, L"\\\\?\\") == 0);
if (pathW.size() >= CARBWIN_MAX_PATH && !hasPrefix)
{
return L"\\\\?\\" + pathW;
}
if (pathW.size() < CARBWIN_MAX_PATH && hasPrefix)
{
return pathW.substr(4, pathW.size() - 4);
}
return pathW;
}
inline std::wstring getWindowsCanonicalPath(const std::wstring& pathW)
{
wchar_t* canonical = nullptr;
auto hr = PathAllocCanonicalize(pathW.c_str(), CARBWIN_PATHCCH_ALLOW_LONG_PATHS, &canonical);
if (CARBWIN_SUCCEEDED(hr))
{
std::wstring result = canonical;
LocalFree(canonical);
return result;
}
ErrorApi::instance().setError(
omni::core::kResultFail, omni::string{ omni::formatted, "PathAllocCanonicalize failed with HRESULT 0x%08x", hr });
return pathW;
}
inline std::wstring getWindowsFullPath(const std::wstring& pathW)
{
// Retrieve the size
DWORD size = GetFullPathNameW(pathW.c_str(), 0, nullptr, nullptr);
if (size != 0)
{
std::wstring fullPathName(size - 1, '\0');
size = GetFullPathNameW(pathW.c_str(), size, &fullPathName[0], nullptr);
if (size)
{
// Assert if the Win32 API lied to us. Note that sometimes it does use less than asked for.
CARB_ASSERT(size <= fullPathName.size());
fullPathName.resize(size);
return fullPathName;
}
}
ErrorApi::setFromWinApiErrorCode();
return pathW;
}
inline void adjustWindowsDllSearchPaths()
{
// MSDN:
// https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories
// LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
// This value is a combination of LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, and
// LOAD_LIBRARY_SEARCH_USER_DIRS.
SetDefaultDllDirectories(CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
}
} // namespace extras
} // namespace carb
#endif
|
omniverse-code/kit/include/carb/extras/StringSafe.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Wrappers for libc string functions to avoid dangerous edge cases.
*/
#pragma once
// for vsnprintf() on windows
#if !defined(_CRT_SECURE_NO_WARNINGS) && !defined(DOXYGEN_BUILD)
# define _CRT_SECURE_NO_WARNINGS
#endif
#include "../Defines.h"
#include "ScopeExit.h"
#include <cstdarg>
#include <cstdio>
#include <cstring>
// pyerrors.h defines vsnprintf to be _vsnprintf on Windows, which is non-standard and breaks things. In the more modern
// C++ that we're using, std::vsnprintf does what we want, so get rid of pyerrors.h's badness here. As a service to
// others, we'll also undefine pyerrors.h's `snprintf` symbol.
#if defined(Py_ERRORS_H) && CARB_PLATFORM_WINDOWS
# undef vsnprintf
# undef snprintf
#endif
namespace carb
{
namespace extras
{
/** Compare two strings in a case sensitive manner.
*
* @param[in] str1 The first string to compare. This may not be `nullptr`.
* @param[in] str2 The second string to compare. This may not be `nullptr`.
* @returns `0` if the two strings match.
* @returns A negative value if `str1` should be ordered before `str2`.
* @returns A positive value if `str1` should be ordered after `str2`.
*/
inline int32_t compareStrings(const char* str1, const char* str2)
{
return strcmp(str1, str2);
}
/** Compare two strings in a case insensitive manner.
*
* @param[in] str1 The first string to compare. This may not be `nullptr`.
* @param[in] str2 The second string to compare. This may not be `nullptr`.
* @returns `0` if the two strings match.
* @returns A negative value if `str1` should be ordered before `str2`.
* @returns A positive value if `str1` should be ordered after `str2`.
*/
inline int32_t compareStringsNoCase(const char* str1, const char* str2)
{
#if CARB_PLATFORM_WINDOWS
return _stricmp(str1, str2);
#else
return strcasecmp(str1, str2);
#endif
}
/**
* Check if two memory regions overlaps.
*
* @param[in] ptr1 pointer to a first memory region.
* @param[in] size1 size in bytes of the first memory region.
* @param[in] ptr2 pointer to a second memory region.
* @param[in] size2 size in bytes of the second memory region.
*
* @return true if memory regions overlaps or false if they are not.
*/
inline bool isMemoryOverlap(const void* ptr1, size_t size1, const void* ptr2, size_t size2)
{
// We assume flat memory model.
uintptr_t addr1 = uintptr_t(ptr1);
uintptr_t addr2 = uintptr_t(ptr2);
if (addr1 < addr2)
{
if (addr2 - addr1 >= size1)
{
return false;
}
}
else if (addr1 > addr2)
{
if (addr1 - addr2 >= size2)
{
return false;
}
}
return true;
}
/**
* Copy a string with optional truncation.
*
* @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero).
* @param[in] dstBufSize size in characters of the destination buffer.
* @param[in] srcString pointer to a source string.
*
* @return a number of copied characters to the destination buffer (not including the trailing \0).
*
* @remark This function copies up to dstBufSize - 1 characters from the 0-terminated string srcString
* to the buffer dstBuf and appends trailing \0 to the result. This function is guarantee that the result
* has trailing \0 as long as dstBufSize is larger than 0.
*/
inline size_t copyStringSafe(char* dstBuf, size_t dstBufSize, const char* srcString)
{
CARB_ASSERT(dstBuf || dstBufSize == 0);
CARB_ASSERT(srcString);
if (dstBufSize > 0)
{
// Compute length of the source string to be copied.
size_t copyLength = strlen(srcString);
// Check the source and destination are not overlapped.
CARB_ASSERT(!isMemoryOverlap(dstBuf, dstBufSize, srcString, copyLength + 1));
if (copyLength >= dstBufSize)
{
copyLength = dstBufSize - 1;
memcpy(dstBuf, srcString, copyLength);
}
else if (copyLength > 0)
{
memcpy(dstBuf, srcString, copyLength);
}
dstBuf[copyLength] = '\0';
return copyLength;
}
return 0;
}
/**
* Copy slice of string with optional truncation.
*
* @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero).
* @param[in] dstBufSize size in characters of the destination buffer.
* @param[in] srcString pointer to a source string (can be nullptr in the case if maxCharacterCount is zero).
* @param[in] maxCharacterCount maximum number of characters to be copied from the source string.
*
* @return a number of copied characters to the destination buffer (not including the trailing \0).
*
* @remarks This function copies up to min(dstBufSize - 1, maxCharacterCount) characters from the source string
* srcString to the buffer dstBuf and appends trailing \0 to the result. This function is guarantee that the result has
* trailing \0 as long as dstBufSize is larger than 0.
*/
inline size_t copyStringSafe(char* dstBuf, size_t dstBufSize, const char* srcString, size_t maxCharacterCount)
{
CARB_ASSERT(dstBuf || dstBufSize == 0);
CARB_ASSERT(srcString || maxCharacterCount == 0);
// NOTE: We don't use strncpy_s in implementation even if it's available in the system because it places empty
// string to the destination buffer in case of truncation of source string (see the detailed description at
// https://en.cppreference.com/w/c/string/byte/strncpy).
// Instead, we use always our own implementation which is tolerate to any case of truncation.
if (dstBufSize > 0)
{
// Compute length of the source string slice to be copied.
size_t copyLength = (maxCharacterCount > 0) ? strnlen(srcString, CARB_MIN(dstBufSize - 1, maxCharacterCount)) : 0;
// Check the source and destination are not overlapped.
CARB_ASSERT(!isMemoryOverlap(dstBuf, dstBufSize, srcString, copyLength));
if (copyLength > 0)
{
memcpy(dstBuf, srcString, copyLength);
}
dstBuf[copyLength] = '\0';
return copyLength;
}
return 0;
}
/**
* A vsnprintf wrapper that clamps the return value.
*
* @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero).
* @param[in] dstBufSize size in characters of the destination buffer.
* @param[in] fmtString pointer to a format string (passed to the vsnprintf call).
* @param[in] argsList arguments list
*
* @return a number of characters written to the destination buffer (not including the trailing \0).
*
* @remarks This function is intended to be used in code where an index is incremented by snprintf.
* In the following example, if vsnprintf() were used, idx can become larger than
* len, causing wraparound errors, but with formatStringV(), idx will never
* become larger than len.
*
* idx += formatStringV(buf, len - idx, ...);
* idx += formatStringV(buf, len - idx, ...);
*
*/
inline size_t formatStringV(char* dstBuf, size_t dstBufSize, const char* fmtString, va_list argsList)
{
CARB_ASSERT(dstBuf || dstBufSize == 0);
CARB_ASSERT(fmtString);
if (dstBufSize > 0)
{
int rc = std::vsnprintf(dstBuf, dstBufSize, fmtString, argsList);
size_t count = size_t(rc);
if (rc < 0)
{
// We assume no output in a case of I/O error.
dstBuf[0] = '\0';
count = 0;
}
else if (count >= dstBufSize)
{
// ANSI C always adds the null terminator, older MSVCRT versions do not.
dstBuf[dstBufSize - 1] = '\0';
count = (dstBufSize - 1);
}
return count;
}
return 0;
}
/**
* A snprintf wrapper that clamps the return value.
*
* @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero).
* @param[in] dstBufSize size in characters of the destination buffer.
* @param[in] fmtString pointer to a format string (passed to the snprintf call).
*
* @return a number of characters written to the destination buffer (not including the trailing \0).
*
* @remarks This function is intended to be used in code where an index is incremented by snprintf.
* In the following example, if snprintf() were used, idx can become larger than
* len, causing wraparound errors, but with formatString(), idx will never
* become larger than len.
*
* idx += formatString(buf, len - idx, ...);
* idx += formatString(buf, len - idx, ...);
*
*/
inline size_t formatString(char* dstBuf, size_t dstBufSize, const char* fmtString, ...) CARB_PRINTF_FUNCTION(3, 4);
inline size_t formatString(char* dstBuf, size_t dstBufSize, const char* fmtString, ...)
{
size_t count;
va_list argsList;
va_start(argsList, fmtString);
count = formatStringV(dstBuf, dstBufSize, fmtString, argsList);
va_end(argsList);
return count;
}
/** Test if one string is a prefix of the other.
* @param[in] str The string to test.
* @param[in] prefix The prefix to test on @p str.
* @returns `true` if @p str begins with @p prefix.
* @returns `false` otherwise.
*/
inline bool isStringPrefix(const char* str, const char* prefix)
{
for (size_t i = 0; prefix[i] != '\0'; i++)
{
if (str[i] != prefix[i])
{
return false;
}
}
return true;
}
/**
* Formats as with vsnprintf() and calls a Callable with the result and the size. The memory for the string is managed
* for the caller.
* \details This function attempts to use the stack first but will fall back to the heap if the given \p fmt and
* arguments do not fit on the stack.
* \tparam StackSize The size of the stack buffer to reserve. The default is 256 characters. This amount includes the
* NUL terminator.
* \tparam Callable The type of callable that will be invoked with the formatted string and its size. The type should be
* `void(const char*, size_t)`; any return type will be ignored. The size given will not include the NUL terminator.
* \param fmt The `printf`-style format string.
* \param ap The collection of variadic arguments as initialized by `va_start` or `va_copy`.
* \param c The \c Callable that will be invoked after the string format. Any return value is ignored. It is undefined
* behavior to use the pointer value passed to \p c after \p c returns.
*/
template <size_t StackSize = 256, class Callable>
void withFormatNV(const char* fmt, va_list ap, Callable&& c) noexcept
{
char* heap = nullptr;
char buffer[StackSize];
va_list ap2;
va_copy(ap2, ap);
CARB_SCOPE_EXIT
{
va_end(ap2);
delete[] heap;
};
constexpr static char kErrorFormat[] = "<vsnprintf failed>";
constexpr static char kErrorAlloc[] = "<failed to allocate>";
// Optimistically try to format
char* pbuf = buffer;
int isize = std::vsnprintf(pbuf, StackSize, fmt, ap);
if (CARB_UNLIKELY(isize < 0))
{
c(kErrorFormat, CARB_COUNTOF(kErrorFormat) - 1);
return;
}
auto size = size_t(isize);
if (size >= StackSize)
{
// Need the heap
pbuf = heap = new (std::nothrow) char[size + 1];
if (CARB_UNLIKELY(!heap))
{
c(kErrorAlloc, CARB_COUNTOF(kErrorAlloc) - 1);
return;
}
isize = std::vsnprintf(pbuf, size + 1, fmt, ap2);
if (CARB_UNLIKELY(isize < 0))
{
c(kErrorFormat, CARB_COUNTOF(kErrorFormat) - 1);
return;
}
size = size_t(isize);
}
c(const_cast<const char*>(pbuf), size);
}
/**
* Formats as with vsnprintf() and calls a Callable with the result. The memory for the string is managed for the
* caller.
* \details This function attempts to use the stack first but will fall back to the heap if the given \p fmt and
* arguments do not fit on the stack.
* \tparam StackSize The size of the stack buffer to reserve. The default is 256 characters. This amount includes the
* NUL terminator.
* \tparam Callable The type of callable that will be invoked with the formatted string. The type should be
* `void(const char*)`; any return type will be ignored.
* \param fmt The `printf`-style format string.
* \param ap The collection of variadic arguments as initialized by `va_start` or `va_copy`.
* \param c The \c Callable that will be invoked after the string format. Any return value is ignored. It is undefined
* behavior to use the pointer value passed to \p c after \p c returns.
*/
template <size_t StackSize = 256, class Callable>
void withFormatV(const char* fmt, va_list ap, Callable&& c)
{
// Adapt to drop the size
withFormatNV<StackSize>(fmt, ap, [&](const char* p, size_t) { c(p); });
}
/**
* @copydoc CARB_FORMATTED
* \param size The size of the stack buffer to reserve. If the formatted string will be larger than this size, a buffer
* will be created on the heap instead, and destroyed once the callable returns.
*/
#define CARB_FORMATTED_SIZE(size, fmt, ...) \
do \
{ \
va_list CARB_JOIN(ap, __LINE__); \
va_start(CARB_JOIN(ap, __LINE__), fmt); \
CARB_SCOPE_EXIT \
{ \
va_end(CARB_JOIN(ap, __LINE__)); \
}; \
::carb::extras::withFormatV<size>((fmt), CARB_JOIN(ap, __LINE__), __VA_ARGS__); \
} while (0)
/**
* Formats a string as if by vsnprintf and invokes a callable with the result.
* \details This macro constructs a `va_list`, gathers the variadic parameters with `va_start`, formats the string with
* `std::vsnprintf`, and calls a Callable with the formatted string. This function reserves a stack buffer of the size
* requested by \c size for \ref CARB_FORMATTED_SIZE or a default size for \ref CARB_FORMATTED, but if the formatted
* string will not fit into that buffer, will use the heap to create a larger buffer.
* \param fmt The `printf`-style format string.
* \param ... A Callable that may be invoked as via `...(p)` where `p` is a `const char*`, such as a lambda, functor or
* function pointer. Retaining and reading `p` after the Callable returns is undefined behavior. If an error occurs
* with `std::vsnprintf` then `p` will be `<vsnprintf failed>`, or if a heap buffer was required and allocation
* failed, then `p` will be `<failed to allocate>`. If you wish the callback to receive the length of the formatted
* string as well, use \ref CARB_FORMATTED_N() or \ref CARB_FORMATTED_N_SIZE().
* \note This macro is intended to be used in variadic functions as a simple means of replacing uses of
* `std::vsnprintf`.
* ```cpp
* void myLogFunction(const char* fmt, ...) {
* CARB_FORMATTED([&](const char* p) {
* log(p);
* });
* }
* ```
* \see CARB_FORMATTED(), CARB_FORMATTED_SIZE(), CARB_FORMATTED_N(), CARB_FORMATTED_N_SIZE(),
* carb::extras::withFormatNV(), carb::extras::withFormatV()
*/
#define CARB_FORMATTED(fmt, ...) CARB_FORMATTED_SIZE(256, fmt, __VA_ARGS__)
/**
* @copydoc CARB_FORMATTED_N
* \param size The size of the stack buffer to reserve. If the formatted string will be larger than this size, a buffer
* will be created on the heap instead, and destroyed once the callable returns.
*/
#define CARB_FORMATTED_N_SIZE(size, fmt, ...) \
do \
{ \
va_list CARB_JOIN(ap, __LINE__); \
va_start(CARB_JOIN(ap, __LINE__), fmt); \
CARB_SCOPE_EXIT \
{ \
va_end(CARB_JOIN(ap, __LINE__)); \
}; \
::carb::extras::withFormatNV<size>((fmt), CARB_JOIN(ap, __LINE__), __VA_ARGS__); \
} while (0)
/**
* Formats a string as if by vsnprintf and invokes a callable with the result and the length.
* \details This macro constructs a `va_list`, gathers the variadic parameters with `va_start`, formats the string with
* `std::vsnprintf`, and calls a Callable with the formatted string and length. This function reserves a stack buffer of
* the size requested by \c size for \ref CARB_FORMATTED_N_SIZE or a default size for \ref CARB_FORMATTED_N, but if the
* formatted string will not fit into the stack buffer, will use the heap to create a larger buffer.
* \param fmt The `printf`-style format string.
* \param ... A Callable that may be invoked as via `...(p, n)` (where `p` is a `const char*` and `n` is a `size_t`),
* such as a lambda, functor or function pointer. Retaining and reading `p` after the Callable returns is undefined
* behavior. If an error occurs with `std::vsnprintf` then `p` will be `<vsnprintf failed>`, or if a heap buffer was
* required and allocation failed, then `p` will be `<failed to allocate>`. If you do not need the length provided to
* the Callable, use \ref CARB_FORMATTED() or \ref CARB_FORMATTED_SIZE() instead.
* \note This macro is intended to be used in variadic functions as a simple means of replacing uses of
* `std::vsnprintf`.
* ```cpp
* void myLogFunction(const char* fmt, ...) {
* CARB_FORMATTED_N([&](const char* p, size_t len) {
* log(p, len);
* });
* }
* ```
*/
#define CARB_FORMATTED_N(fmt, ...) CARB_FORMATTED_N_SIZE(256, fmt, __VA_ARGS__)
} // namespace extras
} // namespace carb
|
omniverse-code/kit/include/carb/math/Util.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite math utility functions
#pragma once
#include "../cpp/Bit.h"
#include "../Defines.h"
#include <array>
#if CARB_COMPILER_MSC
extern "C"
{
unsigned char _BitScanReverse(unsigned long* _Index, unsigned long _Mask);
unsigned char _BitScanReverse64(unsigned long* _Index, uint64_t _Mask);
unsigned char _BitScanForward(unsigned long* _Index, unsigned long _Mask);
unsigned char _BitScanForward64(unsigned long* _Index, uint64_t _Mask);
}
# pragma intrinsic(_BitScanReverse)
# pragma intrinsic(_BitScanReverse64)
# pragma intrinsic(_BitScanForward)
# pragma intrinsic(_BitScanForward64)
#elif CARB_COMPILER_GNUC
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
namespace carb
{
/** Namespace for various math helper functions. */
namespace math
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
// The Helper class is specialized by type and size since many intrinsics have different names for different sizes. This
// allows implementation of a helper function in the Helper class for the minimum size supported. Since each size
// inherits from the smaller size, the minimum supported size will be selected. This also means that even though a
// function is implemented in the size==1 specialization, for instance, it must be understood that T may be larger than
// size 1.
template <class T, size_t Size = sizeof(T)>
class Helper;
// Specialization for functions where sizeof(T) >= 1
template <class T>
class Helper<T, 1>
{
public:
static_assert(std::numeric_limits<T>::is_specialized, "Requires numeric type");
using Signed = typename std::make_signed_t<T>;
using Unsigned = typename std::make_unsigned_t<T>;
static int numLeadingZeroBits(const T& val)
{
# if CARB_COMPILER_MSC
unsigned long result;
if (_BitScanReverse(&result, (unsigned long)(Unsigned)val))
return int((sizeof(T) * 8 - 1) - result);
return int(sizeof(T) * 8);
# else
constexpr size_t BitDiff = 8 * (sizeof(unsigned int) - sizeof(T));
return val ? int(__builtin_clz((unsigned int)(Unsigned)val) - BitDiff) : int(sizeof(T) * 8);
# endif
}
// BitScanForward implementation for 1-4 byte integers.
static int bitScanForward(const T& val)
{
# if CARB_COMPILER_MSC
unsigned long result;
if (_BitScanForward(&result, (unsigned long)(Unsigned)val))
{
// BitScanForward returns the bit position zero-indexed, but we want to return the bit index + 1 to allow
// returning 0 to indicate that no bit is set
return (int)(result + 1);
}
return 0;
# else
return __builtin_ffs((unsigned int)(Unsigned)val);
# endif
}
// BitScanReverse implementation for 1-4 byte integers.
static int bitScanReverse(const T& val)
{
# if CARB_COMPILER_MSC
unsigned long result;
if (_BitScanReverse(&result, (unsigned long)(Unsigned)val))
{
// BitScanReverse returns the bit position zero-indexed, but we want to return the bit index + 1 to allow
// returning 0 to indicate that no bit is set
return (int)(result + 1);
}
return 0;
# else
// The most significant set bit is calculated from the total number of bits minus the number of leading zeroes
return val ? int(int(sizeof(unsigned int) * 8) - __builtin_clz((unsigned int)(Unsigned)val)) : 0;
# endif
}
};
// Specialization for functions where sizeof(T) >= 2
template <class T>
class Helper<T, 2> : public Helper<T, 1>
{
public:
using Base = Helper<T, 1>;
using typename Base::Signed;
using typename Base::Unsigned;
};
// Specialization for functions where sizeof(T) >= 4
template <class T>
class Helper<T, 4> : public Helper<T, 2>
{
public:
using Base = Helper<T, 2>;
using typename Base::Signed;
using typename Base::Unsigned;
};
// Specialization for functions where sizeof(T) >= 8
template <class T>
class Helper<T, 8> : public Helper<T, 4>
{
public:
using Base = Helper<T, 4>;
using typename Base::Signed;
using typename Base::Unsigned;
static int numLeadingZeroBits(const T& val)
{
# if CARB_COMPILER_MSC
unsigned long result;
if (_BitScanReverse64(&result, (Unsigned)val))
return int((sizeof(T) * 8 - 1) - result);
return int(sizeof(T) * 8);
# else
constexpr int BitDiff = int(8 * (sizeof(uint64_t) - sizeof(T)));
static_assert(BitDiff == 0, "Unexpected size");
return val ? (__builtin_clzll((Unsigned)val) - BitDiff) : int(sizeof(T) * 8);
# endif
}
// BitScanForward implementation for 8 byte integers
static int bitScanForward(const T& val)
{
static_assert(sizeof(T) == sizeof(uint64_t), "Unexpected size");
# if CARB_COMPILER_MSC
unsigned long result;
if (_BitScanForward64(&result, (Unsigned)val))
{
// BitScanForward returns the bit position zero-indexed, but we want to return the bit index + 1 to allow
// returning 0 to indicate that no bit is set
return (int)(result + 1);
}
return 0;
# else
return __builtin_ffsll((Unsigned)val);
# endif
}
// BitScanReverse implementation for 8 byte integers
static int bitScanReverse(const T& val)
{
static_assert(sizeof(T) == sizeof(uint64_t), "Unexpected size");
# if CARB_COMPILER_MSC
unsigned long result;
if (_BitScanReverse64(&result, (Unsigned)val))
{
// BitScanReverse returns the bit position zero-indexed, but we want to return the bit index + 1 to allow
// returning 0 to indicate that no bit is set
return (int)(result + 1);
}
return 0;
# else
return val ? int(int(sizeof(uint64_t) * 8) - __builtin_clzll((Unsigned)val)) : 0;
# endif
}
};
} // namespace detail
#endif
/**
* Returns whether the given integer value is a power of two.
*
* @param[in] val The non-zero integer value. Negative numbers are treated as unsigned values.
* @returns true if the integer value is a power of two; false otherwise. Undefined behavior arises if \p val is zero.
*/
template <class T>
constexpr bool isPowerOf2(const T& val)
{
// must be an integer type
static_assert(std::is_integral<T>::value, "Requires integer type");
CARB_ASSERT(val != 0); // 0 is undefined
using Uns = typename std::make_unsigned_t<T>;
return (Uns(val) & (Uns(val) - 1)) == 0;
}
/**
* Returns the number of leading zero bits for an integer value.
*
* @param[in] val The integer value
* @returns The number of most-significant zero bits. For a zero value, returns the number of bits for the type T.
*/
template <class T>
int numLeadingZeroBits(const T& val)
{
// must be an integer type
static_assert(std::is_integral<T>::value, "Requires integer type");
return detail::Helper<T>::numLeadingZeroBits(val);
}
/**
* Searches an integer value from least significant bit to most significant bit for the first set (1) bit.
*
* @param[in] val The integer value
* @return One plus the bit position of the first set bit, or zero if \p val is zero.
*/
template <class T>
int bitScanForward(const T& val)
{
// must be an integer type
static_assert(std::numeric_limits<T>::is_integer, "Requires integer type");
return detail::Helper<T>::bitScanForward(val);
}
/**
* Searches an integer value from most significant bit to least significant bit for the first set (1) bit.
*
* @param[in] val The integer value
* @return One plus the bit position of the first set bit, or zero if \p val is zero.
*/
template <class T>
int bitScanReverse(const T& val)
{
// must be an integer type
static_assert(std::numeric_limits<T>::is_integer, "Requires integer type");
return detail::Helper<T>::bitScanReverse(val);
}
/**
* Returns the number of set (1) bits in an integer value.
*
* @param[in] val The integer value
* @return The number of set (1) bits.
*/
template <class T>
int popCount(const T& val)
{
// must be an integer type
static_assert(std::numeric_limits<T>::is_integer, "Requires integer type");
return cpp::popcount(static_cast<typename std::make_unsigned_t<T>>(val));
}
} // namespace math
} // namespace carb
|
omniverse-code/kit/include/carb/cpp20/Semaphore.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "Atomic.h"
#include "../cpp/Semaphore.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::binary_semaphore;
using ::carb::cpp::counting_semaphore;
} // namespace cpp20
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({
carb::cpp20::binary_semaphore sema1{ false };
carb::cpp20::counting_semaphore<128> sema2{ 0 };
CARB_UNUSED(sema1, sema2);
});
|
omniverse-code/kit/include/carb/cpp20/Memory.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "../cpp17/Memory.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::construct_at;
} // namespace cpp20
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({ static_assert(std::is_function<decltype(carb::cpp20::construct_at<bool>)>::value, ""); });
|
omniverse-code/kit/include/carb/cpp20/TypeTraits.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "../cpp17/TypeTraits.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
//! (Deprecated) Namespace for C++20 features using C++14 semantics. Use \ref carb::cpp instead.
namespace cpp20
{
using ::carb::cpp::is_nothrow_convertible;
using ::carb::cpp::remove_cvref;
using ::carb::cpp::remove_cvref_t;
using ::carb::cpp::type_identity;
using ::carb::cpp::type_identity_t;
} // namespace cpp20
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({
static_assert(carb::cpp20::is_nothrow_convertible<bool, int>::value, "1");
static_assert(std::is_same<int, carb::cpp20::remove_cvref<const int&>::type>::value, "2");
static_assert(std::is_same<int, carb::cpp20::remove_cvref_t<const int&>>::value, "3");
static_assert(std::is_same<int, carb::cpp20::type_identity<int>::type>::value, "4");
static_assert(std::is_same<int, carb::cpp20::type_identity_t<int>>::value, "4");
});
|
omniverse-code/kit/include/carb/cpp20/Barrier.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "Atomic.h"
#include "Bit.h"
#include "../cpp/Barrier.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::barrier;
}
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({ carb::cpp20::barrier<> val{ 5 }; });
|
omniverse-code/kit/include/carb/cpp20/Latch.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "Atomic.h"
#include "../cpp/Latch.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::latch;
}
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({ carb::cpp20::latch l{ 5 }; });
|
omniverse-code/kit/include/carb/cpp20/Span.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "TypeTraits.h"
#include "../cpp17/StdDef.h"
#include "../cpp/Span.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::data; // From ImplData.h
using ::carb::cpp::dynamic_extent;
using ::carb::cpp::span;
} // namespace cpp20
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({
static_assert(std::is_function<decltype(carb::cpp20::data<int, 5>)>::value, "");
static_assert(carb::cpp20::dynamic_extent == size_t(-1), "");
static_assert(std::is_class<carb::cpp20::span<int, 5>>::value, "");
});
|
omniverse-code/kit/include/carb/cpp20/Bit.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "TypeTraits.h"
#include "../cpp/Bit.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::bit_cast;
using ::carb::cpp::bit_ceil;
using ::carb::cpp::bit_floor;
using ::carb::cpp::countl_zero;
using ::carb::cpp::countr_zero;
using ::carb::cpp::endian;
using ::carb::cpp::has_single_bit;
using ::carb::cpp::popcount;
} // namespace cpp20
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({
static_assert(std::is_function<decltype(carb::cpp20::bit_cast<int, unsigned>)>::value, "1");
static_assert(std::is_function<decltype(carb::cpp20::bit_ceil<unsigned>)>::value, "2");
static_assert(std::is_function<decltype(carb::cpp20::bit_floor<unsigned>)>::value, "3");
static_assert(std::is_function<decltype(carb::cpp20::countl_zero<unsigned>)>::value, "4");
static_assert(std::is_function<decltype(carb::cpp20::countr_zero<unsigned>)>::value, "5");
static_assert(std::is_enum<carb::cpp20::endian>::value, "6");
static_assert(std::is_function<decltype(carb::cpp20::has_single_bit<unsigned>)>::value, "7");
static_assert(std::is_function<decltype(carb::cpp20::popcount<unsigned>)>::value, "8");
});
|
omniverse-code/kit/include/carb/cpp20/Atomic.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Redirection for backwards compatibility
#pragma once
#include "../cpp/Atomic.h"
CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead")
namespace carb
{
namespace cpp20
{
using ::carb::cpp::atomic;
using ::carb::cpp::atomic_bool;
using ::carb::cpp::atomic_char;
using ::carb::cpp::atomic_char16_t;
using ::carb::cpp::atomic_char32_t;
using ::carb::cpp::atomic_int;
using ::carb::cpp::atomic_int16_t;
using ::carb::cpp::atomic_int32_t;
using ::carb::cpp::atomic_int64_t;
using ::carb::cpp::atomic_int8_t;
using ::carb::cpp::atomic_int_fast16_t;
using ::carb::cpp::atomic_int_fast32_t;
using ::carb::cpp::atomic_int_fast64_t;
using ::carb::cpp::atomic_int_fast8_t;
using ::carb::cpp::atomic_int_least16_t;
using ::carb::cpp::atomic_int_least32_t;
using ::carb::cpp::atomic_int_least64_t;
using ::carb::cpp::atomic_int_least8_t;
using ::carb::cpp::atomic_intmax_t;
using ::carb::cpp::atomic_intptr_t;
using ::carb::cpp::atomic_llong;
using ::carb::cpp::atomic_long;
using ::carb::cpp::atomic_notify_all;
using ::carb::cpp::atomic_notify_one;
using ::carb::cpp::atomic_ptrdiff_t;
using ::carb::cpp::atomic_ref;
using ::carb::cpp::atomic_schar;
using ::carb::cpp::atomic_short;
using ::carb::cpp::atomic_size_t;
using ::carb::cpp::atomic_uchar;
using ::carb::cpp::atomic_uint;
using ::carb::cpp::atomic_uint16_t;
using ::carb::cpp::atomic_uint32_t;
using ::carb::cpp::atomic_uint64_t;
using ::carb::cpp::atomic_uint8_t;
using ::carb::cpp::atomic_uint_fast16_t;
using ::carb::cpp::atomic_uint_fast32_t;
using ::carb::cpp::atomic_uint_fast64_t;
using ::carb::cpp::atomic_uint_fast8_t;
using ::carb::cpp::atomic_uint_least16_t;
using ::carb::cpp::atomic_uint_least32_t;
using ::carb::cpp::atomic_uint_least64_t;
using ::carb::cpp::atomic_uint_least8_t;
using ::carb::cpp::atomic_uintmax_t;
using ::carb::cpp::atomic_uintptr_t;
using ::carb::cpp::atomic_ullong;
using ::carb::cpp::atomic_ulong;
using ::carb::cpp::atomic_ushort;
using ::carb::cpp::atomic_wait;
using ::carb::cpp::atomic_wait_explicit;
using ::carb::cpp::atomic_wchar_t;
} // namespace cpp20
} // namespace carb
CARB_INCLUDE_PURIFY_TEST({
static_assert(std::is_class<carb::cpp20::atomic<int>>::value, "1");
static_assert(std::is_class<carb::cpp20::atomic_ref<int>>::value, "2");
static_assert(std::is_function<decltype(carb::cpp20::atomic_wait<int>)>::value, "3");
static_assert(std::is_function<decltype(carb::cpp20::atomic_wait_explicit<int>)>::value, "4");
static_assert(std::is_function<decltype(carb::cpp20::atomic_notify_one<int>)>::value, "5");
static_assert(std::is_function<decltype(carb::cpp20::atomic_notify_all<int>)>::value, "6");
});
|
omniverse-code/kit/include/carb/detail/DeferredLoad.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Internal utilities for loading Carbonite functions at runtime.
#include "../Defines.h"
#if !defined(CARB_REQUIRE_LINKED) || defined(DOXYGEN_BUILD)
//! Changes how the `carbReallocate` symbol is acquired.
//!
//! If \c CARB_REQUIRE_LINKED is defined as 1 before this file is included, then Carbonite-provided functions (e.g.
//! `carbReallocate` and `omniGetErrorApi`) will be imported from \e carb.dll or \e libcarb.so and the binary must link
//! against the import library for the module. This can be useful for applications that want to use these functions
//! prior to initializing the framework.
//!
//! If not defined or defined as \c 0, the functions will be marked weakly-linked and the binary need not link against
//! the import library. Attempting to call these functions will dynamically attempt to find then in the already-loaded
//! \e carb module. If it cannot be found a warning will be thrown.
//!
//! \see CARB_DETAIL_DEFINE_DEFERRED_LOAD
//! \see carbReallocate
# define CARB_REQUIRE_LINKED 0
#endif
//! Create a "deferred loader" function.
//!
//! \param fn_name_ The name of the function to define.
//! \param symbol_ The target function to attempt to load.
//! \param type_pack_ The type of the symbol to load as a parenthesized pack. For example, if the target \c symbol_
//! refers to something like `int foo(char, double)`, this would be `(int (*)(char, double))`. The enclosing
//! parenthesis are needed because these arguments contain spaces and commas.
#define CARB_DETAIL_DEFINE_DEFERRED_LOAD(fn_name_, symbol_, type_pack_) \
inline auto fn_name_()->CARB_DEPAREN(type_pack_) \
{ \
CARB_DETAIL_DEFINE_DEFERRED_LOAD_IMPL(symbol_, type_pack_); \
} \
static_assert(true, "follow with ;")
#if CARB_REQUIRE_LINKED || defined DOXYGEN_BUILD
//! \cond DEV
//! Implementation of the function body for \c CARB_DETAIL_DEFINE_DEFERRED_LOAD.
# define CARB_DETAIL_DEFINE_DEFERRED_LOAD_IMPL(symbol_, type_pack_) return &symbol_
//! \endcond DEV
#elif CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS
# define CARB_DETAIL_DEFINE_DEFERRED_LOAD_IMPL(symbol_, type_pack_) \
auto impl = &symbol_; \
CARB_FATAL_UNLESS(impl != nullptr, "Could not find `" CARB_STRINGIFY( \
symbol_) "` function -- make sure that libcarb.so is loaded"); \
return impl
#elif CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
# define CARB_DETAIL_DEFINE_DEFERRED_LOAD_IMPL(symbol_, type_pack_) \
using TargetSymbolType = CARB_DEPAREN(type_pack_); \
static TargetSymbolType cached_impl = nullptr; \
if (!cached_impl) \
{ \
HMODULE carb_dll_h = GetModuleHandleW(L"carb.dll"); \
CARB_FATAL_UNLESS(carb_dll_h != nullptr, "Could not find `carb.dll` module -- make sure that it is loaded"); \
cached_impl = reinterpret_cast<TargetSymbolType>(GetProcAddress(carb_dll_h, CARB_STRINGIFY(symbol_))); \
CARB_FATAL_UNLESS( \
cached_impl != nullptr, \
"Could not find `" CARB_STRINGIFY( \
symbol_) "` function at runtime -- #define CARB_REQUIRE_LINKED 1 before including this file"); \
} \
return cached_impl
#else
# define CARB_DETAIL_DEFINE_DEFERRED_LOAD_IMPL(symbol_, type_pack_) CARB_UNSUPPORTED_PLATFORM()
#endif
|
omniverse-code/kit/include/carb/detail/NoexceptType.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \cond DEV
//! \file
//!
//! \brief Workaround for GCC's \c -Wnoexcept-type warning in pre-C++17.
#pragma once
#include "../Defines.h"
//! \def CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE
//! Push a new layer of diagnostic checks which ignore GCC's \c noexcept-type warning. If this warning is not relevant
//! for the compiler configuration, this does nothing.
//!
//! GCC 7 before C++17 warns you about using a `R(*)(Args...) noexcept` as a type parameter because the mangling will
//! change in C++17. If you do not rely on mangling (as is the case of most inlined code), then this warning can be
//! safely ignored. The only case where an inlined function relies on mangling rules is if you rely on a function-local
//! static to be the same across shared object boundaries between two functions with different `noexcept` specifiers,
//! which is not common. See the GCC bug (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80985) for additional details.
//!
//! Use of this macro should always be paired with \c CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE.
//!
//! \code
//! void foo() noexcept;
//!
//! CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE()
//! template <typename F>
//! void bar(F f) // <- error would occur here
//! {
//! f();
//! }
//! CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE()
//!
//! int main()
//! {
//! bar(foo); // <- attempt to provide `F = void(*)() noexcept`
//! }
//! \endcode
//!
//! \def CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE
//! The opposite of \c CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE -- pops one layer of diagnostics if push added one. If
//! \c CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE did nothing, then this macro will also do nothing.
#if __cplusplus < 201703L && CARB_COMPILER_GNUC && !CARB_TOOLCHAIN_CLANG && __GNUC__ == 7
# define CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE() CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wnoexcept-type")
# define CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE() CARB_IGNOREWARNING_GNUC_POP
#else
# define CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE()
# define CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE()
#endif
//! \endcond
|
omniverse-code/kit/include/carb/eventdispatcher/EventDispatcherBindingsPython.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../dictionary/DictionaryBindingsPython.h"
#include "../variant/VariantBindingsPython.h"
#include "IEventDispatcher.h"
namespace carb
{
namespace eventdispatcher
{
inline variant::Variant objectToVariant(const py::handle& o)
{
if (py::isinstance<py::bool_>(o))
{
return variant::Variant(o.cast<bool>());
}
else if (py::isinstance<py::int_>(o))
{
return variant::Variant(o.cast<int64_t>());
}
else if (py::isinstance<py::float_>(o))
{
return variant::Variant(o.cast<double>());
}
else if (py::isinstance<py::str>(o))
{
auto str = o.cast<std::string>();
return variant::Variant(omni::string(str.begin(), str.end()));
}
else
{
return variant::Variant(o.cast<py::object>());
}
}
// Requires the GIL
inline py::object variantToObject(const variant::Variant& v)
{
if (v.data().vtable->typeName == variant::eBool)
{
return py::bool_(v.getValue<bool>().value());
}
else if (v.data().vtable->typeName == variant::eFloat || v.data().vtable->typeName == variant::eDouble)
{
return py::float_(v.getValue<double>().value());
}
else if (v.data().vtable->typeName == variant::eString)
{
omni::string str = v.getValue<omni::string>().value();
return py::str(str.data(), str.length());
}
else if (v.data().vtable->typeName == variant::eCharPtr)
{
const char* p = v.getValue<const char*>().value();
return py::str(p);
}
else if (v.data().vtable->typeName == variant::eDictionary)
{
auto item = v.getValue<const dictionary::Item*>().value();
auto iface = getCachedInterface<dictionary::IDictionary>();
CARB_ASSERT(iface, "Failed to acquire interface IDictionary");
return dictionary::getPyObject(iface, item);
}
else if (v.data().vtable->typeName == variant::PyObjectVTable::get()->typeName)
{
return v.getValue<py::object>().value();
}
else
{
// Try numeric
auto intval = v.getValue<int64_t>();
if (intval)
return py::int_(intval.value());
CARB_LOG_WARN("Unknown type %s to convert to python object; using None", v.data().vtable->typeName.c_str());
CARB_ASSERT(false, "Unknown type %s to convert to python", v.data().vtable->typeName.c_str());
return py::none();
}
}
class PyEvent : public std::enable_shared_from_this<PyEvent>
{
const Event* p;
std::vector<NamedVariant> variants;
CARB_PREVENT_COPY_AND_MOVE(PyEvent);
public:
RString eventName;
PyEvent(const Event& e) : p(&e), eventName(p->eventName)
{
}
void endRef()
{
if (p)
{
// Would use weak_from_this(), but need C++17; check against 2 since shared_from_this() will increase the
// count by one.
if (this->shared_from_this().use_count() > 2)
{
// Need a local copy
variants = { p->variants, p->variants + p->numVariants };
}
p = nullptr;
}
}
bool hasKey(const char* pkey) const
{
RStringKey key(pkey);
if (p)
return p->hasKey(key);
return std::binary_search(variants.begin(), variants.end(), NamedVariant{ key, {} }, detail::NamedVariantLess{});
}
py::object get(const char* pkey) const
{
const variant::Variant* v = nullptr;
RStringKey key(pkey);
if (p)
v = p->get(key);
else
{
auto iter =
std::lower_bound(variants.begin(), variants.end(), NamedVariant{ key, {} }, detail::NamedVariantLess{});
if (iter != variants.end() && iter->name == key)
v = &iter->value;
}
return v ? variantToObject(*v) : py::none();
}
};
using PyEventPtr = std::shared_ptr<PyEvent>;
inline void definePythonModule(py::module& m)
{
m.def("acquire_eventdispatcher_interface", []() { return getCachedInterface<IEventDispatcher>(); },
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>(),
R"(Acquires the Event Dispatcher interface.)");
py::class_<ObserverGuard, std::shared_ptr<ObserverGuard>>(m, "ObserverGuard", R"(ObserverGuard.
Lifetime control for a registered observer. Unregister the observer by calling the reset() function or allowing the
object to be collected.)")
.def("reset", [](ObserverGuard& self) { self.reset(); }, py::call_guard<py::gil_scoped_release>(),
R"(Explicitly stops an observer.
Having this object collected has the same effect, implicitly.
This is safe to perform while dispatching.
Since observers can be in use by this thread or any thread, this function is carefully synchronized with all other
Event Dispatcher operations.
- During `reset()`, further calls to the observer are prevented, even if other threads are currently dispatching an
event that would be observed by the observer in question.
- If any other thread is currently calling the observer in question, `reset()` will wait until all other threads have
left the observer callback function.
- If the observer function is *not* in the backtrace of the current thread, the observer function is immediately
released.
- If the observer function is in the backtrace of the current thread, `reset()` will return without waiting and without
releasing the observer callback. Instead, releasing the function will be performed when the `dispatch_event()` call
in the current thread finishes.
When `reset()` returns, it is guaranteed that the observer callback function will no longer be called and all calls to
it have completed (except if the calling thread is dispatching).)");
py::class_<PyEvent, PyEventPtr>(m, "Event", R"(Event.
Contains the event_name and payload for a dispatched event.
)")
.def_property_readonly("event_name", [](const PyEventPtr& self) { return self->eventName.c_str(); },
py::call_guard<py::gil_scoped_release>(), R"(The name of the event)")
.def("has_key", &PyEvent::hasKey, py::arg("key_name"), py::call_guard<py::gil_scoped_release>(),
R"(Returns True if a given key name is present in the payload.
Args:
key_name: The name of a key to check against the payload.
Returns:
`True` if the key is present in the payload; `False` otherwise.)")
.def("get", &PyEvent::get, py::arg("key_name") /* GIL managed internally */, R"(Accesses a payload item by key name.
Args:
key_name: The name of a key to find in the payload.
Returns:
None if the key is not present, otherwise returns an object representative of the type in the payload.)")
.def("__getitem__", &PyEvent::get, py::arg("key_name") /* GIL managed internally */,
R"(Accesses a payload item by key name.
Args:
key_name: The name of a key to find in the payload.
Returns:
None if the key is not present, otherwise returns an object representative of the type in the payload.)");
py::class_<IEventDispatcher>(m, "IEventDispatcher", R"()")
.def("observe_event",
[](IEventDispatcher* ed, int order, const char* eventName, std::function<void(PyEventPtr)> onEventFn,
py::handle filterDict) {
std::vector<NamedVariant> vec;
if (!filterDict.is_none())
{
auto dict = filterDict.cast<py::dict>();
vec.reserve(dict.size());
for (auto& entry : dict)
{
vec.push_back(
{ RStringKey(entry.first.cast<std::string>().c_str()), objectToVariant(entry.second) });
}
std::sort(vec.begin(), vec.end(), detail::NamedVariantLess{});
}
auto p = new decltype(onEventFn)(std::move(onEventFn));
auto func = [](const Event& e, void* ud) {
// Convert the event
auto event = std::make_shared<PyEvent>(e);
callPythonCodeSafe(*static_cast<decltype(onEventFn)*>(ud), event);
event->endRef();
};
auto cleanup = [](void* ud) { delete static_cast<decltype(onEventFn)*>(ud); };
py::gil_scoped_release nogil;
return ObserverGuard(
ed->internalObserveEvent(order, RString(eventName), vec.size(), vec.data(), func, cleanup, p));
},
py::arg("order") = 0, py::arg("event_name"), py::arg("on_event"), py::arg("filter") = py::none(),
py::return_value_policy::move,
R"(Registers an observer with the Event Dispatcher system.
An observer is a callback that is called whenever :func:`.dispatch_event` is called. The observers are invoked in the
thread that calls `dispatch_event()`, and multiple threads may be calling `dispatch_event()` simultaneously, so
observers must be thread-safe unless the application can ensure synchronization around `dispatch_event()` calls.
Observers can pass an optional dictionary of `filter` arguments. The key/value pairs of `filter` arguments cause an
observer to only be invoked for a `dispatch_event()` call that contains at least the same values. For instance, having a
filter dictionary of `{"WindowID": 1234}` will only cause the observer to be called if `dispatch_event()` is given the
same value as a `"WindowID"` parameter.
Observers can be added inside of an observer notification (i.e. during a call to `dispatch_event()`), however these new
observers will not be called for currently the dispatching event. A subsequent recursive call to `dispatch_event()` (on
the current thread only) will also call the new observer. The new observer will be available to all other threads once
the `dispatch_event()` call (in which it was added) completes.
Args:
order: (int) A value determining call order. Observers with lower order values are called earlier. Observers with
the same order value and same filter argument values will be called in the order they are registered. Observers
with the same order value with different filter arguments are called in an indeterminate order.
event_name: (str) The event name to observe
on_event: (function) A function that is invoked when an event matching `event_name` and any `filter` arguments is
dispatched.
filter: [optional] (dict) If present, must be a dict of key(str)/value(any) pairs.
Returns:
An ObserverGuard object that, when collected, removes the observer from the Event Dispatcher system.
)")
.def("has_observers",
[](IEventDispatcher* ed, const char* eventName, py::handle filterDict) {
std::vector<NamedVariant> vec;
if (!filterDict.is_none())
{
auto dict = filterDict.cast<py::dict>();
vec.reserve(dict.size());
for (auto& entry : dict)
{
vec.push_back(
{ RStringKey(entry.first.cast<std::string>().c_str()), objectToVariant(entry.second) });
}
std::sort(vec.begin(), vec.end(), detail::NamedVariantLess{});
}
py::gil_scoped_release nogil;
return ed->internalHasObservers(RString(eventName), vec.size(), vec.data());
},
py::arg("event_name"), py::arg("filter") = py::none(),
R"(Queries the Event Dispatcher whether any observers are listening to a specific event signature.
Emulates a call to :func:`.dispatch_event()` (without actually calling any observers) and returns `True` if any
observers would be called.
Args:
event_name: (str) The event name to query
filter: [optional] (dict) If present, must be a dict of key(str)/value(any) pairs.
Returns:
`True` if at least one observer would be called with the given `filter` arguments; `False` otherwise.)")
.def("dispatch_event",
[](IEventDispatcher* ed, const char* eventName, py::handle payload) {
std::vector<NamedVariant> vec;
if (!payload.is_none())
{
auto dict = payload.cast<py::dict>();
vec.reserve(dict.size());
for (auto& entry : dict)
{
vec.push_back({ RStringKey(entry.first.cast<std::string>().c_str()),
variant::Variant(entry.second.cast<py::object>()) });
}
std::sort(vec.begin(), vec.end(), detail::NamedVariantLess{});
}
py::gil_scoped_release nogil;
return ed->internalDispatch({ RString(eventName), vec.size(), vec.data() });
},
py::arg("event_name"), py::arg("payload") = py::none(),
R"(Dispatches an event and immediately calls all observers that would observe this particular event.
Finds and calls all observers (in the current thread) that observe the given event signature.
It is safe to recursively dispatch events (i.e. call `dispatch_event()` from within a called observer), but care must be
taken to avoid endless recursion. See the rules in :func:`.observe_event()` for observers added during a
`dispatch_event()` call.
Args:
event_name: (str) The name of the event to dispatch
payload: (dict) If present, must be a dict of key(str)/value(any) pairs.
Returns:
The number of observers that were called, excluding those from recursive calls.)");
}
} // namespace eventdispatcher
} // namespace carb
|
omniverse-code/kit/include/carb/eventdispatcher/EventDispatcherTypes.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Type definitions for *carb.eventdispatcher.plugin*
#pragma once
#include "../Strong.h"
#include "../variant/VariantUtils.h"
namespace carb
{
namespace eventdispatcher
{
//! A handle to an observer, registered with \ref IEventDispatcher::observeEvent().
CARB_STRONGTYPE(Observer, size_t);
//! Special value indicating an invalid observer.
constexpr Observer kInvalidObserver{};
//! Structure definition for a named variant: a key/value pair with a value of varying type.
struct NamedVariant
{
RStringKey name; //!< The key
variant::Variant value; //!< The value
};
static_assert(std::is_standard_layout<NamedVariant>::value, ""); // Not interop-safe as it is not trivially copyable
//! Structure definition for event data. Typically not used; instead use the \ref Event wrapper-class.
struct EventData
{
RString eventName; //!< The name of the event
size_t numVariants; //!< Number of items in the \c variants array member
NamedVariant const* variants; //!< An array of \ref NamedVariant of length \c numVariants
};
CARB_ASSERT_INTEROP_SAFE(EventData);
//! A presentation class for \ref EventData. Allows querying the data via a simple C++ interface.
class Event final : public EventData
{
CARB_PREVENT_COPY_AND_MOVE(Event);
public:
/**
* Returns true if an Event contains the requested key.
*
* @param key The key to query.
* @returns \c true if the key is contained in the Event, \c false otherwise.
*/
bool hasKey(RStringKey key) const;
/**
* Returns a variant value from the event by key.
* @param key The key to query.
* @returns A \ref variant::Variant representing the item if the key is present; \c nullptr otherwise.
*/
const variant::Variant* get(RStringKey key) const;
/**
* Retrieves a value from the Event by key.
*
* @tparam T The requested type to convert the value to.
* @param key The key to query.
* @returns An \c optional value where \c has_value() is \c true if the key exists and the variant value that it
* represents can be converted to type \c T. Otherwise returns an empty \c optional.
*/
template <class T>
cpp::optional<T> getValue(RStringKey key) const;
/**
* Retrieves a value from the Event by key, or a fallback value.
*
* Effectively the same as `getValue<T>(key).value_or(defaultValue)`
*
* @tparam T The requested type to convert the value to.
* @param key The key to query.
* @param defaultValue A value to return if the key does not exist or is not convertible to \c T.
*/
template <class T>
T getValueOr(RStringKey key, T&& defaultValue) const;
};
static_assert(sizeof(Event) == sizeof(EventData), "");
//! Callback function called when an event is dispatched. Typically not manually used as it is generated by
//! \ref IEventDispatcher::observeEvent().
using ObserverFn = void (*)(const Event&, void*);
//! Callback function called when an observer is terminated with \ref IEventDispatcher::stopObserving(). Typically not
//! manually used as it is generated by \ref IEventDispatcher::observeEvent().
using CleanupFn = void (*)(void*);
//! Structure to manage the lifetime of an observer. Similar to \c std::unique_ptr.
class ObserverGuard
{
public:
CARB_PREVENT_COPY(ObserverGuard);
/**
* Default constructor. Constructs an empty \c ObserverGuard.
*/
constexpr ObserverGuard() noexcept;
/**
* Constructor that accepts an \ref Observer handle.
* @param o The \ref Observer to manage.
*/
constexpr explicit ObserverGuard(Observer o) noexcept;
/**
* Move constructor. Moves the \ref Observer managed by \p other to \c *this and leaves \p other empty.
* @param other The other \c ObserverGuard.
*/
ObserverGuard(ObserverGuard&& other) noexcept;
/**
* Destructor.
*/
~ObserverGuard() noexcept;
/**
* Move-assign operator. Moves the \ref Observer managed by \p other to \c *this.
* @param other The other \c ObserverGuard.
*/
ObserverGuard& operator=(ObserverGuard&& other) noexcept;
/**
* Releases the managed \ref Observer to the caller and leaves \c *this empty.
*
* @note This does not stop the managed \ref Observer.
* @return The \ref Observer previously managed by \c *this.
*/
Observer release() noexcept;
/**
* Stops any currently managed observer (as via \ref IEventDispatcher::stopObserving()) and takes ownership of the
* given \ref Observer.
*
* @param o The new \ref Observer to manage, or \ref kInvalidObserver to remain empty.
*/
void reset(Observer o = kInvalidObserver) noexcept;
/**
* Exchanges state with another \c ObserverGuard.
* @param o The other \c ObserverGuard.
*/
void swap(ObserverGuard& o) noexcept;
/**
* Returns the managed \ref Observer while maintaining management of it.
* @returns The managed \ref Observer.
*/
constexpr Observer get() const noexcept;
/**
* Validation test.
* @returns \c true if \c *this is non-empty (manages a valid observer); \c false otherwise.
*/
explicit operator bool() const noexcept;
private:
Observer m_o;
};
} // namespace eventdispatcher
} // namespace carb
|
omniverse-code/kit/include/carb/eventdispatcher/IEventDispatcher.inl | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "../variant/IVariant.h"
#include "../variant/VariantUtils.h"
namespace carb
{
namespace eventdispatcher
{
namespace detail
{
template <class T>
NamedVariant translate(std::pair<RStringKey, T>&& p)
{
return { p.first, variant::Variant{ p.second } };
}
struct NamedVariantLess
{
bool operator()(const NamedVariant& lhs, const NamedVariant& rhs)
{
return lhs.name.owner_before(rhs.name);
}
};
struct NamedVariantEqual
{
bool operator()(const NamedVariant& lhs, const NamedVariant& rhs)
{
return lhs.name == rhs.name;
}
};
} // namespace detail
inline constexpr ObserverGuard::ObserverGuard() noexcept : m_o(kInvalidObserver)
{
}
inline constexpr ObserverGuard::ObserverGuard(Observer o) noexcept : m_o(o)
{
}
inline ObserverGuard::ObserverGuard(ObserverGuard&& other) noexcept : m_o(std::exchange(other.m_o, kInvalidObserver))
{
}
inline ObserverGuard::~ObserverGuard() noexcept
{
reset();
}
inline ObserverGuard& ObserverGuard::operator=(ObserverGuard&& other) noexcept
{
swap(other);
return *this;
}
inline Observer ObserverGuard::release() noexcept
{
return std::exchange(m_o, kInvalidObserver);
}
inline void ObserverGuard::reset(Observer o) noexcept
{
if (m_o != kInvalidObserver)
{
auto iface = carb::getCachedInterface<IEventDispatcher>();
CARB_ASSERT(iface, "Failed to acquire interface IEventDispatcher");
iface->stopObserving(m_o);
}
m_o = o;
}
inline void ObserverGuard::swap(ObserverGuard& o) noexcept
{
std::swap(m_o, o.m_o);
}
constexpr inline Observer ObserverGuard::get() const noexcept
{
return m_o;
}
inline ObserverGuard::operator bool() const noexcept
{
return m_o != kInvalidObserver;
}
inline bool operator==(const ObserverGuard& lhs, const ObserverGuard& rhs)
{
return lhs.get() == rhs.get();
}
inline bool operator!=(const ObserverGuard& lhs, const ObserverGuard& rhs)
{
return lhs.get() != rhs.get();
}
inline bool operator<(const ObserverGuard& lhs, const ObserverGuard& rhs)
{
return lhs.get() < rhs.get();
}
inline void swap(ObserverGuard& lhs, ObserverGuard& rhs) noexcept
{
lhs.swap(rhs);
}
template <class Invocable, class... Args>
CARB_NODISCARD ObserverGuard
IEventDispatcher::observeEvent(int order, RString eventName, Invocable&& invocable, Args&&... filterArgs)
{
using FunctionType = std::function<void(const Event&)>;
auto pFunc = new FunctionType{ std::forward<Invocable>(invocable) };
std::array<NamedVariant, sizeof...(filterArgs)> variants{ detail::translate(std::forward<Args>(filterArgs))... };
std::sort(variants.begin(), variants.end(), detail::NamedVariantLess{});
return ObserverGuard(
internalObserveEvent(order, eventName, variants.size(), variants.data(),
[](const Event& event, void* ud) { (*static_cast<FunctionType*>(ud))(event); },
[](void* ud) { delete static_cast<FunctionType*>(ud); }, pFunc));
}
template <class Invocable, class InIter>
CARB_NODISCARD ObserverGuard
IEventDispatcher::observeEventIter(int order, RString eventName, Invocable&& invocable, InIter begin, InIter end)
{
using FunctionType = std::function<void(const Event&)>;
auto pFunc = new FunctionType{ std::forward<Invocable>(invocable) };
std::vector<NamedVariant> variants{ begin, end };
std::sort(variants.begin(), variants.end(), detail::NamedVariantLess{});
return ObserverGuard(
internalObserveEvent(order, eventName, variants.size(), variants.data(),
[](const Event& event, void* ud) { (*static_cast<FunctionType*>(ud))(event); },
[](void* ud) { delete static_cast<FunctionType*>(ud); }, pFunc));
}
template <class... Args>
bool IEventDispatcher::hasObservers(RString eventName, Args&&... filterArgs)
{
std::array<NamedVariant, sizeof...(filterArgs)> variants{ detail::translate(std::forward<Args>(filterArgs))... };
std::sort(variants.begin(), variants.end(), detail::NamedVariantLess{});
CARB_ASSERT(std::adjacent_find(variants.begin(), variants.end(), detail::NamedVariantEqual{}) == variants.end(),
"At least one non-unique key specified");
return internalHasObservers(eventName, variants.size(), variants.data());
}
template <class InIter>
bool IEventDispatcher::hasObserversIter(RString eventName, InIter begin, InIter end)
{
std::vector<NamedVariant> variants{ begin, end };
std::sort(variants.begin(), variants.end(), detail::NamedVariantLess{});
CARB_ASSERT(std::adjacent_find(variants.begin(), variants.end(), detail::NamedVariantEqual{}) == variants.end(),
"At least one non-unique key specified");
return internalHasObservers(eventName, variants.size(), variants.data());
}
template <class... Args>
size_t IEventDispatcher::dispatchEvent(RString eventName, Args&&... payload)
{
std::array<NamedVariant, sizeof...(payload)> variants{ detail::translate(std::forward<Args>(payload))... };
std::sort(variants.begin(), variants.end(), detail::NamedVariantLess{});
CARB_ASSERT(std::adjacent_find(variants.begin(), variants.end(), detail::NamedVariantEqual{}) == variants.end(),
"Event has duplicate keys");
return internalDispatch({ eventName, variants.size(), variants.data() });
}
template <class InIter>
size_t IEventDispatcher::dispatchEventIter(RString eventName, InIter begin, InIter end)
{
std::vector<NamedVariant> variants{ begin, end };
std::sort(variants.begin(), variants.end(), detail::NamedVariantLess{});
CARB_ASSERT(std::adjacent_find(variants.begin(), variants.end(), detail::NamedVariantEqual{}) == variants.end(),
"Event has duplicate keys");
return internalDispatch({ eventName, variants.size(), variants.data() });
}
inline const variant::Variant* Event::get(RStringKey key) const
{
auto iter = std::lower_bound(variants, variants + numVariants, NamedVariant{ key, {} }, detail::NamedVariantLess{});
if (iter != (variants + numVariants) && iter->name == key)
{
return &iter->value;
}
return nullptr;
}
inline bool Event::hasKey(RStringKey key) const
{
return std::binary_search(variants, variants + numVariants, NamedVariant{ key, {} }, detail::NamedVariantLess{});
}
template <class T>
cpp::optional<T> Event::getValue(RStringKey key) const
{
if (auto variant = get(key))
return variant->getValue<T>();
return {};
}
template <class T>
T Event::getValueOr(RStringKey key, T&& defaultValue) const
{
return getValue<T>(key).value_or(std::forward<T>(defaultValue));
}
} // namespace eventdispatcher
} // namespace carb
// Specialization for std::hash
template <>
struct std::hash<::carb::eventdispatcher::ObserverGuard>
{
size_t operator()(const ::carb::eventdispatcher::ObserverGuard& g) const noexcept
{
return std::hash<carb::eventdispatcher::Observer>{}(g.get());
}
};
|
omniverse-code/kit/include/carb/eventdispatcher/IEventDispatcher.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Interface definition for *carb.eventdispatcher.plugin*
#pragma once
#include "../Interface.h"
#include "EventDispatcherTypes.h"
namespace carb
{
//! Namespace for *carb.eventdispatcher.plugin* and related utilities.
namespace eventdispatcher
{
class ObserverGuard;
//! Interface for *carb.eventdispatcher.plugin*.
struct IEventDispatcher
{
CARB_PLUGIN_INTERFACE("carb::eventdispatcher::IEventDispatcher", 0, 1)
//! @private (see observeEvent())
Observer(CARB_ABI* internalObserveEvent)(int order,
RString eventName,
size_t numVariants,
NamedVariant const* variants,
ObserverFn fn,
CleanupFn cleanup,
void* ud);
/**
* Stops the given observer. Safe to perform while dispatching.
*
* Since observers can be in use by this thread or any thread, this function is carefully synchronized with all
* other IEventDispatcher operations.
* - During stopObserving(), further calls to the observer are prevented, even if other threads are currently
* dispatching an event that would be observed by the observer in question.
* - If any other thread is currently calling the observer in question, stopObserving() will wait until all other
* threads have left the observer function.
* - If the observer function is \b not in the callstack of the current thread, the cleanup function provided to
* \c internalObserveEvent() is called and any \ref variant::Variant objects captured to filter events are
* destroyed.
* - If the observer function is in the callstack of the current thread, stopObserving() will return without
* waiting, calling the cleanup function or destroying \ref variant::Variant objects. Instead, this cleanup will
* be performed when the \ref dispatchEvent() call in the current thread finishes.
*
* When stopObserving() returns, it is guaranteed that the observer function will no longer be called and all calls
* to it have completed (except if the calling thread is dispatching).
*
* @warning This function must be called exactly once per \ref Observer created by \ref observeEvent(). The
* \ref ObserverGuard calls this function automatically.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
*
* @param ob The \ref Observer to stop.
* @returns \c true if the Observer was found and stopped; \c false otherwise.
*/
bool(CARB_ABI* stopObserving)(Observer ob);
//! @private (see hasObservers())
bool(CARB_ABI* internalHasObservers)(RString eventName, size_t numVariants, NamedVariant const* variants);
//! @private (see dispatchEvent())
size_t(CARB_ABI* internalDispatch)(const EventData&);
/**
* Queries to see if the system is currently dispatching an event.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
*
* @param currentThread If \c false, checks to see if any thread is currently dispatching. However, the return value
* should be used for debugging purposes only as it is a transient value and could be stale by the time it is read
* by the application. If \c true, checks to see if the current thread is dispatching (that is, the callstack
* includes a call to \ref dispatchEvent()).
* @returns \c true if any thread or the current thread is dispatching based on the value of \p currentThread;
* \c false otherwise.
*/
bool(CARB_ABI* isDispatching)(bool currentThread);
/**
* Registers an observer with the Event Dispatcher system.
*
* An observer is an invocable object (function, functor, lambda, etc.) that is called whenever \ref dispatchEvent()
* is called. The observers are invoked in the thread that calls \ref dispatchEvent(), and multiple threads could be
* calling \ref dispatchEvent() simultaneously, so observers must be thread-safe unless the application can ensure
* synchronization around \ref dispatchEvent() calls.
*
* Observers can pass zero or any number of @p filterArgs parameters. These @p filterArgs cause an observer to only
* be invoked for a \ref dispatchEvent() call that contains at least the same values. For instance, having a filter
* pair for key "WindowID" with a specific value will only cause the observer to be called if \ref dispatchEvent()
* is given the same value as a "WindowID" parameter.
*
* Observers can be added inside of an observer notification (i.e. during a call to \ref dispatchEvent()), however
* these new observers will <b>not be called</b> for the currently dispatching event. A subsequent recursive call to
* \ref dispatchEvent() <em>(on the current thread only)</em> will also call the new observer. The new observer will
* be available to all other threads once the \ref dispatchEvent() call--in which it was added--returns.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
*
* @param order A value determining call order. Observers with lower order values are called earlier. Observers with
* the same order value and same filter argument values will be called in the order they are registered. Observers
* with the same order value with \a different filter argument values are called in an indeterminate order.
* @param eventName The name of the event to observe.
* @param invocable An object that is invoked when an event matching the \p eventName and \p filterArgs is
* dispatched. The object must be callable as `void(const Event&)`.
* @param filterArgs Zero or more arguments that filter observer invocations. Each argument must be of type
* `std::pair<RStringKey, T>` where the first parameter is the key and the second is the value. The value must be
* of a type understood by a \ref variant::Translator specialization.
* @returns An \ref ObserverGuard representing the lifetime of the observer. When the \ref ObserverGuard is reset or
* destroyed, the observer is unregistered as with \ref stopObserving().
*/
template <class Invocable, class... Args>
CARB_NODISCARD ObserverGuard observeEvent(int order, RString eventName, Invocable&& invocable, Args&&... filterArgs);
/**
* Registers an observer with the Event Dispatcher system.
*
* An observer is an invocable object (function, functor, lambda, etc.) that is called whenever \ref dispatchEvent()
* is called. The observers are invoked in the thread that calls \ref dispatchEvent(), and multiple threads could be
* calling \ref dispatchEvent() simultaneously, so observers must be thread-safe unless the application can ensure
* synchronization around \ref dispatchEvent() calls.
*
* Observers can pass zero or any number of @p filterArgs parameters. These @p filterArgs cause an observer to only
* be invoked for a \ref dispatchEvent() call that contains at least the same values. For instance, having a filter
* pair for key "WindowID" with a specific value will only cause the observer to be called if \ref dispatchEvent()
* is given the same value as a "WindowID" parameter.
*
* Observers can be added inside of an observer notification (i.e. during a call to \ref dispatchEvent()), however
* these new observers will <b>not be called</b> for the currently dispatching event. However, a recursive call to
* \ref dispatchEvent() <em>(on the current thread only)</em> will also call the new observer. The new observer will
* be available to all other threads once the \ref dispatchEvent() call--in which it was added--returns.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
*
* @param order A value determining call order. Observers with lower order values are called earlier. Observers with
* the same order value and same filter argument values will be called in the order they are registered. Observers
* with the same order value with \a different filter argument values are called in an indeterminate order.
* @param eventName The name of the event to observe.
* @param invocable An object that is invoked when an event matching the \p eventName and \p filterArgs is
* dispatched. The object must be callable as `void(const Event&)`.
* @tparam InIter An InputIterator that is forward-iterable and resolves to a \ref NamedVariant when dereferenced.
* @param begin An InputIterator representing the start of the filter parameters.
* @param end A past-the-end InputIterator representing the end of the filter parameters.
* @returns An \ref ObserverGuard representing the lifetime of the observer. When the \ref ObserverGuard is reset or
* destroyed, the observer is unregistered as with \ref stopObserving().
*/
template <class Invocable, class InIter>
CARB_NODISCARD ObserverGuard
observeEventIter(int order, RString eventName, Invocable&& invocable, InIter begin, InIter end);
/**
* Queries the Event Dispatcher whether any observers are listening to a specific event signature.
*
* Emulates a call to \ref dispatchEvent() (without actually calling any observers) and returns \c true if any
* observers would be called.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
* @param eventName The name of the event to query.
* @param filterArgs Zero or more key/value pairs that would be used for observer filtering as in a call to
* \ref dispatchEvent(). Each argument must be of type `std::pair<RStringKey, T>` where the first parameter is the
* key and the second is the value. The value must be of a type understood by a \ref variant::Translator
* specialization.
* @returns \c true if at least one observer would be called if the same arguments were passed to
* \ref dispatchEvent(); \c false otherwise.
*/
template <class... Args>
bool hasObservers(RString eventName, Args&&... filterArgs);
/**
* Queries the Event Dispatcher whether any observers are listening to a specific event signature.
*
* Emulates a call to \ref dispatchEvent() (without actually calling any observers) and returns \c true if any
* observers would be called.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
* @tparam InIter An InputIterator that is forward-iterable and resolves to a \ref NamedVariant when dereferenced.
* The entries are used for observer filtering.
* @param eventName The name of the event to query.
* @param begin An InputIterator representing the start of the event key/value pairs.
* @param end A past-the-end InputIterator representing the end of the event key/value pairs.
* @returns \c true if at least one observer would be called if the same arguments were passed to
* \ref dispatchEvent(); \c false otherwise.
*/
template <class InIter>
bool hasObserversIter(RString eventName, InIter begin, InIter end);
/**
* Dispatches an event and immediately calls all observers that would observe this particular event.
*
* Finds and calls all observers (in the current thread) that observe the given event signature.
*
* It is safe to recursively dispatch events (i.e. call dispatchEvent() from a called observer), but care must be
* taken to avoid endless recursion. See the rules in observeEvent() for observers added during a dispatchEvent()
* call.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
* @param eventName The name of the event to dispatch.
* @param payload Zero or more key/value pairs that are used as the event payload and may be queried by observers or
* used to filter observers. Each argument must be of type `std::pair<RStringKey, T>` where the first parameter is
* the key and the second is the value. The value must be of a type understood by a \ref variant::Translator
* specialization.
* @returns The count of observers that were called. Recursive dispatch calls are not included.
*/
template <class... Args>
size_t dispatchEvent(RString eventName, Args&&... payload);
/**
* Dispatches an event and immediately calls all observers that would observe this particular event.
*
* Finds and calls all observers (in the current thread) that observe the given event signature.
*
* It is safe to recursively dispatch events (i.e. call dispatchEvent() from a called observer), but care must be
* taken to avoid endless recursion. See the rules in observeEvent() for observers added during a dispatchEvent()
* call.
*
* @thread_safety Safe to perform while any thread is performing any operation against IEventDispatcher.
* @tparam InIter An InputIterator that is forward-iterable and resolves to a \ref NamedVariant when dereferenced.
* The entries are used as the event payload and may be queried by observers or used to filter observers.
* @param eventName The name of the event to dispatch.
* @param begin An InputIterator representing the start of the event key/value pairs.
* @param end A past-the-end InputIterator representing the end of the event key/value pairs.
* @returns The count of observers that were called. Recursive dispatch calls are not included.
*/
template <class InIter>
size_t dispatchEventIter(RString eventName, InIter begin, InIter end);
};
} // namespace eventdispatcher
} // namespace carb
#include "IEventDispatcher.inl"
|
omniverse-code/kit/include/carb/filesystem/FindFiles.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Utilities for finding files.
#pragma once
#include "../extras/Path.h"
#include "../extras/StringProcessor.h"
#include "../extras/StringUtils.h"
#include "IFileSystem.h"
#include "../Format.h"
#include "../../omni/str/Wildcard.h"
#include <cstdint>
#include <cstring>
namespace carb
{
namespace filesystem
{
//! Flag type for \ref FindFilesArgs
//! @see kFindFilesFlagNone kFindFilesFlagRecursive kFindFilesFlagMatchStem kFindFilesFlagReplaceEnvironmentVariables
using FindFilesFlag = uint32_t;
//! Default empty flag
constexpr FindFilesFlag kFindFilesFlagNone = 0x0;
//! Flag to recursively search directories.
constexpr FindFilesFlag kFindFilesFlagRecursive = (1 << 0);
//! When matching wildcards, only match the "stem".
//!
//! The "stem" is defined by carb::extras::Path. In short, given the following files:
//!
//! /a/b/c/d.txt -> d
//! /a/b/c/d -> d
//! /a/b/c/.d -> .d
//! /a/b/c/d.old.txt -> d.old
constexpr FindFilesFlag kFindFilesFlagMatchStem = (1 << 1);
//! Before walking the filesystem, a text replace is performed on each given search path. The token `${MY_ENV_VAR}`
//! would be replaced with the environment variable `MY_ENV_VAR`.
//!
//! Example: ${USERPROFILE}/kit -> C:/Users/ncournia/kit
constexpr FindFilesFlag kFindFilesFlagReplaceEnvironmentVariables = (1 << 2);
//! Callback for each encountered file invoked before canonicalization and pattern matching.
//! @param path the non-canonical path encountered
//! @param userData the value of \ref FindFilesArgs::onFilterNonCanonicalContext
//! @retval WalkAction::eContinue to continue with canonicalization and pattern matching.
//! @retval WalkAction::eSkip to stop processing the file and move to the next file.
//! @retval WalkAction::eStop to stop the search.
using FindFilesOnFilterNonCanonicalFn = WalkAction(const char* path, void* userData);
//! Callback invoked when a file matches a pattern matchWildcards and does not match a pattern in excludeWildcards.
//! @param canonical The canonical path to the file
//! @param userData the value of \ref FindFilesArgs::onMatchedContext
using FindFilesOnMatchedFn = void(const char* canonical, void* userData);
//! Callback invoked when a file matches a pattern matchWildcards and excludeWildcards.
//! @param canonical The canonical path to the file
//! @param userData the value of \ref FindFilesArgs::onExcludedContext
using FindFilesOnExcludedFn = void(const char* canonical, void* userData);
//! Callback invoked when a file matches does not match a pattern in matchWildcards.
//! @param canonical The canonical path to the file
//! @param userData the value of \ref FindFilesArgs::onSkippedContext
using FindFilesOnSkippedFn = void(const char* canonical, void* userData);
//! Callback invoked when starting a search in one of the given search paths.
//! @param canonical The canonical path to the file
//! @param userData the value of \ref FindFilesArgs::onSearchPathContext
using FindFilesOnSearchPathFn = void(const char* path, void* userData);
//! Search parameters passed to findFiles().
//!
//! Recommended usage:
//!
//! FindFilesArgs args{}; // this zero initializes arguments
//!
//! const char* const* paths = { "/myPath", "myRelativePath" };
//! const char* const* patterns = { "*.dll" };
//!
//! args.searchPaths = paths;
//! args.searchPathsCount = CARB_COUNTOF(paths);
//!
//! args.matchWildcards = patterns;
//! args.matchWildcardsCount = CARB_COUNTOF(patterns);
//!
//! args.onMatched = [](const char* canonical, void*) { printf("found: %s\n", canonical); };
//!
//! if (!findFiles(args)) { CARB_LOG_ERROR(" :( "); }
//!
struct FindFilesArgs
{
//! A list of paths (directories) to search.
//!
//! If \ref kFindFilesFlagReplaceEnvironmentVariables is specified in flags, tokens in the form `${MY_ENV_VAR}` will
//! be replaced with the corresponding environment variable.
//!
//! If \ref kFindFilesFlagRecursive is specified in flags, each path is searched recursively.
//!
//! Paths may be absolute or relative. If relative, the value of \ref IFileSystem::getAppDirectoryPath() is
//! prepended to the path.
//!
//! @warning Must not be nullptr.
const char* const* searchPaths;
uint32_t searchPathsCount; //!< Number of paths in searchPaths. Must be greater than 0.
//! The wildcard pattern to match files in the given searchPaths.
//!
//! Special characters are:
//! * `*` matches all characters
//! * `?` matches a single character.
//!
//! For example, given the file `"libMyPlugin.plugin.dll"`:
//! * `*` -> Matches!
//! * `lib` -> Not a match.
//! * `*.so` -> Not a match.
//! * `lib*` -> Matches!
//! * `*.plugin.*` -> Matches!
//! * `libMyPlugin.plugin?dll` -> Matches!
//!
//! When matching, only the filename is considered. So, given the path `/a/b/c/d.txt` only `d.txt` is considered
//! when matching.
//!
//! The extension of the filename can be ignored by passing the \ref kFindFilesFlagMatchStem to flags.
//!
//! Matched files may be excluded (see \ref excludeWildcards below).
//!
//! @warning Must not be nullptr.
const char* const* matchWildcards;
uint32_t matchWildcardsCount; //!< Number of patterns in matchWildcards. Must be greater than 0.
//! The wildcard pattern to exclude files in the given search paths.
//!
//! Pattern matching follow the same rules as \ref matchWildcards.
//!
//! These patterns are checked only when the filename matches \ref matchWildcards. If the filename matches a
//! pattern in both \ref matchWildcards and \ref excludeWildcards, the file is excluded.
//!
//! May be nullptr.
const char* const* excludeWildcards;
uint32_t excludeWildcardsCount; //!< Number of patterns in excludeWildcards. May be 0.
//! A list of prefixes to ignore during pattern matching.
//!
//! If not pattern matches a filename, pattern matching will be attempted again with the prefixes in this list
//! stripped. For example, given:
//!
//! ignorePrexies = { "lib" };
//! matchWildcard = { "MyPlugin.plugin.*" };
//!
//! We see the following output:
//! * `MyPlugin.plugin.dll` -> Match!
//! * `libMyPlugin.plugin.dll` -> Match! ("lib" prefix was ignored)
//!
//! May be nullptr
const char* const* ignorePrefixes;
uint32_t ignorePrefixesCount; //!< Number of prefixes in ignorePrefixes. May be 0.
//! IFileSystem to use to walk the given search paths.
//!
//! If nullptr, `tryAcquireInterface<IFileSystem>` is called.
IFileSystem* fs;
//! Callback for each encountered file invoked before canonicalization and pattern matching.
//!
//! This callback is invoked on each file in the given search paths. The callback is invoked before many of the
//! expensive parts of the search algorithm, such as file canonicalization and pattern matching.
//! May be nullptr.
FindFilesOnFilterNonCanonicalFn* onFilterNonCanonical;
void* onFilterNonCanonicalContext; //!< Context passed to onFilterNonCanonical. May be nullptr.
//! Callback invoked when a file matches a pattern matchWildcards and does not match a pattern in excludeWildcards.
//!
//! May be nullptr.
FindFilesOnMatchedFn* onMatched;
void* onMatchedContext; //!< Context passed to onMatched. May be nullptr.
//! Callback invoked when a file matches a pattern matchWildcards and excludeWildcards.
//!
//! May be nullptr.
FindFilesOnExcludedFn* onExcluded;
void* onExcludedContext; //!< Context passed to onExcluded. May be nullptr.
//! Callback invoked when a file matches does not match a pattern in matchWildcards.
//!
//! May be nullptr.
FindFilesOnSkippedFn* onSkipped;
void* onSkippedContext; //!< Context passed to onSkipped. May be nullptr.
//! Callback invoked when starting a search in one of the given search paths.
//!
//! May be nullptr.
FindFilesOnSearchPathFn* onSearchPath;
void* onSearchPathContext; //!< Context passed to onSearchPath. May be nullptr.
//! Bitmask of flags to change search behavior. See FindFilesFlag.
FindFilesFlag flags;
};
//! Finds files in a given list of search paths matching a given list of patterns.
//!
//! See \ref FindFilesArgs for argument documentation.
//!
//! The search can be incredibly expensive:
//! `O(searchPathsCount^(<files>^(ignorePrefixesCount^(matchWildcardsCount + excludeWildcardsCount))))`
//!
//! The following Python-ish pseudo-code gives you an idea of the algorithm used:
//! \rst
//! .. code-block:: python
//!
//! foreach path in searchPaths:
//! path = substituteEnvVars(path)
//! foreach file in path:
//! if eContinue == onFilterNonCanonical(file):
//! foreach prefix in ["", ignorePrefixes]:
//! stripped = prefix[len(prefix):]
//! matched = False
//! if isMatch(stripped, matchWildcards): # loops over each wildcard pattern
//! if isMatch(stripped, excludeWildcards): # loops over each wildcard pattern
//! return # any match of an exclusion pattern immediately excludes the file
//! else:
//! matched = True
//! if matched:
//! return onMatched(canonical)
//! \endrst
//! \param args The arguments as a structure
//! \returns `true` if the filesystem was searched; `false` otherwise.
inline bool findFiles(const FindFilesArgs& args);
#ifndef DOXYGEN_BUILD
namespace detail
{
struct FindFilesContext
{
const FindFilesArgs* args;
IFileSystem* fs;
};
inline WalkAction onFile(const DirectoryItemInfo* const info, void* userData)
{
if (info->type == DirectoryItemType::eFile)
{
auto context = reinterpret_cast<const FindFilesContext*>(userData);
// the canonicalization of a file is expensive. here we give the user a chance to
// tell us if we should canonicalize the file
if (context->args->onFilterNonCanonical)
{
WalkAction action =
context->args->onFilterNonCanonical(info->path, context->args->onFilterNonCanonicalContext);
switch (action)
{
case WalkAction::eStop:
return WalkAction::eStop;
case WalkAction::eSkip:
return WalkAction::eContinue;
default: // eContinue
break; // fall-through
}
}
std::string canonical = context->fs->makeCanonicalPath(info->path);
extras::Path path(canonical);
std::string target;
if (context->args->flags & kFindFilesFlagMatchStem)
{
target = path.getStem();
}
else
{
target = path.getFilename();
}
const char* toMatch = target.c_str();
// note, even if a pattern matches, we still have to loop through all of "ignorePrefixesCount" looking for an
// exclusion since exclusions take precedent.
bool matched = false;
for (int32_t i = -1; i < int32_t(context->args->ignorePrefixesCount); ++i)
{
const char* prefix = "";
if (-1 != i)
{
prefix = context->args->ignorePrefixes[i];
}
if (extras::startsWith(toMatch, prefix))
{
const char* strippedMatch = toMatch + std::strlen(prefix);
if (omni::str::matchWildcards(
strippedMatch, context->args->matchWildcards, context->args->matchWildcardsCount))
{
if (omni::str::matchWildcards(
strippedMatch, context->args->excludeWildcards, context->args->excludeWildcardsCount))
{
if (context->args->onExcluded)
{
context->args->onExcluded(canonical.c_str(), context->args->onExcludedContext);
}
return WalkAction::eContinue; // exclusion takes precedent. ignore the file and keep searching
}
else
{
matched = true;
}
}
}
}
if (matched)
{
if (context->args->onMatched)
{
context->args->onMatched(canonical.c_str(), context->args->onMatchedContext);
}
}
else
{
if (context->args->onSkipped)
{
context->args->onSkipped(canonical.c_str(), context->args->onSkippedContext);
}
}
}
return WalkAction::eContinue;
}
} // namespace detail
#endif
inline bool findFiles(const FindFilesArgs& args)
{
if (!args.searchPaths || !args.searchPathsCount)
{
CARB_LOG_ERROR("searchPath must be specified");
return false;
}
if (!args.matchWildcards || !args.matchWildcardsCount)
{
CARB_LOG_ERROR("match wildcard must be specified");
return false;
}
auto framework = getFramework();
if (!framework)
{
CARB_LOG_ERROR("carb::Framework not active");
return false;
}
IFileSystem* fs;
if (args.fs)
{
fs = framework->verifyInterface<IFileSystem>(args.fs);
if (!fs)
{
CARB_LOG_ERROR("incompatible carb::filesystem::IFileSystem");
return false;
}
}
else
{
fs = framework->tryAcquireInterface<IFileSystem>();
if (!fs)
{
CARB_LOG_ERROR("unable to acquire carb::filesystem::IFileSystem");
return false;
}
}
detail::FindFilesContext userData = { &args, fs };
for (uint32_t i = 0; i < args.searchPathsCount; ++i)
{
const char* dir = args.searchPaths[i];
std::string dirWithEnv;
if (args.flags & kFindFilesFlagReplaceEnvironmentVariables)
{
dirWithEnv = extras::replaceEnvironmentVariables(dir);
dir = dirWithEnv.c_str();
}
extras::Path path{ dir };
const char* fullPath = path.getStringBuffer();
std::string tmp;
if (!path.isAbsolute())
{
tmp = carb::fmt::format("{}/{}", fs->getAppDirectoryPath(), dir);
fullPath = tmp.c_str();
}
if (args.onSearchPath)
{
args.onSearchPath(fullPath, args.onSearchPathContext);
}
if (args.flags & kFindFilesFlagRecursive)
{
fs->forEachDirectoryItemRecursive(fullPath, detail::onFile, const_cast<detail::FindFilesContext*>(&userData));
}
else
{
fs->forEachDirectoryItem(fullPath, detail::onFile, &userData);
}
}
return true;
}
} // namespace filesystem
} // namespace carb
|
omniverse-code/kit/include/carb/filesystem/IFileSystem.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Carbonite FileSystem interface definition file.
#pragma once
#include "../Defines.h"
#include "../Types.h"
#include <stdlib.h>
#include <string>
#include <time.h>
#include <vector>
namespace carb
{
//! Namespace for Carbonite FileSystem.
namespace filesystem
{
//! Opaque type for referring to a File instance.
//! @see IFileSystem::openFileToRead IFileSystem::openFileToWrite IFileSystem::openFileToReadWrite
//! IFileSystem::openFileToAppend
struct File DOXYGEN_EMPTY_CLASS;
struct IFileSystem;
//! Type definition of a subscription.
typedef uint32_t SubscriptionId;
//! Indicates an invalid subscription.
const SubscriptionId kInvalidSubscriptionId = 0;
/**
* Defines the type of directory item.
*/
enum class DirectoryItemType
{
eFile, //!< Item type is a file, or other type such as socket or block device; type is not a directory
eDirectory, //!< Item type is a directory
};
/**
* Defines change action that is reported to callback function.
*/
enum class ChangeAction
{
/// Reported when a file is created
eCreated,
/// Reported when a file is modified
eModified,
/// Reported when a file is deleted
eDeleted,
/// Generally reported when a file is renamed. However, due to OS limitations in how events are delivered, a rename
/// may come through on rare occasion as separate eCreated and eDeleted events.
/// These are supported on Windows and Linux but not Mac OS.
eRenamed
};
/**
* Defines the behavior requested by the callback function.
*/
enum class WalkAction : signed char
{
/// Stops all iteration and causes forEachDirectoryItem[Recursive] to return immediately.
eStop = -1,
/// Skips the rest of the current directory and any remaining subdirectories of the current directory.
eSkip,
/// Continues iteration.
eContinue,
};
/**
* Information about a file
*/
struct FileInfo
{
/// The type of this item: Directory or File.
DirectoryItemType type;
/// The time that this item was last modified.
time_t modifiedTimestamp;
/// The time that this item was created.
time_t createdTimestamp;
/// The size of this item in bytes.
size_t size;
/// Whether this item is a symlink. On Windows, this is a reparse point which also includes directory junctions.
bool isSymlink;
};
/**
* Defines struct to hold item info during directory walk.
*/
struct DirectoryItemInfo : public FileInfo
{
//! The path to the file.
//!
//! Make a copy of the string if retention is desired after the callback. The path will be prefixed with the `path`
//! that is passed to \ref IFileSystem::forEachDirectoryItem() (or
//! \ref IFileSystem::forEachDirectoryItemRecursive()).
const char* path;
};
/**
* fixed positions in a file that a file pointer can be moved relative to.
*/
enum class FileWhence
{
eBegin, ///< beginning of the file.
eCurrent, ///< current position in the file.
eEnd, ///< end of the file.
};
/**
* defines the potential states that an open file stream can be in. These states are only valid
* after an operation such as read, write, seek, etc complete. The current state of the file
* stream can be retrieved with getFileStatus(). Its return value will persist until another
* operation on the stream completes.
*/
enum class FileStatus
{
eOk, ///< the stream is valid and ready to be operated on. No special state is set.
eEof, ///< the stream has reached an end-of-file condition on the last operation.
eError, ///< the stream has encountered an error on the last operation.
};
/** Base type for flags for the IFileSystem::makeCanonicalPathEx2() function. */
using CanonicalFlags = uint32_t;
/** Flag to indicate that the file must also exist in order for the function to succeed. When
* this flag is used, the behavior will match IFileSystem::makeCanonicalPathEx2().
*/
constexpr CanonicalFlags fCanonicalFlagCheckExists = 0x01;
/**
* Defines the callback function to use when listening to changes on file system.
*
* @param path The path for file system change.
* @param action The change action that occurred.
* @param userData The user data associated with the subscription to the change event.
* @param newPath The path for the new name of the file. Used only for eRenamed action, otherwise it's nullptr
*/
typedef void (*OnChangeEventFn)(const char* path, ChangeAction action, void* userData, const char* newPath);
/**
* Defines a file system for Carbonite.
*
* This interface provides a number of useful platform independent functions when working with files and folders in a
* file system. All paths are in UTF-8 encoding using forward slash as path separator.
*
* On Windows, the maximum path of 32767 characters is supported. However, path components can't be longer than 255
* characters.
* Linux has a maximum filename length of 255 characters for most filesystems (including EXT4), and a
* maximum path of 4096 characters.
*/
struct IFileSystem
{
// 1.3: Eliminated error/warning logging and made use of ErrorApi for error codes
CARB_PLUGIN_INTERFACE("carb::filesystem::IFileSystem", 1, 3)
/**
* Returns the full path to the executable for this program.
*
* @ref ErrorApi state is not changed by this function.
*
* @return the full canonical path to the executable, including executable name and extension.
* This path will not change for the lifetime of the process.
*/
const char*(CARB_ABI* getExecutablePath)();
/**
* Returns the full path to the directory that contains the executable for this program.
*
* @ref ErrorApi state is not changed by this function.
*
* @returns the full canonical path to the directory that contains the executable file.
* This will not include the executable filename itself. This path will not
* change for the lifetime of the process.
*/
const char*(CARB_ABI* getExecutableDirectoryPath)();
/**
* Retrieves the full path to the 'app'.
*
* @ref ErrorApi state is not changed by this function.
*
* @returns the buffer containing the application path string. The contents of this buffer
* will be modified by any call to setAppDirectoryPath(). The buffer itself will
* persist for the lifetime of the framework. This will return `nullptr` until it
* is initialized by a call to \ref setAppDirectoryPath().
*
* @note Access to the application directory string is not thread safe. It is the caller's
* responsibility to ensure the application path is not being modified from another
* thread while it is being retrieved.
*/
const char*(CARB_ABI* getAppDirectoryPath)();
/**
* Sets the full path to the 'app'.
*
* @note (Windows) The extended path prefix is stripped if provided. Directory separators are converted to `/`.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultOutOfMemory - A buffer to store the path could not be allocated
* * @ref omni::core::kResultInsufficientBuffer - \p path exceeds the size of the buffer
*
* @param[in] path the relative or absolute path to the 'app'. If a relative path is used,
* this will be resolved relative to the current working directory.
* @returns no return value.
*/
void(CARB_ABI* setAppDirectoryPath)(const char* path);
/**
* Returns the full path to the current working directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed on success
* * @ref omni::core::kResultOutOfMemory - A buffer to store the path could not be allocated
* * @ref omni::core::kResultInsufficientBuffer - the working directory exceeds the size of the buffer
* * Other errors may be reported based on the underlying platform calls
*
* @returns `nullptr` if an error occurs, or the buffer containing the current working directory path string. The
* contents of this buffer will be modified by any call to \ref getCurrentDirectoryPath() or
* \ref setCurrentDirectoryPath(). The buffer itself will persist for the lifetime of the framework.
*
* @note Retrieving the current working directory is not thread safe. Since only a single
* working directory is maintained for each process, it could be getting changed from
* another thread while being retrieved. It is the caller's responsibility to ensure
* that all access to the current working directory is safely serialized.
*/
const char*(CARB_ABI* getCurrentDirectoryPath)();
/**
* Sets the current working directory for the system.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed on success
* * @ref omni::core::kResultInvalidArgument - @p path was `nullptr`
* * @ref omni::core::kResultOutOfMemory - A buffer to store the path could not be allocated
* * @ref omni::core::kResultInsufficientBuffer - the working directory exceeds the size of the buffer
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] path the new current working directory path. This may be a relative or
* absolute path. This must name a directory that already exists. This
* name must not exist as a file on the file system. This may not be
* nullptr.
* @returns `true` if the new working directory is successfully set; `false` if an error occurs.
*
* @note Setting or retrieving the current working directory is not thread safe. Since
* the current working directory is global to the process, the caller is responsible
* for guaranteeing that the working directory will not change while attempting to
* retrieve it.
*/
bool(CARB_ABI* setCurrentDirectoryPath)(const char* path);
/**
* Tests whether the path provided exists in the file system.
*
* This function does not generate any error logging.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed on success
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The absolute or relative path to test for existence. Relative paths are resolved from
* the current working directory (as returned from getCurrentDirectoryPath()).
* @return true if and only if 'path' exists in the file system.
*/
bool(CARB_ABI* exists)(const char* path);
/**
* Tests whether it's possible to write to file with the provided path.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultSuccess - \p path exists but was not writable
* * @ref omni::core::kResultInvalidArgument - \p path is `nullptr`
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultInvalidState - Parent path is not a directory so \p path can not be created
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * Other errors may be reported based on the underlying platform calls
*
* @param path The absolute or relative path to test for writability. Relative paths are resolved from
* the current working directory (as returned from getCurrentDirectoryPath()).
* @return true if it's possible to write to this file.
*
* @note This accessibility check only answers the question of whether the user has
* _permission_ to write to the file, not that an open for write will always succeed.
* At least on Windows, it is still possible that another thread or process could
* have the file open without write sharing capabilities. In this case, the caller
* should just do a test open of the file since that will answer the question of
* whether write sharing is currently allowed on the file. On Linux there isn't any
* kernel enforced file sharing functionality so permission to the file should also
* imply the user will succeed to open it for write.
*/
bool(CARB_ABI* isWritable)(const char* path);
/**
* Tests whether the path provided is a directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultSuccess - \p path exists but was not a directory
* * @ref omni::core::kResultInvalidArgument - \p path is `nullptr`
* * @ref omni::core::kResultNotFound - The file was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The absolute or relative path to test for existence. Relative paths are resolved from
* the current working directory (as returned from getCurrentDirectoryPath()).
* @return true if and only if 'path' is a directory.
*/
bool(CARB_ABI* isDirectory)(const char* path);
/**
* Use platform functions to build canonical path relative to the base root.
*
* The path must exist. See @ref makeCanonicalPath() or @ref makeCanonicalPathEx2() for a version where the path may
* not need to exist.
*
* @par Errors
* Accessible via @ref carb::ErrorApi. This function always modifies the error state.
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultInsufficientBuffer - The provided \p buffer was too small to receive the canonicalized
* string. The contents of \p buffer are unchanged and the return value is the number of bytes required (including
* the NUL terminator).
* * @ref omni::core::kResultNullPointer - No buffer was provided, so nothing was written. The return value is the
* number of bytes required to contain the canonical path (include the NUL terminator).
* * Other errors may be reported based on the underlying platform calls
*
* @param path The absolute or relative path to canonicalize.
* @param base The base path to resolve relative path against. This can be `nullptr`to use
* the working directory (as returned from getCurrentDirectoryPath()) to resolve
* the relative path.
* @param buffer The buffer to write the canonical path to. This may be `nullptr` if only
* the required size of the buffer is needed.
* @param bufferSize The size of the buffer @p buffer in bytes.
* @return The number of characters written to the buffer @p buffer if the buffer is large enough.
* If the buffer is not large enough, nothing will be written to the buffer and the
* required size of the buffer in bytes including the NUL terminator will be returned. If an error occurs,
* 0 is returned.
*/
size_t(CARB_ABI* makeCanonicalPathEx)(const char* path, const char* base, char* buffer, size_t bufferSize);
/**
* Use platform functions to build canonical path relative to the base root.
*
* The path must exist if \ref fCanonicalFlagCheckExists is passed in the \p flags parameter.
*
* @par Errors
* Accessible via @ref carb::ErrorApi. This function always modifies the error state.
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The absolute or relative path to canonicalize.
* @param base The base path to resolve relative path against. This can be `nullptr`to use
* the working directory (as returned from getCurrentDirectoryPath()) to resolve
* the relative path.
* @param flags Flags to control the behavior of this operation.
* @return A `std::string` containing the canonicalized path, or an empty string if an error occurs.
*
* @note By default, this assumes that the requested file exists on the filesystem. On
* Linux, the existence of the file will still be checked as a side effect of the
* operation. On Windows however, no explicit check for the file existing in the
* filesystem will be performed unless the @ref fCanonicalFlagCheckExists flag is used.
*/
std::string makeCanonicalPath(const char* path,
const char* base = nullptr,
CanonicalFlags flags = fCanonicalFlagCheckExists);
/**
* Opens a file for reading in binary mode.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed with a non-`nullptr` return value
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * @ref omni::core::kResultOutOfMemory - Allocation failure
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] path The absolute or relative path for the file. This may not be nullptr.
* Relative paths are resolved from the current working directory (as
* returned from getCurrentDirectoryPath()).
* @returns a new File object representing the opened file if the file exists and was able
* to be successfully opened for read. This object must be passed to closeFile()
* when it is no longer needed.
* @returns nullptr if the named file does not exist in the file system or another error
* occurred (ie: insufficient permissions, allocation failure, etc).
*
* @remarks This opens an existing file for reading. If the file does not exist, this will
* fail. A new file will never be created if the named file does not already exist.
* If a new file needs to be created, it must first be opened for write with
* openFileToWrite(), for read and write with openFileToReadWrite(), or for append
* with openFileToAppend(). The file pointer will initially be at the beginning of
* the file. All reads will occur starting from the current file pointer position.
*/
File*(CARB_ABI* openFileToRead)(const char* path);
/**
* Opens a file for writing in binary mode.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed with a non-`nullptr` return value
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * @ref omni::core::kResultOutOfMemory - Allocation failure
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] path The absolute or relative path for the file. This may not be nullptr.
* Relative paths are resolved from the current working directory (as
* returned from getCurrentDirectoryPath()).
* @returns a new File object representing the opened file if successful. A new file will
* have been created if it previously did not exist. This object must be passed
* to closeFile() when it is no longer needed.
* @returns nullptr if the named file could neither be created nor opened. This may be
* the result of insufficient permissions to the file or an allocation failure.
* A warning will be written to the default logger in this case.
*
* @remarks This opens a file for writing. If the file does not exist, it will be created.
* If the file does exist, it will always be truncated to an empty file. The file
* pointer will initially be positioned at the beginning of the file. All writes to
* the file will occur at the current file pointer position. If the file needs
* to be opened for writing without truncating its contents, it should be opened
* either for append access (ie: openFileToAppend()) or for read/write access
* (ie: openFileToReadWrite()).
*/
File*(CARB_ABI* openFileToWrite)(const char* path);
/**
* Opens a file for appending in binary mode.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed with a non-`nullptr` return value
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * @ref omni::core::kResultOutOfMemory - Allocation failure
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] path The absolute or relative path for the file. This may not be nullptr.
* Relative paths are resolved from the current working directory (as
* returned from getCurrentDirectoryPath()).
* @returns a new File object representing the opened file if successful. A new file will
* have been created if it previously did not exist. This object must be passed
* to closeFile() when it is no longer needed.
* @returns nullptr if the named file could neither be created nor opened. This may be
* the result of insufficient permissions to the file or an allocation failure.
* A warning will be written to the default logger in this case.
*
* @remarks This opens a file for appending. If the file does not exist, it will always be
* created. The file pointer is initially positioned at the end of the file. All
* writes to the file will be performed at the end of the file regardless of the
* current file pointer position. If random access writes are needed, the file
* should be opened for read/write access (ie: openFileToReadWrite()) instead.
*/
File*(CARB_ABI* openFileToAppend)(const char* path);
/**
* Closes a file returned by any of the openFileTo*() functions.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - @p file was `nullptr`
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] file the File object representing the file to be closed. This object
* will no longer be valid upon return and must not be used again.
* This object would have been returned by a previous openFileTo*()
* call. If `nullptr` is provided, it is ignored.
* @returns no return value.
* @see openFileToRead openFileToWrite openFileToAppend openFileToReadWrite
*
* @post The \ref File is destroyed and must not be accessed anymore.
*/
void(CARB_ABI* closeFile)(File* file);
/**
* Gets the total size of the file.
*
* @note Writable files will execute a \ref flushFile() as part of this request.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @param file object corresponding to an open file.
* @return The total size of the file in bytes, or 0 if an error occurs. If the file is 0 bytes,
* \ref carb::ErrorApi::getError() can be queried and the result will be \ref omni::core::kResultSuccess.
*/
size_t(CARB_ABI* getFileSize)(File* file);
/**
* Gets the time of last modification to the file.
*
* @note Writable files will execute a \ref flushFile() as part of this request.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @param file object corresponding to an open file.
* @return The time this file was last modified. If an error occurs, 0 is returned and
* @ref carb::ErrorApi::getError() contains the error code.
*/
time_t(CARB_ABI* getFileModTime)(File* file);
/**
* Gets the time of last modification to the file or directory item at path.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultNotFound - The file was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to a file or directory item; relative paths are resolved from the current
* working directory (as returned from getCurrentDirectoryPath()).
* @return The time the item at 'path' was last modified. If an error occurs, 0 is returned and
* @ref carb::ErrorApi::getError() contains the error code.
*/
time_t(CARB_ABI* getModTime)(const char* path);
/**
* Gets the time of creation of the file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @param file object corresponding to an open file.
* @return The time this file was created. If an error occurs, 0 is returned and @ref carb::ErrorApi::getError()
* contains the error code.
*/
time_t(CARB_ABI* getFileCreateTime)(File* file);
/**
* Gets the time of creation of the file or directory item at path.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultNotFound - The file was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to a file or directory item; relative paths are resolved from the current
* working directory (as returned from getCurrentDirectoryPath()).
* @return The time the file at @p path was created. If an error occurs, 0 is returned and
* @ref carb::ErrorApi::getError() contains the error code.
*/
time_t(CARB_ABI* getCreateTime)(const char* path);
/**
* Reads a chunk of binary data from a file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultFail - A failure was reported during read, \ref getFileStatus() will report error.
* * Other errors may be reported based on the underlying platform calls
*
* @param file Object corresponding to an open file for reading in binary mode.
* @param chunk Memory to read the binary data to, at least chunkSize bytes large.
* @param chunkSize Number of bytes to read from file into 'chunk' memory area.
* @return Number of bytes read, this can be less than requested 'chunkSize' when reading the last bytes of
* data. Will return 0 when all data has been read from the file.
*/
size_t(CARB_ABI* readFileChunk)(File* file, void* chunk, size_t chunkSize);
/**
* Writes a chunk of binary data to a file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultFail - A failure was reported during write, \ref getFileStatus() will report error.
* * Other errors may be reported based on the underlying platform calls
*
* @param file An open file for writing in binary mode.
* @param chunk The memory buffer to write to the file.
* @param chunkSize Number of bytes from 'chunk' to write to the file.
* @returns the number of bytes successfully written to the file. This can be less than the
* requested @p chunkSize if an error occurs (ie: disk full).
* @returns 0 if no data could be written to the file.
*/
size_t(CARB_ABI* writeFileChunk)(File* file, const void* chunk, const size_t chunkSize);
/**
* Reads a line of character data from a text file (without including the line ending characters `\r` or `\n`).
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed with a non-`nullptr` return value
* * @ref omni::core::kResultSuccess - At end-of-file
* * @ref omni::core::kResultFail - A failure was reported during read, \ref getFileStatus() will report error.
* * Other errors may be reported based on the underlying platform calls
*
* @note This function considers a `\n` by itself to be a line ending, as well as `\r\n`. A `\r` by itself is not
* considered a line ending. The line endings are consumed from the file stream but are not present in the result.
* @note For @p maxLineSize of 0, `nullptr` is always returned without any change to the @p file read pointer. For
* @p maxLineSize of 1 when not at end-of-file, @p line will only contain a NUL terminator and if a line ending is
* at the start of the file stream it will be consumed.
*
* @param file A file returned from openFileToRead() or openFileToReadWrite().
* @param line The string that will receive the read line. Unlike `fgets()`, the result will NOT end with any line
* ending characters (`\n` or `\r\n`), but they will be consumed from the file stream.
* @param maxLineSize The maximum number of characters that can be read into @p line, including NUL terminator.
* If the buffer is exhausted before end-of-line is reached the buffer will be NUL terminated and thus still a
* proper C-style string but won't necessarily contain the full line from the file.
* @return Returns @p line on each successful read, or `nullptr` if @p file is at end-of-file or an error occurs.
*/
char*(CARB_ABI* readFileLine)(File* file, char* line, size_t maxLineSize);
/**
* Writes a line of characters to a text file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned.
* * @ref omni::core::kResultFail - A failure was reported during write, \ref getFileStatus() will report error.
* * Other errors may be reported based on the underlying platform calls
*
* @param file An file returned from openFileToWrite() or openFileToAppend().
* @param line The null-terminated string to write. A newline will always be appended to the
* string in the file if it is successfully written.
* @returns true if the string is successfully written to the file.
* @returns false if the full string could not be written to the file.
*/
bool(CARB_ABI* writeFileLine)(File* file, const char* line);
/**
* Flushes any unwritten data to the file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * Other errors may be reported based on the underlying platform calls
*
* When a file is closed, either by calling closeFile or during program termination, all the associated buffers are
* automatically flushed.
*
* @param file An open file for writing or appending.
*/
void(CARB_ABI* flushFile)(File* file);
/**
* Removes (deletes) a file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The file was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] path The path of the file to be removed. This must not have any open file
* objects on it otherwise the operation will fail.
* @returns true if the file was removed from the file system.
* @returns false if the file could not be removed. This is often caused by either having
* the file still open by either the calling process or another process, or by
* not having sufficient permission to delete the file.
*/
bool(CARB_ABI* removeFile)(const char* path);
/**
* Make a temporary directory.
*
* The directory is created under the system temporary directory area and will have a randomized name.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultInsufficientBuffer - The provided bufferSize was not sufficient
* * Other errors may be reported based on the underlying platform calls
*
* @param pathBuffer The buffer that will receive the full path to the created directory. This may not
* be `nullptr`.
* @param bufferSize The size of the buffer for storing the path. This size also includes the null
* terminator for the string. If this is too small to store the output path.
* @return `true` if the creation was successful and a path to the newly created temporary directory
* was returned in @p pathBuffer. On success, the temporary directory is guaranteed to exist
* and be writable by the caller. The caller is responsible for removing this directory when
* it is no longer needed.
* @return `false` if the temporary directory could not be created for any reason. In this case, the
* @p pathBuffer buffer will not be modified and its contents will be undefined.
*/
bool(CARB_ABI* makeTempDirectory)(char* pathBuffer, size_t bufferSize);
/** Make a single directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultAlreadyExists - The directory already exists. If `false` is returned then a file exists
* that prevents creation of the directory; if `true` is returned then the directory already exists (not an error)
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to the directory to create. Relative paths will be resolved from the
* current working directory (as returned from getCurrentDirectoryPath()). This
* may not be nullptr or an empty string.
* @retval true if the path did not previously exist and the creation as a folder was successful, or if the path
* already existed as a directory (@ref omni::core::kResultAlreadyExists is reported)
* @retval false if the path already existed as a non-directory entry (@ref omni::core::kResultAlreadyExists), or
* if the path could not be created for another reason (@ref carb::ErrorApi will have reason)
*
* @remarks This attempts to make a single new directory entry. All path components leading up
* to the new path must already exist for this to be expected to succeed. The path
* may already exist and this call will still succeed.
*
* @remarks Note that this operation is global to the system. There is no control over what
* other threads or processes in the system may be simultaneously doing to the named
* path. It is the caller's responsibility to gracefully handle any potential failures
* due to the action of another thread or process.
*
* @note There is a possible race condition with another thread or process creating the same
* path simultaneously. If this occurs, this call will still succeed in most cases.
* There is an additional rare possible race condition where the file or folder could
* also be deleted by an external thread or process after it also beat the calling thread
* to creating the path. In this case, this call will fail. For this to occur there
* would need to be the named path created then immediately destroyed externally.
*
* @note This call itself is thread safe. However, the operation it performs may race with
* other threads or processes in the system. Since file system directories are global
* and shared by other processes, an external caller may create or delete the same
* directory as is requested here during the call. There is unfortunately no way to
* prevent this or make it safer since the creator or deleter of the path may not
* even be local to the system (ie: a network share operation was requested). The
* best a caller can do you be to guarantee its own threads do not simultaneously
* attempt to operate on the same path.
*/
bool(CARB_ABI* makeDirectory)(const char* path);
/** Make one or more directories.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultAlreadyExists - The directory already exists. If `false` is returned then a file exists
* that prevents creation of the directory; if `true` is returned then the directory already exists (not an error)
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to the directory to create. Relative paths will be resolved from the
* current working directory (as returned from getCurrentDirectoryPath()). This
* may not be nullptr or an empty string.
* @retval true if the path did not previously exist and the creation as a folder was successful, or if the path
* already existed as a directory (@ref omni::core::kResultAlreadyExists is reported)
* @retval false if the path already existed as a non-directory entry (@ref omni::core::kResultAlreadyExists), or
* if the path could not be created for another reason (@ref carb::ErrorApi will have reason)
*
* @remarks This attempts to create one or more directories. All components listed in the path
* will be created if they do not already exist. If one of the path components already
* exists as a non-directory object, the operation will fail. If creating any of the
* intermediate path components fails, the whole operation will fail. If any of the
* components already exists as a directory, it will be ignored and continue with the
* operation.
*
* @note This call itself is thread safe. The operation itself may have a race condition with
* other threads or processes however. Please see makeDirectory() for more information
* about these possible race conditions.
*/
bool(CARB_ABI* makeDirectories)(const char* path);
/**
* Remove a directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The directory was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to the directory to remove; relative paths will be resolved from the
* current working directory (as returned from getCurrentDirectoryPath()).
* @return true if the removal was successful, otherwise false.
* @note This will never follow symbolic links. The symbolic link will be removed, but its target will not.
* @note On Windows, it is neither possible to remove the current working directory nor any
* directory containing it. This is because the Windows process holds an open handle
* to the current working directory without delete sharing permissions at all times.
* In order to remove the current working directory, the caller must first change the
* working directory to another valid path, then call removeDirectory(). On Linux,
* removing the current working directory is technically possible, however, doing so
* will leave the process in an undefined state since its working directory is no longer
* valid. Changing away from the working directory before calling this is still a good
* idea even on Linux.
*/
bool(CARB_ABI* removeDirectory)(const char* path);
/**
* Copy a file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAlreadyExists - The target file already exists
* * Other errors may be reported based on the underlying platform calls
*
* @param from The path to a file to copy; relative paths will be resolved from the current
* working directory (as returned from getCurrentDirectoryPath()).
* @param to The destination filename and path; relative paths will be resolved from the
* current working directory (as returned from getCurrentDirectoryPath()).
* @returns \c true if the file was copied successfully; \c false if an error occurs.
*/
bool(CARB_ABI* copy)(const char* from, const char* to);
/**
* Moves (renames) a file or directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAlreadyExists - The target file already exists
* * Other errors may be reported based on the underlying platform calls
*
* @note A rename to the same file will be successful with no error.
*
* @param from The path to a file or directory to rename; relative paths will be resolved from
* the current working directory (as returned from getCurrentDirectoryPath()).
* @param to The destination path; relative paths will be resolved from the current working
* directory (as returned from getCurrentDirectoryPath()).
* @returns \c true if the file was moved successfully; \c false if an error occurs.
*/
bool(CARB_ABI* move)(const char* from, const char* to);
/**
* User implemented callback function type for directory iteration.
*
* @note On Posix systems, a block device, socket, or pipe will still have `info->type` as
* \ref DirectoryItemType::eFile, but \ref ErrorApi::getError() will report \ref omni::core::kResultInvalidDataType;
* otherwise \ref ErrorApi::getError() will report \ref omni::core::kResultSuccess.
*
* @param info about a file. See \ref DirectoryItemInfo. The `path` member will be prefixed by the `path` passed to
* \ref forEachDirectoryItem() (or \ref forEachDirectoryItemRecursive())
* @param userData Any data that needs to be passed to the function for managing state across function calls, etc.
* @return one of the `WalkAction` enum values to instruct forEachDirectoryItem[Recursive] on how to proceed.
*
* @note It is entirely possible that by the time this callback function is called for a given file
* or directory, that file or directory could have already been deleted, moved, or renamed by
* another thread or process. In this case the file information that is passed to the callback
* function may already be out of date. The callback function should take this into account
* before taking any action on the given file or directory. One possible way to detect this
* is to check if the `info->createdTimestamp` and `info->modifiedTimestamp` values are zero.
* The callback could also verify that the file still exists before acting on it.
*/
typedef WalkAction (*OnDirectoryItemFn)(const DirectoryItemInfo* const info, void* userData);
/**
* Iterate through each item in the directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The path was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to the directory; relative paths will be resolved from the current
* working directory (as returned from getCurrentDirectoryPath()).
* @param onDirectoryItem The function to call for each directory item, see \ref OnDirectoryItemFn type
* @param userData The user data passed to the callback function for each item. May be `nullptr`.
*
* @note It is entirely possible that by the time the callback function is called for a given file
* or directory, that file or directory could have already been deleted, moved, or renamed by
* another thread or process. In this case the file information that is passed to the callback
* function may already be out of date. The callback function should take this into account
* before taking any action on the given file or directory. One possible way to detect this
* is to check if the @ref DirectoryItemInfo::createdTimestamp and
* @ref DirectoryItemInfo::modifiedTimestamp values are zero. The callback could also verify
* that the file still exists before acting on it.
*/
void(CARB_ABI* forEachDirectoryItem)(const char* path, OnDirectoryItemFn onDirectoryItem, void* userData);
/**
* Iterate through each item in the directory and recursive into subdirectories.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The path was not found
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to the directory; relative paths will be resolved from the current
* working directory (as returned from getCurrentDirectoryPath()).
* @param onDirectoryItem The function to call for each directory item, see IFileSystem::DirectoryCallback type
* @param userData The user data passed to the callback function for each item.
* @note This will follow symbolic links.
*
* @note It is entirely possible that by the time the callback function is called for a given file
* or directory, that file or directory could have already been deleted, moved, or renamed by
* another thread or process. In this case the file information that is passed to the callback
* function may already be out of date. The callback function should take this into account
* before taking any action on the given file or directory. One possible way to detect this
* is to check if the @ref DirectoryItemInfo::createdTimestamp and
* @ref DirectoryItemInfo::modifiedTimestamp values are zero. The callback could also verify
* that the file still exists before acting on it.
*/
void(CARB_ABI* forEachDirectoryItemRecursive)(const char* path, OnDirectoryItemFn onDirectoryItem, void* userData);
/**
* Subscribes to listen on change events on a path.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless @ref kInvalidSubscriptionId is returned
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultFail - A system error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to subscribe to.
* This path must be an existing file or directory on disk.
* @param onChangeEvent The callback function to be called when the events are fired.
* @param userData The user data passed to the callback function for each item.
* @returns subscription id if the path was successfully subscribed
* @retval kInvalidSubscriptionId if @p path does not exist, or some other error occurred (see @ref ErrorApi to
* determine the reason)
*
* @note The change subscriptions on directories are not recursive.
* If you watch a directory, you will not get change events for
* files/directories within subdirectories.
*
* @note Modifications to subdirectories (e.g. creating/deleting a file
* inside it) will not produce change events.
* OM-1071: there is a bug in the Windows implementation where deleting
* a file in a subdirectory produces a @ref ChangeAction::eModified event.
*
* @note If @p path points to a directory, deleting the directory will produce
* a @ref ChangeAction::eDeleted event and then no more events will be
* produced from the stream, even if the directory is created again.
* This behavior differs if @p path points to a file. Change events
* will continue to be produced for a file after it's been deleted if
* it's created again.
*
* @note Mac OS only appears to support ~512 subscriptions in a process
* (this value was determined experimentally).
* For subscription 513+, notifications are no longer sent.
*/
SubscriptionId(CARB_ABI* subscribeToChangeEvents)(const char* path, OnChangeEventFn onChangeEvent, void* userData);
/**
* Unsubscribes from listening to change events on a path.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultNotFound - The given \p subscriptionId was not found
* * @ref omni::core::kResultFail - A system error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @note It is safe to call this from within the callback passed to @ref subscribeToChangeEvents(). The function
* will not return until the subscription callback is guaranteed to be exited by all other threads.
*
* @param subscription Subscription id
*/
void(CARB_ABI* unsubscribeToChangeEvents)(SubscriptionId subscriptionId);
/**
* retrieves the current file pointer position for an open file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * @ref omni::core::kResultSuccess - No error occurred
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] file the file object to retrieve the current position for. This may have been
* opened for read or write. Files that were opened for append will always
* write at the end of the file regardless of the current file position. The
* file pointer's current position is typically unused or undefined in the
* append case.
* @returns the current position in the file in bytes relative to the beginning.
* @returns -1 if the file's position could not be retrieved.
*
* @remarks This retrieves the current location of the file pointer in a file that has been
* opened for read, write, or append. The offset is always returned in bytes. The
* current file position may be beyond the end of the file if the file pointer was
* recently placed beyond the end of the file. However, this does not actually
* reflect the size of the file until at least one byte is written into it at the
* new position beyond the file's end.
*/
int64_t(CARB_ABI* getFilePosition)(File* file);
/**
* sets the new file pointer position for an open file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * \ref omni::core::kResultInvalidArgument - an invalid argument was supplied
* * \ref omni::core::kResultFail - an underlying platform call failed
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] file the file object to set the current position for. This may have been
* opened for read or write. Files that were opened for append will
* always write at the end of the file regardless of the current file
* position. The file pointer's current position is typically unused or
* undefined in the append case.
* @param[in] offsetFromWhence the new position for the file pointer relative to the
* location specified in @p whence. This value may be negative
* only if @p whence is not FileWhence::eBegin. This may specify
* an index beyond the current end of the file when combined with
* @p whence.
* @param[in] whence the fixed location in the file to move the file pointer relative to.
* @returns true if the file position was successfully set.
* @returns false if the file position could not be set or was invalid.
*
* @remarks This attempts to reposition the file pointer in an open file. The new absolute
* position may not be negative once combined with @p whence. If the new absolute
* position is beyond the current end of the file, the file will not be extended
* until at least one byte is written into the file at that new position or the file
* is truncated at the current position with truncateFileAtCurrentPosition(). When
* it is written to or truncated with a larger size than previous, the new space
* will be filled with zeros. Note however, that if the file pointer is set beyond
* the end of the file, the getFilePosition() call will return that same position
* even though it is larger than the file currently is.
*/
bool(CARB_ABI* setFilePosition)(File* file, int64_t offsetFromWhence, FileWhence whence);
/**
* truncates a file at the current file position.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - An invalid argument was provided
* * @ref omni::core::kResultAccessDenied - Attempting to truncate a read-only file
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] file the file to be truncated. This must have been opened for write or
* append.
* @retval true if the file was successfully truncated.
* @retval false if the file could not be truncated for any reason.
*
* @remarks This truncates a file at the current file pointer position. This can be used
* to extend a file without needing to write anything to it by opening the file,
* setting the file pointer to the desired size with setFilePointer(), then calling
* this function to set the new end of the file. The new area of the file will be
* filled with zeros if it was extended. If the file is being shortened, all data
* in the file beyond the current file pointer will be removed.
*/
bool(CARB_ABI* truncateFileAtCurrentPosition)(File* file);
/**
* helper functions to move to the beginning of an open file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * Other errors may be reported based on the underlying platform calls
*
* @see setFilePosition()
* @param[in] file the file stream
* @returns \c true if the file pointer is successfully moved; \c false if an error occurs.
*/
bool setFilePositionBegin(File* file);
/**
* helper functions to move to the end of an open file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * Other errors may be reported based on the underlying platform calls
*
* @see setFilePosition()
* @param[in] file the file stream
* @returns \c true if the file pointer is successfully moved; \c false if an error occurs.
*/
bool setFilePositionEnd(File* file);
/**
* opens the file for read and write in binary mode.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `nullptr` is returned
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * @ref omni::core::kResultOutOfMemory - Allocation failure
* * Other errors may be reported based on the underlying platform calls
*
* @param[in] path the absolute or relative path to the file to open. This may not be
* nullptr. Relative paths are resolved from the current working
* directory (as returned from getCurrentDirectoryPath()).
* @returns a new open file stream object if the file is successfully opened. This file
* object must be closed with closeFile() when it is no longer needed.
* @returns nullptr if the file could not be opened for any reason. This can occur if the
* file could not be created or there are insufficient permissions to access the
* file, or an allocation failure occurred.
*
* @remarks This opens a file for both read and write access. If the file already exists, it
* is not truncated. If the file does not exist, it will be created. The file
* pointer is initially placed at the beginning of the file. All writes to the file
* will occur at the current file pointer location.
*/
File*(CARB_ABI* openFileToReadWrite)(const char* path);
/**
* retrieves the current status of a file stream object.
*
* @par Errors
* This function does not modify the calling thread's error state
*
* @param[in] file an open file stream to check the status of.
* @retval FileStatus::eOk if the file stream is still in a valid state and more read or
* write operation may potentially succeed.
* @retval FileStatus::eError if the file stream has encountered an error of any kind.
* This may include a partial write due to a full disk or a disk quota being
* reached.
* @retval FileStatus::eEof if a file stream opened for read has already read the last
* bytes in the file. A future call to readFile*() will simply return 0 or
* nullptr from the same file position.
*
* @remarks This retrieves the current status of a file stream object. The status allows
* the caller to differentiate an error from an end-of-file condition for the
* last file operation. The error condition on the file will be reset after
* each operation after being stored for later retrieval. The file stream status
* value will remain valid until the next operation is performed on the file.
*
* @note As with all other file operations, retrieving this status is not thread safe
* and could change if another thread performs an unprotected operation on the
* same stream. It is the caller's responsibility to ensure operations on the
* file stream are appropriately protected.
*
* @note The file status will not be modified by calls to getFileSize(), getFileModTime(),
* flushFile(), or getFilePosition().
*
*/
FileStatus(CARB_ABI* getFileStatus)(File* file);
/**
* fills the FileInfo struct with info about the given file.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - \p info was \c nullptr or \p path was empty or \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * Other errors may be reported based on the underlying platform calls
*
* @param path The path to the file.
* @param info The struct populated with info about the file.
* @return \c true if information was gathered; \c false if an error occurs.
*/
bool(CARB_ABI* getFileInfo)(const char* path, FileInfo* info);
/**
* Returns the current time of the file system.
*
* @par Errors
* This function does not change error state
*
* @returns the current time as via `time(0)`
*/
time_t(CARB_ABI* getCurrentTime)();
/**
* Tests whether it's possible to read a file or directory.
*
* @par Errors
* Accessible via @ref carb::ErrorApi
* * Note: Error state is not changed unless `false` is returned
* * @ref omni::core::kResultInvalidArgument - \p path is `nullptr`
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultAccessDenied - Access was denied to the file
* * Other errors may be reported based on the underlying platform calls
*
* @param path The absolute or relative path to test for readability. Relative paths are
* resolved from the current working directory (as returned from the
* getCurrentDirectoryPath() function). This may not be `nullptr` or an
* empty string.
* @returns `true` if the given file or directory exists and is readable by the calling user.
* Returns `false` if the file or directory doesn't exist or the user does not have
* permission to read from it. For a directory, readability represents permission
* to list the contents of the directory.
*
* @note This accessibility check only answers the question of whether the user has
* _permission_ to read the file, not that an open for read will always succeed.
* At least on Windows, it is still possible that another thread or process could
* have the file open without read sharing capabilities. In this case, the caller
* should just do a test open of the file since that will answer the question of
* whether read sharing is currently allowed on the file. On Linux there isn't any
* kernel enforced file sharing functionality so permission to the file should also
* imply the user will succeed to open it for read.
*/
bool(CARB_ABI* isReadable)(const char* path);
/**
* Use platform functions to build canonical path relative to the base root.
*
* The path must exist if \ref fCanonicalFlagCheckExists is passed in the \p flags parameter.
*
* @par Errors
* Accessible via @ref carb::ErrorApi. This function always modifies the error state.
* * @ref omni::core::kResultSuccess - No error occurred
* * @ref omni::core::kResultInvalidArgument - \p path was \c nullptr
* * @ref omni::core::kResultNotFound - The file was not found
* * @ref omni::core::kResultInsufficientBuffer - The provided \p buffer was too small to receive the canonicalized
* string. The contents of \p buffer are unchanged and the return value is the number of bytes required (including
* the NUL terminator).
* * @ref omni::core::kResultNullPointer - No buffer was provided, so nothing was written. The return value is the
* number of bytes required to contain the canonical path (include the NUL terminator).
* * Other errors may be reported based on the underlying platform calls
*
* If returned size is greater than passed bufferSize, then nothing is written to the buffer.
* If returned size is 0, then canonical path failed to be built or doesn't exist.
*
* @param path The absolute or relative path to canonicalize.
* @param base The base path to resolve relative path against. This can be `nullptr`to use
* the working directory (as returned from getCurrentDirectoryPath()) to resolve
* the relative path.
* @param flags Flags to control the behavior of this operation.
* @param buffer The buffer to write the canonical path to. This may be `nullptr` if only
* the required size of the buffer is needed.
* @param bufferSize The size of the buffer @p buffer in bytes.
* @return The number of bytes written to the buffer @p buffer if the buffer is large enough.
* If the buffer is not large enough, nothing will be written to the buffer and the
* required size of the buffer in bytes will be returned. If an error occurs, 0 is returned.
*
* @note By default, this assumes that the requested file exists on the filesystem. On
* Linux, the existence of the file will still be checked as a side effect of the
* operation. On Windows however, no explicit check for the file existing in the
* filesystem will be performed unless the @ref fCanonicalFlagCheckExists is used.
*/
size_t(CARB_ABI* makeCanonicalPathEx2)(
const char* path, const char* base, CanonicalFlags flags, char* buffer, size_t bufferSize);
};
inline std::string IFileSystem::makeCanonicalPath(const char* path, const char* base, CanonicalFlags flags)
{
std::string str(128, '\0');
size_t bytes = this->makeCanonicalPathEx2(path, base, flags, &str[0], str.size());
if (bytes == 0)
return {};
if (bytes > str.size())
{
str.resize(bytes);
bytes = this->makeCanonicalPathEx2(path, base, flags, &str[0], str.size());
CARB_ASSERT(bytes != 0 && str.size() >= bytes);
}
str.resize(bytes - 1); // Bytes includes the NUL terminator, so remove it here
return str;
}
inline bool IFileSystem::setFilePositionBegin(File* file)
{
return setFilePosition(file, 0, FileWhence::eBegin);
}
inline bool IFileSystem::setFilePositionEnd(File* file)
{
return setFilePosition(file, 0, FileWhence::eEnd);
}
} // namespace filesystem
} // namespace carb
|
omniverse-code/kit/include/carb/assert/AssertUtils.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Helper utility functions to modify assertion failure behavior.
*/
#pragma once
#include "../Framework.h"
/** Placeholder macro for any work that needs to be done at the global level for any IAssert
* related functionality. Do not call this directly.
*/
#define CARB_ASSERT_GLOBALS()
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Namespace for all assertion checking helpers and interfaces. */
namespace assert
{
/** Registers the IAssert implementation with the calling module.
*
* @returns No return value.
*
* @remarks This will be called once during framework startup to attempt to register the
* IAssert interface implementation with the calling module. Once the interface
* is acquired, it will be valid through @ref g_carbAssert until the framework
* is shutdown.
*/
inline void registerAssertForClient() noexcept
{
g_carbAssert = getFramework()->tryAcquireInterface<IAssert>();
}
/** Removes the global instance of the IAssert interface.
*
* @returns No return value.
*
* @remarks This will be called during framework shutdown or module unload to clear out the
* IAssert interface pointer for the module. Once cleared out, all functionality
* that makes use of it will be effectively disabled for that module.
*/
inline void deregisterAssertForClient() noexcept
{
g_carbAssert = nullptr;
}
/** Disables the assertion failure dialog for the process.
*
* @param[in] disable `true` to disable the assertion dialog from appearing. `false` to enable
* the assertion dialog.
*
* @returns The previous value of the `disableDialog` flag, in other words: `true` if the dialog
* was previously disabled; `false` if the dialog was previously enabled.
*
* @remarks By default this dialog only shows on Windows when not attached to a debugger.
* Disabling the dialog is useful for test apps or unit tests that want to run in a
* 'headless' mode but that may still trigger assertions. In this case, at least if
* the assertion fails and the process possibly crashes, it won't be stuck waiting
* on user input.
*/
inline bool disableDialog(bool disable)
{
if (g_carbAssert)
{
return !!(g_carbAssert->setAssertionFlags(disable ? fAssertSkipDialog : 0, disable ? 0 : fAssertSkipDialog) &
fAssertSkipDialog);
}
return false;
}
/** Sets whether the software breakpoint for a failed assertion should be triggered.
*
* @param[in] enabled Set to `true` to trigger the software breakpoint when an assertion fails.
* Set to `false` to skip over the software breakpoint and just continue
* execution when an assertion fails. The default behavior is to always
* trigger the software breakpoint unless it is overridden by user input
* on the assertion dialog (if enabled).
* @returns The previous value of the `useBreakpoint` flag, in other words: `true` if breakpoints
* were previously enabled; `false` if breakpoints were previously disabled.
*
* @remarks This sets whether the software breakpoint for failed assertions should be triggered.
* This can be used to allow failed assertions to just continue execution instead of
* hitting the software breakpoint. The assertion failure message is always still
* written to the log destinations. This is useful for checking whether certain 'safe'
* assertions failed during execution - allow them to continue execution as normal,
* then periodically check the assertion failure count with getFailureCount().
* Note that this still won't prevent a crash after a 'fatal' assertion fails.
*/
inline bool useBreakpoint(bool enabled)
{
if (g_carbAssert)
{
return !(g_carbAssert->setAssertionFlags(enabled ? 0 : fAssertSkipBreakpoint, enabled ? fAssertSkipBreakpoint : 0) &
fAssertSkipBreakpoint);
}
return true;
}
/** Sets whether a message should be printed out to the console on a failed assertion.
*
* @param[in] enabled Set to `true` to cause an assertion message to be printed to the console when
* an assertion fails. Set to `false` to prevent the assertion message from showing.
* The assertion message is shown by default.
* @return The previous value of the `showToConsole` flag, in other words: `true` if show-to-console was
* previously enabled; `false` if show-to-console was previously disabled.
*/
inline bool showToConsole(bool enabled)
{
if (g_carbAssert)
{
return !(g_carbAssert->setAssertionFlags(enabled ? 0 : fAssertNoConsole, enabled ? fAssertNoConsole : 0) &
fAssertNoConsole);
}
return true;
}
/** Retrieves the current assertion failure count for the calling process.
*
* @returns The total number of assertions that have failed in the calling process. For most
* normally functioning apps, this should always be zero. This can be used in unit
* tests to determine whether some 'safe' assertions failed without requiring manual
* verification or user input. When used in unit tests, this should be combined with
* carbAssertUseBreakpoint() to ensure the normal execution isn't stopped if an
* assertion fails.
*/
inline uint64_t getFailureCount()
{
return g_carbAssert ? g_carbAssert->getAssertionFailureCount() : 0;
}
} // namespace assert
} // namespace carb
|
omniverse-code/kit/include/carb/assert/IAssert.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides an interface to allow for more detailed assertion failure dialogues.
*/
#pragma once
// NOTE: this interface is included and used in a very low level header. No more headers than are
// absolutely necessary should be included from here.
#include "../Interface.h"
#include <stdarg.h>
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Namespace for all assertion checking helpers and interfaces. */
namespace assert
{
/** Base type for the flags that control the behavior of CARB_ASSERT() and CARB_CHECK() failure reporting. */
using AssertFlags = uint32_t;
/** Flag to indicate that the assertion confirmation dialog should always be skipped for this
* process. When set, the dialog will be assumed to always behave as though the button to
* break into the debugger had been pressed. When clear, the dialog will show based on
* platform defaults.
*/
constexpr AssertFlags fAssertSkipDialog = 0x00000001;
/** Flag to indicate that the software breakpoint that is triggered on a failing assertion
* is to be ignored. When set, the breakpoint will never be executed and execution will
* simply continue after reporting the failed assertion to the logs. When clear, the
* breakpoint will be executed normally.
*/
constexpr AssertFlags fAssertSkipBreakpoint = 0x00000002;
/** Flag to indicate that the assertion should not produce any console output. When set, an
* assertion will not print anything to the console, but the failure count will increase.
*/
constexpr AssertFlags fAssertNoConsole = 0x00000004;
/** Interface to provide functionality to display assertion failures in greater detail. This
* provides a way to encapsulate OS specific functionality for gathering additional information,
* displaying dialogues, and providing additional debugging functionality. Without this interface,
* assertion failure reports are only really limited to log messages and software breakpoints.
*/
struct IAssert
{
CARB_PLUGIN_INTERFACE("carb::assert::IAssert", 1, 0)
/** Sets, clears, or retrieves the assertion behavioral flags.
*
* @param[in] set A mask of zero or more flags to enable. This may be 0 to indicate
* that no new flags should be set. This is a combination of the
* fAssert* flags.
* @param[in] clear A mask of zero or more flags to disable. This may be 0 to indicate
* that no new flags should be cleared. This is a combination of the
* fAssert* flags.
* @returns The flags immediately before set/clear changes were applied.
*
* @note This is always thread safe; changes are applied atomically. Also, set and clear can be 0
* to retrieve the current set of flags.
*/
AssertFlags(CARB_ABI* setAssertionFlags)(AssertFlags set, AssertFlags clear);
/** Retrieves the count of how many assertions have failed.
*
* @returns The number of assertions that have failed in the calling process.
*
* @remarks This retrieves the current number of assertion failures that have occurred in the
* calling process. This may be combined with using the @ref fAssertSkipBreakpoint
* and @ref fAssertSkipDialog flags to allow certain assertions to continue in a
* 'headless' mode whose behavior can then be monitored externally.
*/
uint64_t(CARB_ABI* getAssertionFailureCount)();
/** Reports the failure of an assertion condition to all applicable destinations.
*
* @param[in] condition The text describing the failed assertion condition. This may not be
* `nullptr`.
* @param[in] file The name of the file that the assertion is in. This may not be
* `nullptr`.
* @param[in] func The name of the function that the assertion is in. This may not be
* `nullptr`.
* @param[in] line The line number that the assertion failed in.
* @param[in] fmt A printf() style format string providing more information for the
* failed assertion. This may be `nullptr` if no additional information
* is necessary or provided.
* @param[in] ... Additional arguments required to fulfill the format string's needs.
* Note that this is expected to be a single va_list object containing
* the arguments. For this reason, the @ref reportFailedAssertion()
* variant is expected to be the one that is called instead of the 'V'
* one being called directly.
* @returns `true` if a software breakpoint should be triggered.
* @returns `false` if the assertion should attempt to be ignored.
*
* @remarks This handles displaying an assertion failure message to the user. The failure
* message will be unconditionally written to the attached console and the debugger
* output window (if running on Windows under a debugger). If no debugger is
* attached to the process, a simple message box will be shown to the user indicating
* that an assertion failure occurred and allowing them to choose how to proceed.
* If a debugger is attached, the default behavior is to break into the debugger
* unconditionally.
*
* @note If running under the MSVC debugger, double clicking on the assertion failure text
* in the MSVC output window will jump to the source file and line containing the
* failed assertion.
*/
bool(CARB_ABI* reportFailedAssertionV)(
const char* condition, const char* file, const char* func, int32_t line, const char* fmt, ...);
/** Reports the failure of an assertion condition to all applicable destinations.
*
* @param[in] condition The text describing the failed assertion condition. This may not be
* `nullptr`.
* @param[in] file The name of the file that the assertion is in. This may not be
* `nullptr`.
* @param[in] func The name of the function that the assertion is in. This may not be
* `nullptr`.
* @param[in] line The line number that the assertion failed in.
* @param[in] fmt A printf() style format string providing more information for the
* failed assertion. This may be `nullptr` if no additional information
* is necessary or provided.
* @param[in] ... Additional arguments required to fulfill the format string's needs.
* @returns `true` if a software breakpoint should be triggered.
* @returns `false` if the assertion should attempt to be ignored.
*
* @remarks This handles displaying an assertion failure message to the user. The failure
* message will be unconditionally written to the attached console and the debugger
* output window (if running on Windows under a debugger). If no debugger is
* attached to the process, a simple message box will be shown to the user indicating
* that an assertion failure occurred and allowing them to choose how to proceed.
* If a debugger is attached, the default behavior is to break into the debugger
* unconditionally.
*
* @note If running under the MSVC debugger, double clicking on the assertion failure text
* in the MSVC output window will jump to the source file and line containing the
* failed assertion.
*
* @note This variant of the function is present to allow the @p fmt parameter to default
* to `nullptr` so that it can be used with a version of the CARB_ASSERT() macro that
* doesn't pass any message.
*/
bool reportFailedAssertion(
const char* condition, const char* file, const char* func, int32_t line, const char* fmt = nullptr, ...)
{
va_list args;
bool result;
va_start(args, fmt);
result = reportFailedAssertionV(condition, file, func, line, fmt, &args);
va_end(args);
return result;
}
};
} // namespace assert
} // namespace carb
/** Defines the global variable that holds the pointer to the IAssert implementation. This will
* be `nullptr` if the IAssert interface is unavailable, disabled, or has not been initialized
* yet. This variable is specific to each module.
*/
CARB_WEAKLINK CARB_HIDDEN carb::assert::IAssert* g_carbAssert;
|
omniverse-code/kit/include/carb/streamclient/StreamClient.h | // Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Interface.h>
#include <carb/cudainterop/CudaInterop.h>
#include <carb/graphics/Graphics.h>
#include <carb/input/IInput.h>
namespace carb
{
namespace streamclient
{
class Context;
class Frame;
/**
* Defines the streamclient interface.
*/
struct StreamClient
{
CARB_PLUGIN_INTERFACE("carb::streamclient::StreamClient", 0, 2);
/**
* Creates stream client context.
*
* @param[in] graphics A pointer to a graphics interface to use.
* @param[in] cudaInterop A pointer to a CUDA interop interface.
* @param[in] device A pointer to a graphics device instance.
* @return A pointer to the stream client context or nullptr.
*/
Context*(CARB_ABI* createContext)(carb::graphics::Graphics* graphics,
carb::cudainterop::CudaInterop* cudaInterop,
carb::graphics::Device* device);
/**
* Destroys stream client context.
*
* @param[in] ctx A pointer to the stream client context.
*/
void(CARB_ABI* destroyContext)(Context* ctx);
/**
* Starts stream client.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] addr A pointer to a server IP address.
* @param[in] port A server port number.
* @return true if client started and connected successfully.
*/
bool(CARB_ABI* startClient)(Context* ctx, const char* addr, uint16_t port);
/**
* Stops stream client.
*
* @param[in] ctx A pointer to the stream client context.
*/
void(CARB_ABI* stopClient)(Context* ctx);
/**
* Pushes keyboard input event to a remote stream server.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] evt A reference to the keyboard input event description.
*/
void(CARB_ABI* pushKeyboardEvent)(Context* ctx, const carb::input::KeyboardEvent& evt);
/**
* Pushes mouse input event to a remote stream server.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] evt A reference to the mouse input event description.
*/
void(CARB_ABI* pushMouseEvent)(Context* ctx, const carb::input::MouseEvent& evt);
/**
* Pushes gamepad input event to a remote stream server.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] evt A reference to the gamepad input event description.
*/
void(CARB_ABI* pushGamepadEvent)(Context* ctx, const carb::input::GamepadEvent& evt);
/**
* Pushes window resize event to a remote stream server.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] width New window width.
* @param[in] height New window height.
*/
void(CARB_ABI* pushResizeEvent)(Context* ctx, uint32_t width, uint32_t height);
/**
* Fetches video frame from streaming queue.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] cmdList A pointer to the graphics command list to store readback and transformation commands.
* @return A pointer to a video frame object or nullptr.
*
* The lifetime of each video frame object is managed inside stream client context, so caller don't have manage it
* by self. The contents of video frame object becomes invalid after Nth call of fetch function.
*
* This method DOES NOT execute the command list, just adds readback, transformation and resource state transition
* commands in it. So the actual frame content will be available only after the command list will be executed on the
* caller side. Additionally, caller could add a fence in the same list after this method call to check when the
* frame content will be ready. It is not nessesary if caller uses the same command list for rendering commands.
*/
Frame*(CARB_ABI* fetchFrame)(Context* ctx, carb::graphics::CommandList* cmdList);
/**
* Renders video frame with built-in tiny renderer.
*
* @param[in] ctx A pointer to the stream client context.
* @param[in] cmdList A pointer to the graphics command list to store rendering commands.
* @param[in] frame A pointer to the video frame object or nullptr.
*
* This method DOES NOT render and DOES NOT execute the command list. It adds rendering commands in the
* provided command list for subsequent execution on the caller side.
*/
void(CARB_ABI* renderFrame)(Context* ctx, carb::graphics::CommandList* cmdList, Frame* frame);
/**
* Returns a pointer to texture object from a video frame object.
*
* @param[in] frame A pointer to a frame object obtained from fetchFrame call.
* @return a pointer to texture object or nullptr.
*/
carb::graphics::Texture*(CARB_ABI* getFrameTexture)(const Frame* frame);
/**
* Returns a pointer to texture descriptor object from a video frame object.
*
* @param[in] frame A pointer to a frame object obtained from fetchFrame call.
* @return a pointer to texture descriptor object or nullptr.
*/
carb::graphics::Descriptor*(CARB_ABI* getFrameDescriptor)(const Frame* frame);
/**
* Returns an extent of a video frame.
*
* @param[in] frame A pointer to a frame object obtained from fetchFrame call.
* @return a pair of { width, height } for a given frame.
*/
carb::Uint2(CARB_ABI* getFrameExtent)(const Frame* frame);
};
} // namespace streamclient
} // namespace carb
|
omniverse-code/kit/include/carb/streamclient/StreamClientUtils.h | // Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <algorithm>
#include <utility>
#include <carb/Defines.h>
#include <carb/Framework.h>
#include <carb/streamclient/StreamClient.h>
namespace carb
{
namespace streamclient
{
/**
* Defines the wrapper around streamclient interface and context.
*/
class StreamClientWrapper
{
public:
/**
* Constructs an uninitilized wrapper object.
*/
inline StreamClientWrapper(){};
/**
* Deinitialize and destroys wrapper object.
*/
virtual ~StreamClientWrapper()
{
done();
};
inline void swap(StreamClientWrapper& other)
{
std::swap(m_interface, other.m_interface);
std::swap(m_context, other.m_context);
}
inline std::string resolvePath(const std::string& path, const std::string& root = "")
{
auto tokens = carb::getCachedInterface<carb::tokens::ITokens>();
carb::extras::Path resultPath = carb::tokens::resolveString(tokens, path.c_str());
// If relative - relative to the root
if (!root.empty() && resultPath.isRelative())
{
resultPath = carb::extras::Path(root).join(resultPath);
}
return resultPath;
}
public:
/**
* Initialize the wrapper instance
*
* @param[in] framework A pointer to a framework interface to use.
* @param[in] graphics A pointer to a graphics interface to use.
* @param[in] cudaInterop A pointer to a CUDA interop interface.
* @param[in] device A pointer to a graphics device instance.
* @return True if successfull.
*/
bool init(carb::Framework* framework,
carb::graphics::Graphics* graphics,
carb::cudainterop::CudaInterop* cudaInterop,
carb::graphics::Device* device)
{
{
// Ensure we load the plugin
const std::string gfxPath = resolvePath("${kit}/plugins/gpu.foundation");
const char* paths[] = { gfxPath.c_str() };
const char* plugins[] = { "carb.livestream.plugin" };
loadPluginsFromPatterns(plugins, countOf(plugins), paths, countOf(paths));
}
m_interface = framework->acquireInterface<carb::streamclient::StreamClient>();
if (!m_interface)
{
return false;
}
m_context = m_interface->createContext(graphics, cudaInterop, device);
if (!m_context)
{
return false;
}
return true;
}
/**
* Deinitialize the wrapper instance.
*/
void done()
{
if (m_interface && m_context)
{
m_interface->stopClient(m_context);
m_interface->destroyContext(m_context);
m_context = nullptr;
}
}
/**
* Starts stream client.
*
* @param[in] addr A pointer to a server IP address.
* @param[in] port A server port number.
* @return true if client started and connected successfully.
*/
bool start(const char* addr, uint16_t port)
{
if (m_interface && m_context)
{
return m_interface->startClient(m_context, addr, port);
}
return false;
}
/**
* Stops stream client.
*/
void stop()
{
if (m_interface && m_context)
{
m_interface->stopClient(m_context);
}
}
/**
* Pushes keyboard input event to a remote stream server.
*
* @param[in] evt A reference to the keyboard input event description.
*/
void pushKeyboardEvent(const carb::input::KeyboardEvent& evt)
{
if (m_interface && m_context)
{
m_interface->pushKeyboardEvent(m_context, evt);
}
}
/**
* Pushes mouse input event to a remote stream server.
*
* @param[in] evt A reference to the keyboard input event description.
*/
void pushMouseEvent(const carb::input::MouseEvent& evt)
{
if (m_interface && m_context)
{
m_interface->pushMouseEvent(m_context, evt);
}
}
/**
* Pushes gamepad input event to a remote stream server.
*
* @param[in] evt A reference to the mouse input event description.
*/
void pushGamepadEvent(const carb::input::GamepadEvent& evt)
{
if (m_interface && m_context)
{
m_interface->pushGamepadEvent(m_context, evt);
}
}
/**
* Pushes window resize event to a remote stream server.
*
* @param[in] width New window width.
* @param[in] height New window height.
*/
void pushResizeEvent(uint32_t width, uint32_t height)
{
if (m_interface && m_context)
{
m_interface->pushResizeEvent(m_context, width, height);
}
}
/**
* Fetches video frame from streaming queue.
*
* @param[in] cmdList A pointer to the graphics command list to store readback and transformation commands.
* @return A pointer to a video frame object or nullptr.
*/
Frame* fetchFrame(carb::graphics::CommandList* cmdList)
{
if (m_interface && m_context && cmdList)
{
return m_interface->fetchFrame(m_context, cmdList);
}
return nullptr;
}
/**
* Renders video frame with built-in tiny renderer.
*
* @param[in] cmdList A pointer to the graphics command list to store rendering commands.
* @param[in] frame A pointer to the video frame object or nullptr.
*/
void renderFrame(carb::graphics::CommandList* cmdList, Frame* frame)
{
if (m_interface && m_context && cmdList && frame)
{
m_interface->renderFrame(m_context, cmdList, frame);
}
}
/**
* Returns a pointer to texture object from a video frame object.
*
* @param[in] frame A pointer to a frame object obtained from fetchFrame call.
* @return a pointer to texture object or nullptr.
*/
carb::graphics::Texture* getFrameTexture(const Frame* frame)
{
if (m_interface && frame)
{
return m_interface->getFrameTexture(frame);
}
return nullptr;
}
/**
* Returns a pointer to texture descriptor object from a video frame object.
*
* @param[in] frame A pointer to a frame object obtained from fetchFrame call.
* @return a pointer to texture descriptor object or nullptr.
*/
carb::graphics::Descriptor* getFrameDescriptor(const Frame* frame)
{
if (m_interface && frame)
{
return m_interface->getFrameDescriptor(frame);
}
return nullptr;
}
/**
* Returns an extent of a video frame.
*
* @param[in] frame A pointer to a frame object obtained from fetchFrame call.
* @return a pair of { width, height } for a given frame.
*/
carb::Uint2 getFrameExtent(const Frame* frame)
{
if (m_interface && frame)
{
return m_interface->getFrameExtent(frame);
}
return { 0, 0 };
}
private:
StreamClientWrapper(const StreamClientWrapper&) = delete;
StreamClientWrapper& operator=(const StreamClientWrapper&) = delete;
private:
carb::streamclient::StreamClient* m_interface = nullptr;
carb::streamclient::Context* m_context = nullptr;
};
} // namespace streamclient
} // namespace carb
|
omniverse-code/kit/include/carb/livestream/StreamServer.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Interface.h>
#include <carb/cudainterop/CudaInterop.h>
#include <carb/graphics/Graphics.h>
#include <carb/graphicsmux/GraphicsMux.h>
#include <carb/input/IInput.h>
namespace carb
{
namespace livestream
{
class Context;
enum class AudioSampleFormat: uint32_t
{
eSFloat, //! floating point in the range [-1 .. 1]
eUFloat, //! floating point in the range [0 .. 1]
eSInt16, //! signed 16-bit integer in the range [INT16_MIN .. INT16_MAX]
eUInt16 //! unsigned 16-bit integer in the range [0 .. UINT16_MAX]
};
/**
* Describes audio samples buffer
*/
struct AudioSamplesDesc
{
AudioSampleFormat sampleFormat; //! audio sample format
uint32_t samplingRate; //! sampling rate (sampling frequency) in Hertz
uint32_t channelCount; //! total number of channels
uint32_t channelMask; //! channel presence mask (unmuted channels are marked with non-zero bits)
};
/**
* Defines the Livestream Vision interface.
*/
struct Vision
{
CARB_PLUGIN_INTERFACE("carb::livestream::Vision", 0, 4);
/**
* Creates Livestream Vision context.
*
* @param graphics Pointer to optional graphics interface to use or nullptr.
* @param graphicsmux Pointer to optional graphics multiplexing API for async CUDA command recording or nullptr.
* @param device Pointer to optional graphics device instance or nullptr.
* @return Pointer to Livestream Vision context or nullptr.
*/
Context*(CARB_ABI* createContext)(carb::graphics::Graphics* graphics,
carb::graphicsmux::GraphicsMux* graphicsMux,
carb::graphics::Device* device);
/**
* Destroys Livestream Vision context.
*
* @param ctx Pointer to the Livestream Vision context.
*/
void(CARB_ABI* destroyContext)(Context* ctx);
/**
* Binds input interfaces to a Livestream Vision context.
*
* @param ctx Pointer to the Livestream Vision context.
* @param keyboard Pointer to the keyboard input interface.
* @param mouse Pointer to the mouse input interface.
* @param gamepad Pointer to the gamepad input interface.
*/
void(CARB_ABI* bindInput)(Context* ctx,
carb::input::Keyboard* keyboard,
carb::input::Mouse* mouse,
carb::input::Gamepad* gamepad);
/**
* Pump the cached livestream input events into carb::input.
* This function must be called from main thread.
*
* @param ctx Pointer to the Livestream Vision context.
*/
void(CARB_ABI* updateInput)(Context* ctx);
/**
* Starts Livestream Vision server.
*
* @param ctx Pointer to the Livestream Vision context.
* @return true if server started successfully.
*/
bool(CARB_ABI* startServer)(Context* ctx);
/**
* Stops Livestream Vision server.
*
* @param ctx Pointer to the Livestream Vision context.
*/
void(CARB_ABI* stopServer)(Context* ctx);
/**
* Get remote client width and height.
*
* @param ctx Pointer to the Livestream Vision context.
* @param extent Pointer to an extent destination.
* @return true if extent is filled with valid data.
*/
bool(CARB_ABI* getRemoteClientExtent)(Context* ctx, carb::Uint2* extent);
/**
* Records a command to send a frame from a CUDA buffer memory.
*
* @param ctx Pointer to the Livestream Vision context.
* @param commandList Pointer to the command list to use.
* @param cudaMemory Unified pointer to the CUDA buffer memory.
* @param pitch The frame row pitch in bytes.
* @param width The frame width in pixels.
* @param height The frame height in rows.
*/
void(CARB_ABI* cmdSendCudaMemoryFrame)(Context* ctx,
carb::graphicsmux::CommandList* commandList,
void* cudaMemory,
uint32_t pitch,
uint32_t width,
uint32_t height);
/**
* Enqueue a frame from a CUDA buffer memory.
*
* @param ctx Pointer to the Livestream Vision context.
* @param cudaMemory Unified pointer to the CUDA buffer memory.
* @param pitch The frame row pitch in bytes.
* @param width The frame width in pixels.
* @param height The frame height in rows.
*/
void(CARB_ABI* sendCudaMemoryFrame)(Context* ctx, void* cudaMemory, uint32_t pitch, uint32_t width, uint32_t height);
/**
* Enqueue a frame from a CUDA buffer external memory.
*
* @param ctx Pointer to the Livestream Vision context.
* @param cudaExternalMemory Pointer to the CUDA buffer external memory.
* @param pitch The frame row pitch in bytes.
* @param width The frame width in pixels
* @param height The frame height in rows
*/
void(CARB_ABI* sendCudaExternalMemoryFrame)(Context* ctx,
carb::cudainterop::ExternalMemory* cudaExternalMemory,
uint32_t pitch,
uint32_t width,
uint32_t height);
/**
* Enqueue a frame from a shared texture.
*
* @param ctx Pointer to the Livestream Vision context.
* @param textureHandle Pointer to the shared texture handle description.
* @param texture Pointer to the texture object.
*/
void(CARB_ABI* sendSharedTextureFrame)(Context* ctx,
carb::graphics::SharedResourceHandle* textureHandle,
carb::graphics::Texture* texture);
/**
* Enqueue an audio samples.
*
* @param ctx Pointer to the Livestream Vision context.
* @param buf Pointer to the auduo samples buffer.
* @param size Audio samples buffer size in bytes.
* @param time Audio samples starting time in milleseconds.
* @param desc Audio samples description.
*/
void(CARB_ABI* sendAudioSamples)(Context* ctx, const void* buf, size_t size, uint32_t time, const AudioSamplesDesc& desc);
};
} // namespace livestream
} // namespace carb
|
omniverse-code/kit/include/carb/livestream/StreamServerUtils.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Framework.h>
#include <carb/livestream/StreamServer.h>
#include <algorithm>
#include <utility>
namespace carb
{
namespace livestream
{
/**
* Defines the wrapper around stream server interface and its context.
*/
class StreamServerWrapper
{
public:
/**
* Constructs an uninitilized wrapper object.
*/
inline StreamServerWrapper(){};
/**
* Deinitialize and destroys wrapper object.
*/
virtual ~StreamServerWrapper()
{
done();
};
inline void swap(StreamServerWrapper& other)
{
std::swap(m_interface, other.m_interface);
std::swap(m_context, other.m_context);
}
public:
/**
* Initialize the wrapper instance.
*
* @param[in] framework Pointer to a framework interface to use.
* @param[in] graphics Pointer to a graphics interface to use.
* @param[in] graphicsMux Pointer to optional graphics multiplexing API for async CUDA command recording or nullptr.
* @param[in] device Pointer to a graphics device instance.
* @return true if successfull.
*/
bool init(carb::Framework* framework,
carb::graphics::Graphics* graphics,
carb::graphicsmux::GraphicsMux* graphicsMux,
carb::graphics::Device* device)
{
m_interface = framework->tryAcquireInterface<carb::livestream::Vision>();
if (!m_interface)
{
return false;
}
m_context = m_interface->createContext(graphics, graphicsMux, device);
if (!m_context)
{
return false;
}
return true;
}
/**
* Deinitialize the wrapper instance.
*/
void done()
{
if (m_interface && m_context)
{
m_interface->stopServer(m_context);
m_interface->destroyContext(m_context);
m_context = nullptr;
}
}
/**
* Check if the wrapper instance is initialized properly.
*
* @return true if the wrapper is initialized properly.
*/
inline bool isValid() const
{
return (m_interface && m_context);
}
/**
* Binds input interfaces to a server context.
*
* @param keyboard Pointer to the keyboard input interface.
* @param mouse Pointer to the mouse input interface.
* @param gamepad Pointer to the gamepad input interface.
*/
void bindInput(carb::input::Keyboard* keyboard, carb::input::Mouse* mouse, carb::input::Gamepad* gamepad)
{
if (m_interface && m_context)
{
m_interface->bindInput(m_context, keyboard, mouse, gamepad);
}
}
/**
* Pump the remote client cached input events into carb::input.
* This function must be called from main thread.
*/
void updateInput()
{
if (m_interface && m_context)
{
m_interface->updateInput(m_context);
}
}
/**
* Starts streaming server.
*
* @return true if server started successfully.
*/
bool start()
{
if (m_interface && m_context)
{
return m_interface->startServer(m_context);
}
return false;
}
/**
* Stops streaming server.
*/
void stop()
{
if (m_interface && m_context)
{
m_interface->stopServer(m_context);
}
}
/**
* Get remote client cached width and height.
*
* @param extent Pointer to an extent destination.
* @return true if extent is filled with valid data.
*/
bool getRemoteClientExtent(carb::Uint2* extent)
{
if (m_interface && m_context && extent)
{
return m_interface->getRemoteClientExtent(m_context, extent);
}
return false;
}
/**
* Records a command to send a frame from a CUDA buffer memory.
*
* @param commandList Pointer to the command list to use.
* @param cudaMemory Unified pointer to the CUDA buffer memory.
* @param pitch The frame row pitch in bytes.
* @param width The frame width in pixels.
* @param height The frame height in rows.
*/
void cmdSendCudaMemoryFrame(
carb::graphicsmux::CommandList* commandList, void* cudaMemory, uint32_t pitch, uint32_t width, uint32_t height)
{
if (m_interface && m_context)
{
m_interface->cmdSendCudaMemoryFrame(m_context, commandList, cudaMemory, pitch, width, height);
}
}
/**
* Enqueue a frame from a CUDA buffer memory.
*
* @param cudaMemory Unified pointer to the CUDA buffer memory.
* @param pitch The frame row pitch in bytes.
* @param width The frame width in pixels.
* @param height The frame height in rows.
*/
void sendCudaMemoryFrame(void* cudaMemory, uint32_t pitch, uint32_t width, uint32_t height)
{
if (m_interface && m_context)
{
m_interface->sendCudaMemoryFrame(m_context, cudaMemory, pitch, width, height);
}
}
/**
* Enqueue a frame from a CUDA buffer external memory.
*
* @param cudaExternalMemory Pointer to the CUDA buffer external memory.
* @param pitch The frame row pitch in bytes.
* @param width The frame width in pixels
* @param height The frame height in rows
*/
void sendCudaExternalMemoryFrame(carb::cudainterop::ExternalMemory* cudaExternalMemory,
uint32_t pitch,
uint32_t width,
uint32_t height)
{
if (m_interface && m_context)
{
m_interface->sendCudaExternalMemoryFrame(m_context, cudaExternalMemory, pitch, width, height);
}
}
/**
* Enqueue a frame from a shared texture.
*
* @param textureHandle Pointer to the shared texture handle description.
* @param texture Pointer to the texture object.
*/
void sendSharedTextureFrame(carb::graphics::SharedResourceHandle* textureHandle, carb::graphics::Texture* texture)
{
if (m_interface && m_context)
{
m_interface->sendSharedTextureFrame(m_context, textureHandle, texture);
}
}
/**
* Enqueue an audio samples.
*
* @param buf Pointer to the auduo samples buffer.
* @param size Audio samples buffer size in bytes.
* @param time Audio samples starting time in milleseconds.
* @param desc Audio samples description.
*/
void sendAudioSamples(const void* buf, size_t size, uint32_t time, const AudioSamplesDesc& desc)
{
if (m_interface && m_context)
{
m_interface->sendAudioSamples(m_context, buf, size, time, desc);
}
}
private:
StreamServerWrapper(const StreamServerWrapper&) = delete;
StreamServerWrapper& operator=(const StreamServerWrapper&) = delete;
private:
carb::livestream::Vision* m_interface = nullptr;
carb::livestream::Context* m_context = nullptr;
};
} // namespace livestream
} // namespace carb
|
omniverse-code/kit/include/carb/container/IntrusiveList.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite intrusive list container.
#pragma once
#include "../Defines.h"
#include <iterator>
namespace carb
{
namespace container
{
/**
* Defines a "link node" that \ref IntrusiveList will use for tracking data for the contained type.
*/
template <class T>
class IntrusiveListLink
{
public:
//! The object that contains `*this`.
using ValueType = T;
//! Constructor.
constexpr IntrusiveListLink() noexcept = default;
//! Destructor. Asserts that the link is not contained in an @ref IntrusiveList.
~IntrusiveListLink()
{
// Shouldn't be contained at destruction time
CARB_ASSERT(!isContained());
}
//! Reports whether this link object is inserted into am @ref IntrusiveList container.
//! @returns `true` if this link object is present in an @ref IntrusiveList; `false` otherwise.
bool isContained() const noexcept
{
return m_next != nullptr;
}
private:
template <class U, IntrusiveListLink<U> U::*V>
friend class IntrusiveList;
CARB_VIZ IntrusiveListLink* m_next{ nullptr };
IntrusiveListLink* m_prev{ nullptr };
CARB_PREVENT_COPY_AND_MOVE(IntrusiveListLink);
constexpr IntrusiveListLink(IntrusiveListLink* init) noexcept : m_next(init), m_prev(init)
{
}
};
/**
* IntrusiveList is very similar to std::list, but requires the tracking information to be contained within the stored
* type `T`, rather than built around it. In other words, the tracking information is "intrusive" in the type `T` by way
* of the @ref IntrusiveListLink type. IntrusiveList does no allocation of the `T` type; all allocation is done outside
* of the context of IntrusiveList, which allows stored items to be on the stack, grouped with other items, etc.
*
* The impetus behind intrusive containers is specifically to allow the application to own the allocation patterns for a
* type, but still be able to store them in a container. For `std::list`, everything goes through an `Allocator` type,
* but in a real application some stored instances may be on the stack while others are on the heap, which makes using
* `std::list` impractical. Furthermore, a stored type may wish to be removed from one list and inserted into another.
* With `std::list`, this would require heap interaction to erase from one list and insert into another. With
* IntrusiveList, this operation would not require any heap interaction and would be done very quickly (O(1)).
*
* Another example is a `std::list` of polymorphic types. For `std::list` the contained type would have to be a pointer
* or pointer-like type which is an inefficient use of space, cache, etc.
*
* Since IntrusiveList doesn't require any form of `Allocator`, the allocation strategy is completely left up to the
* application. This means that items could be allocated on the stack, pooled, or items mixed between stack and heap.
*
* IntrusiveList matches `std::list` with the following exceptions:
* - The `iterator` and `initializer_list` constructor variants are not present in IntrusiveList.
* - The `iterator` and `initializer_list` insert() variants are not present in IntrusiveList.
* - IntrusiveList cannot be copied (though may still be moved).
* - IntrusiveList does not have `erase()` to erase an item from the list, but instead has remove() which will remove an
* item from the container. It is up to the caller to manage the memory for the item.
* - Likewise, clear() functions as a "remove all" and does not destroy items in the container.
* - IntrusiveList does not have any emplace functions as it is not responsible for construction of items.
* - iter_from_value() is a new function that translates an item contained in IntrusiveList into an iterator.
*
* Example:
* @code{.cpp}
* // Given a class Waiter whose purpose is to wait until woken:
* class Waiter {
* public:
* void wait();
* IntrusiveListLink<Waiter> link;
* };
*
* IntrusiveList<Waiter, &Waiter::link> list;
*
* Waiter w;
* list.push_back(w);
* w.wait();
* list.remove(w);
*
* // Since the Waiter instance is on the stack there is no heap used to track items in `list`.
* @endcode
*
* Example 2:
* @code{.cpp}
* // Intrusive list can be used to move items between multiple lists using the same link node without any heap
* // usage.
* class MyItem { public:
* // ...
* void process();
* IntrusiveListLink<MyItem> link;
* };
*
* using MyItemList = IntrusiveList<MyItem, &MyItem::link>;
* MyItemList dirty;
* MyItemList clean;
*
* MyItemList::iter;
* while (!dirty.empty())
* {
* MyItem& item = dirty.pop_front();
* item.process();
* clean.push_back(item);
* }
* @endcode
*
* @tparam T The contained object type.
* @tparam U A pointer-to-member of `T` that must be of type @ref IntrusiveListLink. This member will be used by the
* IntrusiveList for tracking the contained object.
*/
template <class T, IntrusiveListLink<T> T::*U>
class CARB_VIZ IntrusiveList
{
public:
//! The type of the contained object.
using ValueType = T;
//! The type of the @ref IntrusiveListLink that must be a member of ValueType.
using Link = IntrusiveListLink<T>;
// Iterator support
// clang-format off
//! A LegacyBidirectionalIterator to `const ValueType`.
//! @see <a href="https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator">LegacyBidirectionalIterator</a>
class const_iterator
{
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
using iterator_category = std::bidirectional_iterator_tag;
using value_type = ValueType;
using difference_type = ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
const_iterator() noexcept = default;
reference operator * () const { assertNotEnd(); return IntrusiveList::_value(*m_where); }
pointer operator -> () const { assertNotEnd(); return std::addressof(operator*()); }
const_iterator& operator ++ () noexcept /* ++iter */ { assertNotEnd(); incr(); return *this; }
const_iterator operator ++ (int) noexcept /* iter++ */ { assertNotEnd(); const_iterator i{ *this }; incr(); return i; }
const_iterator& operator -- () noexcept /* --iter */ { decr(); return *this; }
const_iterator operator -- (int) noexcept /* iter-- */ { const_iterator i{ *this }; decr(); return i; }
bool operator == (const const_iterator& rhs) const noexcept { assertSameOwner(rhs); return m_where == rhs.m_where; }
bool operator != (const const_iterator& rhs) const noexcept { assertSameOwner(rhs); return m_where != rhs.m_where; }
protected:
friend class IntrusiveList;
Link* m_where{ nullptr };
#if CARB_ASSERT_ENABLED
const IntrusiveList* m_owner{ nullptr };
const_iterator(Link* where, const IntrusiveList* owner) : m_where(where), m_owner(owner) {}
void assertOwner(const IntrusiveList* list) const noexcept
{
CARB_ASSERT(m_owner == list, "IntrusiveList iterator for invalid container");
}
void assertSameOwner(const const_iterator& rhs) const noexcept
{
CARB_ASSERT(m_owner == rhs.m_owner, "IntrusiveList iterators are from different containers");
}
void assertNotEnd() const noexcept
{
CARB_ASSERT(m_where != m_owner->_end(), "Invalid operation on IntrusiveList::end() iterator");
}
#else
const_iterator(Link* where, const IntrusiveList*) : m_where(where) {}
void assertOwner(const IntrusiveList* list) const noexcept
{
CARB_UNUSED(list);
}
void assertSameOwner(const const_iterator& rhs) const noexcept
{
CARB_UNUSED(rhs);
}
void assertNotEnd() const noexcept {}
#endif // !CARB_ASSERT_ENABLED
void incr() { m_where = m_where->m_next; }
void decr() { m_where = m_where->m_prev; }
#endif // !DOXYGEN_SHOULD_SKIP_THIS
};
//! A LegacyBidirectionalIterator to `ValueType`.
//! @see <a href="https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator">LegacyBidirectionalIterator</a>
class iterator : public const_iterator
{
using Base = const_iterator;
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
using iterator_category = std::bidirectional_iterator_tag;
using value_type = ValueType;
using difference_type = ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
iterator() noexcept = default;
reference operator * () const { this->assertNotEnd(); return IntrusiveList::_value(*this->m_where); }
pointer operator -> () const { this->assertNotEnd(); return std::addressof(operator*()); }
iterator& operator ++ () noexcept /* ++iter */ { this->assertNotEnd(); this->incr(); return *this; }
iterator operator ++ (int) noexcept /* iter++ */ { this->assertNotEnd(); iterator i{ *this }; this->incr(); return i; }
iterator& operator -- () noexcept /* --iter */ { this->decr(); return *this; }
iterator operator -- (int) noexcept /* iter-- */ { iterator i{ *this }; this->decr(); return i; }
protected:
friend class IntrusiveList;
iterator(Link* where, const IntrusiveList* owner) : Base(where, owner) {}
#endif
};
//! Helper definition for std::reverse_iterator<iterator>
using reverse_iterator = std::reverse_iterator<iterator>;
//! Helper definition for std::reverse_iterator<const_iterator>
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// clang-format on
CARB_PREVENT_COPY(IntrusiveList);
//! Constructor. Initializes `*this` to be empty().
constexpr IntrusiveList() : m_list(&m_list)
{
}
//! Move-construct. Moves all entries to `*this` from @p other and leaves it empty.
//! @param other Another IntrusiveList to move entries from.
IntrusiveList(IntrusiveList&& other) noexcept : m_list(&m_list)
{
swap(other);
}
//! Destructor. Implies clear().
~IntrusiveList()
{
clear();
m_list.m_next = m_list.m_prev = nullptr; // prevent the assert
}
//! Move-assign. Moves all entries from @p other and leaves @p other in a valid but possibly non-empty state.
//! @param other Another IntrusiveList to move entries from.
IntrusiveList& operator=(IntrusiveList&& other) noexcept
{
swap(other);
return *this;
}
//! Checks whether the container is empty.
//! @returns `true` if `*this` is empty; `false` otherwise.
bool empty() const noexcept
{
return !m_size;
}
//! Returns the number of elements contained.
//! @returns The number of elements contained.
size_t size() const noexcept
{
return m_size;
}
//! Returns the maximum possible number of elements.
//! @returns The maximum possible number of elements.
size_t max_size() const noexcept
{
return size_t(-1);
}
// Forward iterator support
//! Returns an iterator to the beginning.
//! @returns An iterator to the beginning.
iterator begin() noexcept
{
return iterator(_head(), this);
}
//! Returns an iterator to the end.
//! @returns An iterator to the end.
iterator end() noexcept
{
return iterator(_end(), this);
}
//! Returns a const_iterator to the beginning.
//! @returns A const_iterator to the beginning.
const_iterator cbegin() const noexcept
{
return const_iterator(_head(), this);
}
//! Returns a const_iterator to the end.
//! @returns A const_iterator to the end.
const_iterator cend() const noexcept
{
return const_iterator(_end(), this);
}
//! Returns a const_iterator to the beginning.
//! @returns A const_iterator to the beginning.
const_iterator begin() const noexcept
{
return cbegin();
}
//! Returns a const_iterator to the end.
//! @returns A const_iterator to the end.
const_iterator end() const noexcept
{
return cend();
}
// Reverse iterator support
//! Returns a reverse_iterator to the beginning.
//! @returns A reverse_iterator to the beginning.
reverse_iterator rbegin() noexcept
{
return reverse_iterator(end());
}
//! Returns a reverse_iterator to the end.
//! @returns A reverse_iterator to the end.
reverse_iterator rend() noexcept
{
return reverse_iterator(begin());
}
//! Returns a const_reverse_iterator to the beginning.
//! @returns A const_reverse_iterator to the beginning.
const_reverse_iterator crbegin() const noexcept
{
return const_reverse_iterator(cend());
}
//! Returns a const_reverse_iterator to the end.
//! @returns A const_reverse_iterator to the end.
const_reverse_iterator crend() const noexcept
{
return const_reverse_iterator(cbegin());
}
//! Returns a const_reverse_iterator to the beginning.
//! @returns A const_reverse_iterator to the beginning.
const_reverse_iterator rbegin() const noexcept
{
return crbegin();
}
//! Returns a const_reverse_iterator to the end.
//! @returns A const_reverse_iterator to the end.
const_reverse_iterator rend() const noexcept
{
return crend();
}
//! Returns an iterator to the given value if it is contained in `*this`, otherwise returns `end()`. O(n).
//! @param[in] value The value to check for.
//! @returns An @ref iterator to @p value if contained in `*this`; end() otherwise.
iterator locate(T& value) noexcept
{
Link* l = _link(value);
if (!l->isContained())
return end();
Link* b = m_list.m_next;
while (b != _end())
{
if (b == l)
return iterator(l, this);
b = b->m_next;
}
return end();
}
//! Returns an iterator to the given value if it is contained in `*this`, otherwise returns `end()`. O(n).
//! @param[in] value The value to check for.
//! @returns A @ref const_iterator to @p value if contained in `*this`; end() otherwise.
const_iterator locate(T& value) const noexcept
{
Link* l = _link(value);
if (!l->isContained())
return end();
Link* b = m_list.m_next;
while (b != _end())
{
if (b == l)
return const_iterator(l, this);
b = b->m_next;
}
return end();
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
CARB_DEPRECATED("Use locate()") iterator find(T& value) noexcept
{
return locate(value);
}
CARB_DEPRECATED("Use locate()") const_iterator find(T& value) const noexcept
{
return locate(value);
}
#endif
//! Naively produces an @ref IntrusiveList::iterator for @p value within `*this`.
//! @warning Undefined behavior results if @p value is not contained within `*this`. Use find() to safely check.
//! @param value The value to convert.
//! @returns An @ref iterator to @p value.
iterator iter_from_value(T& value)
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained() || locate(value) != end());
return iterator(l->isContained() ? l : _end(), this);
}
//! Naively produces an @ref IntrusiveList::iterator for @p value within `*this`.
//! @warning Undefined behavior results if @p value is not contained within `*this`. Use find() to safely check.
//! @param value The value to convert.
//! @returns A @ref const_iterator to @p value.
const_iterator iter_from_value(T& value) const
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained() || locate(value) != end());
return const_iterator(l->isContained() ? l : _end(), this);
}
//! Accesses the first element.
//! @warning Undefined behavior if `*this` is empty().
//! @returns A reference to the first element.
T& front()
{
CARB_ASSERT(!empty());
return _value(*_head());
}
//! Accesses the first element.
//! @warning Undefined behavior if `*this` is empty().
//! @returns A const reference to the first element.
const T& front() const
{
CARB_ASSERT(!empty());
return _value(*_head());
}
//! Accesses the last element.
//! @warning Undefined behavior if `*this` is empty().
//! @returns A reference to the last element.
T& back()
{
CARB_ASSERT(!empty());
return _value(*_tail());
}
//! Accesses the last element.
//! @warning Undefined behavior if `*this` is empty().
//! @returns A const reference to the last element.
const T& back() const
{
CARB_ASSERT(!empty());
return _value(*_tail());
}
//! Inserts an element at the beginning of the list.
//! @note Precondition: @p value must not be contained (via `U`) in `*this` or any other IntrusiveList.
//! @param value The value to insert.
//! @returns @p value for convenience.
T& push_front(T& value)
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained());
Link* const prev = _head();
l->m_next = prev;
l->m_prev = _end();
m_list.m_next = l;
prev->m_prev = l;
++m_size;
return value;
}
//! Removes the first element.
//! @note Precondition: `*this` must not be empty().
//! @returns The prior first element in the list, which is now no longer contained in the list.
T& pop_front()
{
CARB_ASSERT(!empty());
Link* const head = _head();
Link* const next = head->m_next;
m_list.m_next = next;
next->m_prev = _end();
head->m_next = head->m_prev = nullptr;
--m_size;
return _value(*head);
}
//! Inserts an element at the end of the list.
//! @note Precondition: @p value must not be contained (via `U`) in `*this` or any other IntrusiveList.
//! @param value The value to insert.
//! @returns @p value for convenience.
T& push_back(T& value)
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained());
Link* const prev = _tail();
l->m_next = _end();
l->m_prev = prev;
prev->m_next = l;
m_list.m_prev = l;
++m_size;
return value;
}
//! Removes the last element.
//! @note Precondition: `*this` must not be empty().
//! @returns The prior last element in the list, which is now no longer contained in the list.
T& pop_back()
{
CARB_ASSERT(!empty());
Link* const tail = _tail();
Link* const prev = tail->m_prev;
m_list.m_prev = prev;
prev->m_next = _end();
tail->m_next = tail->m_prev = nullptr;
--m_size;
return _value(*tail);
}
//! Removes all elements from the list.
//! @note Postcondition: `*this` is empty().
void clear()
{
if (_head() != _end())
{
do
{
Link* p = _head();
m_list.m_next = p->m_next;
p->m_next = p->m_prev = nullptr;
} while (_head() != _end());
m_list.m_prev = _end();
m_size = 0;
}
}
//! Inserts an element before @p pos.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`; @p value must not be contained (via `U`)
//! in this or any other IntrusiveList.
//! @param pos A @ref const_iterator indicating the insertion position. @p value will be inserted before @p pos.
//! @param value The value to insert.
//! @returns An @ref iterator to the newly-inserted @p value.
iterator insert(const_iterator pos, T& value)
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained());
l->m_prev = pos.m_where->m_prev;
l->m_next = pos.m_where;
l->m_prev->m_next = l;
l->m_next->m_prev = l;
++m_size;
return iterator(l, this);
}
//! Removes an element by iterator.
//! @note Precondition: @p pos must be a valid const_iterator of `*this` and may not be end().
//! @param pos A @ref const_iterator to the element to remove.
//! @returns A @ref iterator to the element immediately following @p pos, or end() if no elements followed it.
iterator remove(const_iterator pos)
{
CARB_ASSERT(!empty());
pos.assertNotEnd();
pos.assertOwner(this);
Link* next = pos.m_where->m_next;
pos.m_where->m_prev->m_next = pos.m_where->m_next;
pos.m_where->m_next->m_prev = pos.m_where->m_prev;
pos.m_where->m_next = pos.m_where->m_prev = nullptr;
--m_size;
return iterator(next, this);
}
//! Removes an element by reference.
//! @note Precondition: @p value must be contained in `*this`.
//! @param value The element to remove.
//! @returns @p value for convenience.
T& remove(T& value)
{
Link* l = _link(value);
if (l->isContained())
{
CARB_ASSERT(!empty());
CARB_ASSERT(locate(value) != end());
l->m_prev->m_next = l->m_next;
l->m_next->m_prev = l->m_prev;
l->m_next = l->m_prev = nullptr;
--m_size;
}
return value;
}
//! Swaps the contents of `*this` with another IntrusiveList.
//! @param other The other IntrusiveList to swap with.
void swap(IntrusiveList& other) noexcept
{
if (this != std::addressof(other))
{
// Fix up the end iterators first.
Link *&lhead = _head()->m_prev, *<ail = _tail()->m_next;
Link *&rhead = other._head()->m_prev, *&rtail = other._tail()->m_next;
lhead = ltail = other._end();
rhead = rtail = _end();
// Now swap pointers
std::swap(_end()->m_next, other._end()->m_next);
std::swap(_end()->m_prev, other._end()->m_prev);
std::swap(m_size, other.m_size);
}
}
//! Merges two sorted lists.
//! @note Precondition: `*this` and @p other must be sorted using @p comp.
//! @note This operation is stable: for equivalent elements in the two lists elements from `*this` shall always
//! precede the elements from @p other. The order of equivalent elements within `*this` and @p other will not
//! change.
//! @param[inout] other Another IntrusiveList to merge with. Must be sorted via `comp`. Will be empty after this
//! call.
//! @param comp The comparator predicate, such as `std::less`.
template <class Compare>
void merge(IntrusiveList& other, Compare comp)
{
if (this == std::addressof(other))
return;
if (!other.m_size)
// Nothing to do
return;
// splice all of other's nodes onto the end of *this
Link* const head = _end();
Link* const otherHead = other._end();
Link* const mid = otherHead->m_next;
_splice(head, other, mid, otherHead, other.m_size);
if (head->m_next != mid)
_mergeSame(head->m_next, mid, head, comp);
}
//! Merges two sorted lists.
//! @see merge(IntrusiveList& other, Compare comp)
//! @param[inout] other Another IntrusiveList to merge with. Must be sorted via `comp`. Will be empty after this
//! call.
//! @param comp The comparator predicate, such as `std::less`.
template <class Compare>
void merge(IntrusiveList&& other, Compare comp)
{
merge(other, comp);
}
//! Merges two sorted lists via `std::less`.
//! @see merge(IntrusiveList& other, Compare comp)
//! @param[inout] other Another IntrusiveList to merge with. Must be sorted via `comp`. Will be empty after this
//! call.
void merge(IntrusiveList& other)
{
merge(other, std::less<ValueType>());
}
//! Merges two sorted lists via `std::less`.
//! @see merge(IntrusiveList& other, Compare comp)
//! @param[inout] other Another IntrusiveList to merge with. Must be sorted via `comp`. Will be empty after this
//! call.
void merge(IntrusiveList&& other)
{
merge(other);
}
//! Transfers elements from another IntrusiveList into `*this`.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`.
//! @param pos The position before which to insert elements from @p other.
//! @param other Another IntrusiveList to splice from. Will be empty after this call.
void splice(const_iterator pos, IntrusiveList& other)
{
pos.assertOwner(this);
if (this == std::addressof(other) || other.empty())
return;
_splice(pos.m_where, other, other.m_list.m_next, other._end(), other.m_size);
}
//! Transfers elements from another IntrusiveList into `*this`.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`.
//! @param pos The position before which to insert elements from @p other.
//! @param other Another IntrusiveList to splice from. Will be empty after this call.
void splice(const_iterator pos, IntrusiveList&& other)
{
splice(pos, other);
}
//! Transfers an element from another IntrusiveList into `*this`.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`. @p it must be a valid iterator of @p other
//! and may not be `other.end()`.
//! @param pos The position before which to insert the element from @p other.
//! @param other The IntrusiveList that @p it is from.
//! @param it An @ref iterator to an element from @p other. Will be removed from @p other and transferred to
//! `*this`.
void splice(const_iterator pos, IntrusiveList& other, iterator it)
{
pos.assertOwner(this);
it.assertNotEnd();
it.assertOwner(std::addressof(other));
Link* const last = it.m_where->m_next;
if (this != std::addressof(other) || (pos.m_where != it.m_where && pos.m_where != last))
_splice(pos.m_where, other, it.m_where, last, 1);
}
//! Transfers an element from another IntrusiveList into `*this`.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`. @p it must be a valid iterator of @p other
//! and may not be `other.end()`.
//! @param pos The position before which to insert the element from @p other.
//! @param other The IntrusiveList that @p it is from.
//! @param it An @ref iterator to an element from @p other. Will be removed from @p other and transferred to
//! `*this`.
void splice(const_iterator pos, IntrusiveList&& other, iterator it)
{
splice(pos, other, it);
}
//! Transfers a range of elements from another IntrusiveList into `*this`.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`. @p first and @p end must be a valid
//! iterator range of @p other. @p pos must not be in the range `[first, end)`.
//! @param pos The position before which to insert the element(s) from @p other.
//! @param other The IntrusiveList that @p first and @p end are from.
//! @param first Combined with @p end describes a range of elements from @p other that will be moved to @p pos.
//! @param end Combined with @p first describes a range of elements from @p other that will be moved to @p pos.
void splice(const_iterator pos, IntrusiveList& other, const_iterator first, const_iterator end)
{
pos.assertOwner(this);
first.assertOwner(std::addressof(other));
end.assertOwner(std::addressof(other));
if (first == end)
return;
#if CARB_ASSERT_ENABLED
if (pos.m_owner == first.m_owner)
{
// The behavior is undefined if pos is an iterator in the range [first, end); though we don't have an
// efficient way of testing for that, so loop through and check
for (const_iterator it = first; it != end; ++it)
CARB_ASSERT(it != pos);
}
#endif
if (this != std::addressof(other))
{
size_t range = std::distance(first, end);
CARB_ASSERT(other.m_size >= range);
other.m_size -= range;
m_size += range;
}
_splice(pos.m_where, first.m_where, end.m_where);
}
//! Transfers a range of elements from another IntrusiveList into `*this`.
//! @note Precondition: @p pos must be a valid const_iterator of `*this`. @p first and @p end must be a valid
//! iterator range of @p other. @p pos must not be in the range `[first, end)`.
//! @param pos The position before which to insert the element(s) from @p other.
//! @param other The IntrusiveList that @p first and @p end are from.
//! @param first Combined with @p end describes a range of elements from @p other that will be moved to @p pos.
//! @param end Combined with @p first describes a range of elements from @p other that will be moved to @p pos.
void splice(const_iterator pos, IntrusiveList&& other, const_iterator first, const_iterator end)
{
splice(pos, other, first, end);
}
//! Reverses the order of the elements.
void reverse() noexcept
{
Link* end = _end();
Link* n = end;
for (;;)
{
Link* next = n->m_next;
n->m_next = n->m_prev;
n->m_prev = next;
if (next == end)
break;
n = next;
}
}
//! Sorts the contained elements by the specified comparator function.
//! @param comp The comparator function, such as `std::less`.
template <class Compare>
void sort(Compare comp)
{
_sort(_end()->m_next, m_size, comp);
}
//! Sorts the contained elements by the specified comparator function.
void sort()
{
sort(std::less<ValueType>());
}
private:
CARB_VIZ Link m_list;
CARB_VIZ size_t m_size{ 0 };
template <class Compare>
static Link* _sort(Link*& first, size_t size, Compare comp)
{
switch (size)
{
case 0:
return first;
case 1:
return first->m_next;
default:
break;
}
auto mid = _sort(first, size >> 1, comp);
const auto last = _sort(mid, size - (size >> 1), comp);
first = _mergeSame(first, mid, last, comp);
return last;
}
template <class Compare>
static Link* _mergeSame(Link* first, Link* mid, const Link* last, Compare comp)
{
// Merge the sorted ranges [first, mid) and [mid, last)
// Returns the new beginning of the range (which won't be `first` if it was spliced elsewhere)
Link* newfirst;
if (comp(_value(*mid), _value(*first)))
// mid will be spliced to the front of the range
newfirst = mid;
else
{
// Establish comp(mid, first) by skipping over elements from the first range already in position
newfirst = first;
do
{
first = first->m_next;
if (first == mid)
return newfirst;
} while (!comp(_value(*mid), _value(*first)));
}
// process one run splice
for (;;)
{
auto runStart = mid;
// find the end of the run of elements we need to splice from the second range into the first
do
{
mid = mid->m_next;
} while (mid != last && comp(_value(*mid), _value(*first)));
// [runStart, mid) goes before first
_splice(first, runStart, mid);
if (mid == last)
return newfirst;
// Re-establish comp(mid, first) by skipping over elements from the first range already in position.
do
{
first = first->m_next;
if (first == mid)
return newfirst;
} while (!comp(_value(*mid), _value(*first)));
}
}
Link* _splice(Link* const where, IntrusiveList& other, Link* const first, Link* const last, size_t count)
{
if (this != std::addressof(other))
{
// Different list, need to fix up size
m_size += count;
other.m_size -= count;
}
return _splice(where, first, last);
}
static Link* _splice(Link* const before, Link* const first, Link* const last) noexcept
{
CARB_ASSERT(before != first && before != last && first != last);
Link* const firstPrev = first->m_prev;
firstPrev->m_next = last;
Link* const lastPrev = last->m_prev;
lastPrev->m_next = before;
Link* const beforePrev = before->m_prev;
beforePrev->m_next = first;
before->m_prev = lastPrev;
last->m_prev = firstPrev;
first->m_prev = beforePrev;
return last;
}
static Link* _link(T& value) noexcept
{
return std::addressof(value.*U);
}
static T& _value(Link& l) noexcept
{
// Need to calculate the offset of our link member which will allow adjusting the pointer to where T is.
// This will not work if T uses virtual inheritance. Also, offsetof() cannot be used because we have a pointer
// to the member
size_t offset = size_t(reinterpret_cast<uint8_t*>(&(((T*)0)->*U)));
return *reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(std::addressof(l)) - offset);
}
static const T& _value(const Link& l) noexcept
{
// Need to calculate the offset of our link member which will allow adjusting the pointer to where T is.
// This will not work if T uses virtual inheritance. Also, offsetof() cannot be used because we have a pointer
// to the member
size_t offset = size_t(reinterpret_cast<uint8_t*>(&(((T*)0)->*U)));
return *reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(std::addressof(l)) - offset);
}
constexpr Link* _head() const noexcept
{
return const_cast<Link*>(m_list.m_next);
}
constexpr Link* _tail() const noexcept
{
return const_cast<Link*>(m_list.m_prev);
}
constexpr Link* _end() const noexcept
{
return const_cast<Link*>(&m_list);
}
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/RingBuffer.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// Implements a thread-safe (if used as directed) ring-buffer that can be used to store objects of various types and
// sizes. An age-old problem of ring-buffers is that they must copy the data in and out because data may wrap around and
// therefore not be contiguous. This implementation gets around that issue by using virtual memory to map the same page
// adjacently in memory. This uses double the address space without double the memory and allows pointers to be returned
// to the caller that automatically wrap around.
#pragma once
#include "../Defines.h"
#include "../CarbWindows.h"
#include "../cpp/Atomic.h"
#include "../extras/Errors.h"
#include "../thread/Util.h"
#include <atomic>
#include <memory>
#include <utility>
#if CARB_POSIX
# include <sys/mman.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
#endif
#if CARB_PLATFORM_MACOS
# include <sys/posix_shm.h>
# define ftruncate64 ftruncate
#endif
namespace carb
{
namespace container
{
namespace detail
{
#if CARB_PLATFORM_WINDOWS
// RingBufferAllocator performs the memory-mapping trick listed above. First the requested size is rounded up to the
// system allocation granularity, then we search the address space for a place where we can map that much memory to two
// adjacent addresses.
class RingBufferAllocator
{
public:
uint8_t* Allocate(size_t& size)
{
if (!size)
size = 1;
// Get the allocation granularity
CARBWIN_SYSTEM_INFO info;
memset(&info, 0, sizeof(info));
::GetSystemInfo(reinterpret_cast<SYSTEM_INFO*>(&info));
// Round up to allocation granularity
size += (info.dwAllocationGranularity - 1);
size &= ~size_t(info.dwAllocationGranularity - 1);
HANDLE mapping = ::CreateFileMappingW(
CARBWIN_INVALID_HANDLE_VALUE, nullptr, CARBWIN_PAGE_READWRITE, (DWORD)(size >> 32), (DWORD)size, nullptr);
CARB_FATAL_UNLESS(
mapping != nullptr, "CreateFileMapping failed: %s", carb::extras::getLastWinApiErrorMessage().c_str());
// Map to two adjacent pages so that writes across the boundary will wrap around automatically.
for (;;)
{
// Try to reserve a block of memory large enough for both mappings
uint8_t* search = (uint8_t*)::VirtualAlloc(nullptr, size * 2, CARBWIN_MEM_RESERVE, CARBWIN_PAGE_READWRITE);
CARB_FATAL_UNLESS(search != nullptr, "Failed to find a mapping location");
::VirtualFree(search, 0, CARBWIN_MEM_RELEASE);
uint8_t* where = (uint8_t*)::MapViewOfFileEx(mapping, CARBWIN_FILE_MAP_ALL_ACCESS, 0, 0, size, search);
DWORD err1 = ::GetLastError();
CARB_FATAL_UNLESS(where || search, "MapViewOfFileEx failed to find starting location: %s",
carb::extras::getLastWinApiErrorMessage().c_str());
if (!where)
{
// Failed to map here; continue the search
continue;
}
uint8_t* where2 = (uint8_t*)::MapViewOfFileEx(mapping, CARBWIN_FILE_MAP_ALL_ACCESS, 0, 0, size, where + size);
DWORD err2 = ::GetLastError();
CARB_FATAL_UNLESS(where2 == nullptr || where2 == (where + size),
"MapViewOfFileEx returned unexpected value: %s",
carb::extras::getLastWinApiErrorMessage().c_str());
if (where2)
{
// We can close the mapping handle without affecting the mappings
::CloseHandle(mapping);
return where;
}
// Failed to map in the expected location; unmap and try again
::UnmapViewOfFile(where);
search = where + info.dwAllocationGranularity;
CARB_FATAL_UNLESS(search < info.lpMaximumApplicationAddress, "Failed to find a mapping location");
CARB_UNUSED(err1, err2);
}
}
void Free(uint8_t* mem, size_t size)
{
::UnmapViewOfFile(mem);
::UnmapViewOfFile(mem + size);
}
};
#elif CARB_POSIX
class RingBufferAllocator
{
public:
uint8_t* Allocate(size_t& size)
{
if (!size)
size = 1;
int const granularity = getpagesize();
// Round up to allocation granularity
size = (size + granularity - 1) & -(ptrdiff_t)granularity;
// Create a memory "file" and size to the requested size
# if 0
// memfd_create would be the preferable way of doing this, but it doesn't appear to be available
int fd = ::memfd_create("ringbuffer", 0u);
CARB_FATAL_UNLESS(fd != -1, "memfd_create failed: %d/%s", errno, strerror(errno));
# else
// Fall back to creating a shared memory object. Linux doesn't appear to have a way to do this anonymously like
// Windows does.
char buffer[128];
# if CARB_PLATFORM_MACOS
// Mac OS limits the SHM name to PSHMNAMLEN.
// POSIX seems to limit this to PATH_MAX.
snprintf(buffer, CARB_MIN(PSHMNAMLEN + 1, sizeof(buffer)), "/carb-ring-%d-%p", getpid(), this);
# else
snprintf(buffer, CARB_MIN(PATH_MAX + 1, sizeof(buffer)), "/carb-ringbuffer-%d-%p", getpid(), this);
# endif
int fd = shm_open(buffer, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
CARB_FATAL_UNLESS(fd != -1, "shm_open failed: %d/%s", errno, strerror(errno));
shm_unlink(buffer);
# endif
CARB_FATAL_UNLESS(ftruncate64(fd, size) != -1, "ftruncate failed: %d/%s", errno, strerror(errno));
// Map to two adjacent pages so that writes across the boundary will wrap around automatically.
// Try to map twice the address space and then re-map the top portion first
uint8_t* search = (uint8_t*)mmap(nullptr, size * 2, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (search != MAP_FAILED)
{
// Unmap the top half
munmap(search + size, size);
// Re-map as the same page as bottom
uint8_t* mmap2 = (uint8_t*)mmap(search + size, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mmap2 == (search + size))
{
// Success!
// We no longer need the file descriptor around since the mmaps survive without it
close(fd);
return search;
}
// Failed or didn't take the hint for some reason
if (mmap2 != MAP_FAILED)
munmap(mmap2, size);
munmap(search, size);
}
else
{
search = nullptr;
}
// Fall-back to search mode
for (;;)
{
uint8_t* where = (uint8_t*)mmap(search, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
CARB_FATAL_UNLESS(
where != MAP_FAILED || search, "mmap failed to find starting location: %d/%s", errno, strerror(errno));
if (where == MAP_FAILED || (search && where != search))
{
// Failed to map here; continue the search
CARB_FATAL_UNLESS(!where || munmap(where, size) == 0, "munmap failed: %d/%s", errno, strerror(errno));
search += granularity;
continue;
}
uint8_t* where2 = (uint8_t*)mmap(where + size, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (where2 != MAP_FAILED)
{
if (where2 == (where + size))
{
// We can close the file descriptor without affecting the mappings
close(fd);
return where;
}
// Got a response, but not where we asked for
CARB_FATAL_UNLESS(munmap(where2, size) == 0, "munmap failed: %d/%s", errno, strerror(errno));
where2 = nullptr;
}
// Failed to map in the expected location. Unmap the first and try again.
CARB_FATAL_UNLESS(munmap(where, size) == 0, "munmap failed: %d/%s", errno, strerror(errno));
search = where + granularity;
CARB_FATAL_UNLESS(search >= where, "Failed to find a mapping location");
}
}
void Free(uint8_t* mem, size_t size)
{
munmap(mem, size);
munmap(mem + size, size);
}
};
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
} // namespace detail
class RingBuffer : private detail::RingBufferAllocator
{
public:
/**
* The guaranteed minimum alignment returned by alloc().
*/
constexpr static size_t kMinAlignment = sizeof(size_t);
/**
* The maximum alignment that can be requested by alloc().
*/
constexpr static size_t kMaxAlignment = 4096;
/**
* Constructs the RingBuffer
*
* @param memSize The requested size in bytes. This will be rounded up to the system's allocation granularity.
*/
RingBuffer(size_t memSize);
~RingBuffer();
/**
* Returns the storage capacity of the RingBuffer.
*
* This size will be greater than or equal to the size passed to the RingBuffer() constructor. Not all of this space
* is usable by the application as some is used for internal record-keeping.
*
* @return size in bytes of the storage area of the RingBuffer
*/
size_t capacity() const;
/**
* Returns the approximate used space of the RingBuffer.
*
* This is approximate due to other threads potentially changing the RingBuffer while this function is being called.
*
* @return the approximate size in bytes available to be read
*/
size_t approx_used() const;
/**
* Returns the approximate available space of the RingBuffer.
*
* This is approximate due to other threads potentially changing the RingBuffer while this function is being called.
* Also, some memory is used for record-keeping, so not all of this space is available to the application.
*
* @return the approximate size in bytes available to be written
*/
size_t approx_available() const;
/**
* Allocates the requested size from the RingBuffer.
*
* The returned pointer is not available to be read() from the RingBuffer until commit() is called. If space is not
* available, or the requested size exceed the total available memory of the RingBuffer, nullptr is returned.
* @thread_safety may be called from multiple threads simultaneously.
*
* @param bytes The requested size in bytes to write to the RingBuffer
* @param align The alignment required for the returned memory block. at least `sizeof(size_t)` alignment is
* guaranteed. Must be a power of 2 and must not exceed \ref kMaxAlignment.
* @return A pointer to memory of \ref bytes size to be written by the application. Use commit() to signal to the
* RingBuffer that the memory is ready to be read(). nullptr is returned if the requested size is not available or
* the requested alignment could not be granted.
*/
void* alloc(size_t bytes, size_t align = 0);
/**
* Allocates the requested size from the RingBuffer, waiting until space is available.
*
* The returned pointer is not available to be read() from the RingBuffer until commit() is called. If space is not
* available, \ref onWait is called and the function waits until space is available. If the requested size exceeds
* the total available memory of the RingBuffer, or alignment is invalid, nullptr is returned. Note that in a
* single-threaded environment, this function may deadlock.
*
* @thread_safety may be called from multiple threads simultaneously.
*
* @param bytes The requested size in bytes to write to the RingBuffer
* @param onWait A function-like object that is called when waiting must occur
* @param align The alignment required for the returned memory block. at least `sizeof(size_t)` alignment is
* guaranteed. Must be a power of 2 and must not exceed \ref kMaxAlignment.
* @return A pointer to memory of \ref bytes size to be written by the application. Use commit() to signal to the
* RingBuffer that the memory is ready to be read(). nullptr is returned if the requested size exceeds the total
* RingBuffer size or the requested alignment could not be granted.
*/
template <class Func>
void* allocWait(size_t bytes, Func&& onWait, size_t align = 0);
/**
* Commits memory returned by alloc() or allocWait() and makes it available to read().
*
* This must be called on every block of memory returned from alloc() and allocWait(), otherwise subsequent read()
* operations will fail.
*
* @thread_safety may be called from multiple threads simultaneously.
*
* @param where The memory returned from alloc() that is ready to be committed.
*/
void commit(void* where);
/**
* Peeks at next value from the RingBuffer without removing it, and calls \ref f() with the value.
*
* @thread_safety may be called from multiple threads simultaneously, and may be called while other threads are
* writing via alloc() and commit(). May NOT be called while read() is called from another thread.
*
* @param f must be a function-like object with signature void(void* memory, size_t size) where memory is a pointer
* to the memory block that was returned from alloc() and size is the size that was passed to alloc().
* @return true if a value was successfully peeked and \ref f was called. false if no values are available to be
* peeked or the next value has not been committed by commit() yet.
*/
template <class Func>
bool peek(Func&& f) const;
/**
* Reads a value from the RingBuffer and calls \ref f() with the value.
*
* @thread_safety may NOT be called from multiple threads simultaneously. Can be called while other threads are
* writing via alloc() and commit(). Must also be serialized with peek().
*
* @param f must be a function-like object with signature void(void* memory, size_t size) where memory is a pointer
* to the memory block that was returned from alloc() and size is the size that was passed to alloc().
* @return true if a value was successfully read and \ref f was called. false if no values are available to be read
* or the next value has not been committed by commit() yet.
*/
template <class Func>
bool read(Func&& f);
/**
* Reads all values from the RingBuffer and calls \ref f() on each value. Causes less contention with alloc() than
* repeated read() calls because shared pointers are only updated at the end, but this also means that space in the
* RingBuffer only becomes available right before readAll() returns.
*
* @thread_safety may NOT be called from multiple threads simultaneously. Can be called while other threads are
* writing via alloc() and commit(). Must also be serialized with peek() and read().
*
* @param f must be a function-like object with signature bool(void* memory, size_t size) where memory is a pointer
* to the memory block that was returned from alloc() and `size` is the size that was passed to alloc(). If \ref f
* returns true, then the value is consumed and \ref f is called with the next value if one exists. If \ref f
* returns false, then the value is not consumed (similar to peek()) and readAll() terminates.
* @returns the count of times that \ref f returns true. If the next value to read is not committed, or no values
* are available for read, 0 is returned.
*/
template <class Func>
size_t readAll(Func&& f);
/**
* Reads a value from the RingBuffer by copying it into the given buffer.
*
* @thread_safety may be called from multiple threads simultaneously. Can be called while other threads are writing
* via alloc() and commit(). When multiple threads are reading simultaneously, a larger value (than \ref bufferSize)
* may be spuriously returned and should be ignored by the application.
*
* When a single thread is calling readCopy(), \ref bufferSize can be 0 to determine the size of the next value to
* be read. With multiple threads calling readCopy() another thread could read the value.
*
* @param buffer The memory buffer to write to.
* @param bufferSize The size of \ref buffer and the maximum size of an object that can be read.
* @return 0 if no values are available to be read or the next value hasn't been committed by commit() yet. If
* the return value is less-than or equal-to bufferSize, the next value has been read and copied into \ref buffer.
* If the return value is greater than bufferSize, the value has NOT been read and the return value indicates the
* minimum size of \ref bufferSize required to read the next object.
*/
size_t readCopy(void* buffer, size_t bufferSize);
/**
* Returns if \ref mem belongs to the RingBuffer.
*
* @param mem The memory block to check.
* @return true if \ref mem is owned by the RingBuffer; false otherwise.
*/
bool isOwned(void* mem) const;
/**
* Helper function to write the given object to the RingBuffer.
*
* @thread_safety may be called from multiple threads simultaneously.
*
* @param t The object to write. This parameter is forwarded to the constructor of T.
* @return true if the object was written; false if space could not be allocated for the object.
*/
template <class T>
bool writeObject(T&& t);
/**
* Helper function to write the given object to the RingBuffer, waiting until space is available to write.
*
* Note that in a single-threaded environment, this function may deadlock.
*
* @thread_safety may be called from multiple threads simultaneously.
*
* @param t The object to write. This parameter is forwarded to the constructor of T.
* @param onWait The function-like object to call when waiting must occur.
* @return true if the object was written; false if space could not be allocated for the object.
*/
template <class T, class Func>
bool writeObjectWait(T&& t, Func&& onWait);
/**
* Helper function to read an object from the RingBuffer.
*
* @thread_safety may NOT be called from multiple threads simultaneously. Can be called while other threads are
* writing via alloc() and commit().
*
* @param t The object to populate (via std::move) with the next object in the RingBuffer.
* @return true if the object was read; false if no object was available to read
*/
template <class T>
bool readObject(T& t);
/**
* Waits until data has been allocated from the RingBuffer. This is not as useful as waiting for committed data
* (since data may not yet be available to read), but can be done simultaneously by multiple threads.
*
* @thread_safety may be called from multiple threads simultaneously.
*/
void waitForAllocatedData();
/**
* Waits until data has been committed to the RingBuffer that is ready to be read.
*
* @thread_safety may NOT be called from multiple threads simultaneously. Can be called while other threads are
* writing via alloc() and commit(). Use waitForAllocatedData() if multiple threads are necessary.
*/
void waitForCommittedData();
private:
struct Header
{
constexpr static uint32_t kCommitted = uint32_t(1) << 0;
constexpr static uint32_t kPadding = uint32_t(1) << 1;
carb::cpp::atomic_uint32_t bytes;
std::uint32_t requestedBytes;
Header(uint32_t bytes_, uint32_t requestedBytes_, uint32_t flags = 0)
: bytes(bytes_ | flags), requestedBytes(requestedBytes_)
{
CARB_ASSERT((bytes_ & (kCommitted | kPadding)) == 0);
}
};
size_t constrain(size_t val) const
{
return val & (m_memorySize - 1);
}
template <class T>
static T* alignForward(T* where, size_t align)
{
return reinterpret_cast<T*>((reinterpret_cast<size_t>(where) + align - 1) & -(ptrdiff_t)align);
}
static bool isPowerOf2(size_t val)
{
return (val & (val - 1)) == 0;
}
constexpr static size_t kCacheLineSize = 64;
uint8_t* const m_memory;
size_t const m_memorySize;
carb::cpp::atomic_size_t m_readPtr{ 0 };
// Pad so that the write head/tail members are in a separate cache line
size_t padding1[(kCacheLineSize - sizeof(uint8_t*) - sizeof(size_t) - sizeof(carb::cpp::atomic_size_t)) / sizeof(size_t)];
// Use a two-phased write approach. The stable condition is where m_writeHead and m_writeTail are equal. However,
// during alloc(), m_writeHead is moved first and the space between m_writeHead and m_writeTail is in flux and can
// not be read. Once alloc() has written everything that it needs to, m_writeTail catches up to m_writeHead and the
// RingBuffer is once again stable.
carb::cpp::atomic_size_t m_writeHead{ 0 };
carb::cpp::atomic_size_t m_writeTail{ 0 };
// Pad out to a separate cache line
size_t padding2[(kCacheLineSize - (2 * sizeof(carb::cpp::atomic_size_t))) / sizeof(size_t)];
};
inline RingBuffer::RingBuffer(size_t memSize)
: m_memory(detail::RingBufferAllocator::Allocate(memSize)), m_memorySize(memSize)
{
CARB_UNUSED(padding1);
CARB_UNUSED(padding2);
static_assert(alignof(Header) <= kMinAlignment, "Invalid alignment assumption");
#if CARB_DEBUG
// Test rollover
m_readPtr = m_writeHead = m_writeTail = size_t(-ptrdiff_t(m_memorySize));
#endif
}
inline RingBuffer::~RingBuffer()
{
// Nothing should be remaining in the ring buffer at destruction time
CARB_ASSERT(approx_used() == 0);
detail::RingBufferAllocator::Free(m_memory, m_memorySize);
}
inline size_t RingBuffer::capacity() const
{
return m_memorySize;
}
inline size_t RingBuffer::approx_used() const
{
size_t write = m_writeTail.load(std::memory_order_relaxed);
size_t read = m_readPtr.load(std::memory_order_relaxed);
ptrdiff_t diff = (write - read);
return diff < 0 ? 0 : diff > ptrdiff_t(m_memorySize) ? m_memorySize : size_t(diff);
}
inline size_t RingBuffer::approx_available() const
{
return capacity() - approx_used();
}
inline void* RingBuffer::alloc(size_t bytes, size_t align)
{
// Will never have enough memory to allocate this
if (bytes == 0 || (bytes + align) > (m_memorySize - sizeof(Header)))
return nullptr;
// Alignment greater than max is not allowed
if (align > kMaxAlignment || !isPowerOf2(align))
{
return nullptr;
}
// Make sure bytes is aligned at least to kMinAlignment.
size_t requestedBytes = bytes;
bytes = (bytes + kMinAlignment - 1) & -(ptrdiff_t)kMinAlignment;
if (align <= kMinAlignment)
align = kMinAlignment;
size_t const baseNeeded = bytes + sizeof(Header);
size_t writeHead = m_writeHead.load(std::memory_order_acquire);
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
uint8_t* currentMem;
ptrdiff_t padding;
size_t needed;
for (;;)
{
currentMem = m_memory + constrain(writeHead) + sizeof(Header);
padding = alignForward(currentMem, align) - currentMem;
CARB_ASSERT((padding & ptrdiff_t(sizeof(Header) - 1)) == 0); // Must be aligned to sizeof(Header)
needed = baseNeeded + padding;
// Check if we have enough available to satisfy the request
if (ptrdiff_t(needed) > ptrdiff_t(capacity() - (writeHead - readPtr)))
{
return nullptr;
}
// Update the pointer
if (CARB_LIKELY(m_writeHead.compare_exchange_strong(
writeHead, writeHead + needed, std::memory_order_acquire, std::memory_order_relaxed)))
break;
// Failed; writeHead was updated by the failed compare_exchange; refresh readPtr
readPtr = m_readPtr.load(std::memory_order_acquire);
}
if (padding)
{
// Create the padding space Header if necessary
new (currentMem - sizeof(Header)) Header(uint32_t(padding - sizeof(Header)), uint32_t(padding - sizeof(Header)),
Header::kPadding | Header::kCommitted);
currentMem += padding;
}
// Create the header (with the kCommitted bit zero)
new (currentMem - sizeof(Header)) Header(uint32_t(bytes), uint32_t(requestedBytes));
// We have to wait until m_writeTail becomes our writeHead. This allows sequential writes to be properly ordered.
size_t tail = m_writeTail.load(std::memory_order_relaxed);
while (tail != writeHead)
{
m_writeTail.wait(tail, std::memory_order_relaxed);
tail = m_writeTail.load(std::memory_order_relaxed);
}
m_writeTail.store(writeHead + needed, std::memory_order_release);
m_writeTail.notify_all();
return currentMem;
}
template <class Func>
inline void* RingBuffer::allocWait(size_t bytes, Func&& onWait, size_t align)
{
// Will never have enough memory to allocate this
if (bytes == 0 || (bytes + align) > (m_memorySize - sizeof(Header)))
{
return nullptr;
}
// Alignment greater than max is not allowed
if (align > kMaxAlignment || !isPowerOf2(align))
{
CARB_ASSERT(0);
return nullptr;
}
// Make sure bytes is aligned at least to kMinAlignment.
size_t requestedBytes = bytes;
bytes = (bytes + kMinAlignment - 1) & -(ptrdiff_t)kMinAlignment;
size_t const baseNeeded = bytes + sizeof(Header);
size_t writeHead;
uint8_t* const baseMem = m_memory;
uint8_t* currentMem;
ptrdiff_t padding;
size_t needed;
if (align <= kMinAlignment)
{
// We don't need any padding, so just increment the pointer
needed = baseNeeded;
padding = 0;
writeHead = m_writeHead.fetch_add(needed, std::memory_order_acquire);
currentMem = baseMem + constrain(writeHead) + sizeof(Header);
}
else
{
// When specific alignment is required, we can't blindly increment the writeHead pointer, because the amount of
// padding necessary is dependent on the current value of writeHead.
writeHead = m_writeHead.load(std::memory_order_acquire);
for (;;)
{
currentMem = baseMem + constrain(writeHead) + sizeof(Header);
padding = alignForward(currentMem, align) - currentMem;
CARB_ASSERT((padding & ptrdiff_t(sizeof(Header) - 1)) == 0); // Must be aligned to sizeof(Header)
needed = baseNeeded + padding;
// Update the pointer
if (CARB_LIKELY(m_writeHead.compare_exchange_strong(
writeHead, writeHead + needed, std::memory_order_acquire, std::memory_order_relaxed)))
{
break;
}
// Failed; writeHead was updated by the failed compare_exchange. Loop and try again
}
}
// If necessary, block until we have space to write
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
if (CARB_UNLIKELY(ptrdiff_t(writeHead + needed - readPtr) > ptrdiff_t(m_memorySize)))
{
// We don't currently have capacity, so we need to wait
onWait();
// Wait for memory to be available
do
{
m_readPtr.wait(readPtr, std::memory_order_relaxed);
readPtr = m_readPtr.load(std::memory_order_relaxed);
} while (ptrdiff_t(writeHead + needed - readPtr) > ptrdiff_t(m_memorySize));
}
if (padding)
{
// Create the padding space Header if necessary
new (currentMem - sizeof(Header)) Header(uint32_t(padding - sizeof(Header)), uint32_t(padding - sizeof(Header)),
Header::kPadding | Header::kCommitted);
currentMem += padding;
}
// Create the header (with the kCommitted bit zero)
new (currentMem - sizeof(Header)) Header(uint32_t(bytes), uint32_t(requestedBytes));
// We have to wait until m_writeTail becomes our writeHead. This allows sequential writes to be properly ordered.
size_t tail = m_writeTail.load(std::memory_order_relaxed);
while (tail != writeHead)
{
m_writeTail.wait(tail, std::memory_order_relaxed);
tail = m_writeTail.load(std::memory_order_relaxed);
}
m_writeTail.store(writeHead + needed, std::memory_order_release);
m_writeTail.notify_all();
return currentMem;
}
inline void RingBuffer::commit(void* mem)
{
CARB_ASSERT(isOwned(mem));
Header* header = reinterpret_cast<Header*>(reinterpret_cast<uint8_t*>(mem) - sizeof(Header));
uint32_t result = header->bytes.fetch_or(Header::kCommitted, std::memory_order_release);
header->bytes.notify_one(); // notify the waiter in waitForCommittedData()
CARB_ASSERT(!(result & Header::kCommitted)); // Shouldn't already be committed
CARB_UNUSED(result);
}
template <class Func>
inline bool RingBuffer::peek(Func&& f) const
{
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
size_t writePtr = m_writeTail.load(std::memory_order_acquire);
for (;;)
{
// Any bytes to read?
if (ptrdiff_t(writePtr - readPtr) <= 0)
return false;
uint8_t* offset = m_memory + constrain(readPtr);
Header* header = reinterpret_cast<Header*>(offset);
// Check if the next header has been committed
uint32_t bytes = header->bytes.load(std::memory_order_acquire);
if (!!(bytes & Header::kPadding))
{
// For padding, we're just going to skip it and look ahead
CARB_ASSERT(!!(bytes & Header::kCommitted)); // Should be committed
bytes &= ~(Header::kPadding | Header::kCommitted);
readPtr += (bytes + sizeof(Header));
continue;
}
// Must be committed
if (!(bytes & Header::kCommitted))
return false;
bytes &= ~Header::kCommitted;
// This may also indicate multiple threads calling read() simultaneously which is not allowed
CARB_FATAL_UNLESS(
(bytes + sizeof(Header)) <= (writePtr - readPtr), "RingBuffer internal error or memory corruption");
// Call the function to handle the data
f(offset + sizeof(Header), header->requestedBytes);
return true;
}
}
template <class Func>
inline bool RingBuffer::read(Func&& f)
{
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
size_t writePtr = m_writeTail.load(std::memory_order_acquire);
for (;;)
{
// Any bytes to read?
if (ptrdiff_t(writePtr - readPtr) <= 0)
return false;
uint8_t* offset = m_memory + constrain(readPtr);
Header* header = reinterpret_cast<Header*>(offset);
// Check if the next header has been committed
size_t bytes = header->bytes.load(std::memory_order_acquire);
if (!!(bytes & Header::kPadding))
{
// Try to skip padding
CARB_ASSERT(!!(bytes & Header::kCommitted)); // Should be committed
bytes &= ~(Header::kPadding | Header::kCommitted);
CARB_FATAL_UNLESS(m_readPtr.exchange(readPtr + bytes + sizeof(Header), std::memory_order_release) == readPtr,
"RingBuffer::read is not thread-safe; call from only one thread or use readCopy()");
m_readPtr.notify_all();
readPtr += (bytes + sizeof(Header));
continue;
}
// Must be committed
if (!(bytes & Header::kCommitted))
return false;
bytes &= ~Header::kCommitted;
// This may also indicate multiple threads calling read() simultaneously which is not allowed
CARB_FATAL_UNLESS(
(bytes + sizeof(Header)) <= (writePtr - readPtr), "RingBuffer internal error or memory corruption");
// Call the function to handle the data
f(offset + sizeof(Header), header->requestedBytes);
// Move the read pointer
CARB_FATAL_UNLESS(m_readPtr.exchange(readPtr + bytes + sizeof(Header), std::memory_order_release) == readPtr,
"RingBuffer::read is not thread-safe; call from only one thread or use readCopy()");
m_readPtr.notify_all();
return true;
}
}
template <class Func>
inline size_t RingBuffer::readAll(Func&& f)
{
size_t origReadPtr = m_readPtr.load(std::memory_order_acquire);
size_t writePtr = m_writeTail.load(std::memory_order_acquire);
size_t count = 0;
size_t readPtr = origReadPtr;
for (;;)
{
// Any bytes to read?
if (ptrdiff_t(writePtr - readPtr) <= 0)
{
break;
}
uint8_t* offset = m_memory + constrain(readPtr);
Header* header = reinterpret_cast<Header*>(offset);
// Check if the next header has been committed
size_t bytes = header->bytes.load(std::memory_order_acquire);
if (!!(bytes & Header::kPadding))
{
// Try to skip padding
CARB_ASSERT(!!(bytes & Header::kCommitted)); // Should be committed
bytes &= ~(Header::kPadding | Header::kCommitted);
readPtr += (bytes + sizeof(Header));
continue;
}
// Terminate iteration if we encounter a non-committed value
if (!(bytes & Header::kCommitted))
break;
bytes &= ~Header::kCommitted;
// This may also indicate multiple threads calling read() simultaneously which is not allowed
CARB_FATAL_UNLESS(
(bytes + sizeof(Header)) <= (writePtr - readPtr), "RingBuffer internal error or memory corruption");
// Call the function to handle the data
if (!f(offset + sizeof(Header), header->requestedBytes))
break;
++count;
// Advance the read pointer
readPtr += (bytes + sizeof(Header));
}
if (readPtr != origReadPtr)
{
CARB_FATAL_UNLESS(m_readPtr.exchange(readPtr, std::memory_order_release) == origReadPtr,
"RingBuffer::readAll is not thread-safe; call from only one thread or use readCopy()");
m_readPtr.notify_all();
}
return count;
}
inline size_t RingBuffer::readCopy(void* buffer, size_t bufSize)
{
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
for (;;)
{
size_t writePtr = m_writeTail.load(std::memory_order_acquire);
// Any bytes to read?
if (ptrdiff_t(writePtr - readPtr) <= 0)
return 0;
uint8_t* offset = m_memory + constrain(readPtr);
Header* header = reinterpret_cast<Header*>(offset);
// Check if the next header has been committed
size_t bytes = header->bytes.load(std::memory_order_acquire);
if (!!(bytes & Header::kPadding))
{
// Try to skip padding
CARB_ASSERT(!!(bytes & Header::kCommitted)); // Padding is always committed
bytes &= ~(Header::kPadding | Header::kCommitted);
// If we fail the compare_exchange, readPtr is re-loaded and we try again.
if (CARB_LIKELY(m_readPtr.compare_exchange_strong(
readPtr, readPtr + sizeof(Header) + bytes, std::memory_order_release, std::memory_order_relaxed)))
readPtr += (sizeof(Header) + bytes);
m_readPtr.notify_all();
continue;
}
// Must be committed
if (!(bytes & Header::kCommitted))
return 0;
bytes &= ~Header::kCommitted;
if ((bytes + sizeof(Header)) > (writePtr - readPtr))
{
// This *may* happen if another thread has advanced the read pointer, and another thread has written to the
// block of data that we're currently trying to read from. It is incredibly rare, but we should refresh our
// pointers and try again.
readPtr = m_readPtr.load(std::memory_order_acquire);
continue;
}
// Check if we have enough space to write. If not, return the size needed. NOTE: for the reasons listed in the
// above comment, this may spuriously return.
if (header->requestedBytes > bufSize)
return header->requestedBytes;
// Copy the data
memcpy(buffer, offset + sizeof(Header), header->requestedBytes);
// If we fail the compare_exchange, readPtr is re-loaded and we try again.
if (CARB_LIKELY(m_readPtr.compare_exchange_strong(
readPtr, readPtr + sizeof(Header) + bytes, std::memory_order_release, std::memory_order_relaxed)))
{
m_readPtr.notify_all();
return header->requestedBytes;
}
}
}
inline bool RingBuffer::isOwned(void* mem) const
{
return mem >= m_memory && mem < (m_memory + (2 * m_memorySize));
}
template <class T>
bool RingBuffer::writeObject(T&& obj)
{
using Type = typename std::decay<T>::type;
void* mem = this->alloc(sizeof(Type), alignof(Type));
if (!mem)
return false;
new (mem) Type(std::forward<T>(obj));
this->commit(mem);
return true;
}
template <class T, class Func>
bool RingBuffer::writeObjectWait(T&& obj, Func&& onWait)
{
using Type = typename std::decay<T>::type;
void* mem = this->allocWait(sizeof(Type), std::forward<Func>(onWait), alignof(Type));
if (!mem)
return false;
new (mem) Type(std::forward<T>(obj));
this->commit(mem);
return true;
}
template <class T>
bool RingBuffer::readObject(T& obj)
{
return this->read([&obj](void* mem, size_t size) {
using Type = typename std::decay<T>::type;
CARB_UNUSED(size);
CARB_ASSERT(size >= sizeof(Type));
CARB_ASSERT((reinterpret_cast<size_t>(mem) & (alignof(Type) - 1)) == 0);
Type* p = reinterpret_cast<Type*>(mem);
obj = std::move(*p);
p->~Type();
});
}
inline void RingBuffer::waitForAllocatedData()
{
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
size_t writePtr = m_writeTail.load(std::memory_order_acquire);
while (ptrdiff_t(writePtr - readPtr) <= 0)
{
m_writeTail.wait(writePtr, std::memory_order_relaxed);
writePtr = m_writeTail.load(std::memory_order_relaxed);
}
}
inline void RingBuffer::waitForCommittedData()
{
size_t readPtr = m_readPtr.load(std::memory_order_acquire);
size_t writePtr = m_writeTail.load(std::memory_order_acquire);
for (;;)
{
// Any bytes to read?
if (ptrdiff_t(writePtr - readPtr) <= 0)
{
m_writeTail.wait(writePtr);
writePtr = m_writeTail.load(std::memory_order_relaxed);
continue;
}
uint8_t* offset = m_memory + constrain(readPtr);
Header* header = reinterpret_cast<Header*>(offset);
// Check if the next header has been committed
uint32_t bytes = header->bytes.load(std::memory_order_acquire);
if (!!(bytes & Header::kPadding))
{
// For padding, we're just going to skip it and look ahead
CARB_ASSERT(!!(bytes & Header::kCommitted)); // Should be committed
bytes &= ~(Header::kPadding | Header::kCommitted);
// Skip the header
readPtr += (bytes + sizeof(Header));
offset = m_memory + constrain(readPtr);
header = reinterpret_cast<Header*>(offset);
}
// Must be committed
if (!(bytes & Header::kCommitted))
{
// Wait for commit
header->bytes.wait(bytes, std::memory_order_relaxed);
}
// Bytes are now available
return;
}
}
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/RHUnorderedSet.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite Robin-hood Unordered Set container.
#pragma once
#include "RobinHoodImpl.h"
namespace carb
{
namespace container
{
/**
* Implements an Unordered Set, that is: a container that contains a set of keys that all must be unique. There is no
* defined order to the set of keys.
*
* \copydetails detail::RobinHood
*
* @warning This container is similar to, but not a drop-in replacement for `std::unordered_set` due to differences in
* iterator invalidation and memory layout.
*
* Iterator/reference/pointer invalidation (note differences from `std::unordered_set`):
* Operation | Invalidates
* --------- | -----------
* All read operations | Never
* `clear`, `rehash`, `reserve`, `operator=`, `insert`, `emplace` | Always
* `erase` | Only the element removed
* `swap` | All iterators, no pointers/references
*
* @tparam Key The key type
* @tparam Hasher A functor to use as a hashing function for \c Key
* @tparam Equals A functor to use to compare two \c Key values for equality
* @tparam LoadFactorMax100 The load factor to use for the table. This value must be in the range `[10, 100]` and
* represents the percentage of entries in the hash table that will be filled before resizing. Open-addressing hash maps
* with 100% usage have better memory usage but worse performance since they need "gaps" in the hash table to terminate
* runs.
*/
template <class Key, class Hasher = std::hash<Key>, class Equals = std::equal_to<Key>, size_t LoadFactorMax100 = 80>
class RHUnorderedSet
: public detail::RobinHood<LoadFactorMax100, Key, const Key, detail::Identity<Key, const Key>, Hasher, Equals>
{
using Base = detail::RobinHood<LoadFactorMax100, Key, const Key, detail::Identity<Key, const Key>, Hasher, Equals>;
public:
//! The key type
using key_type = typename Base::key_type;
//! The value type (effectively `const key_type`)
using value_type = typename Base::value_type;
//! Unsigned integer type (typically \c size_t)
using size_type = typename Base::size_type;
//! Signed integer type (typically \c ptrdiff_t)
using difference_type = typename Base::difference_type;
//! The hash function
using hasher = typename Base::hasher;
//! The key-equals function
using key_equal = typename Base::key_equal;
//! \c value_type&
using reference = typename Base::reference;
//! `const value_type&`
using const_reference = typename Base::const_reference;
//! \c value_type*
using pointer = typename Base::pointer;
//! `const value_type*`
using const_pointer = typename Base::const_pointer;
//! A \a LegacyForwardIterator to \c value_type
using iterator = typename Base::iterator;
//! A \a LegacyForwardIterator to `const value_type`
using const_iterator = typename Base::const_iterator;
//! A \a LegacyForwardIterator to \c value_type that proceeds to the next matching key when incremented.
using find_iterator = typename Base::find_iterator;
//! A \a LegacyForwardIterator to `const value_type` that proceeds to the next matching key when incremented.
using const_find_iterator = typename Base::const_find_iterator;
/**
* Constructs empty container.
*/
constexpr RHUnorderedSet() noexcept = default;
/**
* Copy constructor. Copies elements from another container.
*
* @note \c *this may have a different \ref capacity() than \p other.
* @param other The other container to copy entries from.
*/
RHUnorderedSet(const RHUnorderedSet& other) : Base(other)
{
}
/**
* Move constructor. Moves elements from another container.
*
* @note No move constructors on contained elements are invoked. \p other will be empty() after this operation.
* @param other The other container to move entries from.
*/
RHUnorderedSet(RHUnorderedSet&& other) : Base(std::move(other))
{
}
/**
* Destructor. Destroys all contained elements and frees memory.
*/
~RHUnorderedSet() = default;
/**
* Copy-assign operator. Destroys all currently stored elements and copies elements from another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedSet& operator=(const RHUnorderedSet& other)
{
Base::operator=(other);
return *this;
}
/**
* Move-assign operator. Effectively swaps with another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedSet& operator=(RHUnorderedSet&& other)
{
Base::operator=(std::move(other));
return *this;
}
/**
* Inserts an element into the container.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param value The value to insert by copying.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
std::pair<iterator, bool> insert(const value_type& value)
{
return this->insert_unique(value);
}
/**
* Inserts an element into the container.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param value The value to insert by moving.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
std::pair<iterator, bool> insert(value_type&& value)
{
return this->insert_unique(std::move(value));
}
/**
* Inserts an element into the container. Only participates in overload resolution if
* `std::is_constructible_v<value_type, P&&>` is true.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param value The value to insert by constructing via `std::forward<P>(value)`.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
template <class P>
std::pair<iterator, bool> insert(std::enable_if_t<std::is_constructible<value_type, P&&>::value, P&&> value)
{
return insert(value_type{ std::forward<P>(value) });
}
/**
* Constructs an element in-place.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param args The arguments to pass to the \c value_type constructor.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
template <class... Args>
std::pair<iterator, bool> emplace(Args&&... args)
{
// The value is the key, so just construct the item here
return insert(value_type{ std::forward<Args>(args)... });
}
/**
* Removes elements with the given key.
*
* References, pointers and iterators to the erase element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param key the key value of elements to remove
* @returns the number of elements removed (either 1 or 0).
*/
size_type erase(const key_type& key)
{
auto vt = this->internal_find(key);
if (vt)
{
this->internal_erase(vt);
return 1;
}
return 0;
}
/**
* Returns the number of elements matching the specified key.
*
* @param key The key to check for.
* @returns The number of elements with the given key (either 1 or 0).
*/
size_t count(const key_type& key) const
{
return !!this->internal_find(key);
}
#ifndef DOXYGEN_BUILD
using Base::begin;
using Base::cbegin;
using Base::cend;
using Base::end;
using Base::capacity;
using Base::empty;
using Base::max_size;
using Base::size;
using Base::clear;
using Base::erase;
using Base::swap;
using Base::contains;
using Base::equal_range;
using Base::find;
using Base::rehash;
using Base::reserve;
#endif
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/RobinHoodImpl.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite Robin-hood container generic implementation.
#pragma once
#include "../Defines.h"
#include <algorithm>
#include <iterator>
#include "../cpp/Bit.h"
namespace carb
{
namespace container
{
namespace detail
{
#ifndef DOXYGEN_BUILD
template <class Key, class ValueType>
struct Select1st
{
const Key& operator()(const ValueType& vt) const noexcept
{
return vt.first;
}
};
template <class Key, class ValueType>
struct Identity
{
const Key& operator()(const ValueType& vt) const noexcept
{
return vt;
}
};
#endif
/**
* Implements a "Robin Hood" open-addressing hash container that can either store keys alone or key/value pairs; this
* template is not meant to be used directly--instead use \ref RHUnorderedSet, \ref RHUnorderedMap,
* \ref RHUnorderedMultimap, or \ref RHUnorderedMultiset.
*
* \details
* In an open-addressing ("OA") hash table, the contained items are stored in the buckets directly. Contrast this with
* traditional hash tables that typically have a level of indirection: buckets point to the head of a linked-list that
* contains every item that hashes to that bucket. Open-addressing hash tables are great for using contiguous memory,
* whereas traditional hash tables have a separate allocation per node and fragment memory. However, OA hash tables have
* a couple downsides: if a collision occurs on insertion, probing must happen until an open spot is found where the
* item can be placed. For a find operation, probing must continue until an empty spot is reached to make sure that
* all keys have been checked. When erasing an item, a "deleted" marker must be put in its place so that probing past
* the key can continue. This system also gives advantage to earlier insertions and penalizes later collisions.
*
* The Robin Hood algorithm for open-addressing hashing was first postulated by Pedro Celis in 1986:
* https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf. Simply put, it applies a level of fairness to locality of
* items within the OA hash table. This is done by tracking the distance from an items ideal insertion point. Similarly
* the distance-from-ideal can be easily computed for existing locations that are probed. Once a probed location for a
* new item will cause the new item to be worse off (farther from ideal insertion) than the existing item, the new item
* can "steal" the location from the existing item, which must then probe until it finds a location where it is worse
* off than the existing item, and so on. This balancing of locality has beneficial side effects for finding and erasing
* too: when searching for an item, once a location is reached where the item would be worse off than the existing item,
* probing can cease with the knowledge that the item is not contained.
*
* OA hash tables cannot be direct drop-in replacements for closed-addressing hash containers such as
* `std::unordered_map` as nearly every modification to the table can potentially invalidate any other iterator.
*
* Open-addressing hash tables may not be a good replacement for `std` unordered containers in cases where the key
* and/or value is very large (though this may be mitigated somewhat by using indirection through `std::unique_ptr`).
* Since OA hash tables must carry the size of each value_type, having a low load factor (or a high capacity() to size()
* ratio) wastes a lot of memory, especially if the key/value pair is very large.
*
* It is important to keep OA hash tables as compact as possible, as operations like `clear()` and iterating over the
* hash table are `O(n)` over `capacity()`, not `size()`. You can always ensure that the hash table is as compact as
* possible by calling `rehash(0)`.
*
* Because of the nature of how elements are stored in this hash table, there are two iterator types: `iterator` and
* `find_iterator` (both with `const` versions). These types can be compared with each other, but incrementing these
* objects works differently. `iterator` and `const_iterator` traverse to the next item in the container, while
* `find_iterator` and `const_find_iterator` will only traverse to the next item with the same key. In multi-key
* containers, items with the same key may not necessarily be stored adjacently, so incrementing `iterator` may not
* encounter the next item with the same key as the previous. For unique-key containers, incrementing a `find_iterator`
* will always produce `end()` since keys are guaranteed to be unique.
*/
template <size_t LoadFactorMax100, class Key, class ValueType, class KeyFromValue, class Hasher, class Equals>
class CARB_VIZ RobinHood
{
public:
#ifndef DOXYGEN_BUILD
using key_type = Key;
using value_type = ValueType;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using hasher = Hasher;
using key_equal = Equals;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
static_assert(LoadFactorMax100 >= 10 && LoadFactorMax100 <= 100, "Load factor must be in range [10, 100]");
// clang-format off
class iter_base
{
public:
constexpr iter_base() noexcept = default;
bool operator == (const iter_base& other) const noexcept { CARB_ASSERT(owner == other.owner); return where == other.where; }
bool operator != (const iter_base& other) const noexcept { CARB_ASSERT(owner == other.owner); return where != other.where; }
protected:
constexpr iter_base(const RobinHood* owner_, value_type* where_) noexcept : owner(owner_), where(where_) {}
CARB_VIZ const RobinHood* owner{ nullptr };
CARB_VIZ value_type* where{ nullptr };
};
class CARB_VIZ const_find_iterator : public iter_base
{
using Base = iter_base;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = RobinHood::value_type;
using difference_type = ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
constexpr const_find_iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
const_find_iterator& operator ++ () noexcept { CARB_ASSERT(this->where); incr(); return *this; }
const_find_iterator operator ++ (int) noexcept { const_find_iterator i{ *this }; incr(); return i; }
protected:
friend class RobinHood;
constexpr const_find_iterator(const RobinHood* owner_, value_type* where_) noexcept : Base{ owner_, where_ } {}
void incr() { CARB_ASSERT(this->owner && this->where); this->where = this->owner->_findnext(this->where); }
};
class find_iterator : public const_find_iterator
{
using Base = const_find_iterator;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = RobinHood::value_type;
using difference_type = ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
constexpr find_iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
find_iterator& operator ++ () noexcept { CARB_ASSERT(this->where); this->incr(); return *this; }
find_iterator operator ++ (int) noexcept { CARB_ASSERT(this->where); find_iterator i{ *this }; this->incr(); return i; }
protected:
friend class RobinHood;
constexpr find_iterator(const RobinHood* owner_, value_type* where_) noexcept : Base(owner_, where_) {}
};
class CARB_VIZ const_iterator : public iter_base
{
using Base = iter_base;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = RobinHood::value_type;
using difference_type = ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
constexpr const_iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
const_iterator& operator ++ () noexcept { CARB_ASSERT(this->where); incr(); return *this; }
const_iterator operator ++ (int) noexcept { const_iterator i{ *this }; incr(); return i; }
protected:
friend class RobinHood;
constexpr const_iterator(const RobinHood* owner_, value_type* where_) noexcept : Base{ owner_, where_ } {}
void incr() { CARB_ASSERT(this->owner && this->where); this->where = this->owner->_next(this->where); }
};
class iterator : public const_iterator
{
using Base = const_iterator;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = RobinHood::value_type;
using difference_type = ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
constexpr iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
iterator& operator ++ () noexcept { CARB_ASSERT(this->where); this->incr(); return *this; }
iterator operator ++ (int) noexcept { CARB_ASSERT(this->where); iterator i{ *this }; this->incr(); return i; }
protected:
friend class RobinHood;
constexpr iterator(const RobinHood* owner_, value_type* where_) noexcept : Base(owner_, where_) {}
};
// clang-format on
constexpr RobinHood() noexcept = default;
RobinHood(const RobinHood& other)
{
// This effectively rebuilds `other` as *this, but it sizes *this as compactly as possible (whereas `other` may
// have a high capacity():size() ratio).
reserve(other.size());
for (auto& entry : other)
{
auto result = internal_insert_multi(KeyFromValue{}(entry));
new (result) value_type(entry); // copy
}
}
RobinHood(RobinHood&& other)
{
std::swap(m_data, other.m_data);
}
~RobinHood()
{
if (m_data.m_table)
{
if (!empty() && !std::is_trivially_destructible<value_type>::value)
{
for (size_t i = 0; i != m_data.m_tableSize; ++i)
{
if (isHashValid(m_data.m_hashes[i]))
m_data.m_table[i].~value_type();
}
}
std::free(std::exchange(m_data.m_table, nullptr));
m_data.m_hashes = nullptr;
m_data.m_size = m_data.m_tableSize = 0;
}
}
RobinHood& operator=(const RobinHood& other)
{
clear();
reserve(other.size());
for (auto& entry : other)
{
auto result = internal_insert_multi(KeyFromValue{}(entry));
new (result) value_type(entry);
}
return *this;
}
RobinHood& operator=(RobinHood&& other)
{
if (this != &other)
{
std::swap(m_data, other.m_data);
}
return *this;
}
#endif
/**
* Creates an iterator to the first element in the container.
*
* @returns a `const_iterator` to the first element in the container. If the container is empty() the iterator
* will be equal to \ref cend().
*/
const_iterator cbegin() const
{
if (CARB_UNLIKELY(empty()))
return cend();
auto const end = m_data.m_hashes + m_data.m_tableSize;
for (auto e = m_data.m_hashes; e != end; ++e)
if (isHashValid(*e))
return { this, m_data.m_table + (e - m_data.m_hashes) };
// Should never get here since we checked empty()
CARB_ASSERT(0);
return cend();
}
/**
* Creates an iterator to the first element in the container.
*
* @returns an `iterator` to the first element in the container. If the container is empty() the iterator will
* be equal to \ref end().
*/
iterator begin()
{
if (CARB_UNLIKELY(empty()))
return end();
auto const kEnd = m_data.m_hashes + m_data.m_tableSize;
for (auto e = m_data.m_hashes; e != kEnd; ++e)
if (isHashValid(*e))
return { this, m_data.m_table + (e - m_data.m_hashes) };
// Should never get here since we checked empty()
CARB_ASSERT(0);
return end();
}
/**
* Creates an iterator to the first element in the container.
*
* @returns a `const_iterator` to the first element in the container. If the container is empty() the iterator
* will be equal to \ref end().
*/
const_iterator begin() const
{
return cbegin();
}
/**
* Creates an iterator to the past-the-end element in the container.
*
* @returns a `const_iterator` to the past-the-end element in the container. This iterator is a placeholder;
* attempting to access it results in undefined behavior.
*/
const_iterator cend() const
{
return { this, nullptr };
}
/**
* Creates an iterator to the past-the-end element in the container.
*
* @returns an `iterator` to the past-the-end element in the container. This iterator is a placeholder;
* attempting to access it results in undefined behavior.
*/
iterator end()
{
return { this, nullptr };
}
/**
* Creates an iterator to the past-the-end element in the container.
*
* @returns a `const_iterator` to the past-the-end element in the container. This iterator is a placeholder;
* attempting to access it results in undefined behavior.
*/
const_iterator end() const
{
return cend();
}
/**
* Checks whether the container is empty.
* @returns \c true if the container contains no elements; \c false otherwise.
*/
bool empty() const noexcept
{
return !m_data.m_size;
}
/**
* Returns the number of elements contained. O(1)
* @returns the number of elements contained.
*/
size_t size() const noexcept
{
return m_data.m_size;
}
/**
* Returns the maximum possible number of elements. O(1)
* @returns the maximum possible number of elements.
*/
constexpr size_t max_size() const noexcept
{
return size_t(-1) & ~kDeletedBit;
}
/**
* Returns the number of elements that can be stored with the current memory usage. This is based on the
* `LoadFactorMax100` percentage and the current power-of-two memory allocation size. O(1)
* @see reserve()
* @returns the number of elements that can be stored with the current memory usage.
*/
size_t capacity() const noexcept
{
// Handle case where Windows.h may have defined 'max'
#pragma push_macro("max")
#undef max
if (CARB_LIKELY(m_data.m_tableSize <= (std::numeric_limits<size_t>::max() / 100)))
return (m_data.m_tableSize * LoadFactorMax100) / 100;
#pragma pop_macro("max")
// In the unlikely event of a huge table, switch operations to not overflow
return (m_data.m_tableSize / 100) * LoadFactorMax100;
}
/**
* Clears the contents. O(n) over \ref capacity()
*
* Erases all elements from the container. After this call \ref size() returns zero. Invalidates all iterators,
* pointers and references to contained elements.
*
* @note This does not free the memory used by the container; to free the hash table memory, use `rehash(0)` after
* this call.
*/
void clear()
{
if (!empty())
{
size_t* const end = m_data.m_hashes + m_data.m_tableSize;
for (size_t* e = m_data.m_hashes; e != end; ++e)
{
if (isHashValid(*e) && !std::is_trivially_destructible<value_type>::value)
m_data.m_table[e - m_data.m_hashes].~value_type();
*e = kEmpty;
}
m_data.m_size = 0;
}
}
/**
* Swaps the contents of two containers. O(1)
*
* Exchanges the contents of \c *this with \p other. Will not invoke any move/copy/swap operations on the individual
* elements.
*
* All iterators are invalidated for both containers. However, pointers and references to contained elements remain
* valid.
*
* The \c Hasher and \c KeyEqual template parameters must be \a Swappable.
* @param other The other container to swap with \c *this.
*/
void swap(RobinHood& other)
{
std::swap(m_data, other.m_data);
}
/**
* Removes the given element.
*
* References, pointers and iterators to the erased element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param pos The \c iterator to the element to remove. This iterator must be valid and dereferenceable.
* @returns the iterator immediately following \p pos.
*/
iterator erase(const_iterator pos)
{
CARB_ASSERT(pos.owner == this);
assertContained(pos.where);
internal_erase(pos.where);
return iterator{ this, _next(pos.where) };
}
/**
* Removes the elements in the given range.
*
* The range `[first, last)` must be a valid range in `*this`. References, pointers and iterators to erased elements
* are invalidated. All other iterators, pointers and references to other elements remain valid.
*
* @param first The start of the range of iterators to remove.
* @param last The past-the-end iterator for the range to remove.
* @returns \p last
*/
iterator erase(const_iterator first, const_iterator last)
{
while (first != last)
first = erase(first);
return { this, first.where };
}
/**
* Removes the given element.
*
* References, pointers and iterators to the erased element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param pos The \c const_find_iterator to the element to remove. This iterator must be valid and dereferenceable.
* @returns the \c find_iterator immediately following \p pos.
*/
find_iterator erase(const_find_iterator pos)
{
CARB_ASSERT(pos.owner == this);
assertContained(pos.where);
find_iterator next{ this, _findnext(pos.where) };
internal_erase(pos.where);
return next;
}
/**
* Removes the elements in the given range.
*
* The range `[first, last)` must be a valid range in `*this`. References, pointers and iterators to erased elements
* are invalidated. All other iterators, pointers and references to other elements remain valid.
*
* @param first The start of the range of iterators to remove.
* @param last The past-the-end iterator for the range to remove.
* @returns \p last
*/
find_iterator erase(const_find_iterator first, const_find_iterator last)
{
while (first != last)
first = erase(first);
return { this, first.where };
}
/**
* Finds the first element with the specified key.
*
* @note \c find_iterator objects returned from this function will only iterate through elements with the same key;
* they cannot be used to iterate through the entire container.
*
* @param key The key of the element(s) to search for.
* @returns a \c find_iterator to the first element matching \p key, or \ref end() if no element was found matching
* \p key.
*/
find_iterator find(const key_type& key)
{
return { this, internal_find(key) };
}
/**
* Finds the first element with the specified key.
*
* @note \c const_find_iterator objects returned from this function will only iterate through elements with the same
* key; they cannot be used to iterate through the entire container.
*
* @param key The key of the element(s) to search for.
* @returns a \c const_find_iterator to the first element matching \p key, or \ref cend() if no element was found
* matching \p key.
*/
const_find_iterator find(const key_type& key) const
{
return { this, internal_find(key) };
}
/**
* Returns whether there is at least one element matching a given key in the container.
*
* @note This function can be faster than \c count() for multimap and multiset containers.
* @param key The key of the element to search for.
* @returns \c true if at least one element matching \p key exists in the container; \c false otherwise.
*/
bool contains(const key_type& key) const
{
return !!internal_find(key);
}
/**
* Returns a range containing all elements with the given key.
*
* @note \c find_iterator objects returned from this function will only iterate through elements with the same key;
* they cannot be used to iterate through the entire container.
*
* @param key The key of the element(s) to search for.
* @returns A \c pair containing a pair of iterators for the desired range. If there are no such elements, both
* iterators will be \ref end().
*/
std::pair<find_iterator, find_iterator> equal_range(const key_type& key)
{
auto vt = this->internal_find(key);
find_iterator fend{ this, nullptr };
return vt ? std::make_pair(find_iterator{ this, vt }, fend) : std::make_pair(fend, fend);
}
/**
* Returns a range containing all elements with the given key.
*
* @note \c const_find_iterator objects returned from this function will only iterate through elements with the same
* key; they cannot be used to iterate through the entire container.
*
* @param key The key of the element(s) to search for.
* @returns A \c pair containing a pair of iterators for the desired range. If there are no such elements, both
* iterators will be \ref end().
*/
std::pair<const_find_iterator, const_find_iterator> equal_range(const key_type& key) const
{
auto vt = this->internal_find(key);
const_find_iterator fend{ this, nullptr };
return vt ? std::make_pair(const_find_iterator{ this, vt }, fend) : std::make_pair(fend, fend);
}
/**
* Reserves space for at least the specified number of elements and regenerates the hash table.
*
* Sets \ref capacity() of \c *this to a value greater-than-or-equal-to \p n. If \ref capacity() already exceeds
* \p n, nothing happens.
*
* If a rehash occurs, all iterators, pointers and references to existing elements are invalidated.
*
* @param n The desired minimum capacity of \c *this.
*/
void reserve(size_t n)
{
if (n > capacity())
{
rehash(n);
}
}
/**
* Sets the capacity of the container to the lowest valid value greater-than-or-equal-to the given value, and
* rehashes the container.
*
* If \p n is less-than \ref size(), \ref size() is used instead.
*
* The value is computed as if by `cpp::bit_ceil(std::ceil(float(n * 100) / float(LoadFactorMax100)))` with a
* minimum size of 8.
*
* If the container is empty and \p n is zero, the memory for the container is freed.
*
* After this function is called, all iterators, pointers and references to existing elements are invalidated.
*
* @param n The minimum capacity for the container. The actual size of the container may be larger than this.
*/
void rehash(size_t n)
{
if (n < m_data.m_size)
n = m_data.m_size;
if (n == 0)
{
std::free(m_data.m_table);
m_data.m_table = nullptr;
m_data.m_hashes = nullptr;
m_data.m_tableSize = 0;
return;
}
ncvalue_type* const oldtable = m_data.m_table;
size_t* const oldhashes = m_data.m_hashes;
size_t* const oldend = oldhashes + m_data.m_tableSize;
size_t minsize = (n * 100 + (LoadFactorMax100 - 1)) / LoadFactorMax100; // ceiling (round up)
constexpr static auto kMinSize_ = kMinSize; // CC-1110
size_t newsize = ::carb_max(kMinSize_, cpp::bit_ceil(minsize)); // must be a power of 2
m_data.m_tableSize = newsize;
CARB_ASSERT(capacity() >= m_data.m_size);
m_data.m_table =
static_cast<ncvalue_type*>(std::malloc(m_data.m_tableSize * (sizeof(ncvalue_type) + sizeof(size_t))));
m_data.m_hashes = reinterpret_cast<size_t*>(m_data.m_table + m_data.m_tableSize);
size_t* const end = m_data.m_hashes + m_data.m_tableSize;
// Initialize
for (size_t* e = m_data.m_hashes; e != end; ++e)
*e = kEmpty;
for (size_t* e = oldhashes; e != oldend; ++e)
if (isHashValid(*e))
{
auto result = internal_insert_multi2(*e, KeyFromValue{}(oldtable[e - oldhashes]));
new (result) ncvalue_type(std::move(oldtable[e - oldhashes]));
oldtable[e - oldhashes].~value_type();
}
std::free(oldtable);
}
#ifndef DOXYGEN_BUILD
protected:
constexpr static size_t kDeletedBit = size_t(1) << (8 * sizeof(size_t) - 1);
constexpr static size_t kEmpty = size_t(-1) & ~kDeletedBit;
constexpr static size_t kMinSize = 8; // Minimum hash table size
static_assert(cpp::has_single_bit(kMinSize), "Must be power of 2");
using ncvalue_type = typename std::remove_const_t<value_type>;
static constexpr bool isEmpty(size_t h) noexcept
{
return h == kEmpty;
}
static constexpr bool isDeleted(size_t h) noexcept
{
return !!(h & kDeletedBit);
}
static constexpr bool isHashValid(size_t h) noexcept
{
return !(isDeleted(h) || isEmpty(h));
}
struct Data : public Hasher, public Equals
{
CARB_VIZ ncvalue_type* m_table{ nullptr };
CARB_VIZ size_t* m_hashes{ nullptr };
CARB_VIZ size_t m_size{ 0 };
CARB_VIZ size_t m_tableSize{ 0 };
};
size_t hash(const key_type& key) const noexcept
{
const Hasher& hasher = m_data;
size_t h = size_t(hasher(key)) & ~kDeletedBit;
return h ^ (h == kEmpty);
}
bool equals(const key_type& k1, const key_type& k2) const noexcept
{
const Equals& e = m_data;
return e(k1, k2);
}
void assertContained(const value_type* v) const
{
CARB_UNUSED(v);
CARB_ASSERT(v >= m_data.m_table && v < (m_data.m_table + m_data.m_tableSize));
}
const size_t* _end() const noexcept
{
return m_data.m_hashes + m_data.m_tableSize;
}
value_type* _next(value_type* prev) const
{
assertContained(prev);
const size_t* e = m_data.m_hashes + (prev - m_data.m_table) + 1;
for (; e != _end(); ++e)
if (isHashValid(*e))
return m_data.m_table + (e - m_data.m_hashes);
return nullptr;
}
value_type* _findnext(value_type* prev) const
{
assertContained(prev);
size_t const h = m_data.m_hashes[(prev - m_data.m_table)];
CARB_ASSERT(isHashValid(h));
key_type const& key = KeyFromValue{}(*prev);
size_t const kMask = (m_data.m_tableSize - 1);
size_t const start = (h & kMask); // starting index of the search. If we get back to this point, we're done.
size_t index = ((prev - m_data.m_table) + 1) & kMask;
size_t dist = (index - start) & kMask;
for (; index != start; index = (index + 1) & kMask, ++dist)
{
size_t* e = m_data.m_hashes + index;
if (isEmpty(*e))
{
return nullptr;
}
if (*e == h && equals(KeyFromValue{}(m_data.m_table[index]), key))
{
return m_data.m_table + index;
}
size_t entryDist = (index - *e) & kMask;
if (dist > entryDist)
{
return nullptr;
}
}
return nullptr;
}
constexpr iterator make_iter(value_type* where) const noexcept
{
return iterator{ this, where };
}
std::pair<iterator, bool> insert_unique(const value_type& value)
{
auto result = internal_insert(KeyFromValue{}(value));
if (result.second)
new (result.first) value_type(value);
return std::make_pair(iterator{ this, result.first }, result.second);
}
std::pair<iterator, bool> insert_unique(value_type&& value)
{
auto result = internal_insert(KeyFromValue{}(value));
if (result.second)
new (result.first) value_type(std::move(value));
return std::make_pair(iterator{ this, result.first }, result.second);
}
iterator insert_multi(const value_type& value)
{
return { this, new (internal_insert_multi(KeyFromValue{}(value))) value_type(value) };
}
iterator insert_multi(value_type&& value)
{
return { this, new (internal_insert_multi(KeyFromValue{}(value))) value_type(std::move(value)) };
}
ncvalue_type* internal_insert_multi(const key_type& key)
{
if (((m_data.m_size) + 1) >= capacity())
{
reserve(m_data.m_size + 1);
}
CARB_ASSERT(m_data.m_size < m_data.m_tableSize);
size_t h = hash(key);
++m_data.m_size;
return internal_insert_multi2(h, key);
}
ncvalue_type* internal_insert_multi2(size_t h, const key_type& key)
{
size_t const kMask = (m_data.m_tableSize - 1);
size_t index = h & kMask;
size_t last = (index - 1) & kMask;
size_t dist = 0; // distance from desired slot
size_t* e;
for (;;)
{
e = m_data.m_hashes + index;
if (isEmpty(*e))
{
*e = h;
return m_data.m_table + index;
}
// Compute the distance of the existing item or deleted entry
size_t const existingDist = (index - *e) & kMask;
if (isDeleted(*e))
{
// The evicted item can only go into a deleted slot only if it's "fair": our distance-from-desired must
// be same or worse than the existing deleted item.
if (dist >= existingDist)
{
// We can take a deleted entry that meets or exceeds our desired distance
*e = h;
return m_data.m_table + (e - m_data.m_hashes);
}
}
else if (dist > existingDist)
{
// Our distance from desired now exceeds the current entry, so we'll take it and evict whatever was
// previously there. Proceed to the next phase to find a spot for the evicted entry.
dist = existingDist;
break;
}
if (CARB_UNLIKELY(index == last))
{
// We reached the end without finding a valid spot, but there are deleted entries in the table. So
// rebuild to remove all of the deleted entries and recursively call.
rebuild();
return internal_insert_multi2(h, key);
}
index = (index + 1) & kMask;
++dist;
}
// At this point, we have to evict an existing item in order to insert at a fair position. The slot that will
// contain our new entry is pointed at by `orig`. Our caller will be responsible for initializing the value_type
ncvalue_type* const orig = m_data.m_table + (e - m_data.m_hashes);
std::swap(*e, h);
ncvalue_type value(std::move(*orig));
orig->~value_type(); // caller will need to reconstruct.
// We are now taking the perspective of the evicted item. `h` is already the hash value for the evicted item, so
// recompute `last`. `dist` is already the distance from desired for the evicted item as well.
last = (h - 1) & kMask;
// Start with the following index as it is the first candidate for the evicted item.
index = (index + 1) & kMask;
++dist;
for (;;)
{
e = m_data.m_hashes + index;
if (isEmpty(*e))
{
// Found an empty slot that the evicted item can move into.
*e = h;
new (m_data.m_table + index) value_type(std::move(value));
return orig;
}
size_t existingDist = (index - *e) & kMask;
if (isDeleted(*e))
{
// The evicted item can only go into a deleted slot only if it's "fair": our distance-from-desired must
// be same or worse than the existing deleted item.
if (dist >= existingDist)
{
*e = h;
new (m_data.m_table + index) value_type(std::move(value));
return orig;
}
}
else if (dist > existingDist)
{
// For an existing item, we can swap it out with the previously evicted item if it is worse off than the
// item at this location. It becomes the new evicted item and we continue traversal until we find a
// suitable location for it.
std::swap(*e, h);
swapValue(value, m_data.m_table[e - m_data.m_hashes]);
dist = existingDist;
last = (h - 1) & kMask;
}
if (index == last)
{
// We're in a bad state. There are too many deleted items and we've walked the entire list trying to
// find a location. Do a rebuild to remove all the deleted entries and re-hash everything then call
// recursively.
std::swap(m_data.m_hashes[orig - m_data.m_table], h);
// Reconstruct the item at orig since it was previously deleted.
new (orig) value_type(std::move(value));
CARB_ASSERT(h == hash(key));
rebuild();
return internal_insert_multi2(h, key);
}
index = (index + 1) & kMask;
++dist;
}
}
std::pair<ncvalue_type*, bool> internal_insert(const key_type& key)
{
if ((m_data.m_size + 1) >= capacity())
{
reserve(m_data.m_size + 1);
}
CARB_ASSERT(m_data.m_size < m_data.m_tableSize);
size_t h = hash(key);
auto result = internal_insert2(h, key);
m_data.m_size += result.second;
return result;
}
std::pair<ncvalue_type*, bool> internal_insert2(size_t h, const key_type& key)
{
size_t const kMask = (m_data.m_tableSize - 1);
size_t index = h & kMask;
size_t last = (index - 1) & kMask;
size_t dist = 0; // distance from desired slot
size_t* firstDeletedSlot = nullptr;
size_t* e;
for (;;)
{
e = m_data.m_hashes + index;
if (isEmpty(*e))
{
*e = h;
return std::make_pair(m_data.m_table + index, true);
}
if (*e == h && equals(KeyFromValue{}(m_data.m_table[index]), key))
{
return std::make_pair(m_data.m_table + index, false);
}
// Compute the distance of the existing item or deleted entry
size_t const existingDist = (index - *e) & kMask;
if (dist > existingDist)
{
// Our distance from desired now exceeds the current entry, so we'll take it. If it's deleted, we can
// merely take it, but if something already exists there, we need to move it down the line.
if (!firstDeletedSlot && isDeleted(*e))
{
firstDeletedSlot = e;
}
if (firstDeletedSlot)
{
// If we found a deleted slot, we can go into it
*firstDeletedSlot = h;
return std::make_pair(m_data.m_table + (firstDeletedSlot - m_data.m_hashes), true);
}
if (CARB_UNLIKELY(index == last))
{
// We reached the end without finding a valid spot, but there are deleted entries in the table. So
// rebuild to remove all of the deleted entries and recursively call.
rebuild();
return internal_insert2(h, key);
}
// We break out and proceed to find a new location for the existing entry
dist = existingDist;
break;
}
else if (!firstDeletedSlot && dist == existingDist && isDeleted(*e))
{
firstDeletedSlot = e;
}
if (CARB_UNLIKELY(index == last))
{
// We reached the end without finding a valid spot. Rebuild to remove all deleted entries and call
// recursively.
rebuild();
return internal_insert2(h, key);
}
index = (index + 1) & kMask;
++dist;
}
// At this point, we guarantee that we need to insert and we had to evict an existing item. The slot that will
// contain our new entry is pointed at by `orig`. Our caller will be responsible for initializing the value_type
ncvalue_type* const orig = m_data.m_table + (e - m_data.m_hashes);
std::swap(*e, h);
ncvalue_type value(std::move(*orig));
orig->~value_type(); // caller will need to reconstruct.
// We are now taking the perspective of the evicted item. `h` is already the hash value for the evicted item, so
// recompute `last`. `dist` is already the distance from desired for the evicted item as well.
last = (h - 1) & kMask;
// Start with the following index as it is the first candidate for the evicted item.
index = (index + 1) & kMask;
++dist;
for (;;)
{
e = m_data.m_hashes + index;
if (isEmpty(*e))
{
// Found an empty slot that the evicted item can move into.
*e = h;
new (m_data.m_table + index) value_type(std::move(value));
return std::make_pair(orig, true);
}
size_t existingDist = (index - *e) & kMask;
if (isDeleted(*e))
{
// The evicted item can only go into a deleted slot only if it's "fair": our distance-from-desired must
// be same or worse than the existing deleted item.
if (dist >= existingDist)
{
*e = h;
new (m_data.m_table + index) value_type(std::move(value));
return std::make_pair(orig, true);
}
}
else if (dist > existingDist)
{
// For an existing item, we can swap it out with the previously evicted item if it is worse off than the
// item at this location. It becomes the new evicted item and we continue traversal until we find a
// suitable location for it.
std::swap(*e, h);
swapValue(value, m_data.m_table[e - m_data.m_hashes]);
dist = existingDist;
last = (h - 1) & kMask;
}
if (index == last)
{
// We're in a bad state. There are too many deleted items and we've walked the entire list trying to
// find a location. Do a rebuild to remove all the deleted entries and re-hash everything then call
// recursively.
std::swap(m_data.m_hashes[orig - m_data.m_table], h);
// Reconstruct the item at orig since it was previously deleted.
new (orig) value_type(std::move(value));
CARB_ASSERT(h == hash(key));
rebuild();
return internal_insert2(h, key);
}
index = (index + 1) & kMask;
++dist;
}
}
size_t internal_count_multi(const key_type& key) const
{
size_t count = 0;
for (auto vt = internal_find(key); vt; vt = _findnext(vt))
++count;
return count;
}
void internal_erase(value_type* value)
{
--m_data.m_size;
value->~value_type();
size_t index = value - m_data.m_table;
size_t* h = m_data.m_hashes + index;
// Set the deleted bit, but we retain most bits in the hash so that distance checks work properly.
*h |= kDeletedBit;
// If our next entry is kEmpty, then we can walk backwards and set everything to kEmpty. This will keep the
// table a bit cleaner of deleted entries.
size_t const kMask = m_data.m_tableSize - 1;
if (isEmpty(m_data.m_hashes[(index + 1) & kMask]))
{
do
{
*h = kEmpty;
index = (index - 1) & kMask;
h = m_data.m_hashes + index;
} while (isDeleted(*h));
}
}
value_type* internal_find(const key_type& key) const
{
if (CARB_UNLIKELY(empty()))
return nullptr;
size_t const h = hash(key);
size_t const kMask = size_t(m_data.m_tableSize - 1);
size_t index = h & kMask;
size_t dist = 0;
for (;;)
{
size_t* e = m_data.m_hashes + index;
if (isEmpty(*e))
return nullptr;
if (*e == h && equals(KeyFromValue{}(m_data.m_table[index]), key))
{
return m_data.m_table + index;
}
size_t entryDist = (index - *e) & kMask;
if (dist > entryDist)
return nullptr;
// We do not need to check against the last entry here because distance keeps increasing. Eventually it will
// be larger than the number of items in the map.
++dist;
index = (index + 1) & kMask;
}
}
static void swapValue(ncvalue_type& v1, ncvalue_type& v2) noexcept
{
// Cannot use std::swap because key is const, so work around it with move-construct/destruction
ncvalue_type temp{ std::move(v1) };
v1.~value_type();
new (&v1) ncvalue_type(std::move(v2));
v2.~value_type();
new (&v2) ncvalue_type(std::move(temp));
}
// Similar to rehash except that it keeps the same table size
void rebuild()
{
ncvalue_type* const oldtable = m_data.m_table;
size_t* const oldhashes = m_data.m_hashes;
size_t* const oldend = oldhashes + m_data.m_tableSize;
m_data.m_table =
static_cast<ncvalue_type*>(std::malloc(m_data.m_tableSize * (sizeof(ncvalue_type) + sizeof(size_t))));
m_data.m_hashes = reinterpret_cast<size_t*>(m_data.m_table + m_data.m_tableSize);
size_t* const end = m_data.m_hashes + m_data.m_tableSize;
for (size_t* e = m_data.m_hashes; e != end; ++e)
*e = kEmpty;
if (CARB_LIKELY(m_data.m_size != 0))
{
for (size_t* e = oldhashes; e != oldend; ++e)
{
if (isHashValid(*e))
{
auto result = internal_insert_multi2(*e, KeyFromValue{}(oldtable[e - oldhashes]));
new (result) ncvalue_type(std::move(oldtable[e - oldhashes]));
oldtable[e - oldhashes].~value_type();
}
}
}
std::free(oldtable);
}
#endif
private:
CARB_VIZ Data m_data;
};
/**
* ADL swap function. Swaps between two containers that have the same template parameters.
*
* @param lhs The first container
* @param rhs The second container.
*/
template <size_t LoadFactorMax100, class Key, class ValueType, class KeyFromValue, class Hasher, class Equals>
void swap(RobinHood<LoadFactorMax100, Key, ValueType, KeyFromValue, Hasher, Equals>& lhs,
RobinHood<LoadFactorMax100, Key, ValueType, KeyFromValue, Hasher, Equals>& rhs)
{
lhs.swap(rhs);
}
/**
* Equality operator. Checks for equality between two containers.
*
* @param lhs The first container.
* @param rhs The second container.
* @returns \c true if the containers are equal, that is, the second container is a permutation of the first.
*/
template <size_t LoadFactorMax100_1, size_t LoadFactorMax100_2, class Key, class ValueType, class KeyFromValue, class Hasher1, class Hasher2, class Equals>
bool operator==(const RobinHood<LoadFactorMax100_1, Key, ValueType, KeyFromValue, Hasher1, Equals>& lhs,
const RobinHood<LoadFactorMax100_2, Key, ValueType, KeyFromValue, Hasher2, Equals>& rhs)
{
Equals equals{};
return std::is_permutation(
lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), [&equals](const ValueType& l, const ValueType& r) {
KeyFromValue kfv{};
return equals(kfv(l), kfv(r));
});
}
/**
* Inequality operator. Checks for inequality between two containers.
*
* @param lhs The first container.
* @param rhs The second container.
* @returns \c true if the containers are not equal, that is, the second container is not a permutation of the first.
*/
template <size_t LoadFactorMax100_1, size_t LoadFactorMax100_2, class Key, class ValueType, class KeyFromValue, class Hasher1, class Hasher2, class Equals>
bool operator!=(const RobinHood<LoadFactorMax100_1, Key, ValueType, KeyFromValue, Hasher1, Equals>& lhs,
const RobinHood<LoadFactorMax100_2, Key, ValueType, KeyFromValue, Hasher2, Equals>& rhs)
{
return !(lhs == rhs);
}
} // namespace detail
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/LocklessQueue.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Defines the LocklessQueue class
#pragma once
#include "../Defines.h"
#include "../cpp/Atomic.h"
#include "../thread/Util.h"
#include <thread>
namespace carb
{
//! Carbonite container classes
namespace container
{
template <class T>
class LocklessQueueLink;
template <class T, LocklessQueueLink<T> T::*U>
class LocklessQueue;
/**
* Defines the link object. Each class contained by LocklessQueue must have a member of type LocklessQueueLink.
*/
template <class T>
class LocklessQueueLink
{
public:
/**
* Default constructor.
*/
constexpr LocklessQueueLink() = default;
CARB_PREVENT_COPY_AND_MOVE(LocklessQueueLink);
private:
CARB_VIZ std::atomic<T*> m_next;
friend T;
template <class U, LocklessQueueLink<U> U::*V>
friend class LocklessQueue;
};
/**
* @brief Implements a lockless queue: a FIFO queue that is thread-safe yet requires no kernel synchronization.
*
* LocklessQueue is designed to be easy-to-use. For a class `Foo` that you want to be contained in a LocklessQueue, it
* must have a member of type LocklessQueueLink<Foo>. This member is what the LocklessQueue will use for tracking data.
*
* Pushing to LocklessQueue is simply done through LocklessQueue::push(), which is entirely thread-safe.
* LocklessQueue ensures first-in-first-out (FIFO) for each producer pushing to LocklessQueue. Multiple producers
* may be pushing into LocklessQueue simultaneously, so their items can become mingled, but each producer's pushed
* items will be strongly ordered.
*
* Popping on the other hand is different for single-consumer vs. multiple-consumer. For
* single-consumer (via the LocklessQueue::popSC() function) only one thread may be popping from LocklessQueue at any
* given time. It is up to the caller to ensure this mutual exclusivity.
*
* If multiple-consumer is desired, use the LocklessQueue::popMC() function; it ensures additional
* thread safety and is therefore higher cost. Furthermore LocklessQueue::popMC() has a contention back-off
* capability that will attempt to solve high-contention situations with progressive spin and sleep if absolutely
* necessary.
*
* Simple example:
* ```cpp
* class Foo
* {
* public:
* LocklessQueueLink<Foo> m_link;
* };
*
* LocklessQueue<Foo, &Foo::m_link> queue;
* queue.push(new Foo);
* Foo* p = queue.popSC();
* delete p;
* ```
*
* @thread_safety LocklessQueue is entirely thread-safe except where declared otherwise. No allocation happens with a
* LocklessQueue; instead the caller is responsible for construction/destruction of contained objects.
*
* @tparam T The type to contain.
* @tparam U A pointer-to-member of a LocklessQueueLink member within T (see above example).
*/
template <class T, LocklessQueueLink<T> T::*U>
class CARB_VIZ LocklessQueue
{
public:
/**
* Constructs a new LocklessQueue.
*/
constexpr LocklessQueue() : m_head(nullptr), m_tail(nullptr)
{
}
CARB_PREVENT_COPY(LocklessQueue);
/**
* LocklessQueue is partially movable in that it can be move-constructed from another LocklessQueue, but cannot be
* move-assigned. This is to guarantee that the state of the receiving LocklessQueue is a fresh state.
*/
LocklessQueue(LocklessQueue&& rhs) : m_head(nullptr), m_tail(nullptr)
{
this->steal(rhs);
}
/**
* Cannot move-assign, only move-construct. This is to guarantee the state of the receiving LocklessQueue is a fresh
* state.
*/
LocklessQueue& operator=(LocklessQueue&&) = delete;
/**
* Destructor.
*
* @warning Asserts that isEmpty() returns `true`.
*/
~LocklessQueue()
{
// Not good to destroy when not empty
CARB_ASSERT(isEmpty());
}
/**
* Indicates whether the queue is empty.
*
* @warning Another thread may have modified the LocklessQueue before this function returns.
*
* @returns `true` if the queue appears empty; `false` if items appear to exist in the queue.
*/
bool isEmpty() const
{
// Reading the tail is more efficient because much contention can happen on m_head
return !m_tail.load(std::memory_order_relaxed);
}
/**
* Pushes an entry onto the LocklessQueue.
*
* @param p The item to push into the queue.
*
* @returns `true` if the queue was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
bool push(T* p)
{
// Make sure the node isn't already pointing at something
next(p).store(nullptr, std::memory_order_relaxed);
return _push(p, p);
}
/**
* Pushes a contiguous block of entries from [ @p begin, @p end) onto the queue.
*
* @note All of the entries are guaranteed to remain strongly ordered and will not be interspersed with entries from
* other threads.
*
* @param begin An <a href="https://en.cppreference.com/w/cpp/named_req/InputIterator">InputIterator</a> of the
* first item to push. `*begin` must resolve to a `T&`.
* @param end An off-the-end InputIterator after the last item to push.
* @returns true if the queue was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
#ifndef DOXYGEN_BUILD
template <class InputItRef,
std::enable_if_t<std::is_convertible<decltype(std::declval<InputItRef&>()++, *std::declval<InputItRef&>()), T&>::value,
bool> = false>
#else
template <class InputItRef>
#endif
bool push(InputItRef begin, InputItRef end)
{
// Handle empty list
if (begin == end)
return false;
// Walk through iterators and have them point to each other
InputItRef last = begin;
InputItRef iter = begin;
iter++;
for (; iter != end; last = iter++)
{
next(std::addressof(*last)).store(std::addressof(*iter), std::memory_order_relaxed);
}
next(std::addressof(*last)).store(nullptr, std::memory_order_relaxed);
return _push(std::addressof(*begin), std::addressof(*last));
}
/**
* Pushes a block of pointers-to-entries from [ @p begin, @p end) onto the queue.
*
* @note All of the entries are guaranteed to remain strongly ordered and will not be interspersed with entries from
* other threads.
*
* @param begin An <a href="https://en.cppreference.com/w/cpp/named_req/InputIterator">InputIterator</a> of the
* first item to push. `*begin` must resolve to a `T*`.
* @param end An off-the-end InputIterator after the last item to push.
* @returns true if the queue was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
#ifndef DOXYGEN_BUILD
template <class InputItPtr,
std::enable_if_t<std::is_convertible<decltype(std::declval<InputItPtr&>()++, *std::declval<InputItPtr&>()), T*>::value,
bool> = true>
#else
template <class InputItPtr>
#endif
bool push(InputItPtr begin, InputItPtr end)
{
// Handle empty list
if (begin == end)
return false;
// Walk through iterators and have them point to each other
InputItPtr last = begin;
InputItPtr iter = begin;
iter++;
for (; iter != end; last = iter++)
{
next(*last).store(*iter, std::memory_order_relaxed);
}
next(*last).store(nullptr, std::memory_order_relaxed);
return _push(*begin, *last);
}
/**
* Ejects all entries from this queue as a new LocklessQueue.
*
* @note To clear all items use popAll().
*/
CARB_NODISCARD LocklessQueue eject()
{
return LocklessQueue(std::move(*this));
}
/**
* Atomically steals all entries from another LocklessQueue and adds them to *this.
*
* Effectively pops everything from \p rhs and then pushes everything to \c *this. This can be done in two steps
* though since everything is already linked together: first the head/tail of \p rhs are exchanged with \c nullptr
* in a multi-consumer manner, then since everything is already linked together they can be pushed as one group onto
* the end of \c *this. Therefore, this is much quicker than a loop that pops from one queue and pushes to another.
* @param rhs A LocklessQueue to atomically steal all entries from.
*/
void steal(LocklessQueue& rhs)
{
static T* const mediator = reinterpret_cast<T*>(size_t(-1));
// Need to pop everything from rhs, so this is similar to popAll()
T* head;
for (;;)
{
// The mediator acts as both a lock and a signal
head = rhs.m_head.exchange(mediator, std::memory_order_relaxed);
if (CARB_UNLIKELY(!head))
{
// The first xchg on the tail will tell the enqueuing thread that it is safe to blindly write out to the
// head pointer. A cmpxchg honors the algorithm.
T* m = mediator;
if (CARB_UNLIKELY(!rhs.m_head.compare_exchange_strong(
m, nullptr, std::memory_order_relaxed, std::memory_order_relaxed)))
{
// Couldn't write a nullptr back. Try again.
continue;
}
if (CARB_UNLIKELY(!!rhs.m_tail.load(std::memory_order_relaxed)))
{
bool isNull;
// Wait for consistency
this_thread::spinWaitWithBackoff([&] { return rhs.consistent(isNull); });
if (!isNull)
{
// Try again.
continue;
}
}
// Nothing on the queue.
return;
}
if (CARB_UNLIKELY(head == mediator))
{
// Another thread is in a pop function. Wait until m_head is no longer the mediator.
this_thread::spinWaitWithBackoff([&] { return rhs.mediated(); });
// Try again.
continue;
}
break;
}
// Release our lock and swap with the tail
rhs.m_head.store(nullptr, std::memory_order_release);
T* end = rhs.m_tail.exchange(nullptr, std::memory_order_release);
// Push onto *this
_push(head, end);
}
/**
* Empties the queue.
*
* @note To perform an action on each item as it is popped, use forEach() instead.
*/
void popAll()
{
static T* const mediator = reinterpret_cast<T*>(size_t(-1));
T* head;
for (;;)
{
// The mediator acts as both a lock and a signal
head = m_head.exchange(mediator, std::memory_order_relaxed);
if (CARB_UNLIKELY(!head))
{
// The first xchg on the tail will tell the enqueuing thread that it is safe to blindly write out to the
// head pointer. A cmpxchg honors the algorithm.
T* m = mediator;
if (CARB_UNLIKELY(!m_head.compare_exchange_strong(
m, nullptr, std::memory_order_relaxed, std::memory_order_relaxed)))
{
// Couldn't write a nullptr back. Try again.
continue;
}
if (CARB_UNLIKELY(!!m_tail.load(std::memory_order_relaxed)))
{
bool isNull;
// Wait for consistency
this_thread::spinWaitWithBackoff([&] { return this->consistent(isNull); });
if (!isNull)
{
// Try again.
continue;
}
}
// Nothing on the queue.
return;
}
if (CARB_UNLIKELY(head == mediator))
{
// Another thread is in a pop function. Wait until m_head is no longer the mediator.
this_thread::spinWaitWithBackoff([&] { return this->mediated(); });
// Try again.
continue;
}
break;
}
// Release our lock and swap with the tail
m_head.store(nullptr, std::memory_order_release);
m_tail.exchange(nullptr, std::memory_order_release);
}
/**
* Pops all available items from the queue calling a functionish object on each.
*
* First, pops all available items from `*this` and then calls @p f on each.
*
* @note As the pop is the first thing that happens, any new entries that get pushed while the function is executing
* will NOT be popped and will remain in LocklessQueue when this function returns.
*
* @param f A functionish object that accepts a `T*` parameter. Called for each item that was popped from the queue.
*/
template <class Func>
void forEach(Func&& f)
{
static T* const mediator = reinterpret_cast<T*>(size_t(-1));
T* head;
for (;;)
{
// The mediator acts as both a lock and a signal
head = m_head.exchange(mediator, std::memory_order_relaxed);
if (CARB_UNLIKELY(!head))
{
// The first xchg on the tail will tell the enqueuing thread that it is safe to blindly write out to the
// head pointer. A cmpxchg honors the algorithm.
T* m = mediator;
if (CARB_UNLIKELY(!m_head.compare_exchange_strong(
m, nullptr, std::memory_order_relaxed, std::memory_order_relaxed)))
{
// Couldn't write a nullptr back. Try again.
continue;
}
if (CARB_UNLIKELY(!!m_tail.load(std::memory_order_relaxed)))
{
bool isNull;
// Wait for consistency
this_thread::spinWaitWithBackoff([&] { return this->consistent(isNull); });
if (!isNull)
{
// Try again.
continue;
}
}
// Nothing on the queue.
return;
}
if (CARB_UNLIKELY(head == mediator))
{
// Another thread is in a pop function. Wait until m_head is no longer the mediator.
this_thread::spinWaitWithBackoff([&] { return this->mediated(); });
// Try again.
continue;
}
break;
}
// Release our lock and swap with the tail
m_head.store(nullptr, std::memory_order_release);
T* e = m_tail.exchange(nullptr, std::memory_order_release);
for (T *p = head, *n; p; p = n)
{
// Ensure that we have a next item (except for `e`; the end of the queue). It's possible
// that a thread is in `push()` and has written the tail at the time of exchange, above,
// but has not yet written the previous item's next pointer.
n = next(p).load(std::memory_order_relaxed);
if (CARB_UNLIKELY(!n && p != e))
n = waitForEnqueue(next(p));
f(p);
}
}
/**
* Pop first entry (Single-consumer).
*
* @thread_safety May only be done in a single thread and is mutually exclusive with all other functions that modify
* LocklessQueue *except* push(). Use popMC() for a thread-safe pop function.
*
* @warning Debug builds will assert if a thread safety issue is detected.
*
* @returns the first item removed from the queue, or `nullptr` if the queue is empty.
*/
T* popSC()
{
#if CARB_ASSERT_ENABLED
// For debug builds, swap with a mediator to ensure that another thread is not in this function
static T* const mediator = reinterpret_cast<T*>(size_t(-1));
T* h = m_head.exchange(mediator, std::memory_order_acquire);
CARB_ASSERT(
h != mediator, "LocklessQueue: Another thread is racing with popSC(). Use popMC() for multi-consumer.");
while (CARB_UNLIKELY(!h))
{
h = m_head.exchange(nullptr, std::memory_order_release);
if (h == mediator)
{
// We successfully swapped a nullptr for the mediator we put there.
return nullptr;
}
// Another thread in push() could've put something else here, so check it again.
}
#else
// If head is null the queue is empty
T* h = m_head.load(std::memory_order_acquire);
if (CARB_UNLIKELY(!h))
{
return nullptr;
}
#endif
// Load the next item and store into the head
T* n = next(h).load(std::memory_order_acquire);
m_head.store(n, std::memory_order_relaxed);
T* e = h;
if (CARB_UNLIKELY(!n && !m_tail.compare_exchange_strong(
e, nullptr, std::memory_order_release, std::memory_order_relaxed)))
{
// The next item was null, but we failed to write null to the tail, so another thread must have added
// something. Read the next value from `h` and store it in the _head.
n = next(h).load(std::memory_order_acquire);
if (CARB_UNLIKELY(!n))
n = waitForEnqueue(next(h));
m_head.store(n, std::memory_order_relaxed);
}
// This isn't really necessary but prevents dangling pointers.
next(h).store(nullptr, std::memory_order_relaxed);
return h;
}
/**
* Pop first entry (Multiple-consumer).
*
* @ref popSC() is the single-consumer variant of this function and performs better in a single-consumer
* environment.
* @note In a highly-contentious situation, this function will back off and attempt to sleep in order to resolve the
* contention.
*
* @returns the first item removed from the queue, or `nullptr` if the queue is empty.
*/
T* popMC()
{
static T* const mediator = reinterpret_cast<T*>(size_t(-1));
T* head;
for (;;)
{
// The mediator acts as both a lock and a signal
head = m_head.exchange(mediator, std::memory_order_relaxed);
if (CARB_UNLIKELY(!head))
{
// The first xchg on the tail will tell the enqueuing thread that it is safe to blindly write out to the
// head pointer. A cmpxchg honors the algorithm.
T* m = mediator;
if (CARB_UNLIKELY(!m_head.compare_exchange_strong(
m, nullptr, std::memory_order_relaxed, std::memory_order_relaxed)))
{
// Couldn't write a nullptr back. Try again.
continue;
}
if (CARB_UNLIKELY(!!m_tail.load(std::memory_order_relaxed)))
{
bool isNull;
// Wait for consistency
this_thread::spinWaitWithBackoff([&] { return this->consistent(isNull); });
if (!isNull)
{
// Try again.
continue;
}
}
// Nothing on the queue.
return nullptr;
}
if (CARB_UNLIKELY(head == mediator))
{
// Another thread is in a pop function. Wait until m_head is no longer the mediator.
this_thread::spinWaitWithBackoff([&] { return this->mediated(); });
// Try again.
continue;
}
break;
}
// Restore the head pointer to a sane value before returning.
// If 'next' is nullptr, then this item _might_ be the last item.
T* n = next(head).load(std::memory_order_relaxed);
if (CARB_UNLIKELY(!n))
{
m_head.store(nullptr, std::memory_order_relaxed);
// Try to clear the tail to ensure the queue is now empty.
T* h = head;
if (m_tail.compare_exchange_strong(h, nullptr, std::memory_order_release, std::memory_order_relaxed))
{
// Both head and tail are nullptr now.
// Clear head's next pointer so that it's not dangling
next(head).store(nullptr, std::memory_order_relaxed);
return head;
}
// There must be a next item now.
n = next(head).load(std::memory_order_acquire);
if (CARB_UNLIKELY(!n))
n = waitForEnqueue(next(head));
}
m_head.store(n, std::memory_order_relaxed);
// Clear head's next pointer so that it's not dangling
next(head).store(nullptr, std::memory_order_relaxed);
return head;
}
//! @copydoc popMC()
T* pop()
{
return popMC();
}
/**
* Pushes an item onto the queue and notifies a waiting listener.
*
* Equivalent to doing `auto b = push(p); notifyOne(); return b;`.
*
* @see push(), notifyOne()
*
* @param p The item to push.
* @returns `true` if LocklessQueue was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
bool pushNotify(T* p)
{
bool b = push(p);
notifyOne();
return b;
}
/**
* Blocks the calling thread until an item is available and returns it (Single-consumer).
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @thread_safety May only be done in a single thread and is mutually exclusive with all other functions that modify
* LocklessQueue *except* push(). Use popMC() for a thread-safe pop function.
*
* @warning Debug builds will assert if a thread safety issue is detected.
*
* @see popSC(), wait()
*
* @returns The first item popped from the queue.
*/
T* popSCWait()
{
T* p = popSC();
while (!p)
{
wait();
p = popSC();
}
return p;
}
/**
* Blocks the calling thread until an item is available and returns it (Single-consumer) or a timeout elapses.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @thread_safety May only be done in a single thread and is mutually exclusive with all other functions that modify
* LocklessQueue *except* push(). Use popMC() for a thread-safe pop function.
*
* @warning Debug builds will assert if a thread safety issue is detected.
*
* @see popSC(), waitFor()
*
* @param dur The duration to wait for an item to become available.
* @returns The first item popped from the queue or `nullptr` if the timeout period elapses.
*/
template <class Rep, class Period>
T* popSCWaitFor(const std::chrono::duration<Rep, Period>& dur)
{
return popSCWaitUntil(std::chrono::steady_clock::now() + dur);
}
/**
* Blocks the calling thread until an item is available and returns it (Single-consumer) or the clock reaches a time
* point.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @thread_safety May only be done in a single thread and is mutually exclusive with all other functions that modify
* LocklessQueue *except* push(). Use popMC() for a thread-safe pop function.
*
* @warning Debug builds will assert if a thread safety issue is detected.
*
* @see popSC(), waitUntil()
*
* @param tp The time to wait until for an item to become available.
* @returns The first item popped from the queue or `nullptr` if the timeout period elapses.
*/
template <class Clock, class Duration>
T* popSCWaitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
T* p = popSC();
while (!p)
{
if (!waitUntil(tp))
{
return popSC();
}
p = popSC();
}
return p;
}
/**
* Blocks the calling thread until an item is available and returns it (Multiple-consumer).
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @note In a highly-contentious situation, this function will back off and attempt to sleep in order to resolve the
* contention.
*
* @see popMC(), wait()
*
* @returns the first item removed from the queue.
*/
T* popMCWait()
{
T* p = popMC();
while (!p)
{
wait();
p = popMC();
}
return p;
}
/**
* Blocks the calling thread until an item is available and returns it (Multiple-consumer) or a timeout elapses.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @note In a highly-contentious situation, this function will back off and attempt to sleep in order to resolve the
* contention.
*
* @see popMC(), waitFor()
*
* @param dur The duration to wait for an item to become available.
* @returns the first item removed from the queue or `nullptr` if the timeout period elapses.
*/
template <class Rep, class Period>
T* popMCWaitFor(const std::chrono::duration<Rep, Period>& dur)
{
return popMCWaitUntil(std::chrono::steady_clock::now() + dur);
}
/**
* Blocks the calling thread until an item is available and returns it (Multiple-consumer) or the clock reaches a
* time point.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @note In a highly-contentious situation, this function will back off and attempt to sleep in order to resolve the
* contention.
*
* @see popMC(), waitUntil()
*
* @param tp The time to wait until for an item to become available.
* @returns the first item removed from the queue or `nullptr` if the timeout period elapses.
*/
template <class Clock, class Duration>
T* popMCWaitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
T* p = popMC();
while (!p)
{
if (!waitUntil(tp))
{
return popMC();
}
p = popMC();
}
return p;
}
/**
* Waits until the queue is non-empty.
*
* @note Requires notification that the queue is non-empty, such as from pushNotify(), notifyOne() or notifyAll().
*
* @note Though wait() returns, another thread may have popped the available item making the queue empty again. Use
* popSCWait() / popMCWait() if it is desired to ensure that the current thread can obtain an item.
*/
void wait()
{
m_tail.wait(nullptr, std::memory_order_relaxed);
}
/**
* Waits until LocklessQueue is non-empty or a specified duration has passed.
*
* @note Though waitFor() returns `true`, another thread may have popped the available item making the queue empty
* again. Use popSCWaitFor() / popMCWaitFor() if it is desired to ensure that the current thread can obtain an item.
*
* @note Requires notification that the queue is non-empty, such as from pushNotify(), notifyOne() or notifyAll().
*
* @param dur The duration to wait for an item to become available.
* @returns `true` if an item appears to be available; `false` if the timeout elapses.
*/
template <class Rep, class Period>
bool waitFor(const std::chrono::duration<Rep, Period>& dur)
{
return m_tail.wait_for(nullptr, dur, std::memory_order_relaxed);
}
/**
* Waits until LocklessQueue is non-empty or a specific time is reached.
*
* @note Though waitUntil() returns `true`, another thread may have popped the available item making the queue empty
* again. Use popSCWaitUntil() / popMCWaitUntil() if it is desired to ensure that the current thread can obtain an
* item.
*
* @note Requires notification that the queue is non-empty, such as from pushNotify(), notifyOne() or notifyAll().
*
* @param tp The time to wait until for an item to become available.
* @returns `true` if an item appears to be available; `false` if the time is reached.
*/
template <class Clock, class Duration>
bool waitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
return m_tail.wait_until(nullptr, tp, std::memory_order_relaxed);
}
/**
* Notifies a single waiting thread.
*
* Notifies a single thread waiting in wait(), waitFor(), waitUntil(), popSCWait(), popMCWait(), popSCWaitFor(),
* popMCWaitFor(), popSCWaitUntil(), or popMCWaitUntil() to wake and check the queue.
*/
void notifyOne()
{
m_tail.notify_one();
}
/**
* Notifies all waiting threads.
*
* Notifies all threads waiting in wait(), waitFor(), waitUntil(), popSCWait(), popMCWait(), popSCWaitFor(),
* popMCWaitFor(), popSCWaitUntil(), or popMCWaitUntil() to wake and check the queue.
*/
void notifyAll()
{
m_tail.notify_all();
}
private:
CARB_VIZ cpp::atomic<T*> m_head;
CARB_VIZ cpp::atomic<T*> m_tail;
constexpr static unsigned kWaitSpins = 1024;
bool _push(T* first, T* last)
{
// Swap the tail with our new last item
T* token = m_tail.exchange(last, std::memory_order_release);
CARB_ASSERT(token != last);
if (CARB_LIKELY(token))
{
// The previous tail item now points to our new first item.
next(token).store(first, std::memory_order_relaxed);
return false;
}
else
{
// Queue was empty; head points to our first item
m_head.store(first, std::memory_order_relaxed);
return true;
}
}
// This function name breaks naming paradigms so that it shows up prominently in stack traces.
CARB_NOINLINE T* __WAIT_FOR_ENQUEUE__(std::atomic<T*>& ptr)
{
T* val;
int spins = 0;
while ((val = ptr.load(std::memory_order_relaxed)) == nullptr)
{
spins++;
CARB_UNUSED(spins);
std::this_thread::yield();
}
return val;
}
T* waitForEnqueue(std::atomic<T*>& ptr)
{
unsigned spins = kWaitSpins;
T* val;
while (CARB_UNLIKELY(spins-- > 0))
{
if (CARB_LIKELY((val = ptr.load(std::memory_order_relaxed)) != nullptr))
return val;
CARB_HARDWARE_PAUSE();
}
return __WAIT_FOR_ENQUEUE__(ptr);
}
// Predicate: returns `false` until m_head and m_tail are both null or non-null
bool consistent(bool& isNull) const
{
T* h = m_head.load(std::memory_order_relaxed);
T* t = m_tail.load(std::memory_order_relaxed);
isNull = !t;
return !h == !t;
}
// Predicate: returns Ready when _head is no longer the mediator
bool mediated() const
{
static T* const mediator = reinterpret_cast<T*>(size_t(-1));
return m_head.load(std::memory_order_relaxed) != mediator;
}
static std::atomic<T*>& next(T* p)
{
return (p->*U).m_next;
}
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/RHUnorderedMultiset.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite Robin-hood Unordered Multi-set container.
#pragma once
#include "RobinHoodImpl.h"
namespace carb
{
namespace container
{
/**
* Implements an Unordered Multimap, that is: a container that contains a set of keys where keys may be inserted
* multiple times, each creating a new element. There is no defined order to the set of keys.
*
* \copydetails detail::RobinHood
*
* @warning This container is similar to, but not a drop-in replacement for `std::unordered_multiset` due to differences
* in iterator invalidation and memory layout.
*
* Iterator/reference/pointer invalidation (note differences from `std::unordered_multiset`):
* Operation | Invalidates
* --------- | -----------
* All read operations | Never
* `clear`, `rehash`, `reserve`, `operator=`, `insert`, `emplace` | Always
* `erase` | Only the element removed
* `swap` | All iterators, no pointers/references
*
* @tparam Key The key type
* @tparam Hasher A functor to use as a hashing function for \c Key
* @tparam Equals A functor to use to compare two \c Key values for equality
* @tparam LoadFactorMax100 The load factor to use for the table. This value must be in the range `[10, 100]` and
* represents the percentage of entries in the hash table that will be filled before resizing. Open-addressing hash maps
* with 100% usage have better memory usage but worse performance since they need "gaps" in the hash table to terminate
* runs.
*/
template <class Key, class Hasher = std::hash<Key>, class Equals = std::equal_to<Key>, size_t LoadFactorMax100 = 80>
class RHUnorderedMultiset
: public detail::RobinHood<LoadFactorMax100, Key, const Key, detail::Identity<Key, const Key>, Hasher, Equals>
{
using Base = detail::RobinHood<LoadFactorMax100, Key, const Key, detail::Identity<Key, const Key>, Hasher, Equals>;
public:
//! The key type
using key_type = typename Base::key_type;
//! The value type (effectively `const key_type`)
using value_type = typename Base::value_type;
//! Unsigned integer type (typically \c size_t)
using size_type = typename Base::size_type;
//! Signed integer type (typically \c ptrdiff_t)
using difference_type = typename Base::difference_type;
//! The hash function
using hasher = typename Base::hasher;
//! The key-equals function
using key_equal = typename Base::key_equal;
//! \c value_type&
using reference = typename Base::reference;
//! `const value_type&`
using const_reference = typename Base::const_reference;
//! \c value_type*
using pointer = typename Base::pointer;
//! `const value_type*`
using const_pointer = typename Base::const_pointer;
//! A \a LegacyForwardIterator to \c value_type
using iterator = typename Base::iterator;
//! A \a LegacyForwardIterator to `const value_type`
using const_iterator = typename Base::const_iterator;
//! A \a LegacyForwardIterator to \c value_type that proceeds to the next matching key when incremented.
using find_iterator = typename Base::find_iterator;
//! A \a LegacyForwardIterator to `const value_type` that proceeds to the next matching key when incremented.
using const_find_iterator = typename Base::const_find_iterator;
/**
* Constructs empty container.
*/
constexpr RHUnorderedMultiset() noexcept = default;
/**
* Copy constructor. Copies elements from another container.
*
* @note \c *this may have a different \ref capacity() than \p other.
* @param other The other container to copy entries from.
*/
RHUnorderedMultiset(const RHUnorderedMultiset& other) : Base(other)
{
}
/**
* Move constructor. Moves elements from another container.
*
* @note No move constructors on contained elements are invoked. \p other will be empty() after this operation.
* @param other The other container to move entries from.
*/
RHUnorderedMultiset(RHUnorderedMultiset&& other) : Base(std::move(other))
{
}
/**
* Destructor. Destroys all contained elements and frees memory.
*/
~RHUnorderedMultiset() = default;
/**
* Copy-assign operator. Destroys all currently stored elements and copies elements from another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedMultiset& operator=(const RHUnorderedMultiset& other)
{
Base::operator=(other);
return *this;
}
/**
* Move-assign operator. Effectively swaps with another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedMultiset& operator=(RHUnorderedMultiset&& other)
{
Base::operator=(std::move(other));
return *this;
}
/**
* Inserts an element into the container.
*
* All iterators, references and pointers are invalidated.
*
* @param value The value to insert by copying.
* @returns an \c iterator to the inserted element.
*/
iterator insert(const value_type& value)
{
return this->insert_multi(value);
}
/**
* Inserts an element into the container.
*
* All iterators, references and pointers are invalidated.
*
* @param value The value to insert by moving.
* @returns an \c iterator to the inserted element.
*/
iterator insert(value_type&& value)
{
return this->insert_multi(std::move(value));
}
/**
* Inserts an element into the container. Only participates in overload resolution if
* `std::is_constructible_v<value_type, P&&>` is true.
*
* All iterators, references and pointers are invalidated.
*
* @param value The value to insert by constructing via `std::forward<P>(value)`.
* @returns an \c iterator to the inserted element.
*/
template <class P>
iterator insert(std::enable_if_t<std::is_constructible<value_type, P&&>::value, P&&> value)
{
return insert(value_type{ std::forward<P>(value) });
}
/**
* Constructs an element in-place.
*
* All iterators, references and pointers are invalidated.
*
* @param args The arguments to pass to the \c value_type constructor.
* @returns an \c iterator to the inserted element.
*/
template <class... Args>
iterator emplace(Args&&... args)
{
// The value is the key, so just construct the item here
return insert(value_type{ std::forward<Args>(args)... });
}
/**
* Removes elements with the given key.
*
* References, pointers and iterators to the erase element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param key the key value of elements to remove
* @returns the number of elements removed.
*/
size_type erase(const key_type& key)
{
size_t count = 0;
auto vt = this->internal_find(key);
decltype(vt) next;
for (; vt; vt = next)
{
next = this->_findnext(vt);
this->internal_erase(vt);
++count;
}
return count;
}
/**
* Returns the number of elements matching the specified key.
*
* @param key The key to check for.
* @returns The number of elements with the given key.
*/
size_t count(const key_type& key) const
{
return this->internal_count_multi(key);
}
#ifndef DOXYGEN_BUILD
using Base::begin;
using Base::cbegin;
using Base::cend;
using Base::end;
using Base::capacity;
using Base::empty;
using Base::max_size;
using Base::size;
using Base::clear;
using Base::erase;
using Base::swap;
using Base::contains;
using Base::equal_range;
using Base::find;
using Base::rehash;
using Base::reserve;
#endif
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/RHUnorderedMultimap.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite Robin-hood Unordered Multi-map container.
#pragma once
#include "RobinHoodImpl.h"
namespace carb
{
namespace container
{
/**
* Implements an Unordered Multimap, that is: a container that contains a mapping of keys to values where keys may be
* inserted multiple times, each creating a new element. There is no defined order to the set of keys.
*
* \copydetails detail::RobinHood
*
* @warning This container is similar to, but not a drop-in replacement for `std::unordered_multimap` due to differences
* in iterator invalidation and memory layout.
*
* Iterator/reference/pointer invalidation (note differences from `std::unordered_multimap`):
* Operation | Invalidates
* --------- | -----------
* All read operations | Never
* `clear`, `rehash`, `reserve`, `operator=`, `insert`, `emplace` | Always
* `erase` | Only the element removed
* `swap` | All iterators, no pointers/references
*
* @tparam Key The key type
* @tparam Value The mapped type to be associated with `Key`
* @tparam Hasher A functor to use as a hashing function for \c Key
* @tparam Equals A functor to use to compare two \c Key values for equality
* @tparam LoadFactorMax100 The load factor to use for the table. This value must be in the range `[10, 100]` and
* represents the percentage of entries in the hash table that will be filled before resizing. Open-addressing hash maps
* with 100% usage have better memory usage but worse performance since they need "gaps" in the hash table to terminate
* runs.
*/
template <class Key, class Value, class Hasher = std::hash<Key>, class Equals = std::equal_to<Key>, size_t LoadFactorMax100 = 80>
class RHUnorderedMultimap
: public detail::
RobinHood<LoadFactorMax100, Key, std::pair<const Key, Value>, detail::Select1st<Key, std::pair<const Key, Value>>, Hasher, Equals>
{
using Base = detail::
RobinHood<LoadFactorMax100, Key, std::pair<const Key, Value>, detail::Select1st<Key, std::pair<const Key, Value>>, Hasher, Equals>;
public:
//! The key type
using key_type = typename Base::key_type;
//! The mapped value type
using mapped_type = Value;
//! The value type (effectively `std::pair<const key_type, mapped_type>`)
using value_type = typename Base::value_type;
//! Unsigned integer type (typically \c size_t)
using size_type = typename Base::size_type;
//! Signed integer type (typically \c ptrdiff_t)
using difference_type = typename Base::difference_type;
//! The hash function
using hasher = typename Base::hasher;
//! The key-equals function
using key_equal = typename Base::key_equal;
//! \c value_type&
using reference = typename Base::reference;
//! `const value_type&`
using const_reference = typename Base::const_reference;
//! \c value_type*
using pointer = typename Base::pointer;
//! `const value_type*`
using const_pointer = typename Base::const_pointer;
//! A \a LegacyForwardIterator to \c value_type
using iterator = typename Base::iterator;
//! A \a LegacyForwardIterator to `const value_type`
using const_iterator = typename Base::const_iterator;
//! A \a LegacyForwardIterator to \c value_type that proceeds to the next matching key when incremented.
using find_iterator = typename Base::find_iterator;
//! A \a LegacyForwardIterator to `const value_type` that proceeds to the next matching key when incremented.
using const_find_iterator = typename Base::const_find_iterator;
/**
* Constructs empty container.
*/
constexpr RHUnorderedMultimap() noexcept = default;
/**
* Copy constructor. Copies elements from another container.
*
* @note \c *this may have a different \ref carb::container::detail::RobinHood::capacity() than \p other.
* @param other The other container to copy entries from.
*/
RHUnorderedMultimap(const RHUnorderedMultimap& other) : Base(other)
{
}
/**
* Move constructor. Moves elements from another container.
*
* @note No move constructors on contained elements are invoked. \p other will be
* \ref carb::container::detail::RobinHood::empty() after this operation.
* @param other The other container to move entries from.
*/
RHUnorderedMultimap(RHUnorderedMultimap&& other) : Base(std::move(other))
{
}
/**
* Destructor. Destroys all contained elements and frees memory.
*/
~RHUnorderedMultimap() = default;
/**
* Copy-assign operator. Destroys all currently stored elements and copies elements from another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedMultimap& operator=(const RHUnorderedMultimap& other)
{
Base::operator=(other);
return *this;
}
/**
* Move-assign operator. Effectively swaps with another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedMultimap& operator=(RHUnorderedMultimap&& other)
{
Base::operator=(std::move(other));
return *this;
}
/**
* Inserts an element into the container.
*
* All iterators, references and pointers are invalidated.
*
* @param value The value to insert by copying.
* @returns an \c iterator to the inserted element.
*/
iterator insert(const value_type& value)
{
return this->insert_multi(value);
}
/**
* Inserts an element into the container.
*
* All iterators, references and pointers are invalidated.
*
* @param value The value to insert by moving.
* @returns an \c iterator to the inserted element.
*/
iterator insert(value_type&& value)
{
return this->insert_multi(std::move(value));
}
/**
* Inserts an element into the container. Only participates in overload resolution if
* `std::is_constructible_v<value_type, P&&>` is true.
*
* All iterators, references and pointers are invalidated.
*
* @param value The value to insert by constructing via `std::forward<P>(value)`.
* @returns an \c iterator to the inserted element.
*/
template <class P>
iterator insert(std::enable_if_t<std::is_constructible<value_type, P&&>::value, P&&> value)
{
return insert(value_type{ std::forward<P>(value) });
}
/**
* Constructs an element in-place.
*
* All iterators, references and pointers are invalidated.
*
* @param args The arguments to pass to the \c value_type constructor.
* @returns an \c iterator to the inserted element.
*/
template <class... Args>
iterator emplace(Args&&... args)
{
// We need the key, so just construct the item here
return insert(value_type{ std::forward<Args>(args)... });
}
/**
* Removes elements with the given key.
*
* References, pointers and iterators to the erase element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param key the key value of elements to remove
* @returns the number of elements removed.
*/
size_type erase(const key_type& key)
{
size_t count = 0;
auto vt = this->internal_find(key);
decltype(vt) next;
for (; vt; vt = next)
{
next = this->_findnext(vt);
this->internal_erase(vt);
++count;
}
return count;
}
/**
* Returns the number of elements matching the specified key.
*
* @param key The key to check for.
* @returns The number of elements with the given key.
*/
size_t count(const key_type& key) const
{
return this->internal_count_multi(key);
}
#ifndef DOXYGEN_BUILD
using Base::begin;
using Base::cbegin;
using Base::cend;
using Base::end;
using Base::capacity;
using Base::empty;
using Base::max_size;
using Base::size;
using Base::clear;
using Base::erase;
using Base::swap;
using Base::contains;
using Base::equal_range;
using Base::find;
using Base::rehash;
using Base::reserve;
#endif
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/RHUnorderedMap.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite Robin-hood Unordered Map container.
#pragma once
#include "RobinHoodImpl.h"
namespace carb
{
namespace container
{
/**
* Implements an Unordered Map, that is: a container that contains a mapping of keys to values where all keys must be
* unique. There is no defined order to the set of keys.
*
* \copydetails detail::RobinHood
*
* @warning This container is similar to, but not a drop-in replacement for `std::unordered_map` due to differences in
* iterator invalidation and memory layout.
*
* Iterator/reference/pointer invalidation (note differences from `std::unordered_map`):
* Operation | Invalidates
* --------- | -----------
* All read operations: Never
* `clear`, `rehash`, `reserve`, `operator=`, `insert`, `emplace`, `try_emplace`, `operator[]` | Always
* `erase` | Only the element removed
* `swap` | All iterators, no pointers/references
*
* @tparam Key The key type
* @tparam Value The mapped type to be associated with `Key`
* @tparam Hasher A functor to use as a hashing function for \c Key
* @tparam Equals A functor to use to compare two \c Key values for equality
* @tparam LoadFactorMax100 The load factor to use for the table. This value must be in the range `[10, 100]` and
* represents the percentage of entries in the hash table that will be filled before resizing. Open-addressing hash maps
* with 100% usage have better memory usage but worse performance since they need "gaps" in the hash table to terminate
* runs.
*/
template <class Key, class Value, class Hasher = std::hash<Key>, class Equals = std::equal_to<Key>, size_t LoadFactorMax100 = 80>
class RHUnorderedMap
: public detail::
RobinHood<LoadFactorMax100, Key, std::pair<const Key, Value>, detail::Select1st<Key, std::pair<const Key, Value>>, Hasher, Equals>
{
using Base = detail::
RobinHood<LoadFactorMax100, Key, std::pair<const Key, Value>, detail::Select1st<Key, std::pair<const Key, Value>>, Hasher, Equals>;
public:
//! The key type
using key_type = typename Base::key_type;
//! The mapped value type
using mapped_type = Value;
//! The value type (effectively `std::pair<const key_type, mapped_type>`)
using value_type = typename Base::value_type;
//! Unsigned integer type (typically \c size_t)
using size_type = typename Base::size_type;
//! Signed integer type (typically \c ptrdiff_t)
using difference_type = typename Base::difference_type;
//! The hash function
using hasher = typename Base::hasher;
//! The key-equals function
using key_equal = typename Base::key_equal;
//! \c value_type&
using reference = typename Base::reference;
//! `const value_type&`
using const_reference = typename Base::const_reference;
//! \c value_type*
using pointer = typename Base::pointer;
//! `const value_type*`
using const_pointer = typename Base::const_pointer;
//! A \a LegacyForwardIterator to \c value_type
using iterator = typename Base::iterator;
//! A \a LegacyForwardIterator to `const value_type`
using const_iterator = typename Base::const_iterator;
//! A \a LegacyForwardIterator to \c value_type that proceeds to the next matching key when incremented.
using find_iterator = typename Base::find_iterator;
//! A \a LegacyForwardIterator to `const value_type` that proceeds to the next matching key when incremented.
using const_find_iterator = typename Base::const_find_iterator;
/**
* Constructs empty container.
*/
constexpr RHUnorderedMap() noexcept = default;
/**
* Copy constructor. Copies elements from another container.
*
* @note \c *this may have a different \ref carb::container::detail::RobinHood::capacity()
* than \p other.
* @param other The other container to copy entries from.
*/
RHUnorderedMap(const RHUnorderedMap& other) : Base(other)
{
}
/**
* Move constructor. Moves elements from another container.
*
* @note No move constructors on contained elements are invoked. \p other will be
* \ref carb::container::detail::RobinHood::empty() after this operation.
* @param other The other container to move entries from.
*/
RHUnorderedMap(RHUnorderedMap&& other) : Base(std::move(other))
{
}
/**
* Destructor. Destroys all contained elements and frees memory.
*/
~RHUnorderedMap() = default;
/**
* Copy-assign operator. Destroys all currently stored elements and copies elements from another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedMap& operator=(const RHUnorderedMap& other)
{
Base::operator=(other);
return *this;
}
/**
* Move-assign operator. Effectively swaps with another container.
*
* @param other The other container to copy entries from.
* @returns \c *this
*/
RHUnorderedMap& operator=(RHUnorderedMap&& other)
{
Base::operator=(std::move(other));
return *this;
}
/**
* Inserts an element into the container.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param value The value to insert by copying.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
std::pair<iterator, bool> insert(const value_type& value)
{
return this->insert_unique(value);
}
/**
* Inserts an element into the container.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param value The value to insert by moving.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
std::pair<iterator, bool> insert(value_type&& value)
{
return this->insert_unique(std::move(value));
}
/**
* Inserts an element into the container. Only participates in overload resolution if
* `std::is_constructible_v<value_type, P&&>` is true.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param value The value to insert by constructing via `std::forward<P>(value)`.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
template <class P>
std::pair<iterator, bool> insert(std::enable_if_t<std::is_constructible<value_type, P&&>::value, P&&> value)
{
return insert(value_type{ std::forward<P>(value) });
}
/**
* Constructs an element in-place.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* @param args The arguments to pass to the \c value_type constructor.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
template <class... Args>
std::pair<iterator, bool> emplace(Args&&... args)
{
// We need the key, so just construct the item here
return insert(value_type{ std::forward<Args>(args)... });
}
/**
* Inserts in-place if the key does not exist; does nothing if the key already exists.
*
* Inserts a new element into the container with key \p key and value constructed with \p args if there is no
* element with the key in the container. If the key does not exist and the insert succeeds, constructs `value_type`
* as `value_type{std::piecewise_construct, std::forward_as_tuple(key),
* std::forward_as_tuple(std::forward<Args>(args)...}`.
*
* @param key The key used to look up existing and insert if not found.
* @param args The args used to construct \ref mapped_type.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
template <class... Args>
std::pair<iterator, bool> try_emplace(const key_type& key, Args&&... args)
{
auto result = this->internal_insert(key);
if (result.second)
new (result.first) value_type(std::piecewise_construct, std::forward_as_tuple(key),
std::forward_as_tuple(std::forward<Args>(args)...));
return std::make_pair(this->make_iter(result.first), result.second);
}
/**
* Inserts in-place if the key does not exist; does nothing if the key already exists.
*
* Inserts a new element into the container with key \p key and value constructed with \p args if there is no
* element with the key in the container. If the key does not exist and the insert succeeds, constructs `value_type`
* as `value_type{std::piecewise_construct, std::forward_as_tuple(std::move(key)),
* std::forward_as_tuple(std::forward<Args>(args)...}`.
*
* @param key The key used to look up existing and insert if not found.
* @param args The args used to construct \ref mapped_type.
* @returns A \c pair consisting of an iterator to the inserted element (or the existing element that prevented the
* insertion) and a \c bool that will be \c true if insertion took place or \c false if insertion did \a not take
* place.
*/
template <class... Args>
std::pair<iterator, bool> try_emplace(key_type&& key, Args&&... args)
{
auto result = this->internal_insert(key);
if (result.second)
new (result.first) value_type(std::piecewise_construct, std::forward_as_tuple(std::move(key)),
std::forward_as_tuple(std::forward<Args>(args)...));
return std::make_pair(this->make_iter(result.first), result.second);
}
/**
* Removes elements with the given key.
*
* References, pointers and iterators to the erase element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param key the key value of elements to remove
* @returns the number of elements removed (either 1 or 0).
*/
size_type erase(const key_type& key)
{
auto vt = this->internal_find(key);
if (vt)
{
this->internal_erase(vt);
return 1;
}
return 0;
}
#if CARB_EXCEPTIONS_ENABLED || defined(DOXYGEN_BUILD)
/**
* Access specified element with bounds checking.
*
* This function is only available if exceptions are enabled.
*
* @param key The key of the element to find.
* @returns a reference to the mapped value of the element with key equivalent to \p key.
* @throws std::out_of_range if no such element exists.
*/
mapped_type& at(const key_type& key)
{
auto vt = this->internal_find(key);
if (vt)
return vt->second;
throw std::out_of_range("key not found");
}
/**
* Access specified element with bounds checking.
*
* This function is only available if exceptions are enabled.
*
* @param key The key of the element to find.
* @returns a reference to the mapped value of the element with key equivalent to \p key.
* @throws std::out_of_range if no such element exists.
*/
const mapped_type& at(const key_type& key) const
{
auto vt = this->internal_find(key);
if (vt)
return vt->second;
throw std::out_of_range("key not found");
}
#endif
/**
* Returns a reference to a value that is mapped to the given key, performing an insertion if such key does not
* already exist.
*
* If \p key does not exist, inserts a \c value_type constructed in-place from
* `std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>()`.
*
* \ref key_type must be \a CopyConstructible and \ref mapped_type must be \a DefaultConstructible.
* @param key the key of the element to find or insert
* @returns a reference to the \ref mapped_type mapped to \p key.
*/
mapped_type& operator[](const key_type& key)
{
auto result = this->internal_insert(key);
if (result.second)
new (result.first) value_type(std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>());
return result.first->second;
}
/**
* Returns a reference to a value that is mapped to the given key, performing an insertion if such key does not
* already exist.
*
* If \p key does not exist, inserts a \c value_type constructed in-place from
* `std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple<>()`.
*
* \ref key_type must be \a CopyConstructible and \ref mapped_type must be \a DefaultConstructible.
* @param key the key of the element to find or insert
* @returns a reference to the \ref mapped_type mapped to \p key.
*/
mapped_type& operator[](key_type&& key)
{
auto result = this->internal_insert(key);
if (result.second)
new (result.first) value_type(std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>());
return result.first->second;
}
/**
* Returns the number of elements matching the specified key.
*
* @param key The key to check for.
* @returns The number of elements with the given key (either 1 or 0).
*/
size_t count(const key_type& key) const
{
return !!this->internal_find(key);
}
#ifndef DOXYGEN_BUILD
using Base::begin;
using Base::cbegin;
using Base::cend;
using Base::end;
using Base::capacity;
using Base::empty;
using Base::max_size;
using Base::size;
using Base::clear;
using Base::erase;
using Base::swap;
using Base::contains;
using Base::equal_range;
using Base::find;
using Base::rehash;
using Base::reserve;
#endif
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/BufferedObject.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Defines the BufferedObject class
#pragma once
#include "../Defines.h"
#include "../cpp/Utility.h"
#include "../cpp/Atomic.h"
#include <array>
#include <cstdint>
#include <utility>
namespace carb
{
namespace container
{
/**
* Lock-Free Asynchronous Buffer
* Supports only 1 producer, 1 consumer
*
* BufferedObject is used when you have 1 producer and 1 consumer and both
* the producer and consumer are operating at different frequencies.
* The consumer only ever cares to see the latest data available.
*
* Examples:
*
* BufferedObject<int> b;
* assert(b.front() == 0);
* b.emplace_back(42);
* assert(b.front() == 0);
* b.pop_front();
* assert(b.front() == 42);
*
* BufferedObject<uint32_t> b{ in_place, 1U, 2U, 3U };
* assert(b.front() == 3U);
* b.pop_front(); // do nothing, as nothing was pushed
* assert(b.front() == 3U);
* b.push_back(42U);
* assert(b.front() == 3U);
* b.pop_front();
* assert(b.front() == 42U);
*/
template <typename T>
class BufferedObject final
{
CARB_PREVENT_COPY_AND_MOVE(BufferedObject);
enum Flags : uint8_t
{
eFlagsCreate = 0x06, // Field0=0, Field1=0, Field2=1, Field3=2
eFlagsDestroy = 0x00,
eDataAvailable = 0x40, // Field0=1
eField0Mask = 0xc0,
eField1Mask = 0x30,
eField2Mask = 0x0c,
eField3Mask = 0x03,
};
public:
/**
* Create an async buffer from an array of 3 items using default ctors
*/
BufferedObject() : m_flags(eFlagsCreate), m_buffer{}
{
}
/**
* Create an async buffer from an array of 3 items
*
* @param args arguments to forward to construct the elements of the buffer
*/
template <typename... TArgs>
constexpr explicit BufferedObject(carb::cpp::in_place_t, TArgs&&... args)
: m_flags(eFlagsCreate), m_buffer{ std::forward<TArgs>(args)... }
{
}
/**
* Destroy async buffer.
*/
~BufferedObject()
{
m_flags = eFlagsDestroy;
}
/**
* Insert a new item into the container constructed in-place with the given args
*
* @param args arguments to forward to construct newly produced value and move it onto the buffer
*/
template <typename... TArgs>
void emplace_back(TArgs&&... args)
{
uint8_t flagsNow;
uint8_t newFlags;
// place item in buffer in producer index/slot
m_buffer[(m_flags.load(std::memory_order_acquire) & eField1Mask) >> 4] = { std::forward<TArgs>(args)... };
//
// to produce a new value we need to:
// 1. set field 0 in flags to 1 (using mask eNewDataMask)
// 2. swap fields 1 and 2 ((flagsNow & eField2Mask) << 2) | ((flagsNow & eField1Mask) >> 2)
// 3. leave field 3 unchanged (flagsNow & eField3Mask)
//
do
{
flagsNow = m_flags.load(std::memory_order_acquire);
newFlags = eDataAvailable | ((flagsNow & eField2Mask) << 2) | ((flagsNow & eField1Mask) >> 2) |
(flagsNow & eField3Mask);
} while (
!m_flags.compare_exchange_strong(flagsNow, newFlags, std::memory_order_acq_rel, std::memory_order_relaxed));
}
/**
* Insert a new item into the container by moving item
*
* @param item item to insert/move
*/
void push_back(T&& item)
{
emplace_back(std::move(item));
}
/**
* Insert a new item into the container by copying item
*
* @param item item to copy
*/
void push_back(T const& item)
{
emplace_back(item);
}
/**
* Get reference to the latest item.
*
* @return reference to latest item
*/
T& front()
{
return m_buffer[m_flags.load(std::memory_order_acquire) & eField3Mask];
}
/**
* Attempt to replace the front element of the container with a newly produced value.
* If no new value was pushed/emplaced, this function does nothing.
*/
void pop_front()
{
uint8_t flagsNow;
uint8_t newFlags;
//
// to consume a new value:
// 1. check if new data available bit is set, if not just return previous data
// 2. remove the new data available bit
// 3. swap fields 2 and 3 ((flagsNow & eField3Mask) << 2) | ((flagsNow & eField2Mask) >> 2)
// 4. leave field 1 unchanged (flagsNow & eField1Mask)
//
do
{
flagsNow = m_flags.load(std::memory_order_acquire);
// check new data available bit set first
if ((flagsNow & eDataAvailable) == 0)
{
break;
}
newFlags = (flagsNow & eField1Mask) | ((flagsNow & eField3Mask) << 2) | ((flagsNow & eField2Mask) >> 2);
} while (
!m_flags.compare_exchange_strong(flagsNow, newFlags, std::memory_order_acq_rel, std::memory_order_relaxed));
}
private:
/*
* 8-bits of flags (2-bits per field)
*
* 0 1 2 3
* +--+--+--+--+
* |00|00|00|00|
* +--+--+--+--+
*
* Field 0: Is new data available? 0 == no, 1 == yes
* Field 1: Index into m_buffer that new values are pushed/emplaced into via push_back()/emplace_back()
* Field 2: Index into m_buffer that is the buffer between producer and consumer
* Field 3: Index into m_buffer that represents front()
*
* When the producer pushes a new value to m_buffer[field1], it will then atomically swap
* Field 1 and Field 2 and set Field 0 to 1 (to indicate new data is available)
*
* When the consumer calls front(), it just returns m_buffer[field3]. Since the producer
* never changes field3 value, the consumer is safe to call front() without any locks, even
* if the producer is pushing new values.
*
* When the consumer calls pop_front(), it will atomically swap
* Field 3 and Field 2 and set Field 0 back to 0 (to indicate middle buffer was drained)
*
* Producer
* * only ever sets Field 0 to 1
* * only ever writes to m_buffer[field1]
* * only ever swaps Field 1 and Field 2
*
* Consumer
* * only ever sets Field 0 to 0
* * only ever reads to m_buffer[field3]
* * only ever swaps Field 2 and Field 3
*/
std::atomic<uint8_t> m_flags;
std::array<T, 3> m_buffer;
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/LocklessStack.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Defines the LocklessStack class.
#pragma once
#include "../Defines.h"
#include "../cpp/Atomic.h"
#include "../thread/Mutex.h"
#include "../thread/Util.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <thread>
#if CARB_POSIX
# include <dlfcn.h>
#endif
#if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD)
//! On non-Windows platforms we fallback to a non-Lockless version that uses a mutex. This is because handling a pop()
//! requires potentially catching a SIGSEGV to restart the operation (similar to a cmpxchg failing). On Windows this is
//! easily done with SEH (Structured Exception Handling), but on Linux this requires a signal handler. If this file is
//! compiled into multiple dynamic objects then multiple signal handlers will be registered. Furthermore, the signal
//! handler of the currently active LocklessStack needs to be at the beginning of the handler chain. This is untenable
//! from a performance perspective. Therefore we use a mutex to ensure that all reads will be safe.
# define CARB_LOCKLESSSTACK_IS_LOCKLESS 1
#else
# define CARB_LOCKLESSSTACK_IS_LOCKLESS 0
#endif
namespace carb
{
namespace container
{
template <class T>
class LocklessStackLink;
template <class T, LocklessStackLink<T> T::*U>
class LocklessStack;
#ifndef DOXYGEN_BUILD
namespace detail
{
template <class T, LocklessStackLink<T> T::*U>
class LocklessStackHelpers;
template <class T, LocklessStackLink<T> T::*U>
class LocklessStackBase;
} // namespace detail
#endif
/**
* Defines the link object. Each class contained in LocklessStack must have a member of type LocklessStackLink<T>. A
* pointer to this member is required as the second parameter for LocklessStack.
*/
template <class T>
class LocklessStackLink
{
public:
/**
* Default constructor.
*/
constexpr LocklessStackLink() = default;
private:
CARB_VIZ LocklessStackLink<T>* m_next;
friend T;
template <class U, LocklessStackLink<U> U::*V>
friend class detail::LocklessStackHelpers;
template <class U, LocklessStackLink<U> U::*V>
friend class detail::LocklessStackBase;
template <class U, LocklessStackLink<U> U::*V>
friend class LocklessStack;
};
#if !defined(DOXYGEN_BUILD)
namespace detail
{
# if CARB_LOCKLESSSTACK_IS_LOCKLESS
class SignalHandler
{
public:
static bool readNext(void** out, void* in)
{
// We do this in a SEH block (on Windows) because it's possible (though rare) that another thread could have
// already popped and destroyed `cur` which would cause EXCEPTION_ACCESS_VIOLATION. By handling it in an
// exception handler, we recover cleanly and try again. On 64-bit Windows, there is zero cost unless an
// exception is thrown, at which point the kernel will find the Exception info and Unwind Info for the function
// that we're in.
__try
{
*out = *(void**)in;
return true;
}
__except (1)
{
return false;
}
}
};
# endif
template <class T, LocklessStackLink<T> T::*U>
class LocklessStackHelpers
{
public:
// Access the LocklessStackLink member of `p`
static LocklessStackLink<T>* link(T* p)
{
return std::addressof(p->*U);
}
// Converts a LocklessStackLink to the containing object
static T* convert(LocklessStackLink<T>* p)
{
// We need to calculate the offset of our link member and calculate where T is.
// Note that this doesn't work if T uses virtual inheritance
size_t offset = (size_t) reinterpret_cast<char*>(&(((T*)0)->*U));
return reinterpret_cast<T*>(reinterpret_cast<char*>(p) - offset);
}
};
// Base implementations
# if !CARB_LOCKLESSSTACK_IS_LOCKLESS
template <class T, LocklessStackLink<T> T::*U>
class LocklessStackBase : protected LocklessStackHelpers<T, U>
{
using Base = LocklessStackHelpers<T, U>;
public:
bool _isEmpty() const
{
return !m_head.load();
}
bool _push(T* first, T* last)
{
std::lock_guard<Lock> g(m_lock);
// Relaxed because under the lock
Base::link(last)->m_next = m_head.load(std::memory_order_relaxed);
bool const wasEmpty = !m_head.load(std::memory_order_relaxed);
m_head.store(Base::link(first), std::memory_order_relaxed);
return wasEmpty;
}
T* _popOne()
{
std::unique_lock<Lock> g(m_lock);
// Relaxed because under the lock
auto cur = m_head.load(std::memory_order_relaxed);
if (!cur)
{
return nullptr;
}
m_head.store(cur->m_next, std::memory_order_relaxed);
return Base::convert(cur);
}
T* _popAll()
{
std::lock_guard<Lock> g(m_lock);
// Relaxed because under the lock
LocklessStackLink<T>* head = m_head.exchange(nullptr, std::memory_order_relaxed);
return head ? Base::convert(head) : nullptr;
}
void _wait()
{
auto p = m_head.load();
while (!p)
{
m_head.wait(p);
p = m_head.load();
}
}
template <class Rep, class Period>
bool _waitFor(const std::chrono::duration<Rep, Period>& dur)
{
return _waitUntil(std::chrono::steady_clock::now() + dur);
}
template <class Clock, class Duration>
bool _waitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
auto p = m_head.load();
while (!p)
{
if (!m_head.wait_until(p, tp))
return false;
p = m_head.load();
}
return true;
}
void _notifyOne()
{
m_head.notify_one();
}
void _notifyAll()
{
m_head.notify_all();
}
private:
// Cannot be lockless if we don't have SEH
// Testing reveals that mutex is significantly faster than spinlock in highly-contended cases.
using Lock = carb::thread::mutex;
Lock m_lock;
cpp::atomic<LocklessStackLink<T>*> m_head{ nullptr };
};
# else
// Windows implementation: requires SEH and relies upon the fact that aligned pointers on modern OSes don't
// use at least 10 bits of the 64-bit space, so it uses those bits as a sequence number to ensure uniqueness between
// different threads competing to pop.
template <class T, LocklessStackLink<T> T::*U>
class LocklessStackBase : protected LocklessStackHelpers<T, U>
{
using Base = LocklessStackHelpers<T, U>;
public:
constexpr LocklessStackBase()
{
}
bool _isEmpty() const
{
return !decode(m_head.load(std::memory_order_acquire));
}
bool _push(T* first, T* last)
{
// All OS bits should either be zero or one, and it needs to be 8-byte-aligned.
LocklessStackLink<T>* lnk = Base::link(first);
CARB_ASSERT((size_t(lnk) & kCPUMask) == 0 || (size_t(lnk) & kCPUMask) == kCPUMask, "Unexpected OS bits set");
CARB_ASSERT((size_t(lnk) & ((1 << 3) - 1)) == 0, "Pointer not aligned properly");
uint16_t seq;
uint64_t expected = m_head.load(std::memory_order_acquire), temp;
decltype(lnk) next;
do
{
next = decode(expected, seq);
Base::link(last)->m_next = next;
temp = encode(lnk, seq + 1); // Increase sequence
} while (CARB_UNLIKELY(
!m_head.compare_exchange_strong(expected, temp, std::memory_order_release, std::memory_order_relaxed)));
return !next;
}
T* _popOne()
{
uint64_t expected = m_head.load(std::memory_order_acquire);
LocklessStackLink<T>* cur;
uint16_t seq;
bool isNull = false;
this_thread::spinWaitWithBackoff([&] {
cur = decode(expected, seq);
if (!cur)
{
// End attempts because the stack is empty
isNull = true;
return true;
}
// Attempt to read the next value
LocklessStackLink<T>* newhead;
if (!detail::SignalHandler::readNext((void**)&newhead, cur))
{
// Another thread changed `cur`, so reload and try again.
expected = m_head.load(std::memory_order_acquire);
return false;
}
// Only push needs to increase `seq`
uint64_t temp = encode(newhead, seq);
return m_head.compare_exchange_strong(expected, temp, std::memory_order_release, std::memory_order_relaxed);
});
return isNull ? nullptr : Base::convert(cur);
}
T* _popAll()
{
uint16_t seq;
uint64_t expected = m_head.load(std::memory_order_acquire), temp;
for (;;)
{
LocklessStackLink<T>* head = decode(expected, seq);
if (!head)
{
return nullptr;
}
// Keep the same sequence since only push() needs to increment the sequence
temp = encode(nullptr, seq);
if (CARB_LIKELY(
m_head.compare_exchange_weak(expected, temp, std::memory_order_release, std::memory_order_relaxed)))
{
return Base::convert(head);
}
}
}
void _wait()
{
uint64_t head = m_head.load(std::memory_order_acquire);
while (!decode(head))
{
m_head.wait(head, std::memory_order_relaxed);
head = m_head.load(std::memory_order_acquire);
}
}
template <class Rep, class Period>
bool _waitFor(const std::chrono::duration<Rep, Period>& dur)
{
return _waitUntil(std::chrono::steady_clock::now() + dur);
}
template <class Clock, class Duration>
bool _waitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
uint64_t head = m_head.load(std::memory_order_acquire);
while (!decode(head))
{
if (!m_head.wait_until(head, tp, std::memory_order_relaxed))
{
return false;
}
head = m_head.load(std::memory_order_acquire);
}
return true;
}
void _notifyOne()
{
m_head.notify_one();
}
void _notifyAll()
{
m_head.notify_all();
}
private:
// On 64-bit architectures, we make use of the fact that CPUs only use a certain number of address bits.
// Intel CPUs require that these 8 to 16 most-significant-bits match (all 1s or 0s). Since 8 appears to be the
// lowest common denominator, we steal 7 bits (to save the value of one of the bits so that they can match) for a
// sequence number. The sequence is important as it causes the resulting stored value to change even if the stack is
// pushing and popping the same value.
//
// Pointer compression drops the `m` and `z` bits from the pointer. `m` are expected to be consistent (all 1 or 0)
// and match the most-significant `P` bit. `z` are expected to be zeros:
//
// 63 ------------------------------ BITS ------------------------------ 0
// mmmmmmmP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPzzz
//
// `m_head` is encoded as the shifted compressed pointer bits `P` with sequence bits `s`:
// 63 ------------------------------ BITS ------------------------------ 0
// PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPss ssssssss
static_assert(sizeof(size_t) == 8, "64-bit only");
CARB_VIZ constexpr const static size_t kCpuBits = 7; // MSBs that are limited by CPU hardware and must match the
// 56th bit
constexpr const static size_t kCPUMask = ((size_t(1) << (kCpuBits + 1)) - 1) << (63 - kCpuBits);
CARB_VIZ constexpr const static size_t kSeqBits = kCpuBits + 3; // We also use the lowest 3 bits as part of the
// sequence
CARB_VIZ constexpr const static size_t kSeqMask = (size_t(1) << kSeqBits) - 1;
CARB_VIZ cpp::atomic_uint64_t m_head{ 0 };
static LocklessStackLink<T>* decode(size_t val)
{
// Clear the `s` sequence bits and shift as a signed value to sign-extend so that the `m` bits are filled in to
// match the most-significant `P` bit.
return reinterpret_cast<LocklessStackLink<T>*>(ptrdiff_t(val & ~kSeqMask) >> kCpuBits);
}
static LocklessStackLink<T>* decode(size_t val, uint16_t& seq)
{
seq = val & kSeqMask;
return decode(val);
}
static size_t encode(LocklessStackLink<T>* p, uint16_t seq)
{
// Shift the pointer value, dropping the most significant `m` bits and write the sequence number over the `z`
// and space created in the least-significant area.
return ((reinterpret_cast<size_t>(p) << kCpuBits) & ~kSeqMask) + (seq & uint16_t(kSeqMask));
}
};
# endif
} // namespace detail
#endif
/**
* @brief Implements a lockless stack: a LIFO container that is thread-safe yet requires no kernel involvement.
*
* LocklessStack is designed to be easy-to-use. For a class `Foo` that you want to be contained in a LocklessStack, it
* must have a member of type LocklessStackLink<Foo>. This member is what the LocklessStack will use for tracking data.
*
* Pushing to LocklessStack is simply done through LocklessStack::push(), which is entirely thread-safe. LocklessStack
* ensures last-in-first-out (LIFO) for each producer pushing to LocklessStack. Multiple producers may be pushing to
* LocklessStack simultaneously, so their items can become mingled, but each producer's pushed items will be strongly
* ordered.
*
* Popping is done through LocklessStack::pop(), which is also entirely thread-safe. Multiple threads may all attempt to
* pop from the same LocklessStack simultaneously.
*
* Simple example:
* ```cpp
* class Foo
* {
* public:
* LocklessStackLink<Foo> m_link;
* };
*
* LocklessStack<Foo, &Foo::m_link> stack;
* stack.push(new Foo);
* Foo* p = stack.pop();
* delete p;
* ```
*
* @thread_safety LocklessStack is entirely thread-safe except where declared otherwise. No allocation happens with a
* LocklessStack; instead the caller is responsible for construction/destruction of contained objects.
*
* \warning LocklessStack on non-Windows implementations is not Lockless (i.e. uses a mutex to synchronize). For an
* explanation as to why, see \ref CARB_LOCKLESSSTACK_IS_LOCKLESS.
*
* @tparam T The type to contain.
* @tparam U A pointer-to-member of a LocklessStackLink member within T (see above example).
*/
template <class T, LocklessStackLink<T> T::*U>
class LocklessStack final : protected detail::LocklessStackBase<T, U>
{
using Base = detail::LocklessStackBase<T, U>;
public:
/**
* Constructor.
*/
constexpr LocklessStack() = default;
/**
* Destructor.
*
* Asserts that isEmpty() returns true.
*/
~LocklessStack()
{
// Ensure the stack is empty
CARB_ASSERT(isEmpty());
}
/**
* Indicates whether the stack is empty.
*
* @warning Another thread may have modified the LocklessStack before this function returns.
*
* @returns `true` if the stack appears empty; `false` if items appear to exist in the stack.
*/
bool isEmpty() const
{
return Base::_isEmpty();
}
/**
* Pushes an item onto the stack.
*
* @param p The item to push onto the stack.
*
* @return `true` if the stack was previously empty prior to push; `false` otherwise. Note that this is atomically
* correct as opposed to checking isEmpty() before push().
*/
bool push(T* p)
{
return Base::_push(p, p);
}
/**
* Pushes a contiguous block of entries from [ @p begin, @p end) onto the stack.
*
* @note All of the entries are guaranteed to remain strongly ordered and will not be interspersed with entries from
* other threads. @p begin will be popped from the stack first.
*
* @param begin An <a href="https://en.cppreference.com/w/cpp/named_req/InputIterator">InputIterator</a> of the
* first item to push. `*begin` must resolve to a `T&`.
* @param end An off-the-end InputIterator after the last item to push.
* @returns `true` if the stack was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
#ifndef DOXYGEN_BUILD
template <class InputItRef,
std::enable_if_t<std::is_convertible<decltype(std::declval<InputItRef&>()++, *std::declval<InputItRef&>()), T&>::value,
bool> = false>
#else
template <class InputItRef>
#endif
bool push(InputItRef begin, InputItRef end)
{
if (begin == end)
{
return false;
}
// Walk the list and have them point to each other
InputItRef last = begin;
InputItRef iter = begin;
for (iter++; iter != end; last = iter++)
{
Base::link(std::addressof(*last))->m_next = Base::link(std::addressof(*iter));
}
return Base::_push(std::addressof(*begin), std::addressof(*last));
}
/**
* Pushes a block of pointers-to-entries from [ @p begin, @p end) onto the stack.
*
* @note All of the entries are guaranteed to remain strongly ordered and will not be interspersed with entries from
* other threads. @p begin will be popped from the stack first.
*
* @param begin An <a href="https://en.cppreference.com/w/cpp/named_req/InputIterator">InputIterator</a> of the
* first item to push. `*begin` must resolve to a `T*`.
* @param end An off-the-end InputIterator after the last item to push.
* @returns `true` if the stack was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
#ifndef DOXYGEN_BUILD
template <class InputItPtr,
std::enable_if_t<std::is_convertible<decltype(std::declval<InputItPtr&>()++, *std::declval<InputItPtr&>()), T*>::value,
bool> = true>
#else
template <class InputItPtr>
#endif
bool push(InputItPtr begin, InputItPtr end)
{
if (begin == end)
{
return false;
}
// Walk the list and have them point to each other
InputItPtr last = begin;
InputItPtr iter = begin;
for (iter++; iter != end; last = iter++)
{
Base::link(*last)->m_next = Base::link(*iter);
}
return Base::_push(*begin, *last);
}
/**
* Pops an item from the top of the stack if available.
*
* @return An item popped from the stack. If the stack was empty, then `nullptr` is returned.
*/
T* pop()
{
return Base::_popOne();
}
/**
* Empties the stack.
*
* @note To perform an action on each item as it is popped, use forEach() instead.
*/
void popAll()
{
Base::_popAll();
}
/**
* Pops all available items from the stack calling a functionish object on each.
*
* First, pops all available items from `*this` and then calls @p f on each.
*
* @note As the pop is the first thing that happens, any new entries that get pushed while the function is executing
* will NOT be popped and will remain in the stack when this function returns.
*
* @param f A functionish object that accepts a `T*` parameter. Called for each item that was popped from the stack.
*/
template <class Func>
void forEach(Func&& f)
{
T* p = Base::_popAll();
LocklessStackLink<T>* h = p ? Base::link(p) : nullptr;
while (h)
{
p = Base::convert(h);
h = h->m_next;
f(p);
}
}
/**
* Pushes an item onto the stack and notifies a waiting listener.
*
* Equivalent to doing `auto b = push(p); notifyOne(); return b;`.
*
* @see push(), notifyOne()
*
* @param p The item to push.
* @returns `true` if the stack was empty prior to push; `false` otherwise. Note that this is atomically correct
* as opposed to calling isEmpty() before push().
*/
bool pushNotify(T* p)
{
bool b = push(p);
notifyOne();
return b;
}
/**
* Blocks the calling thread until an item is available and returns it.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @see pop(), wait()
*
* @returns The first item popped from the stack.
*/
T* popWait()
{
T* p = pop();
while (!p)
{
wait();
p = pop();
}
return p;
}
/**
* Blocks the calling thread until an item is available and returns it or a timeout elapses.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @see pop(), waitFor()
*
* @param dur The duration to wait for an item to become available.
* @returns the first item removed from the stack or `nullptr` if the timeout period elapses.
*/
template <class Rep, class Period>
T* popWaitFor(const std::chrono::duration<Rep, Period>& dur)
{
return popWaitUntil(std::chrono::steady_clock::now() + dur);
}
/**
* Blocks the calling thread until an item is available and returns it or the clock reaches a time point.
*
* Requires the item to be pushed with pushNotify(), notifyOne() or notifyAll().
*
* @see pop(), waitUntil()
*
* @param tp The time to wait until for an item to become available.
* @returns the first item removed from the stack or `nullptr` if the timeout period elapses.
*/
template <class Clock, class Duration>
T* popWaitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
T* p = pop();
while (!p)
{
if (!waitUntil(tp))
{
return pop();
}
p = pop();
}
return p;
}
/**
* Waits until the stack is non-empty.
*
* @note Requires notification that the stack is non-empty, such as from pushNotify(), notifyOne() or notifyAll().
*
* @note Though wait() returns, another thread may have popped the available item making the stack empty again. Use
* popWait() if it is desired to ensure that the current thread can obtain an item.
*/
void wait()
{
Base::_wait();
}
/**
* Waits until the stack is non-empty or a specified duration has passed.
*
* @note Though waitFor() returns `true`, another thread may have popped the available item making the stack empty
* again. Use popWaitFor() if it is desired to ensure that the current thread can obtain an item.
*
* @note Requires notification that the stack is non-empty, such as from pushNotify(), notifyOne() or notifyAll().
*
* @param dur The duration to wait for an item to become available.
* @returns `true` if an item appears to be available; `false` if the timeout elapses.
*/
template <class Rep, class Period>
bool waitFor(const std::chrono::duration<Rep, Period>& dur)
{
return Base::_waitFor(dur);
}
/**
* Waits until the stack is non-empty or a specific time is reached.
*
* @note Though waitUntil() returns `true`, another thread may have popped the available item making the stack empty
* again. Use popWaitUntil() if it is desired to ensure that the current thread can obtain an item.
*
* @note Requires notification that the stack is non-empty, such as from pushNotify(), notifyOne() or notifyAll().
*
* @param tp The time to wait until for an item to become available.
* @returns `true` if an item appears to be available; `false` if the time is reached.
*/
template <class Clock, class Duration>
bool waitUntil(const std::chrono::time_point<Clock, Duration>& tp)
{
return Base::_waitUntil(tp);
}
/**
* Notifies a single waiting thread.
*
* Notifies a single thread waiting in wait(), waitFor(), waitUntil(), popWait(), popWaitFor(), or popWaitUntil() to
* wake and check the stack.
*/
void notifyOne()
{
Base::_notifyOne();
}
/**
* Notifies all waiting threads.
*
* Notifies all threads waiting in wait(), waitFor(), waitUntil(), popWait(), popWaitFor(), or popWaitUntil() to
* wake and check the stack.
*/
void notifyAll()
{
Base::_notifyAll();
}
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/container/IntrusiveUnorderedMultimap.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite intrusive unordered multi-map container.
#pragma once
#include "../Defines.h"
#include "../cpp/Bit.h"
#include <cmath>
#include <functional>
#include <iterator>
#include <memory>
namespace carb
{
namespace container
{
template <class Key, class T>
class IntrusiveUnorderedMultimapLink;
template <class Key, class T, IntrusiveUnorderedMultimapLink<Key, T> T::*U, class Hash, class Pred>
class IntrusiveUnorderedMultimap;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
struct NontrivialDummyType
{
constexpr NontrivialDummyType() noexcept
{
}
};
static_assert(!std::is_trivially_default_constructible<NontrivialDummyType>::value, "Invalid assumption");
template <class Key, class T>
class IntrusiveUnorderedMultimapLinkBase
{
public:
using KeyType = const Key;
using MappedType = T;
using ValueType = std::pair<const Key, T&>;
constexpr IntrusiveUnorderedMultimapLinkBase() noexcept = default;
~IntrusiveUnorderedMultimapLinkBase()
{
// Shouldn't be contained at destruction time
CARB_ASSERT(!isContained());
}
bool isContained() const noexcept
{
return m_next != nullptr;
}
private:
template <class Key2, class U, IntrusiveUnorderedMultimapLink<Key2, U> U::*V, class Hash, class Pred>
friend class ::carb::container::IntrusiveUnorderedMultimap;
IntrusiveUnorderedMultimapLink<Key, T>* m_next{ nullptr };
IntrusiveUnorderedMultimapLink<Key, T>* m_prev{ nullptr };
CARB_PREVENT_COPY_AND_MOVE(IntrusiveUnorderedMultimapLinkBase);
constexpr IntrusiveUnorderedMultimapLinkBase(IntrusiveUnorderedMultimapLink<Key, T>* init) noexcept
: m_next(init), m_prev(init)
{
}
};
} // namespace detail
#endif
/**
* Defines a "link node" that \ref IntrusiveUnorderedMultimap will use for tracking data for the contained type.
*/
template <class Key, class T>
class IntrusiveUnorderedMultimapLink : public detail::IntrusiveUnorderedMultimapLinkBase<Key, T>
{
using Base = detail::IntrusiveUnorderedMultimapLinkBase<Key, T>;
public:
//! Constructor.
constexpr IntrusiveUnorderedMultimapLink() noexcept : empty{}
{
}
//! Destructor. Asserts that the link is not contained in an @ref IntrusiveUnorderedMultimap.
~IntrusiveUnorderedMultimapLink()
{
// Shouldn't be contained at destruction time
CARB_ASSERT(!this->isContained());
}
private:
template <class Key2, class U, IntrusiveUnorderedMultimapLink<Key2, U> U::*V, class Hash, class Pred>
friend class IntrusiveUnorderedMultimap;
union
{
detail::NontrivialDummyType empty;
typename Base::ValueType value;
};
CARB_PREVENT_COPY_AND_MOVE(IntrusiveUnorderedMultimapLink);
};
/**
* IntrusiveUnorderedMultimap is a closed-addressing hash table very similar to std::unordered_multimap, but requires
* the tracking information to be contained within the stored type `T`, rather than built around it. In other words, the
* tracking information is "intrusive" in the type `T` by way of the IntrusiveUnorderedMultimapLink type.
* IntrusiveUnorderedMultimap does no allocation of the `T` type; all allocation is done outside of the context of
* IntrusiveUnorderedMultimap, which allows stored items to be on the stack, grouped with other items, etc.
*
* The impetus behind intrusive containers is specifically to allow the application to own the allocation patterns for a
* type, but still be able to store them in a container. For `std::unordered_multimap`, everything goes through an
* `Allocator` type, but in a real application some stored instances may be on the stack while others are on the heap,
* which makes using `std::unordered_multimap` impractical. Furthermore, a stored type may which to be removed from one
* list and inserted into another. With `std::unordered_multimap`, this would require heap interaction to erase from one
* list and insert into another. With IntrusiveUnorderedMultimap, this operation would not require any heap interaction
* and would be done very quickly (O(1)).
*
* Another example is a `std::unordered_multimap` of polymorphic types. For `std::unordered_multimap` the mapped type
* would have to be a pointer or pointer-like type which is an inefficient use of space, cache, etc. The
* \c IntrusiveUnorderedMultimapLink can be part of the contained object which is a more efficient use of space.
*
* Since IntrusiveUnorderedMultimap doesn't require any form of `Allocator`, the allocation strategy is completely left
* up to the application. This means that items could be allocated on the stack, pooled, or items mixed between stack
* and heap.
*
* An intrusive unique-map (i.e. an intrusive equivalent to `std::unordered_map`) is impractical because allocation is
* not the responsibility of the container. For `std::unordered_map::insert`, if a matching key already exists, a new
* entry is not created and an iterator to the existing entry is returned. Conversely, with the intrusive container, the
* insert function is being given an already-created object that cannot be destroyed. It is therefore up to the
* application to ensure uniqueness if desired. Similarly, the existence of an intrusive (multi-)set is impractical
* since a type `T` is required to be contained and a custom hasher/equality-predicate would have to be written to
* support it--it would be simpler to use @ref carb::container::IntrusiveList.
*
* It is important to select a good hashing function in order to reduce collisions that may sap performance. Generally
* \c std::hash is used which is typically based on the FNV-1a hash algorithm. Hash computation is only done for finding
* the bucket that would contain an item. Once the bucket is selected, the \c Pred template parameter is used to compare
* keys until a match is found. A truly ideal hash at the default load factor of \c 1.0 results in a single entry per
* bucket; however, this is not always true in practice. Hash collisions cause multiple items to fall into the same
* bucket, increasing the amount of work that must be done to find an item.
*
* Iterator invalidation mirrors that of `std::unordered_multimap`: rehashing invalidates iterators and may cause
* elements to be rearranged into different buckets, but does not invalidate references or pointers to keys or the
* mapped type.
*
* IntrusiveUnorderedMultimap matches `std::unordered_multimap` with the following exceptions:
* - The `iterator` and `initializer_list` constructor variants are not present in IntrusiveUnorderedMultimap.
* - The `iterator` and `initializer_list` insert() variants are not present in IntrusiveUnorderedMultimap.
* - IntrusiveUnorderedMultimap cannot be copied (though may still be moved).
* - IntrusiveUnorderedMultimap does not have `erase()` to erase an item from the list, but instead has remove() which
* will remove an item from the container. It is up to the caller to manage the memory for the item.
* - Likewise, clear() functions as a "remove all" and does not destroy items in the container.
* - iter_from_value() is a new function that translates an item contained in IntrusiveUnorderedMultimap into an
* iterator.
* - `local_iterator` and `begin(size_type)`/`end(size_type)` are not implemented.
*
* Example:
* @code{.cpp}
* class Subscription {
* public:
* IntrusiveUnorderedMultimapLink<std::string, Subscription> link;
* void notify();
* };
*
* IntrusiveUnorderedMultimap<std::string, &Subscription::link> map;
*
* Subscription sub;
* map.emplace("my subscription", sub);
*
* // Notify all subscriptions:
* for (auto& entry : map)
* entry.second.notify();
*
* map.remove("my subscription");
* @endcode
*
* @tparam Key A key to associate with the mapped data.
* @tparam T The mapped data, referred to by `Key`.
* @tparam U A pointer-to-member of `T` that must be of type @ref IntrusiveUnorderedMultimapLink. This member will be
* used by the IntrusiveUnorderedMultimap for storing the key type and tracking the contained object.
* @tparam Hash A class that is used to hash the key value. Better hashing functions produce better performance.
* @tparam Pred A class that is used to equality-compare two key values.
*/
template <class Key, class T, IntrusiveUnorderedMultimapLink<Key, T> T::*U, class Hash = ::std::hash<Key>, class Pred = ::std::equal_to<Key>>
class IntrusiveUnorderedMultimap
{
using BaseLink = detail::IntrusiveUnorderedMultimapLinkBase<Key, T>;
public:
//! The type of the key; type `Key`
using KeyType = const Key;
//! The type of the mapped data; type `T`
using MappedType = T;
//! The type of the @ref IntrusiveUnorderedMultimapLink that must be a member of MappedType.
using Link = IntrusiveUnorderedMultimapLink<Key, T>;
//! Helper definition for `std::pair<const Key, T&>`.
using ValueType = typename Link::ValueType;
// Iterator support
// clang-format off
//! A LegacyForwardIterator to `const ValueType`.
//! @see <a href="https://en.cppreference.com/w/cpp/named_req/ForwardIterator">LegacyForwardIterator</a>
class const_iterator
{
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
using iterator_category = std::forward_iterator_tag;
using value_type = ValueType;
using difference_type = ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
const_iterator() noexcept = default;
reference operator * () const { assertNotEnd(); return m_where->value; }
pointer operator -> () const { assertNotEnd(); return std::addressof(operator*()); }
const_iterator& operator ++ () noexcept /* ++iter */ { assertNotEnd(); incr(); return *this; }
const_iterator operator ++ (int) noexcept /* iter++ */ { assertNotEnd(); const_iterator i{ *this }; incr(); return i; }
bool operator == (const const_iterator& rhs) const noexcept { assertSameOwner(rhs); return m_where == rhs.m_where; }
bool operator != (const const_iterator& rhs) const noexcept { assertSameOwner(rhs); return m_where != rhs.m_where; }
protected:
friend class IntrusiveUnorderedMultimap;
Link* m_where{ nullptr };
#if CARB_ASSERT_ENABLED
const IntrusiveUnorderedMultimap* m_owner{ nullptr };
const_iterator(Link* where, const IntrusiveUnorderedMultimap* owner) noexcept : m_where(where), m_owner(owner) {}
void assertOwner(const IntrusiveUnorderedMultimap* other) const noexcept
{
CARB_ASSERT(m_owner == other, "IntrusiveUnorderedMultimap iterator for invalid container");
}
void assertSameOwner(const const_iterator& rhs) const noexcept
{
CARB_ASSERT(m_owner == rhs.m_owner, "IntrusiveUnorderedMultimap iterators are from different containers");
}
void assertNotEnd() const noexcept
{
CARB_ASSERT(m_where != m_owner->_end(), "Invalid operation on IntrusiveUnorderedMultimap::end() iterator");
}
#else
const_iterator(Link* where, const IntrusiveUnorderedMultimap*) noexcept : m_where(where) {}
void assertOwner(const IntrusiveUnorderedMultimap* other) const noexcept
{
CARB_UNUSED(other);
}
void assertSameOwner(const const_iterator& rhs) const noexcept
{
CARB_UNUSED(rhs);
}
void assertNotEnd() const noexcept {}
#endif // !CARB_ASSERT_ENABLED
void incr() noexcept { m_where = m_where->m_next; }
#endif // !DOXYGEN_SHOULD_SKIP_THIS
};
//! A LegacyForwardIterator to `ValueType`.
//! @see <a href="https://en.cppreference.com/w/cpp/named_req/ForwardIterator">LegacyForwardIterator</a>
class iterator : public const_iterator
{
using Base = const_iterator;
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
using iterator_category = std::forward_iterator_tag;
using value_type = ValueType;
using difference_type = ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
iterator() noexcept = default;
reference operator * () const { this->assertNotEnd(); return this->m_where->value; }
pointer operator -> () const { this->assertNotEnd(); return std::addressof(operator*()); }
iterator& operator ++ () noexcept /* ++iter */ { this->assertNotEnd(); this->incr(); return *this; }
iterator operator ++ (int) noexcept /* iter++ */ { this->assertNotEnd(); iterator i{ *this }; this->incr(); return i; }
private:
friend class IntrusiveUnorderedMultimap;
iterator(Link* where, const IntrusiveUnorderedMultimap* owner) : Base(where, owner) {}
#endif
};
// clang-format on
CARB_PREVENT_COPY(IntrusiveUnorderedMultimap);
//! Constructor. Initializes `*this` to be empty().
constexpr IntrusiveUnorderedMultimap() : m_list(_end())
{
}
//! Move-construct. Moves all entries to `*this` from @p other and leaves it empty.
//! @param other Another IntrusiveUnorderedMultimap to move entries from.
IntrusiveUnorderedMultimap(IntrusiveUnorderedMultimap&& other) noexcept : m_list(_end())
{
swap(other);
}
//! Destructor. Implies clear().
~IntrusiveUnorderedMultimap()
{
clear();
m_list.m_next = m_list.m_prev = nullptr; // Prevents the assert
}
//! Move-assign. Moves all entries from @p other and leaves @p other in a valid but possibly non-empty state.
//! @param other Another IntrusiveUnorderedMultimap to move entries from.
IntrusiveUnorderedMultimap& operator=(IntrusiveUnorderedMultimap&& other) noexcept
{
swap(other);
return *this;
}
//! Checks whether the container is empty.
//! @returns `true` if `*this` is empty; `false` otherwise.
bool empty() const noexcept
{
return !m_size;
}
//! Returns the number of elements contained.
//! @returns The number of elements contained.
size_t size() const noexcept
{
return m_size;
}
//! Returns the maximum possible number of elements.
//! @returns The maximum possible number of elements.
size_t max_size() const noexcept
{
return size_t(-1);
}
// Iterator support
//! Returns an iterator to the beginning.
//! @returns An iterator to the beginning.
iterator begin() noexcept
{
return iterator(_head(), this);
}
//! Returns an iterator to the end.
//! @returns An iterator to the end.
iterator end() noexcept
{
return iterator(_end(), this);
}
//! Returns a const_iterator to the beginning.
//! @returns A const_iterator to the beginning.
const_iterator cbegin() const noexcept
{
return const_iterator(_head(), this);
}
//! Returns a const_iterator to the end.
//! @returns A const_iterator to the end.
const_iterator cend() const noexcept
{
return const_iterator(_end(), this);
}
//! Returns a const_iterator to the beginning.
//! @returns A const_iterator to the beginning.
const_iterator begin() const noexcept
{
return cbegin();
}
//! Returns a const_iterator to the end.
//! @returns A const_iterator to the end.
const_iterator end() const noexcept
{
return cend();
}
//! Returns an iterator to the given value if it is contained in `*this`, otherwise returns `end()`. O(n).
//! @param value The value to check for.
//! @returns An @ref iterator to @p value if contained in `*this`; end() otherwise.
iterator locate(T& value) noexcept
{
Link* l = _link(value);
return iterator(l->isContained() ? _listfind(value) : _end(), this);
}
//! Returns an iterator to the given value if it is contained in `*this`, otherwise returns `end()`. O(n).
//! @param value The value to check for.
//! @returns A @ref const_iterator to @p value if contained in `*this`; end() otherwise.
const_iterator locate(T& value) const noexcept
{
Link* l = _link(value);
return const_iterator(l->isContained() ? _listfind(value) : _end(), this);
}
//! Naively produces an @ref iterator for @p value within `*this`.
//! @warning Undefined behavior results if @p value is not contained within `*this`. Use locate() to safely check.
//! @param value The value to convert.
//! @returns An @ref iterator to @p value.
iterator iter_from_value(T& value)
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained() || _listfind(value) != _end());
return iterator(l->isContained() ? l : _end(), this);
}
//! Naively produces an @ref iterator for @p value within `*this`.
//! @warning Undefined behavior results if @p value is not contained within `*this`. Use locate() to safely check.
//! @param value The value to convert.
//! @returns A @ref const_iterator to @p value.
const_iterator iter_from_value(T& value) const
{
Link* l = _link(value);
CARB_ASSERT(!l->isContained() || _listfind(value) != _end());
return const_iterator(l->isContained() ? l : _end(), this);
}
//! Removes all elements.
//! @note Postcondition: `*this` is empty().
void clear()
{
if (_head() != _end())
{
do
{
Link* p = _head();
p->value.~ValueType(); // Destruct the key
m_list.m_next = p->m_next;
p->m_next = p->m_prev = nullptr;
} while (_head() != _end());
m_list.m_prev = _end();
m_size = 0;
// Clear the buckets
memset(m_buckets.get(), 0, sizeof(LinkPair) * m_bucketCount);
}
}
//! Inserts an element.
//! @note No uniqueness checking is performed; multiple values with the same `Key` may be inserted.
//! @note Precondition: `value.second` must not be contained (via `U`) in this or any other
//! IntrusiveUnorderedMultimap.
//! @param value The pair of `[key, value reference]` to insert.
//! @returns An @ref iterator to the newly-inserted @p value.
iterator insert(ValueType value)
{
T& val = value.second;
Link* l = _link(val);
CARB_ASSERT(!l->isContained());
// Construct the key
new (&l->value) ValueType(std::move(value));
// Hash
size_t const hash = Hash{}(l->value.first);
++m_size;
// Find insertion point
reserve(size());
LinkPair& bucket = m_buckets[_bucket(hash)];
if (bucket.first)
{
// Need to see if there's a matching value in the bucket so that we group all keys together
Pred pred{};
Link* const end = bucket.second->m_next;
for (Link* p = bucket.first; p != end; p = p->m_next)
{
if (pred(l->value.first, p->value.first))
{
// Match! Insert here.
l->m_prev = p->m_prev;
l->m_next = p;
l->m_prev->m_next = l;
l->m_next->m_prev = l;
if (p == bucket.first)
{
bucket.first = l;
}
return iterator(l, this);
}
}
// Didn't find a match within the bucket. Just add to the end of the bucket
l->m_prev = bucket.second;
l->m_next = end;
l->m_prev->m_next = l;
l->m_next->m_prev = l;
bucket.second = l;
}
else
{
// Insert at end of the list
l->m_prev = _tail();
l->m_next = _end();
l->m_prev->m_next = l;
l->m_next->m_prev = l;
bucket.first = bucket.second = l;
}
return iterator(l, this);
}
//! Inserts an element while allowing key emplacement.
//! @note No uniqueness checking is performed; multiple values with the same `Key` may be inserted.
//! @note Precondition: The `second` member of the constructed `pair` must not be contained (via `U`) in this or any
//! other IntrusiveUnorderedMultimap.
//! @param args Arguments passed to `std::pair<KeyType, MappedType>` to insert.
//! @returns An @ref iterator to the newly-inserted value.
template <class... Args>
iterator emplace(Args&&... args)
{
return insert(ValueType{ std::forward<Args>(args)... });
}
//! Finds an element with a specific key.
//! @param key The key that identifies an element.
//! @returns An @ref iterator to the element, if found; end() otherwise.
iterator find(const Key& key)
{
if (empty())
{
return end();
}
size_t const hash = Hash{}(key);
LinkPair& pair = m_buckets[_bucket(hash)];
if (!pair.first)
{
return end();
}
Pred pred{};
for (Link* p = pair.first; p != pair.second->m_next; p = p->m_next)
{
if (pred(p->value.first, key))
{
return iterator(p, this);
}
}
// Not found
return end();
}
//! Finds an element with a specific key.
//! @param key The key that identifies an element.
//! @returns A @ref const_iterator to the element, if found; end() otherwise.
const_iterator find(const Key& key) const
{
if (empty())
{
return cend();
}
size_t const hash = Hash{}(key);
LinkPair& pair = m_buckets[_bucket(hash)];
if (!pair.first)
{
return cend();
}
Pred pred{};
Link* const bucketEnd = pair.second->m_next;
for (Link* p = pair.first; p != bucketEnd; p = p->m_next)
{
if (pred(p->value.first, key))
{
return const_iterator(p, this);
}
}
return cend();
}
//! Finds a range of elements matching the given key.
//! @param key The key that identifies an element.
//! @returns A `pair` of @ref iterator objects that define a range: the `first` iterator is the first item in the
//! range and the `second` iterator is immediately past the end of the range. If no elements exist with @p key,
//! `std::pair(end(), end())` is returned.
std::pair<iterator, iterator> equal_range(const Key& key)
{
if (empty())
{
return std::make_pair(end(), end());
}
size_t const hash = Hash{}(key);
LinkPair& pair = m_buckets[_bucket(hash)];
if (!pair.first)
{
return std::make_pair(end(), end());
}
Pred pred{};
Link* p = pair.first;
Link* const bucketEnd = pair.second->m_next;
for (; p != bucketEnd; p = p->m_next)
{
if (pred(p->value.first, key))
{
// Inner loop: terminates when no longer matches or bucket ends
Link* first = p;
p = p->m_next;
for (; p != bucketEnd; p = p->m_next)
{
if (!pred(p->value.first, key))
{
break;
}
}
return std::make_pair(iterator(first, this), iterator(p, this));
}
}
return std::make_pair(end(), end());
}
//! Finds a range of elements matching the given key.
//! @param key The key that identifies an element.
//! @returns A `pair` of @ref const_iterator objects that define a range: the `first` const_iterator is the first
//! item in the range and the `second` const_iterator is immediately past the end of the range. If no elements
//! exist with @p key, `std::pair(end(), end())` is returned.
std::pair<const_iterator, const_iterator> equal_range(const Key& key) const
{
if (empty())
{
return std::make_pair(cend(), cend());
}
size_t const hash = Hash{}(key);
LinkPair& pair = m_buckets[_bucket(hash)];
if (!pair.first)
{
return std::make_pair(cend(), cend());
}
Pred pred{};
Link* p = pair.first;
Link* const bucketEnd = pair.second->m_next;
for (; p != bucketEnd; p = p->m_next)
{
if (pred(p->value.first, key))
{
// Inner loop: terminates when no longer matches or bucket ends
Link* first = p;
p = p->m_next;
for (; p != bucketEnd; p = p->m_next)
{
if (!pred(p->value.first, key))
{
break;
}
}
return std::make_pair(const_iterator(first, this), const_iterator(p, this));
}
}
return std::make_pair(cend(), cend());
}
//! Returns the number of elements matching a specific key.
//! @param key The key to search for.
//! @returns The number of elements matching the given key.
size_t count(const Key& key) const
{
if (empty())
{
return 0;
}
size_t const hash = Hash{}(key);
LinkPair& pair = m_buckets[_bucket(hash)];
if (!pair.first)
{
return 0;
}
Pred pred{};
Link* p = pair.first;
Link* const bucketEnd = pair.second->m_next;
for (; p != bucketEnd; p = p->m_next)
{
if (pred(p->value.first, key))
{
// Inner loop: terminates when no longer matches or bucket ends
size_t count = 1;
p = p->m_next;
for (; p != bucketEnd; p = p->m_next)
{
if (!pred(p->value.first, key))
{
break;
}
++count;
}
return count;
}
}
return 0;
}
//! Removes an element by iterator.
//! @note Precondition: @p pos must be a valid const_iterator of `*this` and may not be end().
//! @param pos A @ref const_iterator to the element to remove.
//! @returns A @ref iterator to the element immediately following @p pos, or end() if no elements followed it.
iterator remove(const_iterator pos)
{
CARB_ASSERT(!empty());
pos.assertNotEnd();
pos.assertOwner(this);
Link* l = pos.m_where;
Link* next = l->m_next;
// Fix up bucket if necessary
LinkPair& pair = m_buckets[_bucket(Hash{}(l->value.first))];
if (pair.first == l)
{
if (pair.second == l)
{
// Empty bucket now
pair.first = pair.second = nullptr;
}
else
{
pair.first = next;
}
}
else if (pair.second == l)
{
pair.second = l->m_prev;
}
l->m_prev->m_next = l->m_next;
l->m_next->m_prev = l->m_prev;
l->m_next = l->m_prev = nullptr;
--m_size;
// Destruct value
l->value.~ValueType();
return iterator(next, this);
}
//! Removes an element by reference.
//! @note Precondition: @p value must be contained in `*this`.
//! @param value The element to remove.
//! @returns @p value for convenience.
T& remove(T& value)
{
Link* l = _link(value);
if (l->isContained())
{
CARB_ASSERT(!empty());
CARB_ASSERT(_listfind(value) != _end());
// Fix up bucket if necessary
LinkPair& pair = m_buckets[_bucket(Hash{}(l->value.first))];
if (pair.first == l)
{
if (pair.second == l)
{
// Empty bucket now
pair.first = pair.second = nullptr;
}
else
{
pair.first = l->m_next;
}
}
else if (pair.second == l)
{
pair.second = l->m_prev;
}
l->m_prev->m_next = l->m_next;
l->m_next->m_prev = l->m_prev;
l->m_next = l->m_prev = nullptr;
--m_size;
// Destruct value
l->value.~ValueType();
}
return value;
}
//! Removes all elements matching a specific key.
//! @param key The key to search for.
//! @returns The number of elements that were removed.
size_t remove(const Key& key)
{
size_t count{ 0 };
auto pair = equal_range(key);
while (pair.first != pair.second)
{
remove(pair.first++);
++count;
}
return count;
}
//! Swaps the contents of `*this` with another IntrusiveUnorderedMultimap.
//! @param other The other IntrusiveUnorderedMultimap to swap with.
void swap(IntrusiveUnorderedMultimap& other) noexcept
{
if (this != std::addressof(other))
{
// Fix up the end iterators first
Link *&lhead = _head()->m_prev, *<ail = _tail()->m_next;
Link *&rhead = other._head()->m_prev, *&rtail = other._tail()->m_next;
lhead = ltail = other._end();
rhead = rtail = _end();
// Now swap everything else
std::swap(m_buckets, other.m_buckets);
std::swap(m_bucketCount, other.m_bucketCount);
std::swap(_end()->m_next, other._end()->m_next);
std::swap(_end()->m_prev, other._end()->m_prev);
std::swap(m_size, other.m_size);
std::swap(m_maxLoadFactor, other.m_maxLoadFactor);
}
}
//! Returns the number of buckets.
//! @returns The number of buckets.
size_t bucket_count() const noexcept
{
return m_bucketCount;
}
//! Returns the maximum number of buckets.
//! @returns The maximum number of buckets.
size_t max_bucket_count() const noexcept
{
return size_t(-1);
}
//! Returns the bucket index for a specific key.
//! @param key The key to hash.
//! @returns A bucket index in the range `[0, bucket_count())`.
size_t bucket(const Key& key) const
{
return _bucket(Hash{}(key));
}
//! Returns the average number of elements per bucket.
//! @returns The average number of elements per bucket.
float load_factor() const
{
return bucket_count() ? float(size()) / float(bucket_count()) : 0.f;
}
//! Returns the max load factor for `*this`.
//! @returns The max load factor for `*this`. The default is 1.0.
float max_load_factor() const noexcept
{
return m_maxLoadFactor;
}
//! Sets the maximum load factor for `*this`.
//! @note Precondition: @p ml must be greater than 0.
//! @note Changes do not take effect until the hash table is re-generated.
//! @param ml The new maximum load factor for `*this`.
void max_load_factor(float ml)
{
CARB_ASSERT(ml > 0.f);
m_maxLoadFactor = ml;
}
//! Reserves space for at least the specified number of elements and re-generates the hash table.
//! @param count The minimum number of elements to reserve space for.
void reserve(size_t count)
{
rehash(size_t(std::ceil(count / max_load_factor())));
}
//! Reserves at least the specified number of buckets and re-generates the hash table.
//! @param buckets The minimum number of buckets required.
void rehash(size_t buckets)
{
if (buckets > m_bucketCount)
{
constexpr static size_t kMinBuckets(8);
static_assert(carb::cpp::has_single_bit(kMinBuckets), "Invalid assumption");
buckets = carb::cpp::bit_ceil(::carb_max(buckets, kMinBuckets));
CARB_ASSERT(carb::cpp::has_single_bit(buckets));
m_buckets.reset(new LinkPair[buckets]);
memset(m_buckets.get(), 0, sizeof(LinkPair) * buckets);
m_bucketCount = buckets;
// Walk through the list backwards and rehash everything. Things that have equal keys and are already
// grouped together will remain so.
Link* cur = _tail();
m_list.m_prev = m_list.m_next = _end();
Link* next;
Hash hasher;
for (; cur != _end(); cur = next)
{
next = cur->m_prev;
LinkPair& bucket = m_buckets[_bucket(hasher(cur->value.first))];
if (bucket.first)
{
// Insert in front of whatever was in the bucket
cur->m_prev = bucket.first->m_prev;
cur->m_next = bucket.first;
cur->m_prev->m_next = cur;
cur->m_next->m_prev = cur;
bucket.first = cur;
}
else
{
// Insert at the front of the list and the beginning of the bucket
cur->m_prev = _end();
cur->m_next = _head();
cur->m_prev->m_next = cur;
cur->m_next->m_prev = cur;
bucket.first = bucket.second = cur;
}
}
}
}
private:
struct LinkPair
{
Link* first;
Link* second;
};
std::unique_ptr<LinkPair[]> m_buckets{};
size_t m_bucketCount{ 0 };
BaseLink m_list;
size_t m_size{ 0 };
float m_maxLoadFactor{ 1.f };
size_t _bucket(size_t hash) const
{
// bucket count is always a power of 2
return hash & (m_bucketCount - 1);
}
Link* _listfind(T& value) const
{
Link* find = _link(value);
Link* p = _head();
for (; p != _end(); p = p->m_next)
{
if (p == find)
{
return p;
}
}
return _end();
}
static Link* _link(T& value) noexcept
{
return std::addressof(value.*U);
}
static T& _value(Link& l) noexcept
{
// Need to calculate the offset of our link member which will allow adjusting the pointer to where T is.
// This will not work if T uses virtual inheritance. Also, offsetof() cannot be used because we have a pointer
// to the member
size_t offset = size_t(reinterpret_cast<uint8_t*>(&(((T*)0)->*U)));
return *reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(std::addressof(l)) - offset);
}
static const T& _value(const Link& l) noexcept
{
// Need to calculate the offset of our link member which will allow adjusting the pointer to where T is.
// This will not work if T uses virtual inheritance. Also, offsetof() cannot be used because we have a pointer
// to the member
size_t offset = size_t(reinterpret_cast<uint8_t*>(&(((T*)0)->*U)));
return *reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(std::addressof(l)) - offset);
}
constexpr Link* _head() const noexcept
{
return const_cast<Link*>(m_list.m_next);
}
constexpr Link* _tail() const noexcept
{
return const_cast<Link*>(m_list.m_prev);
}
constexpr Link* _end() const noexcept
{
return static_cast<Link*>(const_cast<BaseLink*>(&m_list));
}
};
} // namespace container
} // namespace carb
|
omniverse-code/kit/include/carb/process/Util.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite process utilities.
#pragma once
#include "../Defines.h"
#include "../extras/ScopeExit.h"
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#elif CARB_POSIX
# include <unistd.h>
# include <fcntl.h>
# if CARB_PLATFORM_MACOS
# include <sys/errno.h>
# include <sys/sysctl.h>
# endif
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
#include <vector>
namespace carb
{
//! Namespace for Carbonite process utilities.
namespace process
{
/** The type for a process ID. */
using ProcessId = uint32_t;
#if CARB_PLATFORM_WINDOWS
static_assert(sizeof(ProcessId) >= sizeof(DWORD), "ProcessId type is too small");
#elif CARB_POSIX
static_assert(sizeof(ProcessId) >= sizeof(pid_t), "ProcessId type is too small");
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
/** The printf format macro to print a process ID. */
#define OMNI_PRIpid PRIu32
/** The printf format macro to print a process ID in hexadecimal. */
#define OMNI_PRIxpid PRIx32
} // namespace process
/**
* Namespace for utilities that operate on the current thread specifically.
*/
namespace this_process
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
# if CARB_PLATFORM_WINDOWS
// Returns the process creation time as a Windows FILETIME (number of 100ns units since Jan 1, 1600 GMT).
inline uint64_t getCreationTime()
{
CARBWIN_FILETIME creationTime{}, exitTime{}, kernelTime{}, userTime{};
BOOL b = ::GetProcessTimes(::GetCurrentProcess(), (LPFILETIME)&creationTime, (LPFILETIME)&exitTime,
(LPFILETIME)&kernelTime, (LPFILETIME)&userTime);
CARB_ASSERT(b);
CARB_UNUSED(b);
return (uint64_t(creationTime.dwHighDateTime) << 32) + creationTime.dwLowDateTime;
}
// Converts a time_t (Unix epoch - seconds since Jan 1, 1970 GMT) to a Windows FILETIME
// (100ns units since Jan 1, 1600 GMT).
inline uint64_t timeTtoFileTime(time_t val)
{
// Multiply by 10 million to convert to 100ns units, then add a constant that is the number of 100ns units between
// Jan 1, 1600 GMT and Jan 1, 1970 GMT
return uint64_t(val) * 10'000'000 + 116444736000000000;
}
// Parses the system startup time from the Windows event log as a Unix time (seconds since Jan 1, 1970 GMT).
// Adapted from https://docs.microsoft.com/en-us/windows/win32/eventlog/querying-for-event-source-messages
// Another possibility would be to use WMI's LastBootupTime, but it is affected by hibernation and clock sync.
inline time_t parseSystemStartupTime()
{
// Open the system event log
HANDLE hEventLog = ::OpenEventLogW(NULL, L"System");
CARB_ASSERT(hEventLog);
if (!hEventLog)
return time_t(0);
// Make sure to close the handle when we're finished
CARB_SCOPE_EXIT
{
CloseEventLog(hEventLog);
};
constexpr static size_t kBufferSize = 65536; // Start with a fairly large buffer
std::vector<uint8_t> bytes(kBufferSize);
// A lambda that will find the "Event Log Started" record from a buffer
auto findRecord = [](const uint8_t* bytes, DWORD bytesRead) -> const CARBWIN_EVENTLOGRECORD* {
constexpr static wchar_t kDesiredSourceName[] = L"EventLog";
constexpr static DWORD kDesiredEventId = 6005; // Event Log Started
const uint8_t* const end = bytes + bytesRead;
while (bytes < end)
{
auto record = reinterpret_cast<const CARBWIN_EVENTLOGRECORD*>(bytes);
// Check the SourceName (first field after the event log record)
auto SourceName = reinterpret_cast<const WCHAR*>(bytes + sizeof(CARBWIN_EVENTLOGRECORD));
if (0 == memcmp(SourceName, kDesiredSourceName, sizeof(kDesiredSourceName)))
{
if ((record->EventID & 0xFFFF) == kDesiredEventId)
{
// Found it!
return record;
}
}
bytes += record->Length;
}
return nullptr;
};
for (;;)
{
DWORD dwBytesRead, dwMinimumBytesNeeded;
if (!ReadEventLogW(hEventLog, CARBWIN_EVENTLOG_SEQUENTIAL_READ | CARBWIN_EVENTLOG_BACKWARDS_READ, 0,
bytes.data(), (DWORD)bytes.size(), &dwBytesRead, &dwMinimumBytesNeeded))
{
DWORD err = GetLastError();
if (err == CARBWIN_ERROR_INSUFFICIENT_BUFFER)
{
// Insufficient buffer.
bytes.resize(dwMinimumBytesNeeded);
}
else
{
// Error
return time_t(0);
}
}
else
{
if (auto record = findRecord(bytes.data(), dwBytesRead))
{
// Found the record!
return time_t(record->TimeGenerated);
}
}
}
}
// Gets the system startup time as a Unix time (seconds since Jan 1, 1970 GMT).
inline time_t getSystemStartupTime()
{
static time_t systemStartupTime = parseSystemStartupTime();
return systemStartupTime;
}
# endif
} // namespace detail
#endif
/**
* Returns the ID of the currently executing process.
* @returns The current ID of the process.
*/
inline process::ProcessId getId()
{
#if CARB_PLATFORM_WINDOWS
return GetCurrentProcessId();
#elif CARB_POSIX
return getpid();
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Get the ID of the currently executing process.
* @note Linux: This value is cached, so this can be unsafe if you are using fork() or clone() without calling exec()
* after. This should be safe if you're only using @ref carb::launcher::ILauncher to launch processes.
* @returns The current ID of the process.
*/
inline process::ProcessId getIdCached()
{
#if CARB_PLATFORM_WINDOWS
return GetCurrentProcessId();
#elif CARB_POSIX
// glibc (since 2.25) does not cache the result of getpid() due to potential
// edge cases where a fork() syscall was done without the glibc wrapper, so
// we'll cache it here.
static pid_t cached = getpid();
return cached;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Returns an ID uniquely identifying this process at least for the uptime of the machine.
*
* Process IDs aren't unique; they can be reused. They are great at identifying a process at a given point in time, but
* not on a timeline that includes the future and the past. That's what this function seeks to do: give an ultra-high
* probability that the generated ID has never been in use on this system since the last restart.
*
* This function accomplishes this by combining PID with process creation time.
*
* On Windows, 30 bits are available for process IDs and the remaining 34 bits are used for the timestamp in 32ms units.
* For a collision to happen, either 17.4 years would have to pass for rollover or a process would have to start, finish
* and the process ID be reused by the system within the same 32ms unit.
*
* For Linux, up to 22 bits are available for process IDs (but most systems use the default of 15 bits). The remaining
* 42 bits are used for the timestamp. The timestamp is based on the kernel frequency (ticks per second). A kernel
* frequency of 100 will result in using 10ms units for the timestamp and the rollover period is 1,394 years. The
* maximum resolution used for the timer will result in using 1 ms units for the timestamp and a rollover period of
* 139.4 years. For a collision to happen, either the rollover period would have to pass or a process would have to
* start, finish and the process ID be reused by the system within the timestamp unit (1 ms - 10 ms).
*
* @warning This function is frozen to maintain @rstref{ABI compatibility <abi-compatibility>} over plugins that may be
* built at different times. Do not change the results of this function, ever! Instead, add a different function.
*
* @note The first call to this function within a module may be slow as additional information is obtained from the
* system. That information is then cached and subsequent calls within the module are very fast.
*
* @returns A unique identifier for this process from the last restart until the system is rebooted.
*/
inline uint64_t getUniqueId()
{
#if CARB_PLATFORM_WINDOWS
// See: https://stackoverflow.com/questions/17868218/what-is-the-maximum-process-id-on-windows
// Range 00000000 - FFFFFFFC, but aligned to 4 bytes, so 30 significant bits
const static DWORD pid = GetCurrentProcessId();
// creationTime is the number of 32ms units since system startup until this process started.
// 34 bits of 32ms units gives us ~17.4 years of time until rollover. It is highly unlikely that a process ID would
// be reused by the system within the same 32ms timeframe that the process started.
const static uint64_t creationTime =
((detail::getCreationTime() - detail::timeTtoFileTime(detail::getSystemStartupTime())) / 320'000) &
0x3ffffffff; // mask
CARB_ASSERT((pid & 0x3) == 0); // Test assumption
return (uint64_t(pid) << 32) + creationTime;
#elif CARB_PLATFORM_LINUX
// We need to retrieve this from /proc. Unfortunately, because of fork(), the PID can change but if the PID changes
// then the creation time will change too. According to https://man7.org/linux/man-pages/man5/proc.5.html the
// maximum value for a pid is 1<<22 or ~4 million. That gives us 42 bits for timing information.
// NOTE: This is not thread-safe static initialization. However, this is okay because every thread in a process will
// arrive at the same value, so it doesn't matter if multiple threads write the same value.
static uint64_t cachedValue{};
// Read the pid every time as it can change if we fork().
process::ProcessId pid = getId();
if (CARB_UNLIKELY((cachedValue >> 42) != pid))
{
CARB_ASSERT((pid & 0xffc00000) == 0); // Only 22 bits are used for PIDs
// PID changed (or first time). Read the process start time from /proc
int fd = open("/proc/self/stat", O_RDONLY);
CARB_FATAL_UNLESS(fd != -1, "Failed to open /proc/self/stat: {%d/%s}", errno, strerror(errno));
char buf[4096];
ssize_t bytes = CARB_RETRY_EINTR(read(fd, buf, CARB_COUNTOF(buf) - 1));
CARB_FATAL_UNLESS(bytes >= 0, "Failed to read from /proc/self/stat");
CARB_ASSERT(size_t(bytes) < (CARB_COUNTOF(buf) - 1)); // We should have read everything
close(fd);
buf[bytes] = '\0';
unsigned long long starttime; // time (in clock ticks) since system boot when the process started
// See https://man7.org/linux/man-pages/man5/proc.5.html
// the starttime value is the 22nd value so skip all of the other values.
// Someone evil (read: me when testing) could have a space or parens as part of the binary name. So look for the
// last close parenthesis and start from there. Hopefully no other fields get added to /proc/[pid]/stat that use
// parentheses.
const char* start = strrchr(buf, ')');
CARB_ASSERT(start);
int match = sscanf(
start, ") %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %*d %*d %llu", &starttime);
CARB_FATAL_UNLESS(match == 1, "Failed to parse process start time from /proc/self/stat");
static long ticksPerSec = sysconf(_SC_CLK_TCK);
long divisor;
if (ticksPerSec <= 0)
divisor = 1;
else if (ticksPerSec < 1000)
divisor = ticksPerSec;
else
divisor = ticksPerSec / 1000;
// Compute the cached value.
cachedValue = (uint64_t(pid) << 42) + ((starttime / divisor) & 0x3ffffffffff);
}
CARB_ASSERT(cachedValue != 0);
return cachedValue;
#elif CARB_PLATFORM_MACOS
// MacOS has a maximum process ID of 99998 and a minimum of 100. This can fit into 17 bits.
// The remaining 47 bits are used for the process creation timestamp.
static uint64_t cachedValue{};
process::ProcessId pid = getId();
if (CARB_UNLIKELY((cachedValue >> 47) != pid))
{
struct kinfo_proc info;
struct timeval startTime;
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid };
size_t length = sizeof(info);
int result;
CARB_ASSERT((pid & 0xfffe0000) == 0); // Only 17 bits are used for PIDs.
// retrieve the process start time.
memset(&info, 0, sizeof(info));
result = sysctl(mib, CARB_COUNTOF(mib), &info, &length, nullptr, 0);
CARB_FATAL_UNLESS(result == 0, "failed to retrieve the process information.");
startTime = info.kp_proc.p_starttime;
// create the unique ID by converting the process creation time to a number of 10ms units
// then adding in the process ID in the high bits.
cachedValue = (((((uint64_t)startTime.tv_sec * 1'000'000) + startTime.tv_usec) / 10'000) & 0x7fffffffffffull) +
(((uint64_t)pid) << 47);
}
CARB_ASSERT(cachedValue != 0);
return cachedValue;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
} // namespace this_process
} // namespace carb
|
omniverse-code/kit/include/carb/audio/AudioUtils.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Inline utility functions for audio processing.
*/
#pragma once
#ifndef DOXYGEN_SHOULD_SKIP_THIS
# define _USE_MATH_DEFINES
#endif
#include "../Framework.h"
#include "../logging/Log.h"
#include "../math/Util.h"
#include "AudioTypes.h"
#include "IAudioData.h"
#include "IAudioPlayback.h"
#include "IAudioUtils.h"
#include "IAudioCapture.h"
#include <atomic>
#include <limits.h>
#include <math.h>
#include <string.h>
#if CARB_PLATFORM_WINDOWS
# define strdup _strdup
#endif
namespace carb
{
namespace audio
{
/** converts an angle in degrees to an angle in radians.
*
* @param[in] degrees the angle in degrees to be converted.
* @returns the requested angle in radians.
*/
template <typename T>
constexpr float degreesToRadians(T degrees)
{
return degrees * (float(M_PI) / 180.f);
}
/** converts an angle in degrees to an angle in radians.
*
* @param[in] degrees the angle in degrees to be converted.
* @returns the requested angle in radians.
*/
constexpr double degreesToRadians(double degrees)
{
return degrees * (M_PI / 180.0);
}
/** converts an angle in radians to an angle in degrees.
*
* @param[in] radians the angle in radians to be converted.
* @returns the requested angle in degrees.
*/
template <typename T>
constexpr float radiansToDegrees(T radians)
{
return (radians * (180.f / float(M_PI)));
}
/** converts an angle in radians to an angle in degrees.
*
* @param[in] radians the angle in radians to be converted.
* @returns the requested angle in degrees.
*/
constexpr double radiansToDegrees(double radians)
{
return (radians * (180.0 / M_PI));
}
/** counts the number of set bits in a bit flag set.
*
* @param[in] value_ the value to count set bits in.
* @returns the number of set bits in the given value.
*/
template <typename T>
size_t getSetBitCount(T value_)
{
return math::popCount(value_);
}
/** Retrieves the total number of speakers for a given speaker mode.
*
* @param[in] mode the speaker mode to retrieve the speaker count for.
* @returns the number of speakers expected for the requested speaker mode.
* @returns 0 if an unknown speaker count is passed in.
* @returns 0 if @ref kSpeakerModeDefault is passed in.
*/
constexpr size_t getSpeakerCountForMode(SpeakerMode mode)
{
switch (mode)
{
case kSpeakerModeDefault:
return 0;
case kSpeakerModeMono:
return 1;
case kSpeakerModeStereo:
return 2;
case kSpeakerModeQuad:
return 4;
case kSpeakerModeFourPointOne:
return 5;
case kSpeakerModeFivePointOne:
return 6;
case kSpeakerModeSixPointOne:
return 7;
case kSpeakerModeSevenPointOne:
return 8;
case kSpeakerModeNinePointOne:
return 10;
case kSpeakerModeSevenPointOnePointFour:
return 12;
case kSpeakerModeNinePointOnePointFour:
return 14;
case kSpeakerModeNinePointOnePointSix:
return 16;
default:
return getSetBitCount(mode);
}
}
/** retrieves a default speaker mode for a given channel count.
* @param[in] channels the number of channels to get the default speaker mode for.
* @returns a standard speaker mode with the requested channel count.
* @retval kSpeakerModeDefault if no standard speaker mode is defined for the given channel
* count.
*/
constexpr SpeakerMode getSpeakerModeForCount(size_t channels)
{
switch (channels)
{
case 1:
return kSpeakerModeMono;
case 2:
return kSpeakerModeStereo;
case 3:
return kSpeakerModeTwoPointOne;
case 4:
return kSpeakerModeQuad;
case 5:
return kSpeakerModeFourPointOne;
case 6:
return kSpeakerModeFivePointOne;
case 7:
return kSpeakerModeSixPointOne;
case 8:
return kSpeakerModeSevenPointOne;
case 10:
return kSpeakerModeNinePointOne;
case 12:
return kSpeakerModeSevenPointOnePointFour;
case 14:
return kSpeakerModeNinePointOnePointFour;
case 16:
return kSpeakerModeNinePointOnePointSix;
default:
return kSpeakerModeDefault;
}
}
/** calculates a set of speaker flags for a channel count.
*
* @param[in] channels the number of channels to calculate the speaker flags for. This
* should be less than or equal to @ref kMaxChannels.
* @returns a set of speaker flags as a SpeakerMode value representing the number of channels
* that was requested. Note that this will not necessarily be a standard speaker
* mode layout for the given channel count. This should only be used in cases where
* getSpeakerModeForCount() returns @ref kSpeakerModeDefault and a speaker mode value
* other than kSpeakerModeDefault is strictly needed.
*/
constexpr SpeakerMode getSpeakerFlagsForCount(size_t channels)
{
if (channels >= kMaxChannels)
return 0xffffffffffffffffull;
return (1ull << channels) - 1;
}
/** retrieves a speaker name from a single speaker mode flag.
*
* @param[in] flag a single speaker flag to convert to a speaker name. This must be one of
* the fSpeakerFlag* speaker flags.
* @returns one of the @ref Speaker names if converted successfully.
* @retval Speaker::eCount if an invalid speaker flag is passed in.
*/
constexpr Speaker getSpeakerFromSpeakerFlag(SpeakerMode flag)
{
switch (flag)
{
case fSpeakerFlagFrontLeft:
return Speaker::eFrontLeft;
case fSpeakerFlagFrontRight:
return Speaker::eFrontRight;
case fSpeakerFlagFrontCenter:
return Speaker::eFrontCenter;
case fSpeakerFlagLowFrequencyEffect:
return Speaker::eLowFrequencyEffect;
case fSpeakerFlagSideLeft:
return Speaker::eSideLeft;
case fSpeakerFlagSideRight:
return Speaker::eSideRight;
case fSpeakerFlagBackLeft:
return Speaker::eBackLeft;
case fSpeakerFlagBackRight:
return Speaker::eBackRight;
case fSpeakerFlagBackCenter:
return Speaker::eBackCenter;
case fSpeakerFlagTopFrontLeft:
return Speaker::eTopFrontLeft;
case fSpeakerFlagTopFrontRight:
return Speaker::eTopFrontRight;
case fSpeakerFlagTopBackLeft:
return Speaker::eTopBackLeft;
case fSpeakerFlagTopBackRight:
return Speaker::eTopBackRight;
case fSpeakerFlagFrontLeftWide:
return Speaker::eFrontLeftWide;
case fSpeakerFlagFrontRightWide:
return Speaker::eFrontRightWide;
case fSpeakerFlagTopLeft:
return Speaker::eTopLeft;
case fSpeakerFlagTopRight:
return Speaker::eTopRight;
default:
return Speaker::eCount;
}
}
/** retrieves an indexed speaker name from a speaker mode mask.
*
* @param[in] channelMask the channel mask to retrieve one of the speaker names from. This must
* be a combination of one or more of the fSpeakerFlag* flags.
* @param[in] index the zero based index of the speaker name to retrieve. This indicates
* which of the set speaker bits in the channel mask will be converted
* and returned.
* @returns the index of the speaker name of the @p index-th speaker set in the given channel
* mask. This may be cast to a @ref Speaker name if it is less than
* @ref Speaker::eCount. If it is greater than or equal to @ref Speaker::eCount, this
* would represent a custom unnamed speaker in the channel mask. This would be the
* index of the channel's sample in each frame of output data for the given channel
* mask.
* @retval kInvalidSpeakerName if the index is out of range of the number of speakers in
* the given channel mask.
*/
constexpr size_t getSpeakerFromSpeakerMode(SpeakerMode channelMask, size_t index)
{
// no bits set in the channel mask -> nothing to do => fail.
if (channelMask == 0)
return kInvalidSpeakerName;
SpeakerMode bit = 1;
size_t i = 0;
// walk through the channel mask searching for set bits.
for (; bit != 0; bit <<= 1, i++)
{
// no speaker set for this bit => skip it.
if ((channelMask & bit) == 0)
continue;
if (index == 0)
return i;
index--;
}
return kInvalidSpeakerName;
}
/**
* retrieves the number of bits per channel for a given sample format.
*
* @param[in] fmt the sample format to retrieve the bit count for. This may be any of the
* SampleFormat::ePcm* formats. There is no defined bit count for the raw
* and default formats.
* @returns the number of bits per sample associated with the requested sample format.
*/
constexpr size_t sampleFormatToBitsPerSample(SampleFormat fmt)
{
switch (fmt)
{
case SampleFormat::ePcm8:
return 8;
case SampleFormat::ePcm16:
return 16;
case SampleFormat::ePcm24:
return 24;
case SampleFormat::ePcm32:
return 32;
case SampleFormat::ePcmFloat:
return 32;
default:
return 0;
}
}
/** converts a bits per sample count to an integer PCM sample format.
*
* @param[in] bps the bits per sample to convert.
* @returns the integer PCM sample format that corresponds to the requested bit count.
* @retval SampleFormat::eCount if no supported sample format matches the requested
* bit count.
*/
constexpr SampleFormat bitsPerSampleToIntegerPcmSampleFormat(size_t bps)
{
switch (bps)
{
case 8:
return SampleFormat::ePcm8;
case 16:
return SampleFormat::ePcm16;
case 24:
return SampleFormat::ePcm24;
case 32:
return SampleFormat::ePcm32;
default:
return SampleFormat::eCount;
}
}
/**
* converts a time in milliseconds to a frame count.
*
* @param[in] timeInMilliseconds the time in milliseconds to be converted to a frame count.
* @param[in] frameRate the frame rate of the audio that needs a frame count calculated.
* @returns the minimum number of frames required to cover the requested number of milliseconds
* at the requested frame rate. Note that if the time isn't exactly divisible by
* the frame rate, a partial frame may be truncated.
*/
constexpr size_t millisecondsToFrames(size_t timeInMilliseconds, size_t frameRate)
{
return (frameRate * timeInMilliseconds) / 1000;
}
/**
* converts a time in microseconds to a frame count.
*
* @param[in] timeInMicroseconds the time in microseconds to be converted to a frame count.
* @param[in] frameRate the frame rate of the audio that needs a frame count calculated.
* @returns the minimum number of frames required to cover the requested number of microseconds
* at the requested frame rate. Note that if the time isn't exactly divisible by
* the frame rate, a partial frame may be truncated.
*/
constexpr size_t microsecondsToFrames(size_t timeInMicroseconds, size_t frameRate)
{
return (frameRate * timeInMicroseconds) / 1000000;
}
/**
* converts a time in milliseconds to a frame count.
*
* @param[in] timeInMilliseconds the time in milliseconds to be converted to a frame count.
* @param[in] format the format information block for the sound data this time is
* being converted for.
* @returns the minimum number of frames required to cover the requested number of milliseconds
* at the requested frame rate. Note that if the time isn't exactly divisible by
* the frame rate, a partial frame may be truncated.
*/
inline size_t millisecondsToFrames(size_t timeInMilliseconds, const SoundFormat* format)
{
return millisecondsToFrames(timeInMilliseconds, format->frameRate);
}
/**
* converts a time in microseconds to a frame count.
*
* @param[in] timeInMicroseconds the time in microseconds to be converted to a frame count.
* @param[in] format the format information block for the sound data this time is
* being converted for.
* @returns the minimum number of frames required to cover the requested number of microseconds
* at the requested frame rate. Note that if the time isn't exactly divisible by
* the frame rate, a partial frame may be truncated.
*/
inline size_t microsecondsToFrames(size_t timeInMicroseconds, const SoundFormat* format)
{
return microsecondsToFrames(timeInMicroseconds, format->frameRate);
}
/**
* converts a time in milliseconds to a byte count.
*
* @param[in] timeInMilliseconds the time in milliseconds to be converted to a frame count.
* @param[in] frameRate the frame rate of the audio that needs a frame count calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24,
* or 32. This does not properly handle byte offset calculations for
* compressed audio formats.
* @returns the approximate number of bytes of audio data required to fill the requested number
* of milliseconds. Note that this will not be an exact value because the data format
* may not divide evenly into the requested number of milliseconds.
*/
constexpr size_t millisecondsToBytes(size_t timeInMilliseconds, size_t frameRate, size_t channels, size_t bps)
{
return (timeInMilliseconds * frameRate * channels * bps) / (1000 * CHAR_BIT);
}
/**
* converts a time in microseconds to a byte count.
*
* @param[in] timeInMicroseconds the time in microseconds to be converted to a frame count.
* @param[in] frameRate the frame rate of the audio that needs a frame count calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24,
* or 32. This does not properly handle byte offset calculations for
* compressed audio formats.
* @returns the approximate number of bytes of audio data required to fill the requested number
* of microseconds. Note that this will not be an exact value because the data format
* may not divide evenly into the requested number of microseconds.
*/
constexpr size_t microsecondsToBytes(size_t timeInMicroseconds, size_t frameRate, size_t channels, size_t bps)
{
return (timeInMicroseconds * frameRate * channels * bps) / (1000000 * CHAR_BIT);
}
/**
* converts a time in milliseconds to a byte count.
*
* @param[in] timeInMilliseconds the time in milliseconds to be converted to a frame count.
* @param[in] frameRate the frame rate of the audio that needs a frame count calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format for the data. This must be a PCM sample format.
* @returns the approximate number of bytes of audio data required to fill the requested number
* of milliseconds. Note that this will not be an exact value because the data format
* may not divide evenly into the requested number of milliseconds.
*/
constexpr size_t millisecondsToBytes(size_t timeInMilliseconds, size_t frameRate, size_t channels, SampleFormat format)
{
return millisecondsToBytes(timeInMilliseconds, frameRate, channels, sampleFormatToBitsPerSample(format));
}
/**
* converts a time in microseconds to a byte count.
*
* @param[in] timeInMicroseconds the time in microseconds to be converted to a frame count.
* @param[in] frameRate the frame rate of the audio that needs a frame count calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format for the data. This must be a PCM sample format.
* @returns the approximate number of bytes of audio data required to fill the requested number
* of microseconds. Note that this will not be an exact value because the data format
* may not divide evenly into the requested number of microseconds.
*/
constexpr size_t microsecondsToBytes(size_t timeInMicroseconds, size_t frameRate, size_t channels, SampleFormat format)
{
return microsecondsToBytes(timeInMicroseconds, frameRate, channels, sampleFormatToBitsPerSample(format));
}
/**
* converts a time in milliseconds to a byte count.
*
* @param[in] timeInMilliseconds the time in milliseconds to be converted to a frame count.
* @param[in] format the format information block for the sound data this time is
* being converted for.
* @returns the approximate number of bytes of audio data required to fill the requested number
* of milliseconds. Note that this will not be an exact value because the data format
* may not divide evenly into the requested number of milliseconds.
*/
inline size_t millisecondsToBytes(size_t timeInMilliseconds, const SoundFormat* format)
{
return millisecondsToBytes(timeInMilliseconds, format->frameRate, format->channels, format->bitsPerSample);
}
/**
* converts a time in microseconds to a byte count.
*
* @param[in] timeInMicroseconds the time in microseconds to be converted to a frame count.
* @param[in] format the format information block for the sound data this time is
* being converted for.
* @returns the approximate number of bytes of audio data required to fill the requested number
* of microseconds. Note that this will not be an exact value because the data format
* may not divide evenly into the requested number of microseconds.
*/
inline size_t microsecondsToBytes(size_t timeInMicroseconds, const SoundFormat* format)
{
return microsecondsToBytes(timeInMicroseconds, format->frameRate, format->channels, format->bitsPerSample);
}
/**
* converts a frame count at a given frame rate to a time in milliseconds.
*
* @param[in] frames the frame count to be converted.
* @param[in] frameRate the frame rate of the audio that needs a time calculated.
* @returns the time in milliseconds associated with the given number of frames playing at the
* requested frame rate.
*/
constexpr size_t framesToMilliseconds(size_t frames, size_t frameRate)
{
return (frames * 1000) / frameRate;
}
/**
* converts a frame count at a given frame rate to a time in microseconds.
*
* @param[in] frames the frame count to be converted.
* @param[in] frameRate the frame rate of the audio that needs a time calculated.
* @returns the time in microseconds associated with the given number of frames playing at the
* requested frame rate.
*/
constexpr size_t framesToMicroseconds(size_t frames, size_t frameRate)
{
return (frames * 1000000) / frameRate;
}
/**
* converts a frame count at a given frame rate to a time in milliseconds.
*
* @param[in] frames the frame count to be converted.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the time in milliseconds associated with the given number of frames playing at the
* requested frame rate.
*/
inline size_t framesToMilliseconds(size_t frames, const SoundFormat* format)
{
return framesToMilliseconds(frames, format->frameRate);
}
/**
* converts a frame count at a given frame rate to a time in microseconds.
*
* @param[in] frames the frame count to be converted.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the time in microseconds associated with the given number of frames playing at the
* requested frame rate.
*/
inline size_t framesToMicroseconds(size_t frames, const SoundFormat* format)
{
return framesToMicroseconds(frames, format->frameRate);
}
/**
* converts a frame count to a byte offset.
*
* @param[in] frames the frame count to be converted to a byte count.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24, or
* 32. This does not properly handle byte offset calculations for compressed
* audio formats.
* @returns the calculated byte offset to the start of the requested frame of audio data.
*/
constexpr size_t framesToBytes(size_t frames, size_t channels, size_t bps)
{
return (frames * channels * bps) / CHAR_BIT;
}
/**
* converts a frame count to a byte offset.
*
* @param[in] frames the frame count to be converted to a byte count.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format of the data. This must be a PCM sample format.
* @returns the calculated byte offset to the start of the requested frame of audio data.
*/
constexpr size_t framesToBytes(size_t frames, size_t channels, SampleFormat format)
{
return framesToBytes(frames, channels, sampleFormatToBitsPerSample(format));
}
/**
* converts a frame count to a byte offset.
*
* @param[in] frames the frame count to be converted to a byte count.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the calculated byte offset to the start of the requested frame of audio data.
*/
inline size_t framesToBytes(size_t frames, const SoundFormat* format)
{
return framesToBytes(frames, format->channels, format->bitsPerSample);
}
/**
* converts a byte count to a frame count.
*
* @param[in] bytes the number of bytes to be converted to a frame count. Note that this byte
* count is expected to be frame aligned. If it is not frame aligned, the
* return value will be the offset for the frame that includes the requested
* byte offset.
* @param[in] channels the number of channels in the audio data format.
* This may not be 0.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24, or
* 32. This does not properly handle byte offset calculations for compressed
* audio formats.
* This may not be 0.
* @returns the calculated frame offset that will contain the requested byte offset.
*/
constexpr size_t bytesToFrames(size_t bytes, size_t channels, size_t bps)
{
return (bytes * CHAR_BIT) / (channels * bps);
}
/**
* converts a byte count to a frame count.
*
* @param[in] bytes the number of bytes to be converted to a frame count. Note that this byte
* count is expected to be frame aligned. If it is not frame aligned, the
* return value will be the offset for the frame that includes the requested
* byte offset.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format of the data. This must be a PCM sample format.
* @returns the calculated frame offset that will contain the requested byte offset.
*/
constexpr size_t bytesToFrames(size_t bytes, size_t channels, SampleFormat format)
{
size_t bps = sampleFormatToBitsPerSample(format);
if (bps == 0)
{
CARB_LOG_ERROR("attempting to convert bytes to frames in a variable bitrate format (%d), return 0", int(format));
return 0;
}
return bytesToFrames(bytes, channels, bps);
}
/**
* converts a byte count to a frame count.
*
* @param[in] bytes the number of bytes to be converted to a frame count. Note that this byte
* count is expected to be frame aligned. If it is not frame aligned, the
* return value will be the offset for the frame that includes the requested
* byte offset.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* This must be a PCM sample format.
* @returns the calculated frame offset that will contain the requested byte offset.
*/
inline size_t bytesToFrames(size_t bytes, const SoundFormat* format)
{
if (format->bitsPerSample == 0)
{
CARB_LOG_ERROR(
"attempting to convert bytes to frames in a variable bitrate format (%d), return 0", int(format->format));
return 0;
}
return bytesToFrames(bytes, format->channels, format->bitsPerSample);
}
/**
* converts a byte count to an approximate time in milliseconds.
*
* @param[in] bytes the number of bytes to be converted to a time in milliseconds. Note that
* this byte count is expected to be frame aligned.
* @param[in] frameRate the frame rate of the audio that needs a time calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24, or
* 32. This does not properly handle byte offset calculations for compressed
* audio formats.
* @returns the approximate number of milliseconds of audio data that the requested byte count
* represents for the given format.
*/
constexpr size_t bytesToMilliseconds(size_t bytes, size_t frameRate, size_t channels, size_t bps)
{
return (bytesToFrames(bytes * 1000, channels, bps)) / frameRate;
}
/**
* converts a byte count to an approximate time in microseconds.
*
* @param[in] bytes the number of bytes to be converted to a time in microseconds. Note that
* this byte count is expected to be frame aligned.
* @param[in] frameRate the frame rate of the audio that needs a time calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24, or
* 32. This does not properly handle byte offset calculations for compressed
* audio formats.
* @returns the approximate number of microseconds of audio data that the requested byte count
* represents for the given format.
*/
constexpr size_t bytesToMicroseconds(size_t bytes, size_t frameRate, size_t channels, size_t bps)
{
return bytesToFrames(bytes * 1000000, channels, bps) / frameRate;
}
/**
* converts a byte count to an approximate time in milliseconds.
*
* @param[in] bytes the number of bytes to be converted to a time in milliseconds. Note that
* this byte count is expected to be frame aligned.
* @param[in] frameRate the frame rate of the audio that needs a time calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format of the data. This must be a PCM sample format.
* @returns the approximate number of milliseconds of audio data that the requested byte count
* represents for the given format.
*/
constexpr size_t bytesToMilliseconds(size_t bytes, size_t frameRate, size_t channels, SampleFormat format)
{
return bytesToMilliseconds(bytes, frameRate, channels, sampleFormatToBitsPerSample(format));
}
/**
* converts a byte count to an approximate time in microseconds.
*
* @param[in] bytes the number of bytes to be converted to a time in microseconds. Note that
* this byte count is expected to be frame aligned.
* @param[in] frameRate the frame rate of the audio that needs a time calculated.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format of the data. This must be a PCM sample format.
* @returns the approximate number of microseconds of audio data that the requested byte count
* represents for the given format.
*/
constexpr size_t bytesToMicroseconds(size_t bytes, size_t frameRate, size_t channels, SampleFormat format)
{
return bytesToMicroseconds(bytes, frameRate, channels, sampleFormatToBitsPerSample(format));
}
/**
* converts a byte count to an approximate time in milliseconds.
*
* @param[in] bytes the number of bytes to be converted to a time in milliseconds. Note that
* this byte count is expected to be frame aligned.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the approximate number of milliseconds of audio data that the requested byte count
* represents for the given format.
*/
inline size_t bytesToMilliseconds(size_t bytes, const SoundFormat* format)
{
return bytesToMilliseconds(bytes, format->frameRate, format->channels, format->bitsPerSample);
}
/**
* converts a byte count to an approximate time in microseconds.
*
* @param[in] bytes the number of bytes to be converted to a time in microseconds. Note that
* this byte count is expected to be frame aligned.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the approximate number of microseconds of audio data that the requested byte count
* represents for the given format.
*/
inline size_t bytesToMicroseconds(size_t bytes, const SoundFormat* format)
{
return bytesToMicroseconds(bytes, format->frameRate, format->channels, format->bitsPerSample);
}
/**
* converts an input value from one unit to another.
*
* @param[in] input the input value to be converted.
* @param[in] inputUnits the units to convert the @p input value from.
* @param[in] outputUnits the units to convert the @p input value to.
* @param[in] format the format information for the sound that the input value is being
* converted for. This may not be nullptr.
* @returns the converted value in the requested output units.
* @returns 0 if an invalid input or output unit value was given.
*/
inline size_t convertUnits(size_t input, UnitType inputUnits, UnitType outputUnits, const SoundFormat* format)
{
CARB_ASSERT(format != nullptr);
switch (inputUnits)
{
case UnitType::eBytes:
switch (outputUnits)
{
case UnitType::eBytes:
return input;
case UnitType::eFrames:
return bytesToFrames(input, format);
case UnitType::eMilliseconds:
return bytesToMilliseconds(input, format);
case UnitType::eMicroseconds:
return bytesToMicroseconds(input, format);
default:
break;
}
break;
case UnitType::eFrames:
switch (outputUnits)
{
case UnitType::eBytes:
return framesToBytes(input, format);
case UnitType::eFrames:
return input;
case UnitType::eMilliseconds:
return framesToMilliseconds(input, format);
case UnitType::eMicroseconds:
return framesToMicroseconds(input, format);
default:
break;
}
break;
case UnitType::eMilliseconds:
switch (outputUnits)
{
case UnitType::eBytes:
return millisecondsToBytes(input, format);
case UnitType::eFrames:
return millisecondsToFrames(input, format);
case UnitType::eMilliseconds:
return input;
case UnitType::eMicroseconds:
return input * 1000;
default:
break;
}
break;
case UnitType::eMicroseconds:
switch (outputUnits)
{
case UnitType::eBytes:
return microsecondsToBytes(input, format);
case UnitType::eFrames:
return microsecondsToFrames(input, format);
case UnitType::eMilliseconds:
return input / 1000;
case UnitType::eMicroseconds:
return input;
default:
break;
}
break;
default:
break;
}
return 0;
}
/**
* aligns a byte count to a frame boundary for an audio data format.
*
* @param[in] bytes the byte count to align to a frame boundary. This will be aligned to the
* next higher frame boundary if it is not already aligned.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24, or
* 32. This does not properly handle byte offset calculations for compressed
* audio formats.
* @returns the requested byte count aligned to the next frame boundary if it is not already
* aligned.
* @returns the requested byte count unmodified if it is already aligned to a frame boundary.
*/
constexpr size_t alignBytesToFrameCeil(size_t bytes, size_t channels, size_t bps)
{
size_t blockSize = (channels * bps) / CHAR_BIT;
size_t count = bytes + (blockSize - 1);
return count - (count % blockSize);
}
/**
* aligns a byte count to a frame boundary for an audio data format.
*
* @param[in] bytes the byte count to align to a frame boundary. This will be aligned to the
* next higher frame boundary if it is not already aligned.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format of the data. This must be a PCM sample format.
* @returns the requested byte count aligned to the next frame boundary if it is not already
* aligned.
* @returns the requested byte count unmodified if it is already aligned to a frame boundary.
*/
inline size_t alignBytesToFrameCeil(size_t bytes, size_t channels, SampleFormat format)
{
return alignBytesToFrameCeil(bytes, channels, sampleFormatToBitsPerSample(format));
}
/**
* aligns a byte count to a frame boundary for an audio data format.
*
* @param[in] bytes the byte count to align to a frame boundary. This will be aligned to the
* next higher frame boundary if it is not already aligned.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the requested byte count aligned to the next frame boundary if it is not already
* aligned.
* @returns the requested byte count unmodified if it is already aligned to a frame boundary.
*/
inline size_t alignBytesToFrameCeil(size_t bytes, const SoundFormat* format)
{
return alignBytesToFrameCeil(bytes, format->channels, format->bitsPerSample);
}
/**
* aligns a byte count to a frame boundary for an audio data format.
*
* @param[in] bytes the byte count to align to a frame boundary. This will be aligned to the
* previous frame boundary if it is not already aligned.
* @param[in] channels the number of channels in the audio data format.
* @param[in] bps the number of bits per sample of audio data. This must be 8, 16, 24, or
* 32. This does not properly handle byte offset calculations for compressed
* audio formats.
* @returns the requested byte count aligned to the previous frame boundary if it is not already
* aligned.
* @returns the requested byte count unmodified if it is already aligned to a frame boundary.
*/
constexpr size_t alignBytesToFrameFloor(size_t bytes, size_t channels, size_t bps)
{
size_t blockSize = (channels * bps) / CHAR_BIT;
return bytes - (bytes % blockSize);
}
/**
* aligns a byte count to a frame boundary for an audio data format.
*
* @param[in] bytes the byte count to align to a frame boundary. This will be aligned to the
* previous frame boundary if it is not already aligned.
* @param[in] channels the number of channels in the audio data format.
* @param[in] format the sample format of the data. This must be a PCM sample format.
* @returns the requested byte count aligned to the previous frame boundary if it is not already
* aligned.
* @returns the requested byte count unmodified if it is already aligned to a frame boundary.
*/
constexpr size_t alignBytesToFrameFloor(size_t bytes, size_t channels, SampleFormat format)
{
return alignBytesToFrameFloor(bytes, channels, sampleFormatToBitsPerSample(format));
}
/**
* aligns a byte count to a frame boundary for an audio data format.
*
* @param[in] bytes the byte count to align to a frame boundary. This will be aligned to the
* previous frame boundary if it is not already aligned.
* @param[in] format the format information block for the sound data this time is being
* converted for.
* @returns the requested byte count aligned to the previous frame boundary if it is not already
* aligned.
* @returns the requested byte count unmodified if it is already aligned to a frame boundary.
*/
inline size_t alignBytesToFrameFloor(size_t bytes, const SoundFormat* format)
{
return alignBytesToFrameFloor(bytes, format->channels, format->bitsPerSample);
}
/**
* Generates a SoundFormat based on the 4 parameters given.
* @param[out] out The SoundFormat to generate.
* @param[in] format The format of the samples in the sound.
* @param[in] frameRate The frame rate of t
* @param[in] channels The number of channels in the sound.
* @param[in] mask The speaker mask of the sound.
*/
inline void generateSoundFormat(
SoundFormat* out, SampleFormat format, size_t channels, size_t frameRate, SpeakerMode mask = kSpeakerModeDefault)
{
out->channels = channels;
out->format = format;
out->frameRate = frameRate;
out->bitsPerSample = sampleFormatToBitsPerSample(out->format);
out->frameSize = out->bitsPerSample / CHAR_BIT * out->channels;
out->blockSize = out->frameSize; // PCM is 1 frame per block
out->framesPerBlock = 1;
out->channelMask = mask;
out->validBitsPerSample = out->bitsPerSample;
}
/**
* Initialize a SoundDataLoadDesc to its defaults.
* @param[out] desc The desc to initialize.
*
* @remarks This initializes @p desc to a set of default values.
* This is useful for cases where only a small subset of members need
* to be changed, since this will initialize the entire struct to
* no-op values. For example, when loading a sound from a file name,
* only @p desc->name and @p desc->flags need to be modified.
*
* @note This function is deprecated and should no longer be used. This
* can be replaced by simply initializing the descriptor with "= {}".
*/
inline void getSoundDataLoadDescDefaults(SoundDataLoadDesc* desc)
{
*desc = {};
}
/**
* Initialize a PlaySoundDesc to its defaults.
* @param[out] desc The desc to initialize.
*
* @remarks This initializes @p desc to a set of default values.
* This is useful for cases where only a small subset of members need
* to be changed, since this will initialize the entire struct to
* no-op values. For example, when playing a one shot sound, only
* @p desc->sound will need to be modified.
*
* @note This function is deprecated and should no longer be used. This
* can be replaced by simply initializing the descriptor with "= {}".
*/
inline void getPlaySoundDescDefaults(PlaySoundDesc* desc)
{
*desc = {};
}
/** fills a cone descriptor with the default cone values.
*
* @param[out] cone the cone descriptor to fill in.
* @returns no return value.
*
* @remarks This fills in a cone descriptor with the default values. Note that the cone
* descriptor doesn't have an implicit constructor because it is intended to be
* a sparse struct that generally does not need to be fully initialized.
*/
inline void getConeDefaults(EntityCone* cone)
{
cone->insideAngle = kConeAngleOmnidirectional;
cone->outsideAngle = kConeAngleOmnidirectional;
cone->volume = { 1.0f, 0.0f };
cone->lowPassFilter = { 0.0f, 1.0f };
cone->reverb = { 0.0f, 1.0f };
cone->ext = nullptr;
}
/** fills a rolloff descriptor with the default rolloff values.
*
* @param[out] desc the rolloff descriptor to fill in.
* @returns no return value.
*
* @remarks This fills in a rolloff descriptor with the default values. Note that the
* rolloff descriptor doesn't have an implicit constructor because it is intended
* to be a sparse struct that generally does not need to be fully initialized.
*/
inline void getRolloffDefaults(RolloffDesc* desc)
{
desc->type = RolloffType::eInverse;
desc->nearDistance = 0.0f;
desc->farDistance = 10000.0f;
desc->volume = nullptr;
desc->lowFrequency = nullptr;
desc->lowPassDirect = nullptr;
desc->lowPassReverb = nullptr;
desc->reverb = nullptr;
desc->ext = nullptr;
}
/** Create an empty SoundData of a specific length.
* @param[in] iface The IAudioData interface to use.
* @param[in] fmt The sample format for the sound.
* @param[in] frameRate The frame rate of the sound.
* @param[in] channels The number of channels for the sound.
* @param[in] bufferLength The length of the sound's buffer as a measure of @p unitType.
* @param[in] unitType The unit type to use for @p bufferLength.
* @param[in] name The name to give the sound, if desired.
*
* @returns The created sound with empty buffer with the valid length set to 0.
* The valid length should be set after the sound's buffer is filled.
* @returns nullptr if @p fmt, @p frameRate or @p channels are invalid or out
* of range.
* @returns nullptr if creation failed unexpectedly (such as out of memory).
*
*/
inline SoundData* createEmptySound(const IAudioData* iface,
SampleFormat fmt,
size_t frameRate,
size_t channels,
size_t bufferLength,
UnitType unitType = UnitType::eFrames,
const char* name = nullptr)
{
SoundDataLoadDesc desc = {};
desc.flags |= fDataFlagEmpty;
if (name == nullptr)
desc.flags |= fDataFlagNoName;
desc.name = name;
desc.pcmFormat = fmt;
desc.frameRate = frameRate;
desc.channels = channels;
desc.bufferLength = bufferLength;
desc.bufferLengthType = unitType;
return iface->createData(&desc);
}
/** Convert a sound to a new sample format.
* @param[in] iface The IAudioData interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] newFmt The new format to set the sound to.
* This can be any valid format; setting this to a PCM format
* will cause the output to be a blob of PCM data.
* @returns The new sound data created. @p snd and the returned value must both
* be released after this call once the caller is finished with them.
* @returns nullptr if the operation failed or the specified format was invalid.
*
* @note When converting to any format with specific encoder settings, these
* will be left at their defaults.
*/
inline SoundData* convertSoundFormat(const IAudioUtils* iface, SoundData* snd, SampleFormat newFmt)
{
ConversionDesc desc = {};
desc.flags = fConvertFlagCopy;
desc.soundData = snd;
desc.newFormat = newFmt;
return iface->convert(&desc);
}
/** Convert a sound to Vorbis.
* @param[in] iface The IAudioData interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] quality @copydoc VorbisEncoderSettings::quality
* @param[in] nativeChannelOrder @copydoc VorbisEncoderSettings::nativeChannelOrder
*
* @returns The new sound data created. @p snd and the returned value must both
* be released after this call once the caller is finished with them.
* @returns nullptr if the operation failed.
*/
inline SoundData* convertToVorbis(const IAudioUtils* iface,
SoundData* snd,
float quality = 0.9f,
bool nativeChannelOrder = false)
{
VorbisEncoderSettings vorbis = {};
ConversionDesc desc = {};
desc.flags = fConvertFlagCopy;
desc.soundData = snd;
desc.newFormat = SampleFormat::eVorbis;
desc.encoderSettings = &vorbis;
vorbis.quality = quality;
vorbis.nativeChannelOrder = nativeChannelOrder;
return iface->convert(&desc);
}
/** Convert a sound to FLAC.
* @param[in] iface The IAudioData interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] compressionLevel Compression level.
* See @ref FlacEncoderSettings::compressionLevel.
* @param[in] bitsPerSample Bit precision of each audio sample.
* 0 will automatically choose the appropriate
* value for the input sample type.
* See @ref FlacEncoderSettings::bitsPerSample.
* @param[in] fileType File container type.
* See @ref FlacEncoderSettings::fileType.
* @param[in] streamableSubset Whether the streamable subset is used.
* Using the default value is recommended.
* See @ref FlacEncoderSettings::streamableSubset.
* @param[in] blockSize Block size used by the encoder.
* 0 will let the encoder choose.
* Letting the encoder choose is recommended.
* See @ref FlacEncoderSettings::blockSize.
* @param[in] verifyOutput Whether output Verification should be enabled.
* See @ref FlacEncoderSettings::verifyOutput.
*
* @returns The new sound data created. @p snd and the returned value must both
* be released after this call once the caller is finished with them.
* @returns nullptr if the operation failed.
* @returns nullptr if the encoding parameters were invalid.
*
* @note It is not recommended to set the encoder settings, apart from
* @p compressionLevel, to anything other than their defaults under most
* circumstances.
*/
inline SoundData* convertToFlac(const IAudioUtils* iface,
SoundData* snd,
uint32_t compressionLevel = 5,
uint32_t bitsPerSample = 0,
FlacFileType fileType = FlacFileType::eFlac,
bool streamableSubset = true,
uint32_t blockSize = 0,
bool verifyOutput = false)
{
FlacEncoderSettings flac = {};
ConversionDesc desc = {};
desc.flags = fConvertFlagCopy;
desc.soundData = snd;
desc.newFormat = SampleFormat::eFlac;
desc.encoderSettings = &flac;
flac.compressionLevel = compressionLevel;
flac.bitsPerSample = bitsPerSample;
flac.fileType = fileType;
flac.streamableSubset = streamableSubset;
flac.blockSize = blockSize;
flac.verifyOutput = verifyOutput;
return iface->convert(&desc);
}
/** Save a sound to disk.
* @param[in] iface The IAudioUtils interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] fileName The path to the file on disk to save this to.
* @param[in] fmt The format to save the sound as.
* This can be any valid format.
* @param[in] flags Flags to alter the behavior of this function.
* @returns true if the sound was successfully saved.
* @returns false if the operation failed.
*
* @note When converting to any format with specific encoder settings, these
* will be left at their defaults.
*/
inline bool saveSoundToDisk(const IAudioUtils* iface,
SoundData* snd,
const char* fileName,
SampleFormat fmt = SampleFormat::eDefault,
SaveFlags flags = 0)
{
SoundDataSaveDesc desc = {};
desc.flags = flags;
desc.format = fmt;
desc.soundData = snd;
desc.filename = fileName;
return iface->saveToFile(&desc);
}
/** Save a sound to disk as Vorbis.
* @param[in] iface The IAudioUtils interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] fileName The path to the file on disk to save this to.
* @param[in] quality @copydoc VorbisEncoderSettings::quality
* @param[in] nativeChannelOrder @copydoc VorbisEncoderSettings::nativeChannelOrder
* @param[in] flags Flags to alter the behavior of this function.
*
* @returns true if the sound was successfully saved.
* @returns false if the operation failed.
*/
inline bool saveToDiskAsVorbis(const IAudioUtils* iface,
SoundData* snd,
const char* fileName,
float quality = 0.9f,
bool nativeChannelOrder = false,
SaveFlags flags = 0)
{
VorbisEncoderSettings vorbis = {};
SoundDataSaveDesc desc = {};
desc.flags = flags;
desc.format = SampleFormat::eVorbis;
desc.soundData = snd;
desc.filename = fileName;
desc.encoderSettings = &vorbis;
vorbis.quality = quality;
vorbis.nativeChannelOrder = nativeChannelOrder;
return iface->saveToFile(&desc);
}
/** Convert a sound to FLAC.
* @param[in] iface The IAudioData interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] fileName The name of the file on disk to create the
* new sound data object from.
* This may not be nullptr.
* @param[in] compressionLevel Compression level.
* See @ref FlacEncoderSettings::compressionLevel.
* @param[in] bitsPerSample Bit precision of each audio sample.
* 0 will automatically choose the appropriate
* value for the input sample type.
* See @ref FlacEncoderSettings::bitsPerSample.
* @param[in] fileType File container type.
* See @ref FlacEncoderSettings::fileType.
* @param[in] streamableSubset Whether the streamable subset is used.
* Using the default value is recommended.
* See @ref FlacEncoderSettings::streamableSubset.
* @param[in] blockSize Block size used by the encoder.
* 0 will let the encoder choose.
* Letting the encoder choose is recommended.
* See @ref FlacEncoderSettings::blockSize.
* @param[in] verifyOutput Whether output Verification should be enabled.
* See @ref FlacEncoderSettings::verifyOutput.
* @param[in] flags Flags to alter the behavior of this function.
*
*
* @returns true if the sound was successfully saved.
* @returns false if the operation failed.
*
* @note It is not recommended to set the encoder settings, apart from
* @p compressionLevel, to anything other than their defaults under most
* circumstances.
*/
inline bool saveToDiskAsFlac(const IAudioUtils* iface,
SoundData* snd,
const char* fileName,
uint32_t compressionLevel = 5,
uint32_t bitsPerSample = 0,
FlacFileType fileType = FlacFileType::eFlac,
bool streamableSubset = true,
uint32_t blockSize = 0,
bool verifyOutput = false,
SaveFlags flags = 0)
{
FlacEncoderSettings flac = {};
carb::audio::SoundDataSaveDesc desc = {};
desc.flags = flags;
desc.format = SampleFormat::eFlac;
desc.soundData = snd;
desc.filename = fileName;
desc.encoderSettings = &flac;
flac.compressionLevel = compressionLevel;
flac.bitsPerSample = bitsPerSample;
flac.fileType = fileType;
flac.streamableSubset = streamableSubset;
flac.blockSize = blockSize;
flac.verifyOutput = verifyOutput;
return iface->saveToFile(&desc);
}
/** Convert a sound to Opus.
* @param[in] iface The IAudioData interface to use.
* @param[in] snd The sound to convert to a new format.
* This may not be nullptr.
* @param[in] fileName The name of the file on disk to create the
* new sound data object from.
* This may not be nullptr.
* @param[in] bitrate @copydoc OpusEncoderSettings::bitrate
* @param[in] usage @copydoc OpusEncoderSettings::usage
* @param[in] complexity @copydoc OpusEncoderSettings::complexity
* @param[in] bitDepth @copydoc OpusEncoderSettings::bitDepth
* @param[in] blockSize @copydoc OpusEncoderSettings::blockSize
* @param[in] bandwidth @copydoc OpusEncoderSettings::bandwidth
* @param[in] outputGain @copydoc OpusEncoderSettings::outputGain
* @param[in] packetLoss @copydoc OpusEncoderSettings::packetLoss
* @param[in] flags @copydoc OpusEncoderSettings::flags
* @param[in] saveFlags Flags to alter the behavior of this function.
*
* @returns true if the sound was successfully saved.
* @returns false if the operation failed.
*
* @note For general purpose audio use (e.g. saving recorded audio to disk for
* storage), you should at most modify @p bitrate, @p usage and @p complexity.
* For storing very heavily compressed audio, you may also want to set
* @p bandwidth and @p bitDepth.
* The rest of the options are mainly for encoding you intend to transmit
* over a network or miscellaneous purposes.
*/
inline bool saveToDiskAsOpus(const IAudioUtils* iface,
SoundData* snd,
const char* fileName,
uint32_t bitrate = 0,
OpusCodecUsage usage = OpusCodecUsage::eGeneral,
int8_t complexity = -1,
uint8_t blockSize = 48,
uint8_t packetLoss = 0,
uint8_t bandwidth = 20,
uint8_t bitDepth = 0,
int16_t outputGain = 0,
OpusEncoderFlags flags = 0,
SaveFlags saveFlags = 0)
{
OpusEncoderSettings opus = {};
carb::audio::SoundDataSaveDesc desc = {};
desc.flags = saveFlags;
desc.format = SampleFormat::eOpus;
desc.soundData = snd;
desc.filename = fileName;
desc.encoderSettings = &opus;
opus.flags = flags;
opus.bitrate = bitrate;
opus.usage = usage;
opus.complexity = complexity;
opus.blockSize = blockSize;
opus.packetLoss = packetLoss;
opus.bandwidth = bandwidth;
opus.bitDepth = bitDepth;
opus.outputGain = outputGain;
return iface->saveToFile(&desc);
}
/** create a sound data object from a file on disk.
*
* @param[in] iface The IAudioData interface to use.
* @param[in] filename The name of the file on disk to create the new sound
* data object from. This may not be nullptr.
* @param[in] streaming set to true to create a streaming sound. This will
* be decoded as it plays. Set to false to decode the
* sound immediately on load.
* @param[in] autoStream The threshold in bytes at which the new sound data
* object will decide to stream instead of decode into
* memory. If the decoded size of the sound will be
* larger than this value, it will be streamed from its
* original source instead of decoded. Set this to 0
* to disable auto-streaming.
* @param[in] fmt The format the sound should be decoded into. By
* default, the decoder choose its preferred format.
* @param[in] flags Optional flags to change the behavior.
* This can be any of: @ref fDataFlagSkipMetaData,
* @ref fDataFlagSkipEventPoints or @ref fDataFlagCalcPeaks.
* @returns The new sound data if successfully created and loaded. This
* object must be released once it is no longer needed.
* @returns nullptr if the operation failed. This may include the file
* not being accessible, the file's data not being the correct
* format, or a decoding error occurs.
*/
inline SoundData* createSoundFromFile(const IAudioData* iface,
const char* filename,
bool streaming = false,
size_t autoStream = 0,
SampleFormat fmt = SampleFormat::eDefault,
DataFlags flags = 0)
{
constexpr DataFlags kValidFlags = fDataFlagSkipMetaData | fDataFlagSkipEventPoints | fDataFlagCalcPeaks;
SoundDataLoadDesc desc = {};
if ((flags & ~kValidFlags) != 0)
{
CARB_LOG_ERROR("invalid flags 0x%08" PRIx32, flags);
return nullptr;
}
desc.flags = flags;
desc.name = filename;
desc.pcmFormat = fmt;
desc.autoStreamThreshold = autoStream;
if (streaming)
desc.flags |= fDataFlagStream;
else
desc.flags |= fDataFlagDecode;
return iface->createData(&desc);
}
/** create a sound data object from a blob in memory.
*
* @param[in] iface The IAudioData interface to use.
* @param[in] dataBlob the blob of data to load the asset from. This may
* not be nullptr. This should include the entire
* contents of the original asset file.
* @param[in] dataLength the length of the data blob in bytes. This may not
* be zero.
* @param[in] streaming set to true to create a streaming sound. This will
* be decoded as it plays. Set to false to decode the
* sound immediately on load.
* @param[in] autoStream The threshold in bytes at which the new sound data
* object will decide to stream instead of decode into
* memory. If the decoded size of the sound will be
* larger than this value, it will be streamed from its
* original source instead of decoded. Set this to 0
* to disable auto-streaming. This will be ignored if
* the data is already uncompressed PCM.
* @param[in] fmt The format the sound should be decoded into. By
* default, the decoder choose its preferred format.
* @param[in] flags Optional flags to change the behavior.
* This can be any of: @ref fDataFlagSkipMetaData,
* @ref fDataFlagSkipEventPoints, @ref fDataFlagCalcPeaks
* or @ref fDataFlagUserMemory.
*
*
* @returns The new sound data if successfully created and loaded. This
* object must be released once it is no longer needed.
* @returns nullptr if the operation failed. This may include the file
* not being accessible, the file's data not being the correct
* format, or a decoding error occurs.
*/
inline SoundData* createSoundFromBlob(const IAudioData* iface,
const void* dataBlob,
size_t dataLength,
bool streaming = false,
size_t autoStream = 0,
SampleFormat fmt = SampleFormat::eDefault,
DataFlags flags = 0)
{
constexpr DataFlags kValidFlags =
fDataFlagSkipMetaData | fDataFlagSkipEventPoints | fDataFlagCalcPeaks | fDataFlagUserMemory;
SoundDataLoadDesc desc = {};
if ((flags & ~kValidFlags) != 0)
{
CARB_LOG_ERROR("invalid flags 0x%08" PRIx32, flags);
return nullptr;
}
desc.flags = fDataFlagInMemory | flags;
desc.dataBlob = dataBlob;
desc.dataBlobLengthInBytes = dataLength;
desc.pcmFormat = fmt;
desc.autoStreamThreshold = autoStream;
if (streaming)
desc.flags |= fDataFlagStream;
else
desc.flags |= fDataFlagDecode;
return iface->createData(&desc);
}
/** Creates a sound data object from a blob of memory.
* @param[in] iface The audio data interface to use.
* @param[in] dataBlob The buffer of data to use to create a sound data object.
* @param[in] dataLength The length of @p buffer in bytes.
* @param[in] frames The number of frames of data in @p buffer.
* @param[in] format The data format to use to interpret the data in @p buffer.
* @returns A new sound data object containing the data in @p buffer if successfully created.
* @returns nullptr if a new sound data object could not be created.
*/
inline SoundData* createSoundFromRawPcmBlob(
const IAudioData* iface, const void* dataBlob, size_t dataLength, size_t frames, const SoundFormat* format)
{
SoundDataLoadDesc desc = {};
desc.flags = carb::audio::fDataFlagFormatRaw | carb::audio::fDataFlagInMemory;
desc.dataBlob = dataBlob;
desc.dataBlobLengthInBytes = dataLength;
desc.channels = format->channels;
desc.frameRate = format->frameRate;
desc.encodedFormat = format->format;
desc.pcmFormat = format->format;
desc.bufferLength = frames;
desc.bufferLengthType = carb::audio::UnitType::eFrames;
return iface->createData(&desc);
}
/** Play a sound with no special parameters.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] ctx The context to play the sound on.
* @param[in] snd The sound to play.
* @param[in] spatial This chooses whether the sound is played as spatial or non-spatial.
*/
inline Voice* playOneShotSound(const IAudioPlayback* iface, Context* ctx, SoundData* snd, bool spatial = false)
{
PlaySoundDesc desc = {};
VoiceParams params = {};
// desc to play the sound once fully in a non-spatial manner
desc.sound = snd;
if (spatial)
{
desc.validParams = fVoiceParamPlaybackMode;
desc.params = ¶ms;
params.playbackMode = fPlaybackModeSpatial;
}
return iface->playSound(ctx, &desc);
}
/** Play a sound sound that loops.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] ctx The context to play the sound on.
* @param[in] snd The sound to play.
* @param[in] loopCount The number of times the sound will loop.
* @param[in] spatial This chooses whether the sound is played as spatial or non-spatial.
* @remarks This plays a sound which loops through the full sound a given
* number of times (or an infinite number of times if desired).
*/
inline Voice* playLoopingSound(const IAudioPlayback* iface,
Context* ctx,
SoundData* snd,
size_t loopCount = kEventPointLoopInfinite,
bool spatial = false)
{
EventPoint loopPoint = {};
PlaySoundDesc desc = {};
VoiceParams params = {};
// desc to play the sound once fully in a non-spatial manner
desc.sound = snd;
desc.loopPoint.loopPoint = &loopPoint;
loopPoint.loopCount = loopCount;
if (spatial)
{
desc.validParams = fVoiceParamPlaybackMode;
desc.params = ¶ms;
params.playbackMode = fPlaybackModeSpatial;
}
return iface->playSound(ctx, &desc);
}
/** Set the volume of a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to alter.
* @param[in] volume The new volume to set on @p voice.
*/
inline void setVoiceVolume(const IAudioPlayback* iface, Voice* voice, float volume)
{
carb::audio::VoiceParams params = {};
params.volume = volume;
iface->setVoiceParameters(voice, fVoiceParamVolume, ¶ms);
}
/** Set the frequencyRatio of a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to alter.
* @param[in] frequencyRatio The new volume to set on @p voice.
*/
inline void setVoiceFrequencyRatio(const IAudioPlayback* iface, Voice* voice, float frequencyRatio)
{
carb::audio::VoiceParams params = {};
params.frequencyRatio = frequencyRatio;
iface->setVoiceParameters(voice, fVoiceParamFrequencyRatio, ¶ms);
}
/** Pause a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to pause.
*/
inline void pauseVoice(const IAudioPlayback* iface, Voice* voice)
{
carb::audio::VoiceParams params = {};
params.playbackMode = fPlaybackModePaused;
iface->setVoiceParameters(voice, fVoiceParamPause, ¶ms);
}
/** Unpause a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to unpause.
*/
inline void unpauseVoice(const IAudioPlayback* iface, Voice* voice)
{
carb::audio::VoiceParams params = {};
iface->setVoiceParameters(voice, fVoiceParamPause, ¶ms);
}
/** Mute a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to mute.
*/
inline void muteVoice(const IAudioPlayback* iface, Voice* voice)
{
carb::audio::VoiceParams params = {};
params.playbackMode = fPlaybackModeMuted;
iface->setVoiceParameters(voice, fVoiceParamMute, ¶ms);
}
/** Unmute a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to unmute.
*/
inline void unmuteVoice(const IAudioPlayback* iface, Voice* voice)
{
carb::audio::VoiceParams params = {};
iface->setVoiceParameters(voice, fVoiceParamMute, ¶ms);
}
/** Set the matrix of a voice.
* @param[in] iface The IAudioPlayback interface to use.
* @param[in] voice The voice to alter.
* @param[in] matrix The new matrix to set on @p voice.
* This can be nullptr to revert to a default matrix.
*/
inline void setVoiceMatrix(const IAudioPlayback* iface, Voice* voice, const float* matrix)
{
carb::audio::VoiceParams params = {};
params.matrix = matrix;
iface->setVoiceParameters(voice, fVoiceParamMatrix, ¶ms);
}
/** Calculate the gain parameter for an Opus encoder from a floating point gain.
* @param[in] gain The floating point gain to convert to an Opus gain parameter.
* This must be between [-128, 128] or it will be clamped.
*
* @returns A gain value that can be used as a parameter to an Opus encoder.
* This is a signed 16 bit fixed point value with 8 fractional bits.
*/
inline int16_t calculateOpusGain(float gain)
{
// multiply by 256 to convert this into a s7.8 fixed point value.
// IEEE754 float has 23 bits in the mantissa, so we can represent the 16
// bit range losslessly with a float
gain *= 256.f;
// clamp the result in case the gain was too large, then truncate the
// fractional part
return int16_t(CARB_CLAMP(gain, float(INT16_MIN), float(INT16_MAX)));
}
/** Calculate a decibel gain value from a linear volume scale.
* @param[in] linear The linear float scale value to convert to a gain value.
*
* @returns The gain value that will produce a linear volume scale of @p linear.
*/
inline float calculateGainFromLinearScale(float linear)
{
// gain is calculated as 20 * log10(linear)
return 20.f * log10f(linear);
}
/** Calculate the linear volume scale from a decibel gain level.
* @param[in] gain The gain value to be converted to a linear scale.
* This parameter should be a fairly small number; for
* example, -186.64 is approximately the decibel gain level
* of the noise floor for 32 bit audio.
*
* @returns The linear volume scale produced by gain @p gain.
*/
inline float calculateLinearScaleFromGain(float gain)
{
return powf(10, gain * (1.f / 20.f));
}
/** Increment a counter with a non-power-of-2 modulo.
* @param[in] counter The counter value to increment.
* This must be less than @p modulo.
* @param[in] modulo The value to perform a modulo by.
* This may not be 0.
*
* @returns @p counter incremented and wrapped around @p modulo.
*
* @remarks This function exists to perform a modulo around a non-power-of-2
* modulo without having to duplicate the wrap code in multiple places.
* Note that this is considerably more efficient than use of the %
* operator where a power-of-2 optimization cannot be made.
*/
inline size_t incrementWithWrap(size_t counter, size_t modulo)
{
CARB_ASSERT(modulo > 0);
CARB_ASSERT(counter < modulo);
return (counter + 1 == modulo) ? 0 : counter + 1;
}
/** Decrement a counter with a non-power-of-2 modulo.
* @param[in] counter The counter value to increment.
* This must be less than or equal to @p modulo.
* @p counter == @p modulo is allowed for some edge cases
* where it's useful.
* @param[in] modulo The value to perform a modulo by.
* This may not be 0.
*
* @returns @p counter incremented and wrapped around @p modulo.
*
* @remarks This function exists to perform a modulo around a non-power-of-2
* modulo without having to duplicate the wrap code in multiple places.
* Note that % does not work for decrementing with a non-power-of-2 modulo.
*/
inline size_t decrementWithWrap(size_t counter, size_t modulo)
{
CARB_ASSERT(modulo > 0);
CARB_ASSERT(counter <= modulo);
return (counter == 0) ? modulo - 1 : counter - 1;
}
/** Calculates an estimate of the current level of video latency.
*
* @param[in] fps The current video frame rate in frames per second. The caller
* is responsible for accurately retrieving and calculating this.
* @param[in] framesInFlight The current number of video frames currently in flight. This
* is the number of frames that have been produced by the renderer
* but have not been displayed to the user yet (or has been presented
* but not realized on screen yet). The frame being produced would
* represent the simulation time (where a synchronized sound is
* expected to start playing), and the other buffered frames are
* ones that go back further in time (ie: older frames as far as
* the simulation is concerned). This may need to be an estimate
* the caller can retrieve from the renderer.
* @param[in] perceptibleDelay A limit below which a zero latency will be calculated. If the
* total calculated latency is less than this threshold, the latency
* will be zeroed out. If total calculated latency is larger than
* this limit, a delay estimate will be calculated. This value is
* given in microseconds. This defaults to 200,000 microseconds.
* @returns The calculated latency estimate in microseconds.
*
* @remarks This is used to calculate an estimate of the current video latency level. This
* value can be used to set the @ref ContextParams2::videoLatency value based on the
* current performance of the video rendering system. This value is used by the audio
* engine to delay the queuing of new voices by a given amount of time.
*/
inline int64_t estimateVideoLatency(double fps, double framesInFlight, int64_t perceptibleDelay = kImperceptibleDelay)
{
constexpr int64_t kMinLatency = 20'000;
double usPerFrame;
if (fps == 0.0)
return 0;
usPerFrame = 1'000'000.0 / fps;
// the current delay is less than the requested perceptible latency time => clamp the
// estimated delay down to zero.
if (usPerFrame * framesInFlight <= perceptibleDelay)
return 0;
// calculate the estimated delay in microseconds. Note that this will fudge the calculated
// total latency by a small amount because there is an expected minimum small latency in
// queuing a new voice already.
return (int64_t)((usPerFrame * framesInFlight) - CARB_MIN(perceptibleDelay / 2, kMinLatency));
}
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/IAudioUtils.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief General audio utilities.
*/
#pragma once
#include "../Interface.h"
#include "AudioTypes.h"
#include "IAudioData.h"
namespace carb
{
namespace audio
{
/************************************* Interface Objects *****************************************/
/** a handle to an open output stream. This is created by openOutputStream(). This holds the
* current state of the output stream and allows it to be written out in multiple chunks.
*/
struct OutputStream;
/********************************* Sound Data Conversion Objects *********************************/
/** flags to control the behavior of a conversion operation.
*
* @{
*/
/** container type for conversion operation flags. */
typedef uint32_t ConvertFlags;
/** convert the sound data object in-place. The old buffer data will be replaced with the
* converted data and all of the object's format information will be updated accordingly.
* This is the default behavior if no flags are given. Note that if the source and
* destination formats are the same and this flag is used, a new reference will be taken
* on the original sound data object. The returned object will be the same as the input
* object, but both will need to be released (just the same as if a new object had been
* returned).
*/
constexpr ConvertFlags fConvertFlagInPlace = 0x00000001;
/** convert the sound data object and return a new copy of the data. The previous sound
* data object will be unmodified and still valid. The new object will contain the same
* audio data, just converted to the new format. The new object needs to be destroyed
* with destroySoundData() when it is no longer needed.
*/
constexpr ConvertFlags fConvertFlagCopy = 0x00000002;
/** when duplicating a sound data object and no conversion is necessary, this allows the
* new object to reference the same data pointer as the original object. It is the
* caller's responsibility to ensure that the original object remains valid for the life
* time of the copied object. This flag will be ignored if a conversion needs to occur.
* This flag is useful when the original sound data object already references user memory
* instead of copying the data. If this flag is not used, the data buffer will always
* be copied from the original buffer.
*/
constexpr ConvertFlags fConvertFlagReferenceData = 0x00000004;
/** forces an operation to copy or decode the input data
* into a new sound data object.
* If the @ref fConvertFlagInPlace is specified and the sound data object is in memory,
* then the object is decoded in place. If the sound is in a file, then this creates a
* new sound data object containing the decoded sound.
* If the @ref fConvertFlagCopy is specified, then a new sound data object
* will be created to contain the converted sound.
* If neither the @ref fConvertFlagCopy nor the @ref fConvertFlagInPlace are specified,
* then the @ref fConvertFlagCopy flag will be implied.
*
* @note Using this flag on a compressed format will cause a re-encode and that
* could cause quality degradation.
*/
constexpr ConvertFlags fConvertFlagForceCopy = 0x00000008;
/** @} */
/** a descriptor of a data type conversion operation. This provides the information needed to
* convert a sound data object from its current format to another data format. Not all data
* formats may be supported as destination formats. The conversion operation will fail if the
* destination format is not supported for encoding. The conversion operation may either be
* performed in-place on the sound data object itself or it may output a copy of the sound
* data object converted to the new format.
*
* Note that this conversion operation will not change the length (mostly), frame rate, or
* channel count of the data, just its sample format. The length of the stream may increase
* by a few frames for some block oriented compression or encoding formats so that the stream
* can be block aligned in length. PCM data will always remain the same length as the input
* since the frames per block count for PCM data is always 1.
*/
struct ConversionDesc
{
/** flags to control how the conversion proceeds. This may be zero or more of the
* fConvertFlag* flags.
*/
ConvertFlags flags = 0;
/** the sound data to be converted. This object may or may not be modified depending on
* which flags are used. The converted data will be equivalent to the original data,
* just in the new requested format. Note that some destination formats may cause some
* information to be lost due to their compression or encoding methods. The converted
* data will contain at least the same number of frames and channels as the original data.
* Some block oriented compression formats may pad the stream with silent frames so that
* a full block can be written out. This may not be nullptr.
*/
SoundData* soundData;
/** the requested destination format for the conversion operation. For some formats,
* this may result in data or quality loss. If this format is not supported for
* encoding, the operation will fail. This can be @ref SampleFormat::eDefault to
* use the same as the original format. This is useful when also using the
* @ref fConvertFlagCopy to duplicate a sound data object.
*
* Note that if this new format matches the existing format this will be a no-op
* unless the @ref fConvertFlagCopy flag is specified. If the 'copy' flag is used,
* this will simply duplicate the existing object. The new object will still need
* to be destroyed with release() when it is no longer needed.
*/
SampleFormat newFormat = SampleFormat::eDefault;
/** additional output format dependent encoder settings. This should be nullptr for PCM
* data formats. Additional objects will be defined for encoder formats that require
* additional parameters (optional or otherwise). For formats that require additional
* settings, this may not be nullptr. Use getCodecFormatInfo() to retrieve the info
* for the codec to find out if the additional settings are required or not.
*/
void* encoderSettings = nullptr;
/** an opaque context value that will be passed to the readCallback and setPosCallback
* functions each time they are called. This value is a caller-specified object that
* is expected to contain the necessary decoding state for a user decoded stream. This
* value is only necessary if the @ref fDataFlagUserDecode flag was used when creating
* the sound data object being converted.
*/
void* readCallbackContext = nullptr;
/** An optional callback that gets fired when the SoundData's final
* reference is released. This is intended to make it easier to perform
* cleanup of a SoundData in cases where @ref fDataFlagUserMemory is used.
* This is intended to be used in cases where the SoundData is using some
* resource that needs to be released after the SoundData is destroyed.
*/
SoundDataDestructionCallback destructionCallback = nullptr;
/** An opaque context value that will be passed to @ref destructionCallback
* when the last reference to the SoundData is released.
* This will not be called if the SoundData is not created successfully.
*/
void* destructionCallbackContext = nullptr;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** Flags that alter the behavior of a PCM transcoding operation.
*/
typedef uint32_t TranscodeFlags;
/** A descriptor for transcoding between PCM formats, which is used for the
* transcodePcm() function
*/
struct TranscodeDesc
{
/** Flags for the transcoding operation.
* This must be 0 as no flags are currently defined.
*/
TranscodeFlags flags = 0;
/** The format of the input data.
* This must be a PCM format.
*/
SampleFormat inFormat;
/** The data format that will be written into @p outBuffer.
* This must be a PCM format.
*/
SampleFormat outFormat;
/** The input buffer to be transcoded.
* Audio in this buffer is interpreted as @ref inFormat.
* This must be long enough to hold @ref samples samples of audio data in
* @ref inFormat.
*/
const void* inBuffer;
/** The output buffer to receive the transcoded data.
* Audio will be transcoded from @ref inBuffer into @ref outBuffer in
* @ref outFormat.
* This must be long enough to hold @ref samples samples of audio data in
* @ref outFormat.
* This may not alias or overlap @ref inBuffer.
*/
void* outBuffer;
/** The number of samples of audio to transcode.
* Note that for multichannel audio, this is the number of frames
* multiplied by the channel count.
*/
size_t samples;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/*********************************** Sound Data Output Objects ***********************************/
/** Flags used for the saveToFile() function. These control how the the sound data object
* is written to the file. Zero or more of these flags may be combined to alter the behavior.
* @{
*/
typedef uint32_t SaveFlags;
/** Default save behavior. */
constexpr SaveFlags fSaveFlagDefault = 0x00000000;
/** Don't write the metadata information into the file.
*/
constexpr SaveFlags fSaveFlagStripMetaData = 0x00000001;
/** Don't write the event point information into the file.
*/
constexpr SaveFlags fSaveFlagStripEventPoints = 0x00000002;
/** Don't write the peaks information into the file.
*/
constexpr SaveFlags fSaveFlagStripPeaks = 0x00000004;
/** a descriptor of how a sound data object should be written out to file. This can optionally
* convert the audio data to a different format. Note that transcoding the audio data could
* result in a loss in quality depending on both the source and destination formats.
*/
struct SoundDataSaveDesc
{
/** Flags that alter the behavior of saving the file.
* These may indicate to the file writer that certain elements in the file
* should be stripped, for example.
*/
SaveFlags flags = 0;
/** the format that the sound data object should be saved in. Note that if the data was
* fully decoded on load, this may still result in some quality loss if the data needs to
* be re-encoded. This may be @ref SampleFormat::eDefault to write the sound to file in
* the sound's encoded format.
*/
SampleFormat format = SampleFormat::eDefault;
/** the sound data to be written out to file. This may not be nullptr. Depending on
* the data's original format and flags and the requested destination format, there
* may be some quality loss if the data needs to be decoded or re-encoded.
* This may not be a streaming sound.
*/
const SoundData* soundData;
/** the destination filename for the sound data. This may be a relative or absolute
* path. For relative paths, these will be resolved according to the rules of the
* IFileSystem interface. This may not be nullptr.
*/
const char* filename;
/** additional output format dependent encoder settings. This should be nullptr for PCM
* data formats. Additional objects will be defined for encoder formats that require
* additional parameters (optional or otherwise). For formats that require additional
* settings, this may not be nullptr. Use getCodecFormatInfo() to retrieve the info
* for the codec to find out if the additional settings are required or not.
*/
void* encoderSettings = nullptr;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** base type for all output stream flags. */
typedef uint32_t OutputStreamFlags;
/** flag to indicate that an output stream should flush its file after each buffer is successfully
* written to it. By default, the stream will not be forced to be flushed until it is closed.
*/
constexpr OutputStreamFlags fStreamFlagFlushAfterWrite = 0x00000001;
/** flag to indicate that the stream should disable itself if an error is encountered writing a
* buffer of audio to the output. And example of a failure could be that the output file fails
* to be opened (ie: permissions issue, path doesn't exist, etc), or there was an encoding error
* with the chosen output format (extremely rare but possible). If such a failure occurs, the
* output stream will simply ignore new incoming data until the stream is closed. If this flag
* is not used, the default behavior is to continue trying to write to the stream. In this
* case, it is possible that the stream could recover and continue writing output again (ie:
* the folder containing the file suddenly was created), however doing so could lead to an
* audible artifact being introduced to the output stream.
*/
constexpr OutputStreamFlags fStreamFlagDisableOnFailure = 0x00000002;
/** a descriptor for opening an output file stream. This allows sound data to be written to a
* file in multiple chunks. The output stream will remain open and able to accept more input
* until it is closed. The output data can be encoded as it is written to the file for certain
* formats. Attempting to open the stream with a format that doesn't support encoding will
* cause the stream to fail.
*/
struct OutputStreamDesc
{
/** flags to control the behavior of the output stream. This may be 0 to specify default
* behavior.
*/
OutputStreamFlags flags = 0;
/** the filename to write the stream to. This may be a relative or absolute path. If a
* relative path is used, it will be resolved according to the rules of the IFileSystem
* interface. If the filename does not include a file extension, one will be added
* according to the requested output format. If no file extension is desired, the
* filename should end with a period ('.'). This may not be nullptr.
*/
const char* filename;
/** the input sample format for the stream. This will be the format of the data that is
* passed in the buffers to writeDataToStream().
* This must be a PCM format (one of SampleFormat::ePcm*).
*/
SampleFormat inputFormat;
/** the output sample format for the stream. This will be the format of the data that is
* written to the output file. If this matches the input data format, the buffer will
* simply be written to the file stream. This may be @ref SampleFormat::eDefault to use
* the same format as @ref inputFormat for the output.
*/
SampleFormat outputFormat = SampleFormat::eDefault;
/** the data rate of the stream in frames per second. This value is recorded to the
* stream but does not affect the actual consumption of data from the buffers.
*/
size_t frameRate;
/** the number of channels in each frame of the stream. */
size_t channels;
/** additional output format dependent encoder settings. This should be nullptr for PCM
* data formats. Additional objects will be defined for encoder formats that require
* additional parameters (optional or otherwise). For formats that require additional
* settings, this may not be nullptr. Use getCodecFormatInfo() to retrieve the info
* for the codec to find out if the additional settings are required or not.
*/
void* encoderSettings = nullptr;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/********************************* Audio Visualization Objects ***********************************/
/** Flags for @ref AudioImageDesc. */
using AudioImageFlags = uint32_t;
/** Don't clear out the image buffer with the background color before drawing.
* This is useful when drawing waveforms onto the same image buffer over
* multiple calls.
*/
constexpr AudioImageFlags fAudioImageNoClear = 0x01;
/** Draw lines between the individual samples when rendering. */
constexpr AudioImageFlags fAudioImageUseLines = 0x02;
/** Randomize The colors used for each sample. */
constexpr AudioImageFlags fAudioImageNoiseColor = 0x04;
/** Draw all the audio channels in the image on top of each other, rather than
* drawing one individual channel.
*/
constexpr AudioImageFlags fAudioImageMultiChannel = 0x08;
/** Perform alpha blending when drawing the samples/lines, rather than
* overwriting the pixels.
*/
constexpr AudioImageFlags fAudioImageAlphaBlend = 0x10;
/** Draw each audio channel as a separate waveform, organized vertically. */
constexpr AudioImageFlags fAudioImageSplitChannels = 0x20;
/** A descriptor for IAudioData::drawWaveform(). */
struct AudioImageDesc
{
/** Flags that alter the drawing style. */
AudioImageFlags flags;
/** The sound to render into the waveform. */
const SoundData* sound;
/** The length of @ref sound to render as an image.
* This may be 0 to render the entire sound.
*/
size_t length;
/** The offset into the sound to start visualizing.
* The region visualized will start at @ref offset and end at @ref offset
* + @ref length. If the region extends beyond the end of the sound, it
* will be internally clamped to the end of the sound.
* If this value is negative, then this is treated as an offset relative
* to the end of the file, rather than the start.
* This may be 0 to render the entire sound.
*/
int64_t offset;
/** The unit type of @ref length and @ref offset.
* Note that using @ref UnitType::eBytes with a variable bitrate format will
* not provide very accurate results.
*/
UnitType lengthType;
/** This specifies which audio channel from @ref sound will be rendered.
* This is ignored when @ref fAudioImageMultiChannel is set on @ref flags.
*/
size_t channel;
/** The buffer that holds the image data.
* The image format is RGBA8888.
* This must be @ref height * @ref pitch bytes long.
* This may not be nullptr.
*/
void* image;
/** The width of the image in pixels. */
size_t width;
/** The width of the image buffer in bytes.
* This can be set to 0 to use 4 * @ref width as the pitch.
* This may be used for applications such as writing a subimage or an
* image that needs some specific alignment.
*/
size_t pitch;
/** The height of the image in pixels. */
size_t height;
/** The background color to write to the image in normalized RGBA color.
* The alpha channel in this color is not used to blend this color with
* the existing data in @ref image; use @ref fAudioImageNoClear if you
* want to render on top of an existing image.
* This value is ignored when @ref fAudioImageNoClear is set on @ref flags.
*/
Float4 background;
/** The colors to use for the image in normalized RGBA colors.
* If @ref fAudioImageMultiChannel, each element in this array maps to each
* channel in the output audio data; otherwise, element 0 is used as the
* color for the single channel.
*/
Float4 colors[kMaxChannels];
};
/** General audio utilities.
* This interface contains a bunch of miscellaneous audio functionality that
* many audio applications can make use of.
*/
struct IAudioUtils
{
CARB_PLUGIN_INTERFACE("carb::audio::IAudioUtils", 1, 0)
/*************************** Sound Data Object Modifications ********************************/
/** clears a sound data object to silence.
*
* @param[in] sound the sound data object to clear. This may not be nullptr.
* @returns true if the clearing operation was successful.
* @returns false if the clearing operation was not successful.
* @note this will remove the SDO from user memory.
* @note this will clear the entire buffer, not just the valid portion.
* @note this will be a lossy operation for some formats.
*/
bool(CARB_ABI* clearToSilence)(SoundData* sound);
/**************************** Sound Data Saving and Streaming ********************************/
/** save a sound data object to a file.
*
* @param[in] desc a descriptor of how the sound data should be saved to file and which
* data format it should be written in. This may not be nullptr.
* @returns true if the sound data is successfully written out to file.
* @returns false if the sound data could not be written to file. This may include being
* unable to open or create the file, or if the requested output format could
* not be supported by the encoder.
*
* @remarks This attempts to save a sound data object to file. The destination data format
* in the file does not necessarily have to match the original sound data object.
* However, if the destination format does not match, the encoder for that format
* must be supported otherwise the operation will fail. Support for the requested
* encoder format may be queried with isCodecFormatSupported() to avoid exposing
* user facing functionality for formats that cannot be encoded.
*/
bool(CARB_ABI* saveToFile)(const SoundDataSaveDesc* desc);
/** opens a new output stream object.
*
* @param[in] desc a descriptor of how the stream should be opened. This may not be
* nullptr.
* @returns a new output stream handle if successfully created. This object must be closed
* with closeOutputStream() when it is no longer needed.
* @returns nullptr if the output stream could not be created. This may include being unable
* to open or create the file, or if the requested output format could not be
* supported by the encoder.
*
* @remarks This opens a new output stream and prepares it to receive buffers of data from
* the stream. The header will be written to the file, but it will initially
* represent an empty stream. The destination data format in the file does not
* necessarily have to match the original sound data object. However, if the
* destination format does not match, the encoder for that format must be supported
* otherwise the operation will fail. Support for the requested encoder format may
* be queried with isCodecFormatSupported() to avoid exposing user facing
* functionality for formats that cannot be encoded.
*/
OutputStream*(CARB_ABI* openOutputStream)(const OutputStreamDesc* desc);
/** closes an output stream.
*
* @param[in] stream the stream to be closed. This may not be nullptr. This must have
* been returned from a previous call to openOutputStream(). This
* object will no longer be valid upon return.
* @returns no return value.
*
* @remarks This closes an output stream object. The header for the file will always be
* updated so that it reflects the actual written stream size. Any additional
* updates for the chosen data format will be written to the file before closing
* as well.
*/
void(CARB_ABI* closeOutputStream)(OutputStream* stream);
/** writes a single buffer of data to an output stream.
*
* @param[in] stream the stream to write the buffer to. This handle must have
* been returned by a previous call to openOutputStream() and
* must not have been closed yet. This may not be nullptr.
* @param[in] data the buffer of data to write to the file. The data in this
* buffer is expected to be in data format specified when the
* output stream was opened. This buffer must be block aligned
* for the given input format. This may not be nullptr.
* @param[in] lengthInFrames the size of the buffer to write in frames. All frames in
* the buffer must be complete. Partial frames will neither
* be detected nor handled.
* @returns true if the buffer is successfully encoded and written to the stream.
* @returns false if the buffer could not be encoded or an error occurs writing it to the
* stream.
*
* @remarks This writes a single buffer of data to an open output stream. It is the caller's
* responsibility to ensure this new buffer is the logical continuation of any of
* the previous buffers that were written to the stream. The buffer will always be
* encoded and written to the stream in its entirety. If any extra frames of data
* do not fit into one of the output format's blocks, the remaining data will be
* cached in the encoder and added to by the next buffer. If the stream ends and
* the encoder still has a partial block waiting, it will be padded with silence
* and written to the stream when it is closed.
*/
bool(CARB_ABI* writeDataToStream)(OutputStream* stream, const void* data, size_t lengthInFrames);
/***************************** Sound Data Format Conversion **********************************/
/** converts a sound data object from one format to another.
*
* @param[in] desc the descriptor of how the conversion operation should be performed.
* This may not be nullptr.
* @returns the converted sound data object.
* @returns nullptr if the conversion could not occur.
*
* @remarks This converts a sound data object from one format to another or duplicates an
* object. The conversion operation may be performed on the same sound data object
* or it may create a new object. The returned sound data object always needs to
* be released with release() when it is no longer needed. This is true
* whether the original object was copied or not.
*
* @note The destruction callback is not copied to the returned SoundData
* even if an in-place conversion is requested.
*
* @note If @ref fConvertFlagInPlace is passed and the internal buffer
* of the input SoundData is being replaced, the original
* destruction callback on the input SoundData will be called.
*/
carb::audio::SoundData*(CARB_ABI* convert)(const ConversionDesc* desc);
/** duplicates a sound data object.
*
* @param[in] sound the sound data object to duplicate. This may not be nullptr.
* @returns the duplicated sound data object. This must be destroyed when it is no longer
* needed with a call to release().
*
* @remarks This duplicates a sound data object. The new object will have the same format
* and data content as the original. If the original referenced user memory, the
* new object will get a copy of its data, not the original pointer. If the new
* object should reference the original data instead, convert() should be
* used instead.
*/
carb::audio::SoundData*(CARB_ABI* duplicate)(const SoundData* sound);
/** A helper function to transcode between PCM formats.
*
* @param[in] desc The descriptor of how the conversion operation should be
* performed.
* This may not be nullptr.
* @returns true if the data is successfully transcoded.
* @returns false if an invalid parameter is passed in or the conversion was not possible.
* @returns false if the input buffer or the output buffer are misaligned for their
* specified sample format.
* createData() be used in cases where a misaligned buffer needs to be used
* (for example when reading raw PCM data from a memory-mapped file).
*
* @remarks This function is a simpler alternative to decodeData() for
* cases where it is known that both the input and output formats
* are PCM formats.
*
* @note There is no requirement for the alignment of @ref TranscodeDesc::inBuffer
* or @ref TranscodeDesc::outBuffer, but the operation is most
* efficient when both are 32 byte aligned
* (e.g. `(static_cast<uintptr_t>(inBuffer) & 0x1F) == 0`).
*
* @note It is valid for @ref TranscodeDesc::inFormat to be the same as
* @ref TranscodeDesc::outFormat; this is equivalent to calling
* memcpy().
*/
bool(CARB_ABI* transcodePcm)(const TranscodeDesc* desc);
/***************************** Audio Visualization *******************************************/
/** Render a SoundData's waveform as an image.
* @param[in] desc The descriptor for the audio waveform input and output.
*
* @returns true if visualization was successful.
* @returns false if no sound was specified.
* @returns false if the input image dimensions corresponded to a 0-size image
* or the buffer for the image was nullptr.
* @returns false if the region of the sound to visualize was 0 length.
* @returns false if the image pitch specified was non-zero and too small
* to fit an RGBA888 image of the desired width.
* @returns false if the specified channel to visualize was invalid.
*
* @remarks This function can be used to visualize the audio samples in a
* sound buffer as an uncompressed RGBA8888 image.
*/
bool(CARB_ABI* drawWaveform)(const AudioImageDesc* desc);
};
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/AudioBindingsPython.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "IAudioPlayback.h"
#include "IAudioData.h"
#include "IAudioUtils.h"
#include "AudioUtils.h"
namespace carb
{
namespace audio
{
/** A helper class to wrap the Voice* object for python.
* There is no way to actually create Voices from these bindings yet.
*
* @note This wrapper only exposes functions to alter voice parameters at the
* moment. This is done because IAudioPlayback is not thread-safe yet
* and allowing other changes would cause thread safety issues with
* Omniverse Kit.
*/
class PythonVoice
{
public:
PythonVoice(IAudioPlayback* iface, audio::Voice* voice)
{
m_iface = iface;
m_voice = voice;
}
void stop()
{
m_iface->stopVoice(m_voice);
}
bool isPlaying()
{
return m_iface->isPlaying(m_voice);
}
bool setLoopPoint(const LoopPointDesc* desc)
{
return m_iface->setLoopPoint(m_voice, desc);
}
size_t getPlayCursor(UnitType type)
{
return m_iface->getPlayCursor(m_voice, type);
}
void setParameters(VoiceParamFlags paramsToSet, const VoiceParams* params)
{
m_iface->setVoiceParameters(m_voice, paramsToSet, params);
}
void getParameters(VoiceParamFlags paramsToGet, VoiceParams* params)
{
m_iface->getVoiceParameters(m_voice, paramsToGet, params);
}
void setPlaybackMode(PlaybackModeFlags mode)
{
VoiceParams params = {};
params.playbackMode = mode;
m_iface->setVoiceParameters(m_voice, fVoiceParamPlaybackMode, ¶ms);
}
void setVolume(float volume)
{
VoiceParams params = {};
params.volume = volume;
m_iface->setVoiceParameters(m_voice, fVoiceParamVolume, ¶ms);
}
void setMute(bool muted)
{
VoiceParams params = {};
params.playbackMode = muted ? fPlaybackModeMuted : 0;
m_iface->setVoiceParameters(m_voice, fVoiceParamMute, ¶ms);
}
void setBalance(float pan, float fade)
{
VoiceParams params = {};
params.balance.pan = pan;
params.balance.fade = fade;
m_iface->setVoiceParameters(m_voice, fVoiceParamBalance, ¶ms);
}
void setFrequencyRatio(float ratio)
{
VoiceParams params = {};
params.frequencyRatio = ratio;
m_iface->setVoiceParameters(m_voice, fVoiceParamFrequencyRatio, ¶ms);
}
void setPriority(int32_t priority)
{
VoiceParams params = {};
params.priority = priority;
m_iface->setVoiceParameters(m_voice, fVoiceParamPriority, ¶ms);
}
void setSpatialMixLevel(float level)
{
VoiceParams params = {};
params.spatialMixLevel = level;
m_iface->setVoiceParameters(m_voice, fVoiceParamSpatialMixLevel, ¶ms);
}
void setDopplerScale(float scale)
{
VoiceParams params = {};
params.dopplerScale = scale;
m_iface->setVoiceParameters(m_voice, fVoiceParamDopplerScale, ¶ms);
}
void setOcclusion(float direct, float reverb)
{
VoiceParams params = {};
params.occlusion.direct = direct;
params.occlusion.reverb = reverb;
m_iface->setVoiceParameters(m_voice, fVoiceParamOcclusionFactor, ¶ms);
}
void setMatrix(std::vector<float> matrix)
{
// FIXME: This should probably validate the source/destination channels.
// We can get the source channels by retrieving the currently playing sound,
// but we have no way to retrieve the context's channel count here.
VoiceParams params = {};
params.matrix = matrix.data();
m_iface->setVoiceParameters(m_voice, fVoiceParamMatrix, ¶ms);
}
void setPosition(Float3 position)
{
VoiceParams params = {};
params.emitter.flags = fEntityFlagPosition;
params.emitter.position = position;
m_iface->setVoiceParameters(m_voice, fVoiceParamEmitter, ¶ms);
}
void setVelocity(Float3 velocity)
{
VoiceParams params = {};
params.emitter.flags = fEntityFlagVelocity;
params.emitter.velocity = velocity;
m_iface->setVoiceParameters(m_voice, fVoiceParamEmitter, ¶ms);
}
void setRolloffCurve(RolloffType type,
float nearDistance,
float farDistance,
std::vector<Float2>& volume,
std::vector<Float2>& lowFrequency,
std::vector<Float2>& lowPassDirect,
std::vector<Float2>& lowPassReverb,
std::vector<Float2>& reverb)
{
RolloffCurve volumeCurve = {};
RolloffCurve lowFrequencyCurve = {};
RolloffCurve lowPassDirectCurve = {};
RolloffCurve lowPassReverbCurve = {};
RolloffCurve reverbCurve = {};
VoiceParams params = {};
params.emitter.flags = fEntityFlagRolloff;
params.emitter.rolloff.type = type;
params.emitter.rolloff.nearDistance = nearDistance;
params.emitter.rolloff.farDistance = farDistance;
if (!volume.empty())
{
volumeCurve.points = volume.data();
volumeCurve.pointCount = volume.size();
params.emitter.rolloff.volume = &volumeCurve;
}
if (!lowFrequency.empty())
{
lowFrequencyCurve.points = lowFrequency.data();
lowFrequencyCurve.pointCount = lowFrequency.size();
params.emitter.rolloff.lowFrequency = &lowFrequencyCurve;
}
if (!lowPassDirect.empty())
{
lowPassDirectCurve.points = lowPassDirect.data();
lowPassDirectCurve.pointCount = lowPassDirect.size();
params.emitter.rolloff.lowPassDirect = &lowPassDirectCurve;
}
if (!lowPassReverb.empty())
{
lowPassReverbCurve.points = lowPassReverb.data();
lowPassReverbCurve.pointCount = lowPassReverb.size();
params.emitter.rolloff.lowPassReverb = &lowPassReverbCurve;
}
if (!reverb.empty())
{
reverbCurve.points = reverb.data();
reverbCurve.pointCount = reverb.size();
params.emitter.rolloff.reverb = &reverbCurve;
}
m_iface->setVoiceParameters(m_voice, fVoiceParamEmitter, ¶ms);
}
private:
Voice* m_voice;
IAudioPlayback* m_iface;
};
class PythonSoundData
{
public:
PythonSoundData(IAudioData* iface, SoundData* data) noexcept
{
m_iface = iface;
m_data = data;
m_utils = carb::getFramework()->acquireInterface<IAudioUtils>();
}
~PythonSoundData() noexcept
{
m_iface->release(m_data);
}
static PythonSoundData* fromRawBlob(IAudioData* iface,
const void* blob,
size_t samples,
SampleFormat format,
size_t channels,
size_t frameRate,
SpeakerMode channelMask)
{
SoundFormat fmt;
size_t bytes = samples * sampleFormatToBitsPerSample(format) / CHAR_BIT;
SoundData* tmp;
generateSoundFormat(&fmt, format, channels, frameRate, channelMask);
tmp = createSoundFromRawPcmBlob(iface, blob, bytes, bytesToFrames(bytes, &fmt), &fmt);
if (tmp == nullptr)
throw std::runtime_error("failed to create a SoundData object");
return new PythonSoundData(iface, tmp);
}
const char* getName()
{
return m_iface->getName(m_data);
}
bool isDecoded()
{
return (m_iface->getFlags(m_data) & fDataFlagStream) == 0;
}
SoundFormat getFormat()
{
SoundFormat fmt;
m_iface->getFormat(m_data, CodecPart::eEncoder, &fmt);
return fmt;
}
size_t getLength(UnitType units)
{
return m_iface->getLength(m_data, units);
}
void setValidLength(size_t length, UnitType units)
{
m_iface->setValidLength(m_data, length, units);
}
size_t getValidLength(UnitType units)
{
return m_iface->getValidLength(m_data, units);
}
std::vector<uint8_t> getBufferU8(size_t offset, size_t length, UnitType units)
{
return getBuffer<uint8_t>(offset, length, units);
}
std::vector<int16_t> getBufferS16(size_t offset, size_t length, UnitType units)
{
return getBuffer<int16_t>(offset, length, units);
}
std::vector<int32_t> getBufferS32(size_t offset, size_t length, UnitType units)
{
return getBuffer<int32_t>(offset, length, units);
}
std::vector<float> getBufferFloat(size_t offset, size_t length, UnitType units)
{
return getBuffer<float>(offset, length, units);
}
void writeBufferU8(const std::vector<uint8_t>& data, size_t offset, UnitType units)
{
return writeBuffer<uint8_t>(data, offset, units);
}
void writeBufferS16(const std::vector<int16_t>& data, size_t offset, UnitType units)
{
return writeBuffer<int16_t>(data, offset, units);
}
void writeBufferS32(const std::vector<int32_t>& data, size_t offset, UnitType units)
{
return writeBuffer<int32_t>(data, offset, units);
}
void writeBufferFloat(const std::vector<float>& data, size_t offset, UnitType units)
{
return writeBuffer<float>(data, offset, units);
}
size_t getMemoryUsed()
{
return m_iface->getMemoryUsed(m_data);
}
uint32_t getMaxInstances()
{
return m_iface->getMaxInstances(m_data);
}
void setMaxInstances(uint32_t limit)
{
m_iface->setMaxInstances(m_data, limit);
}
PeakVolumes getPeakLevel()
{
PeakVolumes vol;
if (!m_iface->getPeakLevel(m_data, &vol))
{
throw std::runtime_error("this sound has no peak volume information");
}
return vol;
}
std::vector<EventPoint> getEventPoints()
{
size_t count = m_iface->getEventPoints(m_data, nullptr, 0);
size_t retrieved;
std::vector<EventPoint> out;
out.resize(count);
retrieved = m_iface->getEventPoints(m_data, out.data(), count);
if (retrieved < count)
{
CARB_LOG_ERROR("retrieved fewer event points than expected (%zu < %zu)\n", retrieved, count);
out.resize(retrieved);
}
return out;
}
const EventPoint* getEventPointById(EventPointId id)
{
return wrapEventPoint(m_iface->getEventPointById(m_data, id));
}
const EventPoint* getEventPointByIndex(size_t index)
{
return wrapEventPoint(m_iface->getEventPointByIndex(m_data, index));
}
const EventPoint* getEventPointByPlayIndex(size_t index)
{
return wrapEventPoint(m_iface->getEventPointByPlayIndex(m_data, index));
}
size_t getEventPointMaxPlayIndex()
{
return m_iface->getEventPointMaxPlayIndex(m_data);
}
bool setEventPoints(std::vector<EventPoint> eventPoints)
{
// text does not work properly in bindings
for (size_t i = 0; i < eventPoints.size(); i++)
{
eventPoints[i].label = nullptr;
eventPoints[i].text = nullptr;
}
return m_iface->setEventPoints(m_data, eventPoints.data(), eventPoints.size());
}
void clearEventPoints()
{
m_iface->setEventPoints(m_data, kEventPointTableClear, 0);
}
std::pair<const char*, const char*> getMetaDataByIndex(size_t index)
{
const char* value;
const char* key = m_iface->getMetaDataTagName(m_data, index, &value);
return std::pair<const char*, const char*>(key, value);
}
const char* getMetaData(const char* tagName)
{
return m_iface->getMetaData(m_data, tagName);
}
bool setMetaData(const char* tagName, const char* tagValue)
{
return m_iface->setMetaData(m_data, tagName, tagValue);
}
bool saveToFile(const char* fileName, SampleFormat format = SampleFormat::eDefault, SaveFlags flags = 0)
{
return saveSoundToDisk(m_utils, m_data, fileName, format, flags);
}
SoundData* getNativeObject()
{
return m_data;
}
private:
EventPoint* wrapEventPoint(const EventPoint* point)
{
if (point == nullptr)
return nullptr;
EventPoint* out = new EventPoint;
*out = *point;
return out;
}
template <typename T>
SampleFormat getFormatFromType()
{
// I'd do this with template specialization but GCC won't accept that
// for some reason
if (std::is_same<T, uint8_t>::value)
{
return SampleFormat::ePcm8;
}
else if (std::is_same<T, int16_t>::value)
{
return SampleFormat::ePcm16;
}
else if (std::is_same<T, int32_t>::value)
{
return SampleFormat::ePcm32;
}
else if (std::is_same<T, float>::value)
{
return SampleFormat::ePcmFloat;
}
else
{
return SampleFormat::eDefault;
}
}
template <typename T>
std::vector<T> getBuffer(size_t offset, size_t length, UnitType units)
{
size_t samples;
size_t soundLength = getValidLength(UnitType::eFrames);
SoundFormat fmt = getFormat();
std::vector<T> out;
if (units == UnitType::eBytes && offset % fmt.frameSize != 0)
{
throw std::runtime_error("byte offset was not aligned correctly for the data type");
}
length = convertUnits(length, units, UnitType::eFrames, &fmt);
offset = convertUnits(offset, units, UnitType::eFrames, &fmt);
if (length == 0 || length > soundLength)
length = soundLength;
if (length == 0)
return {};
offset = CARB_MIN(soundLength - 1, offset);
if (offset + length > soundLength)
{
length = soundLength - offset;
}
samples = length * fmt.channels;
out.resize(samples);
if (isDecoded())
{
size_t byteOffset = convertUnits(offset, UnitType::eFrames, UnitType::eBytes, &fmt);
const void* buffer = m_iface->getReadBuffer(m_data);
writeGenericBuffer(static_cast<const uint8_t*>(buffer) + byteOffset, out.data(), fmt.format,
getFormatFromType<T>(), samples);
}
else
{
size_t decoded = 0;
CodecState* state = nullptr;
CodecStateDesc desc = {};
desc.part = CodecPart::eDecoder;
desc.decode.flags =
fDecodeStateFlagCoarseSeek | fDecodeStateFlagSkipMetaData | fDecodeStateFlagSkipEventPoints;
desc.decode.soundData = m_data;
desc.decode.outputFormat = getFormatFromType<T>();
desc.decode.readCallbackContext = nullptr;
desc.decode.ext = nullptr;
state = m_iface->createCodecState(&desc);
if (state == nullptr)
{
m_iface->destroyCodecState(state);
throw std::runtime_error("failed to initialize the decoder");
}
if (offset != 0 && !m_iface->setCodecPosition(state, offset, UnitType::eFrames))
{
m_iface->destroyCodecState(state);
throw std::runtime_error("failed to seek into the sound");
}
if (m_iface->decodeData(state, out.data(), length, &decoded) == nullptr)
{
m_iface->destroyCodecState(state);
throw std::runtime_error("failed to decode the sound");
}
if (decoded < length)
{
CARB_LOG_ERROR("decoded fewer frames that expected (%zu < %zu)\n", decoded, length);
out.resize(decoded * fmt.channels);
}
m_iface->destroyCodecState(state);
}
return out;
}
template <typename T>
void writeBuffer(const std::vector<T>& data, size_t offset, UnitType units)
{
SoundFormat fmt = getFormat();
void* buffer = m_iface->getBuffer(m_data);
size_t length = data.size();
size_t maxLength = getLength(UnitType::eBytes);
if (!isDecoded())
{
throw std::runtime_error("this SoundData object is read-only");
}
if (units == UnitType::eBytes && offset % fmt.frameSize != 0)
{
throw std::runtime_error("byte offset was not aligned correctly for the data type");
}
offset = convertUnits(offset, units, UnitType::eBytes, &fmt);
if (offset + length > maxLength)
{
length = maxLength - offset;
}
writeGenericBuffer(
data.data(), static_cast<uint8_t*>(buffer) + offset, getFormatFromType<T>(), fmt.format, length);
}
void writeGenericBuffer(const void* in, void* out, SampleFormat inFmt, SampleFormat outFmt, size_t samples)
{
if (inFmt != outFmt)
{
TranscodeDesc desc = {};
desc.inFormat = inFmt;
desc.outFormat = outFmt;
desc.inBuffer = in;
desc.outBuffer = out;
desc.samples = samples;
if (!m_utils->transcodePcm(&desc))
throw std::runtime_error("PCM transcoding failed unexpectedly");
}
else
{
memcpy(out, in, samples * sampleFormatToBitsPerSample(inFmt) / CHAR_BIT);
}
}
IAudioData* m_iface;
IAudioUtils* m_utils;
SoundData* m_data;
};
/** A helper class to wrap the Context* object for python.
* There is no way to actually create or destroy the Context* object in these
* bindings yet.
*
* @note This wrapper only exposes functions to alter Context parameters at the
* moment. This is done because IAudioPlayback is not thread-safe yet
* and allowing other changes would cause thread safety issues with
* Omniverse Kit.
*/
class PythonContext
{
public:
PythonContext(IAudioPlayback* iface, Context* context) : m_context(context), m_iface(iface)
{
}
/** Wrappers for IAudioPlayback functions @{ */
const ContextCaps* getContextCaps()
{
return m_iface->getContextCaps(m_context);
}
void setContextParameters(ContextParamFlags paramsToSet, const ContextParams* params)
{
m_iface->setContextParameters(m_context, paramsToSet, params);
}
void getContextParameters(ContextParamFlags paramsToGet, ContextParams* params)
{
m_iface->getContextParameters(m_context, paramsToGet, params);
}
PythonVoice* playSound(PythonSoundData* sound,
PlayFlags flags,
VoiceParamFlags validParams,
VoiceParams* params,
EventPoint* loopPoint,
size_t playStart,
size_t playLength,
UnitType playUnits)
{
PlaySoundDesc desc = {};
desc.flags = flags;
desc.sound = sound->getNativeObject();
desc.validParams = validParams;
desc.params = params;
desc.loopPoint.loopPoint = loopPoint;
if (loopPoint != nullptr)
{
desc.loopPoint.loopPointIndex = 0;
}
desc.playStart = playStart;
desc.playLength = playLength;
desc.playUnits = playUnits;
return new PythonVoice(m_iface, m_iface->playSound(m_context, &desc));
}
/** @} */
private:
Context* m_context;
IAudioPlayback* m_iface;
};
inline void definePythonModule(py::module& m)
{
const char* docString;
/////// AudioTypes.h ///////
m.attr("MAX_NAME_LENGTH") = py::int_(kMaxNameLength);
m.attr("MAX_CHANNELS") = py::int_(kMaxChannels);
m.attr("MIN_CHANNELS") = py::int_(kMinChannels);
m.attr("MAX_FRAMERATE") = py::int_(kMaxFrameRate);
m.attr("MIN_FRAMERATE") = py::int_(kMinFrameRate);
py::enum_<AudioResult>(m, "AudioResult")
.value("OK", AudioResult::eOk)
.value("DEVICE_DISCONNECTED", AudioResult::eDeviceDisconnected)
.value("DEVICE_LOST", AudioResult::eDeviceLost)
.value("DEVICE_NOT_OPEN", AudioResult::eDeviceNotOpen)
.value("DEVICE_OPEN", AudioResult::eDeviceOpen)
.value("OUT_OF_RANGE", AudioResult::eOutOfRange)
.value("TRY_AGAIN", AudioResult::eTryAgain)
.value("OUT_OF_MEMORY", AudioResult::eOutOfMemory)
.value("INVALID_PARAMETER", AudioResult::eInvalidParameter)
.value("NOT_ALLOWED", AudioResult::eNotAllowed)
.value("NOT_FOUND", AudioResult::eNotFound)
.value("IO_ERROR", AudioResult::eIoError)
.value("INVALID_FORMAT", AudioResult::eInvalidFormat)
.value("NOT_SUPPORTED", AudioResult::eNotSupported);
py::enum_<Speaker>(m, "Speaker")
.value("FRONT_LEFT", Speaker::eFrontLeft)
.value("FRONT_RIGHT", Speaker::eFrontRight)
.value("FRONT_CENTER", Speaker::eFrontCenter)
.value("LOW_FREQUENCY_EFFECT", Speaker::eLowFrequencyEffect)
.value("BACK_LEFT", Speaker::eBackLeft)
.value("BACK_RIGHT", Speaker::eBackRight)
.value("BACK_CENTER", Speaker::eBackCenter)
.value("SIDE_LEFT", Speaker::eSideLeft)
.value("SIDE_RIGHT", Speaker::eSideRight)
.value("TOP_FRONT_LEFT", Speaker::eTopFrontLeft)
.value("TOP_FRONT_RIGHT", Speaker::eTopFrontRight)
.value("TOP_BACK_LEFT", Speaker::eTopBackLeft)
.value("TOP_BACK_RIGHT", Speaker::eTopBackRight)
.value("FRONT_LEFT_WIDE", Speaker::eFrontLeftWide)
.value("FRONT_RIGHT_WIDE", Speaker::eFrontRightWide)
.value("TOP_LEFT", Speaker::eTopLeft)
.value("TOP_RIGHT", Speaker::eTopRight)
.value("COUNT", Speaker::eCount);
m.attr("SPEAKER_FLAG_FRONT_LEFT") = py::int_(fSpeakerFlagFrontLeft);
m.attr("SPEAKER_FLAG_FRONT_RIGHT") = py::int_(fSpeakerFlagFrontRight);
m.attr("SPEAKER_FLAG_FRONT_CENTER") = py::int_(fSpeakerFlagFrontCenter);
m.attr("SPEAKER_FLAG_LOW_FREQUENCY_EFFECT") = py::int_(fSpeakerFlagLowFrequencyEffect);
m.attr("SPEAKER_FLAG_BACK_LEFT") = py::int_(fSpeakerFlagSideLeft);
m.attr("SPEAKER_FLAG_BACK_RIGHT") = py::int_(fSpeakerFlagSideRight);
m.attr("SPEAKER_FLAG_BACK_CENTER") = py::int_(fSpeakerFlagBackLeft);
m.attr("SPEAKER_FLAG_SIDE_LEFT") = py::int_(fSpeakerFlagBackRight);
m.attr("SPEAKER_FLAG_SIDE_RIGHT") = py::int_(fSpeakerFlagBackCenter);
m.attr("SPEAKER_FLAG_TOP_FRONT_LEFT") = py::int_(fSpeakerFlagTopFrontLeft);
m.attr("SPEAKER_FLAG_TOP_FRONT_RIGHT") = py::int_(fSpeakerFlagTopFrontRight);
m.attr("SPEAKER_FLAG_TOP_BACK_LEFT") = py::int_(fSpeakerFlagTopBackLeft);
m.attr("SPEAKER_FLAG_TOP_BACK_RIGHT") = py::int_(fSpeakerFlagTopBackRight);
m.attr("SPEAKER_FLAG_FRONT_LEFT_WIDE") = py::int_(fSpeakerFlagFrontLeftWide);
m.attr("SPEAKER_FLAG_FRONT_RIGHT_WIDE") = py::int_(fSpeakerFlagFrontRightWide);
m.attr("SPEAKER_FLAG_TOP_LEFT") = py::int_(fSpeakerFlagTopLeft);
m.attr("SPEAKER_FLAG_TOP_RIGHT") = py::int_(fSpeakerFlagTopRight);
m.attr("INVALID_SPEAKER_NAME") = py::int_(kInvalidSpeakerName);
m.attr("SPEAKER_MODE_DEFAULT") = py::int_(kSpeakerModeDefault);
m.attr("SPEAKER_MODE_MONO") = py::int_(kSpeakerModeMono);
m.attr("SPEAKER_MODE_STEREO") = py::int_(kSpeakerModeStereo);
m.attr("SPEAKER_MODE_TWO_POINT_ONE") = py::int_(kSpeakerModeTwoPointOne);
m.attr("SPEAKER_MODE_QUAD") = py::int_(kSpeakerModeQuad);
m.attr("SPEAKER_MODE_FOUR_POINT_ONE") = py::int_(kSpeakerModeFourPointOne);
m.attr("SPEAKER_MODE_FIVE_POINT_ONE") = py::int_(kSpeakerModeFivePointOne);
m.attr("SPEAKER_MODE_SIX_POINT_ONE") = py::int_(kSpeakerModeSixPointOne);
m.attr("SPEAKER_MODE_SEVEN_POINT_ONE") = py::int_(kSpeakerModeSevenPointOne);
m.attr("SPEAKER_MODE_NINE_POINT_ONE") = py::int_(kSpeakerModeNinePointOne);
m.attr("SPEAKER_MODE_SEVEN_POINT_ONE_POINT_FOUR") = py::int_(kSpeakerModeSevenPointOnePointFour);
m.attr("SPEAKER_MODE_NINE_POINT_ONE_POINT_FOUR") = py::int_(kSpeakerModeNinePointOnePointFour);
m.attr("SPEAKER_MODE_NINE_POINT_ONE_POINT_SIX") = py::int_(kSpeakerModeNinePointOnePointSix);
m.attr("SPEAKER_MODE_THREE_POINT_ZERO") = py::int_(kSpeakerModeThreePointZero);
m.attr("SPEAKER_MODE_FIVE_POINT_ZERO") = py::int_(kSpeakerModeFivePointZero);
m.attr("SPEAKER_MODE_COUNT") = py::int_(kSpeakerModeCount);
m.attr("SPEAKER_MODE_VALID_BITS") = py::int_(fSpeakerModeValidBits);
m.attr("DEVICE_FLAG_NOT_OPEN") = py::int_(fDeviceFlagNotOpen);
m.attr("DEVICE_FLAG_CONNECTED") = py::int_(fDeviceFlagConnected);
m.attr("DEVICE_FLAG_DEFAULT") = py::int_(fDeviceFlagDefault);
m.attr("DEVICE_FLAG_STREAMER") = py::int_(fDeviceFlagStreamer);
// TODO: bind UserData
py::enum_<SampleFormat>(m, "SampleFormat")
.value("PCM8", SampleFormat::ePcm8)
.value("PCM16", SampleFormat::ePcm16)
.value("PCM24", SampleFormat::ePcm24)
.value("PCM32", SampleFormat::ePcm32)
.value("PCM_FLOAT", SampleFormat::ePcmFloat)
.value("PCM_COUNT", SampleFormat::ePcmCount)
.value("VORBIS", SampleFormat::eVorbis)
.value("FLAC", SampleFormat::eFlac)
.value("OPUS", SampleFormat::eOpus)
.value("MP3", SampleFormat::eMp3)
.value("RAW", SampleFormat::eRaw)
.value("DEFAULT", SampleFormat::eDefault)
.value("COUNT", SampleFormat::eCount);
// this is intentionally not bound since there is currently no python
// functionality that could make use of this behavior
// m.attr("AUDIO_IMAGE_FLAG_NO_CLEAR") = py::int_(fAudioImageNoClear);
m.attr("AUDIO_IMAGE_FLAG_USE_LINES") = py::int_(fAudioImageUseLines);
m.attr("AUDIO_IMAGE_FLAG_NOISE_COLOR") = py::int_(fAudioImageNoiseColor);
m.attr("AUDIO_IMAGE_FLAG_MULTI_CHANNEL") = py::int_(fAudioImageMultiChannel);
m.attr("AUDIO_IMAGE_FLAG_ALPHA_BLEND") = py::int_(fAudioImageAlphaBlend);
m.attr("AUDIO_IMAGE_FLAG_SPLIT_CHANNELS") = py::int_(fAudioImageSplitChannels);
py::class_<SoundFormat>(m, "SoundFormat")
.def_readwrite("channels", &SoundFormat::channels)
.def_readwrite("bits_per_sample", &SoundFormat::bitsPerSample)
.def_readwrite("frame_size", &SoundFormat::frameSize)
.def_readwrite("block_size", &SoundFormat::blockSize)
.def_readwrite("frames_per_block", &SoundFormat::framesPerBlock)
.def_readwrite("frame_rate", &SoundFormat::frameRate)
.def_readwrite("channel_mask", &SoundFormat::channelMask)
.def_readwrite("valid_bits_per_sample", &SoundFormat::validBitsPerSample)
.def_readwrite("format", &SoundFormat::format);
m.attr("INVALID_DEVICE_INDEX") = py::int_(kInvalidDeviceIndex);
// DeviceCaps::thisSize isn't readable and is always constructed to sizeof(DeviceCaps)
py::class_<DeviceCaps>(m, "DeviceCaps")
.def_readwrite("index", &DeviceCaps::index)
.def_readwrite("flags", &DeviceCaps::flags)
.def_readwrite("guid", &DeviceCaps::guid)
.def_readwrite("channels", &DeviceCaps::channels)
.def_readwrite("frame_rate", &DeviceCaps::frameRate)
.def_readwrite("format", &DeviceCaps::format)
// python doesn't seem to like it when an array member is exposed
.def("get_name", [](const DeviceCaps* self) -> const char* { return self->name; });
m.attr("DEFAULT_FRAME_RATE") = py::int_(kDefaultFrameRate);
m.attr("DEFAULT_CHANNEL_COUNT") = py::int_(kDefaultChannelCount);
// FIXME: this doesn't work
// m.attr("DEFAULT_FORMAT") = py::enum_<SampleFormat>(kDefaultFormat);
/////// IAudioPlayback.h ///////
m.attr("CONTEXT_PARAM_ALL") = py::int_(fContextParamAll);
m.attr("CONTEXT_PARAM_SPEED_OF_SOUND") = py::int_(fContextParamSpeedOfSound);
m.attr("CONTEXT_PARAM_WORLD_UNIT_SCALE") = py::int_(fContextParamWorldUnitScale);
m.attr("CONTEXT_PARAM_LISTENER") = py::int_(fContextParamListener);
m.attr("CONTEXT_PARAM_DOPPLER_SCALE") = py::int_(fContextParamDopplerScale);
m.attr("CONTEXT_PARAM_VIRTUALIZATION_THRESHOLD") = py::int_(fContextParamVirtualizationThreshold);
m.attr("CONTEXT_PARAM_SPATIAL_FREQUENCY_RATIO") = py::int_(fContextParamSpatialFrequencyRatio);
m.attr("CONTEXT_PARAM_NON_SPATIAL_FREQUENCY_RATIO") = py::int_(fContextParamNonSpatialFrequencyRatio);
m.attr("CONTEXT_PARAM_MASTER_VOLUME") = py::int_(fContextParamMasterVolume);
m.attr("CONTEXT_PARAM_SPATIAL_VOLUME") = py::int_(fContextParamSpatialVolume);
m.attr("CONTEXT_PARAM_NON_SPATIAL_VOLUME") = py::int_(fContextParamNonSpatialVolume);
m.attr("CONTEXT_PARAM_DOPPLER_LIMIT") = py::int_(fContextParamDopplerLimit);
m.attr("CONTEXT_PARAM_DEFAULT_PLAYBACK_MODE") = py::int_(fContextParamDefaultPlaybackMode);
m.attr("CONTEXT_PARAM_VIDEO_LATENCY") = py::int_(fContextParamVideoLatency);
m.attr("DEFAULT_SPEED_OF_SOUND") = py::float_(kDefaultSpeedOfSound);
m.attr("VOICE_PARAM_ALL") = py::int_(fVoiceParamAll);
m.attr("VOICE_PARAM_PLAYBACK_MODE") = py::int_(fVoiceParamPlaybackMode);
m.attr("VOICE_PARAM_VOLUME") = py::int_(fVoiceParamVolume);
m.attr("VOICE_PARAM_MUTE") = py::int_(fVoiceParamMute);
m.attr("VOICE_PARAM_BALANCE") = py::int_(fVoiceParamBalance);
m.attr("VOICE_PARAM_FREQUENCY_RATIO") = py::int_(fVoiceParamFrequencyRatio);
m.attr("VOICE_PARAM_PRIORITY") = py::int_(fVoiceParamPriority);
m.attr("VOICE_PARAM_PAUSE") = py::int_(fVoiceParamPause);
m.attr("VOICE_PARAM_SPATIAL_MIX_LEVEL") = py::int_(fVoiceParamSpatialMixLevel);
m.attr("VOICE_PARAM_DOPPLER_SCALE") = py::int_(fVoiceParamDopplerScale);
m.attr("VOICE_PARAM_OCCLUSION_FACTOR") = py::int_(fVoiceParamOcclusionFactor);
m.attr("VOICE_PARAM_EMITTER") = py::int_(fVoiceParamEmitter);
m.attr("VOICE_PARAM_MATRIX") = py::int_(fVoiceParamMatrix);
m.attr("PLAYBACK_MODE_SPATIAL") = py::int_(fPlaybackModeSpatial);
m.attr("PLAYBACK_MODE_LISTENER_RELATIVE") = py::int_(fPlaybackModeListenerRelative);
m.attr("PLAYBACK_MODE_DISTANCE_DELAY") = py::int_(fPlaybackModeDistanceDelay);
m.attr("PLAYBACK_MODE_INTERAURAL_DELAY") = py::int_(fPlaybackModeInterauralDelay);
m.attr("PLAYBACK_MODE_USE_DOPPLER") = py::int_(fPlaybackModeUseDoppler);
m.attr("PLAYBACK_MODE_USE_REVERB") = py::int_(fPlaybackModeUseReverb);
m.attr("PLAYBACK_MODE_USE_FILTERS") = py::int_(fPlaybackModeUseFilters);
m.attr("PLAYBACK_MODE_MUTED") = py::int_(fPlaybackModeMuted);
m.attr("PLAYBACK_MODE_PAUSED") = py::int_(fPlaybackModePaused);
m.attr("PLAYBACK_MODE_FADE_IN") = py::int_(fPlaybackModeFadeIn);
m.attr("PLAYBACK_MODE_SIMULATE_POSITION") = py::int_(fPlaybackModeSimulatePosition);
m.attr("PLAYBACK_MODE_NO_POSITION_SIMULATION") = py::int_(fPlaybackModeNoPositionSimulation);
m.attr("PLAYBACK_MODE_SPATIAL_MIX_LEVEL_MATRIX") = py::int_(fPlaybackModeSpatialMixLevelMatrix);
m.attr("PLAYBACK_MODE_NO_SPATIAL_LOW_FREQUENCY_EFFECT") = py::int_(fPlaybackModeNoSpatialLowFrequencyEffect);
m.attr("PLAYBACK_MODE_STOP_ON_SIMULATION") = py::int_(fPlaybackModeStopOnSimulation);
m.attr("PLAYBACK_MODE_DEFAULT_USE_DOPPLER") = py::int_(fPlaybackModeDefaultUseDoppler);
m.attr("PLAYBACK_MODE_DEFAULT_DISTANCE_DELAY") = py::int_(fPlaybackModeDefaultDistanceDelay);
m.attr("PLAYBACK_MODE_DEFAULT_INTERAURAL_DELAY") = py::int_(fPlaybackModeDefaultInterauralDelay);
m.attr("PLAYBACK_MODE_DEFAULT_USE_REVERB") = py::int_(fPlaybackModeDefaultUseReverb);
m.attr("PLAYBACK_MODE_DEFAULT_USE_FILTERS") = py::int_(fPlaybackModeDefaultUseFilters);
m.attr("ENTITY_FLAG_ALL") = py::int_(fEntityFlagAll);
m.attr("ENTITY_FLAG_POSITION") = py::int_(fEntityFlagPosition);
m.attr("ENTITY_FLAG_VELOCITY") = py::int_(fEntityFlagVelocity);
m.attr("ENTITY_FLAG_FORWARD") = py::int_(fEntityFlagForward);
m.attr("ENTITY_FLAG_UP") = py::int_(fEntityFlagUp);
m.attr("ENTITY_FLAG_CONE") = py::int_(fEntityFlagCone);
m.attr("ENTITY_FLAG_ROLLOFF") = py::int_(fEntityFlagRolloff);
m.attr("ENTITY_FLAG_MAKE_PERP") = py::int_(fEntityFlagMakePerp);
m.attr("ENTITY_FLAG_NORMALIZE") = py::int_(fEntityFlagNormalize);
py::enum_<RolloffType>(m, "RolloffType")
.value("INVERSE", RolloffType::eInverse)
.value("LINEAR", RolloffType::eLinear)
.value("LINEAR_SQUARE", RolloffType::eLinearSquare);
m.attr("INSTANCES_UNLIMITED") = py::int_(kInstancesUnlimited);
// this won't be done through flags in python
// m.attr("DATA_FLAG_FORMAT_MASK") = py::int_(fDataFlagFormatMask);
// m.attr("DATA_FLAG_FORMAT_AUTO") = py::int_(fDataFlagFormatAuto);
// m.attr("DATA_FLAG_FORMAT_RAW") = py::int_(fDataFlagFormatRaw);
// m.attr("DATA_FLAG_IN_MEMORY") = py::int_(fDataFlagInMemory);
// m.attr("DATA_FLAG_STREAM") = py::int_(fDataFlagStream);
// m.attr("DATA_FLAG_DECODE") = py::int_(fDataFlagDecode);
// m.attr("DATA_FLAG_FORMAT_PCM") = py::int_(fDataFlagFormatPcm);
// m.attr("DATA_FLAG_EMPTY") = py::int_(fDataFlagEmpty);
// m.attr("DATA_FLAG_NO_NAME") = py::int_(fDataFlagNoName);
// this won't ever be supported in python
// m.attr("DATA_FLAG_USER_MEMORY") = py::int_(fDataFlagUserMemory);
// not supported yet - we may not support it
// m.attr("DATA_FLAG_USER_DECODE") = py::int_(fDataFlagUserDecode);
m.attr("DATA_FLAG_SKIP_METADATA") = py::int_(fDataFlagSkipMetaData);
m.attr("DATA_FLAG_SKIP_EVENT_POINTS") = py::int_(fDataFlagSkipEventPoints);
m.attr("DATA_FLAG_CALC_PEAKS") = py::int_(fDataFlagCalcPeaks);
m.attr("SAVE_FLAG_DEFAULT") = py::int_(fSaveFlagDefault);
m.attr("SAVE_FLAG_STRIP_METADATA") = py::int_(fSaveFlagStripMetaData);
m.attr("SAVE_FLAG_STRIP_EVENT_POINTS") = py::int_(fSaveFlagStripEventPoints);
m.attr("SAVE_FLAG_STRIP_PEAKS") = py::int_(fSaveFlagStripPeaks);
m.attr("MEMORY_LIMIT_THRESHOLD") = py::int_(kMemoryLimitThreshold);
m.attr("META_DATA_TAG_ARCHIVAL_LOCATION") = std::string(kMetaDataTagArchivalLocation);
m.attr("META_DATA_TAG_COMMISSIONED") = std::string(kMetaDataTagCommissioned);
m.attr("META_DATA_TAG_CROPPED") = std::string(kMetaDataTagCropped);
m.attr("META_DATA_TAG_DIMENSIONS") = std::string(kMetaDataTagDimensions);
m.attr("META_DATA_TAG_DISC") = std::string(kMetaDataTagDisc);
m.attr("META_DATA_TAG_DPI") = std::string(kMetaDataTagDpi);
m.attr("META_DATA_TAG_EDITOR") = std::string(kMetaDataTagEditor);
m.attr("META_DATA_TAG_ENGINEER") = std::string(kMetaDataTagEngineer);
m.attr("META_DATA_TAG_KEYWORDS") = std::string(kMetaDataTagKeywords);
m.attr("META_DATA_TAG_LANGUAGE") = std::string(kMetaDataTagLanguage);
m.attr("META_DATA_TAG_LIGHTNESS") = std::string(kMetaDataTagLightness);
m.attr("META_DATA_TAG_MEDIUM") = std::string(kMetaDataTagMedium);
m.attr("META_DATA_TAG_PALETTE_SETTING") = std::string(kMetaDataTagPaletteSetting);
m.attr("META_DATA_TAG_SUBJECT") = std::string(kMetaDataTagSubject);
m.attr("META_DATA_TAG_SOURCE_FORM") = std::string(kMetaDataTagSourceForm);
m.attr("META_DATA_TAG_SHARPNESS") = std::string(kMetaDataTagSharpness);
m.attr("META_DATA_TAG_TECHNICIAN") = std::string(kMetaDataTagTechnician);
m.attr("META_DATA_TAG_WRITER") = std::string(kMetaDataTagWriter);
m.attr("META_DATA_TAG_ALBUM") = std::string(kMetaDataTagAlbum);
m.attr("META_DATA_TAG_ARTIST") = std::string(kMetaDataTagArtist);
m.attr("META_DATA_TAG_COPYRIGHT") = std::string(kMetaDataTagCopyright);
m.attr("META_DATA_TAG_CREATION_DATE") = std::string(kMetaDataTagCreationDate);
m.attr("META_DATA_TAG_DESCRIPTION") = std::string(kMetaDataTagDescription);
m.attr("META_DATA_TAG_GENRE") = std::string(kMetaDataTagGenre);
m.attr("META_DATA_TAG_ORGANIZATION") = std::string(kMetaDataTagOrganization);
m.attr("META_DATA_TAG_TITLE") = std::string(kMetaDataTagTitle);
m.attr("META_DATA_TAG_TRACK_NUMBER") = std::string(kMetaDataTagTrackNumber);
m.attr("META_DATA_TAG_ENCODER") = std::string(kMetaDataTagEncoder);
m.attr("META_DATA_TAG_ISRC") = std::string(kMetaDataTagISRC);
m.attr("META_DATA_TAG_LICENSE") = std::string(kMetaDataTagLicense);
m.attr("META_DATA_TAG_PERFORMER") = std::string(kMetaDataTagPerformer);
m.attr("META_DATA_TAG_VERSION") = std::string(kMetaDataTagVersion);
m.attr("META_DATA_TAG_LOCATION") = std::string(kMetaDataTagLocation);
m.attr("META_DATA_TAG_CONTACT") = std::string(kMetaDataTagContact);
m.attr("META_DATA_TAG_COMMENT") = std::string(kMetaDataTagComment);
m.attr("META_DATA_TAG_SPEED") = std::string(kMetaDataTagSpeed);
m.attr("META_DATA_TAG_START_TIME") = std::string(kMetaDataTagStartTime);
m.attr("META_DATA_TAG_END_TIME") = std::string(kMetaDataTagEndTime);
m.attr("META_DATA_TAG_SUBGENRE") = std::string(kMetaDataTagSubGenre);
m.attr("META_DATA_TAG_BPM") = std::string(kMetaDataTagBpm);
m.attr("META_DATA_TAG_PLAYLIST_DELAY") = std::string(kMetaDataTagPlaylistDelay);
m.attr("META_DATA_TAG_FILE_NAME") = std::string(kMetaDataTagFileName);
m.attr("META_DATA_TAG_ALBUM") = std::string(kMetaDataTagOriginalAlbum);
m.attr("META_DATA_TAG_WRITER") = std::string(kMetaDataTagOriginalWriter);
m.attr("META_DATA_TAG_PERFORMER") = std::string(kMetaDataTagOriginalPerformer);
m.attr("META_DATA_TAG_ORIGINAL_YEAR") = std::string(kMetaDataTagOriginalYear);
m.attr("META_DATA_TAG_PUBLISHER") = std::string(kMetaDataTagPublisher);
m.attr("META_DATA_TAG_RECORDING_DATE") = std::string(kMetaDataTagRecordingDate);
m.attr("META_DATA_TAG_INTERNET_RADIO_STATION_NAME") = std::string(kMetaDataTagInternetRadioStationName);
m.attr("META_DATA_TAG_INTERNET_RADIO_STATION_OWNER") = std::string(kMetaDataTagInternetRadioStationOwner);
m.attr("META_DATA_TAG_INTERNET_RADIO_STATION_URL") = std::string(kMetaDataTagInternetRadioStationUrl);
m.attr("META_DATA_TAG_PAYMENT_URL") = std::string(kMetaDataTagPaymentUrl);
m.attr("META_DATA_TAG_INTERNET_COMMERCIAL_INFORMATION_URL") =
std::string(kMetaDataTagInternetCommercialInformationUrl);
m.attr("META_DATA_TAG_INTERNET_COPYRIGHT_URL") = std::string(kMetaDataTagInternetCopyrightUrl);
m.attr("META_DATA_TAG_WEBSITE") = std::string(kMetaDataTagWebsite);
m.attr("META_DATA_TAG_INTERNET_ARTIST_WEBSITE") = std::string(kMetaDataTagInternetArtistWebsite);
m.attr("META_DATA_TAG_AUDIO_SOURCE_WEBSITE") = std::string(kMetaDataTagAudioSourceWebsite);
m.attr("META_DATA_TAG_COMPOSER") = std::string(kMetaDataTagComposer);
m.attr("META_DATA_TAG_OWNER") = std::string(kMetaDataTagOwner);
m.attr("META_DATA_TAG_TERMS_OF_USE") = std::string(kMetaDataTagTermsOfUse);
m.attr("META_DATA_TAG_INITIAL_KEY") = std::string(kMetaDataTagInitialKey);
m.attr("META_DATA_TAG_CLEAR_ALL_TAGS") = kMetaDataTagClearAllTags;
py::class_<PeakVolumes>(m, "PeakVolumes")
.def_readwrite("channels", &PeakVolumes::channels)
//.def_readwrite("frame", &PeakVolumes::frame)
//.def_readwrite("peak", &PeakVolumes::peak)
.def_readwrite("peak_frame", &PeakVolumes::peakFrame)
.def_readwrite("peak_volume", &PeakVolumes::peakVolume);
m.attr("EVENT_POINT_INVALID_FRAME") = py::int_(kEventPointInvalidFrame);
m.attr("EVENT_POINT_LOOP_INFINITE") = py::int_(kEventPointLoopInfinite);
py::class_<EventPoint>(m, "EventPoint")
.def(py::init<>())
.def_readwrite("id", &EventPoint::id)
.def_readwrite("frame", &EventPoint::frame)
//.def_readwrite("label", &EventPoint::label)
//.def_readwrite("text", &EventPoint::text)
.def_readwrite("length", &EventPoint::length)
.def_readwrite("loop_count", &EventPoint::loopCount)
.def_readwrite("play_index", &EventPoint::playIndex);
// FIXME: maybe we want to bind userdata
py::enum_<UnitType>(m, "UnitType")
.value("BYTES", UnitType::eBytes)
.value("FRAMES", UnitType::eFrames)
.value("MILLISECONDS", UnitType::eMilliseconds)
.value("MICROSECONDS", UnitType::eMicroseconds);
m.doc() = R"(
This module contains bindings for the IAudioPlayback interface.
This is the low-level audio playback interface for Carbonite.
)";
py::class_<ContextCaps> ctxCaps(m, "ContextCaps");
ctxCaps.doc() = R"(
The capabilities of the context object. Some of these values are set
at the creation time of the context object. Others are updated when
speaker positions are set or an output device is opened.
)";
py::class_<ContextParams> ctxParams(m, "ContextParams");
ctxParams.doc() = R"(
Context parameters block. This can potentially contain all of a
context's parameters and their current values. This is used to both
set and retrieve one or more of a context's parameters in a single
call. The set of fContextParam* flags that are passed to
getContextParameter() or setContextParameter() indicates which values
in the block are guaranteed to be valid.
)";
py::class_<ContextParams2> ctxParams2(m, "ContextParams2");
ctxParams2.doc() = R"(
Extended context parameters block. This is used to set and retrieve
extended context parameters and their current values. This object
must be attached to the 'ContextParams.ext' value and the
'ContextParams.flags' value must have one or more flags related
to the extended parameters set for them to be modified or retrieved.
)";
py::class_<LoopPointDesc> loopPointDesc(m, "LoopPointDesc");
loopPointDesc.doc() = R"(
Descriptor of a loop point to set on a voice. This may be specified
to change the current loop point on a voice with set_Loop_Point().
)";
py::class_<DspValuePair> dspValuePair(m, "DspValuePair");
dspValuePair.def_readwrite("inner", &DspValuePair::inner);
dspValuePair.def_readwrite("outer", &DspValuePair::outer);
py::class_<EntityCone> cone(m, "EntityCone");
cone.def_readwrite("inside_angle", &EntityCone::insideAngle);
cone.def_readwrite("outside_angle", &EntityCone::outsideAngle);
cone.def_readwrite("volume", &EntityCone::volume);
cone.def_readwrite("low_pass_filter", &EntityCone::lowPassFilter);
cone.def_readwrite("reverb", &EntityCone::reverb);
cone.doc() = R"(
defines a sound cone relative to an entity's front vector. It is defined by two angles -
the inner and outer angles. When the angle between an emitter and the listener (relative
to the entity's front vector) is smaller than the inner angle, the resulting DSP value
will be the 'inner' value. When the emitter-listener angle is larger than the outer
angle, the resulting DSP value will be the 'outer' value. For emitter-listener angles
that are between the inner and outer angles, the DSP value will be interpolated between
the inner and outer angles. If a cone is valid for an entity, the @ref fEntityFlagCone
flag should be set in @ref EntityAttributes::flags.
Note that a cone's effect on the spatial volume of a sound is purely related to the angle
between the emitter and listener. Any distance attenuation is handled separately.
)";
py::class_<EntityAttributes> entityAttributes(m, "EntityAttributes");
entityAttributes.def_readwrite("flags", &EntityAttributes::flags);
entityAttributes.def_readwrite("position", &EntityAttributes::position);
entityAttributes.def_readwrite("velocity", &EntityAttributes::velocity);
entityAttributes.def_readwrite("forward", &EntityAttributes::forward);
entityAttributes.def_readwrite("up", &EntityAttributes::up);
entityAttributes.def_readwrite("cone", &EntityAttributes::cone);
entityAttributes.doc() = R"(
base spatial attributes of the entity. This includes its position, orientation, and velocity
and an optional cone.
)";
py::class_<RolloffDesc> rolloffDesc(m, "RolloffDesc");
rolloffDesc.def_readwrite("type", &RolloffDesc::type);
rolloffDesc.def_readwrite("near_distance", &RolloffDesc::nearDistance);
rolloffDesc.def_readwrite("far_distance", &RolloffDesc::farDistance);
rolloffDesc.doc() = R"(
Descriptor of the rolloff mode and range.
The C++ API allows rolloff curves to be set through this struct, but in
python you need to use voice.set_rolloff_curve() to do this instead.
)";
py::class_<EmitterAttributes> emitterAttributes(m, "EmitterAttributes");
emitterAttributes.def_readwrite("flags", &EmitterAttributes::flags);
emitterAttributes.def_readwrite("position", &EmitterAttributes::position);
emitterAttributes.def_readwrite("velocity", &EmitterAttributes::velocity);
emitterAttributes.def_readwrite("forward", &EmitterAttributes::forward);
emitterAttributes.def_readwrite("up", &EmitterAttributes::up);
emitterAttributes.def_readwrite("cone", &EmitterAttributes::cone);
emitterAttributes.def_readwrite("rolloff", &EmitterAttributes::rolloff);
py::class_<VoiceParams::VoiceParamBalance> voiceParamBalance(m, "VoiceParamBalance");
voiceParamBalance.def_readwrite("pan", &VoiceParams::VoiceParamBalance::pan);
voiceParamBalance.def_readwrite("fade", &VoiceParams::VoiceParamBalance::fade);
py::class_<VoiceParams::VoiceParamOcclusion> voiceParamOcclusion(m, "VoiceParamOcclusion");
voiceParamOcclusion.def_readwrite("direct", &VoiceParams::VoiceParamOcclusion::direct);
voiceParamOcclusion.def_readwrite("reverb", &VoiceParams::VoiceParamOcclusion::reverb);
py::class_<VoiceParams> voiceParams(m, "VoiceParams");
voiceParams.def_readwrite("playback_mode", &VoiceParams::playbackMode);
voiceParams.def_readwrite("volume", &VoiceParams::volume);
voiceParams.def_readwrite("balance", &VoiceParams::balance);
voiceParams.def_readwrite("frequency_ratio", &VoiceParams::frequencyRatio);
voiceParams.def_readwrite("priority", &VoiceParams::priority);
voiceParams.def_readwrite("spatial_mix_level", &VoiceParams::spatialMixLevel);
voiceParams.def_readwrite("doppler_scale", &VoiceParams::dopplerScale);
voiceParams.def_readwrite("occlusion", &VoiceParams::occlusion);
voiceParams.def_readwrite("emitter", &VoiceParams::emitter);
voiceParams.doc() = R"(
Voice parameters block. This can potentially contain all of a voice's
parameters and their current values. This is used to both set and
retrieve one or more of a voice's parameters in a single call. The
VOICE_PARAM_* flags that are passed to set_voice_parameters() or
get_voice_parameters() determine which values in this block are
guaranteed to be valid.
The matrix parameter isn't available from this struct due to limitations
in python; use voice.set_matrix() instead.
)";
py::class_<PythonContext> ctx(m, "Context");
ctx.doc() = R"(
The Context object for the audio system.
Each individual Context represents an instance of the IAudioPlayback
interface, as well as an individual connection to the system audio
mixer/device. Only a small number of these can be opened for a given
process.
)";
docString = R"(
retrieves the current capabilities and settings for a context object.
This retrieves the current capabilities and settings for a context
object. Some of these settings may change depending on whether the
context has opened an output device or not.
Args:
No arguments.
Returns:
the context's current capabilities and settings. This includes the
speaker mode, speaker positions, maximum bus count, and information
about the output device that is opened (if any).
)";
ctx.def("get_caps", [](PythonContext* self) -> ContextCaps { return *self->getContextCaps(); }, docString,
py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets one or more parameters on a context.
This sets one or more context parameters in a single call. Only
parameters that have their corresponding flag set in paramsToSet will
be modified. If a change is to be relative to the context's current
parameter value, the current value should be retrieved first, modified,
then set.
Args:
paramsToSet: The set of flags to indicate which parameters in the
parameter block params are valid and should be set
on the context. This may be zero or more of the
CONTEXT_PARAM_* bitflags. If this is 0, the call will be
treated as a no-op.
params: The parameter(s) to be set on the context. The flags
indicating which parameters need to be set are given
in paramsToSet. Undefined behavior may occur if
a flag is set but its corresponding value(s) have not
been properly initialized. This may not be None.
Returns:
No return value.
)";
ctx.def("set_parameters", &PythonContext::setContextParameters, docString, py::arg("paramsToSet"),
py::arg("params"), py::call_guard<py::gil_scoped_release>());
docString = R"(
Retrieves one or more parameters for a context.
This retrieves the current values of one or more of a context's
parameters. Only the parameter values listed in paramsToGet flags
will be guaranteed to be valid upon return.
Args:
ParamsToGet: Flags indicating which parameter values need to be retrieved.
This should be a combination of the CONTEXT_PARAM_* bitflags.
Returns:
The requested parameters in a ContextParams struct. Everything else is default-initialized.
)";
ctx.def("get_parameters",
[](PythonContext* self, ContextParamFlags paramsToGet) -> ContextParams {
ContextParams tmp = {};
self->getContextParameters(paramsToGet, &tmp);
return tmp;
},
docString, py::arg("paramsToGet"), py::call_guard<py::gil_scoped_release>());
docString = R"(
Schedules a sound to be played on a voice.
This schedules a sound object to be played on a voice. The sounds current
settings (ie: volume, pitch, playback frame rate, pan, etc) will be assigned to
the voice as 'defaults' before playing. Further changes can be made to the
voice's state at a later time without affecting the sound's default settings.
Once the sound finishes playing, it will be implicitly unassigned from the
voice. If the sound or voice have a callback set, a notification will be
received for the sound having ended.
If the playback of this sound needs to be stopped, it must be explicitly stopped
from the returned voice object using stopVoice(). This can be called on a
single voice or a voice group.
Args:
sound: The sound to schedule.
flags: Flags that alter playback behavior. Must be a combination of PLAY_FLAG_* constants.
valid_params: Which parameters in the params argument to use.
params: The starting parameters for the voice. This conditionally used based on valid_params.
loop_point: A descriptor for how to repeatedly play the sound. This can be None to only play once.
play_start: The start offset to begin playing the sound at. This is measured in play_units.
play_end: The stop offset to finish playing the sound at. This is measured in play_units.
play_units: The units in which play_start and play_stop are measured.
Returns:
A new voice handle representing the playing sound. Note that if no buses are
currently available to play on or the voice's initial parameters indicated that
it is not currently audible, the voice will be virtual and will not be played.
The voice handle will still be valid in this case and can be operated on, but
no sound will be heard from it until it is determined that it should be converted
to a real voice. This can only occur when the update() function is called.
This voice handle does not need to be closed or destroyed. If the voice finishes
its play task, any future calls attempting to modify the voice will simply fail.
None if the requested sound is already at or above its instance limit and the
PLAY_FLAG_MAX_INSTANCES_SIMULATE flag is not used.
None if the play task was invalid or could not be started properly. This can
most often occur in the case of streaming sounds if the sound's original data
could not be opened or decoded properly.
)";
ctx.def("play_sound", &PythonContext::playSound, docString, py::arg("sound"), py::arg("flags") = 0,
py::arg("valid_params") = 0, py::arg("params") = nullptr, py::arg("loop_point") = nullptr,
py::arg("play_start") = 0, py::arg("play_end") = 0, py::arg("play_units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
py::class_<carb::audio::PythonVoice> voice(m, "Voice");
voice.doc() = R"(
Represents a single instance of a playing sound. A single sound object
may be playing on multiple voices at the same time, however each voice
may only be playing a single sound at any given time.
)";
docString = R"(
Stops playback on a voice.
This stops a voice from playing its current sound. This will be
silently ignored for any voice that is already stopped or for an
invalid voice handle. Once stopped, the voice will be returned to a
'free' state and its sound data object unassigned from it. The voice
will be immediately available to be assigned a new sound object to play
from.
This will only schedule the voice to be stopped. Its volume will be
implicitly set to silence to avoid a popping artifact on stop. The
voice will continue to play for one more engine cycle until the volume
level reaches zero, then the voice will be fully stopped and recycled.
At most, 1ms of additional audio will be played from the voice's sound.
Args:
No Arguments.
Returns:
No return value.
)";
voice.def("stop", &PythonVoice::stop, docString, py::call_guard<py::gil_scoped_release>());
docString = R"(
Checks the playing state of a voice.
This checks if a voice is currently playing. A voice is considered
playing if it has a currently active sound data object assigned to it
and it is not paused.
Args:
Voice: The voice to check the playing state for.
Returns:
True if the requested voice is playing.
False if the requested voice is not playing or is paused.
False if the given voice handle is no longer valid.
)";
voice.def("is_playing", &PythonVoice::isPlaying, docString, py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets a new loop point as current on a voice.
This sets a new loop point for a playing voice. This allows for behavior
such as sound atlases or sound playlists to be played out on a single
voice.
When desc is None or the contents of the descriptor do not specify a new
loop point, this will immediately break the loop that is currently playing
on the voice. This will have the effect of setting the voice's current
loop count to zero. The sound on the voice will continue to play out its
current loop iteration, but will not loop again when it reaches its end.
This is useful for stopping a voice that is playing an infinite loop or to
prematurely stop a voice that was set to loop a specific number of times.
This call will effectively be ignored if passed in a voice that is not
currently looping.
For streaming voices, updating a loop point will have a delay due to
buffering the decoded data. The sound will loop an extra time if the loop
point is changed after the buffering has started to consume another loop.
The default buffer time for streaming sounds is currently 200 milliseconds,
so this is the minimum slack time that needs to be given for a loop change.
Args:
voice: the voice to set the loop point on. This may not be nullptr.
point: descriptor of the new loop point to set. This may contain a loop
or event point from the sound itself or an explicitly specified
loop point. This may be nullptr to indicate that the current loop
point should be removed and the current loop broken. Similarly,
an empty loop point descriptor could be passed in to remove the
current loop point.
Returns:
True if the new loop point is successfully set.
False if the voice handle is invalid or the voice has already stopped
on its own.
False if the new loop point is invalid, not found in the sound data
object, or specifies a starting point or length that is outside the
range of the sound data object's buffer.
)";
voice.def("set_loop_point", &PythonVoice::setLoopPoint, docString, py::arg("point"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Retrieves the current play cursor position of a voice.
This retrieves the current play position for a voice. This is not
necessarily the position in the buffer being played, but rather the
position in the sound data object's stream. For streaming sounds, this
will be the offset from the start of the stream. For non-streaming sounds,
this will be the offset from the beginning of the sound data object's
buffer.
If the loop point for the voice changes during playback, the results of
this call can be unexpected. Once the loop point changes, there is no
longer a consistent time base for the voice and the results will reflect
the current position based off of the original loop's time base. As long
as the voice's original loop point remains (ie: setLoopPoint() is never
called on the voice), the calculated position should be correct.
It is the caller's responsibility to ensure that this is not called at the
same time as changing the loop point on the voice or stopping the voice.
Args:
type: The units to retrieve the current position in.
Returns:
The current position of the voice in the requested units.
0 if the voice has stopped playing.
The last play cursor position if the voice is paused.
)";
voice.def("get_play_cursor", &PythonVoice::getPlayCursor, docString, py::arg("type"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets one or more parameters on a voice.
This sets one or more voice parameters in a single call. Only parameters that
have their corresponding flag set in paramToSet will be modified.
If a change is to be relative to the voice's current parameter value, the current
value should be retrieved first, modified, then set.
Args:
paramsToSet: Flags to indicate which of the parameters need to be updated.
This may be one or more of the fVoiceParam* flags. If this is
0, this will simply be a no-op.
params: The parameter(s) to be set on the voice. The flags indicating
which parameters need to be set must be set in
paramToSet by the caller. Undefined behavior
may occur if a flag is set but its corresponding value(s) have
not been properly initialized. This may not be None.
Returns:
No return value.
)";
voice.def("set_parameters", &PythonVoice::setParameters, docString, py::arg("params_to_set"), py::arg("params"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Retrieves one or more parameters for a voice.
This retrieves the current values of one or more of a voice's parameters.
Only the parameter values listed in paramsToGet flags will be guaranteed
to be valid upon return.
Args:
paramsToGet: Flags indicating which parameter values need to be retrieved.
Returns:
The requested parameters in a VoiceParams struct. Everything else is default-initialized.
)";
voice.def("get_parameters",
[](PythonVoice* self, VoiceParamFlags paramsToGet) -> VoiceParams {
VoiceParams tmp = {};
self->getParameters(paramsToGet, &tmp);
return tmp;
},
docString, py::arg("params_to_get") = fVoiceParamAll, py::call_guard<py::gil_scoped_release>());
docString = R"(
Set flags to indicate how a sound is to be played back.
This controls whether the sound is played as a spatial or non-spatial
sound and how the emitter's attributes will be interpreted (ie: either
world coordinates or listener relative).
PLAYBACK_MODE_MUTED and PLAYBACK_MODE_PAUSED are ignored here; you'll
need to use voice.set_mute() or voice.pause() to mute or pause the voice.
Args:
playback_mode: The playback mode flag set to set.
Returns:
None
)";
voice.def("set_playback_mode", &PythonVoice::setPlaybackMode, docString, py::arg("playback_mode"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
The volume level for the voice.
Args:
volume: The volume to set.
This should be 0.0 for silence or 1.0 for normal volume.
A negative value may be used to invert the signal.
A value greater than 1.0 will amplify the signal.
The volume level can be interpreted as a linear scale where
a value of 0.5 is half volume and 2.0 is double volume.
Any volume values in decibels must first be converted to a
linear volume scale before setting this value.
Returns:
None
)";
voice.def(
"set_volume", &PythonVoice::setVolume, docString, py::arg("volume"), py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets the mute state for a voice.
Args:
mute: When this is set to true, the voice's output will be muted.
When this is set to false, the voice's volume will be
restored to its previous level.
This is useful for temporarily silencing a voice without
having to clobber its current volume level or affect its
emitter attributes.
Returns:
None
)";
voice.def("set_mute", &PythonVoice::setMute, docString, py::arg("mute"), py::call_guard<py::gil_scoped_release>());
docString = R"(
Non-spatial sound positioning.
These provide pan and fade values for the voice to give the impression
that the sound is located closer to one of the quadrants of the
acoustic space versus the others.
These values are ignored for spatial sounds.
Args:
pan: The non-spatial panning value for a voice.
This is 0.0 to have the sound "centered" in all speakers.
This is -1.0 to have the sound balanced to the left side.
This is 1.0 to have the sound balanced to the right side.
The way the sound is balanced depends on the number of channels.
For example, a mono sound will be balanced between the left
and right sides according to the panning value, but a stereo
sound will just have the left or right channels' volumes
turned down according to the panning value.
This value is ignored for spatial sounds.
The default value is 0.0.
Note that panning on non-spatial sounds should only be used
for mono or stereo sounds.
When it is applied to sounds with more channels, the results
are often undefined or may sound odd.
fade: The non-spatial fade value for a voice.
This is 0.0 to have the sound "centered" in all speakers.
This is -1.0 to have the sound balanced to the back side.
This is 1.0 to have the sound balanced to the front side.
The way the sound is balanced depends on the number of channels.
For example, a mono sound will be balanced between the front
and back speakers according to the fade value, but a 5.1
sound will just have the front or back channels' volumes
turned down according to the fade value.
This value is ignored for spatial sounds.
The default value is 0.0.
Note that using fade on non-spatial sounds should only be
used for mono or stereo sounds.
When it is applied to sounds with more channels, the results
are often undefined or may sound odd.
Returns:
None
)";
voice.def("set_balance", &PythonVoice::setBalance, docString, py::arg("pan"), py::arg("fade"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Set The frequency ratio for a voice.
Args:
ratio: This will be 1.0 to play back a sound at its normal rate, a
value less than 1.0 to lower the pitch and play it back more
slowly, and a value higher than 1.0 to increase the pitch
and play it back faster.
For example, a pitch scale of 0.5 will play back at half the
pitch (ie: lower frequency, takes twice the time to play
versus normal), and a pitch scale of 2.0 will play back at
double the pitch (ie: higher frequency, takes half the time
to play versus normal).
The default value is 1.0.
On some platforms, the frequency ratio may be silently
clamped to an acceptable range internally.
For example, a value of 0.0 is not allowed.
This will be clamped to the minimum supported value instead.
Note that the even though the frequency ratio *can* be set
to any value in the range from 1/1024 to 1024, this very
large range should only be used in cases where it is well
known that the particular sound being operated on will still
sound valid after the change.
In
the real world, some of these extreme frequency ratios may
make sense, but in the digital world, extreme frequency
ratios can result in audio corruption or even silence.
This
happens because the new frequency falls outside of the range
that is faithfully representable by either the audio device
or sound data itself.
For example, a 4KHz tone being played at a frequency ratio
larger than 6.0 will be above the maximum representable
frequency for a 48KHz device or sound file.
This case will result in a form of corruption known as
aliasing, where the frequency components above the maximum
representable frequency will become audio artifacts.
Similarly, an 800Hz tone being played at a frequency ratio
smaller than 1/40 will be inaudible because it falls below
the frequency range of the human ear.
In general, most use cases will find that the frequency
ratio range of [0.1, 10] is more than sufficient for their
needs.
Further, for many cases, the range from [0.2, 4] would
suffice.
Care should be taken to appropriately cap the used range for
this value.
Returns:
None
)";
voice.def("set_frequency_ratio", &PythonVoice::setFrequencyRatio, docString, py::arg("ratio"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Set the playback priority of this voice.
Args:
priority: This is an arbitrary value whose scale is defined by the
host app.
A value of 0 is the default priority.
Negative values indicate lower priorities and positive
values indicate higher priorities.
This priority value helps to determine which voices are
the most important to be audible at any given time.
When all buses are busy, this value will be used to
compare against other playing voices to see if it should
steal a bus from another lower priority sound or if it
can wait until another bus finishes first.
Higher priority sounds will be ensured a bus to play on
over lower priority sounds.
If multiple sounds have the same priority levels, the
louder sound(s) will take priority.
When a higher priority sound is queued, it will try to
steal a bus from the quietest sound with lower or equal
priority.
Returns:
None
)";
voice.def("set_priority", &PythonVoice::setPriority, docString, py::arg("priority"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets the spatial mix level for the voice.
Args:
level: The mix between the results of a voice's spatial sound
calculations and its non-spatial calculations. When this is
set to 1.0, only the spatial sound calculations will affect
the voice's playback.
This is the default when state.
When set to 0.0, only the non-spatial sound calculations
will affect the voice's
playback.
When set to a value between 0.0 and 1.0, the results of the
spatial and non-spatial sound calculations will be mixed
with the weighting according to this value.
This value will be ignored if PLAYBACK_MODE_SPATIAL is not
set.
The default value is 1.0. Values above 1.0 will be treated
as 1.0.
Values below 0.0 will be treated as 0.0.
PLAYBACK_MODE_SPATIAL_MIX_LEVEL_MATRIX affects the
non-spatial mixing behavior of this parameter for
multi-channel voices.
By default, a multi-channel spatial voice's non-spatial
component will treat each channel as a separate mono voice.
With the PLAYBACK_MODE_SPATIAL_MIX_LEVEL_MATRIX flag set,
the non-spatial component will be set with the specified
output matrix or the default output matrix.
Returns:
None
)";
voice.def("set_spatial_mix_level", &PythonVoice::setSpatialMixLevel, docString, py::arg("level"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets the doppler scale value for the voice.
This allows the result of internal doppler calculations to be scaled to emulate
a time warping effect.
Args:
scale: This should be near 0.0 to greatly reduce the effect of the
doppler calculations, and up to 5.0 to exaggerate the
doppler effect.
A value of 1.0 will leave the calculated doppler factors
unmodified.
The default value is 1.0.
Returns:
None
)";
voice.def("set_doppler_scale", &PythonVoice::setDopplerScale, docString, py::arg("scale"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Sets the occlusion factors for a voice.
These values control automatic low pass filters that get applied to the
Sets spatial sounds to simulate object occlusion between the emitter
and listener positions.
Args:
direct: The occlusion factor for the direct path of the sound.
This is the path directly from the emitter to the listener.
This factor describes how occluded the sound's path
actually is.
A value of 1.0 means that the sound is fully occluded by an
object between the voice and the listener.
A value of 0.0 means that the sound is not occluded by any
object at all.
This defaults to 0.0.
This factor multiplies by EntityCone.low_pass_filter, if a
cone with a non 1.0 lowPassFilter value is specified.
Setting this to a value outside of [0.0, 1.0] will result
in an undefined low pass filter value being used.
reverb: The occlusion factor for the reverb path of the sound.
This is the path taken for sounds reflecting back to the
listener after hitting a wall or other object.
A value of 1.0 means that the sound is fully occluded by an
object between the listener and the object that the sound
reflected off of.
A value of 0.0 means that the sound is not occluded by any
object at all.
This defaults to 1.0.
Returns:
None
)";
voice.def("set_occlusion", &PythonVoice::setOcclusion, docString, py::arg("direct"), py::arg("reverb"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Set the channel mixing matrix to use for this voice.
Args:
matrix: The matrix to set.
The rows of this matrix represent
each output channel from this voice and the columns of this
matrix represent the input channels of this voice (e.g.
this is a inputChannels x outputChannels matrix).
Note that setting the matrix to be smaller than needed will
result in undefined behavior.
The output channel count will always be the number of audio
channels set on the context.
Each cell in the matrix should be a value from 0.0-1.0 to
specify the volume that this input channel should be mixed
into the output channel.
Setting negative values will invert the signal.
Setting values above 1.0 will amplify the signal past unity
gain when being mixed.
This setting is mutually exclusive with balance; setting
one will disable the other.
This setting is only available for spatial sounds if
PLAYBACK_MODE_SPATIAL_MIX_LEVEL_MATRIX if set in the
playback mode parameter.
Multi-channel spatial audio is interpreted as multiple
emitters existing at the same point in space, so a purely
spatial voice cannot have an output matrix specified.
Setting this to None will reset the matrix to the default
for the given channel count.
The following table shows the speaker modes that are used
for the default output matrices.
Voices with a speaker mode that is not in the following
table will use the default output matrix for the speaker
mode in the following table that has the same number of
channels.
If there is no default matrix for the channel count of the
@ref Voice, the output matrix will have 1.0 in the any cell
(i, j) where i == j and 0.0 in all other cells.
Returns:
None
)";
voice.def(
"set_matrix", &PythonVoice::setMatrix, docString, py::arg("matrix"), py::call_guard<py::gil_scoped_release>());
docString = R"(
Set the voice's position.
Args:
position: The current position of the voice in world units.
This should only be expressed in meters if the world
units scale is set to 1.0 for this context.
Returns:
None
)";
voice.def("set_position", &PythonVoice::setPosition, docString, py::arg("position"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Set the voice's velocity.
Args:
velocity: The current velocity of the voice in world units per second.
This should only be expressed in meters per second if the
world units scale is set to 1.0 with for the context.
The magnitude of this vector will be taken as the
listener's current speed and the vector's direction will
indicate the listener's current direction. This vector
should not be normalized unless the listener's speed is
actually 1.0 units per second.
This may be a zero vector if the listener is not moving.
Returns:
None
)";
voice.def("set_velocity", &PythonVoice::setVelocity, docString, py::arg("velocity"),
py::call_guard<py::gil_scoped_release>());
docString = R"(
Set custom rolloff curves on the voice.
Args:
type: The default type of rolloff calculation to use for all DSP
values that are not overridden by a custom curve.
near_distance: The near distance range for the sound.
This is specified in arbitrary world units.
When a custom curve is used, this near distance will
map to a distance of 0.0 on the curve.
This must be less than the far_distance distance.
The near distance is the closest distance that the
emitter's attributes start to rolloff at.
At distances closer than this value, the calculated
DSP values will always be the same as if they were
at the near distance.
far_distance: The far distance range for the sound.
This is specified in arbitrary world units.
When a custom curve is used, this far distance will
map to a distance of 1.0 on the curve. This must be
greater than the @ref nearDistance distance.
The far distance is the furthest distance that the
emitters attributes will rolloff at.
At distances further than this value, the calculated
DSP values will always be the same as if they were at
the far distance (usually silence).
Emitters further than this distance will often become
inactive in the scene since they cannot be heard any
more.
volume: The custom curve used to calculate volume attenuation over
distance.
This must be a normalized curve such that a distance of 0.0
maps to the near_distance distance and a distance of 1.0
maps to the far_distance distance.
When specified, this overrides the rolloff calculation
specified by type when calculating volume attenuation.
If this is an empty array, the parameter will be ignored.
low_frequency: The custom curve used to calculate low frequency
effect volume over distance.
This must be a normalized curve such that a distance
of 0.0 maps to the near_distance distance and a
distance of 1.0 maps to the far_distance distance.
When specified, this overrides the rolloff
calculation specified by type when calculating
the low frequency effect volume.
If this is an empty array, the parameter will be
ignored.
low_pass_reverb: The custom curve used to calculate low pass filter
parameter on the direct path over distance.
This must be a normalized curve such that a
distance of 0.0 maps to the near_distance distance
and a distance of 1.0 maps to the far_distance
distance.
When specified, this overrides the rolloff
calculation specified by type when calculating the
low pass filter parameter.
If this is an empty array, the parameter will be
ignored.
low_pass_reverb: The custom curve used to calculate low pass filter
parameter on the reverb path over distance.
This must be a normalized curve such that a
distance of 0.0 maps to the near_distance distance
and a distance of 1.0 maps to the far_distance
distance.
When specified, this overrides the rolloff
calculation specified by type when calculating the
low pass filter parameter.
If this is an empty array, the parameter will be
ignored.
reverb: The custom curve used to calculate reverb mix level over
distance.
This must be a normalized curve such that a distance of 0.0
maps to the near_distance distance and a distance of 1.0
maps to the @ref farDistance distance.
When specified, this overrides the rolloff calculation
specified by type when calculating the low pass filter
parameter.
If this is an empty array, the parameter will be ignored.
returns:
None
)";
voice.def("set_rolloff_curve", &PythonVoice::setRolloffCurve, docString, py::arg("type"), py::arg("near_distance"),
py::arg("far_distance"), py::arg("volume") = std::vector<Float2>(),
py::arg("low_frequency") = std::vector<Float2>(), py::arg("low_pass_direct") = std::vector<Float2>(),
py::arg("low_pass_reverb") = std::vector<Float2>(), py::arg("reverb") = std::vector<Float2>());
py::class_<carb::audio::PlaybackContextDesc> playbackContextDesc(m, "PlaybackContextDesc");
carb::defineInterfaceClass<IAudioPlayback>(m, "IAudioPlayback", "acquire_playback_interface")
.def("create_context",
[](IAudioPlayback* self, PlaybackContextDesc desc) -> PythonContext {
Context* ctx = self->createContext(&desc);
return PythonContext(self, ctx);
},
py::arg("desc") = PlaybackContextDesc());
carb::defineInterfaceClass<IAudioData>(m, "IAudioData", "acquire_data_interface")
.def("create_sound_from_file",
[](IAudioData* self, const char* fileName, SampleFormat decodedFormat, DataFlags flags, bool streaming,
size_t autoStream) -> PythonSoundData* {
SoundData* tmp = createSoundFromFile(self, fileName, streaming, autoStream, decodedFormat, flags);
if (tmp == nullptr)
throw std::runtime_error("failed to create a SoundData object");
return new PythonSoundData(self, tmp);
},
R"( Create a SoundData object from a file on disk.
Args:
filename The name of the file on disk to create the new sound
data object from.
decodedFormat The format you want the audio to be decoded into.
Although you can retrieve the sound's data through python
in any format, the data will be internally stored as this
format. This is only important if you aren't creating a
decoded sound. This defaults to SampleFormat.DEFAULT,
which will decode the sound to float for now.
flags Optional flags to change the behavior. This can be any
of: DATA_FLAG_SKIP_METADATA, DATA_FLAG_SKIP_EVENT_POINTS
or DATA_FLAG_CALC_PEAKS.
streaming Set to True to create a streaming sound. Streaming
sounds aren't loaded into memory; they remain on disk and
are decoded in chunks as needed. This defaults to False.
autoStream The threshold in bytes at which the new sound data
object will decide to stream instead of decode into
memory. If the decoded size of the sound will be
larger than this value, it will be streamed from its
original source instead of decoded. Set this to 0
to disable auto-streaming. This defaults to 0.
Returns:
The new sound data if successfully created and loaded.
An exception is thrown if the sound could not be loaded. This could
happen if the file does not exist, the file is not a supported type,
the file is corrupt or some other error occurred during decode.
)",
py::arg("fileName"), py::arg("decodedFormat") = SampleFormat::eDefault, py::arg("flags") = 0,
py::arg("streaming") = false, py::arg("autoStream") = 0, py::call_guard<py::gil_scoped_release>())
.def("create_sound_from_blob",
[](IAudioData* self, const py::bytes blob, SampleFormat decodedFormat, DataFlags flags, bool streaming,
size_t autoStream) -> PythonSoundData* {
// this is extremely inefficient, but this appears to be the only way to get the data
std::string s = blob;
SoundData* tmp =
createSoundFromBlob(self, s.c_str(), s.length(), streaming, autoStream, decodedFormat, flags);
if (tmp == nullptr)
throw std::runtime_error("failed to create a SoundData object");
return new PythonSoundData(self, tmp);
},
R"( Create a SoundData object from a data blob in memory
Args:
blob A bytes object which contains the raw data for an audio
file which has some sort of header. Raw PCM data will
not work with this function. Note that due to the way
python works, these bytes will be copied into the
SoundData object's internal buffer if the sound is
streaming.
decodedFormat The format you want the audio to be decoded into.
Although you can retrieve the sound's data through python
in any format, the data will be internally stored as this
format. This is only important if you aren't creating a
decoded sound. This defaults to SampleFormat.DEFAULT,
which will decode the sound to float for now.
flags Optional flags to change the behavior. This can be any
of: DATA_FLAG_SKIP_METADATA, DATA_FLAG_SKIP_EVENT_POINTS
or DATA_FLAG_CALC_PEAKS.
streaming Set to True to create a streaming sound. Streaming
sounds aren't loaded into memory; the audio data remains
in its encoded form in memory and are decoded in chunks
as needed. This is mainly useful for compressed formats
which will expand when decoded. This defaults to False.
autoStream The threshold in bytes at which the new sound data
object will decide to stream instead of decode into
memory. If the decoded size of the sound will be
larger than this value, it will be streamed from its
original source instead of decoded. Set this to 0
to disable auto-streaming. This defaults to 0.
Returns:
The new sound data if successfully created and loaded.
An exception is thrown if the sound could not be loaded. This could
happen if the blob is an unsupported audio format, the blob is corrupt
or some other error during decoding.
)",
py::arg("blob"), py::arg("decodedFormat") = SampleFormat::eDefault, py::arg("flags") = 0,
py::arg("streaming") = false, py::arg("autoStream") = 0, py::call_guard<py::gil_scoped_release>())
.def("create_sound_from_uint8_pcm",
[](IAudioData* self, const std::vector<uint8_t>& pcm, size_t channels, size_t frameRate,
SpeakerMode channelMask) -> PythonSoundData* {
return PythonSoundData::fromRawBlob(
self, pcm.data(), pcm.size(), SampleFormat::ePcm8, channels, frameRate, channelMask);
},
R"( Create a SoundData object from raw 8 bit unsigned integer PCM data.
Args:
pcm The audio data to load into the SoundData object.
This will be copied to an internal buffer in the object.
channels The number of channels of data in each frame of the audio
data.
frame_rate The number of frames per second that must be played back
for the audio data to sound 'normal' (ie: the way it was
recorded or produced).
channel_mask the channel mask for the audio data. This specifies which
speakers the stream is intended for and will be a
combination of one or more of the Speaker names or a
SpeakerMode name. The channel mapping will be set to the
defaults if set to SPEAKER_MODE_DEFAULT, which is the
default value for this parameter.
Returns:
The new sound data if successfully created and loaded.
An exception may be thrown if an out-of-memory situation occurs or some
other error occurs while creating the object.
)",
py::arg("pcm"), py::arg("channels"), py::arg("frame_rate"), py::arg("channel_mask") = kSpeakerModeDefault,
py::call_guard<py::gil_scoped_release>())
.def("create_sound_from_int16_pcm",
[](IAudioData* self, const std::vector<int16_t>& pcm, size_t channels, size_t frameRate,
SpeakerMode channelMask) -> PythonSoundData* {
return PythonSoundData::fromRawBlob(
self, pcm.data(), pcm.size(), SampleFormat::ePcm16, channels, frameRate, channelMask);
},
R"( Create a SoundData object from raw 16 bit signed integer PCM data.
Args:
pcm The audio data to load into the SoundData object.
This will be copied to an internal buffer in the object.
channels The number of channels of data in each frame of the audio
data.
frame_rate The number of frames per second that must be played back
for the audio data to sound 'normal' (ie: the way it was
recorded or produced).
channel_mask the channel mask for the audio data. This specifies which
speakers the stream is intended for and will be a
combination of one or more of the Speaker names or a
SpeakerMode name. The channel mapping will be set to the
defaults if set to SPEAKER_MODE_DEFAULT, which is the
default value for this parameter.
Returns:
The new sound data if successfully created and loaded.
An exception may be thrown if an out-of-memory situation occurs or some
other error occurs while creating the object.
)",
py::arg("pcm"), py::arg("channels"), py::arg("frame_rate"), py::arg("channel_mask") = kSpeakerModeDefault,
py::call_guard<py::gil_scoped_release>())
.def("create_sound_from_int32_pcm",
[](IAudioData* self, const std::vector<int32_t>& pcm, size_t channels, size_t frameRate,
SpeakerMode channelMask) -> PythonSoundData* {
return PythonSoundData::fromRawBlob(
self, pcm.data(), pcm.size(), SampleFormat::ePcm32, channels, frameRate, channelMask);
},
R"( Create a SoundData object from raw 32 bit signed integer PCM data.
Args:
pcm The audio data to load into the SoundData object.
This will be copied to an internal buffer in the object.
channels The number of channels of data in each frame of the audio
data.
frame_rate The number of frames per second that must be played back
for the audio data to sound 'normal' (ie: the way it was
recorded or produced).
channel_mask the channel mask for the audio data. This specifies which
speakers the stream is intended for and will be a
combination of one or more of the Speaker names or a
SpeakerMode name. The channel mapping will be set to the
defaults if set to SPEAKER_MODE_DEFAULT, which is the
default value for this parameter.
Returns:
The new sound data if successfully created and loaded.
An exception may be thrown if an out-of-memory situation occurs or some
other error occurs while creating the object.
)",
py::arg("pcm"), py::arg("channels"), py::arg("frame_rate"), py::arg("channel_mask") = kSpeakerModeDefault,
py::call_guard<py::gil_scoped_release>())
.def("create_sound_from_float_pcm",
[](IAudioData* self, const std::vector<float>& pcm, size_t channels, size_t frameRate,
SpeakerMode channelMask) -> PythonSoundData* {
return PythonSoundData::fromRawBlob(
self, pcm.data(), pcm.size(), SampleFormat::ePcmFloat, channels, frameRate, channelMask);
},
R"( Create a SoundData object from raw 32 bit float PCM data.
Args:
pcm The audio data to load into the SoundData object.
This will be copied to an internal buffer in the object.
channels The number of channels of data in each frame of the audio
data.
frame_rate The number of frames per second that must be played back
for the audio data to sound 'normal' (ie: the way it was
recorded or produced).
channel_mask the channel mask for the audio data. This specifies which
speakers the stream is intended for and will be a
combination of one or more of the Speaker names or a
SpeakerMode name. The channel mapping will be set to the
defaults if set to SPEAKER_MODE_DEFAULT, which is the
default value for this parameter.
Returns:
The new sound data if successfully created and loaded.
An exception may be thrown if an out-of-memory situation occurs or some
other error occurs while creating the object.
)",
py::arg("pcm"), py::arg("channels"), py::arg("frame_rate"), py::arg("channel_mask") = kSpeakerModeDefault,
py::call_guard<py::gil_scoped_release>())
.def("create_empty_sound",
[](IAudioData* self, SampleFormat format, size_t channels, size_t frameRate, size_t bufferLength,
UnitType units, const char* name, SpeakerMode channelMask) -> PythonSoundData* {
(void)channelMask; // FIXME: channelMask!?
SoundData* tmp = createEmptySound(self, format, frameRate, channels, bufferLength, units, name);
if (tmp == nullptr)
throw std::runtime_error("failed to create a SoundData object");
return new PythonSoundData(self, tmp);
},
R"( Create a SoundData object with an empty buffer that can be written to.
After creating a SoundData object with this, you will need to call one of
the write_buffer_*() functions to load your data into the object, then you
will need to call set_valid_length() to indicate how much of the sound now
contains valid data.
Args:
decodedFormat The format for the SoundData object's buffer.
Although you can retrieve the sound's data through python
in any format, the data will be internally stored as this
format. This defaults to SampleFormat.DEFAULT, which will
use float for the buffer.
channels The number of channels of data in each frame of the audio
data.
frame_rate The number of frames per second that must be played back
for the audio data to sound 'normal' (ie: the way it was
recorded or produced).
buffer_length How long you want the buffer to be.
units How buffer_length will be interpreted. This defaults to
UnitType.FRAMES.
name An optional name that can be given to the SoundData
object to make it easier to track. This can be None if it
is not needed. This defaults to None.
channel_mask The channel mask for the audio data. This specifies which
speakers the stream is intended for and will be a
combination of one or more of the Speaker names or a
SpeakerMode name. The channel mapping will be set to the
defaults if set to SPEAKER_MODE_DEFAULT, which is the
default value for this parameter.
Returns:
The new sound data if successfully created and loaded.
An exception may be thrown if an out-of-memory situation occurs or some
other error occurs while creating the object.
)",
py::arg("format"), py::arg("channels"), py::arg("frame_rate"), py::arg("buffer_length"),
py::arg("units") = UnitType::eFrames, py::arg("name") = nullptr,
py::arg("channel_mask") = kSpeakerModeDefault, py::call_guard<py::gil_scoped_release>());
py::class_<PythonSoundData> sound(m, "SoundData");
sound.def("get_name", &PythonSoundData::getName,
R"( Retrieve the name of a SoundData object.
Returns:
The name that was given to the object.
This will return None if the object has no name.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("is_decoded", &PythonSoundData::isDecoded,
R"( Query if the SoundData object is decoded or streaming.
Returns:
True if the object is decoded.
False if the object is streaming.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("get_format", &PythonSoundData::getFormat,
R"( Query the SoundData object's format.
Returns:
For a sound that was decoded on load, this represents the format of the
audio data in the SoundData object's buffer.
For a streaming sound, this returns the format of the underlying sound
asset that is being streamed.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("get_length", &PythonSoundData::getLength,
R"( Query the SoundData object's buffer length.
Args:
units The unit type that will be returned. This defaults to UnitType.FRAMES.
Returns:
The length of the SoundData object's buffer.
)",
py::arg("units") = UnitType::eFrames, py::call_guard<py::gil_scoped_release>());
sound.def("set_valid_length", &PythonSoundData::setValidLength,
R"( Set the length of the valid portion of the SoundData object's buffer.
Args:
length The new valid length to be set.
units How length will be interpreted. This defaults to UnitType.FRAMES.
Returns:
The length of the SoundData object's buffer.
)",
py::arg("length"), py::arg("units") = UnitType::eFrames, py::call_guard<py::gil_scoped_release>());
sound.def("get_valid_length", &PythonSoundData::getValidLength,
R"( Query the SoundData object's buffer length.
Args:
units The unit type that will be returned. This defaults to
UnitType.FRAMES.
Returns:
The length of the SoundData object's buffer.
)",
py::arg("units") = UnitType::eFrames, py::call_guard<py::gil_scoped_release>());
sound.def("get_buffer_as_uint8", &PythonSoundData::getBufferU8,
R"( Retrieve a buffer of audio from the SoundData object in unsigned 8 bit
integer PCM.
Args:
length The length of the buffer you want to retrieve.
This will be clamped if the SoundData object does not have this
much data available.
offset The offset in the SoundData object to start reading from.
units How length and offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
A buffer of audio data from the SoundData object in unsigned 8 bit
integer format. The format is a list containing integer data with
values in the range [0, 255].
)",
py::arg("length") = 0, py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("get_buffer_as_int16", &PythonSoundData::getBufferS16,
R"( Retrieve a buffer of audio from the SoundData object in signed 16 bit
integer PCM.
Args:
length The length of the buffer you want to retrieve.
This will be clamped if the SoundData object does not have this
much data available.
offset The offset in the SoundData object to start reading from.
units How length and offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
A buffer of audio data from the SoundData object in signed 16 bit
integer format. The format is a list containing integer data with
values in the range [-32768, 32767].
)",
py::arg("length") = 0, py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("get_buffer_as_int32", &PythonSoundData::getBufferS32,
R"( Retrieve a buffer of audio from the SoundData object in signed 32 bit
integer PCM.
Args:
length The length of the buffer you want to retrieve.
This will be clamped if the SoundData object does not have this
much data available.
offset The offset in the SoundData object to start reading from.
units How length and offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
A buffer of audio data from the SoundData object in signed 32 bit
integer format. The format is a list containing integer data with
values in the range [-2147483648, 2147483647].
)",
py::arg("length") = 0, py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("get_buffer_as_float", &PythonSoundData::getBufferFloat,
R"( Retrieve a buffer of audio from the SoundData object in 32 bit float PCM.
Args:
length The length of the buffer you want to retrieve.
This will be clamped if the SoundData object does not have this
much data available.
offset The offset in the SoundData object to start reading from.
units How length and offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
A buffer of audio data from the SoundData object in signed 32 bit
integer format. The format is a list containing integer data with
values in the range [-1.0, 1.0].
)",
py::arg("length") = 0, py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("write_buffer_with_uint8", &PythonSoundData::writeBufferU8,
R"( Write a buffer of audio to the SoundData object with unsigned 8 bit PCM
data.
Args:
data The buffer of data to write to the SoundData object.
This must be a list of integer values representable as uint8_t.
offset The offset in the SoundData object to start reading from.
units How offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
No return value.
This will throw an exception if this is not a writable sound object.
Only sounds that were created empty or from raw PCM data are writable.
)",
py::arg("data"), py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("write_buffer_with_int16", &PythonSoundData::writeBufferS16,
R"( Write a buffer of audio to the SoundData object with signed 16 bit PCM
data.
Args:
data The buffer of data to write to the SoundData object.
This must be a list of integer values representable as int16_t.
offset The offset in the SoundData object to start reading from.
units How offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
No return value.
This will throw an exception if this is not a writable sound object.
Only sounds that were created empty or from raw PCM data are writable.
)",
py::arg("data"), py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("write_buffer_with_int32", &PythonSoundData::writeBufferS32,
R"( Write a buffer of audio to the SoundData object with signed 32 bit PCM
data.
Args:
data The buffer of data to write to the SoundData object.
This must be a list of integer values representable as int32_t.
offset The offset in the SoundData object to start reading from.
units How offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
No return value.
This will throw an exception if this is not a writable sound object.
Only sounds that were created empty or from raw PCM data are writable.
)",
py::arg("data"), py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("write_buffer_with_float", &PythonSoundData::writeBufferFloat,
R"( Write a buffer of audio to the SoundData object with 32 bit float PCM
data.
Args:
data The buffer of data to write to the SoundData object.
This must be a list of integer values representable as float.
offset The offset in the SoundData object to start reading from.
units How offset will be interpreted. This defaults to
UnitType.FRAMES.
Returns:
No return value.
This will throw an exception if this is not a writable sound object.
Only sounds that were created empty or from raw PCM data are writable.
)",
py::arg("data"), py::arg("offset") = 0, py::arg("units") = UnitType::eFrames,
py::call_guard<py::gil_scoped_release>());
sound.def("get_memory_used", &PythonSoundData::getMemoryUsed,
R"( Query the amount of memory that's in use by a SoundData object.
This retrieves the amount of memory used by a single sound data object. This
will include all memory required to store the audio data itself, to store the
object and all its parameters, and the original filename (if any). This
information is useful for profiling purposes to investigate how much memory
the audio system is using for a particular scene.
Returns:
The amount of memory in use by this sound, in bytes.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("get_max_instances", &PythonSoundData::getMaxInstances,
R"( Query the SoundData object's max instance count.
This retrieves the current maximum instance count for a sound. This limit
is used to prevent too many instances of a sound from being played
simultaneously. With the limit set to unlimited, playing too many
instances can result in serious performance penalties and serious clipping
artifacts caused by too much constructive interference.
Returns:
The SoundData object's max instance count.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("set_max_instances", &PythonSoundData::setMaxInstances,
R"( Set the SoundData object's max instance count.
This sets the new maximum playing instance count for a sound. This limit will
prevent the sound from being played until another instance of it finishes playing
or simply cause the play request to be ignored completely. This should be used
to limit the use of frequently played sounds so that they do not cause too much
of a processing burden in a scene or cause too much constructive interference
that could lead to clipping artifacts. This is especially useful for short
sounds that are played often (ie: gun shots, foot steps, etc). At some [small]
number of instances, most users will not be able to tell if a new copy of the
sound played or not.
Args:
limit The max instance count to set.
)",
py::arg("limit"), py::call_guard<py::gil_scoped_release>());
sound.def("get_peak_level", &PythonSoundData::getPeakLevel,
R"( Retrieves or calculates the peak volume levels for a sound if possible.
This retrieves the peak volume level information for a sound. This information
is either loaded from the sound's original source file or is calculated if
the sound is decoded into memory at load time. This information will not be
calculated if the sound is streamed from disk or memory.
Returns:
The peak level information from the SoundData object.
This will throw if peak level information is not embedded in the sound.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("get_event_points", &PythonSoundData::getEventPoints,
R"( Retrieves embedded event point information from a sound data object.
This retrieves event point information that was embedded in the sound file that
was used to create a sound data object. The event points are optional in the
data file and may not be present. If they are parsed from the file, they will
also be saved out to any destination file that the same sound data object is
written to, provided the destination format supports embedded event point
information.
Returns:
The list of event points that are embedded in this SoundData object.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("get_event_point_by_id", &PythonSoundData::getEventPointById,
R"( Retrieves a single event point object by its identifier.
Args:
id The ID of the event point to retrieve.
Returns:
The event point is retrieved if it exists.
None is returned if there was no event point found.
)",
py::arg("id"), py::call_guard<py::gil_scoped_release>());
sound.def("get_event_point_by_index", &PythonSoundData::getEventPointByIndex,
R"( Retrieves a single event point object by its index.
Event point indices are contiguous, so this can be used to enumerate event
points alternatively.
Args:
index The index of the event point to retrieve.
Returns:
The event point is retrieved if it exists.
None is returned if there was no event point found.
)",
py::arg("index"), py::call_guard<py::gil_scoped_release>());
sound.def("get_event_point_by_play_index", &PythonSoundData::getEventPointByPlayIndex,
R"( Retrieves a single event point object by its playlist index.
Event point playlist indices are contiguous, so this can be used to
enumerate the playlist.
Args:
index The playlist index of the event point to retrieve.
Returns:
The event point is retrieved if it exists.
None is returned if there was no event point found.
)",
py::arg("index"), py::call_guard<py::gil_scoped_release>());
sound.def("get_event_point_max_play_index", &PythonSoundData::getEventPointMaxPlayIndex,
R"( Retrieve the maximum play index value for the sound.
Returns:
This returns the max play index for this SoundData object.
This will be 0 if no event points have a play index.
This is also the number of event points with playlist indexes,
since the playlist index range is contiguous.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("set_event_points", &PythonSoundData::setEventPoints,
R"( Modifies, adds or removes event points in a SoundData object.
This modifies, adds or removed one or more event points in a sound data
object. An event point will be modified if one with the same ID already
exists. A new event point will be added if it has an ID that is not
already present in the sound data object and its frame offset is valid. An
event point will be removed if it has an ID that is present in the sound
data object but the frame offset for it is set to
EVENT_POINT_INVALID_FRAME. Any other event points with invalid frame
offsets (ie: out of the bounds of the stream) will be skipped and cause the
function to fail.
If an event point is modified or removed such that the playlist
indexes of the event points are no longer contiguous, this function
will adjust the play indexes of all event points to prevent any
gaps.
Args:
eventPoints: The event point(s) to be modified or added. The
operation that is performed for each event point in the
table depends on whether an event point with the same ID
already exists in the sound data object. The event points
in this table do not need to be sorted in any order.
Returns:
True if all of the event points in the table are updated successfully.
False if not all event points could be updated. This includes a
failure to allocate memory or an event point with an invalid frame
offset. Note that this failing doesn't mean that all the event points
failed. This just means that at least failed to be set properly. The
new set of event points may be retrieved and compared to the list set
here to determine which one failed to be updated.
)",
py::arg("eventPoints"), py::call_guard<py::gil_scoped_release>());
sound.def("clear_event_points", &PythonSoundData::clearEventPoints,
R"( Removes all event points from a SoundData object.
Returns:
No return value.
)",
py::call_guard<py::gil_scoped_release>());
sound.def("get_metadata_by_index", &PythonSoundData::getMetaDataByIndex,
R"( Retrieve a metadata tag from a SoundData object by its index.
Args:
index The index of the metadata tag.
Returns:
This returns a tuple: (metadata tag name, metadata tag value).
This returns (None, None) if there was no tag at the specified index.
)",
py::arg("index"), py::call_guard<py::gil_scoped_release>());
sound.def("get_metadata", &PythonSoundData::getMetaData,
R"( Retrieve a metadata value from a SoundData object by its tag name.
Args:
tag_name The metadata tag's name.
Returns:
This returns the metadata tag value for tag_name.
This returns None if there is no tag under tag_name.
)",
py::arg("tag_name"), py::call_guard<py::gil_scoped_release>());
sound.def("set_metadata", &PythonSoundData::setMetaData,
R"( Add a metadata tag to a SoundData object.
Metadata tag names are not case sensitive.
It is not guaranteed that a given file type will be able to store arbitrary
key-value pairs. RIFF files (.wav), for example, store metadata tags under
4 character codes, so only metadata tags that are known to this plugin,
such as META_DATA_TAG_ARTIST or tags that are 4 characters in length can be
stored. Note this means that storing 4 character tags beginning with 'I'
runs the risk of colliding with the known tag names (e.g. 'IART' will
collide with META_DATA_TAG_ARTIST when writing a RIFF file).
tag_name must not contain the character '=' when the output format encodes
its metadata in the Vorbis Comment format (SampleFormat.VORBIS and
SampleFormat.FLAC do this). '=' will be replaced with '_' when
encoding these formats to avoid the metadata being encoded incorrectly.
Additionally, the Vorbis Comment standard states that tag names must only
contain characters from 0x20 to 0x7D (excluding '=') when encoding these
formats.
Args:
tag_name The metadata tag's name.
tag_value The metadata tag's value.
Returns:
No return value.
)",
py::arg("tag_name"), py::arg("tag_value"), py::call_guard<py::gil_scoped_release>());
sound.def("save_to_file", &PythonSoundData::saveToFile,
R"( Save a SoundData object to disk as a playable audio file.
Args:
file_name The path to save this file as.
format The audio format to use when saving this file.
PCM formats will save as a WAVE file (.wav).
flags Flags to alter the behavior of this function.
This is a bitmask of SAVE_FLAG_* flags.
Returns:
True if the SoundData object was saved to disk successfully.
False if saving to disk failed.
)",
py::arg("file_name"), py::arg("format") = SampleFormat::eDefault, py::arg("flags") = 0);
}
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/IAudioDevice.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief The audio device enumeration interface.
*/
#pragma once
#include "../Interface.h"
#include "AudioTypes.h"
namespace carb
{
namespace audio
{
/** the direction to collect device information for. */
enum class DeviceType
{
ePlayback, /**< Audio playback devices (e.g. headphones) */
eCapture, /**< Audio capture devices (e.g. microphone) */
};
/** Which device backend is being used for audio.
*
* @note @ref IAudioCapture will always use DirectSound as a backend on Windows.
* This behavior will be changed eventually so that @ref IAudioCapture uses
* the same device backend as other systems.
*/
enum class DeviceBackend
{
/** The null audio device backend was selected.
* Audio playback and capture will still function as expected, but the
* output audio will be dropped and input audio will be silence.
* This will only be used if manually selected via the `audio/deviceBackend`
* settings key or in the case where a system is missing its core audio libraries.
*/
eNull,
/** Windows Audio Services device API (aka WASAPI).
* This is the only device backend on Windows.
* This is fairly user-friendly and should not require any special handling.
*/
eWindowsAudioServices,
/** Pulse Audio sound server for Linux.
* This is the standard sound server on Linux for consumer audio.
* This API is fairly user-friendly and should not require any special handling.
* Each of the audio streams through Pulse Audio will be visible through
* programs such as `pavucontrol` (volume control program).
* The name of these streams can be set for @ref IAudioPlayback with
* @ref PlaybackContextDesc::outputDisplayName; if that was not set, a generic
* name will be used.
*/
ePulseAudio,
/** Advance Linux Audio System (ALSA).
* This is the underlying kernel sound system as well as an array of plugins.
* Some users may use ALSA so they can use the JACK plugin for professional
* audio applications.
* Some users also prefer to use the `dmix` and `dsnoop` sound servers
* instead of Pulse Audio.
* ALSA is not user-friendly, so the following issues may appear:
* - ALSA devices are sensitive to latency because, for the most part,
* they use a fixed-size ring buffer, so it is possible to get audio
* underruns or overruns on a heavily loaded system or a device
* configured with an extremely small buffer.
* - Some ALSA devices are exclusive access, so there is no guaranteed that
* they will open properly.
* - Multiple configurations of each physical device show up as a separate
* audio device, so a system with two audio devices will have ~40 ALSA
* devices.
* - Opening an ALSA device can take hundreds of milliseconds.
* Combined with the huge device count, this can mean that manually
* enumerating all devices on the system can take several seconds.
* - Some versions of libasound will automatically create devices with
* invalid configurations, such as `dmix` devices that are flagged as
* supporting playback and capture but will fail to open for capture.
* - ALSA devices can be configured with some formats that carb.audio
* does not support, such as big endian formats, ULAW or 64 bit float.
* Users should use a `plug` (format conversion) plugin for ALSA if they
* need to use a device that requires a format such as this.
*/
eAlsa,
/** The Mac OS CoreAudio system.
* This is the standard sound system used on Mac OS.
* This is fairly user-friendly and should not require any special handling.
*/
eCoreAudio,
};
/** A callback that is performed when a device notification occurs.
* @param[in] ctx The context value this notification was registered with.
*
* @remarks This notification will occur on every device change that @p ctx
* registered to. No information about what changed is provided.
*/
typedef void (*DeviceNotifyCallback)(void* ctx);
/** A device change notification context.
* This instance exists to track the lifetime of a device change notification
* subscription.
*/
class DeviceChangeNotifier;
/** An interface to provide simple audio device enumeration functionality, as
* well as device change notifications. This is able to enumerate all audio
* devices attached to the system at any given point and collect the
* information for each device. This is able to collect information and
* provide notifications for both playback and capture devices.
*/
struct IAudioDevice
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
CARB_PLUGIN_INTERFACE("carb::audio::IAudioDevice", 1, 1);
#endif
/** retrieves the total number of devices attached to the system of a requested type.
*
* @param[in] dir the audio direction to get the device count for.
* @returns the total number of connected audio devices of the requested type.
* @returns 0 if no audio devices are connected to the system.
*/
size_t(CARB_ABI* getDeviceCount)(DeviceType dir);
/** Retrieve the capabilities of a device.
* @param[in] dir The audio direction of the device.
* @param[in] index The index of the device to retrieve the description for. This
* should be between 0 and one less than the most recent return
* value of getDeviceCount().
* @param[inout] caps The capabilities of this device.
* `caps->thisSize` must be set to `sizeof(*caps)`
* before passing it.
* @returns @ref AudioResult::eOk if the device info was successfully retrieved.
* @returns @ref AudioResult::eInvalidParameter if the @a thisSize value is not properly
* initialized in @p caps or @p caps is nullptr.
* @returns @ref AudioResult::eOutOfRange if the requested device index is out of range of
* the system's current device count.
* @returns @ref AudioResult::eNotSupported if a device is found but it requires an
* unsupported sample format.
* @returns an AudioResult::* error code if another failure occurred.
*/
AudioResult(CARB_ABI* getDeviceCaps)(DeviceType dir, size_t index, carb::audio::DeviceCaps* caps);
/** Create a device notification object.
* @param[in] type The device type to fire the callback for.
* @param[in] callback The callback that will be fired when a device change occurs.
* This must not be nullptr.
* @param[in] context The object passed to the parameter of @p callback.
*
* @returns A valid device notifier object if successful.
* This must be destroyed with destroyNotifier() when device
* notifications are no longer needed.
* @returns nullptr if an error occurred.
*/
DeviceChangeNotifier*(CARB_ABI* createNotifier)(DeviceType type, DeviceNotifyCallback callback, void* context);
/** Destroy a device notification object.
* @param[in] notifier The notification object to free.
* Device notification callbacks for this object will
* no longer occur.
*/
void(CARB_ABI* destroyNotifier)(DeviceChangeNotifier* notifier);
/** Query the device backend that's currently in use.
* @returns The device backend in use.
* @note This returned value is cached internally, so these calls are inexpensive.
* @note The value this returns will not change until carb.audio reloads.
*/
DeviceBackend(CARB_ABI* getBackend)();
/** Retrieve a minimal set of device properties.
* @param[in] dir The audio direction of the device.
* @param[in] index The index of the device to retrieve the description for. This
* should be between 0 and one less than the most recent return
* value of getDeviceCount().
* @param[inout] caps The basic properties of this device.
* @ref DeviceCaps::name and @ref DeviceCaps::guid will
* be written to this.
* @ref DeviceCaps::flags will have @ref fDeviceFlagDefault
* set if this is the default device, but no other flags
* will be set.
* All other members of this struct will be set to default
* values.
* `caps->thisSize` must be set to `sizeof(*caps)`
* before passing it.
*
* @retval AudioResult::eOk on success.
* @retval AudioResult::eInvalidParameter if @p caps had an invalid `thisSize` member or was `nullptr`.
* @retval AudioResult::eOutOfRange if @p index was past the end of the device list.
*/
AudioResult(CARB_ABI* getDeviceName)(DeviceType type, size_t index, DeviceCaps* caps);
/** Retrieve the capabilities of a device.
* @param[in] dir The audio direction of the device.
* @param[in] guid The guid of the device to retrieve the description for.
* @param[inout] caps The capabilities of this device.
* `caps->thisSize` must be set to `sizeof(*caps)`
* before passing it.
* @returns @ref AudioResult::eOk if the device info was successfully retrieved.
* @returns @ref AudioResult::eInvalidParameter if the @a thisSize value is not properly
* initialized in @p caps, @p caps is `nullptr` or @p guid is `nullptr`.
* @returns @ref AudioResult::eOutOfRange if @p guid did not correspond to a device.
* @returns @ref AudioResult::eNotSupported if a device is found but it requires an
* unsupported sample format.
* @returns an AudioResult::* error code if another failure occurred.
*/
AudioResult(CARB_ABI* getDeviceCapsByGuid)(DeviceType dir,
const carb::extras::Guid* guid,
carb::audio::DeviceCaps* caps);
/** Retrieve a minimal set of device properties.
* @param[in] dir The audio direction of the device.
* @param[in] guid The guid of the device to retrieve the description for.
* @param[inout] caps The basic properties of this device.
* @ref DeviceCaps::name and @ref DeviceCaps::guid will
* be written to this.
* @ref DeviceCaps::flags will have @ref fDeviceFlagDefault
* set if this is the default device, but no other flags
* will be set.
* All other members of this struct will be set to default
* values.
* `caps->thisSize` must be set to `sizeof(*caps)`
* before passing it.
*
* @retval AudioResult::eOk on success.
* @retval AudioResult::eInvalidParameter if the @a thisSize value is not properly
* initialized in @p caps, @p caps is `nullptr` or @p guid is `nullptr`.
* @retval AudioResult::eOutOfRange if @p guid did not correspond to a device.
*/
AudioResult(CARB_ABI* getDeviceNameByGuid)(DeviceType dir,
const carb::extras::Guid* guid,
carb::audio::DeviceCaps* caps);
};
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/IAudioData.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief The audio data management interface.
*/
#pragma once
#include "../Interface.h"
#include "../assets/IAssets.h"
#include "AudioTypes.h"
namespace carb
{
namespace audio
{
/************************************* Interface Objects *****************************************/
/** a buffer of sound data. This includes all of the information about the data's format and the
* sound data itself. This data may be in a decoded PCM stream or an encoded/compressed format.
* Note that much of the information in this object can be accessed through the IAudioData interface.
* This includes (but is not limited to) extra decoding information about the compression format.
*/
struct SoundData DOXYGEN_EMPTY_CLASS;
/** stores information on the current decoding or encoding state of a @ref SoundData object.
* This object is kept separate from the sound data to avoid the limitation that streaming from
* a SoundData object or encoding a single sound to multiple targets can only have one
* simultaneous instance. The information stored in this object determines how the sound
* data is decoded (ie: streamed from disk, streamed from memory, etc) and holds state
* information about the decoding process itself.
*/
struct CodecState DOXYGEN_EMPTY_CLASS;
/********************************* Sound Data Object Creation ************************************/
/** special value to indicate that the maximum instance count for a sound or sound group is
* unlimited. This can be passed to setMaxInstances() or can be returned from getMaxInstances().
*/
constexpr uint32_t kInstancesUnlimited = 0;
/** flags used for the createData() function. These control how the the sound data object is
* created or loaded. Zero or more of these flags may be combined to change the way the audio
* data is loaded. Only one of the fDataFlagFormat* flags may be used since they are all mutually
* exclusive.
*
* Note that not all of these flags can be used when loading a sound object through the asset
* system. Some flags require additional information in order to function properly and that
* information cannot be passed in through the asset system's loadAsset() function.
*
* @{
*/
/** base type used to specify the fDataFlag* flags for createData(). */
typedef uint32_t DataFlags;
/** mask to indicate which flag bits are reserved to specify the file format flags. These flags
* allow the loaded format of file data to be forced instead of auto-detected from the file's
* header. All of the format flags except for @ref fDataFlagFormatRaw may be used with the
* asset system loader. Note that the format values within this mask are all mutually exclusive,
* not individual flag bits. This mask can be used to determine the loaded format of a sound
* data object after it is loaded and the load-time flags retrieved with getFlags().
*/
constexpr DataFlags fDataFlagFormatMask = 0x000000ff;
/** auto detect the format from the file header data. This may only be used when the data is
* coming from a full audio file (on disk or in memory). The format information in the file's
* header will always be used regardless of the filename extension. This format flag is mutually
* exclusive from all other fDataFlagFormat* flags. Once a sound data object is successfully
* created, this flag will be replaced with one that better represents the actual encoded data
* in the sound.
*/
constexpr DataFlags fDataFlagFormatAuto = 0x00000000;
/** force raw PCM data to be loaded. This flag must be specified if the data stream does not
* have any format information present in it. When this format flag is used the data stream
* is expected to just be the raw decodable data for the specified format. There should not
* be any kind of header or chunk signature before the data. This format flag is mutually
* exclusive from all other fDataFlagFormat* flags.
*/
constexpr DataFlags fDataFlagFormatRaw = 0x00000001;
/** the data was loaded as WAV PCM. This flag will be added to the sound data object upon
* load to indicate that the original data was loaded from a PCM WAV/RIFF file. If specified
* before load, this flag will be ignored and the load will behave as though the data format
* flag were specified as @ref fDataFlagFormatAuto. This format flag is mutually exclusive
* from all other fDataFlagFormat* flags.
*/
constexpr DataFlags fDataFlagFormatPcm = 0x00000002;
/** This flag indicates that the metadata should be ignored when opening the sound.
* This is only relevant on sounds that need to be decoded from a file format that
* can store metadata.
* This is intended to be used in cases where the metadata won't be needed.
* Note that subsequent calls to createCodecState() which decode the loaded
* sound will not decode the metadata unless the @ref fDecodeStateFlagForceParse
* flag is used.
*/
constexpr DataFlags fDataFlagSkipMetaData = 0x00200000;
/** This flag indicates that the event points should be ignored when decoding the sound.
* This is only relevant on sounds that need to be decoded from a file format that
* can store event points
* This is intended to be used in cases where the event points won't be needed.
* Note that subsequent calls to createCodecState() which decode the loaded
* sound will not decode the event points unless the @ref fDecodeStateFlagForceParse
* flag is used.
*/
constexpr DataFlags fDataFlagSkipEventPoints = 0x00400000;
/** flag to indicate that the peak volumes for each channel should be calculated for the sound
* data object as its data is decoded at creation time or when streaming into the sound data
* object. This does not have any affect on decode operations that occur while playing back
* the sound data. This may be specified when creating an empty sound. This may be specified
* when the sound data object is loaded through the asset loader system.
*/
constexpr DataFlags fDataFlagCalcPeaks = 0x01000000;
/** load the file data from a blob in memory. The blob of file data is specified in the
* @ref SoundDataLoadDesc::dataBlob value and the blob's size is specified in the
* @ref SoundDataLoadDesc::dataBlobLengthInBytes value. Depending on the other flags used,
* this blob may be copied into the new sound data object or it may be decoded into the
* new object. As long as the @ref fDataFlagUserMemory flag is not also used, the blob
* data may be discarded upon return from createData(). This flag is always implied
* when loading a sound data object through the asset loader system.
*/
constexpr DataFlags fDataFlagInMemory = 0x02000000;
/** when the @ref fDataFlagInMemory flag is also used, this indicates that the original memory
* blob should be directly referenced in the new sound data object instead of copying it. When
* this flag is used, it is the caller's responsibility to ensure the memory blob remains valid
* for the entire lifetime of the sound data object. Note that if the @ref fDataFlagDecode flag
* is specified and the sound is encoded as a PCM format (either in a WAVE file or raw PCM loaded
* with @ref fDataFlagFormatRaw), the original memory blob will still be referenced. Using
* @ref fDataFlagDecode with any other format, such as @ref SampleFormat::eVorbis, will decode
* the audio into a new buffer and the original blob will no longer be needed.
*
* This flag is useful for creating sound data objects that reference audio data in a sound
* bank or sound atlas type object that exists for the lifetime of a scene. The original
* data in the bank or atlas can be referenced directly instead of having to copy it and
* use twice the memory (and time to copy it).
*/
constexpr DataFlags fDataFlagUserMemory = 0x04000000;
/** create the sound data object as empty. The buffer will be allocated to the size
* specified in @ref SoundDataLoadDesc::bufferLength and will be filled with silence.
* The data format information also must be filled out in the SoundDataLoadDesc
* descriptor before calling createData(). All other flags except for the
* @ref fDataFlagNoName and @ref fDataFlagCalcPeaks flags will be ignored when this
* flag is used. This flag is not allowed if specified through the asset loader
* system since it requires extra information.
*/
constexpr DataFlags fDataFlagEmpty = 0x08000000;
/** use the user-decode callbacks when loading or streaming this data. In this case, the
* format of the original sound is unspecified and unknown. The decode callback will be
* used to convert all of the object's data to PCM data when streaming or loading (depending
* on the other flags used). When this flag is used, the decoded format information in the
* SoundDataLoadDesc descriptor must be specified. This flag is not allowed if specified
* through the asset loader system since it requires extra information.
*
* In addition to allowing additional audio formats to be decoded, the user decode callbacks
* can also act as a simple abstract datasource; this may be useful when wanting to read data
* from a pack file without having to copy the full file blob out to memory.
*/
constexpr DataFlags fDataFlagUserDecode = 0x10000000;
/** stream the audio data at runtime. The behavior when using this flag greatly depends
* on some of the other flags and the format of the source data. For example, if the
* @ref fDataFlagInMemory flag is not used, the data will be streamed from disk. If
* that flag is used, the encoded/compressed data will be loaded into the sound data
* object and it will be decoded at runtime as it is needed. This flag may not be
* combined with the @ref fDataFlagDecode flag. If it is, this flag will be ignored
* and the full data will be decoded into PCM at load time. If neither this flag nor
* @ref fDataFlagDecode is specified, the @ref fDataFlagDecode flag will be implied.
* This flag is valid to specify when loading a sound data object through the asset
* loader system.
*/
constexpr DataFlags fDataFlagStream = 0x20000000;
/** decode the sound's full data into PCM at load time. The full stream will be converted
* to PCM data immediately when the new sound data object is created. The destination
* PCM format will be chosen by the decoder if the @ref SoundDataLoadDesc::pcmFormat value
* is set to @ref SampleFormat::eDefault. If it is set to one of the SampleFormat::ePcm*
* formats, the stream will be decoded into that format instead. This flag is valid to
* specify when loading a sound data object through the asset loader system. However,
* if it is used when loading an asset, the original asset data will only be referenced
* if it was already in a PCM format. Otherwise, it will be decoded into a new buffer
* in the new sound data object. If both this flag and @ref fDataFlagStream are specified,
* this flag will take precedence. If neither flag is specified, this one will be implied.
*/
constexpr DataFlags fDataFlagDecode = 0x40000000;
/** don't store the asset name or filename in the new sound data object. This allows some
* memory to to be saved by not storing the original filename or asset name when loading a
* sound data object from file, through the asset system, or when creating an empty object.
* This will also be ignored if the @ref fDataFlagStream flag is used when streaming from
* file since the original filename will be needed to reopen the stream for each new playing
* instance. This flag is valid to specify when loading a sound data object through the
* asset loader system.
*/
constexpr DataFlags fDataFlagNoName = 0x80000000;
/** @} */
/**
* callback function prototype for reading data for fDataFlagUserDecode sound data objects.
*
* @param[in] soundData the sound object to read the sound data for. This object will be
* valid and can be accessed to get information about the decoding
* format. The object's data buffer should not be accessed from
* the callback, but the provided @p data buffer should be used instead.
* This may not be nullptr.
* @param[out] data the buffer that will receive the decoded audio data. This buffer will be
* large enough to hold @p dataLength bytes. This may be nullptr to indicate
* that the remaining number of bytes in the stream should be returned in
* @p dataLength instead of the number of bytes read.
* @param[inout] dataLength on input, this contains the length of the @p data buffer in bytes.
* On output, if @p data was not nullptr, this will contain the
* number of bytes actually written to the buffer. If @p data
* was nullptr, this will contain the number of bytes remaining to be
* read in the stream. All data written to the buffer must be frame
* aligned.
* @param[in] context the callback context value specified in the SoundDataLoadDesc object.
* This is passed in unmodified.
* @returns AudioResult.eOk if the read operation is successful.
* @returns AudioResult.eTryAgain if the read operation was not able to fill an entire buffer and
* should be called again. This return code should be used when new data is not yet
* available but is expected soon.
* @returns AudioResult.eOutOfMemory if the full audio stream has been decoded (if it decides
* not to loop). This indicates that there is nothing left to decode.
* @returns an AudioResult.* error code if the callback could not produce its data for any
* other reason.
*
* @remarks This is used to either decode data that is in a proprietary format or to produce
* dynamic data as needed. The time and frequency at which this callback is performed
* depends on the flags that were originally passed to createData() when the sound
* data object was created. If the @ref fDataFlagDecode flag is used, this would
* only be performed at load time to decode the entire stream.
*
* @remarks When using a decoding callback, the data written to the buffer must be PCM data in
* the format expected by the sound data object. It is the host app's responsibility
* to know the sound format information before calling createData() and to fill
* that information into the @ref SoundDataLoadDesc object.
*/
typedef AudioResult(CARB_ABI* SoundDataReadCallback)(const SoundData* soundData,
void* data,
size_t* dataLength,
void* context);
/**
* an optional callback to reposition the data pointer for a user decoded stream.
*
* @param[in] soundData the sound data object to set the position for. This object will be
* valid and can be used to read data format information. Note that the
* host app is expected to know how to convert the requested decoded
* position into an encoded position. This may not be nullptr.
* @param[in] position the new position to set for the stream. This value must be greater than
* or equal to 0, and less than the length of the sound (as returned from
* getLength()). This value is interpreted according to the @p type value.
* @param[in] type the units to interpret the new read cursor position in. Note that if this
* is specified in milliseconds, the actual position that it seeks to may not
* be accurate. Similarly, if a position in bytes is given, it will be
* rounded up to the next frame boundary.
* @param[in] context the callback context value specified in the @ref SoundDataLoadDesc object.
* This is passed in unmodified.
* @returns AudioResult.eOk if the positioning operation was successful.
* @returns AudioResult.eInvalidParameter if the requested offset is outside the range of the
* active sound.
* @returns an AudioResult.* error code if the operation fails for any other reason.
*
* @remarks This is used to handle operations to reposition the read cursor for user decoded
* sounds. This callback occurs when a sound being decoded loops or when the current
* playback/decode position is explicitly changed. The callback will perform the actual
* work of positioning the decode cursor and the new decoding state information should
* be updated on the host app side. The return value may be returned directly from
* the function that caused the read cursor position to change in the first place.
*/
typedef AudioResult(CARB_ABI* SoundDataSetPosCallback)(const SoundData* soundData,
size_t position,
UnitType type,
void* context);
/** An optional callback that gets fired when the SoundData's final reference is released.
* @param[in] soundData The sound data object to set the destructor for.
* This object will still be valid during this callback,
* but immediately after this callback returns, @p soundData
* will be invalid.
* @param[in] context the callback context value specified in the @ref SoundDataLoadDesc object.
* This is passed in unmodified.
*/
typedef void(CARB_ABI* SoundDataDestructionCallback)(const SoundData* soundData, void* context);
/** the memory limit threshold for determining if a sound should be decoded into memory.
* When the fDataFlagDecode flag is used and the size of the decoded sound is over this limit,
* the sound will not be decoded into memory.
*/
constexpr size_t kMemoryLimitThreshold = 1ull << 31;
/** a descriptor for the sound data to be loaded. This is a flexible loading method that allows
* sound data to be loaded from file, memory, streamed from disk, loaded as raw PCM data, loaded
* from a proprietary data format, decoded or decompressed at load time, or even created as an
* empty sound buffer. The loading method depends on the flags used. For data loaded from file
* or a blob in memory, the data format can be auto detected for known supported formats.
*
* Not all members in this object are used on each loading path. For example, the data format
* information will be ignored when loading from a file that already contains format information
* in its header. Regardless of whether a particular value is ignored, it is still the caller's
* responsibility to appropriately initialize all members of this object.
*
* Sound data is loaded using this descriptor through a single loader function. Because there
* are more than 60 possible combinations of flags that can be used when loading sound data,
* it's not feasible to create a separate loader function for each possible method.
*/
struct SoundDataLoadDesc
{
/** flags to control how the sound data is loaded and decoded (if at all). This is a
* combination of zero or more of the fDataFlag* flags. By default, the sound data's
* format will attempt to be auto detected and will be fully loaded and decoded into memory.
* This value must be initialized before calling createData().
*/
DataFlags flags = 0;
/** Dummy member to enforce padding. */
uint32_t padding1{ 0 };
/** filename or asset name for the new object. This may be specified regardless of whether
* the @ref fDataFlagInMemory flag is used. When that flag is used, this can be used to
* give an asset name to the sound object. The name will not be used for any purpose
* except as a way to identify it to a user in that case. When loading the data from
* a file, this represents the filename to load from. When the @ref fDataFlagInMemory
* flag is not used, this must be the filename to load from. This may be nullptr only
* if the audio data is being loaded from a blob in memory.
*/
const char* name = nullptr;
/** when the @ref fDataFlagInMemory flag is used, this is the blob of data to load from
* memory. If the flag is not specified, this value will be ignored. When loading from
* memory, the @ref dataBlobLengthInBytes will indicate the size of the data blob in bytes.
* Specifying a data blob with @ref fDataFlagFormatRaw with a pointer that is misaligned for
* its sample type is allowed; the effects of @ref fDataFlagUserMemory will be disabled so
* a properly aligned local buffer can be allocated.
* The effects of @ref fDataFlagUserMemory will also be disabled when specifying a wave file
* blob where the data chunk is misaligned for its sample type (this is only possible for 32
* bit formats).
*/
const void* dataBlob = nullptr;
/** when the @ref fDataFlagInMemory flag is used, this value specifies the size of
* the data blob to load in bytes. When the flag is not used, this value is ignored.
*/
size_t dataBlobLengthInBytes = 0;
/** the number of channels to create the sound data with. This value is ignored if the sound
* data itself contains an embedded channel count (ie: when loading from file). This must be
* initialized to a non-zero value when the @ref fDataFlagFormatRaw, @ref fDataFlagEmpty,
* or @ref fDataFlagUserDecode flags are used.
* If @ref fDataFlagUserDecode is used and @ref encodedFormat is a non-PCM format, this will
* be ignored.
*/
size_t channels = kDefaultChannelCount;
/** a mask that maps speaker channels to speakers. All channels in the stream are interleaved
* according to standard SMPTE order. This mask indicates which of those channels are
* present in the stream. This may be @ref kSpeakerModeDefault to allow a standard speaker
* mode to be chosen from the given channel count.
*/
SpeakerMode channelMask = kSpeakerModeDefault;
/** the rate in frames per second that the sound was originally mastered at. This will be the
* default rate that it is processed at. This value is ignored if the sound data itself
* contains an embedded frame rate value (ie: when loading from file). This must be
* initialized to a non-zero value when the @ref fDataFlagFormatRaw, @ref fDataFlagEmpty,
* or @ref fDataFlagUserDecode flags are used.
* If @ref fDataFlagUserDecode is used and @ref encodedFormat is a non-PCM format, this will
* be ignored.
*/
size_t frameRate = kDefaultFrameRate;
/** the data format of each sample in the sound. This value is ignored if the sound data
* itself contains an embedded data format value (ie: when loading from file). This must be
* initialized to a non-zero value when the @ref fDataFlagFormatRaw, @ref fDataFlagEmpty,
* or @ref fDataFlagUserDecode flags are used. This represents the encoded sample format
* of the sound.
*
* If the @ref fDataFlagUserDecode flag is used, this will be the format produced by the
* user decode callback.
* Note that PCM data produced from a user decode callback must be raw PCM data rather than
* a WAVE file blob.
* The user decode callback does not need to provide whole frames/blocks of this sample type,
* since this effectively acts as an arbitrary data source.
* This allows you to specify that the user decode callback returns data in a non-PCM format
* and have it decoded to the PCM format specified by @ref pcmFormat.
*
* If the @ref fDataFlagEmpty flag is used and this is set to @ref SampleFormat::eDefault,
* this will be set to the same sample format as the @ref pcmFormat format.
*/
SampleFormat encodedFormat = SampleFormat::eDefault;
/** the decoded or preferred intermediate PCM format of the sound. This value should be set
* to @ref SampleFormat::eDefault to allow the intermediate format to be chosen by the
* decoder. Otherwise, this should be set to one of the SampleFormat::ePcm* formats to
* force the decoder to use a specific intermediate or internal representation of the sound.
* This is useful for saving memory on large decoded sounds by forcing a smaller format.
*
* When the @ref fDataFlagDecode flag is used, this will be the PCM format that the data is
* decoded into.
*
* When the @ref fDataFlagEmpty flag is used and this is set to @ref SampleFormat::eDefault,
* the decoder will choose the PCM format. If the @ref encodedFormat value is also set to
* @ref SampleFormat::eDefault, it will also use the decoder's preferred PCM format.
*/
SampleFormat pcmFormat = SampleFormat::eDefault;
/** specifies the desired length of an empty sound data buffer, a raw buffer, or user decode
* buffer. This value is interpreted according to the units in @ref bufferLengthType. This
* value is ignored if the sound data itself contains embedded length information (ie: when
* loading from file). This must be initialized to a non-zero value when either the
* @ref fDataFlagFormatRaw, @ref fDataFlagEmpty, or @ref fDataFlagUserDecode flags are used.
* When using this with @ref fDataFlagEmpty, the sound data object will initially be marked
* as containing zero valid frames of data. If played, this will always decode silence.
* If the host app writes new data into the buffer, it must also update the valid data size
* with setValidLength() so that the new data can be played.
*/
size_t bufferLength = 0;
/** determines how the @ref bufferLength value should be interpreted. This value is ignored
* in the same cases @ref bufferLength are ignored in. For @ref fDataFlagEmpty, this may be
* any valid unit type. For @ref fDataFlagFormatRaw and @ref fDataFlagUserDecode, this may
* only be @ref UnitType::eFrames or @ref UnitType::eBytes.
*/
UnitType bufferLengthType = UnitType::eFrames;
/** Dummy member to enforce padding. */
uint32_t padding2{ 0 };
/** a callback function to provide decoded PCM data from a user-decoded data format. This
* value is ignored unless the @ref fDataFlagUserDecode flag is used. This callback
* is responsible for decoding its data into the PCM format specified by the rest of the
* information in this descriptor. The callback function or caller are responsible for
* knowing the decoded format before calling createData() and providing it in this
* object.
*/
SoundDataReadCallback readCallback = nullptr;
/** an optional callback function to provide a way to reposition the decoder in a user
* decoded stream. This value is ignored unless the @ref fDataFlagUserDecode flag
* is used. Even when the flag is used, this callback is only necessary if the
* @ref fDataFlagStream flag is also used and the voice playing it expects to either
* loop the sound or be able to reposition it on command during playback. If this callback
* is not provided, attempts to play this sound on a looping voice or attempts to change
* the streaming playback position will simply fail.
*/
SoundDataSetPosCallback setPosCallback = nullptr;
/** an opaque context value that will be passed to the readCallback and setPosCallback
* functions each time they are called. This value is a caller-specified object that
* is expected to contain the necessary decoding state for a user decoded stream. This
* value is only necessary if the @ref fDataFlagUserDecode flag is used. This value
* will only be used at load time on a user decoded stream if the @ref fDataFlagDecode
* flag is used (ie: causing the full sound to be decoded into memory at load time). If
* the sound is created to be streamed, this will not be used.
*/
void* readCallbackContext = nullptr;
/** An optional callback that gets fired when the SoundData's final
* reference is released. This is intended to make it easier to perform
* cleanup of a SoundData in cases where @ref fDataFlagUserMemory is used.
*/
SoundDataDestructionCallback destructionCallback = nullptr;
/** An opaque context value that will be passed to @ref destructionCallback
* when the last reference to the SoundData is released.
* This will not be called if the SoundData is not created successfully.
*/
void* destructionCallbackContext = nullptr;
/** Reserved for future expansion for options to be used when @ref fDataFlagDecode
* is specified.
*/
void* encoderSettings = nullptr;
/** the maximum number of simultaneous playing instances that this sound can have. This
* can be @ref kInstancesUnlimited to indicate that there should not be a play limit.
* This can be any other value to limit the number of times this sound can be played
* at any one time.
*/
uint32_t maxInstances = kInstancesUnlimited;
/** Dummy member to enforce padding. */
uint32_t padding3{ 0 };
/** the size in bytes at which to decide whether to decode or stream this sound. This
* will only affect compressed non-PCM sound formats. This value will be ignored for
* any PCM format regardless of size. This can be zero to just decide to stream or
* decode based on the @ref fDataFlagDecode or @ref fDataFlagStream flags. If this
* is non-zero, the sound will be streamed if its PCM size is larger than this limit.
* The sound will be fully decoded if its PCM size is smaller than this limit. In
* this case, the @ref fDataFlagDecode flag and @ref fDataFlagStream flag will be ignored.
*
* Note that if this is non-zero, this will always override the stream and decode flags'
* behavior.
*/
size_t autoStreamThreshold = 0;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** additional load parameters for sound data objects. These are passed through to the asset
* loader as a way of passing additional options beyond just the filename and flags. These
* additional options will persist for the lifetime of the loaded asset and will be passed
* to the loader function each time that asset needs to be reloaded from its original data
* source. Any shallow copied objects in here must be guaranteed persistent by the caller
* for the entire period the asset is valid. It is the host app's responsibility to clean
* up any resources in this object once the asset it was used for has been unloaded.
*
* In general, it is best practice not to fill in any of the pointer members of this struct
* and to allow them to just use their default behavior.
*/
struct SoundLoadParameters : public carb::assets::LoadParameters
{
/** additional parameters to pass to the asset loader. The values in here will follow
* all the same rules as using the @ref SoundDataLoadDesc structure to directly load
* a sound data object, except that the @a dataBlob and @a dataBlobLengthInBytes values
* will be ignored (since they are provided by the asset loader system). The other
* behavior that will be ignored will be that the @ref fDataFlagInMemory flag will
* always be used. Loading a sound data object through the asset system does not
* support loading from a disk filename (the asset system itself will handle that
* if the data source supports it).
*
* @note most of the values in this parameter block are still optional. Whether
* each value is needed or not often depends on the flags that are specified.
*
* @note most the pointer members in this parameter block should be set to nullptr
* for safety and ease of cleanup. This includes the @a name, @a dataBlob, and
* @a encoderSettings values. Setting the @a readCallbackContext and
* @a destructionCallbackContext values is acceptable because the host app is
* always expected to manage those objects' lifetimes anyway.
*/
SoundDataLoadDesc params = {};
};
/************************************* Codec State Objects ***************************************/
/** names to identify the different parts of a codec. These are used to indicate which type of
* codec state needs to be created or to indicate which type of sound format to retrieve.
*/
enum class CodecPart
{
/** identifies the decoder part of the codec or that the decoded sound format should be
* retrieved. When retrieving a format, this will be the information for the PCM format
* for the sound. When creating a codec state, this will expect that the decoder descriptor
* information has been filled in.
*/
eDecoder,
/** identifies the encoder part of the codec or that the encoded sound format should be
* retrieved. When retrieving a format, this will be the information for the encoded
* format for the sound. When creating a codec state, this will expect that the encoder
* descriptor information has been filled in.
*/
eEncoder,
};
/** Flags that alter the decoding behavior for SoundData objects.
*/
typedef uint64_t DecodeStateFlags;
/** If this flag is set, the header information of the file will be parsed
* every time createCodecState() is called.
* If this flag is not set, the header information of the file will be cached
* if possible.
*/
constexpr DecodeStateFlags fDecodeStateFlagForceParse = 0x00000001;
/** If this flag is set and the encoded format supports this behavior, indexes
* for seek optimization will be generated when the CodecState is created.
* For a streaming sound on disk, this means that the entire sound will be
* read off disk when creating this index; the sound will not be decoded or
* fully loaded into memory, however.
* This will reduce the time spent when seeking within a SoundData object.
* This will increase the time spent initializing the decoding stream, and this
* will use some additional memory.
* This option currently only affects @ref SampleFormat::eVorbis and
* @ref SampleFormat::eOpus.
* This will clear the metadata and event points from the sound being decoded
* unless the corresponding flag is used to skip the parsing of those elements.
*/
constexpr DecodeStateFlags fDecodeStateFlagOptimizeSeek = 0x00000002;
/** This flag indicates that frame accurate seeking is not needed and the decoder
* may skip additional work that is required for frame-accurate seeking.
* An example usage of this would be a music player; seeking is required, but
* frame-accurate seeking is not required.
* Additionally, this may be useful in cases where the only seeking needed is
* to seek back to the beginning of the sound, since that can always be done
* with perfect accuracy.
*
* This only affects @ref SampleFormat::eVorbis, @ref SampleFormat::eOpus and
* @ref SampleFormat::eMp3.
* For @ref SampleFormat::eVorbis, @ref SampleFormat::eOpus, this will cause
* the decoder to seek to the start of the page containing the target frame,
* rather than trying to skip through that page to find the exact target frame.
*
* For @ref SampleFormat::eMp3, this flag will skip the generation of an index
* upon opening the file.
* This may result in the file length being reported incorrectly, depending on
* how the file was encoded.
* This will also result in seeking being performed by estimating the target
* frame's location (this will be very inaccurate for variable bitrate files).
*/
constexpr DecodeStateFlags fDecodeStateFlagCoarseSeek = 0x00000004;
/** This flag indicates that the metadata should be ignored when decoding the
* sound. This is intended to be used in cases where the metadata won't be
* used, such as decoding audio for playback.
* Note that this only takes effect when @ref fDecodeStateFlagForceParse is
* used.
*/
constexpr DecodeStateFlags fDecodeStateFlagSkipMetaData = 0x00000008;
/** This flag indicates that the event points should be ignored when decoding the
* sound. This is intended to be used in cases where the event points won't be
* used, such as decoding audio for playback.
* Note that this only takes effect when @ref fDecodeStateFlagForceParse is
* used.
*/
constexpr DecodeStateFlags fDecodeStateFlagSkipEventPoints = 0x00000010;
/** a descriptor of how to create a sound decode state object with createCodecState(). By
* separating this object from the sound data itself, this allows the sound to be trivially
* streamed or decoded to multiple voices simultaneously without having to worry about
* managing access to the sound data or loading it multiple times.
*/
struct DecodeStateDesc
{
/** flags to control the behavior of the decoder. This may be 0 or a
* combination of the kDecodeState* flags.
*/
DecodeStateFlags flags;
/** the sound data object to create the decoder state object for. The size and content
* of the decoder object depends on the type of data contained within this object.
* This may not be nullptr. Note that in some cases, the format and length information
* in this object may be updated by the decoder. This would only occur in cases where
* the data were being streamed from disk. If streaming from memory the cached header
* information will be used instead. If this is used at load time (internally), the
* sound data object will always be modified to cache all the important information about
* the sound's format and length.
*/
SoundData* soundData;
/** the desired output format from the decoder.
* This can be SampleFormat::eDefault to use the format from @p soundData;
* otherwise, this must be one of the SampleFormat::ePcm* formats.
*/
SampleFormat outputFormat;
/** an opaque context value that will be passed to the readCallback and setPosCallback
* functions each time they are called. This value is a caller-specified object that
* is expected to contain the necessary decoding state for a user decoded stream. This
* value is only necessary if the @ref fDataFlagUserDecode flag was used when the
* sound data object was created. By specifying this separately from the sound data,
* this allows multiple voices to be able to play a user decoded stream simultaneously.
* It is up to the caller to provide a unique decode state object here for each playing
* instance of the user decoded stream if there is an expectation of multiple instances.
*/
void* readCallbackContext;
/** reserved for future expansion. This must be set to nullptr. */
void* ext;
};
/** flags to control the behavior of the encoder.
*
* @{
*/
/** base type for the encoder descriptor flags. */
typedef uint64_t EncodeStateFlags;
/** Avoid expanding the target @ref SoundData if it runs out of space. The
* encoder will simply start to fail when the buffer is full if this flag is
* used. Note that for some formats this may cause the last block in the
* stream to be missing if the buffer is not block aligned in size.
*/
constexpr EncodeStateFlags fEncodeStateFlagNoExpandBuffer = 0x00000001;
/** Don't copy the metadata information into the target @ref SoundData.
*/
constexpr EncodeStateFlags fEncodeStateFlagStripMetaData = 0x00000002;
/** Don't copy the event point information into the target @ref SoundData.
*/
constexpr EncodeStateFlags fEncodeStateFlagStripEventPoints = 0x00000004;
/** Don't copy the peaks information into the target @ref SoundData.
*/
constexpr EncodeStateFlags fEncodeStateFlagStripPeaks = 0x00000008;
/** @} */
/** a descriptor for creating an encoder state object. This can encode the data into either a
* stream object or a sound data object. Additional encoder settings depend on the output
* format that is chosen.
*/
struct EncodeStateDesc
{
/** flags to control the behavior of the encoder. At least one of the kEncodeStateTarget*
* flags must be specified.
*/
EncodeStateFlags flags;
/** The SoundData this encoding is associated with, if any.
* The Metadata and event points will be copied from this to the header
* of the encoded data.
* This can be set to nullptr if there is no SoundData associated with this
* encoding.
*/
const SoundData* soundData;
/** The target for the encoder.
* This may not be nullptr.
* Note that the target's format information will be retrieved to
* determine the expected format for the encoder's output. At least for
* the channel count and frame rate, this information must also match that
* of the encoder's input stream. The sample format is the only part of
* the format information that the encoder may change.
* @ref target is treated as if it were empty. Any existing valid
* length will be ignored and the encoder will begin writing at the
* start of the buffer. If the metadata or event points are set to be
* copied, from @ref soundData, then those elements of @ref target will
* be cleared first. Passing @ref fEncodeStateFlagStripMetaData or
* @ref fEncodeStateFlagStripEventPoints will also clear the metadata
* and event points, respectively.
*/
SoundData* target;
/** the expected input format to the encoder. This must be one of the SampleFormat::ePcm*
* formats.
*/
SampleFormat inputFormat;
/** additional output format dependent encoder settings. This should be nullptr for PCM
* data formats. Additional objects will be defined for encoder formats that require
* additional parameters (optional or otherwise). For formats that require additional
* settings, this may not be nullptr. Use getCodecFormatInfo() to retrieve the info
* for the codec to find out if the additional settings are required or not.
*/
void* encoderSettings;
/** reserved for future expansion. This must be set to nullptr. */
void* ext;
};
/** a descriptor for the codec state that should be created. This contains the state information
* descriptors for both the encoder and decoder parts of the codec. Only one part may be valid
* at any given point. The part that is specified will indicate which kind of codec state object
* is created.
*/
struct CodecStateDesc
{
/** the codec part that indicates both which type of state object will be created and which
* part of the descriptor is valid.
*/
CodecPart part;
/** the specific codec state descriptors. */
union
{
DecodeStateDesc decode; ///< filled in when creating a decoder state.
EncodeStateDesc encode; ///< filled in when creating an encoder state.
};
/** reserved for future expansion. This must be set to nullptr. */
void* ext;
};
/** Settings specific to wave file encoding.
* This is not required when encoding wave audio.
* This can optionally be specified when encoding into any PCM format.
*/
struct WaveEncoderSettings
{
/** If this is specified, up to 10 bytes of padding will be added to align
* the data chunk for its data format, so that decoding will be more efficient.
* This is done with a 'JUNK' chunk.
* The data chunk can only be misaligned for @ref SampleFormat::ePcm32 and
* @ref SampleFormat::ePcmFloat.
*/
bool alignDataChunk = true;
};
/** Settings specific to Vorbis file encoding.
* This is not required when encoding Vorbis audio.
*/
struct VorbisEncoderSettings
{
/** Reserved for future expansion.
* Must be set to 0.
*/
uint32_t flags = 0;
/** The encoding quality of the compressed audio.
* This may be within the range of -0.1 to 1.0.
* Vorbis is a lossy codec with variable bitrate, so this doesn't correlate
* to an exact bitrate for the output audio.
* A lower quality increases encode time and decreases decode time.
* 0.8-0.9 is suitable for cases where near-perfect reproduction of the
* original audio is desired, such as music that will be listened to on
* its own.
* Lower quality values for the audio should be acceptable for most use
* cases, but the quality value at which artifacts become obvious will
* depend on the content of the audio, the use case and the quality of the
* speakers used.
* With very low quality settings, such as -0.1, audio artifacts will be
* fairly obvious in music, but for simpler audio, such as voice
* recordings, the quality loss may not be as noticeable (especially in
* scenes with background noise).
* This is 0.9 by default.
*/
float quality = 0.9f;
/** If this is true, the encoder will expect its input to be in Vorbis
* channel order. Otherwise WAVE channel order will be expected.
* All codecs use WAVE channel order by default, so this should be set to
* false in most cases.
* This is false by default.
*/
bool nativeChannelOrder = false;
};
/** The file type used to store FLAC encoded audio. */
enum class FlacFileType
{
/** A .flac container.
* This is the most common container type for FLAC encoded audio.
* This is the default format.
*/
eFlac,
/** A .ogg container.
* This allows FLAC to take advantage of all of the features of the Ogg
* container format.
* FLAC data encoded in Ogg containers will be slightly larger and slower
* to decode than the same data stored in a .flac container.
*/
eOgg,
};
/** Settings specific to FLAC file encoding.
* This is not required when encoding FLAC audio.
*/
struct FlacEncoderSettings
{
/** Reserved for future expansion. */
uint32_t flags = 0;
/** The file container type which will be used.
* The default value is @ref FlacFileType::eFlac.
*/
FlacFileType fileType = FlacFileType::eFlac;
/** The number of bits per sample to store.
* This can be used to truncate the audio to a smaller value, such as 16.
* This must be a value within the range of 4-24. Using values other than
* 8, 12, 16, 20 and 24 requires that @ref streamableSubset is set to
* false.
* Although FLAC supports up to 32 bits per sample, the encoder used
* only supports up to 24 bits per sample.
* The default value for this will be the bit width of the input format,
* except for SampleFormat::ePcm32 and SampleFormat::ePcmFloat, which are
* reduced to 24 bit.
* This can be set to 0 to use the default for the input type.
*/
uint32_t bitsPerSample = 0;
/** Set the compression level preset.
* This must be in the range [0-8], where 8 is the maximum compression level.
* A higher level will have a better compression ratio at the cost of
* compression time.
* The default value is 5.
*/
uint32_t compressionLevel = 5;
/** Set the block size for the encoder to use.
* Set this to 0 to let the encoder choose.
* It is recommended to leave this at 0.
* The default value is 0.
*/
uint32_t blockSize = 0;
/** The FLAC 'streamable subset' is a subset of the FLAC encoding that is
* intended to allow decoders that cannot seek to begin playing from the
* middle of a stream.
* If this is set to true, the codec state creation will fail if the
* following conditions are not met:
* - If the frame rate is above 65536, the frame rate must be divisible
* by 10. (see the FLAC standard for an explanation of this).
* - @ref bitsPerSample must be 8, 12, 16, 20 or 24.
* - Specific restrictions are placed on @ref blockSize.
* Please read the FLAC standard if you need to tune that parameter.
* Setting this to false may improve the compression ratio and decoding
* speed. Testing has shown only slight improvement from setting this
* option to false.
* The default value for this is true.
*/
bool streamableSubset = true;
/** Decode the encoded audio to verify that the encoding was performed
* correctly. The encoding will fail if a chunk does not verify.
* The default value for this is false.
*/
bool verifyOutput = false;
};
/** The intended usage for audio.
* This is used to optimize the Opus encoding for certain applications.
*/
enum class OpusCodecUsage
{
/** General purpose codec usage. Don't optimize for any specific signal type. */
eGeneral,
/** Optimize for the best possible reproduction of music. */
eMusic,
/** Optimize to ensure that speech is as recognizable as possible for a
* given bitrate.
* This should be used for applications such as voice chat, which require
* a low bitrate to be used.
*/
eVoice,
};
/** Encode @ref SampleFormat::eOpus with the maximum possible bitrate. */
const uint32_t kOpusBitrateMax = 512001;
/** Flags to use when encoding audio in @ref SampleFormat::eOpus. */
using OpusEncoderFlags = uint32_t;
/** Optimize the encoder for minimal latency at the cost of quality.
* This will disable the LPC and hybrid modules, which will disable
* voice-optimized modes and forward error correction.
* This also disables some functionality within the MDCT module.
* This reduces the codec lookahead to 2.5ms, rather than the default of 6.5ms.
*/
constexpr OpusEncoderFlags fOpusEncoderFlagLowLatency = 0x00000001;
/** Specify whether the encoder is prevented from producing variable bitrate audio.
* This flag should only be set if there is a specific need for constant bitrate audio.
*/
constexpr OpusEncoderFlags fOpusEncoderFlagConstantBitrate = 0x00000002;
/** This enables a mode in the encoder where silence will only produce
* one frame every 400ms. This is intended for applications such as voice
* chat that will continuously send audio, but long periods of silence
* will be produced.
* This is often referred to as DTX.
*/
constexpr OpusEncoderFlags fOpusEncoderFlagDiscontinuousTransmission = 0x00000004;
/** Disable prediction so that any two blocks of Opus data are (almost
* completely) independent.
* This will reduce audio quality.
* This will disable forward error correction.
* This should only be set if there is a specific need for independent
* frames.
*/
constexpr OpusEncoderFlags fOpusEncoderFlagDisablePrediction = 0x00000008;
/** If this is true, the encoder will expect its input to be in Vorbis
* channel order. Otherwise WAVE channel order will be expected.
* All codecs use WAVE channel order by default, so this should be set to
* false in most cases.
* This is only valid for a stream with 1-8 channels.
*/
constexpr OpusEncoderFlags fOpusEncoderFlagNativeChannelOrder = 0x00000010;
/** Settings specific to @ref SampleFormat::eOpus audio encoding.
* This is not required when encoding Opus audio.
*/
struct OpusEncoderSettings
{
/** The flags to use when encoding.
* These are not necessary to set for general purpose use cases.
*/
OpusEncoderFlags flags = 0;
/** The intended usage of the encoded audio.
* This allows the encoder to optimize for the specific usage.
*/
OpusCodecUsage usage = OpusCodecUsage::eGeneral;
/** The number of frames in the audio stream.
* This can to be set so that the audio stream length isn't increased when
* encoding into Opus.
* Set this to 0 if the encoding stream length is unknown in advance or
* if you don't care about the extra padding.
* Setting this to non-zero when calling @ref IAudioUtils::saveToFile() is
* not allowed.
* Setting this incorrectly will result in padding still appearing at the
* end of the audio stream.
*/
size_t frames = 0;
/** The bitrate to target. Higher bitrates will result in a higher quality.
* This can be from 500 to 512000.
* Use @ref kOpusBitrateMax for the maximum possible quality.
* Setting this to 0 will let the encoder choose.
* If variable bitrate encoding is enabled, this is only a target bitrate.
*/
uint32_t bitrate = 0;
/** The packet size to use for encoding.
* This value is a multiple of 2.5ms that is used for the block size.
* This setting is important to modify when performing latency-sensitive
* tasks, such as voice communication.
* Using a block size less than 10ms disables the LPC and hybrid modules,
* which will disable voice-optimized modes and forward error correction.
* Accepted values are:
* * 1: 2.5ms
* * 2: 5ms
* * 4: 10ms
* * 8: 20ms
* * 16: 40ms
* * 24: 60ms
* * 32: 80ms
* * 48: 120ms
* Setting this to an invalid value will result in 60ms being used.
*/
uint8_t blockSize = 48;
/** Set the estimated packet loss during transmission.
* Setting this to a non-zero value will encode some redundant data to
* enable forward error correction in the decoded stream.
* Forward error correction only takes effect in the LPC and hybrid
* modules, so it's more effective on voice data and will be disabled
* when the LPC and hybrid modes are disabled.
* This is a value from 0-100, where 0 is no packet loss and 100 is heavy
* packet loss.
* Setting this to a higher value will reduce the quality at a given
* bitrate due to the redundant data that has to be included.
* This should be set to 0 when encoding to a file or transmitting over a
* reliable medium.
* @note packet loss compensation is not handled in the decoder yet.
*/
uint8_t packetLoss = 0;
/** Set the computational complexity of the encoder.
* This can be from 0 to 10, with 10 being the maximum complexity.
* More complexity will improve compression, but increase encoding time.
* Set this to -1 for the default.
*/
int8_t complexity = -1;
/** The upper bound on bandwidth to specify for the encoder.
* This only sets the upper bound; the encoder will use lower bandwidths
* as needed.
* Accepted values are:
* * 4: 4KHz - narrow band
* * 6: 6KHz - medium band
* * 8: 8KHz - wide band
* * 12: 12 KHz - superwide band
* * 20: 20 KHz - full band
*/
uint8_t bandwidth = 20;
/** A hint for the encoder on the bit depth of the input audio.
* The maximum bit depth of 24 bits is used if this is set to 0.
* This should only be used in cases where you are sending audio into the
* encoder which was previously encoded from a smaller data type.
* For example, when encoding @ref SampleFormat::ePcmFloat data that was
* previously converted from @ref SampleFormat::ePcm16, this should be
* set to 16.
*/
uint8_t bitDepth = 0;
/** The gain to apply to the output audio.
* Set this to 0 for unity gain.
* This is a fixed point value with 8 fractional bits.
* calculateOpusGain() can be used to calculate this parameter from a
* floating point gain value.
* calculateGainFromLinearScale() can be used if a linear volume scale is
* desired, rather than a gain.
*/
int16_t outputGain = 0;
};
/** capabilities flags for codecs. One or more of these may be set in the codec info block
* to indicate the various features a particular codec may support or require.
*
* @{
*/
/** base type for the codec capabilities flags. */
typedef uint32_t CodecCaps;
/** capabilities flag to indicate that the codec supports encoding to the given format. */
constexpr CodecCaps fCodecCapsSupportsEncode = 0x00000001;
/** capabilities flag to indicate that the codec supports decoding from the given format. */
constexpr CodecCaps fCodecCapsSupportsDecode = 0x00000002;
/** capabilities flag to indicate that the format is compressed data (ie: block oriented or
* otherwise). If this flag is not set, the format is a PCM variant (ie: one of the
* SampleFormat::ePcm* formats).
*/
constexpr CodecCaps fCodecCapsCompressed = 0x00000004;
/** capabilities flag to indicate that the codec supports the use of additional parameters
* through the @a encoderSettings value in the encoder state descriptor object. If this
* flag is not set, there are no additional parameters defined for the format.
*/
constexpr CodecCaps fCodecCapsSupportsAdditionalParameters = 0x00000008;
/** capabilities flag to indicate that the codec requires the use of additional parameters
* through the @a encoderSettings value in the encoder state descriptor object. If this
* flag is not set, the additional parameters are optional and the codec is able to choose
* appropriate default.
*/
constexpr CodecCaps fCodecCapsRequiresAdditionalParameters = 0x00000010;
/** capabilities flag to indicate that the codec supports setting the position within the
* stream. If this flag is not set, calls to setCodecPosition() will fail when using
* the codec.
*/
constexpr CodecCaps fCodecCapsSupportsSetPosition = 0x00000020;
/** capabilities flag to indicate that the codec can calculate and set a frame accurate
* position. If this flag is not set, the codec can only handle setting block aligned
* positions. Note that this flag will never be set if @ref fCodecCapsSupportsSetPosition
* is not also set.
*/
constexpr CodecCaps fCodecCapsHasFrameAccuratePosition = 0x00000040;
/** capabilities flag to indicate that the codec can calculate a frame accurate count of
* remaining data. If this flag is not set, the codec can only handle calculating block
* aligned estimates.
*/
constexpr CodecCaps fCodecCapsHasAccurateAvailableValue = 0x00000080;
/** @} */
/** information about a codec for a single sample format. This includes information that is both
* suitable for display and that can be used to determine if it is safe or possible to perform a
* certain conversion operation.
*/
struct CodecInfo
{
/** the encoded sample format that this codec information describes. */
SampleFormat encodedFormat;
/** the PCM sample format that the decoder prefers to decode to and the encoder prefers to encode from. */
SampleFormat preferredFormat;
/** the friendly name of this codec. */
char name[256];
/** the library, system service, or author that provides the functionality of this codec. */
char provider[256];
/** the owner and developer information for this codec. */
char copyright[256];
/** capabilities flags for this codec. */
CodecCaps capabilities;
/** minimum block size in frames supported by this codec. */
size_t minBlockSize;
/** maximum block size in frames supported by this codec. */
size_t maxBlockSize;
/** the minimum number of channels per frame supported by this codec. */
size_t minChannels;
/** the maximum number of channels per frame supported by this codec. */
size_t maxChannels;
};
/*********************************** Metadata Definitions ***********************************/
/** These are the metadata tags that can be written to RIFF (.wav) files.
* Some of these tags were intended to be used on Video or Image data, rather
* than audio data, but all of these are still technically valid to use in
* .wav files.
* These are not case sensitive.
* @{
*/
constexpr char kMetaDataTagArchivalLocation[] = "Archival Location"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagCommissioned[] = "Commissioned"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagCropped[] = "Cropped"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagDimensions[] = "Dimensions"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagDisc[] = "Disc"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagDpi[] = "Dots Per Inch"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagEditor[] = "Editor"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagEngineer[] = "Engineer"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagKeywords[] = "Keywords"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagLanguage[] = "Language"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagLightness[] = "Lightness"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagMedium[] = "Medium"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagPaletteSetting[] = "Palette Setting"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagSubject[] = "Subject"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagSourceForm[] = "Source Form"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagSharpness[] = "Sharpness"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagTechnician[] = "Technician"; /**< Standard RIFF metadata tag. */
constexpr char kMetaDataTagWriter[] = "Writer"; /**< Standard RIFF metadata tag. */
/** These are the metadata tags that can be written to RIFF (.wav) files and
* also have specified usage under the Vorbis Comment metadata format standard
* (used by .ogg and .flac).
* Vorbis Comment supports any metadata tag name, but these ones should be
* preferred as they have a standardized usage.
* @{
*/
constexpr char kMetaDataTagAlbum[] = "Album"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagArtist[] = "Artist"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagCopyright[] = "Copyright"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagCreationDate[] = "Date"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagDescription[] = "Description"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagGenre[] = "Genre"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagOrganization[] = "Organization"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagTitle[] = "Title"; /**< Standard Vorbis metadata tag. */
constexpr char kMetaDataTagTrackNumber[] = "TrackNumber"; /**< Standard Vorbis metadata tag. */
/** If a SoundData is being encoded with metadata present, this tag will
* automatically be added, with the value being the encoder software used.
* Some file formats, such as Ogg Vorbis, require a metadata section and
* the encoder will automatically add this tag.
* Under the Vorbis Comment metadata format, the 'Encoder' tag represents the
* vendor string.
*/
constexpr char kMetaDataTagEncoder[] = "Encoder";
/** This tag unfortunately has a different meaning in the two formats.
* In RIFF metadata tags, this is the 'Source' of the audio.
* In Vorbis Comment metadata tags, this is the International Standard
* Recording Code track number.
*/
constexpr char kMetaDataTagISRC[] = "ISRC";
/** @} */
/** @} */
/** These are metadata tags specified usage under the Vorbis Comment
* metadata format standard (used by .ogg and .flac), but are not supported
* on RIFF (.wav) files.
* Vorbis Comment supports any metadata tag name, but these ones should be
* preferred as they have a standardized usage.
* These are not case sensitive.
* @{
*/
constexpr char kMetaDataTagLicense[] = "License"; /**< Standard metadata tag. */
constexpr char kMetaDataTagPerformer[] = "Performer"; /**< Standard metadata tag. */
constexpr char kMetaDataTagVersion[] = "Version"; /**< Standard metadata tag. */
constexpr char kMetaDataTagLocation[] = "Location"; /**< Standard metadata tag. */
constexpr char kMetaDataTagContact[] = "Contact"; /**< Standard metadata tag. */
/** @} */
/** These are metadata tags specified as part of the ID3v1 comment format (used
* by some .mp3 files).
* These are not supported on RIFF (.wav) files.
* @{
*/
/** This is a generic comment field in the ID3v1 tag. */
constexpr char kMetaDataTagComment[] = "Comment";
/** Speed or tempo of the music.
* This is specified in the ID3v1 extended data tag.
*/
constexpr char kMetaDataTagSpeed[] = "Speed";
/** Start time of the music.
* The ID3v1 extended data tag specifies this as "mmm:ss"
*/
constexpr char kMetaDataTagStartTime[] = "StartTime";
/** End time of the music.
* The ID3v1 extended data tag specifies this as "mmm:ss"
*/
constexpr char kMetaDataTagEndTime[] = "EndTime";
/** This is part of the ID3v1.2 tag. */
constexpr char kMetaDataTagSubGenre[] = "SubGenre";
/** @} */
/** These are extra metadata tags that are available with the ID3v2 metadata
* tag (used by some .mp3 files).
* These are not supported on RIFF (.wav) files.
* @{
*/
/** Beats per minute. */
constexpr char kMetaDataTagBpm[] = "BPM";
/** Delay between songs in a playlist in milliseconds. */
constexpr char kMetaDataTagPlaylistDelay[] = "PlaylistDelay";
/** The original file name for this file.
* This may be used if the file name had to be truncated or otherwise changed.
*/
constexpr char kMetaDataTagFileName[] = "FileName";
constexpr char kMetaDataTagOriginalAlbum[] = "OriginalTitle"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagOriginalWriter[] = "OriginalWriter"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagOriginalPerformer[] = "OriginalPerformer"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagOriginalYear[] = "OriginalYear"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagPublisher[] = "Publisher"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagRecordingDate[] = "RecordingDate"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagInternetRadioStationName[] = "InternetRadioStationName"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagInternetRadioStationOwner[] = "InternetRadioStationOwner"; /**< Standard ID3v2 metadata tag.
*/
constexpr char kMetaDataTagInternetRadioStationUrl[] = "InternetRadioStationUrl"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagPaymentUrl[] = "PaymentUrl"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagInternetCommercialInformationUrl[] = "CommercialInformationUrl"; /**< Standard ID3v2 metadata
tag. */
constexpr char kMetaDataTagInternetCopyrightUrl[] = "CopyrightUrl"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagWebsite[] = "Website"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagInternetArtistWebsite[] = "ArtistWebsite"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagAudioSourceWebsite[] = "AudioSourceWebsite"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagComposer[] = "Composer"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagOwner[] = "Owner"; /**< Standard ID3v2 metadata tag. */
constexpr char kMetaDataTagTermsOfUse[] = "TermsOfUse"; /**< Standard ID3v2 metadata tag. */
/** The musical key that the audio starts with */
constexpr char kMetaDataTagInitialKey[] = "InitialKey";
/** @} */
/** This is a magic value that can be passed to setMetaData() to remove all
* tags from the metadata table for that sound.
*/
constexpr const char* const kMetaDataTagClearAllTags = nullptr;
/** used to retrieve the peak volume information for a sound data object. This contains one
* volume level per channel in the stream and the frame in the stream at which the peak
* occurs.
*/
struct PeakVolumes
{
/** the number of channels with valid peak data in the arrays below. */
size_t channels;
/** the frame that each peak volume level occurs at for each channel. This will be the
* first frame this peak volume level occurs at if it is reached multiple times in the
* stream.
*/
size_t frame[kMaxChannels];
/** the peak volume level that is reached for each channel in the stream. This will be
* in the range [0.0, 1.0]. This information can be used to normalize the volume level
* for a sound.
*/
float peak[kMaxChannels];
/** the frame that the overall peak volume occurs at in the sound. */
size_t peakFrame;
/** the peak volume among all channels of data. This is simply the maximum value found in
* the @ref peak table.
*/
float peakVolume;
};
/** base type for an event point identifier. */
typedef uint32_t EventPointId;
/** an invalid frame offset for an event point. This value should be set if an event point is
* to be removed from a sound data object.
*/
constexpr size_t kEventPointInvalidFrame = ~0ull;
/** This indicates that an event point should loop infinitely.
*/
constexpr size_t kEventPointLoopInfinite = SIZE_MAX;
/** a event point parsed from a data file. This contains the ID of the event point, its name
* label (optional), and the frame in the stream at which it should occur.
*/
struct EventPoint
{
/** the ID of the event point. This is used to identify it in the file information but is
* not used internally except to match up labels or loop points to the event point.
*/
EventPointId id;
/** the frame that the event point occurs at. This is relative to the start of the stream
* for the sound. When updating event points with setEventPoints(), this can be set
* to @ref kEventPointInvalidFrame to indicate that the event point with the ID @ref id
* should be removed from the sound data object. Otherwise, this frame index must be within
* the bounds of the sound data object's stream.
*/
size_t frame;
/** the user-friendly label given to this event point. This may be parsed from a different
* information chunk in the file and will be matched up later based on the event point ID.
* This value is optional and may be nullptr.
*/
const char* label = nullptr;
/** optional text associated with this event point. This may be additional information
* related to the event point's position in the stream such as closed captioning text
* or a message of some sort. It is the host app's responsibility to interpret and use
* this text appropriately. This text will always be UTF-8 encoded.
*/
const char* text = nullptr;
/** Length of the segment of audio referred to by this event point.
* If @ref length is non-zero, then @ref length is the number of frames
* after @ref frame that this event point refers to.
* If @ref length is zero, then this event point refers to the segment
* from @ref frame to the end of the sound.
* If @ref loopCount is non-zero, then the region specified will refer to
* a looping region.
* If @ref playIndex is non-zero, then the region can additionally specify
* the length of audio to play.
*/
size_t length = 0;
/** Number of times this section of audio in the playlist should be played.
* The region of audio to play in a loop is specified by @ref length.
* if @ref loopCount is 0, then this is a non-looping segment.
* If @ref loopCount is set to @ref kEventPointLoopInfinite, this
* specifies that this region should be looped infinitely.
*/
size_t loopCount = 0;
/** An optional method to specify an ordering for the event points or a
* subset of event points.
* A value of 0 indicates that there is no intended ordering for this
* event point.
* The playlist indexes will always be a contiguous range starting from 1.
* If a user attempts to set a non-contiguous range of event point
* playlist indexes on a SoundData, the event point system will correct
* this and make the range contiguous.
*/
size_t playIndex = 0;
/** user data object attached to this event point. This can have an optional destructor
* to clean up the user data object when the event point is removed, the user data object
* is replaced with a new one, or the sound data object containing the event point is
* destroyed. Note that when the user data pointer is replaced with a new one, it is the
* caller's responsibility to ensure that an appropriate destructor is always paired with
* it.
*/
UserData userData = {};
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** special value for setEventPoints() to indicate that the event point table should be
* cleared instead of adding or removing individual event points.
*/
constexpr EventPoint* const kEventPointTableClear = nullptr;
/******************************** Sound Data Management Interface ********************************/
/** interface to manage audio data in general. This includes loading audio data from multiple
* sources (ie: file, memory, raw data, user-decoded, etc), writing audio data to file, streaming
* audio data to file, decoding audio data to PCM, and changing its sample format. All audio
* data management should go through this interface.
*
* See these pages for more detail:
* @rst
* :ref:`carbonite-audio-label`
* :ref:`carbonite-audio-data-label`
@endrst
*/
struct IAudioData
{
CARB_PLUGIN_INTERFACE("carb::audio::IAudioData", 1, 0)
/*************************** Sound Data Creation and Management ******************************/
/** creates a new sound data object.
*
* @param[in] desc a descriptor of how and from where the audio data should be loaded.
* This may not be nullptr.
* @returns the newly created sound data object if it was successfully loaded or parsed.
* When this object is no longer needed, it must be freed with release().
* @returns nullptr if the sound data could not be successfully loaded.
*
* @remarks This creates a new sound data object from a requested data source. This single
* creation point manages the loading of all types of sound data from all sources.
* Depending on the flags used, the loaded sound data may or may not be decoded
* into PCM data.
*/
SoundData*(CARB_ABI* createData)(const SoundDataLoadDesc* desc);
/** acquires a new reference to a sound data object.
*
* @param[in] sound the sound data object to take a reference to. This may not be
* nullptr.
* @returns the sound data object with an additional reference taken on it. This new
* reference must later be released with release().
*
* @remarks This grabs a new reference to a sound data object. Each reference that is
* taken must be released at some point when it is no longer needed. Note that
* the createData() function returns the new sound data object with a single
* reference on it. This final reference must also be released at some point to
* destroy the object.
*/
SoundData*(CARB_ABI* acquire)(SoundData* sound);
/** releases a reference to a sound data object.
*
* @param[in] sound the sound data object to release a reference on. This may not be
* nullptr.
* @returns the new reference count for the sound data object.
* @returns 0 if the sound data object was destroyed (ie: all references were released).
*
* @remarks This releases a single reference to sound data object. If all references have
* been released, the object will be destroyed. Each call to grab a new reference
* with acquire() must be balanced by a call to release that reference. The
* object's final reference that came from createData() must also be released
* in order to destroy it.
*/
size_t(CARB_ABI* release)(SoundData* sound);
/*************************** Sound Data Information Accessors ********************************/
/** retrieves the creation time flags for a sound data object.
*
* @param[in] sound the sound data object to retrieve the creation time flags for.
* @returns the flags that were used when creating the sound object. Note that if the sound
* data object was duplicated through a conversion operation, the data format flags
* may no longer be accurate.
* @returns 0 if @p sound is nullptr.
*/
DataFlags(CARB_ABI* getFlags)(const SoundData* sound);
/** retrieves the name of the file this object was loaded from (if any).
*
* @param[in] sound the sound data object to retrieve the filename for.
* @returns the original filename if the object was loaded from a file.
* @returns nullptr if the object does not have a name.
* @returns nullptr @p sound is nullptr.
*/
const char*(CARB_ABI* getName)(const SoundData* sound);
/** retrieves the length of a sound data object's buffer.
*
* @param[in] sound the sound to retrieve the buffer length for. This may not be nullptr.
* @param[in] units the units to retrieve the buffer length in. Note that if the buffer
* length in milliseconds is requested, the length may not be precise.
* @returns the length of the sound data object's buffer in the requested units.
*
* @remarks This retrieves the length of a sound data object's buffer in the requested units.
* The length of the buffer represents the total amount of audio data that is
* represented by the object. Note that if this object was created to stream data
* from file or the data is stored still encoded or compressed, this will not
* reflect the amount of memory actually used by the object. Only non-streaming
* PCM formats will be able to convert their length into an amount of memory used.
*/
size_t(CARB_ABI* getLength)(const SoundData* sound, UnitType units);
/** sets the current 'valid' size of an empty buffer.
*
* @param[in] sound the sound data object to set the new valid length for. This may
* not be nullptr.
* @param[in] length the new length of valid data in the units specified by @p units.
* This valid data length may not be specified in time units (ie:
* @ref UnitType::eMilliseconds or @ref UnitType::eMicroseconds)
* since it would not be an exact amount and would be likely to
* corrupt the end of the stream. This length must be less than or
equal to the creation time length of the buffer.
* @param[in] units the units to interpret @p length in. This must be in frames or
* bytes.
* @returns true if the new valid data length is successfully updated.
* @returns false if the new length value was out of range of the buffer size or the
* sound data object was not created as empty.
*
* @remarks This sets the current amount of data in the sound data object buffer that is
* considered 'valid' by the caller. This should only be used on sound data objects
* that were created with the @ref fDataFlagEmpty flag. If the host app decides
* to write data to the empty buffer, it must also set the amount of valid data
* in the buffer before that new data can be decoded successfully. When the
* object's encoded format is not a PCM format, it is the caller's responsibility
* to set both the valid byte and valid frame count since that may not be able
* to be calculated without creating a decoder state for the sound. When the
* object's encoded format is a PCM format, both the frames and byte counts
* will be updated in a single call regardless of which one is specified.
*/
bool(CARB_ABI* setValidLength)(SoundData* sound, size_t length, UnitType units);
/** retrieves the current 'valid' size of an empty buffer.
*
* @param[in] sound the sound data object to retrieve the valid data length for. This
* may not be nullptr.
* @param[in] units the units to retrieve the current valid data length in. Note that
* if a time unit is requested, the returned length may not be accurate.
* @returns the valid data length for the object in the specified units.
* @returns 0 if the buffer does not have any valid data.
*
* @remarks This retrieves the current valid data length for a sound data object. For sound
* data objects that were created without the @ref fDataFlagEmpty flag, this will be
* the same as the value returned from getLength(). For an object that was created
* as empty, this will be the length that was last on the object with a call to
* setValidLength().
*/
size_t(CARB_ABI* getValidLength)(const SoundData* sound, UnitType units);
/** retrieves the data buffer for a sound data object.
*
* @param[in] sound the sound to retrieve the data buffer for. This may not be nullptr.
* @returns the data buffer for the sound data object.
* @returns nullptr if @p sound does not have a writable buffer.
* This can occur for sounds created with @ref fDataFlagUserMemory.
* In that case, the caller either already has the buffer address
* (ie: shared the memory block to save on memory or memory copy
* operations), or the memory exists in a location that should
* not be modified (ie: a sound bank or sound atlas).
* @returns nullptr if the @p sound object is invalid.
* @returns nullptr if @p sound is streaming from disk, since a sound
* streaming from disk will not have a buffer.
*
* @remarks This retrieves the data buffer for a sound data object.
* This is intended for cases such as empty sounds where data
* needs to be written into the buffer of @p sound.
* getReadBuffer() should be used for cases where writing to the
* buffer is not necessary, since not all sound will have a
* writable buffer.
* In-memory streaming sounds without @ref fDataFlagUserMemory
* will return a buffer here; that buffer contains the full
* in-memory file, so writing to it will most likely corrupt the
* sound.
*/
void*(CARB_ABI* getBuffer)(const SoundData* sound);
/** Retrieves the read-only data buffer for a sound data object.
*
* @param[in] sound the sound to retrieve the data buffer for. This may not be nullptr.
* @returns the data buffer for the sound data object.
* @returns nullptr if the @p sound object is invalid.
* @returns nullptr if @p sound is streaming from disk, since a sound
* streaming from disk will not have a buffer.
*
* @remarks This retrieves the data buffer for a sound data object.
* Any decoded @ref SoundData will return a buffer of raw PCM
* data that can be directly played.
* getValidLength() should be used to determine the length of a
* decoded buffer.
* Any in-memory streaming @ref SoundData will also return the
* raw file blob; this needs to be decoded before it can be
* played.
*/
const void*(CARB_ABI* getReadBuffer)(const SoundData* sound);
/** retrieves the amount of memory used by a sound data object.
*
* @param[in] sound the sound data object to retrieve the memory usage for.
* @returns the total number of bytes used to store the sound data object.
* @returns 0 if @p sound is nullptr.
*
* @remarks This retrieves the amount of memory used by a single sound data object. This
* will include all memory required to store the audio data itself, to store the
* object and all its parameters, and the original filename (if any). This
* information is useful for profiling purposes to investigate how much memory
* the audio system is using for a particular scene.
*/
size_t(CARB_ABI* getMemoryUsed)(const SoundData* sound);
/** Retrieves the format information for a sound data object.
*
* @param[in] sound The sound data object to retrieve the format information for. This
* may not be nullptr.
* @param[in] type The type of format information to retrieve.
* For sounds that were decoded on load, this
* parameter doesn't have any effect, so it can be
* set to either value.
* For streaming sounds, @ref CodecPart::eDecoder will
* cause the returned format to be the format that the
* audio will be decoded into (e.g. when decoding Vorbis
* to float PCM, this will return @ref SampleFormat::ePcmFloat).
* For streaming sounds, @ref CodecPart::eEncoder will
* cause the returned format to be the format that the
* audio is being decoded from (e.g. when decoding Vorbis
* to float PCM, this will return @ref SampleFormat::eVorbis).
* In short, when you are working with decoded audio data,
* you should be using @ref CodecPart::eDecoder; when you
* are displaying audio file properties to a user, you
* should be using @ref CodecPart::eEncoder.
* @param[out] format Receives the format information for the sound data object. This
* format information will remain constant for the lifetime of the
* sound data object.
* @returns No return value.
*
* @remarks This retrieves the format information for a sound data object. The format
* information will remain constant for the object's lifetime so it can be
* safely cached once retrieved. Note that the encoded format information may
* not be sufficient to do all calculations on sound data of non-PCM formats.
*/
void(CARB_ABI* getFormat)(const SoundData* sound, CodecPart type, SoundFormat* format);
/** retrieves or calculates the peak volume levels for a sound if possible.
*
* @param[in] sound the sound data object to retrieve the peak information for. This may
* not be nullptr.
* @param[out] peaks receives the peak volume information for the sound data object
* @p sound. Note that only the entries corresponding to the number
* of channels in the sound data object will be written. The contents
* of the remaining channels is undefined.
* @returns true if the peak volume levels are available or could be calculated.
* @returns false if the peak volume levels were not calculated or loaded when the
* sound was created.
*
* @remarks This retrieves the peak volume level information for a sound. This information
* is either loaded from the sound's original source file or is calculated if
* the sound is decoded into memory at load time. This information will not be
* calculated if the sound is streamed from disk or memory.
*/
bool(CARB_ABI* getPeakLevel)(const SoundData* sound, PeakVolumes* peaks);
/** retrieves embedded event point information from a sound data object.
*
* @param[in] sound the sound data object to retrieve the event point information
* from. This may not be nullptr.
* @param[out] events receives the event point information. This may be nullptr if
* only the number of event points is required.
* @param[in] maxEvents the maximum number of event points that will fit in the @p events
* buffer. This must be 0 if @p events is nullptr.
* @returns the number of event points written to the buffer @p events if it was not nullptr.
* @returns if the buffer is not large enough to store all the event points, the maximum
* number that will fit is written to the buffer and the total number of event
* points is returned. This case can be detected by checking if the return value
* is larger than @p maxEvents.
* @returns the number of event points contained in the sound object if the buffer is
* nullptr.
*
* @remarks This retrieves event point information that was embedded in the sound file that
* was used to create a sound data object. The event points are optional in the
* data file and may not be present. If they are parsed from the file, they will
* also be saved out to any destination file that the same sound data object is
* written to, provided the destination format supports embedded event point
* information.
*/
size_t(CARB_ABI* getEventPoints)(const SoundData* sound, EventPoint* events, size_t maxEvents);
/** retrieves a single event point object by its identifier.
*
* @param[in] sound the sound data object to retrieve the named event point from. This
* may not be nullptr.
* @param[in] id the identifier of the event point to be retrieved.
* @returns the information for the event point with the requested identifier if found.
* The returned object is only valid until the event point list for the sound is
* modified. This should not be stored for extended periods since its contents
* may be invalidated at any time.
* @returns nullptr if no event point with the requested identifier is found.
*
* @note Access to this event point information is not thread safe. It is the caller's
* responsibility to ensure access to the event points on a sound data object is
* appropriately locked.
*/
const EventPoint*(CARB_ABI* getEventPointById)(const SoundData* sound, EventPointId id);
/** retrieves a single event point object by its index.
*
* @param[in] sound the sound data object to retrieve the event point from. This may not
* be nullptr.
* @param[in] index the zero based index of the event point to retrieve.
* @returns the information for the event point at the requested index. The returned object
* is only valid until the event point list for the sound is modified. This should
* not be stored for extended periods since its contents may be invalidated at any
* time.
* @returns nullptr if the requested index is out of range of the number of event points in
* the sound.
*
* @note Access to this event point information is not thread safe. It is the caller's
* responsibility to ensure access to the event points on a sound data object is
* appropriately locked.
*/
const EventPoint*(CARB_ABI* getEventPointByIndex)(const SoundData* sound, size_t index);
/** retrieves a single event point object by its playlist index.
*
* @param[in] sound The sound data object to retrieve the event
* point from. This may not be nullptr.
* @param[in] playIndex The playlist index of the event point to retrieve.
* Playlist indexes may range from 1 to SIZE_MAX.
* 0 is not a valid playlist index.
* This function is intended to be called in a loop
* with values of @p playIndex between 1 and the
* return value of getEventPointMaxPlayIndex().
* The range of valid event points will always be
* contiguous, so nullptr should not be returned
* within this range.
*
* @returns the information for the event point at the requested playlist
* index. The returned object is only valid until the event
* point list for the sound is modified. This should not be
* stored for extended periods since its contents may be
* invalidated at any time.
* @returns nullptr if @p playIndex is 0.
* @returns nullptr if no event point has a playlist index of @p playIndex.
*
* @note Access to this event point information is not thread safe. It is
* the caller's responsibility to ensure access to the event points
* on a sound data object is appropriately locked.
*/
const EventPoint*(CARB_ABI* getEventPointByPlayIndex)(const SoundData* sound, size_t playIndex);
/** Retrieve the maximum play index value for the sound.
*
* @param[in] sound The sound data object to retrieve the event
* point index from. This may not be nullptr.
*
* @returns This returns the max play index for this sound.
* This will be 0 if no event points have a play index.
* This is also the number of event points with playlist indexes,
* since the playlist index range is contiguous.
*/
size_t(CARB_ABI* getEventPointMaxPlayIndex)(const SoundData* sound);
/** modifies, adds, or removes event points in a sound data object.
*
* @param[inout] sound the sound data object to update the event point(s) in. This may
* not be nullptr.
* @param[in] eventPoints the event point(s) to be modified or added. The operation that is
* performed for each event point in the table depends on whether
* an event point with the same ID already exists in the sound data
* object. The event points in this table do not need to be sorted
* in any order. This may be @ref kEventPointTableClear to indicate
* that all event points should be removed.
* @param[in] count the total number of event points in the @p eventPoint table. This
* must be 0 if @p eventPoints is nullptr.
* @returns true if all of the event points in the table are updated successfully.
* @returns false if not all event points could be updated. This includes a failure to
* allocate memory or an event point with an invalid frame offset. Note that this
* failing doesn't mean that all the event points failed. This just means that at
* least failed to be set properly. The new set of event points may be retrieved
* and compared to the list set here to determine which one failed to be updated.
*
* @remarks This modifies, adds, or removes one or more event points in a sound data object.
* An event point will be modified if one with the same ID already exists. A new
* event point will be added if it has an ID that is not already present in the
* sound data object and its frame offset is valid. An event point will be removed
* if it has an ID that is present in the sound data object but the frame offset for
* it is set to @ref kEventPointInvalidFrame. Any other event points with invalid
* frame offsets (ie: out of the bounds of the stream) will be skipped and cause the
* function to fail.
*
* @note When adding a new event point or changing a string in an event point, the strings
* will always be copied internally instead of referencing the caller's original
* buffer. The caller can therefore clean up its string buffers immediately upon
* return. The user data object (if any) however must persist since it will be
* referenced instead of copied. If the user data object needs to be cleaned up,
* an appropriate destructor function for it must also be provided.
*
* @note If an event point is modified or removed such that the playlist
* indexes of the event points are no longer contiguous, this function
* will adjust the play indexes of all event points to prevent any
* gaps.
*
* @note The playIndex fields on @p eventPoints must be within the region
* of [0, @p count + getEventPoints(@p sound, nullptr, 0)].
* Trying to set playlist indexes outside this range is an error.
*/
bool(CARB_ABI* setEventPoints)(SoundData* sound, const EventPoint* eventPoints, size_t count);
/** retrieves the maximum simultaneously playing instance count for a sound.
*
* @param[in] sound the sound to retrieve the maximum instance count for. This may not
* be nullptr.
* @returns the maximum instance count for the sound if it is limited.
* @retval kInstancesUnlimited if the instance count is unlimited.
*
* @remarks This retrieves the current maximum instance count for a sound. This limit is
* used to prevent too many instances of a sound from being played simultaneously.
* With the limit set to unlimited, playing too many instances can result in serious
* performance penalties and serious clipping artifacts caused by too much
* constructive interference.
*/
uint32_t(CARB_ABI* getMaxInstances)(const SoundData* sound);
/** sets the maximum simultaneously playing instance count for a sound.
*
* @param[in] sound the sound to change the maximum instance count for. This may not be
* nullptr.
* @param[in] limit the new maximum instance limit for the sound. This may be
* @ref kInstancesUnlimited to remove the limit entirely.
* @returns no return value.
*
* @remarks This sets the new maximum playing instance count for a sound. This limit will
* prevent the sound from being played until another instance of it finishes playing
* or simply cause the play request to be ignored completely. This should be used
* to limit the use of frequently played sounds so that they do not cause too much
* of a processing burden in a scene or cause too much constructive interference
* that could lead to clipping artifacts. This is especially useful for short
* sounds that are played often (ie: gun shots, foot steps, etc). At some [small]
* number of instances, most users will not be able to tell if a new copy of the
* sound played or not.
*/
void(CARB_ABI* setMaxInstances)(SoundData* sound, uint32_t limit);
/** retrieves the user data pointer for a sound data object.
*
* @param[in] sound the sound data object to retrieve the user data pointer for. This may
* not be nullptr.
* @returns the stored user data pointer.
* @returns nullptr if no user data has been set on the requested sound.
*
* @remarks This retrieves the user data pointer for the requested sound data object. This
* is used to associate any arbitrary data with a sound data object. It is the
* caller's responsibility to ensure access to data is done in a thread safe
* manner.
*/
void*(CARB_ABI* getUserData)(const SoundData* sound);
/** sets the user data pointer for a sound data object.
*
* @param[in] sound the sound data object to set the user data pointer for. This may
* not be nullptr.
* @param[in] userData the new user data pointer to set. This may include an optional
* destructor if the user data object needs to be cleaned up. This
* may be nullptr to indicate that the user data pointer should be
* cleared out.
* @returns no return value.
*
* @remarks This sets the user data pointer for this sound data object. This is used to
* associate any arbitrary data with a sound data object. It is the caller's
* responsibility to ensure access to this table is done in a thread safe manner.
*
* @note The user data object must not hold a reference to the sound data object that it is
* attached to. Doing so will cause a cyclical reference and prevent the sound data
* object itself from being destroyed.
*
* @note The sound data object that this user data object is attached to must not be accessed
* from the destructor. If the sound data object is being destroyed when the user data
* object's destructor is being called, its contents will be undefined.
*/
void(CARB_ABI* setUserData)(SoundData* sound, const UserData* userData);
/************************************ Sound Data Codec ***************************************/
/** retrieves information about a supported codec.
*
* @param[in] encodedFormat the encoded format to retrieve the codec information for.
* This may not be @ref SampleFormat::eDefault or
* @ref SampleFormat::eRaw. This is the format that the codec
* either decodes from or encodes to.
* @param[in] pcmFormat the PCM format for the codec that the information would be
* retrieved for. This may be @ref SampleFormat::eDefault to
* retrieve the information for the codec for the requested
* encoded format that decodes to the preferred PCM format.
* This may not be @ref SampleFormat::eRaw.
* @returns the info block for the codec that can handle the requested operation if found.
* @returns nullptr if no matching codec for @p encodedFormat and @p pcmFormat could be
* found.
*
* @remarks This retrieves the information about a single codec. This can be used to check
* if an encoding or decoding operation to or from a requested format pair is
* possible and to retrieve some information suitable for display or UI use for the
* format.
*/
const CodecInfo*(CARB_ABI* getCodecFormatInfo)(SampleFormat encodedFormat, SampleFormat pcmFormat);
/** creates a new decoder or encoder state for a sound data object.
*
* @param[in] desc a descriptor of the decoding or encoding operation that will be
* performed. This may not be nullptr.
* @returns the new state object if the operation is valid and the state was successfully
* initialized. This must be destroyed with destroyCodecState() when it is
* no longer needed.
* @returns nullptr if the operation is not valid or the state could not be created or
* initialized.
*
* @remarks This creates a new decoder or encoder state instance for a sound object. This
* will encapsulate all the information needed to perform the operation on the
* stream as efficiently as possible. Note that the output format of the decoder
* will always be a PCM variant (ie: one of the SampleFormat::ePcm* formats).
* Similarly, the input of the encoder will always be a PCM variant. The input
* of the decoder and output of the encoder may be any format.
*
* @remarks The decoder will treat the sound data object as a stream and will decode it
* in chunks from start to end. The decoder's read cursor will initially be placed
* at the start of the stream. The current read cursor can be changed at any time
* by calling setCodecPosition(). Some compressed or block based formats may
* adjust the new requested position to the start of the nearest block.
*
* @remarks The state is separated from the sound data object so that multiple playing
* instances of each sound data object may be decoded and played simultaneously
* regardless of the sample format or decoder used. Similarly, when encoding
* this prevents any limitation on the number of targets a sound could be streamed
* or written to.
*
* @remarks The encoder state is used to manage the encoding of a single stream of data to
* a single target. An encoder will always be able to be created for an operation
* where the source and destination formats match. For formats that do not support
* encoding, this will fail. More info about each encoder format can be queried
* with getCodecFormatInfo().
*
* @remarks The stream being encoded is expected to have the same number of channels as the
* chosen output target.
*/
CodecState*(CARB_ABI* createCodecState)(const CodecStateDesc* desc);
/** destroys a codec state object.
*
* @param[in] state the codec state to destroy. This call will be ignored if this is
* nullptr.
* @returns no return value.
*
* @remarks This destroys a decoder or encoder state object that was previously returned
* from createCodecState(). For a decoder state, any partially decoded data stored
* in the state object will be lost. For an encoder state, all pending data will
* be written to the output target (padded with silence if needed). If the encoder
* was targeting an output stream, the stream will not be closed. If the encoder
* was targeting a sound data object, the stream size information will be updated.
* The buffer will not be trimmed in size if it is longer than the actual stream.
*/
void(CARB_ABI* destroyCodecState)(CodecState* decodeState);
/** decodes a number of frames of data into a PCM format.
*
* @param[in] decodeState the decoder state to use for the decoding operation. This may
* not be nullptr.
* @param[out] buffer receives the decoded PCM data. This buffer must be at least
* large enough to hold @p framesToDecode frames of data in the
* sound data object's stream. This may not be nullptr.
* @param[in] framesToDecode the requested number of frames to decode. This is taken as a
* suggestion. Up to this many frames will be decoded if it is
* available in the stream. If the stream ends before this
* number of frames is read, the remainder of the buffer will be
* left unmodified.
* @param[out] framesDecoded receives the number of frames that were actually decoded into
* the output buffer. This will never be larger than the
* @p framesToDecode value. This may not be nullptr.
* @returns @p buffer if the decode operation is successful and the decoded data was copied
* into the output buffer.
* @returns a non-nullptr value if the sound data object already contains PCM data in the
* requested decoded format.
* @returns nullptr if the decode operation failed for any reason.
* @returns nullptr if @p framesToDecode is 0.
*
* @remarks This decodes a requested number of frames of data into an output buffer. The
* data will always be decoded into a PCM format specified by the decoder when the
* sound data object is first created. If the sound data object already contains
* PCM data in the requested format, nothing will be written to the destination
* buffer, but a pointer into the data buffer itself will be returned instead.
* The returned pointer must always be used instead of assuming that the decoded
* data was written to the output buffer. Similarly, the @p framesToDecode count
* must be used instead of assuming that exactly the requested number of frames
* were successfully decoded.
*/
const void*(CARB_ABI* decodeData)(CodecState* decodeState, void* buffer, size_t framesToDecode, size_t* framesDecoded);
/** retrieves the amount of data available to decode in a sound data object.
*
* @param[in] decodeState the decode state to retrieve the amount of data that is available
* from the current read cursor position to the end of the stream.
* This may not be nullptr.
* @param[in] units the units to retrieve the available data count in. Note that if
* time units are requested (ie: milliseconds), the returned value
* will only be an estimate of the available data.
* @returns the amount of available data in the requested units.
* @returns 0 if no data is available or it could not be calculated.
*
* @remarks This retrieves the amount of data left to decode from the current read cursor
* to the end of the stream. Some formats may not be able to calculate the amount
* of available data.
*/
size_t(CARB_ABI* getDecodeAvailable)(const CodecState* decodeState, UnitType units);
/** retrieves the current cursor position for a codec state.
*
* @param[in] state the codec state to retrieve the current read cursor position for.
* This may not be nullptr.
* @param[in] units the units to retrieve the current read cursor position in. Note that
* if time units are requested (ie: milliseconds), the returned value
* will only be an estimate of the current position since time units are
* not accurate.
* @ref UnitType::eBytes is invalid if the codec being used specifies
* @ref fCodecCapsCompressed.
* @returns the current cursor position in the requested units. For a decoder state, this is
* the location in the sound's data where the next decoding operation will start
* from. For an encoder state, this is effectively the amount of data that has been
* successfully encoded and written to the target.
* @returns 0 if the cursor is at the start of the buffer or output target.
* @returns 0 if the decode position could not be calculated.
* @returns 0 if no data has been successfully written to an output target.
*
* @remarks This retrieves the current cursor position for a codec state. Some formats may
* not be able to calculate an accurate cursor position and may end up aligning it
* to the nearest block boundary instead.
*
* @note Even though the write cursor for an encoder state can be retrieved, setting it is
* not possible since that would cause a discontinuity in the stream and corrupt it.
* If the stream position needs to be rewound to the beginning, the encoder state
* should be recreated and the stream started again on a new output target.
*/
size_t(CARB_ABI* getCodecPosition)(const CodecState* decodeState, UnitType units);
/** sets the new decoder position.
*
* @param[in] decodeState the decoder state to set the position for. This may not be
* nullptr. This must be a decoder state.
* @param[in] newPosition the new offset into the sound data object's buffer to set the
* read cursor to. The units of this offset depend on the value
* in @p units.
* @param[in] units the units to interpret the @p newPosition offset in. Note that
* if time units are requested (ie: milliseconds), the new position
* may not be accurate in the buffer. The only offset that can be
* guaranteed accurate in time units is 0.
* @returns true if the new decoding read cursor position was successfully set.
* @returns false if the new position could not be set or an encoder state was used.
*
* @remarks This attempts to set the decoder's read cursor position to a new offset in the
* sound buffer. The new position may not be accurately set depending on the
* capabilities of the codec. The position may be aligned to the nearest block
* boundary for sound codecs and may fail for others.
*/
bool(CARB_ABI* setCodecPosition)(CodecState* decodeState, size_t newPosition, UnitType units);
/** calculates the maximum amount of data that a codec produce for a given input size.
*
* @param[in] state the codec state to estimate the buffer size for. This may not
* be nullptr. This may be either an encoder or decoder state.
* @param[in] inputSize for a decoder state, this is the number of bytes of input to
* estimate the output frame count for. For an encoder state, this
* is the number of frames of data that will be submitted to the
* encoder during the encoding operation.
* @returns an upper limit on the number of frames that can be decoded from the given input
* buffer size for decoder states.
* @returns an upper limit on the size of the output buffer in bytes that will be needed to
* hold the output for an encoder state.
* @returns 0 if the frame count could not be calculated or the requested size was 0.
*
* @remarks This calculates the maximum buffer size that would be needed to hold the output
* of the codec operation specified by the state object. This can be used to
* allocate or prepare a destination that is large enough to receive the operation's
* full result. Note that the units of both the inputs and outputs are different
* depending on the type of codec state that is used. This is necessary because the
* size of an encoded buffer in frames cannot always be calculated for a given byte
* size and vice versa. Some sample formats only allow for an upper limit to be
* calculated for such cases.
*
* @remarks For a decoder state, this calculates the maximum number of frames of PCM data
* that could be produced given a number of input bytes in the decoder state's
* output format. This is used to be able to allocate a decoding buffer that is
* large enough to hold the results for a given input request.
*
* @remarks For an encoder state, this calculates an estimate of the buffer size needed in
* order to store the encoder output for a number of input frames. For PCM formats,
* the returned size will be exact. For compressed formats, the returned size will
* be an upper limit on the size of the output stream. Note that this value is not
* always fully predictable ahead of time for all formats since some depend on
* the actual content of the stream to adapt their compression (ie: variable
* bit rate formats, frequency domain compression, etc).
*/
size_t(CARB_ABI* getCodecDataSizeEstimate)(const CodecState* decodeState, size_t inputBytes);
/** encodes a simple buffer of data into the output target for the operation.
*
* @param[in] encodeState the encoder state object that is managing the stream encoding
* operation. This may not be nullptr.
* @param[in] buffer the buffer of data to be encoded. This is expected to be in
* the input data format specified when the encoder state object
* was created. This may not be nullptr.
* @param[in] lengthInFrames the size of the input buffer in frames.
* @returns the number of bytes that were successfully encoded and written to the
* output target.
* @returns 0 if the buffer could not be encoded or the output target has become full or
* or fails to write (ie: the sound data object is full and is not allowed or able
* to expand, or writing to the output stream failed).
*
* @remarks This encodes a single buffer of data into an output target. The buffer is
* expected to be in the input sample format for the encoder. The buffer is also
* expected to be the logical continuation of any previous buffers in the stream.
*/
size_t(CARB_ABI* encodeData)(CodecState* encodeState, const void* buffer, size_t lengthInFrames);
/***************************** Sound Data Metadata Information ********************************/
/** Retrieve the names of the metadata tags in a SoundData.
*
* @param[in] sound The sound to retrieve the metadata tag names from.
* @param[in] index The index of the metadata tag in the sound object.
* To enumerate all tags in @p sound, one should call
* this with @p index == 0, then increment until nullptr
* is returned from this function. Note that adding or
* removing tags may alter the ordering of this table,
* but changing the value of a tag will not.
* @param[out] value If this is non-null and a metadata tag exists at
* index @p index, the contents of the metadata tag
* under the returned name is assigned to @p value.
* If this is non-null and no metadata tag exists at
* index @p index, @p value is assigned to nullptr.
* This string is valid until \p sound is destroyed or
* this entry in the metadata table is changed or
* removed.
*
* @returns This returns a null terminated string for the tag name, if a
* tag at index @p index exists.
* The returned string is valid until \p sound is destroyed or
* this entry in the metadata table is changed or removed.
* @returns This returns nullptr if no tag at @p index exists.
*
* @remarks This function allows the metadata of a @ref SoundData object
* to be enumerated. This function can be called with incrementing
* indices, starting from 0, to retrieve all of the metadata tag
* names. @p value can be used to retrieve the contents of each
* metadata tag, if the contents of each tag is needed.
*
* @note If setMetaData() is called, the order of the tags is not
* guaranteed to remain the same.
*/
const char*(CARB_ABI* getMetaDataTagName)(const SoundData* sound, size_t index, const char** value);
/** Retrieve a metadata tag from a SoundData.
*
* @param[in] sound The sound to retrieve the metadata tag from.
* @param[in] tagName The name of the metadata tag to retrieve.
* For example "artist" may retrieve the name of the
* artist who created the SoundData object's contents.
* This may not be nullptr.
*
* @returns This returns a null terminated string if a metadata tag under
* the name @p tagName exited in @p sound.
* The returned string is valid until \p sound is destroyed or
* this entry in the metadata table is changed or removed.
* @returns This returns nullptr if no tag under the name @p tagName was
* found in @p sound.
*/
const char*(CARB_ABI* getMetaData)(const SoundData* sound, const char* tagName);
/** Set a metadata tag on a SoundData.
*
* @param[in] sound The sound to retrieve the metadata tag from.
* @param[in] tagName The name of the metadata tag to set.
* For example, one may set a tag with @p tagName
* "artist" to specify the creator of the SoundData's
* contents. This can be set to @ref kMetaDataTagClearAllTags
* to remove all metadata tags on the sound object.
* @param[in] tagValue A null terminated string to set as the value for
* @p tagName. This can be set to nullptr to remove
* the tag under @p tagName from the object.
*
* @returns This returns true if the tags was successfully added or changed.
* @returns This returns false if @p tagValue is nullptr and no tag was
* found under the name @p tagName.
* @returns This returns false if an error occurred which prevented the
* tag from being set.
*
* @note @p tagName and @p tagValue are copied internally, so it is safe
* to immediately deallocate them after calling this.
* @note Metadata tag names are not case sensitive.
* @note It is not guaranteed that a given file type will be able to store
* arbitrary key-value pairs. RIFF files (.wav), for example, store
* metadata tags under 4 character codes, so only metadata tags
* that are known to this plugin, such as @ref kMetaDataTagArtist
* or tags that are 4 characters in length can be stored. Note this
* means that storing 4 character tags beginning with 'I' runs the
* risk of colliding with the known tag names (e.g. 'IART' will
* collide with @ref kMetaDataTagArtist when writing a RIFF file).
* @note @p tagName must not contain the character '=' when the output format
* encodes its metadata in the Vorbis Comment format
* (@ref SampleFormat::eVorbis and @ref SampleFormat::eFlac do this).
* '=' will be replaced with '_' when encoding these formats to avoid
* the metadata being encoded incorrectly.
* Additionally, the Vorbis Comment standard states that tag names
* must only contain characters from 0x20 to 0x7D (excluding '=')
* when encoding these formats.
*/
bool(CARB_ABI* setMetaData)(SoundData* sound, const char* tagName, const char* tagValue);
};
} // namespace audio
} // namespace carb
#ifndef DOXYGEN_SHOULD_SKIP_THIS
CARB_ASSET(carb::audio::SoundData, 0, 1);
#endif
|
omniverse-code/kit/include/carb/audio/IAudioGroup.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief The audio group interface.
*/
#pragma once
#include "../Interface.h"
#include "AudioTypes.h"
#include "IAudioData.h"
#include "IAudioPlayback.h"
namespace carb
{
namespace audio
{
/************************************* Interface Objects *****************************************/
/** an object containing zero or more sound data objects. This group may be used to hold sounds
* that can be selected with differing probabilities when trying to play a high level sound clip
* or to only select a specific sound as needed. A group may contain any number of sounds.
*/
struct Group;
/******************************** typedefs, enums, & macros **************************************/
/** base type for the flags that control the behavior of the creation of a group. */
typedef uint32_t GroupFlags;
/** group creation flag to indicate that the random number generator for the group should
* be seeded with a fixed constant instead of another random value. This will cause the
* group's random number sequence to be repeatable on each run instead of random. Note that
* the constant seed may be platform or implementation dependent. This is useful for tests
* where a stable but non-consecutive sequence is needed. Note that each group has its own
* random number stream and choosing a random sound from one group will not affect the
* random number stream of any other group.
*/
constexpr GroupFlags fGroupFlagFixedSeed = 0x00000001;
/** an entry in a table of sounds being added to a sound group on creation or a single sound
* being added to a sound group with a certain region to be played. This can be used to
* provide sound atlas support in a sound group. Each (or some) of the sounds in the group
* can be the same, but each only plays a small region instead of the full sound.
*/
struct SoundEntry
{
/** the sound data object to add to the sound group. This must not be nullptr. A reference
* will be taken to this sound data object when it is added to the group.
*/
SoundData* sound;
/** the starting point for playback of the new sound. This value is interpreted in the units
* specified in @ref playUnits. This should be 0 to indicate the start of the sound data object
* as the starting point. This may not be larger than the valid data length (in the same
* units) of the sound data object itself.
*/
uint64_t playStart = 0;
/** the length of data to play in the sound data object. This extends from the @ref playStart
* point extending through this much data measured in the units @ref playUnits. This should
* be 0 to indicate that the remainder of the sound data object starting from @ref playStart
* should be played.
*/
uint64_t playLength = 0;
/** the units to interpret the @ref playStart and @ref playLength values in. Note that using
* some time units may not provide precise indexing into the sound data object. Also note
* that specifying this offset in bytes often does not make sense for compressed data.
*/
UnitType playUnits = UnitType::eFrames;
};
/** descriptor of a new group to be created. A group may be optionally named and optionally
* created with a set of sound data objects initially added to it.
*/
struct GroupDesc
{
/** flags to control the behavior of the group's creation or behavior. This is zero or
* more of the kGroupFlag* flags.
*/
GroupFlags flags = 0;
/** optional name to initially give to the group. This can be changed at any later point
* with setGroupName(). The name has no functional purpose except to identify the group
* to a user.
*/
const char* name = nullptr;
/** the total number of sound data objects in the @ref initialSounds table. */
size_t count = 0;
/** a table of sounds and regions that should be added to the new group immediately on
* creation. This may be nullptr to create an empty group, or this may be a table of
* @ref count sound data objects and regions to be added to the group. When each sound
* is added to the group, a reference to the object will be taken. The reference will
* be released when the sound is removed from the group or the group is destroyed. The
* sound data object will only be destroyed when removed from the group or the group is
* destroyed if the group owned the last reference to it.
*/
SoundEntry* initialSounds = nullptr;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** names of possible methods for choosing sounds to play from a sound group. These are used with
* the chooseSound() function. The probabilities of each sound in the group are only used when
* the @ref ChooseType::eRandom selection type is used.
*/
enum class ChooseType
{
/** choose a sound from the group at random using each sound's relative probabilities to
* perform the selection. By default, all sounds in a group will have a uniform probability
* distribution. The tendency to have one sound selected over others can be changed by
* changing that sound's probability with setProbability().
*/
eRandom,
/** chooses the next sound in the group. The next sound is either the first sound in the
* group if none has been selected yet, or the sound following the one that was most recently
* selected from the group. Even if another selection type was used in a previous call,
* this will still return the sound after the one that was most recently selected. This
* will wrap around to the first sound in the group if the last sound in the group was
* previously selected.
*/
eNext,
/** chooses the previous sound in the group. The previous sound is either the last sound in
* the group if none has been selected yet, or the sound preceding the one that was most
* recently selected from the group. Even if another selection type was used in a previous
* call, this will still return the sound before the one that was most recently selected.
* This will wrap around to the last sound in the group if the first sound in the group was
* previously selected.
*/
ePrevious,
/** always chooses the first sound in the group. */
eFirst,
/** always chooses the last sound in the group. */
eLast,
};
/** used in the @ref ProbabilityDesc object to indicate that all sounds within a group should
* be affected, not just a single index.
*/
constexpr size_t kGroupIndexAll = ~0ull;
/** used to identify an invalid index in the group or that a sound could not be added. */
constexpr size_t kGroupIndexInvalid = static_cast<size_t>(-2);
/** descriptor for specifying the relative probabilities for choosing one or more sounds in a
* sound group. This allows the probabilities for a sound within a group being chosen at play
* time. By default, a sound group assigns equal probabilities to all of its members.
*/
struct ProbabilityDesc
{
/** set to the index of the sound within the group to change the probability for. This may
* either be @ref kGroupIndexAll to change all probabilities within the group, or the
* zero based index of the single sound to change. When @ref kGroupIndexAll is used,
* the @ref probability value is ignored since a uniform distribution will always be set
* for each sound in the group. If this index is outside of the range of the number of
* sounds in the group, this call will silently fail.
*/
size_t index;
/** the new relative probability value to set for the specified sound in the group. This
* value will be ignored if the @ref index value is @ref kGroupIndexAll however. This
* value does not need to be within any given range. This simply specifies the relative
* frequency of the specified sound being selected compared to other sounds in the group.
* Setting this to 0 will cause the sound to never be selected from the group.
*/
float probability;
/** value reserved for future expansion. This should be set to nullptr. */
void* ext = nullptr;
};
/******************************** Audio Sound Group Management Interface *******************************/
/** Sound group management interface.
*
* See these pages for more detail:
* @rst
* :ref:`carbonite-audio-label`
* :ref:`carbonite-audio-group-label`
@endrst
*/
struct IAudioGroup
{
CARB_PLUGIN_INTERFACE("carb::audio::IAudioGroup", 1, 0)
/** creates a new sound group.
*
* @param[in] desc a descriptor of the new group to be created. This may be nullptr to
* create a new, empty, unnamed group.
* @returns the new group object if successfully created. This must be destroyed with a call
* to destroyGroup() when it is no longer needed.
* @returns nullptr if the new group could not be created.
*
* @remarks This creates a new sound group object. A sound group may contain zero or more
* sound data objects. The group may be initially populated by one or more sound
* data objects that are specified in the descriptor or it may be created empty.
*
* @note Access to the group object is not thread safe. It is the caller's responsibility
* to ensure that all accesses that may occur simultaneously are properly protected
* with a lock.
*/
Group*(CARB_ABI* createGroup)(const GroupDesc* desc);
/** destroys a sound group.
*
* @param[in] group the group to be destroyed. This must not be nullptr.
* @returns no return value.
*
* @remarks This destroys a sound group object. Each sound data object in the group at
* the time of destruction will have one reference removed from it. The group
* object will no longer be valid upon return.
*/
void(CARB_ABI* destroyGroup)(Group* group);
/** retrieves the number of sound data objects in a group.
*
* @param[in] group the group to retrieve the sound data object count for. This must
* not be nullptr.
* @returns the total number of sound data objects in the group.
* @returns 0 if the group is empty.
*/
size_t(CARB_ABI* getSize)(const Group* group);
/** retrieves the name of a group.
*
* @param[in] group the group to retrieve the name for. This must not be nullptr.
* @returns the name of the group.
* @returns nullptr if the group does not have a name.
*
* @remarks This retrieves the name of a group. The returned string will be valid until
* the group's name is changed with setGroupName() or the group is destroyed. It
* is highly recommended that the returned string be copied if it needs to persist.
*/
const char*(CARB_ABI* getName)(const Group* group);
/** sets the new name of a group.
*
* @param[in] group the group to set the name for. This must not be nullptr.
* @param[in] name the new name to set for the group. This may be nullptr to remove
* the group's name.
* @returns no return value.
*
* @remarks This sets the new name for a group. This will invalidate any names that were
* previously returned from getGroupName() regardless of whether the new name is
* different.
*/
void(CARB_ABI* setName)(Group* group, const char* name);
/** adds a new sound data object to a group.
*
* @param[in] group the group to add the new sound data object to. This must not be
* nullptr.
* @param[in] sound the sound data object to add to the group. This must not be nullptr.
* @returns the index of the new sound in the group if it is successfully added.
* @retval kGroupIndexInvalid if the new sound could not be added to the group.
*
* @remarks This adds a new sound data object to a group. The group will take a reference
* to the sound data object when it is successfully added. There will be no
* checking to verify that the sound data object is not already a member of the
* group. The initial relative probability for any new sound added to a group
* will be 1.0. This may be changed later with setProbability().
*
* @note This returned index is only returned for the convenience of immediately changing the
* sound's other attributes within the group (ie: the relative probability). This
* index should not be stored for extended periods since it may be invalidated by any
* calls to removeSound*(). If changes to a sound in the group need to be made at a
* later time, the index should either be known ahead of time (ie: from a UI that is
* tracking the group's state), or the group's members should be enumerated to first
* find the index of the desired sound.
*/
size_t(CARB_ABI* addSound)(Group* group, SoundData* sound);
/** adds a new sound data object with a play region to a group.
*
* @param[in] group the group to add the new sound data object to. This must not be
* nullptr.
* @param[in] sound the sound data object and play range data to add to the group.
* This must not be nullptr.
* @returns the index of the new sound in the group if it is successfully added.
* @retval kGroupIndexInvalid if the new sound could not be added to the group.
*
* @remarks This adds a new sound data object with a play range to a group. The group
* will take a reference to the sound data object when it is successfully added.
* There will be no checking to verify that the sound data object is not already
* a member of the group. The play region for the sound may indicate the full
* sound or only a small portion of it. The initial relative probability for any
* new sound added to a group will be 1.0. This may be changed later with
* setProbability().
*
* @note This returned index is only returned for the convenience of immediately changing the
* sound's other attributes within the group (ie: the relative probability). This
* index should not be stored for extended periods since it may be invalidated by any
* calls to removeSound*(). If changes to a sound in the group need to be made at a
* later time, the index should either be known ahead of time (ie: from a UI that is
* tracking the group's state), or the group's members should be enumerated to first
* find the index of the desired sound.
*/
size_t(CARB_ABI* addSoundWithRegion)(Group* group, const SoundEntry* sound);
/** removes a sound data object from a group.
*
* @param[in] group the group to remove the sound from. This must not be nullptr.
* @param[in] sound the sound to be removed from the group. This may be nullptr to
* remove all sound data objects from the group.
* @returns true if the sound is a member of the group and it is successfully removed.
* @returns false if the sound is not a member of the group.
*
* @remarks This removes a single sound data object from a group. Only the first instance
* of the requested sound will be removed from the group. If the sound is present
* in the group multiple times, additional explicit calls to remove the sound must
* be made to remove all of them.
*
* @note Once a sound is removed from a group, the ordering of sounds within the group may
* change. The relative probabilities of each remaining sound will still be
* unmodified.
*/
bool(CARB_ABI* removeSound)(Group* group, SoundData* sound);
/** removes a sound data object from a group by its index.
*
* @param[in] group the group to remove the sound from. This must not be nullptr.
* @param[in] index the zero based index of the sound to remove from the group. This
* may be @ref kGroupIndexAll to clear the entire group. This must not
* be @ref kGroupIndexInvalid.
* @returns true if the sound is a member of the group and it is successfully removed.
* @returns false if the given index is out of range of the size of the group.
*
* @note Once a sound is removed from a group, the ordering of sounds within the group may
* change. The relative probabilities of each remaining sound will still be
* unmodified.
*/
bool(CARB_ABI* removeSoundAtIndex)(Group* group, size_t index);
/** sets the current sound play region for an entry in the group.
*
* @param[in] group the group to modify the play region for a sound in. This must not
* be nullptr.
* @param[in] index the zero based index of the sound entry to update the region for.
* This must not be @ref kGroupIndexInvalid or @ref kGroupIndexAll.
* @param[in] region the specification of the new region to set on the sound. The
* @a sound member will be ignored and assumed that it either matches
* the sound data object already at the given index or is nullptr.
* All other members must be valid. This must not be nullptr.
* @returns true if the play region for the selected sound is successfully updated.
* @returns false if the index was out of range of the size of the group.
*
* @remarks This modifies the play region values for a single sound entry in the group.
* This will not replace the sound data object at the requested entry. Only
* the play region (start, length, and units) will be updated for the entry.
* It is the caller's responsibility to ensure the new play region values are
* within the range of the sound data object's current valid region.
*/
bool(CARB_ABI* setSoundRegion)(Group* group, size_t index, const SoundEntry* region);
/** retrieves the sound data object at a given index in a group.
*
* @param[in] group the group to retrieve a sound from. This must not be nullptr.
* @param[in] index the index of the sound data object to retrieve. This must not be
* @ref kGroupIndexInvalid or @ref kGroupIndexAll.
* @returns the sound data object at the requested index in the group. An extra reference
* to this object will not be taken and therefore does not have to be released.
* This object will be valid as long as it is still a member of the group.
* @returns nullptr if the given index was out of range of the size of the group.
*/
SoundData*(CARB_ABI* getSound)(const Group* group, size_t index);
/** retrieves the sound data object and region information at a given index in a group.
*
* @param[in] group the group to retrieve a sound from. This must not be nullptr.
* @param[in] index the index of the sound data object information to retrieve. This
* must not be @ref kGroupIndexInvalid or @ref kGroupIndexAll.
* @param[out] entry receives the information for the sound entry at the given index in
* the group. This not be nullptr.
* @returns true if the sound data object and its region information are successfully
* retrieved. The sound data object returned in @p entry will not have an extra
* reference taken to it and does not need to be released.
* @returns false if the given index was out of range of the group.
*/
bool(CARB_ABI* getSoundEntry)(const Group* group, size_t index, SoundEntry* entry);
/** sets the new relative probability for a sound being selected from a sound group.
*
* @param[in] group the sound group to change the relative probabilities for. This must
* not be nullptr.
* @param[in] desc the descriptor of the sound within the group to be changed and the
* new relative probability for it. This must not be nullptr.
* @returns no return value.
*
* @remarks This sets the new relative probability for choosing a sound within a sound group.
* Each sound in the group gets a relative probability of 1 assigned to it when it
* is first added to the group (ie: giving a uniform distribution initially). These
* relative probabilities can be changed later by setting a new value for individual
* sounds in the group. The actual probability of a particular sound being chosen
* from the group depends on the total sum of all relative probabilities within the
* group as a whole. For example, if a group of five sounds has been assigned the
* relative probabilities 1, 5, 7, 6, and 1, there is a 1/20 chance of the first or
* last sounds being chosen, a 1/4 chance of the second sound being chosen, a 7/20
* chance of the third sound being chosen, and a 6/20 chance of the fourth sound
* being chosen.
*/
void(CARB_ABI* setProbability)(Group* group, const ProbabilityDesc* desc);
/** retrieves a relative probability for a sound being selected from a sound group.
*
* @param[in] group the group to retrieve a relative probability for.
* @param[in] index the index of the sound in the group to retrieve the relative
* probability for. If this is out of range of the size of the
* group, the call will fail. This must not be @ref kGroupIndexAll
* or @ref kGroupIndexInvalid.
* @returns the relative probability of the requested sound within the group.
* @returns 0.0 if the requested index was out of range of the group's size.
*
* @remarks This retrieves the relative probability of the requested sound within a group
* being chosen by the chooseSound() function when using the ChooseType::eRandom
* selection type. Note that this will always the relative probability value that
* was either assigned when the sound was added to the group (ie: 1.0) or the one
* that was most recently set using a call to the setProbability() function.
*
* @note This is intended to be called in an editor situation to retrieve the relative
* probability values that are currently set on a group for display purposes.
*/
float(CARB_ABI* getProbability)(const Group* group, size_t index);
/** gets the relative probability total for all sounds in the group.
*
* @param[in] group the group to retrieve the relative probabilities total for. This
* must not be nullptr.
* @returns the sum total of the relative probabilities of each sound in the group.
* @returns 0.0 if the group is empty or all sounds have a zero relative probability.
* It is the caller's responsibility to check for this before using it as a
* divisor.
*
* @remarks This retrieves the total of all relative probabilities for all sounds in a
* group. This can be used to calculate the absolute probability of each sound
* in the group. This is done by retrieving each sound's relative probability
* with getProbability(), then dividing it by the value returned here.
*/
float(CARB_ABI* getProbabilityTotal)(const Group* group);
/** chooses a sound from a sound group.
*
* @param[in] group the group to select a sound from. This must not be nullptr.
* @param[in] type the specific algorithm to use when choosing the sound.
* @param[out] play receives the play descriptor for the chosen sound. On success, this
* will be filled in with enough information to play the chosen sound and
* region once as a non-spatial sound. It is the caller's responsibility
* to fill in any additional parameters (ie: voice callback function,
* additional voice parameters, spatial sound information, etc). This
* must not be nullptr. This object is assumed to be uninitialized and
* all members will be filled in.
* @returns true if a sound if chosen and the play descriptor @p play is valid.
* @returns false if the group is empty.
* @returns false if the maximum number of sound instances from this group are already
* playing. This may be tried again later and will succeed when the playing
* instance count drops below the limit.
*
* @remarks This chooses a sound from a group according to the given algorithm. When
* choosing a random sound, the sound is chosen using the relative probabilities
* of each of the sounds in the group. When choosing the next or previous sound,
* the sound in the group either after or before the last one that was most recently
* returned from chooseSound() will be returned. This will never fail unless the
* group is empty.
*/
bool(CARB_ABI* chooseSound)(Group* group, ChooseType type, PlaySoundDesc* play);
/** retrieves the maximum simultaneously playing instance count for sounds in a group.
*
* @param[in] group the group to retrieve the maximum instance count for. This must not
* be nullptr.
* @returns the maximum instance count for the group if it is limited.
* @retval kInstancesUnlimited if the instance count is unlimited.
*
* @remarks This retrieves the current maximum instance count for the sounds in a group.
* This limit is used to prevent too many instances of sounds in this group from
* being played simultaneously. With the limit set to unlimited, playing too many
* instances can result in serious performance penalties and serious clipping
* artifacts caused by too much constructive interference.
*/
uint32_t(CARB_ABI* getMaxInstances)(const Group* group);
/** sets the maximum simultaneously playing instance count for sounds in a group.
*
* @param[in] group the group to change the maximum instance count for. This must not be
* nullptr.
* @param[in] limit the new maximum instance limit for this sound group. This may be
* @ref kInstancesUnlimited to remove the limit entirely.
* @returns no return value.
*
* @remarks This sets the new maximum playing instance count for sounds in a group. This
* limit only affects the results of chooseSound(). When the limit is exceeded,
* calls to chooseSound() will start failing until some sound instances in the
* group finish playing. This instance limit is also separate from the maximum
* instance count for each sound in the group. Individual sound data objects
* also have their own maximum instance counts and will limit themselves when
* they are attempted to be played. Note that these two limits may however
* interact with each other if the group's instance limit is not hit but the
* instance limit for the particular chosen sound has been reached. It is the
* caller's responsibility to ensure the various instance limits are set in such
* a way this interaction is minimized.
*/
void(CARB_ABI* setMaxInstances)(Group* group, uint32_t limit);
/** retrieves the user data pointer for a sound group object.
*
* @param[in] group the sound group to retrieve the user data pointer for. This must
* not be nullptr.
* @returns the stored user data pointer.
* @returns nullptr if no user data has been set on the requested sound group.
*
* @remarks This retrieves the user data pointer for the requested sound group. This
* is used to associate any arbitrary data with a sound group object. It is
* the caller's responsibility to ensure access to data is done in a thread
* safe manner.
*/
void*(CARB_ABI* getUserData)(const Group* group);
/** sets the user data pointer for a sound group.
*
* @param[in] group the sound group to set the user data pointer for. This must not
* be nullptr.
* @param[in] userData the new user data pointer to set. This may include an optional
* destructor if the user data object needs to be cleaned up. This
* may be nullptr to indicate that the user data pointer should be
* cleared out entirely and no new object stored.
* @returns no return value.
*
* @remarks This sets the user data pointer for the given sound group. This is used to
* associate any arbitrary data with a sound group. It is the caller's
* responsibility to ensure access to this table is done in a thread safe manner.
*
* @note The sound group that this user data object is attached to must not be accessed
* from the destructor. If the sound group is being destroyed when the user data
* object's destructor is being called, its contents will be undefined.
*/
void(CARB_ABI* setUserData)(Group* group, const UserData* userData);
};
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/IAudioPlayback.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief The audio playback interface.
*/
#pragma once
#ifndef DOXYGEN_SHOULD_SKIP_THIS
# define _USE_MATH_DEFINES
#endif
#include "../Interface.h"
#include "AudioTypes.h"
#include "IAudioData.h"
#include <math.h>
namespace carb
{
/** Audio playback and capture. */
namespace audio
{
/******************************** typedefs, enums, & macros **************************************/
/** specifies the relative direction to a single speaker. This is effectively a 3-space vector,
* but is explicitly described here to avoid any confusion between various common coordinate
* systems (ie: graphics systems take Z as pointing in the direction of the camera whereas
* audio systems take Z as pointing up).
*
* This direction vector is always taken to be relative to the [real biological] user's expected
* position within the [physical] speaker setup where the origin is the user's position and the
* coordinates in each direction range from -1.0 to 1.0. The provided vector does not need to
* be normalized.
*/
struct SpeakerDirection
{
/** the left-to-right coordinate. A value of 0.0 is in line with the user's gaze. A value
* of -1.0 puts the speaker fully on the user's left side. A value of 1.0 puts the speaker
* fully on the user's right side.
*/
float leftRight = 0.0f;
/** the front-to-back coordinate. A value of 0.0 is in line with the user's ears. A value
* of -1.0 puts the speaker fully behind the user. A value of 1.0 puts the speaker fully
* in front of the user.
*/
float frontBack = 0.0f;
/** the top-to-bottom coordinate. A value of 0.0 is on the plane formed from the user's ears
* and gaze. A value of -1.0 puts the speaker fully below the user. A value of 1.0 puts the
* speaker fully above the user.
*/
float topBottom = 0.0f;
};
/** flags to affect the behavior of a speaker direction descriptor when it is passed to
* setSpeakerDirections().
*/
typedef uint32_t SpeakerDirectionFlags;
/** a descriptor of the direction from the [real biological] user to all speakers in the user's
* sound setup. This is specified by the direction vector from the user's position (assumed
* to be at the origin) to each speaker. This speaker direction set given here must always
* match the speaker mode for the current device and the user's speaker layout, otherwise the
* output results will be undefined. These speaker directions are used to calculate all
* spatial sounds for a context so that they map as accurately as possible to the user's
* specific speaker setup.
*/
struct SpeakerDirectionDesc
{
/** flags to control the behavior of the speaker positioning operation. No flags are
* currently defined. This must be set to 0.
*/
SpeakerDirectionFlags flags = 0;
/** the audio engine's output speaker mode that was selected at either context creation time
* or device opening time. If the speaker mode was set to @ref kSpeakerModeDefault at
* context creation time, this will be set to the channel mask of the device that was
* selected. Each set bit in this mask must have a corresponding vector set in the
* @ref directions table. All other vectors will be ignored. This channel mask can be
* retrieved from getContextCaps() for the currently selected device. Note that selecting
* a new device with setOutput() will always reset the channel mask back to the defaults
* for the new device.
*/
SpeakerMode speakerMode;
/** the direction vectors from the user to each speaker. This does not need to be normalized.
* Note that when this information is retrieved with getContextCaps(), the speaker direction
* vectors may not match the original values that were set since they may have already been
* normalized internally. Each entry in this table is indexed by a @ref Speaker name. For
* speaker modes that have more than @ref Speaker::eCount speakers, the specific mapping and
* positioning for each speaker is left entirely up to the caller (ie: a set of custom
* speaker directions must be specified for each channel for all contexts). Each valid
* vector in this set, except for @ref Speaker::eLowFrequencyEffect, should have a non-zero
* direction. The LFE speaker is always assumed to be located at the origin.
*/
SpeakerDirection directions[kMaxChannels];
/** provides an extended information block. This is reserved for future expansion and should
* be set to nullptr.
*/
void* ext = nullptr;
};
/** names for the state of a stream used in the Streamer object. These are returned from the
* writeData() function to indicate to the audio processing engine whether the processing rate
* needs to temporarily speed up or slow down (or remain the same). For non-real-time contexts,
* this would effectively always be requesting more data after each call. For real-time
* contexts however, if the streamer is writing the audio data to a custom device, these state
* values are used to prevent the device from being starved or overrun.
*/
enum class StreamState
{
/** indicates that the streamer is content with the current data production rate and that
* this rate should be maintained.
*/
eNormal,
/** indicates that the streamer is dangerously close to starving for data. The audio
* processing engine should immediately run another cycle and produce more data.
*/
eCritical,
/** indicates that the streamer is getting close to starving for data and the audio processing
* engine should temporarily increase its data production rate.
*/
eMore,
/** indicates that the streamer is getting close to overrunning and the audio processing
* engine should temporarily decrease its data production rate.
*/
eLess,
/** indicates that the streamer is dangerously close to overrunning its buffer or device.
* The audio processing engine should decrease its data production rate.
*/
eMuchLess,
};
/** interface for a streamer object. This gives the audio context a way to write audio data
* to a generic interface instead of writing the data to an actual audio device. This
* interface is used by specifying a streamer object in the @ref OutputDesc struct when creating
* the context or when calling setOutput(). Note that this interface is intended to implement
* a stateful object with each instance. Two different instances of this interface should
* be able to operate independently from each other.
*
* There is no requirement for how the incoming audio data is processed. The streamer
* implementation may do whatever it sees fit with the incoming audio data. Between the
* any two paired openStream() and closeStream() calls, each writeStreamData() call will
* be delivering sequential buffers in a single stream of audio data. It is up to the
* streamer implementation to interpret that audio data and do something useful with it.
*
* Since the internal usage of this streamer object is inherently asynchronous, all streamer
* objects must be atomically reference counted. When a streamer is set on an audio context,
* a reference will be taken on it. This reference will be released when the streamer is
* either removed (ie: a new output target is set for the context), or the context is destroyed.
*
* @note This interface must be implemented by the host application. No default implementation
* exists. Some example streamer objects can be found in 'carb/audio/Streamers.h'.
*/
struct Streamer
{
/** acquires a single reference to a Streamer object.
*
* @param[in] self the object to take the reference of.
* @returns no return value.
*
* @remarks This acquires a new reference to a Streamer object. The reference must be
* released later with releaseReference() when it is no longer needed. Each
* call to acquireReference() on an object must be balanced with a call to
* releaseReference(). When a new streamer object is created, it should be
* given a reference count of 1.
*/
void(CARB_ABI* acquireReference)(Streamer* self);
/** releases a single reference to a Streamer object.
*
* @param[in] self the object to release a reference to. The object may be destroyed
* if it was the last reference that was released. The caller should
* consider the object invalid upon return unless it is known that
* additional local references still exist on it.
* @returns no return value.
*
* @remarks This releases a single reference to a Streamer object. If the reference count
* reaches zero, the object will be destroyed.
*/
void(CARB_ABI* releaseReference)(Streamer* self);
/** sets the suggested format for the stream output.
*
* @param[in] self the streamer object to open the stream for. This will not be
* nullptr.
* @param[inout] format on input, this contains the suggested data format for the stream.
* On output, this contains the accepted data format. The streamer
* may make some changes to the data format including the data type,
* sample rate, and channel count. It is strongly suggested that the
* input format be accepted since that will result in the least
* amount of processing overhead. The @a format, @a channels,
* @a frameRate, and @a bitsPerSample members must be valid upon
* return. If the streamer changes the data format, only PCM data
* formats are acceptable.
* @returns true if the data format is accepted by the streamer.
* @returns false if the streamer can neither handle the requested format nor
* can it change the requested format to something it likes.
*
* @remarks This sets the data format that the streamer will receive its data in. The
* streamer may change the data format to another valid PCM data format if needed.
* Note that if the streamer returns a data format that cannot be converted to by
* the processing engine, the initialization of the output will fail. Also note
* that if the streamer changes the data format, this will incur a small performance
* penalty to convert the data to the new format.
*
* @remarks This will be called when the audio context is first created. Once the format
* is accepted by both the audio context and the streamer, it will remain constant
* as long as the processing engine is still running on that context. When the
* engine is stopped (or the context is destroyed), a Streamer::close() call will
* be performed signaling the end of the stream. If the engine is restarted again,
* another open() call will be performed to signal the start of a new stream.
*/
bool(CARB_ABI* openStream)(Streamer* self, SoundFormat* format);
/** writes a buffer of data to the stream.
*
* @param[in] self the streamer object to write a buffer of data into. This will not
* be nullptr.
* @param[in] data the audio data being written to the streamer. This data will be in
* the format that was decided on in the call to open() during the
* context creation or the last call to setOutput(). This buffer will
* not persist upon return. The implementation must copy the contents
* of the buffer if it still needs to access the data later.
* @param[in] bytes the number of bytes of valid data in the buffer @p data.
* @retval StreamState::eNormal if the data was written successfully to the streamer
* and the data production rate should continue at the current rate.
* @retval StreamState::eMore if the data was written successfully to the streamer and
* the data production rate should be temporarily increased.
* @retval StreamState::eLess if the data was written successfully to the streamer and
* the data production rate should be temporarily reduced.
*
* @remarks This writes a buffer of data to the streamer. The streamer is responsible for
* doing something useful with the audio data (ie: write it to a file, write it to
* a memory buffer, stream it to another voice, etc). The caller of this function
* is not interested in whether the streamer successfully does something with the
* data - it is always assumed that the operation is successful.
*
* @note This must execute as quickly as possible. If this call takes too long to return
* and the output is going to a real audio device (through the streamer or some other
* means), an audible audio dropout could occur. If the audio context is executing
* in non-realtime mode (ie: baking audio data), this may take as long as it needs
* only at the expense of making the overall baking process take longer.
*/
StreamState(CARB_ABI* writeStreamData)(Streamer* self, const void* data, size_t bytes);
/** closes the stream.
*
* @param[in] self the streamer object to close the stream for. This will not be
* nullptr.
* @returns no return value.
*
* @remarks This signals that a stream has been finished. This occurs when the engine is
* stopped or the audio context is destroyed. No more calls to writeData() should
* be expected until the streamer is opened again.
*/
void(CARB_ABI* closeStream)(Streamer* self);
};
/** base type for the flags that control the output of an audio context. */
typedef uint32_t OutputFlags;
/** flag to indicate that the output should target a real audio device. When set, this indicates
* that the @ref OutputDesc::deviceIndex value will be valid and that it identifies the index of
* the audio device that should be opened.
*/
constexpr OutputFlags fOutputFlagDevice = 0x00000001;
/** flag to indicate that the output should target one or more generic streamer objects. These
* objects are provided by the host app in the @ref OutputDesc::streamer value. The stream will
* be opened when the audio processing engine is started and closed when the engine is stopped
* or the context is destroyed.
*/
constexpr OutputFlags fOutputFlagStreamer = 0x00000002;
/** flag to indicate that an empty streamer table is allowed. This can be used
* to provide a way to set a null output in cases where audio output is not
* wanted, but audio engine behavior, such as voice callbacks, are still desired.
* This is also useful for testing, since you won't be dependent on the test
* systems having a physical audio device.
*/
constexpr OutputFlags fOutputFlagAllowNoStreamers = 0x00000004;
/** mask of output flag bits that are available for public use. Clear bits in this mask are
* used internally and should not be referenced in other flags here. This is not valid as a
* output flag or flag set.
*/
constexpr OutputFlags fOutputFlagAvailableMask = 0xffffffff;
/** descriptor of the audio output target to use for an audio context. This may be specified
* both when creating an audio context and when calling setOutput(). An output may consist
* of a real audio device or one or more streamers.
*/
struct OutputDesc
{
/** flags to indicate which output target is to be used. Currently only a single output
* target may be specified. This must be one of the fOutputFlag* flags. Future versions
* may allow for multiple simultaneous outputs. If this is 0, the default output device
* will be selected. If more than one flag is specified, the audio device index will
* specify which device to use, and the streamer table will specify the set of streamers
* to attach to the output.
*/
OutputFlags flags = 0;
/** the index of the device to open. This must be greater than or equal to 0 and less than
* the most recent return value of getDeviceCount(). Set this to 0 to choose the system's
* default playback device. This defaults to 0. This value is always ignored if the
* @ref fOutputFlagDevice flag is not used.
*/
size_t deviceIndex = 0;
/** the output speaker mode to set. This is one of the SpeakerMode names or a combination of
* the fSpeakerFlag* speaker flags. This will determine the channel layout for the final
* output of the audio engine. This channel layout will be mapped to the selected device's
* speaker mode before sending the final output to the device. This may be set to
* @ref kSpeakerModeDefault to cause the engine's output to match the output of the device
* that is eventually opened. This defaults to @ref kSpeakerModeDefault.
*/
SpeakerMode speakerMode = kSpeakerModeDefault;
/** the frame rate in Hertz to run the processing engine at. This should be 0 for any output
* that targets a real hardware device (ie: the @ref fOutputFlagDevice is used in @ref flags
* or @ref flags is 0), It is possible to specify a non-zero value here when a hardware
* device is targeted, but that may lead to unexpected results depending on the value given.
* For example, this could be set to 1000Hz, but the device could run at 48000Hz. This
* would process the audio data properly, but it would sound awful since the processing
* data rate is so low. Conversely, if a frame rate of 200000Hz is specified but the device
* is running at 48000Hz, a lot of CPU processing time will be wasted.
*
* When an output is targeting only a streamer table, this should be set to the frame rate
* to process audio at. If this is 0, a frame rate of 48000Hz will be used. This value
* should generally be a common audio processing rate such as 44100Hz, 48000Hz, etc. Other
* frame rates can be used, but the results may be unexpected if a frame cannot be perfectly
* aligned to the cycle period.
*/
size_t frameRate = 0;
/** the number of streams objects in the @ref streamer table. This value is ignored if the
* @ref fOutputFlagStreamer flag is not used.
*/
size_t streamerCount = 0;
/** a table of one or more streamer objects to send the final output to. The number of
* streamers in the table is specified in @ref streamerCount. These streamer objects must
* be both implemented and instantiated by the caller. The streamers will be opened when
* the new output target is first setup. All streamers in the table will receive the same
* input data and format settings when opened. This value is ignored if the
* @ref fOutputFlagStreamer flag is not used. Each object in this table will be opened
* when the audio processing engine is started on the context. Each streamer will receive
* the same data in the same format. Each streamer will be closed when the audio processing
* engine is stopped or the context is destroyed.
*
* A reference to each streamer will be acquired when they are assigned as an output. These
* references will all be released when they are no longer active as outputs on the context
* (ie: replaced as outputs or the context is destroyed). No entries in this table may be
* nullptr.
*
* @note If more than one streamer is specified here, It is the caller's responsibility to
* ensure all of them will behave well together. This means that none of them should
* take a substantial amount of time to execute and that they should all return as
* consistent a stream state as possible from writeStreamData(). Furthermore, if
* multiple streamers are targeting real audio devices, their implementations should
* be able to potentially be able to handle large amounts of latency (ie: up to 100ms)
* since their individual stream state returns may conflict with each other and affect
* each other's timings. Ideally, no more than one streamer should target a real
* audio device to avoid this stream state build-up behavior.
*/
Streamer** streamer = nullptr;
/** extended information for this descriptor. This is reserved for future expansion and
* should be set to nullptr.
*/
void* ext = nullptr;
};
/** names for events that get passed to a context callback function. */
enum class ContextCallbackEvent
{
/** an audio device in the system has changed its state. This could mean that one or more
* devices were either added to or removed from the system. Since device change events
* are inherently asynchronous and multiple events can occur simultaneously, this callback
* does not provide any additional information except that the event itself occurred. It
* is the host app's responsibility to enumerate devices again and decide what to do with
* the event. This event will only occur for output audio devices in the system. With
* this event, the @a data parameter to the callback will be nullptr. This callback will
* always be performed during the context's update() call.
*/
eDeviceChange,
/** the audio engine is about to start a processing cycle. This will occur in the audio
* engine thread. This is given as an opportunity to update any voice parameters in a
* manner that can always be completed immediately and will be synchronized with other
* voice parameter changes made at the same time. Since this occurs in the engine thread,
* it is the caller's responsibility to ensure this callback returns as quickly as possible
* so that it does not interrupt the audio processing timing. If this callback takes too
* long to execute, it will cause audio drop-outs. The callback's @a data parameter will
* be set to nullptr for this event.
*/
eCycleStart,
/** the audio engine has just finished a processing cycle. This will occur in the audio
* engine thread. Voice operations performed in here will take effect immediately. Since
* this occurs in the engine thread, it is the caller's responsibility to ensure this
* callback returns as quickly as possible so that it does not interrupt the audio processing
* timing. If this callback takes too long to execute, it will cause audio drop-outs. The
* callback's @a data parameter will be set to nullptr for this event.
*/
eCycleEnd,
};
/** prototype for a context callback event function.
*
* @param[in] context the context object that triggered the callback.
* @param[in] event the event that occurred on the context.
* @param[in] data provides some additional information for the event that occurred. The
* value and content of this object depends on the event that occurred.
* @param[in] userData the user data value that was registered with the callback when the
* context object was created.
* @returns no return value.
*/
typedef void(CARB_ABI* ContextCallback)(Context* context, ContextCallbackEvent event, void* data, void* userData);
/** flags to control the behavior of context creation. No flags are currently defined. */
typedef uint32_t PlaybackContextFlags;
/** flag to indicate that the audio processing cycle start and end callback events should be
* performed. By default, these callbacks are not enabled unless a baking context is created.
* This flag will be ignored if no callback is provided for the context.
*/
constexpr PlaybackContextFlags fContextFlagCycleCallbacks = 0x00000001;
/** flag to indicate that the audio processing engine should be run in 'baking' mode. This will
* allow it to process audio data as fast as the system permits instead of waiting for a real
* audio device to catch up. When this flag is used, it is expected that the context will also
* use a streamer for its output. If a device index is selected as an output, context creation
* and setting a new output will still succeed, but the results will not sound correct due to
* the audio processing likely going much faster than the device can consume the data. Note
* that using this flag will also imply the use of @ref fContextFlagCycleCallbacks if a
* callback function is provided for the context.
*
* When this flag is used, the new context will be created with the engine in a stopped state.
* The engine must be explicitly started with startProcessing() once the audio graph has been
* setup and all initial voices created. This can be combined with @ref fContextFlagManualStop
* to indicate that the engine will be explicitly stopped instead of stopping automatically once
* the engine goes idle (ie: no more voices are active).
*/
constexpr PlaybackContextFlags fContextFlagBaking = 0x00000002;
/** flag to indicate that the audio processing engine will be manually stopped when a baking
* task is complete instead of stopping it when all of the input voices run out of data to
* process. This flag is ignored if the @ref fContextFlagBaking flag is not used. If this
* flag is not used, the intention for the context is to queue an initial set of sounds to
* play on voices before starting the processing engine with startProcessing(). Once all
* triggered voices are complete, the engine will stop automatically. When this flag is
* used, the intention is that the processing engine will stay running, producing silence,
* even if no voices are currently playing. The caller will be expected to make a call to
* stopProcessing() at some point when the engine no longer needs to be running.
*/
constexpr PlaybackContextFlags fContextFlagManualStop = 0x00000004;
/** flag to enable callbacks of type ContextCallbackEvent::eDeviceChange.
* If this flag is not passed, no callbacks of this type will be performed for
* this context.
*/
constexpr PlaybackContextFlags fContextFlagDeviceChangeCallbacks = 0x00000008;
/** descriptor used to indicate the options passed to the createContext() function. This
* determines the how the context will behave.
*/
struct PlaybackContextDesc
{
/** flags to indicate some additional behavior of the context. No flags are currently
* defined. This should be set to 0. In future versions, these flags may be used to
* determine how the @ref ext member is interpreted.
*/
PlaybackContextFlags flags = 0;
/** a callback function to be registered with the new context object. This callback will be
* performed any time the output device list changes. This notification will only indicate
* that a change has occurred, not which specific change occurred. It is the caller's
* responsibility to re-enumerate devices to determine if any further action is necessary
* for the updated device list. This may be nullptr if no device change notifications are
* needed.
*/
ContextCallback callback = nullptr;
/** an opaque context value to be passed to the callback whenever it is performed. This value
* will never be accessed by the context object and will only be passed unmodified to the
* callback function. This value is only used if a device change callback is provided.
*/
void* callbackContext = nullptr;
/** the maximum number of data buses to process simultaneously. This is equivalent to the
* maximum number of potentially audible sounds that could possibly affect the output on the
* speakers. If more voices than this are active, the quietest or furthest voice will be
* deactivated. The default value for this is 64. Set this to 0 to use the default for
* the platform.
*
* For a baking context, this should be set to a value that is large enough to guarantee
* that no voices will become virtualized. If a voice becomes virtualized in a baking
* context and it is set to simulate that voice's current position, the resulting position
* when it becomes a real voice again is unlikely to match the expected position. This is
* because there is no fixed time base to simulate the voice on. The voice will be simulated
* as if it were playing in real time.
*/
size_t maxBuses = 0;
/** descriptor for the output to choose for the new audio context. This must specify at
* least one output target.
*/
OutputDesc output = {};
/** A name to use for any audio device connection that requires one.
* This can be set to nullptr to use a generic default name, if necessary.
* This is useful in situations where a platform, such as Pulse Audio,
* will display a name to the user for each individual audio connection.
* This string is copied internally, so the memory can be discarded after
* calling createContext().
*/
const char* outputDisplayName = nullptr;
/** extended information for this descriptor. This is reserved for future expansion and
* should be set to nullptr.
*/
void* ext = nullptr;
};
/** the capabilities of the context object. Some of these values are set at the creation time
* of the context object. Others are updated when speaker positions are set or an output
* device is opened. This is only used to retrieve the capabilities of the context.
*/
struct ContextCaps
{
/** the maximum number of data buses to process simultaneously. This is equivalent to the
* maximum number of potentially audible sounds that could possibly affect the output on the
* speakers. If more voices than this are active, the quietest or furthest voice will be
* deactivated. This value is set at creation time of the context object. This can be
* changed after creation with setBusCount().
*/
size_t maxBuses;
/** the directions of each speaker. Only the speaker directions for the current speaker
* mode will be valid. All other speaker directions will be set to (0, 0, 0). This table
* can be indexed using the Speaker::* names. When a new context is first created or when
* a new device is selected with setOutput(), the speaker layout will always be set to
* the default for that device. The host app must set a new speaker direction layout
* if needed after selecting a new device.
*/
SpeakerDirectionDesc speakerDirections;
/** the info for the connection to the currently selected device.
* If no device is selected, the @a flags member will be set to @ref
* fDeviceFlagNotOpen. If a device is selected, its information will be
* set in here, including its preferred output format.
* Note that the format information may differ from the information
* returned by getDeviceDetails() as this is the format that the audio is
* being processed at before being sent to the device.
*/
DeviceCaps selectedDevice;
/** the output target that is currently in use for the context. This will provide access
* to any streamer objects in use or the index of the currently active output device. The
* device index stored in here will match the one in @ref selectedDevice if a real audio
* device is in use.
*/
OutputDesc output;
/** reserved for future expansion. This must be nullptr. */
void* ext;
};
/** flags that indicate how listener and voice entity objects should be treated and which
* values in the @ref EntityAttributes object are valid. This may be 0 or any combination
* of the fEntityFlag* flags.
* @{
*/
typedef uint32_t EntityAttributeFlags;
/** flags for listener and voice entity attributes. These indicate which entity attributes
* are valid or will be updated, and indicate what processing still needs to be done on them.
*/
/** the @ref EntityAttributes::position vector is valid. */
constexpr EntityAttributeFlags fEntityFlagPosition = 0x00000001;
/** the @ref EntityAttributes::velocity vector is valid. */
constexpr EntityAttributeFlags fEntityFlagVelocity = 0x00000002;
/** the @ref EntityAttributes::forward vector is valid. */
constexpr EntityAttributeFlags fEntityFlagForward = 0x00000004;
/** the @ref EntityAttributes::up vector is valid. */
constexpr EntityAttributeFlags fEntityFlagUp = 0x00000008;
/** the @ref EntityAttributes::cone values are valid. */
constexpr EntityAttributeFlags fEntityFlagCone = 0x00000010;
/** the @ref EmitterAttributes::rolloff values are valid. */
constexpr EntityAttributeFlags fEntityFlagRolloff = 0x00000020;
/** all vectors in the entity information block are valid. */
constexpr EntityAttributeFlags fEntityFlagAll = fEntityFlagPosition | fEntityFlagVelocity | fEntityFlagForward |
fEntityFlagUp | fEntityFlagCone | fEntityFlagRolloff;
/** when set, this flag indicates that setListenerAttributes() or setEmitterAttributes()
* should make the @a forward and @a up vectors perpendicular and normalized before setting
* them as active. This flag should only be used when it is known that the vectors are not
* already perpendicular.
*/
constexpr EntityAttributeFlags fEntityFlagMakePerp = 0x80000000;
/** when set, this flag indicates that setListenerAttributes() or setEmitterAttributes()
* should normalize the @a forward and @a up vectors before setting them as active. This
* flag should only be used when it is known that the vectors are not already normalized.
*/
constexpr EntityAttributeFlags fEntityFlagNormalize = 0x40000000;
/** @} */
/** distance based DSP value rolloff curve types. These represent the formula that will be
* used to calculate the spatial DSP values given the distance between an emitter and the
* listener. This represents the default attenuation calculation that will be performed
* for all curves that are not overridden with custom curves. The default rolloff model
* will follow the inverse square law (ie: @ref RolloffType::eInverse).
*/
enum class RolloffType
{
/** defines an inverse attenuation curve where a distance at the 'near' distance is full
* volume and at the 'far' distance gives silence. This is calculated with a formula
* proportional to (1 / distance).
*/
eInverse,
/** defines a linear attenuation curve where a distance at the 'near' distance is full
* volume and at the 'far' distance gives silence. This is calculated with
* (max - distance) / (max - min).
*/
eLinear,
/** defines a linear square attenuation curve where a distance at the 'near' distance is
* full volume and at the 'far' distance gives silence. This is calculated with
* ((max - distance) / (max - min)) ^ 2.
*/
eLinearSquare,
};
/** defines the point-wise curve that is used for specifying custom rolloff curves.
* This curve is defined as a set of points that are treated as a piece-wise curve where each
* point's X value represents the listener's normalized distance from the emitter, and the Y
* value represents the DSP value at that distance. A linear interpolation is done between
* points on the curve. Any distances beyond the X value on the last point on the curve
* simply use the DSP value for the last point. Similarly, and distances closer than the
* first point simply use the first point's DSP value. This curve should always be normalized
* such that the first point is at a distance of 0.0 (maps to the emitter's 'near' distance)
* and the last point is at a distance of 1.0 (maps to the emitter's 'far' distance). The
* interpretation of the specific DSP values at each point depends on the particular usage
* of the curve. If used, this must contain at least one point.
*/
struct RolloffCurve
{
/** the total number of points on the curve. This is the total number of entries in the
* @ref points table. This must be greater than zero.
*/
size_t pointCount;
/** the table of data points in the curve. Each point's X value represents a normalized
* distance from the emitter to the listener. Each point's Y value is the corresponding
* DSP value to be interpolated at that distance. The points in this table must be sorted
* in increasing order of distance. No two points on the curve may have the same distance
* value. Failure to meet these requirements will result in undefined behavior.
*/
Float2* points;
};
/** descriptor of the rolloff mode, range, and curves to use for an emitter. */
struct RolloffDesc
{
/** the default type of rolloff calculation to use for all DSP values that are not overridden
* by a custom curve. This defaults to @ref RolloffType::eLinear.
*/
RolloffType type;
/** the near distance range for the sound. This is specified in arbitrary world units.
* When a custom curve is used, this near distance will map to a distance of 0.0 on the
* curve. This must be less than the @ref farDistance distance. The near distance is the
* closest distance that the emitter's attributes start to rolloff at. At distances
* closer than this value, the calculated DSP values will always be the same as if they
* were at the near distance. This defaults to 0.0.
*/
float nearDistance;
/** the far distance range for the sound. This is specified in arbitrary world units. When
* a custom curve is used, this far distance will map to a distance of 1.0 on the curve.
* This must be greater than the @ref nearDistance distance. The far distance is the
* furthest distance that the emitters attributes will rolloff at. At distances further
* than this value, the calculated DSP values will always be the same as if they were at
* the far distance (usually silence). Emitters further than this distance will often
* become inactive in the scene since they cannot be heard any more. This defaults to
* 10000.0.
*/
float farDistance;
/** the custom curve used to calculate volume attenuation over distance. This must be a
* normalized curve such that a distance of 0.0 maps to the @ref nearDistance distance
* and a distance of 1.0 maps to the @ref farDistance distance. When specified, this
* overrides the rolloff calculation specified by @ref type when calculating volume
* attenuation. This defaults to nullptr.
*/
RolloffCurve* volume;
/** the custom curve used to calculate low frequency effect volume over distance. This
* must be a normalized curve such that a distance of 0.0 maps to the @ref nearDistance
* distance and a distance of 1.0 maps to the @ref farDistance distance. When specified,
* this overrides the rolloff calculation specified by @ref type when calculating the low
* frequency effect volume. This defaults to nullptr.
*/
RolloffCurve* lowFrequency;
/** the custom curve used to calculate low pass filter parameter on the direct path over
* distance. This must be a normalized curve such that a distance of 0.0 maps to the
* @ref nearDistance distance and a distance of 1.0 maps to the @ref farDistance distance.
* When specified, this overrides the rolloff calculation specified by @ref type when
* calculating the low pass filter parameter. This defaults to nullptr.
*/
RolloffCurve* lowPassDirect;
/** the custom curve used to calculate low pass filter parameter on the reverb path over
* distance. This must be a normalized curve such that a distance of 0.0 maps to the
* @ref nearDistance distance and a distance of 1.0 maps to the @ref farDistance distance.
* When specified, this overrides the rolloff calculation specified by @ref type when
* calculating the low pass filter parameter. This defaults to nullptr.
*/
RolloffCurve* lowPassReverb;
/** the custom curve used to calculate reverb mix level over distance. This must be a
* normalized curve such that a distance of 0.0 maps to the @ref nearDistance distance and
* a distance of 1.0 maps to the @ref farDistance distance. When specified, this overrides
* the rolloff calculation specified by @ref type when calculating the low pass filter
* parameter. This defaults to nullptr.
*/
RolloffCurve* reverb;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** specifies a pair of values that define a DSP value range to be interpolated between based
* on an emitter-listener angle that is between a cone's inner and outer angles. For angles
* that are smaller than the cone's inner angle, the 'inner' DSP value will always be used.
* Similarly, for angles that are larger than the cone's outer angle, the 'outer' DSP value
* will always be used. Interpolation will only occur when the emitter-listener angle is
* between the cone's inner and outer angles. No specific meaning or value range is attached
* to the 'inner' and 'outer' DSP values. These come from the specific purpose that this
* object is used for.
*/
struct DspValuePair
{
/** the DSP value to be used for angles less than the cone's inner angle and as one of
* the interpolation endpoints for angles between the cone's inner and outer angles.
*/
float inner;
/** the DSP value to be used for angles greater than the cone's outer angle and as one of
* the interpolation endpoints for angles between the cone's inner and outer angles.
*/
float outer;
};
/** the angle to specify for @ref EntityCone::insideAngle and @ref EntityCone::outsideAngle
* in order to mark the cone as disabled. This will treat the emitter or listener as
* omni-directional.
*/
constexpr float kConeAngleOmnidirectional = (float)(2.0 * M_PI);
/** defines a sound cone relative to an entity's front vector. It is defined by two angles -
* the inner and outer angles. When the angle between an emitter and the listener (relative
* to the entity's front vector) is smaller than the inner angle, the resulting DSP value
* will be the 'inner' value. When the emitter-listener angle is larger than the outer
* angle, the resulting DSP value will be the 'outer' value. For emitter-listener angles
* that are between the inner and outer angles, the DSP value will be interpolated between
* the inner and outer angles. If a cone is valid for an entity, the @ref fEntityFlagCone
* flag should be set in @ref EntityAttributes::flags.
*
* Note that a cone's effect on the spatial volume of a sound is purely related to the angle
* between the emitter and listener. Any distance attenuation is handled separately.
*/
struct EntityCone
{
/** the inside angle of the entity's sound cone in radians. This describes the angle around
* the entity's forward vector within which the entity's DSP values will always use their
* 'inner' values. This angle will extend half way in all directions around the forward
* vector. For example, a 30 degree (as converted to radians to store here) inside angle
* will extend 15 degrees in all directions around the forward vector. Set this to
* @ref kConeAngleOmnidirectional to define an omni-directional entity. This must be
* greater than or equal to 0 and less than or equal to @ref outsideAngle.
*/
float insideAngle;
/** the outside angle of the entity's sound cone in radians. This describes the angle
* around the entity's forward vector up to which the volume will be interpolated. When
* the emitter-listener angle is larger than this angle, the 'outer' DSP values will always
* be used. This angle will extend half way in all directions around the forward vector.
* For example, a 30 degree (as converted to radians to store here) inside angle will extend
* 15 degrees in all directions around the forward vector. Set this to
* @ref kConeAngleOmnidirectional to define an omni-directional entity. This must be greater
* than or equal to @ref insideAngle.
*/
float outsideAngle;
/** the volumes to use for emitter-listener lines that are inside and outside the entity's
* cone angles. These will be used as the endpoint values to interpolate to for angles
* between the inner and outer angles, and for the values for all angles outside the cone's
* inner and outer angles. These should be in the range 0.0 (silence) to 1.0 (full volume).
*/
DspValuePair volume;
/** the low pass filter parameter values to use for emitter-listener lines that are inside
* and outside the entity's cone angles. These will be used as the endpoint values to
* interpolate to for angles between the inner and outer angles, and for the values for all
* angles outside the cone's inner and outer angles. There is no specific range for these
* values other than what is commonly accepted for low pass filter parameters.
* This multiplies by member `direct` of @ref VoiceParams::occlusion, if
* that is set to anything other than 1.0.
* Setting this to a value outside of [0.0, 1.0] will result in an undefined low pass
* filter value being used.
*/
DspValuePair lowPassFilter;
/** the reverb mix level values to use for emitter-listener lines that are inside and outside
* the entity's cone angles. These will be used as the endpoint values to interpolate to for
* angles between the inner and outer angles, and for the values for all angles outside the
* cone's inner and outer angles. This should be in the range 0.0 (no reverb) to 1.0 (full
* reverb).
*/
DspValuePair reverb;
/** reserved for future expansion. This must be nullptr. */
void* ext = nullptr;
};
/** base spatial attributes of the entity. This includes its position, orientation, and velocity
* and an optional cone.
*/
struct EntityAttributes
{
/** a set of flags that indicate which of members of this struct are valid. This may be
* fEntityFlagAll to indicate that all members contain valid data.
*/
EntityAttributeFlags flags;
/** the current position of the listener in world units. This should only be expressed in
* meters if the world units scale is set to 1.0 for this context. This value is ignored
* if the fEntityFlagPosition flag is not set in @ref flags.
*/
Float3 position;
/** the current velocity of the listener in world units per second. This should only be
* expressed in meters per second if the world units scale is set to 1.0 with
* for the context. The magnitude of this vector will be taken as the listener's
* current speed and the vector's direction will indicate the listener's current direction.
* This vector should not be normalized unless the listener's speed is actually 1.0 units
* per second. This may be a zero vector if the listener is not moving. This value is
* ignored if the fEntityFlagVelocity flag is not set in @ref flags. This vector will
* not be modified in any way before use.
*/
Float3 velocity;
/** a vector indicating the direction the listener is currently facing. This does not need
* to be normalized, but should be for simplicity. If the fEntityFlagNormalize flag is
* set in @ref flags, this vector will be normalized internally before being used. This
* vector should be perpendicular to the @ref up vector unless the fEntityFlagMakePerp
* flag is set in @ref flags. This must not be a zero vector unless the fEntityFlagForward
* flag is not set in @ref flags.
*/
Float3 forward;
/** a vector indicating the upward direction for the listener. This does not need to be
* normalized, but should be for simplicity. If the fEntityFlagNormalize flag is set in
* @ref flags, this vector will be normalized internally before being used. This vector
* should be perpendicular to the @ref forward vector unless the fEntityFlagMakePerp flag
* is set in @ref flags. This must not be a zero vector unless the fEntityFlagUp flag is
* not set in @ref flags.
*/
Float3 up;
/** defines an optional sound cone for an entity. The cone is a segment of a sphere around
* the entity's position opening up toward its front vector. The cone is defined by an
* inner and outer angle, and several DSP values to be interpolated between for those two
* endpoint angles. This cone is valid if the @ref fEntityFlagCone flag is set in
* @ref flags.
*/
EntityCone cone;
};
/** spatial attributes for a listener entity. */
struct ListenerAttributes : EntityAttributes
{
/** provides an extended information block. This is reserved for future expansion and should
* be set to nullptr. The values in @ref flags may be used to indicate how this value should
* be interpreted.
*/
void* ext = nullptr;
};
/** spatial attributes of an emitter entity. */
struct EmitterAttributes : EntityAttributes
{
/** a descriptor of the rolloff parameters for this emitter. This is valid and accessed only
* if the @ref fEntityFlagRolloff flag is set in @ref EntityAttributes::flags. The curves
* (if any) in this descriptor must remain valid for the entire time a voice is playing the
* sound represented by this emitter.
*/
RolloffDesc rolloff;
/** provides an extended information block. This is reserved for future expansion and must
* be set to nullptr. The values in @ref flags may be used to indicate how this value should
* be interpreted.
*/
void* ext = nullptr;
};
/** voice callback reason names. These identify what kind of callback is being performed.
* This can either be an event point or the end of the sound.
*/
enum class VoiceCallbackType
{
/** the sound reached its end and has implicitly stopped. This will not be hit for looping
* sounds until the last loop iteration completes and the sound stops playing. In the
* voice callback for this type, the @a data parameter will be set to nullptr.
*/
eSoundEnded,
/** the engine has reached one of the playing sound's event points. These are arbitrary
* points within the sound that need notification so that other objects in the simulation
* can react to the sound. These event points are often chosen by the sound designers.
* In the voice callback for this type, the @a data parameter will be set to the event
* point object that was triggered.
*/
eEventPoint,
/** the engine has reached a loop point. This callback occurs when the new loop iteration
* starts.
* This will only be triggered on voices that have the @ref fPlayFlagRealtimeCallbacks flag
* set.
* On streaming sounds, these callbacks are triggered when the buffer containing a loop end
* has finished playing, rather than when the loop end is decoded. This is not guaranteed to
* be called exactly on the ending frame of the loop.
* If an excessively short loop (e.g. 2ms) is put on a streaming sound,
* some loop callbacks may be skipped.
*/
eLoopPoint,
};
/** prototype for a voice event callback function.
*
* @param[in] voice the voice object that produced the event callback.
* @param[in] callbackType the type of callback being performed. This can either be that the
* sound ended or that one of its event points was hit.
* @param[in] sound the sound data object that the voice is playing or just finished playing.
* @param[in] data some extra data specific to the callback type that occurred. This will
* be nullptr for @ref VoiceCallbackType::eSoundEnded callbacks. This will
* be the EventPoint information for the event point that was hit for
* @ref VoiceCallbackType::eEventPoint callbacks.
* @param[in] context the context value that was specified at the time the callback function was
* registered with the voice.
* @return @ref AudioResult::eOk. Returning any other value may result in the mixer being halted
* or the playback of the current sound stopping.
*
* @remarks This callback allows a system to receive notifications of events occurring on a sound
* object that is playing on a voice. This callback is performed when either the
* sound finishes playing or when one of its event points is hit. Since this callback
* may be performed in the context of the mixer thread, it should take as little time as
* possible to return. Instead of performing heavy calculations, it should simply set a
* flag that those calculations need to be handled on another worker thread at a later
* time.
*/
typedef AudioResult(CARB_ABI* VoiceCallback)(
Voice* voice, VoiceCallbackType callbackType, SoundData* sound, void* data, void* context);
/** base type for the various playback mode flags. The default state for all these flags
* is false (ie: all flags cleared). These flags are set in @ref VoiceParams::playbackMode
* and are only valid when @ref fVoiceParamPlaybackMode, @ref fVoiceParamPause, or
* @ref fVoiceParamMute are used for the parameter block flags.
*
* @{
*/
typedef uint32_t PlaybackModeFlags;
/** flag to indicate whether a sound should be played back as a spatial or non-spatial
* sound. When false, the sound is played in non-spatial mode. This means that only
* the current explicit volume level and pan values will affect how the sound is mapped
* to the output channels. If true, all spatial positioning calculations will be
* performed for the sound and its current emitter attributes (ie: position, orientation,
* velocity) will affect how it is mapped to the output channels.
*/
constexpr PlaybackModeFlags fPlaybackModeSpatial = 0x00000001;
/** flag to indicate how the spatial attributes of an emitter are to be interpreted.
* When true, the emitter's current position, orientation, and velocity will be added
* to those of the listener object to get the world coordinates for each value. The
* spatial calculations will be performed using these calculated world values instead.
* This is useful for orienting and positioning sounds that are 'attached' to the
* listener's world representation (ie: camera, player character, weapon, etc), but
* still move somewhat relative to the listener. When not set, the emitter's spatial
* attributes will be assumed to be in world coordinates already and just used directly.
*/
constexpr PlaybackModeFlags fPlaybackModeListenerRelative = 0x00000002;
/** flag to indicate whether triggering this sound should be delayed to simulate its
* travel time to reach the listener. The sound's trigger time is considered the time
* of the event that produces the sound at the emitter's current location. For distances
* to the listener that are less than an imperceptible threshold (around 20ms difference
* between the travel times of light and sound), this value will be ignored and the sound
* will just be played immediately. The actual distance for this threshold depends on
* the current speed of sound versus the speed of light. For all simulation purposes, the
* speed of light is considered to be infinite (at ~299700km/s in air, there is no
* terrestrial environment that could contain a larger space than light can travel (or
* that scene be rendered) in even a fraction of a second).
*
* Note that if the distance delay is being used to play a sound on a voice, that voice's
* current frequency ratio will not affect how long it takes for the delay period to expire.
* If the frequency ratio is being used to provide a time dilation effect on the sound rather
* than a pitch change or playback speed change, the initial distance delay period will seem
* to be different than expected because of this. If a time dilation effect is needed, that
* should be done by changing the context's spatial sound frequency ratio instead.
*/
constexpr PlaybackModeFlags fPlaybackModeDistanceDelay = 0x00000004;
/** flag to indicate whether interaural time delay calculations should occur on this
* voice. This will cause the left or right channel(s) of the voice to be delayed
* by a few frames to simulate the difference in time that it takes a sound to reach
* one ear versus the other. These calculations will be performed using the current
* speed of sound for the context and a generalized acoustic model of the human head.
* This will be ignored for non-spatial sounds and sounds with fewer than two channels.
* This needs to be set when the voice is created for it to take effect.
* The performance cost of this effect is minimal when the interaural time
* delay is set to 0.
* For now, interaural time delay will only take effect when the @ref SoundData
* being played is 1 channel and the output device was opened with 2 channels.
* This effect adds a small level of distortion when an emitter's angle is changing
* relative to the listener; this is imperceptible in most audio, but it can be
* audible with pure sine waves.
*/
constexpr PlaybackModeFlags fPlaybackModeInterauralDelay = 0x00000008;
/** flag to indicate whether Doppler calculations should be performed on this sound.
* This is ignored for non-spatial sounds. When true, the Doppler calculations will
* be automatically performed for this voice if it is moving relative to the listener.
* If neither the emitter nor the listener are moving, the Doppler shift will not
* have any affect on the sound. When false, the Doppler calculations will be skipped
* regardless of the relative velocities of this emitter and the listener.
*/
constexpr PlaybackModeFlags fPlaybackModeUseDoppler = 0x00000010;
/** flag to indicate whether this sound is eligible to be sent to a reverb effect. This
* is ignored for non-spatial sounds. When true, the sound playing on this voice will
* be sent to a reverb effect if one is present in the current sound environment. When
* false, the sound playing on this voice will bypass any reverb effects in the current
* sound environment.
*/
constexpr PlaybackModeFlags fPlaybackModeUseReverb = 0x00000020;
/** flag to indicate whether filter parameters should be automatically calculated and
* applied for the sound playing on this voice. The filter parameters can be changed
* by the spatial occlusion factor and interaural time delay calculations.
*/
constexpr PlaybackModeFlags fPlaybackModeUseFilters = 0x00000040;
/** flag to indicate the current mute state for a voice. This is valid only when the
* @ref fVoiceParamMute flag is used. When this flag is set, the voice's output will be
* muted. When this flag is not set, the voice's volume will be restored to its previous
* level. This is useful for temporarily silencing a voice without having to clobber its
* current volume level or affect its emitter attributes.
*/
constexpr PlaybackModeFlags fPlaybackModeMuted = 0x00000080;
/** flag to indicate the current pause state of a sound. This is valid only when the
* @ref fVoiceParamPause flag is used. When this flag is set, the voice's playback is
* paused. When this flag is not set, the voice's playback will resume. Note that if all
* buses are occupied, pausing a voice may allow another voice to steal its bus. When a
* voice is resumed, it will continue playback from the same location it was paused at.
*
* When pausing or unpausing a sound, a small volume ramp will be used internally to avoid
* a popping artifact in the stream. This will not affect the voice's current volume level.
*
* Note that if the voice is on the simulation path and it is paused and unpaused rapidly,
* the simulated position may not be updated properly unless the context's update() function
* is also called at least at the same rate that the voice is paused and unpaused at. This
* can lead to a voice's simulated position not being accurately tracked if care is not also
* taken with the frequency of update() calls.
*/
constexpr PlaybackModeFlags fPlaybackModePaused = 0x00000100;
/** Flag to indicate that the sound should fade in when being initially played.
* This should be used when it's not certain that the sound is starting on a
* zero-crossing, so playing it without a fade-in will cause a pop.
* The fade-in takes 10-20ms, so this isn't suitable for situations where a
* gradual fade-in is desired; that should be done manually using callbacks.
* This flag has no effect after the sound has already started playing;
* actions like unpausing and unmuting will always fade in to avoid a pop.
*/
constexpr PlaybackModeFlags fPlaybackModeFadeIn = 0x00000200;
/** Flags to indicate the behavior that is used when a simulated voice gets assigned
* to a bus.
*
* @ref fPlaybackModeSimulatePosition will cause the voice's playback position to
* be simulated during update() calls while the voice is not assigned to a bus.
* When the voice is assigned to a bus, it will begin at that simulated
* position. For example if a sound had its bus stolen then was assigned to a
* bus 2 seconds later, the sound would begin playback at the position 2
* seconds after the position it was when the bus was stolen.
* Voices are faded in from silence when the beginning playback part way
* through to avoid discontinuities.
* Additionally, voices that have finished playback while in the simulated state
* will be cleaned up automatically.
*
* @ref fPlaybackModeNoPositionSimulation will cause a simulated voice to begin
* playing from the start of its sound when it is assigned to a bus.
* Any voice with this setting will not finish when being simulated unless stopVoice()
* is called.
* This is intended for uses cases such as infinitely looping ambient noise
* (e.g. a burning torch); cases where a sound will not play infinitely may
* sound strange when this option is used.
* This option reduces the calculation overhead of update().
* This behavior will be used for sounds that are infinitely looping if neither
* of @ref fPlaybackModeSimulatePosition or @ref fPlaybackModeNoPositionSimulation
* are specified.
*
* If neither of @ref fPlaybackModeSimulatePosition nor
* @ref fPlaybackModeNoPositionSimulation are specified, the default behavior
* will be used. Infinitely looping sounds have the default behavior of
* @ref fPlaybackModeNoPositionSimulation and sounds with no loop or a finite
* loop count will use @ref fPlaybackModeSimulatePosition.
*
* When retrieving the playback mode from a playing voice, exactly one of
* these bits will always be set. Trying to update the playback mode to have
* both of these bits clear or both of these bits set will result in the
* previous value of these two bits being preserved in the playback mode.
*/
constexpr PlaybackModeFlags fPlaybackModeSimulatePosition = 0x00000400;
/** @copydoc fPlaybackModeSimulatePosition */
constexpr PlaybackModeFlags fPlaybackModeNoPositionSimulation = 0x00000800;
/** flag to indicate that a multi-channel spatial voice should treat a specific matrix as its
* non-spatial output, when using the 'spatial mix level' parameter, rather than blending all
* channels evenly into the output. The matrix used will be the one specified by the voice
* parameters. If no matrix was specified in the voice parameters, the default matrix for
* that channel combination will be used. If there is no default matrix for that channel
* combination, the default behavior of blending all channels evenly into the output will be used.
* This flag is ignored on non-spatial voices, since they cannot use the 'spatial mix level'
* parameter.
* This flag is also ignored on mono voices.
* This should be used with caution as the non-spatial mixing matrix may add a direction to each
* channel (the default ones do this), which could make the spatial audio sound very strange.
* Additionally, the default mixing matrices will often be quieter than the fully spatial sound
* so this may sound unexpected
* (this is because the default matrices ensure no destination channel has more than 1.0 volume,
* while the spatial calculations are treated as multiple emitters at the same point in
* space).
* The default behavior of mixing all channels evenly is intended to make the sound become
* omni-present which is the intended use case for this feature.
*/
constexpr PlaybackModeFlags fPlaybackModeSpatialMixLevelMatrix = 0x00001000;
/** flag to disable the low frequency effect channel (@ref Speaker::eLowFrequencyEffect)
* for a spatial voice. By default, some component of the 3D audio will be mixed into
* the low frequency effect channel; setting this flag will result in none of the audio
* being mixed into this channel.
* This flag may be desirable in cases where spatial sounds have a specially mastered
* low frequency effect channel that will be played separately.
* This has no effect on a non-spatial voice; disabling the low frequency
* effect channel on a non-spatial voice can be done through by setting its
* mixing matrix.
*/
constexpr PlaybackModeFlags fPlaybackModeNoSpatialLowFrequencyEffect = 0x00002000;
/** flag to indicate that a voice should be immediately stopped if it ever gets unassigned from
* its bus and put on the simulation path. This will also fail calls to playSound() if the
* voice is immediately put on the simulation path. The default behavior is that voices will
* be able to go into simulation mode.
*/
constexpr PlaybackModeFlags fPlaybackModeStopOnSimulation = 0x00004000;
/** mask of playback mode bits that are available for public use. Clear bits in this mask are
* used internally and should not be referenced in other flags here. This is not valid as a
* playback mode flag or flag set.
*/
constexpr PlaybackModeFlags fPlaybackModeAvailableMask = 0x7fffffff;
/** default playback mode flag states. These flags allow the context's default playback mode
* for selected playback modes to be used instead of always having to explicitly specify various
* playback modes for each new play task. Note that these flags only take effect when a sound
* is first played on a voice, or when update() is called after changing a voice's default
* playback mode state. Changing the context's default playback mode settings will not take
* effect on voices that are already playing.
*
* When these flags are used in the VoiceParams::playbackMode flag set in a PlaySoundDesc
* descriptor or a setVoiceParameters() call, these will take the state for their corresponding
* non-default flags from the context's default playback mode state value and ignore the flags
* specified for the voice's parameter itself.
*
* When these flags are used in the ContextParams::playbackMode flag set, they can be used
* to indicate a 'force off', 'force on', or absolute state for the value. When used, the
* 'force' states will cause the feature to be temporarily disabled or enabled on all playing
* buses on the next update cycle. Using these forced states will not change the playback
* mode settings of each individual playing voice, but simply override them. When the force
* flag is removed from the context, each voice's previous behavior will resume (on the next
* update cycle). When these are used as an absolute state, they determine what the context's
* default playback mode for each flag will be.
*
* Note that for efficiency's sake, if both 'force on' and 'force off' flags are specified
* for any given state, the 'force off' flag will always take precedence. It is up to the
* host app to ensure that conflicting flags are not specified simultaneously.
*
* @{
*/
/** when used in a voice parameters playback mode flag set, this indicates that new voices will
* always use the context's current default Doppler playback mode flag and ignore any specific
* flag set on the voice parameters. When used on the context's default playback mode flag set,
* this indicates that the context's default Doppler mode is enabled.
*/
constexpr PlaybackModeFlags fPlaybackModeDefaultUseDoppler = 0x40000000;
/** when used in a voice parameters playback mode flag set, this indicates that new voices will
* always use the context's current default distance delay playback mode flag and ignore any
* specific flag set on the voice parameters. When used on the context's default playback mode
* flag set, this indicates that the context's default distance delay mode is enabled.
*/
constexpr PlaybackModeFlags fPlaybackModeDefaultDistanceDelay = 0x20000000;
/** when used in a voice parameters playback mode flag set, this indicates that new voices will
* always use the context's current default interaural time delay playback mode flag and ignore
* any specific flag set on the voice parameters. When used on the context's default playback
* mode flag set, this indicates that the context's default interaural time delay mode is
* enabled.
*/
constexpr PlaybackModeFlags fPlaybackModeDefaultInterauralDelay = 0x10000000;
/** when used in a voice parameters playback mode flag set, this indicates that new voices will
* always use the context's current default reverb playback mode flag and ignore any specific
* flag set on the voice parameters. When used on the context's default playback mode flag set,
* this indicates that the context's default reverb mode is enabled.
*/
constexpr PlaybackModeFlags fPlaybackModeDefaultUseReverb = 0x08000000;
/** when used in a voice parameters playback mode flag set, this indicates that new voices will
* always use the context's current default filters playback mode flag and ignore any specific
* flag set on the voice parameters. When used on the context's default playback mode flag set,
* this indicates that the context's default filters mode is enabled.
*/
constexpr PlaybackModeFlags fPlaybackModeDefaultUseFilters = 0x04000000;
/** the mask of all 'default' state playback mode flags. If new flags are added above,
* they must be added here as well.
*/
constexpr PlaybackModeFlags fPlaybackModeDefaultMask =
fPlaybackModeDefaultUseDoppler | fPlaybackModeDefaultDistanceDelay | fPlaybackModeDefaultInterauralDelay |
fPlaybackModeDefaultUseReverb | fPlaybackModeDefaultUseFilters;
/** the maximum number of 'default' state playback mode flags. If new flags are added above,
* their count may not exceed this value otherwise the playback mode flags will run out of
* bits.
*/
constexpr size_t kPlaybackModeDefaultFlagCount = 10;
// FIXME: exhale can't handle this
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/** retrieves a set of default playback mode flags that will behave as 'force off' behavior.
*
* @param[in] flags the set of fPlaybackModeDefault* flags to use as 'force off' flags.
* @returns the corresponding 'force off' flags for the input flags. These are suitable
* for setting in the context parameters' default playback mode value. These
* should not be used in the voice parameter block's playback mode value - this
* will lead to unexpected behavior.
*/
constexpr PlaybackModeFlags getForceOffPlaybackModeFlags(PlaybackModeFlags flags)
{
return (flags & fPlaybackModeDefaultMask) >> kPlaybackModeDefaultFlagCount;
}
/** retrieves a set of default playback mode flags that will behave as 'force on' behavior.
*
* @param[in] flags the set of fPlaybackModeDefault* flags to use as 'force on' flags.
* @returns the corresponding 'force on' flags for the input flags. These are suitable
* for setting in the context parameters' default playback mode value. These
* should not be used in the voice parameter block's playback mode value - this
* will lead to unexpected behavior.
*/
constexpr PlaybackModeFlags getForceOnPlaybackModeFlags(PlaybackModeFlags flags)
{
return (flags & fPlaybackModeDefaultMask) >> (kPlaybackModeDefaultFlagCount * 2);
}
#endif
/** @} */
/** @} */
/** base type for the voice parameter flags. These flags describe the set of parameters in the
* @ref VoiceParams structure that are valid for an operation. For setting operations, the
* caller is responsible for ensuring that all flagged values are valid in the @ref VoiceParams
* structure before calling. For getting operations, the flagged values will be valid upon
* return.
* @{
*/
typedef uint32_t VoiceParamFlags;
/** all parameters are valid. */
constexpr VoiceParamFlags fVoiceParamAll = static_cast<VoiceParamFlags>(~0);
/** when set, this flag indicates that the @ref VoiceParams::playbackMode value is valid. This
* does not however include the @ref fPlaybackModeMuted and @ref fPlaybackModePaused states in
* @ref VoiceParams::playbackMode unless the @ref fVoiceParamMute or @ref fVoiceParamPause
* flags are also set.
*/
constexpr VoiceParamFlags fVoiceParamPlaybackMode = 0x00000001;
/** when set, this flag indicates that the @ref VoiceParams::volume value is valid. */
constexpr VoiceParamFlags fVoiceParamVolume = 0x00000002;
/** when set, this flag indicates that the state of the @ref fPlaybackModeMuted flag is valid
* in the @ref VoiceParams::playbackMode flag set.
*/
constexpr VoiceParamFlags fVoiceParamMute = 0x00000004;
/** when set, this flag indicates that the @ref VoiceParams::balance values are valid. */
constexpr VoiceParamFlags fVoiceParamBalance = 0x00000008;
/** when set, this flag indicates that the @ref VoiceParams::frequencyRatio value is valid. */
constexpr VoiceParamFlags fVoiceParamFrequencyRatio = 0x00000010;
/** when set, this flag indicates that the @ref VoiceParams::priority value is valid. */
constexpr VoiceParamFlags fVoiceParamPriority = 0x00000020;
/** when set, this flag indicates that the state of the @ref fPlaybackModePaused flag is valid
* in the @ref VoiceParams::playbackMode flag set.
*/
constexpr VoiceParamFlags fVoiceParamPause = 0x00000040;
/** when set, this flag indicates that the @ref VoiceParams::spatialMixLevel value is valid. */
constexpr VoiceParamFlags fVoiceParamSpatialMixLevel = 0x00000080;
/** when set, this flag indicates that the @ref VoiceParams::dopplerScale value is valid. */
constexpr VoiceParamFlags fVoiceParamDopplerScale = 0x00000100;
/** when set, this flag indicates that the @ref VoiceParams::occlusion values are valid. */
constexpr VoiceParamFlags fVoiceParamOcclusionFactor = 0x00000200;
/** when set, this flag indicates that the @ref VoiceParams::emitter values are valid. */
constexpr VoiceParamFlags fVoiceParamEmitter = 0x00000400;
/** when set, this flag indicates that the @ref VoiceParams::matrix values are valid. */
constexpr VoiceParamFlags fVoiceParamMatrix = 0x00000800;
/** @} */
/** voice parameters block. This can potentially contain all of a voice's parameters and their
* current values. This is used to both set and retrieve one or more of a voice's parameters
* in a single call. The fVoiceParam* flags that are passed to setVoiceParameters() or
* getVoiceParameters() determine which values in this block are guaranteed to be valid.
*/
struct VoiceParams
{
/** flags to indicate how a sound is to be played back. These values is valid only when the
* @ref fVoiceParamPlaybackMode, @ref fVoiceParamMute, or @ref fVoiceParamPause flags are
* used. This controls whether the sound is played as a spatial or non-spatial sound and
* how the emitter's attributes will be interpreted (ie: either world coordinates or
* listener relative).
*/
PlaybackModeFlags playbackMode;
/** the volume level for the voice. This is valid when the @ref fVoiceParamVolume flag is
* used. This should be 0.0 for silence or 1.0 for normal volume. A negative value may be
* used to invert the signal. A value greater than 1.0 will amplify the signal. The volume
* level can be interpreted as a linear scale where a value of 0.5 is half volume and 2.0 is
* double volume. Any volume values in decibels must first be converted to a linear volume
* scale before setting this value. The default value is 1.0.
*/
float volume;
/** non-spatial sound positioning parameters. These provide pan and fade values for the
* voice to give the impression that the sound is located closer to one of the quadrants
* of the acoustic space versus the others. These values are ignored for spatial sounds.
*/
struct VoiceParamBalance
{
/** sets the non-spatial panning value for a voice. This value is valid when the
* @ref fVoiceParamBalance flag is used. This is 0.0 to have the sound "centered" in all
* speakers. This is -1.0 to have the sound balanced to the left side. This is 1.0 to
* have the sound balanced to the right side. The way the sound is balanced depends on
* the number of channels. For example, a mono sound will be balanced between the left
* and right sides according to the panning value, but a stereo sound will just have the
* left or right channels' volumes turned down according to the panning value. This
* value is ignored for spatial sounds. The default value is 0.0.
*
* Note that panning on non-spatial sounds should only be used for mono or stereo sounds.
* When it is applied to sounds with more channels, the results are often undefined or
* may sound odd.
*/
float pan;
/** sets the non-spatial fade value for a voice. This value is valid when the
* @ref fVoiceParamBalance flag is used. This is 0.0 to have the sound "centered" in all
* speakers. This is -1.0 to have the sound balanced to the back side. This is 1.0 to
* have the sound balanced to the front side. The way the sound is balanced depends on
* the number of channels. For example, a mono sound will be balanced between the front
* and back speakers according to the fade value, but a 5.1 sound will just have the
* front or back channels' volumes turned down according to the fade value. This value
* is ignored for spatial sounds. The default value is 0.0.
*
* Note that using fade on non-spatial sounds should only be used for mono or stereo
* sounds. When it is applied to sounds with more channels, the results are often
* undefined or may sound odd.
*/
float fade;
} balance; //!< Non-spatial sound positioning parameters.
/** the frequency ratio for a voice. This is valid when the @ref fVoiceParamFrequencyRatio
* flag is used. This will be 1.0 to play back a sound at its normal rate, a value less than
* 1.0 to lower the pitch and play it back more slowly, and a value higher than 1.0 to
* increase the pitch and play it back faster. For example, a pitch scale of 0.5 will play
* back at half the pitch (ie: lower frequency, takes twice the time to play versus normal),
* and a pitch scale of 2.0 will play back at double the pitch (ie: higher frequency, takes
* half the time to play versus normal). The default value is 1.0.
*
* On some platforms, the frequency ratio may be silently clamped to an acceptable range
* internally. For example, a value of 0.0 is not allowed. This will be clamped to the
* minimum supported value instead.
*
* Note that the even though the frequency ratio *can* be set to any value in the range from
* 1/1024 to 1024, this very large range should only be used in cases where it is well known
* that the particular sound being operated on will still sound valid after the change. In
* the real world, some of these extreme frequency ratios may make sense, but in the digital
* world, extreme frequency ratios can result in audio corruption or even silence. This
* happens because the new frequency falls outside of the range that is faithfully
* representable by either the audio device or sound data itself. For example, a 4KHz tone
* being played at a frequency ratio larger than 6.0 will be above the maximum representable
* frequency for a 48KHz device or sound file. This case will result in a form of corruption
* known as aliasing, where the frequency components above the maximum representable
* frequency will become audio artifacts. Similarly, an 800Hz tone being played at a
* frequency ratio smaller than 1/40 will be inaudible because it falls below the frequency
* range of the human ear.
*
* In general, most use cases will find that the frequency ratio range of [0.1, 10] is more
* than sufficient for their needs. Further, for many cases, the range from [0.2, 4] would
* suffice. Care should be taken to appropriately cap the used range for this value.
*/
float frequencyRatio;
/** the playback priority of this voice. This is valid when the @ref fVoiceParamPriority
* flag is used. This is an arbitrary value whose scale is defined by the host app. A
* value of 0 is the default priority. Negative values indicate lower priorities and
* positive values indicate higher priorities. This priority value helps to determine
* which voices are the most important to be audible at any given time. When all buses
* are busy, this value will be used to compare against other playing voices to see if
* it should steal a bus from another lower priority sound or if it can wait until another
* bus finishes first. Higher priority sounds will be ensured a bus to play on over lower
* priority sounds. If multiple sounds have the same priority levels, the louder sound(s)
* will take priority. When a higher priority sound is queued, it will try to steal a bus
* from the quietest sound with lower or equal priority.
*/
int32_t priority;
/** the spatial mix level. This is valid when @ref fVoiceParamSpatialMixLevel flag is used.
* This controls the mix between the results of a voice's spatial sound calculations and its
* non-spatial calculations. When this is set to 1.0, only the spatial sound calculations
* will affect the voice's playback. This is the default when state. When set to 0.0, only
* the non-spatial sound calculations will affect the voice's playback. When set to a value
* between 0.0 and 1.0, the results of the spatial and non-spatial sound calculations will
* be mixed with the weighting according to this value. This value will be ignored if
* @ref fPlaybackModeSpatial is not set. The default value is 1.0.
* Values above 1.0 will be treated as 1.0. Values below 0.0 will be treated as 0.0.
*
* @ref fPlaybackModeSpatialMixLevelMatrix affects the non-spatial mixing behavior of this
* parameter for multi-channel voices. By default, a multi-channel spatial voice's non-spatial
* component will treat each channel as a separate mono voice. With the
* @ref fPlaybackModeSpatialMixLevelMatrix flag set, the non-spatial component will be set
* with the specified output matrix or the default output matrix.
*/
float spatialMixLevel;
/** the Doppler scale value. This is valid when the @ref fVoiceParamDopplerScale flag is
* used. This allows the result of internal Doppler calculations to be scaled to emulate
* a time warping effect. This should be near 0.0 to greatly reduce the effect of the
* Doppler calculations, and up to 5.0 to exaggerate the Doppler effect. A value of 1.0
* will leave the calculated Doppler factors unmodified. The default value is 1.0.
*/
float dopplerScale;
/** the occlusion factors for a voice. This is valid when the @ref fVoiceParamOcclusionFactor
* flag is used. These values control automatic low pass filters that get applied to the
* spatial sounds to simulate object occlusion between the emitter and listener positions.
*/
struct VoiceParamOcclusion
{
/** the occlusion factor for the direct path of the sound. This is the path directly from
* the emitter to the listener. This factor describes how occluded the sound's path
* actually is. A value of 1.0 means that the sound is fully occluded by an object
* between the voice and the listener. A value of 0.0 means that the sound is not
* occluded by any object at all. This defaults to 0.0.
* This factor multiplies by @ref EntityCone::lowPassFilter, if a cone with a non 1.0
* lowPassFilter value is specified.
* Setting this to a value outside of [0.0, 1.0] will result in an undefined low pass
* filter value being used.
*/
float direct;
/** the occlusion factor for the reverb path of the sound. This is the path taken for
* sounds reflecting back to the listener after hitting a wall or other object. A value
* of 1.0 means that the sound is fully occluded by an object between the listener and
* the object that the sound reflected off of. A value of 0.0 means that the sound is
* not occluded by any object at all. This defaults to 1.0.
*/
float reverb;
} occlusion; //!< Occlusion factors for a voice.
/** the attributes of the emitter related for this voice. This is only valid when the
* @ref fVoiceParamEmitter flag is used. This includes the emitter's position, orientation,
* velocity, cone, and rolloff curves. The default values for these attributes are noted
* in the @ref EmitterAttributes object. This will be ignored for non-spatial sounds.
*/
EmitterAttributes emitter;
/** the channel mixing matrix to use for this @ref Voice. The rows of this matrix represent
* each output channel from this @ref Voice and the columns of this matrix represent the
* input channels of this @ref Voice (e.g. this is a inputChannels x outputChannels matrix).
* The output channel count will always be the number of audio channels set on the
* @ref Context.
* Each cell in the matrix should be a value from 0.0-1.0 to specify the volume that
* this input channel should be mixed into the output channel. Setting negative values
* will invert the signal. Setting values above 1.0 will amplify the signal past unity
* gain when being mixed.
*
* This setting is mutually exclusive with @ref balance; setting one will disable the
* other.
* This setting is only available for spatial sounds if @ref fPlaybackModeSpatialMixLevelMatrix
* if set in the playback mode parameter. Multi-channel spatial audio is interpreted as
* multiple emitters existing at the same point in space, so a purely spatial voice cannot
* have an output matrix specified.
*
* Setting this to nullptr will reset the matrix to the default for the given channel
* count.
* The following table shows the speaker modes that are used for the default output
* matrices. Voices with a speaker mode that is not in the following table will
* use the default output matrix for the speaker mode in the following table that
* has the same number of channels.
* If there is no default matrix for the channel count of the @ref Voice, the output
* matrix will have 1.0 in the any cell (i, j) where i == j and 0.0 in all other cells.
*
* | Channels | Speaker Mode |
* | -------- | ---------------------------------- |
* | 1 | kSpeakerModeMono |
* | 2 | kSpeakerModeStereo |
* | 3 | kSpeakerModeTwoPointOne |
* | 4 | kSpeakerModeQuad |
* | 5 | kSpeakerModeFourPointOne |
* | 6 | kSpeakerModeFivePointOne |
* | 7 | kSpeakerModeSixPointOne |
* | 8 | kSpeakerModeSevenPointOne |
* | 10 | kSpeakerModeNinePointOne |
* | 12 | kSpeakerModeSevenPointOnePointFour |
* | 14 | kSpeakerModeNinePointOnePointFour |
* | 16 | kSpeakerModeNinePointOnePointSix |
*
* It is recommended to explicitly set an output matrix on a non-spatial @ref Voice
* if the @ref Voice or the @ref Context have a speaker layout that is not found in
* the above table.
*/
const float* matrix;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** base type for the context parameter flags. These flags describe the set of parameters in the
* @ref ContextParams structure that are valid for an operation. For setting operations, the
* caller is responsible for ensuring that all flagged values are valid in the @ref ContextParams
* structure before calling. For getting operations, the flagged values will be valid upon
* return.
* @{
*/
using ContextParamFlags = uint32_t;
/** all parameters are valid. */
constexpr ContextParamFlags fContextParamAll = ~0u;
/** when set, this flag indicates that the @ref ContextParams::speedOfSound value is valid. */
constexpr ContextParamFlags fContextParamSpeedOfSound = 0x00000001;
/** when set, this flag indicates that the @ref ContextParams::unitsPerMeter value is valid. */
constexpr ContextParamFlags fContextParamWorldUnitScale = 0x00000002;
/** when set, this flag indicates that the @ref ContextParams::listener values are valid. */
constexpr ContextParamFlags fContextParamListener = 0x00000004;
/** when set, this flag indicates that the @ref ContextParams::dopplerScale value is valid. */
constexpr ContextParamFlags fContextParamDopplerScale = 0x00000008;
/** when set, this flag indicates that the @ref ContextParams::virtualizationThreshold value
* is valid.
*/
constexpr ContextParamFlags fContextParamVirtualizationThreshold = 0x00000010;
/** when set, this flag indicates that the @ref ContextParams::spatialFrequencyRatio value
* is valid.
*/
constexpr ContextParamFlags fContextParamSpatialFrequencyRatio = 0x00000020;
/** when set, this flag indicates that the @ref ContextParams::nonSpatialFrequencyRatio value
* is valid.
*/
constexpr ContextParamFlags fContextParamNonSpatialFrequencyRatio = 0x00000040;
/** when set, this flag indicates that the @ref ContextParams::masterVolume value is valid. */
constexpr ContextParamFlags fContextParamMasterVolume = 0x00000080;
/** when set, this flag indicates that the @ref ContextParams::spatialVolume value is valid. */
constexpr ContextParamFlags fContextParamSpatialVolume = 0x00000100;
/** when set, this flag indicates that the @ref ContextParams::nonSpatialVolume value is valid. */
constexpr ContextParamFlags fContextParamNonSpatialVolume = 0x00000200;
/** when set, this flag indicates that the @ref ContextParams::dopplerLimit value is valid. */
constexpr ContextParamFlags fContextParamDopplerLimit = 0x00000400;
/** when set, this flag indicates that the @ref ContextParams::defaultPlaybackMode value is valid. */
constexpr ContextParamFlags fContextParamDefaultPlaybackMode = 0x00000800;
/** when set, this flag indicates that the @ref ContextParams::flags value is valid. */
constexpr ContextParamFlags fContextParamFlags = 0x00001000;
/** When set, this flag indicates that the @ref ContextParams2::videoLatency and
* @ref ContextParams2::videoLatencyTrim values are valid. In this case, the
* @ref ContextParams::ext value must be set to point to a @ref ContextParams2
* object.
*/
constexpr ContextParamFlags fContextParamVideoLatency = 0x00002000;
/** flag to indicate that voice table validation should be performed any time a voice is allocated
* or recycled. There is a performance cost to enabling this. Any operation involving a new
* voice or recycling a voice will become O(n^2). This flag is ignored in release builds.
* When this flag is not used, no voice validation will be performed.
*/
constexpr ContextParamFlags fContextParamFlagValidateVoiceTable = 0x10000000;
/** @} */
/** The default speed of sound parameter for a Context.
* This is specified in meters per second.
* This is the approximate speed of sound in air at sea level at 15 degrees Celsius.
*/
constexpr float kDefaultSpeedOfSound = 340.f;
/** context parameters block. This can potentially contain all of a context's parameters and
* their current values. This is used to both set and retrieve one or more of a context's
* parameters in a single call. The set of fContextParam* flags that are passed to
* getContextParameter() or setContextParameter() indicates which values in the block are
* guaranteed to be valid.
*/
struct ContextParams
{
/** the speed of sound for the context. This is valid when the @ref fContextParamSpeedOfSound
* flag is used. This is measured in meters per second. This will affect the calculation of
* Doppler shift factors and interaural time difference for spatial voices. The default
* value is @ref kDefaultSpeedOfSound m/s.
* This value can be changed at any time to affect Doppler calculations globally. This should
* only change when the sound environment itself changes (ie: move from air into water).
*/
float speedOfSound;
/** the number of arbitrary world units per meter. This is valid when the
* @ref fContextParamWorldUnitScale flag is used. World units are arbitrary and often
* determined by the level/world designers. For example, if the world units are in feet,
* this value would need to be set to 3.28. All spatial audio calculations are performed in
* SI units (ie: meters for distance, seconds for time). This provides a conversion factor
* from arbitrary world distance units to SI units. This conversion factor will affect all
* audio distance and velocity calculations. This defaults to 1.0, indicating that the world
* units are assumed to be measured in meters. This must not be 0.0 or negative.
*/
float unitsPerMeter;
/** the global Doppler scale value for this context. This is applied to all calculated
* Doppler factors to enhance or diminish the effect of the Doppler factor. A value of
* 1.0 will leave the calculated Doppler levels unmodified. A value lower than 1.0 will
* have the result of diminishing the Doppler effect. A value higher than 1.0 will have
* the effect of enhancing the Doppler effect. This is useful for handling global time
* warping effects. This parameter is a unit less scaling factor. This defaults to 1.0.
*/
float dopplerScale;
/** the global Doppler limit value for this context. This will cap the calculated Doppler
* factor at the high end. This is to avoid excessive aliasing effects for very fast moving
* emitters or listener. When the relative velocity between the listener and an emitter is
* nearing the speed of sound, the calculated Doppler factor can approach ~11 million.
* Accurately simulating this would require a very large scale anti-aliasing or filtering pass
* on all resampling operations on the emitter. That is unfortunately not possible in
* general. Clamping the Doppler factor to something relatively small like 16 will still
* result in the effect being heard but will reduce the resampling artifacts related to high
* frequency ratios. A Doppler factor of 16 represents a relative velocity of ~94% the speed
* of sound so there shouldn't be too much of a loss in the frequency change simulation.
* This defaults to 16. This should not be negative or zero.
*/
float dopplerLimit;
/** the effective volume level at which a voice will become virtual. A virtual voice will
* not decode any data and will perform only minimal update tasks when needed. This
* is expressed as a linear volume value from 0.0 (silence) to 1.0 (full volume). The
* default volume is 0.0.
*/
float virtualizationThreshold;
/** the global frequency ratio to apply to all active spatial voices. This should only be
* used to handle time dilation effects on the voices, not to deal with pitch changes (ie:
* record a sound at a high frequency to save on storage space and load time, but then always
* play it back at a reduced pitch). If this is used for pitch changes, it will interfere
* with distance delay calculations and possibly lead to other undesirable behavior.
* This will not affect any non-spatial voices. This defaults to 1.0.
*/
float spatialFrequencyRatio;
/** the global frequency ratio to apply to all active non-spatial voices. This can be used
* to perform a pitch change (and as a result play time change) on all non-spatial voices,
* or it can be used to simulate a time dilation effect on all non-spatial voices. This
* will not affect any spatial voices. This defaults to 1.0.
*/
float nonSpatialFrequencyRatio;
/** the global master volume for this context. This will only affect the volume level of
* the final mixed output signal. It will not directly affect the relative volumes of
* each voice being played. No individual voice will be able to produce a signal louder
* than this volume level. This is set to 0.0 to silence all output. This defaults to
* 1.0 (ie: full volume). This should not be set beyond 1.0.
*/
float masterVolume;
/** the relative volume of all spatial voices. This will be the initial volume level of
* any new spatial voice. The volume specified in that voice's parameters will be multiplied
* by this volume. This does not affect the volume level of non-spatial voices. This is
* set to 0.0 to silence all spatial voices. This defaults to 1.0 (ie: full volume). This
* should not be set beyond 1.0. This volume is independent of the @ref masterVolume value
* but will effectively be multiplied by it for the final output.
*/
float spatialVolume;
/** the relative volume of all non-spatial voices. This will be the initial volume level of
* any new non-spatial voice. The volume specified in that voice's parameters will be
* multiplied by this volume. This does not affect the volume level of spatial voices. This
* is set to 0.0 to silence all non-spatial voices. This defaults to 1.0 (ie: full volume).
* This should not be set beyond 1.0. This volume is independent of the @ref masterVolume
* value but will effectively be multiplied by it for the final output.
*/
float nonSpatialVolume;
/** attributes of the listener. This is valid when the @ref fContextParamListener flag is
* used. Only the values that have their corresponding fEntityFlag* flags set will be
* updated on a set operation. Any values that do not have their corresponding flag set
* will just be ignored and the previous value will remain current. This can be used to (for
* example) only update the position for the listener but leave its orientation and velocity
* unchanged. The flags would also indicate whether the orientation vectors need to be
* normalized or made perpendicular before continuing. Fixing up these orientation vectors
* should only be left up to this call if it is well known that the vectors are not already
* correct.
*
* It is the caller's responsibility to decide on the listener's appropriate position and
* orientation for any given situation. For example, if the listener is represented by a
* third person character, it would make the most sense to set the position to the
* character's head position, but to keep the orientation relative to the camera's forward
* and up vectors (possibly have the camera's forward vector projected onto the character's
* forward vector). If the character's orientation were used instead, the audio may jump
* from one speaker to another as the character rotates relative to the camera.
*/
ListenerAttributes listener;
/** defines the default playback mode flags for the context. These will provide 'default'
* behavior for new voices. Any new voice that uses the fPlaybackModeDefault* flags in
* its voice parameters block will inherit the default playback mode behavior from this
* value. Note that only specific playback modes are supported in these defaults. This
* also provides a means to either 'force on' or 'force off' certain features for each
* voice. This value is a collection of zero or more of the fPlaybackModeDefault* flags,
* and flags that have been returned from either getForceOffPlaybackModeFlags() or
* getForceOnPlaybackModeFlags(). This may not include any of the other fPlaybackMode*
* flags that are not part of the fPlaybackModeDefault* set. If the other playback mode
* flags are used, the results will be undefined. This defaults to 0.
*/
PlaybackModeFlags defaultPlaybackMode;
/** flags to control the behavior of the context. This is zero or more of the
* @ref ContextParamFlags flags. This defaults to 0.
*/
ContextParamFlags flags;
/** Reserved for future expansion. This must be set to nullptr unless a @ref ContextParams2
* object is also being passed in.
*/
void* ext = nullptr;
};
/** Extended context parameters descriptor object. This provides additional context parameters
* that were not present in the original version of @ref ContextParams. This structure also
* has room for future expansion.
*/
struct ContextParams2
{
/** An estimate of the current level of latency between when a video frame is produced
* and when it will be displayed to the screen. In cases where a related renderer is
* buffering frames (ie: double or triple buffering frames in flight), there can be
* a latency build-up between when a video frame is displayed on screen and when sounds
* related to that particular image should start playing. This latency is related to
* the frame buffering count from the renderer and the current video frame rate. Since
* the video framerate can vary at runtime, this value could be updated frequently with
* new estimates based on the current video frame rate.
*
* This value is measured in microseconds and is intended to be an estimate of the current
* latency level between video frame production and display. This will be used by the
* playback context to delay the start of new voices by approximately this amount of time.
* This should be used to allow the voices to be delayed until a time where it is more
* likely that a related video frame is visible on screen. If this is set to 0 (the
* default), all newly queued voices will be scheduled to start playing as soon as possible.
*
* The carb::audio::estimateVideoLatency() helper function can be used to help calculate
* this latency estimate. Negative values are not allowed.
*/
int64_t videoLatency = 0;
/** An additional user specified video latency value that can be used to adjust the
* value specified in @ref videoLatency by a constant amount. This is expressed in
* microseconds. This could for example be exposed to user settings to allow user-level
* adjustment of audio/video sync or it could be a per-application tuned value to tweak
* audio/video sync. This defaults to 0 microseconds. Negative values are allowed if
* needed as long as @ref videoLatency plus this value is still positive. The total
* latency will always be silently clamped to 0 as needed.
*/
int64_t videoLatencyTrim = 0;
/** Extra padding space reserved for future expansion. Do not use this value directly.
* In future versions, new context parameters will be borrowed from this buffer and given
* proper names and types as needed. When this padding buffer is exhausted, a new
* @a ContextParams3 object will be added that can be chained to this one.
*/
void* padding[32] = {};
/** Reserved for future expansion. This must be set to `nullptr`. */
void* ext = nullptr;
};
/** special value for @ref LoopPointDesc::loopPointIndex that indicates no loop point will be
* used. This will be overridden if the @ref LoopPointDesc::loopPoint value is non-nullptr.
*/
constexpr size_t kLoopDescNoLoop = ~0ull;
/** descriptor of a loop point to set on a voice. This may be specified both when a sound is
* first assigned to a voice in playSound() and to change the current loop point on the voice
* at a later time with setLoopPoint().
*/
struct LoopPointDesc
{
/** the event point to loop at. This may either be an explicitly constructed event point
* information block, or be one of the sound's event points, particularly one that is flagged
* as a loop point. This will define a location to loop back to once the end of the initial
* play region is reached. This event point must be within the range of the sound's data
* buffer. If the event point contains a zero length, the loop region will be taken to be
* the remainder of the sound starting from the loop point. This loop point will also
* contain a loop count. This loop count can be an explicit count or indicate that it
* should loop infinitely. Only a single loop point may be set for any given playing
* instance of a sound. Once the sound starts playing on a voice, the loop point and loop
* count may not be changed. A loop may be broken early by passing nullptr or an empty
* loop point descriptor to setLoopPoint() if needed. This may be nullptr to use one of
* the loop points from the sound itself by its index by specifying it in
* @ref loopPointIndex.
*
* When a loop point is specified explicitly in this manner, it will only be shallow
* copied into the voice object. If its string data is to be maintained to be passed
* through to a callback, it is the caller's responsibility to ensure the original loop
* point object remains valid for the entire period the voice is playing. Otherwise, the
* string members of the loop point should be set to nullptr.
*
* For performance reasons, it is important to ensure that streaming
* sounds do not have short loops (under 1 second is considered very
* short), since streaming loops will usually require seeking and some
* formats will need to partially decode blocks, which can require
* decoding thousands of frames in some formats.
*/
const EventPoint* loopPoint = nullptr;
/** the index of the loop point to use from the sound data object itself. This may be
* @ref kLoopDescNoLoop to indicate that no loop point is necessary. This value is only
* used if @ref loopPoint is nullptr. If the sound data object does not have a valid
* loop point at the specified index, the sound will still play but it will not loop.
* The loop point identified by this index must remain valid on the sound data object
* for the entire period that the voice is playing.
*/
size_t loopPointIndex = kLoopDescNoLoop;
/** reserved for future expansion. This must be set to nullptr. */
void* ext = nullptr;
};
/** base type for the play descriptor flags. Zero or more of these may be specified in
* @ref PlaySoundDesc::flags.
* @{
*/
typedef uint32_t PlayFlags;
/** when set, this indicates that the event points from the sound data object
* @ref PlaySoundDesc::sound should be used to trigger callbacks. If this flag is not set,
* no event point callbacks will be triggered for the playing sound.
*/
constexpr PlayFlags fPlayFlagUseEventPoints = 0x00000001;
/** when set, this indicates that voice event callbacks will be performed on the engine thread
* immediately when the event occurs instead of queuing it to be performed in a later call to
* update() on the host app thread. This flag is useful for streaming sounds or sounds that
* have data dynamically written to them. This allows for a lower latency callback system.
* If the callback is performed on the engine thread, it must complete as quickly as possible
* and not perform any operations that may block (ie: read from a file, wait on a signal, use
* a high contention lock, etc). If the callback takes too long, it will cause the engine cycle
* to go over time and introduce an artifact or audio dropout into the stream. In general, if
* a real-time callback takes more than ~1ms to execute, there is a very high possibility that
* it could cause an audio dropout. If this flag is not set, all callback events will be queued
* when they occur and will not be called until the next call to update() on the context object.
*/
constexpr PlayFlags fPlayFlagRealtimeCallbacks = 0x00000002;
/** when set, this indicates that if a voice is started with a sound that is already over its
* max play instances count, it should still be started but immediately put into simulation
* mode instead of taking a bus. When not set, the call to playSound() will fail if the sound's
* max instance count is above the max instances count. Note that if the new voice is put into
* simulation mode, it will still count as a playing instance of the sound which will cause its
* instance count to go above the maximum. This flag should be used sparingly at best.
*
* Note that when this flag is used, a valid voice will be created for the sound even though
* it is at or above its current instance limit. Despite it being started in simulation mode,
* this will still consume an extra instance count for the sound. The new voice will only be
* allowed to be devirtualized once its sound's instance count has dropped below its limit
* again. However, if the voice has a high priority level and the instance count is still
* above the limit, this will prevent other voices from being devirtualized too. This flag
* is best used on low priority, short, fast repeating sounds.
*/
constexpr PlayFlags fPlayFlagMaxInstancesSimulate = 0x00000004;
/** mask of playback flag bits that are available for public use. Clear bits in this mask are
* used internally and should not be referenced in other flags here. This is not valid as a
* playback flag or flag set.
*/
constexpr PlayFlags fPlayFlagAvailableMask = 0x01ffffff;
/** @} */
/** descriptor of how to play a single sound. At the very least, the @ref sound value must be
* specified.
*/
struct PlaySoundDesc
{
/** flags to describe the way to allocate the voice and play the sound. This may be zero
* or more of the fPlayFlag* flags.
*/
PlayFlags flags = 0;
/** the sound data object to be played. This may not be nullptr. The sound's data buffer
* will provide the data for the voice. By default, the whole sound will be played. If
* a non-zero value for @ref playStart and @ref playLength are also given, only a portion
* of the sound's data will be played.
*/
SoundData* sound;
/** the set of voice parameters that are valid. This can be @ref fVoiceParamAll if all of
* the parameters in the block are valid. It may be a combination of other fVoiceParam*
* flags if only certain parameters are valid. If set to 0, the parameters block in
* @ref params will be ignored and the default parameters used instead.
*/
VoiceParamFlags validParams = 0;
/** the initial parameters to set on the voice. This may be nullptr to use the default
* parameters for the voice. Note that the default parameters for spatial sounds will
* not necessarily be positioned appropriately in the world. If needed, only a portion
* of the parameter block may be specified by listing only the flags for the valid parameters
* in @ref validParams.
*/
VoiceParams* params = nullptr;
/** descriptor of an optional loop point to set for the voice. This may be changed at a
* later point on the voice with setLoopPoint() as well. This will identify the region
* to be played after the initial play region from @ref playStart through @ref playLength
* completes, or after the previous loop completes.
*/
LoopPointDesc loopPoint = {};
/** the callback function to bind to the voice. This provides notifications of the sound
* ending, loops starting on the sound, and event points getting hit in the sound. This
* callback will occur during an update() call if the @ref fPlayFlagRealtimeCallbacks flag
* is not used in @ref flags. This will occur on the engine thread if the flag is set.
* Note that if the callback is executing on the engine thread, it must complete its task
* as quickly as possible so that it doesn't stall the engine's processing operations.
* In most cases, it should just flag that the event occurred and return. The flagged
* event should then be handled on another thread. Blocking the engine thread can result
* in audio dropouts or popping artifacts in the stream. In general, if a real-time
* callback takes more than ~1ms to execute, there is a very high possibility that it could
* cause an audio dropout. This may be nullptr if no callbacks are needed.
*/
VoiceCallback callback = nullptr;
/** the opaque user context value that will be passed to the callback function any time
* it is called. This value is ignored if @ref callback is nullptr.
*/
void* callbackContext = nullptr;
/** the offset in the sound to start the initial playback at. The units of this value are
* specified in @ref playUnits. If this is set to 0, playback will start from the beginning
* of the sound data object. It is the caller's responsibility to ensure that this starting
* point occurs at a zero crossing in the data (otherwise a popping artifact will occur).
* This starting offset must be within the range of the sound data object's buffer. This
* may be outside of any chosen loop region. This region of the sound will be played before
* the loop region plays. This initial play region (starting at this offset and extending
* through @ref playLength) does not count as one of the loop iterations.
*/
size_t playStart = 0;
/** the length of the initial play region. The units of this value are specified in
* @ref playUnits. This may be set to 0 to indicate that the remainder of the sound data
* object's buffer should be played starting from @ref playStart. This length plus the
* starting offset must be within the range of the sound data object's buffer.
*/
size_t playLength = 0;
/** the units that the @ref playStart and @ref playLength values are given in. This may be
* any unit, but the use of time units could result in undesirable artifacts since they are
* not accurate units.
*/
UnitType playUnits = UnitType::eFrames;
/** reserved for future expansion. This must be set to `nullptr` unless it is pointing
* to a @ref PlaySoundDesc2 object.
*/
void* ext = nullptr;
};
/** Extended descriptor to allow for further control over how a new voice plays its sound. This
* must be set in @ref PlaySoundDesc::ext if it is to be included in the original play descriptor
* for the voice.
*/
struct PlaySoundDesc2
{
/** The time in microseconds to delay the start of this voice's sound. This will delay the
* start of the sound by an explicit amount requested by the caller. This specified delay
* time will be in addition to the context's delay time (@ref ContextParams2::videoLatency)
* and the calculated distance delay. This value may be negative to offset the context's
* delay time. However, once all delay times have been combined (context, per-voice,
* distance delay), the total delay will be clamped to 0. This defaults to 0us.
*/
int64_t delayTime = 0;
/** Extra padding space reserved for future expansion. Do not use this value directly.
* In future versions, new context parameters will be borrowed from this buffer and given
* proper names and types as needed. When this padding buffer is exhausted, a new
* @a PlaySoundDesc3 object will be added that can be chained to this one.
*/
void* padding[32] = {};
/** Reserved for future expansion. This must be set to `nullptr`. */
void* ext = nullptr;
};
/********************************** IAudioPlayback Interface **********************************/
/** Low-Level Audio Playback Plugin Interface.
*
* See these pages for more detail:
* @rst
* :ref:`carbonite-audio-label`
* :ref:`carbonite-audio-playback-label`
@endrst
*/
struct IAudioPlayback
{
CARB_PLUGIN_INTERFACE("carb::audio::IAudioPlayback", 1, 1)
/************************ context and device management functions ****************************/
/** retrieves the current audio output device count for the system.
*
* @return the number of audio output devices that are currently connected to the system.
* Device 0 in the list will be the system's default or preferred device.
*
* @note The device count is a potentially volatile value. This can change at any time
* without notice due to user action. For example, the user could remove an audio
* device from the system or add a new one at any time. Thus it is a good idea to
* open the device as quickly as possible after choosing the device index. There
* is no guarantee that the device list will even remain stable during a single
* device enumeration loop. The only device index that is guaranteed to be valid
* is the system default device index of 0.
*/
size_t(CARB_ABI* getDeviceCount)();
/** retrieves the capabilities and information about a single audio output device.
*
* @param[in] deviceIndex the index of the device to retrieve info for. This must be
* between 0 and the most recent return value from getDeviceCount().
* @param[out] caps receives the device information. The @a thisSize value must be set
* to sizeof(DeviceCaps) before calling.
* @returns @ref AudioResult::eOk if the device info was successfully retrieved.
* @returns @ref AudioResult::eInvalidParameter if the @a thisSize value is not properly
* initialized in @p caps or @p caps is nullptr.
* @returns @ref AudioResult::eOutOfRange if the requested device index is out of range of
* the system's current device count.
* @returns @ref AudioResult::eNotSupported if a device is found but it requires an
* unsupported sample format.
* @returns an AudioResult::* error code if the requested device index was out of range
* or the info buffer was invalid.
*
* @remarks This retrieves information about a single audio output device. The
* information will be returned in the @p info buffer. This may fail if the
* device corresponding to the requested index has been removed from the
* system.
*/
AudioResult(CARB_ABI* getDeviceCaps)(size_t deviceIndex, DeviceCaps* caps);
/** creates a new audio output context object.
*
* @param[in] desc a description of the initial settings and capabilities to use for the
* new context object. Set this to nullptr to use all default context
* settings.
* @returns the newly created audio output context object.
*
* @remarks This creates a new audio output context object. This object is responsible for
* managing all access to a single instance of the audio context. Note that there
* will be a separate audio engine thread associated with each instance of this
* context object.
*
* @remarks Upon creation, this object will be in a default state. This means that the
* selected device will be opened and its processing engine created. It will
* output at the chosen device's default frame rate and channel count. If needed,
* a new device may be selected with setOutput(). If a custom speaker mask
* (ie: not one of the standard preset kSpeakerMode* modes) was specified when
* creating the context or a device or speaker mask with more than
* @ref Speaker::eCount channels was used, the caller must make a call to
* setSpeakerDirections() before any spatial sounds can be played. Failing to do
* so will result in undefined behavior in the final audio output.
*
* @note If selecting a device fails during context creation, the context will still be
* created successfully and be valid for future operations. The caller will have
* to select another valid device at a later point before any audio will be output
* however. A caller can check if a device has been opened successfully by calling
* getContextCaps() and checking the @a selectedDevice.flags member to see if it has
* been set to something other than @ref fDeviceFlagNotOpen.
*/
Context*(CARB_ABI* createContext)(const PlaybackContextDesc* desc);
/** destroys an audio output context object.
*
* @param[in] context the context object to be destroyed. Upon return, this object will no
* longer be valid.
* @retval AudioResult::eOk.
*
* @remarks This destroys an audio output context object that was previously created
* with createContext(). If the context is still active and has a running mixer, it
* will be stopped before the object is destroyed. All resources associated with
* the device will be both invalidated and destroyed as well. Only audio data
* buffers that were queued on voices will be left (it is the caller's
* responsibility to destroy those).
*/
AudioResult(CARB_ABI* destroyContext)(Context* context);
/** retrieves the current capabilities and settings for a context object.
*
* @param[in] context the context object to retrieve the capabilities for.
* @returns the context's current capabilities and settings. This includes the speaker mode,
* speaker positions, maximum bus count, and information about the output device
* that is opened (if any).
* @returns nullptr if @p context is nullptr.
*
* @remarks This retrieves the current capabilities and settings for a context object.
* Some of these settings may change depending on whether the context has opened
* an output device or not.
*/
const ContextCaps*(CARB_ABI* getContextCaps)(Context* context);
/** sets one or more parameters on a context.
*
* @param[in] context the context to set the parameter(s) on. This may not be nullptr.
* @param[in] paramsToSet the set of flags to indicate which parameters in the parameter
* block @p params are valid and should be set on the context. This
* may be zero or more of the fContextParam* flags. If this is 0,
* the call will be treated as a no-op.
* @param[in] params the parameter(s) to be set on the context. The flags indicating
* which parameters need to be set are given in @p paramsToSet.
* Undefined behavior may occur if a flag is set but its
* corresponding value(s) have not been properly initialized. This
* may not be nullptr.
* @returns no return value.
*
* @remarks This sets one or more context parameters in a single call. Only parameters that
* have their corresponding flag set in @p paramsToSet will be modified. If a
* change is to be relative to the context's current parameter value, the current
* value should be retrieved first, modified, then set.
*/
void(CARB_ABI* setContextParameters)(Context* context, ContextParamFlags paramsToSet, const ContextParams* params);
/** retrieves one or more parameters for a context.
*
* @param[in] context the context to retrieve parameters for. This may not be nullptr.
* @param[in] paramsToGet flags indicating which parameter values need to be retrieved.
* @param[out] params receives the requested parameter values. This may not be nullptr.
* @returns no return value.
*
* @remarks This retrieves the current values of one or more of a context's parameters. Only
* the parameter values listed in @p paramsToGet flags will be guaranteed to be
* valid upon return.
*/
void(CARB_ABI* getContextParameters)(Context* context, ContextParamFlags paramsToGet, ContextParams* params);
/** Change the maximum number of voices that have their output mixed to the audio device.
* @param[in] ctx The context to modify.
* @param[in] count The new number of buses to select.
* This will be clamped to @ref PlaybackContextDesc::maxBuses,
* if @p count exceeds it.
* This cannot be set to 0.
*
* @returns true if the max bus count was successfully changed.
* @returns false if any voices are still playing on buses.
* @returns false if the operation failed for any other reason (e.g. out of memory).
*
* @note This call needs to stop the audio engine, so this will block for 10-20ms
* if any voices are still playing actively.
*
* @note This should be called infrequently and only in cases where destroying
* the context is not an option.
*
* @note To use this function without introducing audio artifacts, this
* function can only be called after all voices playing on buses
* have become silent or have stopped. The easiest way to ensure this
* is to set the master volume on the context to 0.0.
* At least 10ms must elapse between the volume reduction and this
* call to ensure that the changes have taken effect.
* If voices are being stopped, 20ms must occur between the last
* stopped voice and this call.
*/
bool(CARB_ABI* setBusCount)(Context* ctx, size_t count);
/** sets the [real biological] listener-relative position for all speakers.
*
* @param[in] context the context object to set the speaker positions for. This may not be
* nullptr.
* @param[in] desc a descriptor of the new speaker directions to set for the context.
* This may be nullptr to restore the default speaker directions for the
* currently selected device if it supports a standard speaker mode
* channel count.
* @returns true if the new speaker layout is successfully set.
* @returns false if the call fails or the given speaker mode doesn't match what the device
* was opened at.
*
* @remarks This allows a custom user-relative direction to be set for all speakers. Note
* that these represent the positions of the speakers in the real physical world
* not an entity in the simulated world. A speaker direction is specified as a
* 3-space vector with a left-to-right position, a front-to-back position, and a
* top-to-bottom position. Each coordinate is expected to be within the range
* -1.0 (left, back, or bottom) to 1.0 (right, front, or top). Each speaker
* direction is specified with these three explicit positions instead of an
* X/Y/Z vector to avoid confusion between various common coordinate systems
* (ie: graphics systems often treat negative Z as forward into the screen whereas
* audio systems often treat Z as up).
*
* @remarks When a new device is selected with setOutput(), any previous custom speaker
* directions will be reset to the implicit positions of the new speaker mode. The
* new speaker directions are defined on a cube where the origin (ie: the
* point (0, 0, 0)) represents the position of the user at the center of the
* cube. All values should range from -1.0 to 1.0. The given speaker direction
* vectors do not need to be normalized - this will be done internally. The
* distance from the origin is not important and does not affect spatial sound
* calculations. Only the speaker directions from the user are important.
*
* @remarks These speaker directions are used to affect how spatial audio calculations map
* from the simulated world to the physical world. They will affect the left-to-
* right, front-to-back, and top-to-bottom balancing of the different sound channels
* in each spatial sound calculation.
*
* @note For most applications, setting custom speaker directions is not necessary. This
* would be necessary in situations that use custom speaker modes, situations
* where the expected speaker layout is drastically different from any of the
* standard speaker modes that may be chosen (ie: a car speaker system), or when
* the speaker count does not map to a standard kSpeakerMode* speaker mode.
*
* @note An output must have been successfully selected on the context before this call
* can succeed. This can be checked by verifying that the context caps block's
* @a selectedDevice.flags member is not @ref fDeviceFlagNotOpen.
*/
bool(CARB_ABI* setSpeakerDirections)(Context* context, const SpeakerDirectionDesc* desc);
/** opens a requested audio output device and begins output.
*
* @param[in] context the context object that will have its device index set. This is
* returned from a previous call to createContext(). This must not
* be nullptr.
* @param[in] desc the descriptor of the output to open. This may be nullptr to
* use the default system output device.
* @retval AudioResult::eOk if the requested device is successfully opened.
* @retval AudioResult::eOutOfRange if the device index is invalid.
* @returns an AudioResult::* error code if the operation fails for any other reason. See
* the notes below for more information on failures.
*
* @remarks This sets the index of the audio output device that will be opened and attempts
* to open it. An index of 0 will open the system's default audio output device.
* Note that the device index value is volatile and could change at any time due
* to user activity. It is suggested that the device index be chosen as closely
* as possible to when the device will be opened.
*
* @remarks This allows an existing audio context object to switch to using a different audio
* device for its output after creation without having to destroy and recreate the
* current state of the context. Once a new device is selected, it will be
* available to start processing and outputting audio. Note that switching audio
* devices dynamically may cause an audible pop to occur on both the old device and
* new device depending on the current state of the context. To avoid this, all
* active voices could be muted or paused briefly during the device switch, then
* resumed or un-muted after it completes.
*
* @note If selecting the new device fails, the context will be left without a device to
* play its output on. Upon failure, an attempt to open the system's default device
* may be made by the caller to restore the playback. Note that even choosing the
* system default device may fail for various reasons (ie: the speaker mode of the
* new device cannot be mapped properly, the device is no longer available in the
* system, etc). In this case, all audio processing will still continue but the
* final audio data will just be dropped until a valid output target is connected.
*/
AudioResult(CARB_ABI* setOutput)(Context* context, const OutputDesc* desc);
/** performs required frequent updates for the audio context.
*
* @param[in] context the context object to perform update tasks on.
* @retval AudioResult::eOk if the update is performed successfully.
* @retval AudioResult::eDeviceDisconnected or @ref AudioResult::eDeviceLost if the
* currently selected device has been removed from the system.
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @retval AudioResult::eInvalidParameter if an invalid context is passed in.
* @returns an AudioResult::* error code if the update fails for any other reason.
*
* @remarks This performs common update tasks. Updates need to be performed frequently.
* This will perform any pending callbacks and will ensure that all pending
* parameter changes have been updated in the engine context. This should still
* be called periodically even if no object parameter changes occur.
*
* @remarks All non-realtime voice callbacks will be performed during this call. All
* device change callbacks on the context will also be performed here. Failing
* to call this periodically may cause events to be lost.
*/
AudioResult(CARB_ABI* update)(Context* context);
/** starts the audio processing engine for a context.
*
* @param[in] context the context to start the processing engine for. This must not be
* nullptr.
* @returns no return value.
*
* @remarks This starts the audio processing engine for a context. When creating a playback
* context, the processing engine will always be automatically started. When
* creating a baking context, the processing engine must always be started
* explicitly. This allows the baking operation to be fully setup (ie: queue all
* sounds to be played, set all parameters, etc) before any audio is processed.
* This prevents the baked result from containing an indeterminate amount of silence
* at the start of its stream.
*
* @remarks When using a playback context, this does not need to be called unless the engine
* is being restarted after calling stopProcessing().
*/
void(CARB_ABI* startProcessing)(Context* context);
/** stops the processing engine for a context.
*
* @param[in] context the context to stop the processing engine for. This must not be
* nullptr.
* @returns no return value.
*
* @remarks This stops the audio processing engine for a context. For a playback context,
* this is not necessary unless all processing needs to be halted for some reason.
* For a baking context, this is only necessary if the fContextFlagManualStop flag
* was used when creating the context. If that flags is used, the processing
* engine will be automatically stopped any time it runs out of data to process.
*
* @note Stopping the engine is not the same as pausing the output. Stopping the engine
* will cause any open streamers to be closed and will likely cause an audible pop
* when restarting the engine with startProcessing().
*/
void(CARB_ABI* stopProcessing)(Context* context);
/********************************** sound management functions *******************************/
/** schedules a sound to be played on a voice.
*
* @param[in] context the context to play the new sound on. This must not be nullptr.
* @param[in] desc the descriptor of the play task to be performed. This may not be
* nullptr.
* @returns a new voice handle representing the playing sound. Note that if no buses are
* currently available to play on or the voice's initial parameters indicated that
* it is not currently audible, the voice will be virtual and will not be played.
* The voice handle will still be valid in this case and can be operated on, but
* no sound will be heard from it until it is determined that it should be converted
* to a real voice. This can only occur when the update() function is called.
* This voice handle does not need to be closed or destroyed. If the voice finishes
* its play task, any future calls attempting to modify the voice will simply fail.
* @returns nullptr if the requested sound is already at or above its instance limit and the
* @ref fPlayFlagMaxInstancesSimulate flag is not used.
* @returns nullptr if the play task was invalid or could not be started properly. This can
* most often occur in the case of streaming sounds if the sound's original data
* could not be opened or decoded properly.
*
* @remarks This schedules a sound object to be played on a voice. The sounds current
* settings (ie: volume, pitch, playback frame rate, pan, etc) will be assigned to
* the voice as 'defaults' before playing. Further changes can be made to the
* voice's state at a later time without affecting the sound's default settings.
*
* @remarks Once the sound finishes playing, it will be implicitly unassigned from the
* voice. If the sound or voice have a callback set, a notification will be
* received for the sound having ended.
*
* @remarks If the playback of this sound needs to be stopped, it must be explicitly stopped
* from the returned voice object using stopVoice(). This can be called on a
* single voice or a voice group.
*/
Voice*(CARB_ABI* playSound)(Context* context, const PlaySoundDesc* desc);
/** stops playback on a voice.
*
* @param[in] voice the voice to stop.
* @returns no return value.
*
* @remarks This stops a voice from playing its current sound. This will be silently
* ignored for any voice that is already stopped or for an invalid voice handle.
* Once stopped, the voice will be returned to a 'free' state and its sound data
* object unassigned from it. The voice will be immediately available to be
* assigned a new sound object to play from.
*
* @note This will only schedule the voice to be stopped. Its volume will be implicitly
* set to silence to avoid a popping artifact on stop. The voice will continue to
* play for one more engine cycle until the volume level reaches zero, then the voice
* will be fully stopped and recycled. At most, 1ms of additional audio will be
* played from the voice's sound.
*/
void(CARB_ABI* stopVoice)(Voice* voice);
/********************************** voice management functions *******************************/
/** retrieves the sound (if any) that is currently active on a voice.
*
* @param[in] voice the voice to retrieve the active sound for.
* @returns the sound object that is currently playing on the requested voice.
* @returns nullptr if the voice is not currently playing any sound object.
* @returns nullptr if the given voice handle is no longer valid.
*
* @remarks This retrieves the sound data object that is currently being processed on a
* voice. This can be used to make a connection between a voice and the sound
* data object it is currently processing.
*
* @note If @p voice ends, the returned sound will be freed in the next
* update() call. It is the caller's responsibility to call
* IAudioData::acquire() if the object is going to be held until
* after that update() call. It is also the caller's responsibility
* to ensure acquiring this reference is done in a thread safe
* manner with respect to the update() call.
*/
SoundData*(CARB_ABI* getPlayingSound)(Voice* voice);
/** checks the playing state of a voice.
*
* @param[in] voice the voice to check the playing state for.
* @returns true if the requested voice is playing.
* @returns false if the requested voice is not playing or is paused.
* @returns false if the given voice handle is no longer valid.
*
* @remarks This checks if a voice is currently playing. A voice is considered playing if
* it has a currently active sound data object assigned to it, it is not paused,
* and its play task has not completed yet. This will start failing immediately
* upon the voice completing its play task instead of waiting for the voice to
* be recycled on the next update() call.
*/
bool(CARB_ABI* isPlaying)(Voice* voice);
/** sets a new loop point as current on a voice.
*
* @param[in] voice the voice to set the loop point on. This may not be nullptr.
* @param[in] desc descriptor of the new loop point to set. This may contain a loop
* or event point from the sound itself or an explicitly specified
* loop point. This may be nullptr to indicate that the current loop
* point should be removed and the current loop broken. Similarly,
* an empty loop point descriptor could be passed in to remove the
* current loop point.
* @returns true if the new loop point is successfully set.
* @returns false if the voice handle is invalid or the voice has already stopped on its own.
* @returns false if the new loop point is invalid, not found in the sound data object, or
* specifies a starting point or length that is outside the range of the sound data
* object's buffer.
*
* @remarks This sets a new loop point for a playing voice. This allows for behavior such
* as sound atlases or sound playlists to be played out on a single voice. Ideally
* this should be called from a @ref VoiceCallbackType::eLoopPoint callback to
* ensure the new buffer is queued without allowing the voice to finish on its own
* and to prevent a potential race condition between the engine and the host app
* setting the new loop point. Calling this in a real-time callback would guarantee
* no race would occur, however it could still be done safely in a non-real-time
* callback if the voice's current loop region is long enough and the update()
* function is called frequently enough.
*
* @remarks This could also be called from a @ref VoiceCallbackType::eSoundEnded callback,
* but only if it is done in a real-time callback. In a non-real-time callback
* the voice handle will already have been invalidated by the time the update()
* function performs the callback.
*
* @remarks When @p desc is nullptr or the contents of the descriptor do not specify a new
* loop point, this will immediately break the loop that is currently playing on
* the voice. This will have the effect of setting the voice's current loop count
* to zero. The sound on the voice will continue to play out its current loop
* iteration, but will not loop again when it reaches its end. This is useful for
* stopping a voice that is playing an infinite loop or to prematurely stop a voice
* that was set to loop a specific number of times. This call will effectively be
* ignored if passed in a voice that is not currently looping.
*
* @note For streaming voices, updating a loop point will have a delay due to buffering
* the decoded data. The sound will loop an extra time if the loop point is changed
* after the buffering has started to consume another loop. The default buffer time
* for streaming sounds is currently 200 milliseconds, so this is the minimum slack
* time that needs to be given for a loop change. This means that changing
* a loop point in a @ref VoiceCallbackType::eLoopPoint callback will result in an
* extra loop occurring for a streaming sound.
*/
bool(CARB_ABI* setLoopPoint)(Voice* voice, const LoopPointDesc* desc);
/** retrieves the current play cursor position of a voice.
*
* @param[in] voice the voice to retrieve the play position for.
* @param[in] type the units to retrieve the current position in.
* @returns the current position of the voice in the requested units.
* @returns 0 if the voice does not have a sound assigned to it.
* @returns the last play cursor position if the voice is paused.
*
* @remarks This retrieves the current play position for a voice. This is not necessarily
* the position in the buffer being played, but rather the position in the sound
* data object's stream. For streaming sounds, this will be the offset from the
* start of the stream. For non-streaming sounds, this will be the offset from
* the beginning of the sound data object's buffer.
*
* @note If the loop point for the voice changes during playback, the results of this
* call can be unexpected. Once the loop point changes, there is no longer a
* consistent time base for the voice and the results will reflect the current
* position based off of the original loop's time base. As long as the voice's
* original loop point remains (ie: setLoopPoint() is never called on the voice),
* the calculated position should be correct.
*
* @note It is the caller's responsibility to ensure that this is not called at the same
* time as changing the loop point on the voice or stopping the voice.
*/
size_t(CARB_ABI* getPlayCursor)(Voice* voice, UnitType type);
/** sets one or more parameters on a voice.
*
* @param[in] voice the voice to set the parameter(s) on.
* @param[in] paramsToSet flags to indicate which of the parameters need to be updated.
* This may be one or more of the fVoiceParam* flags. If this is
* 0, this will simply be a no-op.
* @param[in] params the parameter(s) to be set on the voice. The flags indicating
* which parameters need to be set must be set in
* @p paramsToSet by the caller. Undefined behavior
* may occur if a flag is set but its corresponding value(s) have
* not been properly initialized. This may not be nullptr.
* @returns no return value.
*
* @remarks This sets one or more voice parameters in a single call.
* Only parameters that have their corresponding flag set in @p
* paramsToSet will be modified.
* If a change is to be relative to the voice's current parameter value, the current
* value should be retrieved first, modified, then set.
*
* @note only one of @ref fPlaybackModeSimulatePosition or
* @ref fPlaybackModeNoPositionSimulation can be set in the playback
* mode. If none or both of the flags are set, the previous value of
* those two bits will be used.
*/
void(CARB_ABI* setVoiceParameters)(Voice* voice, VoiceParamFlags paramsToSet, const VoiceParams* params);
/** retrieves one or more parameters for a voice.
*
* @param[in] voice the voice to retrieve parameters for.
* @param[in] paramsToGet flags indicating which parameter values need to be retrieved.
* @param[out] params receives the requested parameter values. This may not be nullptr.
* @returns no return value.
*
* @remarks This retrieves the current values of one or more of a voice's parameters. Only
* the parameter values listed in @p paramsToGet flags will be guaranteed to be
* valid upon return.
*/
void(CARB_ABI* getVoiceParameters)(Voice* voice, VoiceParamFlags paramsToGet, VoiceParams* params);
/** stops playback on all voices in a given context.
*
* @param[in] context the context where to stop playback the voices.
*
* @remarks The input context parameter can be nullptr, meaning to stop playback on all
* voices in all contexts in the context table.
*/
void(CARB_ABI* stopAllVoices)(Context* context);
};
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/AudioTypes.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Data types used by the audio interfaces.
*/
#pragma once
#include "../assets/AssetsTypes.h"
#include "carb/Types.h"
#include "carb/extras/Guid.h"
namespace carb
{
namespace audio
{
/** represents a single audio context object. This contains the state for a single instance of
* one of the low-level audio plugins. This is to be treated as an opaque handle to an object
* and should only passed into the function of the plugin that created it.
*/
struct Context DOXYGEN_EMPTY_CLASS;
/** represents a single instance of a playing sound. A single sound object may be playing on
* multiple voices at the same time, however each voice may only be playing a single sound
* at any given time.
*/
struct Voice DOXYGEN_EMPTY_CLASS;
/** various limits values for the audio system.
* @{
*/
constexpr size_t kMaxNameLength = 512; ///< maximum length of a device name in characters.
constexpr size_t kMaxChannels = 64; ///< maximum number of channels supported for output.
constexpr size_t kMinChannels = 1; ///< minimum number of channels supported for capture or output.
constexpr size_t kMaxFrameRate = 200000; ///< maximum frame rate of audio that can be processed.
constexpr size_t kMinFrameRate = 1000; ///< minimum frame rate of audio that can be processed.
/** @} */
/** description of how a size or offset value is defined. This may be given as a */
enum class UnitType : uint32_t
{
eBytes, ///< the size or offset is given as a byte count.
eFrames, ///< the size or offset is given as a frame count.
eMilliseconds, ///< the size or offset is given as a time in milliseconds.
eMicroseconds, ///< the size or offset is given as a time in microseconds.
};
/** possible return values from various audio APIs. These indicate the kind of failure that
* occurred.
*/
enum class AudioResult
{
eOk, ///< the operation was successful.
eDeviceDisconnected, ///< the device was disconnected from the system.
eDeviceLost, ///< access to the device was lost.
eDeviceNotOpen, ///< the device has not been opened yet.
eDeviceOpen, ///< the device has already been opened.
eOutOfRange, ///< a requested parameter was out of range.
eTryAgain, ///< the operation should be retried at a later time.
eOutOfMemory, ///< the operation failed due to a lack of memory.
eInvalidParameter, ///< an invalid parameter was passed in.
eNotAllowed, ///< this operation is not allowed on the object type.
eNotFound, ///< the resource requested, such as a file, was not found.
eIoError, ///< an error occurred in an IO operation.
eInvalidFormat, ///< the format of a resource was invalid.
eOverrun, ///< An overrun occurred
eNotSupported, ///< the resource or operation used is not supported.
};
/** speaker names. Speakers are virtually located on the unit circle with the listener at the
* fSpeakerFlagFrontCenter. Speaker angles are relative to the positive Y axis (ie: forward
* from the listener). Angles increase in the clockwise direction. The top channels are
* located on the unit sphere at an inclination of 45 degrees.
* The channel order of these speakers is represented by the ordering of speakers in this
* enum (e.g. eSideLeft is after eBackLeft).
*/
enum class Speaker
{
eFrontLeft, ///< Front left speaker. Usually located at -45 degrees. Also used for left headphone.
eFrontRight, ///< Front right speaker. Usually located at 45 degrees. Also used for right headphone.
eFrontCenter, ///< Front center speaker. Usually located at 0 degrees.
eLowFrequencyEffect, ///< Low frequency effect speaker (subwoofer). Usually treated as if it is located at the
///< listener.
eBackLeft, ///< Back left speaker. Usually located at -135 degrees.
eBackRight, ///< Back right speaker. Usually located at 135 degrees.
eBackCenter, ///< Back center speaker. Usually located at 180 degrees.
eSideLeft, ///< Side left speaker. Usually located at -90 degrees.
eSideRight, ///< Side right speaker. Usually located at 90 degrees.
eTopFrontLeft, ///< Top front left speaker. Usually located at -45 degrees and raised vertically.
eTopFrontRight, ///< Top front right speaker. Usually located at 45 degrees and raised vertically.
eTopBackLeft, ///< Top back left speaker. Usually located at -135 degrees and raised vertically.
eTopBackRight, ///< Top back right speaker. Usually located at 135 degrees and raised vertically.
eFrontLeftWide, ///< Front left wide speaker. Usually located at -60 degrees.
eFrontRightWide, ///< Front left wide speaker. Usually located at 60 degrees.
eTopLeft, ///< Top left speaker. Usually located at -90 degrees and raised vertically.
eTopRight, ///< Top right speaker. Usually located at 90 degrees and raised vertically.
eCount, ///< Total number of named speakers. This is not a valid speaker name.
};
/** the base type for a set of speaker flag masks. This can be any combination of the
* fSpeakerFlag* speaker names, or one of the kSpeakerMode names.
*/
typedef uint64_t SpeakerMode;
/** @brief a conversion function from a Speaker enum to bitflags.
* @param[in] s The speaker enum to convert to a bitflag.
* @returns The corresponding speaker flag.
*/
constexpr SpeakerMode makeSpeakerFlag(Speaker s)
{
return 1ull << static_cast<SpeakerMode>(s);
}
/** @brief a conversion function from a Speaker enum to bitflags.
* @param[in] s The speaker enum to convert to a bitflag.
* @returns The corresponding speaker flag.
*/
constexpr SpeakerMode makeSpeakerFlag(size_t s)
{
return makeSpeakerFlag(static_cast<Speaker>(s));
}
/** Speaker bitflags that can be used to create speaker modes.
* @{
*/
/** @copydoc Speaker::eFrontLeft */
constexpr SpeakerMode fSpeakerFlagFrontLeft = makeSpeakerFlag(Speaker::eFrontLeft);
/** @copydoc Speaker::eFrontRight */
constexpr SpeakerMode fSpeakerFlagFrontRight = makeSpeakerFlag(Speaker::eFrontRight);
/** @copydoc Speaker::eFrontCenter */
constexpr SpeakerMode fSpeakerFlagFrontCenter = makeSpeakerFlag(Speaker::eFrontCenter);
/** @copydoc Speaker::eLowFrequencyEffect */
constexpr SpeakerMode fSpeakerFlagLowFrequencyEffect = makeSpeakerFlag(Speaker::eLowFrequencyEffect);
/** @copydoc Speaker::eSideLeft */
constexpr SpeakerMode fSpeakerFlagSideLeft = makeSpeakerFlag(Speaker::eSideLeft);
/** @copydoc Speaker::eSideRight */
constexpr SpeakerMode fSpeakerFlagSideRight = makeSpeakerFlag(Speaker::eSideRight);
/** @copydoc Speaker::eBackLeft */
constexpr SpeakerMode fSpeakerFlagBackLeft = makeSpeakerFlag(Speaker::eBackLeft);
/** @copydoc Speaker::eBackRight */
constexpr SpeakerMode fSpeakerFlagBackRight = makeSpeakerFlag(Speaker::eBackRight);
/** @copydoc Speaker::eBackCenter */
constexpr SpeakerMode fSpeakerFlagBackCenter = makeSpeakerFlag(Speaker::eBackCenter);
/** @copydoc Speaker::eTopFrontLeft */
constexpr SpeakerMode fSpeakerFlagTopFrontLeft = makeSpeakerFlag(Speaker::eTopFrontLeft);
/** @copydoc Speaker::eTopFrontRight */
constexpr SpeakerMode fSpeakerFlagTopFrontRight = makeSpeakerFlag(Speaker::eTopFrontRight);
/** @copydoc Speaker::eTopBackLeft */
constexpr SpeakerMode fSpeakerFlagTopBackLeft = makeSpeakerFlag(Speaker::eTopBackLeft);
/** @copydoc Speaker::eTopBackRight */
constexpr SpeakerMode fSpeakerFlagTopBackRight = makeSpeakerFlag(Speaker::eTopBackRight);
/** @copydoc Speaker::eFrontLeftWide */
constexpr SpeakerMode fSpeakerFlagFrontLeftWide = makeSpeakerFlag(Speaker::eFrontLeftWide);
/** @copydoc Speaker::eFrontRightWide */
constexpr SpeakerMode fSpeakerFlagFrontRightWide = makeSpeakerFlag(Speaker::eFrontRightWide);
/** @copydoc Speaker::eTopLeft */
constexpr SpeakerMode fSpeakerFlagTopLeft = makeSpeakerFlag(Speaker::eTopLeft);
/** @copydoc Speaker::eTopRight */
constexpr SpeakerMode fSpeakerFlagTopRight = makeSpeakerFlag(Speaker::eTopRight);
/** @} */
/** the special name for an invalid speaker. Since a speaker mode could also include custom
* bits for unnamed speakers, there needs to be a way to represent failure conditions when
* converting between speaker flags and speaker names.
*/
constexpr size_t kInvalidSpeakerName = ~0ull;
/** common speaker layout modes. These put together a specific set of channels that describe how
* a speaker mode is laid out around the listener.
* @{
*/
/** a special speaker mode that indicates that the audio device's preferred speaker mode
* should be used in the mixer. The individual speaker positions may not be changed
* with setSpeakerDirections() when using this mode.
*/
constexpr SpeakerMode kSpeakerModeDefault = 0;
/** a mono speaker mode. Only a single channel is supported. The one speaker is often
* treated as being positioned at the fSpeakerFlagFrontCenter in front of the listener
* even though it is labeled as 'left'.
*/
constexpr SpeakerMode kSpeakerModeMono = fSpeakerFlagFrontLeft;
/** a stereo speaker mode. This supports two channels. These are usually located at
* -90 degrees and 90 degrees.
*/
constexpr SpeakerMode kSpeakerModeStereo = fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight;
/** A three speaker mode. This has two front speakers and a low frequency effect speaker.
* The speakers are usually located at -45 and 45 degrees.
*/
constexpr SpeakerMode kSpeakerModeTwoPointOne =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagLowFrequencyEffect;
/** a four speaker mode. This has two front speakers and two side or back speakers. The
* speakers are usually located at -45, 45, -135, and 135 degrees around the listener.
*/
constexpr SpeakerMode kSpeakerModeQuad =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight;
/** a five speaker mode. This has two front speakers and two side or back speakers
* and a low frequency effect speaker. The speakers are usually located at -45, 45,
* -135, and 135 degrees around the listener.
*/
constexpr SpeakerMode kSpeakerModeFourPointOne = fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagBackLeft |
fSpeakerFlagBackRight | fSpeakerFlagLowFrequencyEffect;
/** a six speaker mode. This represents a standard 5.1 home theater setup. Speakers are
* usually located at -45, 45, 0, 0, -135, and 135 degrees.
*/
constexpr SpeakerMode kSpeakerModeFivePointOne = fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight |
fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagBackLeft | fSpeakerFlagBackRight;
/** a seven speaker mode. This is an non-standard speaker layout.
* Speakers in this layout are located at -45, 45, 0, 0, -90, 90 and 180 degrees.
*/
constexpr SpeakerMode kSpeakerModeSixPointOne = fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight |
fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagBackCenter | fSpeakerFlagSideLeft | fSpeakerFlagSideRight;
/** an eight speaker mode. This represents a standard 7.1 home theater setup. Speakers are
* usually located at -45, 45, 0, 0, -90, 90, -135, and 135 degrees.
*/
constexpr SpeakerMode kSpeakerModeSevenPointOne =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagSideLeft | fSpeakerFlagSideRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight;
/** a ten speaker mode. This represents a standard 9.1 home theater setup. Speakers are
* usually located at -45, 45, 0, 0, -90, 90, -135, 135, -60 and 60 degrees.
*/
constexpr SpeakerMode kSpeakerModeNinePointOne =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagSideLeft | fSpeakerFlagSideRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight |
fSpeakerFlagFrontLeftWide | fSpeakerFlagFrontRightWide;
/** a twelve speaker mode. This represents a standard 7.1.4 home theater setup. The lower
* speakers are usually located at -45, 45, 0, 0, -90, 90, -135, and 135 degrees. The upper
* speakers are usually located at -45, 45, -135, and 135 at an inclination of 45 degrees.
*/
constexpr SpeakerMode kSpeakerModeSevenPointOnePointFour =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagSideLeft | fSpeakerFlagSideRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight |
fSpeakerFlagTopFrontLeft | fSpeakerFlagTopFrontRight | fSpeakerFlagTopBackLeft | fSpeakerFlagTopBackRight;
/** a fourteen speaker mode. This represents a standard 9.1.4 home theater setup. The lower
* speakers are usually located at -45, 45, 0, 0, -90, 90, -135, 135, -60 and 60 degrees. The upper
* speakers are usually located at -45, 45, -135, and 135 at an inclination of 45 degrees.
*/
constexpr SpeakerMode kSpeakerModeNinePointOnePointFour =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagSideLeft | fSpeakerFlagSideRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight |
fSpeakerFlagFrontLeftWide | fSpeakerFlagFrontRightWide | fSpeakerFlagTopFrontLeft | fSpeakerFlagTopFrontRight |
fSpeakerFlagTopBackLeft | fSpeakerFlagTopBackRight;
/** a sixteen speaker mode. This represents a standard 9.1.6 home theater setup. The lower
* speakers are usually located at -45, 45, 0, 0, -90, 90, -135, 135, -60 and 60 degrees. The upper
* speakers are usually located at -45, 45, -135, 135, -90 and 90 degrees at an inclination of 45 degrees.
*/
constexpr SpeakerMode kSpeakerModeNinePointOnePointSix =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagSideLeft | fSpeakerFlagSideRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight |
fSpeakerFlagFrontLeftWide | fSpeakerFlagFrontRightWide | fSpeakerFlagTopFrontLeft | fSpeakerFlagTopFrontRight |
fSpeakerFlagTopBackLeft | fSpeakerFlagTopBackRight | fSpeakerFlagTopLeft | fSpeakerFlagTopRight;
/** A linear surround setup.
* This is the 3 channel layout in formats using Vorbis channel order.
*/
constexpr SpeakerMode kSpeakerModeThreePointZero =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter;
/** @ref kSpeakerModeFivePointOne without the low frequency effect speaker.
* This is used as the 5 channel layout in formats using Vorbis channel order.
*/
constexpr SpeakerMode kSpeakerModeFivePointZero = fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight |
fSpeakerFlagFrontCenter | fSpeakerFlagBackLeft | fSpeakerFlagBackRight;
/** the total number of 'standard' speaker modes represented here. Other custom speaker modes
* are still possible however by combining the fSpeakerFlag* names in different ways.
*/
constexpr size_t kSpeakerModeCount = 7;
/** All valid speaker mode bits.
*/
constexpr SpeakerMode fSpeakerModeValidBits =
fSpeakerFlagFrontLeft | fSpeakerFlagFrontRight | fSpeakerFlagFrontCenter | fSpeakerFlagLowFrequencyEffect |
fSpeakerFlagSideLeft | fSpeakerFlagSideRight | fSpeakerFlagBackLeft | fSpeakerFlagBackRight |
fSpeakerFlagFrontLeftWide | fSpeakerFlagFrontRightWide | fSpeakerFlagTopFrontLeft | fSpeakerFlagTopFrontRight |
fSpeakerFlagTopBackLeft | fSpeakerFlagTopBackRight | fSpeakerFlagTopLeft | fSpeakerFlagTopRight;
/** @} */
/** flags to indicate the current state of a device in the system. This may be any combination
* of the fDeviceFlag* flags.
*/
typedef uint32_t DeviceFlags;
/** flags to indicate the current state of a device. These are used in the @a flags member of
* the @ref DeviceCaps struct.
* @{
*/
constexpr DeviceFlags fDeviceFlagNotOpen = 0x00000000; ///< no device is currently open.
constexpr DeviceFlags fDeviceFlagConnected = 0x00000001; ///< the device is currently connected to the system.
constexpr DeviceFlags fDeviceFlagDefault = 0x00000002; ///< the device is the system default or preferred device.
constexpr DeviceFlags fDeviceFlagStreamer = 0x00000004; ///< a streamer is being used as an output.
/** @} */
/** prototype for the optional destructor function for a user data object.
*
* @param[in] userData the user data object to be destroyed. This will never be nullptr.
* @returns no return value.
*
* @remarks This destroys the user data object associated with an object. The parent object may
* be a sound data object or sound group, but is irrelevant here since it is not passed
* into this destructor. This destructor is optional. If specified, it will be called
* any time the user data object is replaced with a setUserData() function or when the
* containing object itself is being destroyed.
*/
typedef void(CARB_ABI* UserDataDestructor)(void* userData);
/** an opaque user data object that can be attached to some objects (ie: sound data objects, sound
* groups, etc).
*/
struct UserData
{
/** the opaque user data pointer associated with this entry. The caller is responsible for
* creating this object and ensuring its contents are valid.
*/
void* data = nullptr;
/** the optional destructor that will be used to clean up the user data object whenever it is
* replaced or the object containing this user data object is destroyed. This may be nullptr
* if no clean up is needed for the user data object. It is the host app's responsibility
* to ensure that either this destructor is provided or that the user data object is manually
* cleaned up before anything it is attached to is destroyed.
*/
UserDataDestructor destructor = nullptr;
};
/** the data type for a single sample of raw audio data. This describes how each sample in the
* data buffer should be interpreted. In general, audio data can only be uncompressed Pulse
* Code Modulation (PCM) data, or encoded in some kind of compressed format.
*/
enum class SampleFormat : uint32_t
{
/** 8 bits per sample unsigned integer PCM data. Sample values will range from 0 to 255
* with a value of 128 being 'silence'.
*/
ePcm8,
/** 16 bits per sample signed integer PCM data. Sample values will range from -32768 to
* 32767 with a value of 0 being 'silence'.
*/
ePcm16,
/** 24 bits per sample signed integer PCM data. Sample values will range from -16777216
* to 16777215 with a value of 0 being 'silence'.
*/
ePcm24,
/** 32 bits per sample signed integer PCM data. Sample values will range from -2147483648
* to 2147483647 with a value of 0 being 'silence'.
*/
ePcm32,
/** 32 bits per sample floating point PCM data. Sample values will range from -1.0 to 1.0
* with a value of 0.0 being 'silence'. Note that floating point samples can extend out
* of their range (-1.0 to 1.0) without a problem during mixing. However, once the data
* reaches the device, any samples beyond the range from -1.0 to 1.0 will clip and cause
* distortion artifacts.
*/
ePcmFloat,
/** the total number of PCM formats. This is not a valid format and is only used internally
* to determine how many PCM formats are available.
*/
ePcmCount,
/** The Vorbis codec.
* Vorbis is a lossy compressed codec that is capable of producing high
* quality audio that is difficult to differentiate from lossless codecs.
* Vorbis is suitable for music and other applications that require
* minimal quality loss.
* Vorbis is stored in Ogg file containers (.ogg or .oga).
* Vorbis has a variable block size, with a maximum of 8192 frames per
* block, which makes it non-optimal for low latency audio transfer (e.g.
* voice chat); additionally, the Ogg container combines Vorbis blocks
* into chunks that can be seconds long.
* libvorbis will accept frame rates of 1Hz - 200KHz (Note that IAudioPlayback
* does not supports framerates below @ref kMinFrameRate).
* Vorbis is able to handle up to 255 channels, but sounds with more than 8
* channels have no official ordering. (Note that does not support more than @ref kMaxChannels)
*
* Vorbis has a defined channel mapping for audio with 1-8 channels.
* Channel counts 3 and 5 have an incompatible speaker layout with the
* default layouts in this plugin.
* A 3 channel layout uses @ref kSpeakerModeThreePointZero,
* A 5 channel layout uses @ref kSpeakerModeFivePointZero
* For streams with more than 8 channels, the mapping is undefined and
* must be determined by the application.
*
* These are the results of decoding speed tests run on Vorbis; they are
* shown as the decoding time relative to decoding a 16 bit uncompressed
* WAVE file to @ref SampleFormat::ePcm32. Clip 1 and 2 are stereo music.
* Clip 3 is a mono voice recording. Clip 1 has low inter-channel
* correlation; Clip 2 has high inter-channel correlation.
* Note that the bitrates listed here are approximate, since Vorbis is
* variable bitrate.
* - clip 1, 0.0 quality (64kb/s): 668%
* - clip 1, 0.4 quality (128kb/s): 856%
* - clip 1, 0.9 quality (320kb/s): 1333%
* - clip 2, 0.0 quality (64kb/s): 660%
* - clip 2, 0.4 quality (128kb/s): 806%
* - clip 2, 0.9 quality (320kb/s): 1286%
* - clip 3, 0.0 quality (64kb/s): 682%
* - clip 3, 0.4 quality (128kb/s): 841%
* - clip 3, 0.9 quality (320kb/s): 1074%
*
* These are the file sizes from the previous tests:
* - clip 1, uncompressed: 32.7MiB
* - clip 1, 0.0 quality (64kb/s): 1.5MiB
* - clip 1, 0.4 quality (128kb/s): 3.0MiB
* - clip 1, 0.9 quality (320kb/s): 7.5MiB
* - clip 2, uncompressed: 49.6MiB
* - clip 2, 0.0 quality (64kb/s): 2.0MiB
* - clip 2, 0.4 quality (128kb/s): 4.0MiB
* - clip 2, 0.9 quality (320kb/s): 10.4MiB
* - clip 3, uncompressed: 9.0MiB
* - clip 3, 0.0 quality (64kb/s): 0.9MiB
* - clip 3, 0.4 quality (128kb/s): 1.4MiB
* - clip 3, 0.9 quality (320kb/s): 2.5MiB
*/
eVorbis,
/** The Free Lossless Audio Codec.
* This is a codec capable of moderate compression with a perfect
* reproduction of the original uncompressed signal.
* This encodes and decodes reasonable fast, but the file size is much
* larger than the size of a high quality lossy codec.
* This is suitable in applications where audio data will be repeatedly
* encoded, such as an audio editor. Unlike a lossy codec, repeatedly
* encoding the file with FLAC will not degrade the quality.
* FLAC is very fast to encode and decode compared to other compressed codecs.
* Note that FLAC only stores integer data, so audio of type
* SampleFormat::ePcmFloat will lose precision when stored as FLAC.
* Additionally, the FLAC encoder used only supports up to 24 bit, so
* SampleFormat::ePcm32 will lose some precision when being stored if there
* are more than 24 valid bits per sample.
* FLAC supports frame rates from 1Hz - 655350Hz (Note that IAudioPlayback
* only support framerates of @ref kMinFrameRate to @ref kMaxFrameRate).
* FLAC supports up to 8 channels.
*
* These are the results of decoding speed tests run on FLAC; they are
* shown as the decoding time relative to decoding a 16 bit uncompressed
* WAVE file to @ref SampleFormat::ePcm32. These are the same clips as
* used in the decoding speed test for @ref SampleFormat::eVorbis.
* has high inter-channel correlation.
* - clip 1, compression level 0: 446%
* - clip 1, compression level 5: 512%
* - clip 1, compression level 8: 541%
* - clip 2, compression level 0: 321%
* - clip 2, compression level 5: 354%
* - clip 2, compression level 8: 388%
* - clip 3, compression level 0: 262%
* - clip 3, compression level 5: 303%
* - clip 3, compression level 8: 338%
*
* These are the file sizes from the previous tests:
* - clip 1, uncompressed: 32.7MiB
* - clip 1, compression level 0: 25.7MiB
* - clip 1, compression level 5: 23.7MiB
* - clip 1, compression level 8: 23.4MiB
* - clip 2, uncompressed: 49.6MiB
* - clip 2, compression level 0: 33.1MiB
* - clip 2, compression level 5: 26.8MiB
* - clip 2, compression level 8: 26.3MiB
* - clip 3, uncompressed: 9.0MiB
* - clip 3, compression level 0: 6.2MiB
* - clip 3, compression level 5: 6.1MiB
* - clip 3, compression level 8: 6.0MiB
*
* @note Before encoding FLAC sounds with unusual framerates, please read
* the documentation for @ref FlacEncoderSettings::streamableSubset.
*/
eFlac,
/** The Opus codec.
* This is a lossy codec that is designed to be suitable for almost any
* application.
* Opus can encode very high quality lossy audio, similarly to @ref
* SampleFormat::eVorbis.
* Opus can encode very low bitrate audio at a much higher quality than
* @ref SampleFormat::eVorbis.
* Opus also offers much lower bitrates than @ref SampleFormat::eVorbis.
* Opus is designed for low latency usage, with a minimum latency of 5ms
* and a block size configurable between 2.5ms and 60ms.
* Opus also offers forward error correction to handle packet loss during
* transmission.
*
* Opus is stored in Ogg file containers (.ogg or .oga), but in use cases
* such as network transmission, Ogg containers are not necessary.
* Opus only supports sample rates of 48000Hz, 24000Hz, 16000Hz, 12000Hz and 8000Hz.
* Passing unsupported frame rates below 48KHz to the encoder will result
* in the input audio being resampled to the next highest supported frame
* rate.
* Passing frame rates above 48KHz to the encoder will result in the input
* audio being resampled down to 48KHz.
* The 'Opus Custom' format, which removes this frame rate restriction, is
* not supported.
*
* Opus has a defined channel mapping for audio with 1-8 channels.
* The channel mapping is identical to that of @ref SampleFormat::eVorbis.
* For streams with more than 8 channels, the mapping is undefined and
* must be determined by the application.
* Up to 255 audio channels are supported.
*
* Opus has three modes of operation: a linear predictive coding (LPC)
* mode, a modified discrete cosine transform (MCDT) mode and a hybrid
* mode which combines both the LPC and MCDT mode.
* The LPC mode is optimized to encode voice data at low bitrates and has
* the ability to use forward error correction and packet loss compensation.
* The MCDT mode is suitable for general purpose audio and is optimized
* for minimal latency.
*
* Because Opus uses a fixed number of frames per block, additional
* padding will be added when encoding with a @ref CodecState, unless the
* frame size is specified in advance with @ref OpusEncoderSettings::frames.
*
* These are the results of decoding speed tests run on Opus; they are
* shown as the decoding time relative to decoding a 16 bit uncompressed
* WAVE file to @ref SampleFormat::ePcm32. Clip 1 and 2 are stereo music.
* Clip 3 is a mono voice recording. Clip 1 has low inter-channel
* correlation; Clip 2 has high inter-channel correlation.
* Note that the bitrates listed here are approximate, since Opus is
* variable bitrate.
* - clip 1, 64kb/s: 975%
* - clip 1, 128kb/s: 1181%
* - clip 1, 320kb/s: 2293%
* - clip 2, 64kb/s: 780%
* - clip 2, 128kb/s: 1092%
* - clip 2, 320kb/s: 2376%
* - clip 3, 64kb/s: 850%
* - clip 3, 128kb/s: 997%
* - clip 3, 320kb/s: 1820%
*
* These are the file sizes from the previous tests:
* - clip 1, uncompressed: 32.7MiB
* - clip 1, 64kb/s: 1.5MiB
* - clip 1, 128kb/s: 3.0MiB
* - clip 1, 320kb/s: 7.5MiB
* - clip 2, uncompressed: 49.6MiB
* - clip 2, 64kb/s: 2.3MiB
* - clip 2, 128kb/s: 4.6MiB
* - clip 2, 320kb/s: 11.3MiB
* - clip 3, uncompressed: 9.0MiB
* - clip 3, 64kb/s: 1.7MiB
* - clip 3, 128kb/s: 3.3MiB
* - clip 3, 320kb/s: 6.7MiB
*/
eOpus,
/** MPEG audio layer 3 audio encoding.
* This is currently supported for decoding only; to compress audio with a
* lossy algorithm, @ref SampleFormat::eVorbis or @ref SampleFormat::eOpus
* should be used.
*
* The MP3 decoder currently only has experimental support for seeking;
* files encoded by LAME seem to seek with frame-accurate precision, but
* results may vary on other encoders.
* It is recommended to load the file with @ref fDataFlagDecode,
* if you intend to use frame-accurate loops.
*
* MP3 is faster to decode than @ref SampleFormat::eVorbis and @ref
* SampleFormat::eOpus.
* This is particularly noticeable because MP3's decoding speed is not
* affected as significantly by increasing bitrates as @ref
* SampleFormat::eVorbis and @ref SampleFormat::eOpus.
* The quality degradation of MP3 with low bitrates is much more severe
* than with @ref SampleFormat::eVorbis and @ref SampleFormat::eOpus, so
* this difference in performance is not as severe as it may appear.
* The following are the times needed to decode a sample file that is
* about 10 minutes long:
* | encoding: | time (seconds): |
* |-----------------|-----------------|
* | 45kb/s MP3 | 0.780 |
* | 64kb/s MP3 | 0.777 |
* | 128kb/s MP3 | 0.904 |
* | 320kb/s MP3 | 1.033 |
* | 45kb/s Vorbis | 1.096 |
* | 64kb/s Vorbis | 1.162 |
* | 128kb/s Vorbis | 1.355 |
* | 320kb/s Vorbis | 2.059 |
* | 45kb/s Opus | 1.478 |
* | 64kb/s Opus | 1.647 |
* | 128kb/s Opus | 2.124 |
* | 320kb/s Opus | 2.766 |
*/
eMp3,
/** the data is in an unspecified compressed format. Being able to interpret the data in
* the sound requires extra information on the caller's part.
*/
eRaw,
/** the default or preferred sample format for a device. This format name is only valid when
* selecting a device or decoding data.
*/
eDefault,
/** the number of supported sample formats. This is not a valid format and is only used
* internally to determine how many formats are available.
*/
eCount,
};
/** provides information about the format of a sound. This is used both when creating the sound
* and when retrieving information about its format. When a sound is loaded from a file, its
* format will be implicitly set on load. The actual format can then be retrieved later with
* getSoundFormat().
*/
struct SoundFormat
{
/** the number of channels of data in each frame of the audio data. */
size_t channels;
/** the number of bits per sample of the audio data. This is also encoded in the @ref format
* value, but it is given here as well for ease of use in calculations. This represents the
* number of bits in the decoded samples of the sound stream.
* This will be 0 for variable bitrate compressed formats.
*/
size_t bitsPerSample;
/** the size in bytes of each frame of data in the format. A frame consists of one sample
* per channel. This represents the size of a single frame of decoded data from the sound
* stream.
* This will be 0 for variable bitrate compressed formats.
*/
size_t frameSize;
/** The size in bytes of a single 'block' of encoded data.
* For PCM data, this is the same as a frame.
* For formats with a fixed bitrate, this is the size of a single unit of
* data that can be decoded.
* For formats with a variable bitrate, this will be 0.
* Note that certain codecs can be fixed or variable bitrate depending on
* the encoder settings.
*/
size_t blockSize;
/** The number of frames that will be decoded from a single block of data.
* For PCM formats, this will be 1.
* For formats with a fixed number of frames per block, this will be
* number of frames of data that will be produced when decoding a single
* block of data. Note that variable bitrate formats can have a fixed
* number of frames per block.
* For formats with a variable number of frames per block, this will be 0.
* Note that certain codecs can have a fixed or variable number of frames
* per block depending on the encoder settings.
*/
size_t framesPerBlock;
/** the number of frames per second that must be played back for the audio data to sound
* 'normal' (ie: the way it was recorded or produced).
*/
size_t frameRate;
/** the channel mask for the audio data. This specifies which speakers the stream is intended
* for and will be a combination of one or more of the @ref Speaker names or a
* @ref SpeakerMode name. This may be calculated from the number of channels present in the
* original audio data or it may be explicitly specified in the original audio data on load.
*/
SpeakerMode channelMask;
/** the number of bits of valid data that are present in the audio data. This may be used to
* specify that (for example) a stream of 24-bit sample data is being processed in 32-bit
* containers. Each sample will actually consist of 32-bit data in the buffer, using the
* full 32-bit range, but only the top 24 bits of each sample will be valid useful data.
* This represents the valid number of bits per sample in the decoded data for the sound
* stream.
*/
size_t validBitsPerSample;
/** the format of each sample of audio data. This is given as a symbolic name so
* that the data can be interpreted properly. The size of each sample in bits is also
* given in the @ref bitsPerSample value.
*/
SampleFormat format = SampleFormat::eDefault;
};
/** special value for @ref DeviceCaps::index to indicate that a real audio device is not currently
* selected for output. When this value is present, a streamer output is in use instead. This
* value will only ever be set on the DeviceCaps object returned in the result of the
* IAudioPlayback::getContextCaps() function.
*/
constexpr size_t kInvalidDeviceIndex = ~0ull;
/** contains information about a single audio input or output device. This information can be
* retrieved with IAudioPlayback::getDeviceCaps() or IAudioCapture::getDeviceCaps().
* Note that this information should not be stored since it can change at any time due to user
* activity (ie: unplugging a device, plugging in a new device, changing system default devices,
* etc). Device information should only be queried just before deciding which device to select.
*/
struct DeviceCaps
{
/** indicates the size of this object to allow for versioning and future expansion. This
* must be set to sizeof(DeviceCaps) before calling getDeviceCaps().
*/
size_t thisSize = sizeof(DeviceCaps);
/** the current index of this device in the enumeration order. Note that this value is highly
* volatile and can change at any time due to user action (ie: plugging in or removing a
* device from the system). When a device is added to or removed from the system, the
* information for the device at this index may change. It is the caller's responsibility
* to refresh its collected device information if the device list changes. The device at
* index 0 will always be considered the system's 'default' device.
*/
size_t index;
/** flags to indicate some attributes about this device. These may change at any time due
* to user action (ie: unplugging a device or switching system defaults). This may be 0
* or any combination of the fDeviceFlag* flags.
*/
DeviceFlags flags;
/** a UTF-8 string that describes the name of the audio device. This will most often be a
* 'friendly' name for the device that is suitable for display to the user. This cannot
* be guaranteed for all devices or platforms since its contents are defined by the device
* driver. The string will always be null terminated and may have been truncated if it
* was too long.
*/
char name[kMaxNameLength];
/** a GUID that can be used to uniquely identify the device. The GUID for a given device
* may not be the same from one process to the next, or if the device is removed from the
* system and reattached. The GUID will remain constant for the entire time the device
* is connected to the system however.
*/
carb::extras::Guid guid;
/** the preferred number of channels of data in each frame of the audio data. Selecting
* a device using a different format than this will result in extra processing overhead
* due to the format conversion.
*/
size_t channels;
/** the preferred number of frames per second that must be played back for the audio
* data to sound 'normal' (ie: the way it was recorded or produced). Selecting a
* device using a different frame rate than this will result in extra processing
* overhead due to the frame rate conversion.
*/
size_t frameRate;
/** the preferred format of each sample of audio data. This is given as a symbolic name so
* that the data can be interpreted properly. Selecting a device using a different format
* than this will result in extra processing overhead due to the format conversion.
*/
SampleFormat format = SampleFormat::eDefault;
};
/** various default values for the audio system.
* @{
*/
constexpr size_t kDefaultFrameRate = 48000; ///< default frame rate.
constexpr size_t kDefaultChannelCount = 1; ///< default channel count.
constexpr SampleFormat kDefaultFormat = SampleFormat::ePcmFloat; ///< default sample format.
/** @} */
/** An estimate of the time in microseconds below which many users cannot perceive a
* synchronization issue between a sound and the visual it should be emitted from.
* There are definitely some users that can tell there is a problem with audio/visual
* sync timing close to this value, but they may not be able to say which direction
* the sync issue goes (ie: audio first vs visual event first).
*/
constexpr int64_t kImperceptibleDelay = 200000;
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/IAudioCapture.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief The audio capture interface.
*/
#pragma once
#include "../Interface.h"
#include "../assets/IAssets.h"
#include "AudioTypes.h"
namespace carb
{
namespace audio
{
/******************************** typedefs, enums, & macros **************************************/
/** prototype for a device change callback function.
*
* @param[in] context the context object that triggered the callback.
* @param[in] userData the user data value that was registered with the callback when the
* context object was created.
* @returns no return value.
*
* @remarks This callback will be performed any time an audio capture device changes its
* connection state. This includes when a device is connected to or disconnected
* from the system, or when the system's default capture device changes.
*
* @remarks Only the fact that a change occurred will be implied with this callback. It will
* not deliver specific information about the device or devices that changed (it could
* be many or just one). It is the callback's responsibility to re-discover the
* device list information and decide what if anything should be done about the
* change. The changed device is not reported due to the inherently asynchronous
* nature of device change notifications - once the callback decides to collect
* information about a device it may have already changed again.
*
* @note The callback will always be performed in the context of the thread that calls into
* the update() function. It is the callback's responsibility to ensure that any shared
* resources are accessed in a thread safe manner.
*/
typedef void(CARB_ABI* DeviceChangeCallback)(Context* context, void* userData);
/** flags to control the capture device selection. No flags are currently defined. */
typedef uint32_t CaptureDeviceFlags;
/** Ignore overruns during capture.
* IAudioCapture::lock(), IAudioCapture::read(), IAudioCapture::lock(),
* IAudioCapture::unlock() and IAudioCapture::getAvailableFrames()
* will no longer return @ref AudioResult::eOverrun when the audio device overruns.
* This may be useful in some unexpected circumstance.
*/
constexpr CaptureDeviceFlags fCaptureDeviceFlagIgnoreOverruns = 0x1;
/** describes the parameters to use when selecting a capture device. This includes the sound
* format, buffer length, and device index. This is used when selecting an audio capture device
* with IAudioCapture::setSource().
*/
struct CaptureDeviceDesc
{
/** flags to control the behavior of selecting a capture device. No flags are currently
* defined. These may be used to control how the values in @ref ext are interpreted.
*/
CaptureDeviceFlags flags = 0;
/** the index of the device to be opened. This must be less than the return value of the most
* recent call to getDeviceCount(). Note that since the capture device list can change at
* any time asynchronously due to external user action, setting any particular value here
* is never guaranteed to be valid. There is always the possibility the user could remove
* the device after its information is collected but before it is opened. Using this
* index may either fail to open or open a different device if the system's set of connected
* capture devices changes. The only value that guarantees a device will be opened (at
* least with default settings) is device 0 - the system's default capture device, as long
* as at least one is connected.
*/
size_t deviceIndex = 0;
/** the frame rate to capture audio at. Note that if this is different from the device's
* preferred frame rate (retrieved from a call to getDeviceCaps()), a resampler will have
* to be added to convert the recorded sound to the requested frame rate. This will incur
* an extra processing cost. This may be 0 to use the device's preferred frame rate. The
* actual frame rate may be retrieved with getSoundFormat().
*/
size_t frameRate = 0;
/** the number of channels to capture audio into. This should match the device's preferred
* channel count (retrieved from a recent call to getDeviceCaps()). If the channel count is
* different, the captured audio may not appear in the expected channels of the buffer. For
* example, if a mono source is used, the captured audio may only be present in the front
* left channel of the buffer. This may be 0 to use the device's preferred channel count.
* The actual channel count may be retrieved with getSoundFormat().
*/
size_t channels = 0;
/** the format of each audio sample that is captured. If this does not match the device's
* preferred sample format, a conversion will be performed internally as needed. This will
* incur an extra processing cost however. This may be @ref SampleFormat::eDefault to
* indicate that the device's preferred format should be used instead. In this case, the
* actual sample format may be retrieved with getSoundFormat(). Only PCM sample formats
* and @ref SampleFormat::eDefault are allowed.
*/
SampleFormat sampleFormat = SampleFormat::eDefault;
/** the requested length of the capture buffer. The interpretation of this size value depends
* on the @a lengthType value. This may be given as a byte count, a frame count, or a time
* in milliseconds or microseconds. This may be set to 0 to allow a default buffer length
* to be chosen. If a zero buffer size is used, the buffer's real size can be discovered
* later with a call to getBufferSize(). Note that if a buffer size is given in bytes, it
* may be adjusted slightly to ensure it is frame aligned.
*/
size_t bufferLength = 0;
/** describes how the buffer length value should be interpreted. This value is ignored if
* @ref bufferLength is 0. Note that the buffer size will always be rounded up to the next
* frame boundary even if the size is specified in bytes.
*/
UnitType lengthType = UnitType::eFrames;
/** The number of fragments that the recording buffer is divided into.
* The buffer is divided into this number of fragments; each fragment must
* be filled before the data will be returned by IAudioCapture::lock() or
* IAudioCapture::read().
* If all of the fragments are filled during a looping capture, then this
* is considered an overrun.
* This is important to configure for low latency capture; dividing the
* buffer into smaller fragments will reduce additional capture latency.
* The minimum possible capture latency is decided by the underlying audio
* device (typically 10-20ms).
* This will be clamped to the range [2, 64]
*/
size_t bufferFragments = 8;
/** extended information for this object. This is reserved for future expansion and must be
* set to nullptr. The values in @ref flags will affect how this is interpreted.
*/
void* ext = nullptr;
};
/** flags to control the behavior of context creation. No flags are currently defined. */
typedef uint32_t CaptureContextFlags;
/** descriptor used to indicate the options passed to the createContext() function. This
* determines the how the context will behave and which capture device will be selected.
*/
struct CaptureContextDesc
{
/** flags to indicate some additional behavior of the context. No flags are currently
* defined. This should be set to 0. In future versions, these flags may be used to
* determine how the @ref ext member is interpreted.
*/
CaptureContextFlags flags = 0;
/** a callback function to be registered with the new context object. This callback will be
* performed any time the capture device list changes. This notification will only indicate
* that a change has occurred, not which specific change occurred. It is the caller's
* responsibility to re-enumerate devices to determine if any further action is necessary
* for the updated device list. This may be nullptr if no device change notifications are
* needed.
*/
DeviceChangeCallback changeCallback = nullptr;
/** an opaque context value to be passed to the callback whenever it is performed. This value
* will never be accessed by the context object and will only be passed unmodified to the
* callback function. This value is only used if a device change callback is provided.
*/
void* callbackContext = nullptr;
/** a descriptor of the capture device to initially use for this context. If this device
* fails to be selected, the context will still be created and valid, but any attempt to
* capture audio on the context will fail until a source is successfully selected with
* IAudioCapture::setSource(). The source used on this context may be changed any time
* a capture is not in progress using IAudioCapture::setSource().
*/
CaptureDeviceDesc device;
/** extended information for this descriptor. This is reserved for future expansion and
* must be set to nullptr.
*/
void* ext = nullptr;
};
/** stores the buffer information for gaining access to a buffer of raw audio data. A buffer of
* audio data is a linear buffer that may wrap around if it is set to loop. If the requested
* lock region extends past the end of the buffer, it will wrap around to the beginning by
* returning a second pointer and length as well. If the lock region does not wrap around,
* only the first pointer and length will be returned. The second pointer will be nullptr and
* the second length will be 0.
*
* The interpretation of this buffer is left up to the caller that locks it. Since the lock
* regions point to the raw audio data, it is the caller's responsibility to know the data's
* format (ie: bits per sample) and channel count and interpret them properly. The data format
* information can be collected with the IAudioCapture::getSoundFormat() call.
*
* Note that these returned pointers are writable. It is possible to write new data to the
* locked regions of the buffer (for example, clearing the buffer for security purposes after
* reading), but it is generally not advised or necessary. If the capture buffer is looping,
* the contents will quickly be overwritten soon anyway.
*/
struct LockRegion
{
/** pointer to the first chunk of locked audio data. This will always be non-nullptr on a
* successful lock operation. This will point to the first byte of the requested frame
* offset in the audio buffer.
*/
void* ptr1;
/** The length of ptr1 in frames. */
size_t len1;
/** pointer to the second chunk of locked audio data. This will be nullptr on a successful
* lock operation if the requested lock region did not wrap around the end of the capture
* buffer. This will always point to the first byte in the audio buffer if it is
* non-nullptr.
*/
void* ptr2;
/** The length of ptr2 in frames. */
size_t len2;
};
/********************************** IAudioCapture Interface **************************************/
/** Low-Level Audio Capture Plugin Interface.
*
* See these pages for more detail:
* @rst
* :ref:`carbonite-audio-label`
* :ref:`carbonite-audio-capture-label`
@endrst
*/
struct IAudioCapture
{
CARB_PLUGIN_INTERFACE("carb::audio::IAudioCapture", 1, 0)
/************************ device and context management functions ****************************/
/** retrieves the current audio capture device count for the system.
*
* @returns the number of audio capture devices that are currently connected to the system
* or known to the system. The system's default or preferred device can be found
* by looking at the @a flags member of the info structure retrieved from
* getDeviceCaps(). The default capture device will always be device 0.
*
* @note The device count is a potentially volatile value. This can change at any time,
* without notice, due to user action. For example, the user could remove an audio
* device from the system or add a new one at any time. Thus it is a good idea to
* select the device with setSource() as quickly as possible after choosing the device
* index. There is no guarantee that the device list will even remain stable during
* a single device enumeration loop. The only device index that is guaranteed to be
* valid is the system default device index of 0 (as long as at least one capture
* device is connected).
*/
size_t(CARB_ABI* getDeviceCount)();
/** retrieves the capabilities and information about a single audio capture device.
*
* @param[in] deviceIndex the index of the device to retrieve info for. This must be
* between 0 and the most recent return value from getDeviceCount().
* @param[out] caps receives the device information. The @a thisSize value must be set
* to sizeof(DeviceCaps) before calling.
* @retval AudioResult::eOk if the device info was successfully retrieved.
* @retval AudioResult::eOutOfRange if the requested device index was out of range
* of devices connected to the system.
* @retval AudioResult::eInvalidParameter if the @a thisSize value was not initialized
* in @p caps or @p caps was nullptr.
* @retval AudioResult::eNotAllowed if the device list could not be accessed.
* @returns an @ref AudioResult error code if the call fails for any other reason.
*
* @remarks This retrieves information about a single audio capture device. The
* information will be returned in the @p caps buffer. This may fail if the
* device corresponding to the requested index has been removed from the
* system.
*/
AudioResult(CARB_ABI* getDeviceCaps)(size_t deviceIndex, DeviceCaps* caps);
/** creates a new audio capture context object.
*
* @param[in] desc a descriptor of the initial settings for the capture context. This
* may be nullptr to create a context that uses the default capture
* device in its preferred format. The device's format information
* may later be retrieved with getSoundFormat().
* @returns the newly created audio capture context object if it was successfully created.
* @returns nullptr if a new context object could not be created.
*
* @remarks This creates a new audio capture context object. This object is responsible
* for managing all access to a single instance of the audio capture device. Note
* that there will be a separate recording thread associated with each instance of
* the capture context.
*
* @note If the requested device fails to be set during context creation, the returned
* context object will still be valid, but it will not be able to capture until a
* successful call to setSource() returns. This case may be checked upon return
* using isSourceValid().
*/
Context*(CARB_ABI* createContext)(const CaptureContextDesc* desc);
/** destroys an audio capture context object.
*
* @param[in] context the context object to be destroyed. Upon return, this object will no
* longer be valid.
* @retval AudioResult::eOk if the object was successfully destroyed.
* @retval AudioResult::eInvalidParameter if nullptr is passed in.
*
* @remarks This destroys an audio capture context object that was previously created
* with createContext(). If the context is still active and has a running capture
* thread, it will be stopped before the object is destroyed. All resources
* associated with the context will be both invalidated and destroyed as well.
*/
AudioResult(CARB_ABI* destroyContext)(Context* context);
/** selects a capture device and prepares it to begin recording.
*
* @param[in] context the context object to set the capture source. This context may not
* be actively capturing data when calling this function. A call to
* captureStop() must be made first in this case.
* @param[in] desc a descriptor of the device that should be opened and what format the
* captured data should be in. This may be nullptr to select the
* system's default capture device in its preferred format and a default
* capture buffer size.
* @retval AudioResult::eOk if the requested device was successfully opened.
* @retval AudioResult::eNotAllowed if a capture is currently running.
* @retval AudioResult::eOutOfRange if the requested device index is not valid.
* @retval AudioResult::eInvalidFormat if the requested frame rate or channel count
* is not allowed.
* @returns an @ref AudioResult error code if the device could not be opened.
*
* @remarks This selects a capture device and sets up the recording buffer for it. The audio
* will always be captured as uncompressed PCM data in the requested format. The
* captured audio can be accessed using the lock() and unlock() functions, or with
* read().
*
* @remarks The length of the buffer would depend on the needs of the caller. For example,
* if a looping capture is used, the buffer should be long enough that the caller
* can keep pace with reading the data as it is generated, but not too long that
* it will introduce an unnecessary amount of latency between when the audio is
* captured and the caller does something with it. In many situations, a 10-20
* millisecond buffer should suffice for streaming applications. A delay greater
* than 100ms between when audio is produced and heard will be noticeable to the
* human ear.
*
* @note If this fails, the state of the context may be reset. This must succeed before
* any capture operation can be started with captureStart(). All efforts will be
* made to keep the previous source valid in as many failure cases as possible, but
* this cannot always be guaranteed. If the call fails, the isSourceValid() call can
* be used to check whether a capture is still possible without having to call
* setSource() again.
*
* @note If this succeeds (or fails in non-recoverable ways mentioned above), the context's
* state will have been reset. This means that any previously captured data will be
* lost and that any previous data format information may be changed. This includes
* the case of selecting the same device that was previously selected.
*/
AudioResult(CARB_ABI* setSource)(Context* context, const CaptureDeviceDesc* desc);
/** checks whether a valid capture source is currently selected.
*
* @param[in] context the context to check the capture source on. This may not be nullptr.
* @returns true if the context's currently selected capture source is valid and can start
* a capture.
* @returns false if the context's source is not valid or could not be selected.
*
* @remarks This checks whether a context's current source is valid for capture immediately.
* This can be used after capture creation to test whether the source was
* successfully selected instead of having to attempt to start a capture then
* clear the buffer.
*/
bool(CARB_ABI* isSourceValid)(Context* context);
/**************************** capture state management functions *****************************/
/** starts capturing audio data from the currently opened device.
*
* @param[in] context the context object to start capturing audio from. This context must
* have successfully selected a capture device either on creation or by
* using setSource(). This can be verified with isSourceValid().
* @param[in] looping set to true if the audio data should loop over the buffer and
* overwrite previous data once it reaches the end. Set to false to
* perform a one-shot capture into the buffer. In this mode, the capture
* will automatically stop once the buffer becomes full.
* Note that the cursor position is not reset when capture is stopped,
* so starting a non-looping capture session will result in the remainder
* of the buffer being captured.
*
* @retval AudioResult::eOk if the capture is successfully started.
* @retval AudioResult::eDeviceNotOpen if a device is not selected in the context.
* @returns an AudioResult::* error code if the capture could not be started for any other
* reason.
*
* @remarks This starts an audio capture on the currently opened device for a context. The
* audio data will be captured into an internal data buffer that was created with
* the information passed to the last call to setSource() or when the context was
* created. The recorded audio data can be accessed by locking regions of the
* buffer and copying the data out, or by calling read() to retrieve the data as
* it is produced.
*
* @remarks If the capture buffer is looping, old data will be overwritten after
* the buffer fills up. It is the caller's responsibility in this case to
* periodically check the capture's position with getCaptureCuror(), and
* read the data out once enough has been captured.
*
* @remarks If the capture is not looping, the buffer's data will remain intact even
* after the capture is complete or is stopped. The caller can read the data
* back at any time.
*
* @remarks When the capture is started, any previous contents of the buffer will remain
* and will be added to by the new captured data. If the buffer should be
* cleared before continuing from a previous capture, the clear() function must
* be explicitly called first. Each time a new capture device is selected with
* setSource(), the buffer will be cleared implicitly. Each time the capture
* is stopped with captureStop() however, the buffer will not be cleared and can
* be added to by starting it again.
*/
AudioResult(CARB_ABI* captureStart)(Context* context, bool looping);
/** stops capturing audio data from the selected device.
*
* @param[in] context the context object to stop capturing audio on. This context object
* must have successfully opened a device either on creation or by using
* setSource().
* @returns @ref AudioResult::eOk if the capture is stopped.
* @returns @ref AudioResult::eDeviceNotOpen if a device is not open.
* @returns an AudioResult::* error code if the capture could not be stopped or was never
* started in the first place.
*
* @remarks This stops an active audio capture on the currently opened device for a
* context. The contents of the capture buffer will be left unmodified and can
* still be accessed with lock() and unlock() or read(). If the capture is
* started again, it will be resumed from the same location in the buffer as
* when it was stopped unless clear() is called.
*
* @note If the capture is stopped somewhere in the middle of the buffer (whether
* looping or not), the contents of the remainder of the buffer will be
* undefined. Calling getCaptureCursor() even after the capture is stopped
* will still return the correct position of the last valid frame of data.
*/
AudioResult(CARB_ABI* captureStop)(Context* context);
/** retrieves the current capture position in the device's buffer.
*
* @param[in] context the context object that the capture is occurring on. This context
* object must have successfully opened a device either on creation or
* by using setSource().
* @param[in] type the units to retrieve the current position in. Note that this may
* not return an accurate position if units in milliseconds or
* microseconds are requested. If a position in bytes is requested, the
* returned value will always be aligned to a frame boundary.
* @param[out] position receives the current position of the capture cursor in the units
* specified by @p type. All frames in the buffer up to this point
* will contain valid audio data.
* @retval AudioResult::eOk if the current capture position is successfully retrieved.
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @returns an AudioResult::* error code if the capture position could not be retrieved.
*
* @remarks This retrieves the current capture position in the buffer. This position will be
* valid even after the capture has been stopped with captureStop(). All data in
* the buffer up to the returned position will be valid. If the buffer was looping,
* some of the data at the end of the buffer may be valid as well.
*/
AudioResult(CARB_ABI* getCaptureCursor)(Context* context, UnitType type, size_t* position);
/** checks whether the context is currently capturing audio data.
*
* @param[in] context the context object to check the recording state of.
* @returns true if the context is currently recording.
* @returns false if the context is not recording or no device has been opened.
*/
bool(CARB_ABI* isCapturing)(Context* context);
/********************************* data management functions *********************************/
/** locks a portion of the buffer to be read.
*
* @param[in] context the context object to read data from. This context object must have
* successfully opened a device either on creation or by using
* setSource().
* @param[in] length The length of the buffer to lock, in frames.
* This may be 0 to lock as much data as possible.
* @param[out] region receives the lock region information if the lock operation is
* successful. This region may be split into two chunks if the region
* wraps around the end of the buffer. The values in this struct are
* undefined if the function fails.
* @retval AudioResult::eOk if the requested region is successfully locked.
* @retval AudioResult::eDeviceNotOpen if no device is open.
* @retval AudioResult::eNotAllowed if a region is already locked and needs to be
* unlocked.
* @retval AudioResult::eOverrun if data has not been read fast
* enough and some captured data has overwritten unread data.
* @returns an @ref AudioResult error code if the region could not be locked.
*
* @remarks This locks a portion of the buffer so that data can be read back. The region may
* be split into two chunks if the region wraps around the end of the buffer. A
* non-looping buffer will always be truncated to the end of the buffer and only one
* chunk will be returned.
*
* @remarks Once the locked region is no longer needed, it must be unlocked with a call to
* unlock(). Only one region may be locked on the buffer at any given time.
* Attempting to call lock() twice in a row without unlocking first will result
* in the second call failing.
*/
AudioResult(CARB_ABI* lock)(Context* context, size_t length, LockRegion* region);
/** unlocks a previously locked region of the buffer.
*
* @param[in] context the context object to unlock the buffer on. This context object must
* have successfully opened a device either on creation or by using
* setSource().
* @retval AudioResult::eOk if the region is successfully unlocked.
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @retval AudioResult::eNotAllowed if no region is currently locked.
* @retval AudioResult::eOverrun if the audio device wrote to part
* of the locked buffer before unlock() was called.
* @returns an @ref AudioResult error code if the region could not be unlocked.
*
* @remarks This unlocks a region of the buffer that was locked with a previous call to
* lock(). Once the buffer is unlocked, a new region may be locked with lock().
*
* @note Once the buffer is unlocked, it is not guaranteed that the memory in the region
* will still be accessible. The caller should never cache the locked region
* information between unlocks and future locks. The next successful lock call
* may return a completely different region of memory even for the same offset
* in the buffer.
*/
AudioResult(CARB_ABI* unlock)(Context* context);
/** calculates the required buffer size to store the requested number of frames.
*
* @param[in] context the context object to calculate the buffer size for. This context
* object must have successfully opened a device either on creation
* or by using setSource().
* @param[in] framesCount the number of frames to calculate the storage space for.
* @returns the number of bytes required to store the requested frame count for this
* context's current data format.
* @returns 0 if no device has been selected.
*
* @remarks This is a helper function to calculate the required size in bytes for a buffer
* to store a requested number of frames. This can be used with read() to ensure
* a buffer is large enough to store the available number of frames of data.
*/
size_t(CARB_ABI* calculateReadBufferSize)(Context* context, size_t frameCount);
/** attempts to read captured data from the buffer.
*
* @param[in] context the context object to read data from. This context must have
* successfully opened a device either upon creation or by using
* setSource().
* @param[out] buffer receives the data that was read from the capture stream. This may
* be nullptr if only the available number of frames of data is required.
* In this case, the available frame count will be returned in the
* @p framesRead parameter. The contents of @p buffer are undefined if
* this function fails.
* @param[in] lengthInFrames the maximum number of frames of data that can fit in the
* buffer @p buffer. It is the caller's responsibility to
* know what the device's channel count is and account for
* that when allocating memory for the buffer. The size of
* the required buffer in bytes may be calculated with a call
* to calculateReadBufferSize(). This will always account for
* data format and channel count. If @p buffer is nullptr, this
* must be set to 0.
* @param[out] framesRead receives the total number of frames of audio data that were read
* into the buffer. This may be 0 if no new data is available to be
* read. It is the caller's responsibility to check this value after
* return to ensure garbage data is not being processed. It cannot
* be assumed that the buffer will always be completely filled. The
* calculateReadBufferSize() helper function can be used to calculate
* the size of the read data in bytes from this value. This value
* will not exceed @p lengthInFrames if @p buffer is not nullptr. If
* the buffer is nullptr, this will receive the minimum number of
* frames currently available to be read.
* @retval AudioResult::eOk if at least one frame of data is successfully read from the
* buffer.
* @retval AudioResult::eTryAgain if no data was available to read and @p buffer was
* not nullptr and no other errors occurred (the value in @p framesRead will be 0), or
* if @p buffer is `nullptr` and there is data to be read (the number of available
* frames will be stored in @p framesRead).
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @retval AudioResult::eOutOfMemory if @p lengthInFrames is 0 and @p buffer is not
* nullptr.
* @retval AudioResult::eOverrun if data has not been read fast
* enough and some captured data has overwritten unread data.
* @returns an @ref AudioResult error code if the operation failed for some other reason.
*
* @remarks This provides a means to read the captured audio data as a 'stream'. This
* behaves similarly to the libc read() function - it will read data from the
* current cursor position up to either as much data will fit in the buffer or
* is currently available to immediately read.
*
* @remarks This may be called with a nullptr buffer and 0 buffer length if only the number
* of available frames of data is needed. This call method may be used to determine
* the size of the buffer to pass in or to ensure the buffer is large enough. No
* actual data will be read and the next call with a non-nullptr buffer will be the
* one to consume the data. Note that if audio data is still being captured, the
* number of available frames of data may increase between two consecutive calls.
* This is fine as only the number of frames that will fit in the output buffer
* will be consumed and any extra frames that were captured in the meantime can be
* consumed on the next call. The calcReadBufferSize() function may be used to
* help calculate the required buffer size in bytes from the available frame count.
*
* @note It is the caller's responsibility to call this frequently enough that the capture
* cursor on a looping buffer will not write over the data that has been read so far.
* If the capture cursor passes over the read cursor (ie: the last point that the data
* had been read up to), some corruption in the data may occur when it is finally read
* again. Data should be read from the buffer with a period of at most half the length
* of time required to fill the capture buffer.
*
* @note When this method of reading the captured data is used, it's not necessary to lock
* and unlock regions of the buffer. While using this read method may be easier, it
* may end up being less efficient in certain applications because it may incur some
* extra processing overhead per call that can be avoided with the use of lock(),
* unlock(), and getCaptureCursor(). Also, using this method cannot guarantee that
* the data will be delivered in uniformly sized chunks.
*
* @note The buffer length and read count must be specified in frames here, otherwise there
* is no accurate means of identifying how much data will fit in the buffer and how
* much data was actually read.
*/
AudioResult(CARB_ABI* read)(Context* context, void* buffer, size_t lengthInFrames, size_t* framesRead);
/** retrieves the size of the capture buffer in frames.
*
* @param[in] context the context object to retrieve the buffer size for. This context
* object must have successfully opened a device either upon creation or
* by using setSource().
* @param[in] type the units to retrieve the buffer size in.
* @returns the size of the capture buffer in the specified units.
* @returns 0 if a device hasn't been opened yet.
*
* @remarks This retrieves the actual size of the capture buffer that was created when the
* context opened its device. This is useful as a way to retrieve the buffer size
* in different units than it was created in (ie: create in frames but retrieved as
* time in milliseconds), or to retrieve the size of a buffer on a device that was
* opened with a zero buffer size.
*
* @remarks If the buffer length is requested in milliseconds or microseconds, it may not be
* precise due to rounding issues. The returned buffer size in this case will be
* the minimum time in milliseconds or microseconds that the buffer will cover.
*
* @remarks If the buffer length is requested in bytes, the returned size will always be
* aligned to a frame boundary.
*/
size_t(CARB_ABI* getBufferSize)(Context* context, UnitType type);
/** retrieves the captured data's format information.
*
* @param[in] context the context object to retrieve the data format information for. This
* context object must have successfully opened a device either upon
* creation or by using setSource().
* @param[out] format receives the data format information. This may not be nullptr.
* @retval AudioResult::eOk if the data format information is successfully returned.
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @returns an @ref AudioResult error code if any other error occurs.
*
* @remarks This retrieves the data format information for the internal capture buffer. This
* will identify how the captured audio is intended to be processed. This can be
* collected to identify the actual capture data format if the device is opened
* using its preferred channel count and frame rate.
*/
AudioResult(CARB_ABI* getSoundFormat)(Context* context, SoundFormat* format);
/** clears the capture buffer and resets it to the start.
*
* @param[in] context the context object to clear the buffer on. This context object must
* have successfully opened a device using setSource().
* @retval AudioResult::eOk if the capture buffer was successfully cleared.
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @retval AudioResult::eNotAllowed if the buffer is currently locked or currently capturing.
* @returns an @ref AudioResult error code if the operation fails for any other reason.
*
* @remarks This clears the contents of the capture buffer and resets its cursor back to the
* start of the buffer. This should only be done when the device is not capturing
* data. Attempting to clear the buffer while the capture is running will cause this
* call to fail.
*/
AudioResult(CARB_ABI* clear)(Context* context);
/** Get the available number of frames to be read.
* @param[in] context The context object to clear the buffer on. This context object must
* have successfully opened a device using setSource().
* @param[out] available The number of frames that can be read from the buffer.
* @retval AudioResult::eOk if the frame count was retrieved successfully.
* @retval AudioResult::eDeviceNotOpen if no device has been opened.
* @retval AudioResult::eOverrun if data has not been read fast enough and
* the buffer filled up.
*
*/
AudioResult(CARB_ABI* getAvailableFrames)(Context* context, size_t* available);
};
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/audio/AudioStreamerUtils.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Helper classes for streaming data from @ref carb::audio::IAudioPlayback.
*/
#pragma once
#include "AudioUtils.h"
#include "IAudioData.h"
#include "IAudioPlayback.h"
#include "IAudioUtils.h"
#include "../Framework.h"
#include "../cpp/Atomic.h"
#include "../events/IEvents.h"
#include "../../omni/extras/DataStreamer.h"
#include <atomic>
#include <string.h>
#if CARB_PLATFORM_WINDOWS
# define strdup _strdup
#endif
namespace carb
{
namespace audio
{
/** wrapper base class to handle defining new streamer objects in C++ classes. This base class
* handles all reference counting for the Streamer interface. Objects that inherit from this
* class should never be explicitly deleted. They should always be destroyed through the
* reference counting system. Each object that inherits from this will be created with a
* reference count of 1 meaning that the creator owns a single reference. When that reference
* is no longer needed, it should be released with release(). When all references are
* released, the object will be destroyed.
*
* Direct instantiations of this wrapper class are not allowed because it contains pure
* virtual methods. Classes that inherit from this must override these methods in order to
* be used.
*
* See these pages for more information:
* @rst
* :ref:`carbonite-audio-label`
* :ref:`carbonite-streamer-label`
@endrst
*/
class StreamerWrapper : public Streamer
{
public:
StreamerWrapper()
{
m_refCount = 1;
acquireReference = streamerAcquire;
releaseReference = streamerRelease;
openStream = streamerOpen;
writeStreamData = streamerWriteData;
closeStream = streamerClose;
}
/** acquires a single reference to this streamer object.
*
* @returns no return value.
*
* @remarks This acquires a new reference to this streamer object. The reference must be
* released later with release() when it is no longer needed. Each call to
* acquire() on an object must be balanced with a call to release(). When a new
* streamer object is created, it should be given a reference count of 1.
*/
void acquire()
{
m_refCount.fetch_add(1, std::memory_order_relaxed);
}
/** releases a single reference to this streamer object.
*
* @returns no return value.
*
* @remarks This releases a single reference to this streamer object. If the reference count
* reaches zero, the object will be destroyed. The caller should assume the object
* to have been destroyed unless it is well known that other local references still
* exist.
*/
void release()
{
if (m_refCount.fetch_sub(1, std::memory_order_release) == 1)
{
std::atomic_thread_fence(std::memory_order_acquire);
delete this;
}
}
/** Wait until the close() call has been given.
* @param[in] duration The duration to wait before timing out.
* @returns `true` if the close call has been given
* @returns `false` if the timeout was reached.
*
* @remarks If you disconnect a streamer via IAudioPlayback::setOutput(),
* the engine may not be stopped, so the streamer won't be
* immediately disconnected. In cases like this, you should call
* waitForClose() if you need to access the streamer's written data
* but don't have access to the close() call (e.g. if you're using
* an @ref OutputStreamer).
*/
template <class Rep, class Period>
bool waitForClose(const std::chrono::duration<Rep, Period>& duration) noexcept
{
return m_open.wait_for(true, duration);
}
/** sets the suggested format for this stream output.
*
* @param[inout] format on input, this contains the suggested data format for the stream.
* On output, this contains the accepted data format. The streamer
* may make some changes to the data format including the data type,
* sample rate, and channel count. It is strongly suggested that the
* input format be accepted since that will result in the least
* amount of processing overhead. The @a format, @a channels,
* @a frameRate, and @a bitsPerSample members must be valid upon
* return. If the streamer changes the data format, only PCM data
* formats are acceptable.
* @returns true if the data format is accepted by the streamer.
* @returns false if the streamer can neither handle the requested format nor
* can it change the requested format to something it likes.
*
* @remarks This sets the data format that the streamer will receive its data in. The
* streamer may change the data format to another valid PCM data format if needed.
* Note that if the streamer returns a data format that cannot be converted to by
* the processing engine, the initialization of the output will fail. Also note
* that if the streamer changes the data format, this will incur a small performance
* penalty to convert the data to the new format.
*
* @remarks This will be called when the audio context is first created. Once the format
* is accepted by both the audio context and the streamer, it will remain constant
* as long as the processing engine is still running on that context. When the
* engine is stopped (or the context is destroyed), a Streamer::close() call will
* be performed signaling the end of the stream. If the engine is restarted again,
* another open() call will be performed to signal the start of a new stream.
*
* @note This should not be called directly. This will be called by the audio processing
* engine when this streamer object is first assigned as an output on an audio context.
*/
virtual bool open(SoundFormat* format) = 0;
/** writes a buffer of data to the stream.
*
* @param[in] data the audio data being written to the streamer. This data will be in
* the format that was decided on in the call to open() during the
* context creation or the last call to setOutput(). This buffer will
* not persist upon return. The implementation must copy the contents
* of the buffer if it still needs to access the data later.
* @param[in] bytes the number of bytes of valid data in the buffer @p data.
* @retval StreamState::eNormal if the data was written successfully to the streamer
* and the data production rate should continue at the current rate.
* @retval StreamState::eMore if the data was written successfully to the streamer and
* the data production rate should be temporarily increased.
* @retval StreamState::eLess if the data was written successfully to the streamer and
* the data production rate should be temporarily reduced.
* @retval StreamState::eCritical if the data was written successfully to the streamer
* and more data needs to be provided as soon as possible.
* @retval StreamState::eMuchLess if the data was written successfully to the streamer
* and the data rate needs to be halved.
*
* @remarks This writes a buffer of data to the streamer. The streamer is responsible for
* doing something useful with the audio data (ie: write it to a file, write it to
* a memory buffer, stream it to another voice, etc). The caller of this function
* is not interested in whether the streamer successfully does something with the
* data - it is always assumed that the operation is successful.
*
* @note This must execute as quickly as possible. If this call takes too long to return
* and the output is going to a real audio device (through the streamer or some other
* means), an audible audio dropout could occur. If the audio context is executing
* in non-realtime mode (ie: baking audio data), this may take as long as it needs
* only at the expense of making the overall baking process take longer.
*
* @note This should not be called directly. This will be called by the audio processing
* engine when a buffer of new data is produced.
*/
virtual StreamState writeData(const void* data, size_t bytes) = 0;
/** closes the stream.
*
* @returns no return value.
*
* @remarks This signals that a stream has been finished. This occurs when the engine is
* stopped or the audio context is destroyed. No more calls to writeData() should
* be expected until the streamer is opened again.
*
* @note This should not be called directly. This will be called by the audio processing
* engine when audio processing engine is stopped or the context is destroyed.
*/
virtual void close() = 0;
protected:
virtual ~StreamerWrapper()
{
auto refCount = m_refCount.load(std::memory_order_relaxed);
CARB_UNUSED(refCount);
CARB_ASSERT(refCount == 0,
"deleting the streamer with refcount %zd - was it destroyed by a method other than calling release()?",
refCount);
}
private:
static void CARB_ABI streamerAcquire(Streamer* self)
{
StreamerWrapper* ctxt = static_cast<StreamerWrapper*>(self);
ctxt->acquire();
}
static void CARB_ABI streamerRelease(Streamer* self)
{
StreamerWrapper* ctxt = static_cast<StreamerWrapper*>(self);
ctxt->release();
}
static bool CARB_ABI streamerOpen(Streamer* self, SoundFormat* format)
{
StreamerWrapper* ctxt = static_cast<StreamerWrapper*>(self);
ctxt->m_open = true;
return ctxt->open(format);
}
static StreamState CARB_ABI streamerWriteData(Streamer* self, const void* data, size_t bytes)
{
StreamerWrapper* ctxt = static_cast<StreamerWrapper*>(self);
return ctxt->writeData(data, bytes);
}
static void CARB_ABI streamerClose(Streamer* self)
{
StreamerWrapper* ctxt = static_cast<StreamerWrapper*>(self);
ctxt->close();
ctxt->m_open = false;
ctxt->m_open.notify_all();
}
/** the current reference count to this object. This will be 1 on object creation. This
* object will be destroyed when the reference count reaches zero.
*/
std::atomic<size_t> m_refCount;
/** Flag that marks if the streamer is still open. */
carb::cpp::atomic<bool> m_open{ false };
};
/** a streamer object to write to a stream to a file. The stream will be output in realtime by
* default (ie: writing to file at the same rate as the sound would play back on an audio
* device). This can be sped up by not specifying the @ref fFlagRealtime flag. When this flag
* is not set, the stream data will be produced as fast as possible.
*
* An output filename must be set with setFilename() before the streamer can be opened. All
* other parameters will work properly as their defaults.
*/
class OutputStreamer : public StreamerWrapper
{
public:
/** Type definition for the behavioral flags for this streamer. */
typedef uint32_t Flags;
/** flag to indicate that the audio data should be produced for the streamer at the same
* rate as it would be produced for a real audio device. If this flag is not set, the
* data will be produced as quickly as possible.
*/
static constexpr Flags fFlagRealtime = 0x00000001;
/** flag to indicate that the output stream should be flushed to disk after each buffer is
* written to it. If this flag is not present, flushing to disk will not be guaranteed
* until the stream is closed.
*/
static constexpr Flags fFlagFlush = 0x00000002;
/** Constructor.
* @param[in] outputFormat The encoded format for the output file.
* @param[in] flags Behavioral flags for this instance.
*/
OutputStreamer(SampleFormat outputFormat = SampleFormat::eDefault, Flags flags = fFlagRealtime)
{
m_desc.flags = 0;
m_desc.filename = nullptr;
m_desc.inputFormat = SampleFormat::eDefault;
m_desc.outputFormat = outputFormat;
m_desc.frameRate = 0;
m_desc.channels = 0;
m_desc.encoderSettings = nullptr;
m_desc.ext = nullptr;
m_filename = nullptr;
m_encoderSettings = nullptr;
m_stream = nullptr;
m_utils = nullptr;
m_flags = flags;
}
/** retrieves the descriptor that will be used to open the output stream.
*
* @returns the descriptor object. This will never be nullptr. This can be used to
* manually fill in the descriptor if need be, or to just verify the settings
* that will be used to open the output stream.
*/
OutputStreamDesc* getDescriptor()
{
return &m_desc;
}
/** sets the flags that will control how data is written to the stream.
*
* @param[in] flags the flags that will control how data is written to the stream. This
* is zero or more of the kFlag* flags.
* @returns no return value.
*/
void setFlags(Flags flags)
{
m_flags = flags;
}
/** retrieves the flags that are control how data is written to the stream.
*
* @returns the flags that will control how data is written to the stream. This is zero
* or more of the kFlag* flags.
*/
Flags getFlags() const
{
return m_flags;
}
/** sets the output format for the stream.
*
* @param[in] format the output format for the stream. This can be SampleFormat::eDefault
* to use the same format as the input. If this is to be changed, this
* must be done before open() is called.
* @returns no return value.
*/
void setOutputFormat(SampleFormat format)
{
m_desc.outputFormat = format;
}
/** sets the filename for the output stream.
*
* @param[in] filename the filename to use for the output stream. This must be set
* before open() is called. This may not be nullptr.
* @returns no return value.
*/
void setFilename(const char* filename)
{
char* temp;
temp = strdup(filename);
if (temp == nullptr)
return;
if (m_filename != nullptr)
free(m_filename);
m_filename = temp;
m_desc.filename = m_filename;
}
/** retrieves the filename assigned to this streamer.
*
* @returns the filename assigned to this streamer. This will be nullptr if no filename
* has been set yet.
*/
const char* getFilename() const
{
return m_filename;
}
/** sets the additional encoder settings to use for the output stream.
*
* @param[in] settings the encoder settings block to use to open the output stream.
* This may be nullptr to clear any previously set encoder settings
* block.
* @param[in] sizeInBytes the size of the encoder settings block in bytes.
* @returns no return value.
*
* @remarks This sets the additional encoder settings block to use for the output stream.
* This block will be copied to be stored internally. This will replace any
* previous encoder settings block.
*/
void setEncoderSettings(const void* settings, size_t sizeInBytes)
{
void* temp;
if (settings == nullptr)
{
if (m_encoderSettings != nullptr)
free(m_encoderSettings);
m_encoderSettings = nullptr;
m_desc.encoderSettings = nullptr;
return;
}
temp = malloc(sizeInBytes);
if (temp == nullptr)
return;
if (m_encoderSettings != nullptr)
free(m_encoderSettings);
memcpy(temp, settings, sizeInBytes);
m_encoderSettings = temp;
m_desc.encoderSettings = m_encoderSettings;
}
bool open(SoundFormat* format) override
{
m_utils = getFramework()->acquireInterface<carb::audio::IAudioUtils>();
CARB_ASSERT(m_utils != nullptr, "the IAudioData interface was not successfully acquired!");
CARB_ASSERT(m_desc.filename != nullptr, "call setFilename() first!");
// update the output stream descriptor with the given format information and flags.
if ((m_flags & fFlagFlush) != 0)
m_desc.flags |= fStreamFlagFlushAfterWrite;
m_desc.channels = format->channels;
m_desc.frameRate = format->frameRate;
m_desc.inputFormat = format->format;
m_stream = m_utils->openOutputStream(getDescriptor());
return m_stream != nullptr;
}
StreamState writeData(const void* data, size_t bytes) override
{
CARB_ASSERT(m_utils != nullptr);
CARB_ASSERT(m_stream != nullptr);
m_utils->writeDataToStream(m_stream, data, bytesToFrames(bytes, m_desc.channels, m_desc.inputFormat));
return (m_flags & fFlagRealtime) != 0 ? StreamState::eNormal : StreamState::eCritical;
}
void close() override
{
CARB_ASSERT(m_utils != nullptr);
if (m_stream == nullptr)
return;
m_utils->closeOutputStream(m_stream);
m_stream = nullptr;
}
protected:
~OutputStreamer() override
{
if (m_stream != nullptr)
m_utils->closeOutputStream(m_stream);
if (m_filename != nullptr)
free(m_filename);
if (m_encoderSettings != nullptr)
free(m_encoderSettings);
}
private:
/** the current filename for the output stream. This must be a valid path before open()
* is called.
*/
char* m_filename;
/** the current encoder settings for the output stream. This may be nullptr if no extra
* encoder settings are needed.
*/
void* m_encoderSettings;
/** the flags describing how the stream should be written. This is a combination of zero
* or more of the kFlag* flags.
*/
Flags m_flags;
/** the descriptor to open the output stream with. The information in this descriptor is
* collected by making various set*() calls on this object, or by retrieving and editing
* the descriptor directly with getDescriptor().
*/
OutputStreamDesc m_desc;
/** the output stream to be operated on. This is created in the open() call when this
* streamer is first set as an output on an audio context.
*/
OutputStream* m_stream;
/** the data interface object. */
IAudioUtils* m_utils;
};
/** a null streamer implementation. This will accept all incoming audio data but will simply
* ignore it. The audio processing engine will be told to continue producing data at the
* current rate after each buffer is written. All data formats will be accepted.
*
* This is useful for silencing an output while still allowing audio processing based events to
* occur as scheduled.
*/
class NullStreamer : public StreamerWrapper
{
public:
NullStreamer()
{
}
bool open(SoundFormat* format) override
{
CARB_UNUSED(format);
return true;
}
StreamState writeData(const void* data, size_t bytes) override
{
CARB_UNUSED(data, bytes);
return m_state;
}
void close() override
{
}
/** sets the stream state that will be returned from writeData().
*
* @param[in] state the stream state to return from each writeData() call. This will
* affect the behavior of the audio processing engine and its rate
* of running new cycles. The default is @ref StreamState::eNormal.
* @returns no return value.
*/
void setStreamState(StreamState state)
{
m_state = state;
}
protected:
~NullStreamer() override
{
}
/** the stream state to be returned from each writeData() call. */
StreamState m_state = StreamState::eNormal;
};
/** An event that is sent when the audio stream opens.
* This will inform the listener of the stream's format and version.
*/
constexpr carb::events::EventType kAudioStreamEventOpen = 1;
/** An event that is sent when the audio stream closes. */
constexpr carb::events::EventType kAudioStreamEventClose = 2;
/** Version tag to mark @rstref{ABI breaks <abi-compatibility>}. */
constexpr int32_t kEventStreamVersion = 1;
/** A listener for data from an @ref EventStreamer.
* This allows an easy way to bind the necessary callbacks to receive audio
* data from the stream.
*/
class EventListener : omni::extras::DataListener
{
public:
/** Constructor.
* @param[inout] p The event stream that was returned from the
* getEventStream() call from an @ref EventStreamer.
* @param[in] open The callback which is sent when the audio stream
* is first opened.
* This is used to provide information about the
* data in the audio stream.
* @param[in] writeData The callback which is sent when a buffer of data
* is sent from the stream.
* These callbacks are only sent after an @p open()
* callback has been sent.
* Note that the data sent here may not be properly
* aligned for its data type due to the nature of
* @ref events::IEvents, so you should memcpy the
* data somewhere that's aligned for safety.
* @param[in] close This is called when the audio stream is closed.
*
* @remarks All that needs to be done to start receiving data is to create
* this class. Once the class is created, the callbacks will start
* being sent.
* Note that you must create the listener before the audio stream
* opens, otherwise the open event will never be received, so you
* will not receive data until the stream closes and re-opens.
*/
EventListener(carb::events::IEventStreamPtr p,
std::function<void(const carb::audio::SoundFormat* fmt)> open,
std::function<void(const void* data, size_t bytes)> writeData,
std::function<void()> close)
: omni::extras::DataListener(p)
{
OMNI_ASSERT(open, "this callback is not optional");
OMNI_ASSERT(writeData, "this callback is not optional");
OMNI_ASSERT(close, "this callback is not optional");
m_openCallback = open;
m_writeDataCallback = writeData;
m_closeCallback = close;
}
protected:
/** Function to pass received data to this audio streamer's destination.
*
* @param[in] payload The packet of data that was received. This is expected to contain
* the next group of audio frames in the stream on each call.
* @param[in] bytes The length of @p payload in bytes.
* @param[in] type The data type ID of the data contained in @p payload. This is
* ignored since calls to this handler are always expected to be plain
* data for the stream.
* @returns No return value.
*/
void onDataReceived(const void* payload, size_t bytes, omni::extras::DataStreamType type) noexcept override
{
CARB_UNUSED(type);
if (m_open)
{
m_writeDataCallback(payload, bytes);
}
}
/** Handler function for non-data events on the stream.
*
* @param[in] e The event that was received. This will either be an 'open' or 'close'
* event depending on the value of this event's 'type' member.
* @returns No return value.
*/
void onEventReceived(const carb::events::IEvent* e) noexcept override
{
carb::audio::SoundFormat fmt = {};
auto getIntVal = [this](const carb::dictionary::Item* root, const char* name) -> size_t {
const carb::dictionary::Item* child = m_dict->getItem(root, name);
return (child == nullptr) ? 0 : m_dict->getAsInt64(child);
};
switch (e->type)
{
case kAudioStreamEventOpen:
{
int32_t ver = int32_t(getIntVal(e->payload, "version"));
if (ver != kEventStreamVersion)
{
CARB_LOG_ERROR("EventListener version %" PRId32 " tried to attach to data stream version %" PRId32,
kEventStreamVersion, ver);
disconnect();
return;
}
fmt.channels = getIntVal(e->payload, "channels");
fmt.bitsPerSample = getIntVal(e->payload, "bitsPerSample");
fmt.frameSize = getIntVal(e->payload, "frameSize");
fmt.blockSize = getIntVal(e->payload, "blockSize");
fmt.framesPerBlock = getIntVal(e->payload, "framesPerBlock");
fmt.frameRate = getIntVal(e->payload, "frameRate");
fmt.channelMask = getIntVal(e->payload, "channelMask");
fmt.validBitsPerSample = getIntVal(e->payload, "validBitsPerSample");
fmt.format = SampleFormat(getIntVal(e->payload, "format"));
m_openCallback(&fmt);
m_open = true;
break;
}
case kAudioStreamEventClose:
if (m_open)
{
m_closeCallback();
m_open = false;
}
break;
default:
OMNI_LOG_ERROR("unknown event received %zd", size_t(e->type));
}
}
private:
std::function<void(const carb::audio::SoundFormat* fmt)> m_openCallback;
std::function<void(const void* data, size_t bytes)> m_writeDataCallback;
std::function<void()> m_closeCallback;
bool m_open = false;
};
/** A @ref events::IEvents based audio streamer.
* This will send a stream of audio data through @ref events::IEvents then
* pumps the event stream asynchronously.
* This is ideal for use cases where audio streaming is needed, but the
* component receiving audio is unable to meet the latency requirements of
* other audio streamers.
*
* To receive data from this, you will need to create an @ref EventListener
* with the event stream returned from the getEventStream() call on this class.
*/
class EventStreamer : public StreamerWrapper
{
public:
EventStreamer()
{
}
/** Check if the class actually initialized successfully.
* @returns whether the class actually initialized successfully.
*/
bool isWorking() noexcept
{
return m_streamer.isWorking();
}
/** Specify a desired format for the audio stream.
* @param[in] format The format that you want to be used.
* This can be `nullptr` to just use the default format.
*/
void setFormat(const SoundFormat* format) noexcept
{
if (format != nullptr)
{
m_desiredFormat = *format;
}
else
{
m_desiredFormat = {};
}
}
/** Create an @ref EventListener for this streamer.
*
* @param[in] open The callback which is sent when the audio stream
* is first opened.
* This is used to provide information about the
* data in the audio stream.
* @param[in] writeData The callback which is sent when a buffer of data
* is sent from the stream.
* These callbacks are only sent after an @p open()
* callback has been sent.
* Note that the data sent here may not be properly
* aligned for its data type due to the nature of
* @ref events::IEvents, so you should memcpy the
* data somewhere that's aligned for safety.
* @param[in] close This is called when the audio stream is closed.
*
* @returns An event listener.
* @returns `nullptr` if an out of memory error occurs.
*
* @remarks These callbacks will be fired until the @ref EventListener
* is deleted.
* Note that you must create the listener before the audio stream
* opens, otherwise the open event will never be received, so you
* will not receive data until the stream closes and re-opens.
*/
EventListener* createListener(std::function<void(const carb::audio::SoundFormat* fmt)> open,
std::function<void(const void* data, size_t bytes)> writeData,
std::function<void()> close)
{
return new (std::nothrow) EventListener(m_streamer.getEventStream(), open, writeData, close);
}
/** Retrieve the event stream used by the data streamer.
* @returns The event stream used by the data streamer.
*
* @remarks This event stream is exposed to be subscribed to.
* Sending other events into this stream will cause errors.
*/
carb::events::IEventStreamPtr getEventStream() noexcept
{
return m_streamer.getEventStream();
}
/** Wait for all asynchronous tasks created by this stream to finish. */
void flush() noexcept
{
m_streamer.flush();
}
private:
bool open(carb::audio::SoundFormat* format) noexcept override
{
if (!m_streamer.isWorking())
{
return false;
}
if (m_desiredFormat.channels != 0)
{
format->channels = m_desiredFormat.channels;
format->channelMask = kSpeakerModeDefault;
}
if (m_desiredFormat.frameRate != 0)
{
format->frameRate = m_desiredFormat.frameRate;
}
if (m_desiredFormat.channelMask != kSpeakerModeDefault)
{
format->channelMask = m_desiredFormat.channelMask;
}
if (m_desiredFormat.format != SampleFormat::eDefault)
{
format->format = m_desiredFormat.format;
}
m_streamer.getEventStream()->push(kAudioStreamEventOpen, std::make_pair("version", kEventStreamVersion),
std::make_pair("channels", int64_t(format->channels)),
std::make_pair("bitsPerSample", int64_t(format->bitsPerSample)),
std::make_pair("frameSize", int64_t(format->frameSize)),
std::make_pair("blockSize", int64_t(format->blockSize)),
std::make_pair("framesPerBlock", int64_t(format->framesPerBlock)),
std::make_pair("frameRate", int64_t(format->frameRate)),
std::make_pair("channelMask", int64_t(format->channelMask)),
std::make_pair("validBitsPerSample", int64_t(format->validBitsPerSample)),
std::make_pair("format", int32_t(format->format)));
m_streamer.pumpAsync();
return true;
}
void close() noexcept override
{
if (!m_streamer.isWorking())
{
return;
}
m_streamer.getEventStream()->push(kAudioStreamEventClose);
m_streamer.pumpAsync();
}
StreamState writeData(const void* data, size_t bytes) noexcept override
{
if (!m_streamer.isWorking())
{
return StreamState::eNormal;
}
// just push as bytes here, we'll clean up the type later
m_streamer.pushData(static_cast<const uint8_t*>(data), bytes);
m_streamer.pumpAsync();
return StreamState::eNormal;
}
SoundFormat m_desiredFormat = {};
omni::extras::DataStreamer m_streamer;
};
} // namespace audio
} // namespace carb
|
omniverse-code/kit/include/carb/fastcache/FastCacheTypes.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
namespace carb
{
namespace fastcache
{
struct Float4x4
{
float m[16];
};
struct Double4x4
{
double m[16];
};
// NOTE: omni physics relies on this struct being all floats.
// Actual fastcache users should use Transformd defined below.
struct Transform
{
carb::Float3 position;
carb::Float4 orientation;
carb::Float3 scale;
};
struct TransformD
{
TransformD() {}
explicit TransformD(const Transform& t) : orientation(t.orientation), scale(t.scale) {
position.x = t.position.x;
position.y = t.position.y;
position.z = t.position.z;
}
void CopyTo(Transform& t)
{
t.position.x = float(position.x);
t.position.y = float(position.y);
t.position.z = float(position.z);
t.orientation = orientation;
t.scale = scale;
}
carb::Double3 position;
carb::Float4 orientation;
carb::Float3 scale;
};
// This type can be casted to carb::scenerenderer::VertexElemDesc
struct BufferDesc
{
BufferDesc() = default;
BufferDesc(const void* _data, uint32_t _elementStride, uint32_t _elementSize)
: data(_data), elementStride(_elementStride), elementSize(_elementSize)
{
}
const void* data = nullptr; // float elements, vec2, vec3 or vec4
uint32_t elementStride = 0; // in bytes
uint32_t elementSize = 0; // in bytes
};
typedef uint32_t FastCacheDirtyFlags;
const FastCacheDirtyFlags kFastCacheClean = 0; // only copy data to fast cache
const FastCacheDirtyFlags kFastCacheDirtyTransformRender = 1 << 1; // do we write transform to hydra render sync?
const FastCacheDirtyFlags kFastCacheDirtyTransformScale = 1 << 2; // change scale? false if rigid transform only
const FastCacheDirtyFlags kFastCacheDirtyTransformChildren = 1 << 3; // update all the children?
const FastCacheDirtyFlags kFastCacheDirtyPoints = 1 << 4; // mesh point data dirtied?
const FastCacheDirtyFlags kFastCacheDirtyNormals = 1 << 5; // mesh normal data dirtied?
const FastCacheDirtyFlags kFastCacheDirtyAll = ~0;
// cannot use USD data types in header, so we cast them to void pointer
typedef void* UsdPrimPtr;
} // namespace fastcache
} // namespace carb
|
omniverse-code/kit/include/carb/fastcache/FastCache.h | // Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
#include <carb/fastcache/FastCacheTypes.h>
namespace carb
{
namespace fastcache
{
struct FastCache
{
CARB_PLUGIN_INTERFACE("carb::fastcache::FastCache", 0, 4)
/// API for simple transform update
// set transform for a usd prim to the fast cache
// see FastCacheDirtyBits for options for dirty bits
bool(CARB_ABI* setTransformF)(const pxr::SdfPath& primPath, const Transform& transform, FastCacheDirtyFlags dirtyFlags);
// set 4x4 matrix directly for this prim
bool(CARB_ABI* setWorldMatrixF)(const pxr::SdfPath& primPath, const Float4x4& mat, FastCacheDirtyFlags dirtyFlags);
/// Optimized API for faster transform update
/// each plugin should first call getCacheItemId to get integer id, then use set*ById functions below
// path->index map may have changed, other plugins should update cache index (use getCacheItemId below)
bool(CARB_ABI* indexMaybeDirty)(void);
// index into transform cache buffer for the given prim path
uint32_t(CARB_ABI* getCacheItemId)(const pxr::SdfPath& primPath);
// optimized transform update using precomputed index
bool(CARB_ABI* setTransformByIdF)(uint32_t, const Transform& transform, FastCacheDirtyFlags dirtyFlags);
// Dead function - does nothing.
bool(CARB_ABI* setWorldMatrixById)(uint32_t, const Float4x4& mat, FastCacheDirtyFlags dirtyFlags);
// set transform for a usd instance to the fast cache
// see FastCacheDirtyBits for options for dirty bits
bool(CARB_ABI* setInstanceTransformF)(const pxr::SdfPath& instancerPath,
const Transform& transform,
uint32_t instanceIndex,
FastCacheDirtyFlags dirtyFlags);
// Dead function - does nothing.
bool(CARB_ABI* setInstanceTransformBatch)(const pxr::SdfPath& instancerPath,
const Transform* transform,
uint32_t instanceCount,
uint32_t instanceStartIndex);
// Dead function - does nothing.
bool(CARB_ABI* setInstancePositionBatch)(const pxr::SdfPath& instancerPath,
const carb::Float3* position,
uint32_t instanceCount,
uint32_t instanceStartIndex);
// get transform from fast cache for a usd prim
bool(CARB_ABI* getTransformF)(const pxr::SdfPath& primPath, Transform& transform);
bool(CARB_ABI* setPositionBuffer)(const pxr::SdfPath& primPath, const BufferDesc& buffer);
bool(CARB_ABI* setNormalBuffer)(const pxr::SdfPath& primPath, const BufferDesc& binding);
/*
Sync with USD
*/
void(CARB_ABI* blockUSDUpdate)(bool val);
// Dead function - does nothing.
void(CARB_ABI* enableSyncFastUpdate)(bool val);
// Dead function - does nothing.
bool(CARB_ABI* syncFastUpdate)();
// Dead function - not implemented.
void(CARB_ABI* handleAddedPrim)(const pxr::SdfPath& primPath);
// Dead function - not implemented.
void(CARB_ABI* handleChangedPrim)(const pxr::SdfPath& primPath);
// Dead function - not implemented.
void(CARB_ABI* handleRemovedPrim)(const pxr::SdfPath& primPath);
// Dead function - not implemented.
void(CARB_ABI* resyncPrimCacheMap)(void);
// Dead function - not implemented.
void(CARB_ABI* clearAll)(void);
/// prim range cache
// get size of a prim range (usd prim + all of its decendents)
size_t(CARB_ABI* getPrimRangePathCount)(const pxr::SdfPath& primPath);
// get subtree info (prim range)
void(CARB_ABI* getPrimRangePaths)(const pxr::SdfPath& primPath, pxr::SdfPath* primRangePaths, size_t pathRangeSize);
// Scatter the position data to corresponding instance possition slots routed by the indexMap
bool(CARB_ABI* setInstancePositionF)(const pxr::SdfPath& instancerPath,
const carb::Float3* position,
const uint32_t* indexMap,
const uint32_t& instanceCount);
// Double versions of float functions
bool(CARB_ABI* setTransformD)(const pxr::SdfPath& primPath, const TransformD& transform);
bool(CARB_ABI* setWorldMatrixD)(const pxr::SdfPath& primPath, const Double4x4& mat);
bool(CARB_ABI* setTransformByIdD)(uint32_t, const TransformD& transform);
bool(CARB_ABI* setInstanceTransformD)(const pxr::SdfPath& instancerPath,
const TransformD& transform,
uint32_t instanceIndex);
bool(CARB_ABI* getTransformD)(const pxr::SdfPath& primPath, TransformD& transform);
bool(CARB_ABI* setInstancePositionD)(const pxr::SdfPath& instancerPath,
const carb::Double3* position,
const uint32_t* indexMap,
const uint32_t& instanceCount);
// Overloaded compatibility wrappers (float)
bool setTransform(const pxr::SdfPath& primPath, const Transform& transform, FastCacheDirtyFlags dirtyFlags)
{
return setTransformF(primPath, transform, dirtyFlags);
}
bool setWorldMatrix(const pxr::SdfPath& primPath, const Float4x4& mat, FastCacheDirtyFlags dirtyFlags)
{
return setWorldMatrixF(primPath, mat, dirtyFlags);
}
bool setTransformById(uint32_t id, const Transform& transform, FastCacheDirtyFlags dirtyFlags)
{
return setTransformByIdF(id, transform, dirtyFlags);
}
bool setInstanceTransform(const pxr::SdfPath& instancerPath, const Transform& transform, uint32_t instanceIndex, FastCacheDirtyFlags dirtyFlags)
{
return setInstanceTransformF(instancerPath, transform, instanceIndex, dirtyFlags);
}
bool getTransform(const pxr::SdfPath& primPath, Transform& transform)
{
return getTransformF(primPath, transform);
}
bool setInstancePosition(const pxr::SdfPath& instancerPath, const carb::Float3* position, const uint32_t* indexMap, const uint32_t& instanceCount)
{
return setInstancePositionF(instancerPath, position, indexMap, instanceCount);
}
// Overloaded compatibility wrappers (double)
bool setTransform(const pxr::SdfPath& primPath, const TransformD& transform, FastCacheDirtyFlags)
{
return setTransformD(primPath, transform);
}
bool setWorldMatrix(const pxr::SdfPath& primPath, const Double4x4& mat, FastCacheDirtyFlags)
{
return setWorldMatrixD(primPath, mat);
}
bool setTransformById(uint32_t id, const TransformD& transform, FastCacheDirtyFlags)
{
return setTransformByIdD(id, transform);
}
bool setInstanceTransform(const pxr::SdfPath& instancerPath, const TransformD& transform, uint32_t instanceIndex, FastCacheDirtyFlags)
{
return setInstanceTransformD(instancerPath, transform, instanceIndex);
}
bool getTransform(const pxr::SdfPath& primPath, TransformD& transform)
{
return getTransformD(primPath, transform);
}
bool setInstancePosition(const pxr::SdfPath& instancerPath, const carb::Double3* position, const uint32_t* indexMap, const uint32_t& instanceCount)
{
return setInstancePositionD(instancerPath, position, indexMap, instanceCount);
}
};
} // namespace fastcache
} // namespace carb
|
omniverse-code/kit/include/carb/fastcache/FastCacheHydra.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
#include <carb/fastcache/FastCacheTypes.h>
#include <map>
#include <string>
#include <vector>
namespace carb
{
namespace fastcache
{
/**
Hydra API (used by hydra scene/render delegate, DO NOT use in other plugins)
*/
struct FastCacheHydra
{
CARB_PLUGIN_INTERFACE("carb::fastcache::FastCacheHydra", 0, 2)
// Create an entry for a single prim
// TODO: This is to enable XR controllers to be updated
// this needs a better solution
void(CARB_ABI* populatePrim)(UsdPrimPtr prim);
};
} // namespace fastcache
} // namespace carb
|
omniverse-code/kit/include/carb/typeinfo/ITypeInfo.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Interface.h"
namespace carb
{
namespace typeinfo
{
/**
* All supported Types.
*/
enum class TypeKind
{
eNone,
eBuiltin, ///! int, float etc.
ePointer, ///! int*, const float* etc.
eConstantArray, ///! int[32]
eFunctionPointer, ///! float (*) (char, int)
eRecord, ///! class, struct
eEnum, ///! enum
eUnknown, ///! Unresolved type. Type could be unsupported or not registered in the plugin.
eCount
};
/**
* Type hash is unique type identifier. (FNV-1a 64 bit hash is used).
*/
typedef uint64_t TypeHash;
/**
* Type info common to all types.
*/
struct Type
{
TypeHash hash; ///! Hashed type name string.
const char* name; ///! Type name (C++ canonical name).
size_t size; ///! Size of a type. Generally it is equal to sizeof(Type::name). Could be 0 for some types (void,
/// function).
};
/**
* Get a type info for defined type.
*
* Defining a type is not mandatory, but can be convenient to extract type name, hash and size from a type.
* All builtins are already predefined. Use CARB_TYPE_INFO to define own types.
*
* Usage example:
* printf(getType<unsigned int>().name); // prints "unsigned int";
*/
template <class T>
constexpr Type getType();
/**
* Type link used as a reference to any other type.
*
* If kind is TypeKind::eUnknown -> type is nullptr, hash is valid
* If kind is TypeKind::eNone -> type is nullptr, hash is 0. That means link points to nothing.
* For any other kind -> type points to actual class. E.g. for TypeKind::eRecord type points to RecordType.
*
* Usage example:
* TypeLink type = ...;
* if (type.is<PointerType>())
* TypeLink pointedType = type.getAs<PointerType>()->pointee;
*/
struct TypeLink
{
TypeHash hash = 0;
TypeKind kind = TypeKind::eNone;
void* type = nullptr;
template <typename T>
bool is() const
{
return T::kKind == kind;
}
template <typename T>
const T* getAs() const
{
if (is<T>())
return static_cast<const T*>(type);
return nullptr;
}
};
/**
* Helper class to store const ranges in array. Supports C++11 range-based for loop.
*/
template <class T>
class Range
{
public:
Range() = default;
Range(const T* begin, size_t size) : m_begin(begin), m_size(size)
{
}
const T* begin() const
{
return m_begin;
}
const T* end() const
{
return m_begin + m_size;
}
size_t size() const
{
return m_size;
}
const T& operator[](size_t idx) const
{
CARB_ASSERT(idx < m_size);
return m_begin[idx];
}
private:
const T* m_begin;
size_t m_size;
};
/**
* Attribute is a tag that is used to convey additional (meta) information about fields or records.
*
* The idea is that you can associate some data of particular type with a field or record.
* Use AttributeDesc to specify data pointer, data type and size. Data will be copied internally, so it should be fully
* copyable.
*
* struct MyAttribute { int min, max };
* MyAttribute attr1 = { 0, 100 };
* AttributeDesc desc = { "", &attr1, sizeof(MyAttribute), CARB_HASH_STRING("carb::my::MyAttribute") };
*
* ... pass desc into some of ITypeInfo registration functions, for example in FieldDesc.
* then you can use it as:
*
* const RecordType* r = ...;
* const Attribute& a = r->fields[0]->attributes[0];
* if (a.isType<MyAttribute>())
* return a.getValue<MyAttrubte>();
*
* You can also pass nullptr as data and only use annotation string. Thus have custom string attribute.
*/
class Attribute
{
public:
const char* annotation = nullptr; //!< Stores whole annotation string as is.
const void* data = nullptr; //!< Pointer to the data constructed from attribute expression.
TypeLink type; //!< Type of the attribute data.
template <class T>
bool isType() const
{
return getType<T>().hash == type.hash;
}
template <class T>
const T& getValue() const
{
CARB_ASSERT(isType<T>() && "type mismatch");
return *static_cast<const T*>(data);
}
};
/**
* Attribute descriptor used to specify field and record attributes.
*/
struct AttributeDesc
{
const char* annotation; ///! Annotation string as is (recommended). It is not used anywhere internally, so any
/// information could be stored.
void* data; ///! Pointer to a data to copy. Can be nullptr.
size_t dataSize; ///! Size of data to copy.
TypeHash type; ///! Type of data. Is ignored if data is nullptr or 0 size.
};
/**
* Builtin type. E.g. float, int, double, char etc.
*
* All builtin types are automatically registered and defined (see CARB_TYPE_INFO below).
*/
struct BuiltinType
{
Type base;
static constexpr TypeKind kKind = TypeKind::eBuiltin;
};
/**
* Pointer type. E.g. int*, const float* const*.
*/
struct PointerType
{
Type base;
TypeLink pointee; ///! The type it points to.
static constexpr TypeKind kKind = TypeKind::ePointer;
};
/**
* Represents the canonical version of C arrays with a specified constant size.
* Example: int x[204];
*/
struct ConstantArrayType
{
Type base;
TypeLink elementType; ///! The type of array element.
size_t arraySize; ///! The size of array.
static constexpr TypeKind kKind = TypeKind::eConstantArray;
};
/**
* Function pointer type.
*
* Special type which describes pointer to a function.
*/
struct FunctionPointerType
{
Type base;
TypeLink returnType; ///! Qualified return type of a function.
Range<TypeLink> parameters; ///! Function parameters represented as qualified types.
static constexpr TypeKind kKind = TypeKind::eFunctionPointer;
};
struct FunctionPointerTypeDesc
{
TypeHash returnType;
Range<TypeHash> parameters;
};
struct FieldExtra;
/**
* Represents a field in a record (class or struct).
*/
struct Field
{
TypeLink type; ///! Qualified type of a field.
uint32_t offset; ///! Field offset in a record. Only fields with valid offset are supported.
const char* name; ///! Field name.
FieldExtra* extra; ///! Extra information available for some fields. Can be nullptr.
Range<Attribute> attributes; ///! Field attributes.
//////////// Access ////////////
template <class T>
bool isType() const
{
return getType<T>().hash == type.hash;
}
template <class T>
bool isTypeOrElementType() const
{
if (isType<T>())
return true;
const ConstantArrayType* arrayType = type.getAs<ConstantArrayType>();
return arrayType && (arrayType->elementType.hash == getType<T>().hash);
}
template <class T, typename S>
void setValue(volatile S& instance, T const& value) const
{
memcpy((char*)&instance + offset, &value, sizeof(T));
}
template <class T, typename S>
void setValueChecked(volatile S& instance, T const& value) const
{
if (isType<T>())
setValue(instance, value);
else
CARB_ASSERT(false && "type mismatch");
}
template <class T, typename S>
T& getRef(S& instance) const
{
return *(T*)((char*)&instance + offset);
}
template <class T, typename S>
const T& getRef(const S& instance) const
{
return getRef(const_cast<S&>(instance));
}
template <class T, typename S>
T getValue(const S& instance) const
{
return *(T*)((const char*)&instance + offset);
}
template <class T, typename S>
T getValueChecked(const S& instance) const
{
if (isType<T>())
return getValue<T>(instance);
CARB_ASSERT(false && "type mismatch");
return T{};
}
template <class T, typename S>
T* getPtr(S& instance) const
{
return reinterpret_cast<T*>((char*)&instance + offset);
}
template <class T, typename S>
const T* getPtr(const S& instance) const
{
return getPtr(const_cast<S&>(instance));
}
template <class T, typename S>
T* getPtrChecked(S& instance) const
{
if (isTypeOrElementType<T>())
return getPtr(instance);
CARB_ASSERT(false && "type mismatch");
return nullptr;
}
template <class T, typename S>
const T* getPtrChecked(const S& instance) const
{
return getPtrChecked(const_cast<S&>(instance));
}
};
/**
* Field extra information.
*
* If Field is a function pointer it stores function parameter names.
*/
struct FieldExtra
{
Range<const char*> functionParameters; ///! Function parameter names
};
/**
* Field descriptor used to specify fields.
*
* The main difference from the Field is that type is specified using a hash, which plugin automatically resolves into
* TypeLink during this record registration or later when type with this hash is registered.
*/
struct FieldDesc
{
TypeHash type;
uint32_t offset;
const char* name;
Range<AttributeDesc> attributes;
Range<const char*> extraFunctionParameters;
};
/**
* Represents a record (struct or class) as a collection of fields
*/
struct RecordType
{
Type base;
Range<Field> fields;
Range<Attribute> attributes; ///! Record attributes.
static constexpr TypeKind kKind = TypeKind::eRecord;
};
/**
* Represents single enum constant.
*/
struct EnumConstant
{
const char* name;
uint64_t value;
};
/**
* Represents a enum type (enum or enum class).
*/
struct EnumType
{
Type base;
Range<EnumConstant> constants;
static constexpr TypeKind kKind = TypeKind::eEnum;
};
/**
* ITypeInfo plugin interface.
*
* Split into 2 parts: one for type registration, other for querying type information.
*
* Registration follows the same principle for every function starting with word "register":
* If a type (of the same type kind) with this name is already registered:
* 1. It returns it instead
* 2. Warning is logged.
* 3. The content is checked and error is logged for any mismatch.
*
* The order of type registering is not important. If registered type contains TypeLink inside (fields of a struct,
* returned type of function etc.) it will be lazily resolved when appropriate type is registered.
*
* Every registration function comes in 2 flavors: templated version and explicit (with "Ex" postfix). The first one
* works only if there is appropriate getType<> specialization, thus CARB_TYPE_INFO() with registered type
* should be defined before.
*
*/
struct ITypeInfo
{
CARB_PLUGIN_INTERFACE("carb::typeinfo::ITypeInfo", 1, 0)
/**
* Get a type registered in the plugin by name/type hash. Empty link can be returned.
*/
TypeLink(CARB_ABI* getTypeByName)(const char* name);
TypeLink(CARB_ABI* getTypeByHash)(TypeHash hash);
/**
* Get a record type registered in the plugin by name/type hash. Can return nullptr.
*/
const RecordType*(CARB_ABI* getRecordTypeByName)(const char* name);
const RecordType*(CARB_ABI* getRecordTypeByHash)(TypeHash hash);
/**
* Get a number of all record types registered in the plugin.
*/
size_t(CARB_ABI* getRecordTypeCount)();
/**
* Get all record types registered in the plugin. The count of elements in the array is
* ITypeInfo::getRecordTypeCount().
*/
const RecordType* const*(CARB_ABI* getRecordTypes)();
/**
* Get a enum type registered in the plugin by name/type hash. Can return nullptr.
*/
const EnumType*(CARB_ABI* getEnumTypeByName)(const char* name);
const EnumType*(CARB_ABI* getEnumTypeByHash)(TypeHash hash);
/**
* Get a pointer type registered in the plugin by name/type hash. Can return nullptr.
*/
const PointerType*(CARB_ABI* getPointerTypeByName)(const char* name);
const PointerType*(CARB_ABI* getPointerTypeByHash)(TypeHash hash);
/**
* Get a constant array type registered in the plugin by name/type hash. Can return nullptr.
*/
const ConstantArrayType*(CARB_ABI* getConstantArrayTypeByName)(const char* name);
const ConstantArrayType*(CARB_ABI* getConstantArrayTypeByHash)(TypeHash hash);
/**
* Get a function pointer type registered in the plugin by name/type hash. Can return nullptr.
*/
const FunctionPointerType*(CARB_ABI* getFunctionPointerTypeByName)(const char* name);
const FunctionPointerType*(CARB_ABI* getFunctionPointerTypeByHash)(TypeHash hash);
/**
* Register a new record type.
*/
template <class T>
const RecordType* registerRecordType(const Range<FieldDesc>& fields = {},
const Range<AttributeDesc>& attributes = {});
const RecordType*(CARB_ABI* registerRecordTypeEx)(const char* name,
size_t size,
const Range<FieldDesc>& fields,
const Range<AttributeDesc>& attributes);
/**
* Register a new enum type.
*/
template <class T>
const EnumType* registerEnumType(const Range<EnumConstant>& constants);
const EnumType*(CARB_ABI* registerEnumTypeEx)(const char* name, size_t size, const Range<EnumConstant>& constants);
/**
* Register a new pointer type.
*/
template <class T>
const PointerType* registerPointerType(TypeHash pointee);
const PointerType*(CARB_ABI* registerPointerTypeEx)(const char* name, size_t size, TypeHash pointee);
/**
* Register a new constant array type.
*/
template <class T>
const ConstantArrayType* registerConstantArrayType(TypeHash elementType, size_t arraySize);
const ConstantArrayType*(CARB_ABI* registerConstantArrayTypeEx)(const char* name,
size_t size,
TypeHash elementType,
size_t arraySize);
/**
* Register a new function pointer type.
*/
template <class T>
const FunctionPointerType* registerFunctionPointerType(TypeHash returnType, Range<TypeHash> parameters = {});
const FunctionPointerType*(CARB_ABI* registerFunctionPointerTypeEx)(const char* name,
size_t size,
TypeHash returnType,
Range<TypeHash> parameters);
};
template <class T>
inline const RecordType* ITypeInfo::registerRecordType(const Range<FieldDesc>& fields,
const Range<AttributeDesc>& attributes)
{
const Type type = getType<T>();
return this->registerRecordTypeEx(type.name, type.size, fields, attributes);
}
template <class T>
inline const EnumType* ITypeInfo::registerEnumType(const Range<EnumConstant>& constants)
{
const Type type = getType<T>();
return this->registerEnumTypeEx(type.name, type.size, constants);
}
template <class T>
inline const PointerType* ITypeInfo::registerPointerType(TypeHash pointee)
{
const Type type = getType<T>();
return this->registerPointerTypeEx(type.name, type.size, pointee);
}
template <class T>
inline const ConstantArrayType* ITypeInfo::registerConstantArrayType(TypeHash elementType, size_t arraySize)
{
const Type type = getType<T>();
return this->registerConstantArrayTypeEx(type.name, type.size, elementType, arraySize);
}
template <class T>
inline const FunctionPointerType* ITypeInfo::registerFunctionPointerType(TypeHash returnType, Range<TypeHash> parameters)
{
const Type type = getType<T>();
return this->registerFunctionPointerTypeEx(type.name, type.size, returnType, parameters);
}
} // namespace typeinfo
} // namespace carb
/**
* Convenience macro to define type.
*
* Use it like that:
* CARB_TYPE_INFO(int*)
* CARB_TYPE_INFO(np::MyClass)
*
* NOTE: it is important to also pass full namespace path to your type (to capture it in the type name).
*/
#define CARB_TYPE_INFO(T) \
namespace carb \
{ \
namespace typeinfo \
{ \
template <> \
constexpr carb::typeinfo::Type getType<T>() \
{ \
return { CARB_HASH_STRING(#T), #T, sizeof(T) }; \
} \
} \
}
/**
* Predefined builtin types
*/
CARB_TYPE_INFO(bool)
CARB_TYPE_INFO(char)
CARB_TYPE_INFO(unsigned char)
CARB_TYPE_INFO(short)
CARB_TYPE_INFO(unsigned short)
CARB_TYPE_INFO(int)
CARB_TYPE_INFO(unsigned int)
CARB_TYPE_INFO(long)
CARB_TYPE_INFO(unsigned long)
CARB_TYPE_INFO(long long)
CARB_TYPE_INFO(unsigned long long)
CARB_TYPE_INFO(float)
CARB_TYPE_INFO(double)
CARB_TYPE_INFO(long double)
|
omniverse-code/kit/include/carb/typeinfo/TypeInfoRegistrationUtils.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "ITypeInfo.h"
#include <vector>
namespace carb
{
namespace typeinfo
{
template <class T>
class RecordRegistrator
{
public:
RecordRegistrator() : m_name(getType<T>().name), m_size(sizeof(T))
{
}
template <typename R>
RecordRegistrator<T>& addField(const char* name, R T::*mem)
{
TypeHash type = getType<R>().hash;
uint32_t offset = carb::offsetOf(mem);
m_fields.push_back({ type, offset, name, {}, {} });
return *this;
}
void commit(ITypeInfo* info)
{
info->registerRecordTypeEx(m_name, m_size, { m_fields.data(), m_fields.size() }, {});
}
private:
const char* m_name;
uint64_t m_size;
std::vector<FieldDesc> m_fields;
};
} // namespace typeinfo
} // namespace carb
|
omniverse-code/kit/include/carb/time/TscClock.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Implementation of a clock based on the CPU time-stamp counter
#pragma once
#include "../Defines.h"
#include "../cpp/Numeric.h"
#include "../Strong.h"
#include <thread>
#if CARB_PLATFORM_WINDOWS
// From immintrin.h
extern "C" unsigned __int64 rdtscp(unsigned int*);
# pragma intrinsic(__rdtscp)
# include "../CarbWindows.h"
#elif CARB_POSIX
# include <time.h>
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
namespace carb
{
//! Namespace for time utilities
namespace time
{
//! \cond DEV
namespace detail
{
#if CARB_PLATFORM_WINDOWS
inline uint64_t readTsc(void) noexcept
{
unsigned int cpu;
return __rdtscp(&cpu);
}
inline uint64_t readMonotonic(void) noexcept
{
CARBWIN_LARGE_INTEGER li;
BOOL b = QueryPerformanceCounter((LARGE_INTEGER*)&li);
CARB_ASSERT(b);
CARB_UNUSED(b);
return li.QuadPart;
}
inline uint64_t readMonotonicFreq(void) noexcept
{
CARBWIN_LARGE_INTEGER li;
BOOL b = QueryPerformanceFrequency((LARGE_INTEGER*)&li);
CARB_ASSERT(b);
CARB_UNUSED(b);
return li.QuadPart;
}
#elif CARB_POSIX
# if CARB_X86_64
__inline__ uint64_t readTsc(void) noexcept
{
// Use RDTSCP since it is serializing and flushes the pipeline intrinsically.
uint64_t msr;
// clang-format off
__asm__ __volatile__(
"rdtscp;\n" // read the rdtsc counter
"shl $32, %%rdx;\n" // rdx <<= 32
"or %%rdx, %0" // rax |= rdx, output is in rax
: "=a"(msr) // output to msr variable
: // no inputs
: "%rcx", "%rdx"); // clobbers
// clang-format on
return msr;
}
# elif CARB_AARCH64
__inline__ uint64_t readTsc(void) noexcept
{
// From: https://github.com/google/benchmark/blob/master/src/cycleclock.h
// System timer of ARMv8 runs at a different frequency than the CPU's.
// The frequency is fixed, typically in the range 1-50MHz. It can be
// read at CNTFRQ special register. We assume the OS has set up
// the virtual timer properly.
uint64_t virtualTimer;
asm volatile("mrs %0, cntvct_el0" : "=r"(virtualTimer));
return virtualTimer;
}
# else
CARB_UNSUPPORTED_ARCHITECTURE();
# endif
inline uint64_t readMonotonic(void) noexcept
{
struct timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
return ((tp.tv_sec * 1'000'000'000) + tp.tv_nsec) / 10;
}
inline uint64_t readMonotonicFreq(void) noexcept
{
// 10ns resolution is sufficient for system clock and gives us less chance to overflow in computeTscFrequency()
return 100'000'000;
}
#endif
inline void sampleClocks(uint64_t& tsc, uint64_t& monotonic) noexcept
{
// Attempt to take a TSC stamp and monotonic stamp as closely together as possible. In order to do this, we will
// interleave several timestamps in the pattern: TSC, mono, TSC, mono, ..., TSC
// Essentially this measures how long each monotonic timestamp takes in terms of the much faster TSC. We can then
// take the fastest monotonic timestamp and calculate an equivalent TSC timestamp from the midpoint.
static constexpr int kIterations = 100;
uint64_t stamps[kIterations * 2 + 1];
uint64_t* stamp = stamps;
uint64_t* const end = stamp + (kIterations * 2);
// Sleep so that we hopefully start with a full quanta and are less likely to context switch during this function.
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// Interleave sampling the TSC and monotonic clocks ending on a TSC
while (stamp != end)
{
// Unroll the loop slightly
*(stamp++) = readTsc();
*(stamp++) = readMonotonic();
*(stamp++) = readTsc();
*(stamp++) = readMonotonic();
*(stamp++) = readTsc();
*(stamp++) = readMonotonic();
*(stamp++) = readTsc();
*(stamp++) = readMonotonic();
CARB_ASSERT(stamp <= end);
}
*(stamp++) = readTsc();
// Start with the first as a baseline
uint64_t best = stamps[2] - stamps[0];
tsc = stamps[0] + ((stamps[2] - stamps[0]) / 2);
monotonic = stamps[1];
// Find the best sample
for (int i = 0; i != kIterations; ++i)
{
uint64_t tscDiff = stamps[2 * (i + 1)] - stamps[2 * i];
if (tscDiff < best)
{
best = tscDiff;
// Use a tsc sample midway between two samples
tsc = stamps[2 * i] + (tscDiff / 2);
monotonic = stamps[2 * i + 1];
}
}
}
inline uint64_t computeTscFrequency() noexcept
{
// We have two clocks in two different domains. The CPU-specific TSC and the monotonic clock. We need to compute the
// frequency of the TSC since it is not presented in any way.
uint64_t tsc[2];
uint64_t monotonic[2];
// Sample our clocks and wait briefly then sample again
sampleClocks(tsc[0], monotonic[0]);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
sampleClocks(tsc[1], monotonic[1]);
// This shouldn't happen, given the delay
CARB_ASSERT(monotonic[1] != monotonic[0]);
return ((tsc[1] - tsc[0]) * readMonotonicFreq()) / (monotonic[1] - monotonic[0]);
}
} // namespace detail
//! \endcond
//! Static class for a CPU time-stamp clock
//!
//! The functions and types within this class are used for sampling the CPU's time-stamp counter--typically a clock-
//! cycle resolution clock directly within the CPU hardware.
class tsc_clock
{
public:
//! Type definition of a sample from the CPU time-stamp counter.
//!
//! The time units of this are unspecified. Use \ref Freq to determine the frequency of the time-stamp counter.
CARB_STRONGTYPE(Sample, uint64_t);
//! The frequency of the timestamp counter, that is, the number of Samples per second.
CARB_STRONGTYPE(Freq, uint64_t);
//! Read a sample from the CPU time-stamp clock.
//!
//! Note that this operation is intended to be as fast as possible to maintain accuracy.
//! @returns a time-stamp \ref Sample at the time the function is called.
static Sample sample() noexcept
{
return Sample(detail::readTsc());
}
//! Computes the frequency of the CPU time-stamp clock.
//!
//! The first call to this function can take longer as the CPU time-stamp clock is calibrated.
//! @note This implementation assumes that the frequency never changes. Please verify with your CPU architecture
//! that this assumption is correct.
//! @returns the computed \ref Freq of the CPU time-stamp clock.
static Freq frequency() noexcept
{
static Freq freq{ detail::computeTscFrequency() };
return freq;
}
//! Computes the difference of two samples as a std::chrono::duration
//!
//! @tparam Duration a `std::chrono::duration` template to convert to.
//! @param older The older (starting) sample
//! @param newer The newer (ending) sample
//! @returns The difference in timestamps as the requested `Duration` representation
template <class Duration>
static Duration duration(Sample older, Sample newer) noexcept
{
using To = Duration;
using Rep = typename Duration::rep;
using Period = typename Duration::period;
int64_t diff = newer.get() - older.get();
// std::ratio is compile-time, so we have to do our own computations
using CT = std::common_type_t<Rep, int64_t, intmax_t>;
intmax_t _N1 = 1;
intmax_t _D1 = intmax_t(frequency().get());
intmax_t _N2 = Period::den; // Inverted for divide
intmax_t _D2 = Period::num; // Inverted for divide
intmax_t _Gx = carb::cpp::gcd(_N1, _D2);
intmax_t _Gy = carb::cpp::gcd(_N2, _D1);
intmax_t ratio_num = (_N1 / _Gx) * (_N2 / _Gy); // TODO: Check for overflow
intmax_t ratio_den = (_D1 / _Gy) * (_D2 / _Gx); // TODO: Check for overflow
if (ratio_num == 1 && ratio_den == 1)
return To(Rep(diff));
if (ratio_num != 1 && ratio_den == 1)
return To(Rep(CT(diff) * CT(ratio_num)));
if (ratio_num == 1 && ratio_den != 1)
return To(Rep(CT(diff) / CT(ratio_den)));
// Unfortunately, our frequency() is often not even numbers so the gcd() will be low. Which means that we often
// need to multiply and divide large numbers that end up overflowing. So use double here to keep better
// precision. As an alternative we could try to round the frequency up or down slightly, though this will impact
// precision.
return To(Rep(double(diff) * double(ratio_num) / double(ratio_den)));
}
};
} // namespace time
} // namespace carb
|
omniverse-code/kit/include/carb/time/Util.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include <time.h>
namespace carb
{
namespace time
{
/**
* Platform independent version of asctime_r: convert a `struct tm` into a null-terminated string.
* @tparam N The size of \p buf; must be at least 26 characters.
* @param tm The time component representation.
* @param buf The character buffer to render the string into. Must be at least 26 characters.
* @returns \p buf, or `nullptr` if an error occurs.
*/
template <size_t N>
inline char* asctime_r(const struct tm* tm, char (&buf)[N]) noexcept
{
// Buffer requirements as specified:
// https://linux.die.net/man/3/gmtime_r
// https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/asctime-s-wasctime-s?view=msvc-170
static_assert(N >= 26, "Insufficient buffer size");
#if CARB_PLATFORM_WINDOWS
return asctime_s(buf, N, tm) == 0 ? buf : nullptr;
#elif CARB_POSIX
return ::asctime_r(tm, buf);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Platform independent version of ctime_r; convert a `time_t` into a null-terminated string in the user's local time
* zone.
*
* Equivalent to:
* ```
* struct tm tmBuf;
* return asctime_r(localtime_r(timep, &tmBuf), buf);
* ```
* @tparam N The size of \p buf; must be at least 26 characters.
* @param timep A pointer to a `time_t`.
* @param buf The character buffer to render the string into. Must be at least 26 characters.
* @returns \p buf, or `nullptr` if an error occurs.
*/
template <size_t N>
inline char* ctime_r(const time_t* timep, char (&buf)[N]) noexcept
{
// Buffer requirements as specified:
// https://linux.die.net/man/3/gmtime_r
// https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/ctime-s-ctime32-s-ctime64-s-wctime-s-wctime32-s-wctime64-s?view=msvc-170
static_assert(N >= 26, "Insufficient buffer size");
#if CARB_PLATFORM_WINDOWS
auto err = ctime_s(buf, N, timep);
return err == 0 ? buf : nullptr;
#elif CARB_POSIX
return ::ctime_r(timep, buf);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Platform independent version of gmtime_r: convert a `time_t` to UTC component representation.
* @param timep A pointer to a `time_t`.
* @param result A pointer to a `struct tm` that will receive the result.
* @returns \p result if conversion succeeded; `nullptr` if the year does not fit into an integer or an error occurs.
*/
inline struct tm* gmtime_r(const time_t* timep, struct tm* result) noexcept
{
#if CARB_PLATFORM_WINDOWS
auto err = ::gmtime_s(result, timep);
return err == 0 ? result : nullptr;
#elif CARB_POSIX
return ::gmtime_r(timep, result);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Platform independent version of localtime_r: convert a `time_t` to local timezone component representation.
* @param timep A pointer to a `time_t`.
* @param result A pointer to a `struct tm` that will receive the result.
* @returns \p result if conversion succeeded; `nullptr` if the year does not fit into an integer or an error occurs.
*/
inline struct tm* localtime_r(const time_t* timep, struct tm* result) noexcept
{
#if CARB_PLATFORM_WINDOWS
auto err = ::localtime_s(result, timep);
return err == 0 ? result : nullptr;
#elif CARB_POSIX
return ::localtime_r(timep, result);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
} // namespace time
} // namespace carb
|
omniverse-code/kit/include/carb/settings/ISettings.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief carb.settings interface definition
#pragma once
#include "../Defines.h"
#include "../Types.h"
#include "../InterfaceUtils.h"
#include "../dictionary/IDictionary.h"
#include <cstddef>
namespace carb
{
//! Namespace for \ref carb::settings::ISettings interface and utilities.
namespace settings
{
//! An opaque type representing a settings transaction.
//! @see ISettings::createTransaction
struct Transaction DOXYGEN_EMPTY_CLASS;
/**
* The Carbonite Settings interface.
*
* Carbonite settings are built on top of the \ref carb::dictionary::IDictionary interface. Many dictionary functions
* are replicated in settings, but explicitly use the settings database instead of a generic
* \ref carb::dictionary::Item.
*
* ISettings uses keys (or paths) that start with an optional forward-slash and are forward-slash separated (example:
* "/log/level"). The settings database exists as a root-level \ref carb::dictionary::Item (of type 'dictionary') that
* is created and maintained by the \c ISettings interface (typically through the *carb.settings.plugin* plugin). The
* root level settings \ref carb::dictionary::Item is accessible through `getSettingsDictionary("/")`.
*
* @thread_safety
* All functions in \c ISettings are thread-safe unless otherwise specified. By "thread-safe," this means
* that individual call to a *carb.settings* API function will fully complete in a thread-safe manner; \b however this
* does not mean that multiple calls together will be threadsafe as another thread may act on the settings database
* between the API calls. In order to ensure thread-safety across multiple calls, use the \ref ScopedRead and
* \ref ScopedWrite RAII objects to ensure locking. The settings database uses a global recursive read/write lock to
* ensure thread safety across the entire settings database.
*
* @par Subscriptions
* Portions of the settings database hierarchy can be subscribed to with \ref ISettings::subscribeToTreeChangeEvents, or
* individual keys may be subscribed to with \ref ISettings::subscribeToNodeChangeEvents. Subscriptions are called in
* the context of the thread that triggered the change, and only once that thread has released all settings database
* locks. Subscription callbacks also follow the principles of Basic Callback Hygiene:
* 1. \ref ISettings::unsubscribeToChangeEvents may be called from within the callback to unregister the called
* subscription or any other subscription.
* 2. Unregistering the subscription ensures that it will never be called again, and any calls in process on another
* thread will complete before \ref ISettings::unsubscribeToChangeEvents returns.
* 3. The settings database lock is not held while the callback is called, but may be temporarily taken for API calls
* within the callback.
*
* @see carb::dictionary::IDictionary
*/
struct ISettings
{
CARB_PLUGIN_INTERFACE("carb::settings::ISettings", 1, 0)
/**
* Returns dictionary item type of the key at the given path.
*
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return \ref carb::dictionary::ItemType of value at \p path; if \p path is `nullptr` or does not exist,
* \ref carb::dictionary::ItemType::eCount is returned.
*/
dictionary::ItemType(CARB_ABI* getItemType)(const char* path);
/**
* Checks if the item could be accessible as the provided type, either directly, or via conversion.
*
* @param itemType Item type to check for.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return True if accessible, or false otherwise.
*/
bool(CARB_ABI* isAccessibleAs)(dictionary::ItemType itemType, const char* path);
/**
* Creates a dictionary (or changes an existing value to a dictionary) at the specified path.
*
* If the setting value previously existed as a dictionary, it is not modified. If the setting value exists as
* another type, it is destroyed and a new setting value is created as an empty dictionary. If the setting value did
* not exist, it is created as an empty dictionary. If any levels of the path hierarchy did not exist, they are
* created as dictionary items.
*
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`. Providing the root level ("/"
* or "") is undefined behavior.
*/
void(CARB_ABI* setDictionary)(const char* path);
/**
* Attempts to get the supplied item as integer, either directly or via conversion.
*
* @see carb::dictionary::IDictionary::getAsInt64
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return The 64-bit integer value of the value at \p path. If \p path is invalid, non-existent, or cannot be
* converted to an integer, `0` is returned.
*/
int64_t(CARB_ABI* getAsInt64)(const char* path);
/**
* Sets the integer value at the supplied path.
*
* If an item was already present, changes its original type to 'integer'. If the present item is a dictionary with
* children, all children are destroyed. If \p path doesn't exist, creates integer item, and all the required items
* along the path if necessary.
*
* @see carb::dictionary::IDictionary::setInt64
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value Integer value that will be stored to the supplied path.
*/
void(CARB_ABI* setInt64)(const char* path, int64_t value);
/**
* Attempts to get the supplied item as `int32_t`, either directly or via conversion.
*
* @warning The value is truncated by casting to 32-bits. In debug builds, an assert occurs if the value read from
* the item would be truncated.
* @see carb::dictionary::IDictionary::getAsInt
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return The `int32_t` value of the setting value at \p path. If \p path is invalid, non-existent, or cannot be
* converted to an `int32_t`, `0` is returned.
*/
int32_t getAsInt(const char* path);
/**
* Sets the integer value at the supplied path.
*
* If an item was already present, changes its original type to 'integer'. If the present item is a dictionary with
* children, all children are destroyed. If \p path doesn't exist, creates integer item, and all the required items
* along the path if necessary.
*
* @see carb::dictionary::IDictionary::setInt
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value Integer value that will be stored to the supplied path.
*/
void setInt(const char* path, int32_t value);
/**
* Attempts to get the supplied item as `double`, either directly or via conversion.
*
* @see carb::dictionary::IDictionary::getAsFloat64
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return The `double` value of the setting value at \p path. If \p path is invalid, non-existent, or cannot be
* converted to a `double`, `0.0` is returned.
*/
double(CARB_ABI* getAsFloat64)(const char* path);
/**
* Sets the floating point value at the supplied path.
*
* If an item was already present, changes its original type to 'double'. If the present item is a dictionary with
* children, all children are destroyed. If \p path doesn't exist, creates 'double' item, and all the required items
* along the path if necessary.
*
* @see carb::dictionary::IDictionary::setFloat64
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value Floating point value that will be stored to the supplied path.
*/
void(CARB_ABI* setFloat64)(const char* path, double value);
/**
* Attempts to get the supplied item as `float`, either directly or via conversion.
*
* @see carb::dictionary::IDictionary::getAsFloat
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return The `float` value of the setting value at \p path. If \p path is invalid, non-existent, or cannot be
* converted to a `float`, `0.0f` is returned.
*/
float getAsFloat(const char* path);
/**
* Sets the floating point value at the supplied path.
*
* If an item was already present, changes its original type to 'float'. If the present item is a dictionary with
* children, all children are destroyed. If \p path doesn't exist, creates 'float' item, and all the required items
* along the path if necessary.
*
* @see carb::dictionary::IDictionary::setFloat
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value Floating point value that will be stored to the supplied path.
*/
void setFloat(const char* path, float value);
/**
* Attempts to get the supplied item as `bool`, either directly or via conversion.
*
* @see carb::dictionary::IDictionary::getAsBool
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return The `bool` value of the setting value at \p path. If \p path is invalid, non-existent, or cannot be
* converted to a `bool`, `false` is returned. See \ref carb::dictionary::IDictionary::getAsBool for an
* explanation of how different item types are converted.
*/
bool(CARB_ABI* getAsBool)(const char* path);
/**
* Sets the boolean value at the supplied path.
*
* If an item was already present, changes its original type to 'bool'. If the present item is a dictionary with
* children, all children are destroyed. If \p path doesn't exist, creates 'bool' item, and all the required items
* along the path if necessary.
*
* @see carb::dictionary::IDictionary::setBool
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value Boolean value that will be stored to the supplied path.
*/
void(CARB_ABI* setBool)(const char* path, bool value);
//! @private
const char*(CARB_ABI* internalCreateStringBufferFromItemValue)(const char* path, size_t* pStringLen);
/**
* Attempts to create a new string buffer with a value, either the real string value or a string resulting
* from converting the item value to a string.
*
* @note Please use \ref destroyStringBuffer() to free the created buffer.
*
* @see carb::dictionary::IDictionary::createStringBufferFromItemValue() carb::settings::getStringFromItemValue()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data).
* @return Pointer to the created string buffer if applicable, nullptr otherwise.
*/
const char* createStringBufferFromItemValue(const char* path, size_t* pStringLen = nullptr) const
{
return internalCreateStringBufferFromItemValue(path, pStringLen);
}
//! @private
const char*(CARB_ABI* internalGetStringBuffer)(const char* path, size_t* pStringLen);
/**
* Returns internal raw data pointer to the string value of an item. Thus, doesn't perform any
* conversions.
*
* @warning This function returns the internal string buffer. Another thread may change the setting value which can
* cause the string buffer to be destroyed. It is recommended to take a \ref ScopedRead lock around calling this
* function and using the return value.
*
* @see carb::dictionary::IDictionary::getStringBuffer() carb::settings::getString()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data).
* @return Raw pointer to the internal string value if applicable, nullptr otherwise.
*/
const char* getStringBuffer(const char* path, size_t* pStringLen = nullptr) const
{
return internalGetStringBuffer(path, pStringLen);
}
//! @private
void(CARB_ABI* internalSetString)(const char* path, const char* value, size_t stringLen);
/**
* Sets a string value at the given path.
*
* The given @p path is walked and any dictionary items are changed or created to create the path. If the @p path
* item itself exists but is not of type `eString` it is changed to be `eString`. Change notifications for
* subscriptions are queued. The given string is then set in the item at @p path. If @p value is \c nullptr, the
* string item will store an empty string.
*
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value String value that will be stored to the supplied path. `nullptr` is interpreted as an empty string.
* @param stringLen (optional) The length of the string at \p value to copy. This can be useful if only a portion
* of the string should be copied, or if \p value contains NUL characters (i.e. byte data). The default value of
* `size_t(-1)` treats \p value as a NUL-terminated string.
*/
void setString(const char* path, const char* value, size_t stringLen = size_t(-1)) const
{
internalSetString(path, value, stringLen);
}
/**
* Reads the value from a path, converting if necessary.
* @tparam T The type of item to read. Must be a supported type.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @returns The value read from the \p path.
*/
template <typename T>
T get(const char* path);
/**
* Sets the value at a path.
* @tparam T The type of item to read. Must be a supported type.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value The value to store in the item at \p path.
*/
template <typename T>
void set(const char* path, T value);
/**
* Checks if the item could be accessible as array, i.e. all child items names are valid
* contiguous non-negative integers starting with zero.
*
* @see carb::dictionary::IDictionary::isAccessibleAsArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return True if accessible, or false otherwise.
*/
bool(CARB_ABI* isAccessibleAsArray)(const char* path);
/**
* Checks if the item could be accessible as the array of items of provided type,
* either directly, or via conversion of all elements.
*
* @see carb::dictionary::IDictionary::isAccessibleAsArrayOf
* @param itemType Item type to check for.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return True if a valid array and with all items accessible, or false otherwise.
*/
bool(CARB_ABI* isAccessibleAsArrayOf)(dictionary::ItemType itemType, const char* path);
/**
* Checks if the all the children of the item have array-style indices. If yes, returns the number
* of children (array elements).
*
* @see carb::dictionary::IDictionary::getArrayLength
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return Number of array elements if applicable, or 0 otherwise.
*/
size_t(CARB_ABI* getArrayLength)(const char* path);
/**
* Runs through all the array elements and infers a type that is most suitable for the
* array.
*
* The rules are thus:
* - Strings attempt to convert to float or bool if possible.
* - The converted type of the first element is the initial type.
* - If the initial type is a \ref dictionary::ItemType::eBool and later elements can be converted to
* \ref dictionary::ItemType::eBool without losing precision, \ref dictionary::ItemType::eBool is kept. (String
* variants of "true"/"false", or values exactly equal to 0/1)
* - Elements of type \ref dictionary::ItemType::eFloat can convert to \ref dictionary::ItemType::eInt if they don't
* lose precision.
*
* @see dictionary::IDictionary::getPreferredArrayType
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return \ref dictionary::ItemType that is most suitable for the array, or \ref dictionary::ItemType::eCount on
* failure.
*/
dictionary::ItemType(CARB_ABI* getPreferredArrayType)(const char* path);
/**
* Attempts to read an array item as a 64-bit integer.
*
* Attempts to read the path and array index as an integer, either directly or via conversion, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`0`) is returned if \p path doesn't exist, index doesn't exist, or there is a conversion
* failure.
*
* @see dictionary::IDictionary::getAsInt64At
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @return Integer value, either raw value or cast from the real item type. Zero is returned if \p path doesn't
* exist, is not an array, \p index doesn't exist in the array, or a conversion error occurs.
*/
int64_t(CARB_ABI* getAsInt64At)(const char* path, size_t index);
/**
* Attempts to set a 64-bit integer value in an array item.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). \p index is converted to a string and appended to \p path as a child path name. The
* child path is created as `eInt` or changed to be `eInt`, and the value is set from \p value. Subscription
* notifications are triggered when the current thread no longer has any settings locks.
*
* @see dictionary::IDictionary::setInt64At
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param value Integer value that will be stored to the supplied path.
*/
void(CARB_ABI* setInt64At)(const char* path, size_t index, int64_t value);
/**
* Attempts to read an array item as a 32-bit integer.
*
* Attempts to read the path and array index as an integer, either directly or via conversion, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`0`) is returned if \p path doesn't exist, index doesn't exist, or there is a conversion
* failure.
*
* @warning The value is truncated by casting to 32-bits. In debug builds, an assert occurs if the value read from
* the item would be truncated.
* @see dictionary::IDictionary::getAsIntAt()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @return Integer value, either raw value or cast from the real item type. Zero is returned if \p path doesn't
* exist, is not an array, \p index doesn't exist in the array, or a conversion error occurs.
*/
int32_t getAsIntAt(const char* path, size_t index);
/**
* Attempts to set a 32-bit integer value in an array item.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). \p index is converted to a string and appended to \p path as a child path name. The
* child path is created as `eInt` or changed to be `eInt`, and the value is set from \p value. Subscription
* notifications are triggered when the current thread no longer has any settings locks.
*
* @see dictionary::IDictionary::setIntAt()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param value Integer value that will be stored to the supplied path.
*/
void setIntAt(const char* path, size_t index, int32_t value);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p path is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p path is the location of a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @see carb::dictionary::IDictionary::getAsInt64Array
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param arrayOut Array buffer to fill with integer values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsInt64Array)(const char* path, int64_t* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be an integer array.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). If \p path already exists as a `eDictionary` it is cleared (change notifications
* will be queued for any child items that are destroyed). New child items are created for all elements of the given
* @p array.
*
* @see carb::dictionary::IDictionary::setInt64Array
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Integer array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setInt64Array)(const char* path, const int64_t* array, size_t arrayLength);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p path is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p path is the location of a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
* @warning Any integer element that does not fit within \c int32_t is truncated by casting.
*
* @see carb::dictionary::IDictionary::getAsIntArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param arrayOut Array buffer to fill with integer values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsIntArray)(const char* path, int32_t* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be an integer array.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). If \p path already exists as a `eDictionary` it is cleared (change notifications
* will be queued for any child items that are destroyed). New child items are created for all elements of the given
* @p array.
*
* @see carb::dictionary::IDictionary::setIntArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Integer array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setIntArray)(const char* path, const int32_t* array, size_t arrayLength);
/**
* Attempts to read an array item as a `double`.
*
* Attempts to read the path and array index as a `double`, either directly or via conversion, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`0.0`) is returned if \p path doesn't exist, index doesn't exist, or there is a conversion
* failure.
*
* @see carb::dictionary::IDictionary::getAsFloat64At
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return `double` value, either raw value or cast from the real item type.
*/
double(CARB_ABI* getAsFloat64At)(const char* path, size_t index);
/**
* Attempts to set a `double` value in an array item.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). \p index is converted to a string and appended to \p path as a child path name. The
* child path is created as `eFloat` or changed to be `eFloat`, and the value is set from \p value. Subscription
* notifications are triggered when the current thread no longer has any settings locks.
*
* @see carb::dictionary::IDictionary::setFloat64At
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param value `double` value that will be stored to the supplied path.
*/
void(CARB_ABI* setFloat64At)(const char* path, size_t index, double value);
/**
* Attempts to read an array item as a `float`.
*
* Attempts to read the path and array index as a `float`, either directly or via conversion, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`0.0f`) is returned if \p path doesn't exist, index doesn't exist, or there is a conversion
* failure.
*
* @see carb::dictionary::IDictionary::getAsFloatAt()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @return `float` value, either raw value or cast from the real item type.
*/
float getAsFloatAt(const char* path, size_t index);
/**
* Attempts to set a `float` value in an array item.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). \p index is converted to a string and appended to \p path as a child path name. The
* child path is created as `eFloat` or changed to be `eFloat`, and the value is set from \p value. Subscription
* notifications are triggered when the current thread no longer has any settings locks.
*
* @see carb::dictionary::IDictionary::setFloatAt()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param value Floating point value that will be stored to the supplied path.
*/
void setFloatAt(const char* path, size_t index, float value);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p path is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p path is the location of a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @see carb::dictionary::IDictionary::getAsFloat64Array
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param arrayOut Array buffer to fill with floating point values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsFloat64Array)(const char* path, double* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a `double` array.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). If \p path already exists as a `eDictionary` it is cleared (change notifications
* will be queued for any child items that are destroyed). New child items are created for all elements of the given
* @p array.
*
* @see carb::dictionary::IDictionary::setFloat64Array
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Floating point array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setFloat64Array)(const char* path, const double* array, size_t arrayLength);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p path is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p path is the location of a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
* @warning Any element that does not fit within \c float is truncated by casting.
*
* @see carb::dictionary::IDictionary::getAsFloatArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param arrayOut Array buffer to fill with floating point values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsFloatArray)(const char* path, float* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a `float` array.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). If \p path already exists as a `eDictionary` it is cleared (change notifications
* will be queued for any child items that are destroyed). New child items are created for all elements of the given
* @p array.
*
* @see carb::dictionary::IDictionary::setFloatArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Floating point array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setFloatArray)(const char* path, const float* array, size_t arrayLength);
/**
* Attempts to read an array item as a `bool`.
*
* Attempts to read the path and array index as a `bool`, either directly or via conversion, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`false`) is returned if \p path doesn't exist, index doesn't exist, or there is a conversion
* failure.
*
* @see carb::dictionary::IDictionary::getAsBoolAt
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @return Boolean value, either raw value or cast from the real item type.
*/
bool(CARB_ABI* getAsBoolAt)(const char* path, size_t index);
/**
* Attempts to set a `bool` value in an array item.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). \p index is converted to a string and appended to \p path as a child path name. The
* child path is created as `eBool` or changed to be `eBool`, and the value is set from \p value. Subscription
* notifications are triggered when the current thread no longer has any settings locks.
*
* @see carb::dictionary::IDictionary::setBoolAt
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param value Boolean value that will be stored to the supplied path.
*/
void(CARB_ABI* setBoolAt)(const char* path, size_t index, bool value);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p path is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p path is the location of a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @see carb::dictionary::IDictionary::getAsBoolArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param arrayOut Array buffer to fill with boolean values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsBoolArray)(const char* path, bool* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a `bool` array.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). If \p path already exists as a `eDictionary` it is cleared (change notifications
* will be queued for any child items that are destroyed). New child items are created for all elements of the given
* @p array.
*
* @see carb::dictionary::IDictionary::setBoolArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Boolean array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setBoolArray)(const char* path, const bool* array, size_t arrayLength);
//! @private
const char*(CARB_ABI* internalCreateStringBufferFromItemValueAt)(const char* path, size_t index, size_t* pStringLen);
/**
* Attempts to create a new string buffer with a value, either the real string value or a string resulting
* from converting the item value to a string.
*
* This function effectively converts \p index to a string, appends it to \p path after a path separator ('/'), and
* calls \ref createStringBufferFromItemValue().
*
* @see carb::dictionary::IDictionary::createStringBufferFromItemValueAt()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data). Undefined if the function returns nullptr.
* @return Pointer to the created string buffer if applicable, nullptr otherwise. Non-nullptr return values must be
* passed to \ref destroyStringBuffer to dispose of when finished.
*
* @note It is undefined to create `std::string` out of nullptr. For using the value as `std::string`, see
* \ref carb::settings::getStringFromItemValueAt()
*/
const char* createStringBufferFromItemValueAt(const char* path, size_t index, size_t* pStringLen = nullptr) const
{
return internalCreateStringBufferFromItemValueAt(path, index, pStringLen);
}
//! @private
const char*(CARB_ABI* internalGetStringBufferAt)(const char* path, size_t index, size_t* pStringLen);
/**
* Returns internal raw data pointer to the string value of an item in an array. Thus, doesn't perform any
* conversions.
*
* @warning This function returns the internal string buffer. Another thread may change the setting value which can
* cause the string buffer to be destroyed. It is recommended to take a \ref ScopedRead lock around calling this
* function and using the return value.
*
* @see carb::dictionary::IDictionary::getStringBufferAt()
* @param path Settings database key path of an array item (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data). Undefined if the function returns nullptr.
* @return Raw pointer to the internal string value if applicable, nullptr otherwise.
*
* @note It is undefined to create std::string out of nullptr. For using the value as std::string, @see
* carb::settings::getStringAt()
*/
const char* getStringBufferAt(const char* path, size_t index, size_t* pStringLen = nullptr) const
{
return internalGetStringBufferAt(path, index, pStringLen);
}
//! @private
void(CARB_ABI* internalSetStringAt)(const char* path, size_t index, const char* value, size_t stringLen);
/**
* Sets a string value at the given path.
*
* The given @p path is walked and any dictionary items are changed or created to create the path. @p index is
* converted to a string and appended to @p path. If the item at this composite path
* exists but is not of type `eString` it is changed to be `eString`. Change notifications for
* subscriptions are queued. The given string is then set in the item at the composite path path. If @p value is
* \c nullptr, the string item will store an empty string.
*
* @see carb::dictionary::IDictionary::setStringAt()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param index Index of the element in array.
* @param value String value that will be stored to the supplied path.
* @param stringLen (optional) The length of the string at \p value to copy. This can be useful if only a portion
* of the string should be copied, or if \p value contains NUL characters (i.e. byte data). The default value of
* size_t(-1) treats \p value as a NUL-terminated string.
*/
void setStringAt(const char* path, size_t index, const char* value, size_t stringLen = size_t(-1)) const
{
internalSetStringAt(path, index, value, stringLen);
}
/**
* Returns internal raw data pointers to the string value of all child items of an array. Thus, doesn't perform any
* conversions.
*
* @warning This function returns the internal string buffer(s) for several items. Another thread may change the
* setting value which can cause the string buffer to be destroyed. It is recommended to take a \ref ScopedRead lock
* around calling this function and use of the filled items in @p arrayOut.
*
* If the provided @p path is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p path is the location of a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @see carb::dictionary::IDictionary::getStringBufferArray carb::settings::getStringArray()
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param arrayOut Array buffer to fill with char buffer pointer values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getStringBufferArray)(const char* path, const char** arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a string array.
*
* Ensures that the given \p path exists as an `eDictionary`, changing types as the path is walked (and triggering
* subscription notifications). If \p path already exists as a `eDictionary` it is cleared (change notifications
* will be queued for any child items that are destroyed). New child items are created for all elements of the given
* @p array.
*
* @see carb::dictionary::IDictionary::setStringArray
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array String array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setStringArray)(const char* path, const char* const* array, size_t arrayLength);
/**
* Creates or updates an item to be an array of the given type with provided values.
*
* This is a helper function that will call the appropriate API function based on \c SettingArrayType:
* * `bool`: \ref setBoolArray
* * `int32_t`: \ref setIntArray
* * `int64_t`: \ref setInt64Array
* * `float`: \ref setFloatArray
* * `double`: \ref setFloat64Array
* * `const char*`: \ref setStringArray
*
* @see carb::dictionary::IDictionary::setArray()
* @tparam SettingArrayType The type of elements.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Array to copy values from.
* @param arrayLength Number of items in @p array.
*/
template <typename SettingArrayType>
void setArray(const char* path, const SettingArrayType* array, size_t arrayLength);
/**
* Creates a transaction.
*
* A transaction is an asynchronous settings database that can be applied at a later time as one atomic unit with
* \ref commitTransaction. A transaction may be retained and committed several times. A transaction must be disposed
* of with \ref destroyTransaction when it is no longer needed.
*
* Values can be set within the transaction with \ref setInt64Async, \ref setFloat64Async, \ref setBoolAsync and
* \ref setStringAsync.
*
* @returns An opaque \ref Transaction pointer.
*/
Transaction*(CARB_ABI* createTransaction)();
/**
* Destroys a transaction.
*
* Destroys a transaction previously created with \ref createTransaction.
* @warning After calling this function, the given @p transaction should no longer be used or undefined behavior
* will occur.
* @param transaction The \ref Transaction to destroy.
*/
void(CARB_ABI* destroyTransaction)(Transaction* transaction);
/**
* Commits a transaction.
*
* This atomically copies all of the values set in the transaction to the settings database. This is done as via:
* ```
* // note: transaction->database is expository only
* update("/", transaction->database, nullptr, carb::dictionary::overwriteOriginalWithArrayHandling,
* carb::getCachedInterface<carb::dictionary::IDictionary>());
* ```
* Values can be set within the transaction with \ref setInt64Async, \ref setFloat64Async, \ref setBoolAsync and
* \ref setStringAsync.
*
* This function can be called multiple times for a given @p transaction that has not been destroyed.
*
* Change notifications are queued.
*
* @param transaction The \ref Transaction to commit.
*/
void(CARB_ABI* commitTransaction)(Transaction* transaction);
/**
* Sets a value in a Transaction to be applied at a later time.
*
* The value is not committed to the settings database until \ref commitTransaction is called.
* @note Values cannot be read or deleted from a \ref Transaction.
*
* @param transaction The \ref Transaction previously created with \ref createTransaction.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`. The settings database is not
* modified until \ref commitTransaction is called.
* @param value The value to store in the \p transaction.
*/
void(CARB_ABI* setInt64Async)(Transaction* transaction, const char* path, int64_t value);
//! @copydoc setInt64Async
void(CARB_ABI* setFloat64Async)(Transaction* transaction, const char* path, double value);
//! @copydoc setInt64Async
void(CARB_ABI* setBoolAsync)(Transaction* transaction, const char* path, bool value);
//! @copydoc setInt64Async
void(CARB_ABI* setStringAsync)(Transaction* transaction, const char* path, const char* value);
/**
* Subscribes to change events about a specific item.
*
* When finished with the subscription, call \ref unsubscribeToChangeEvents.
*
* @see carb::dictionary::IDictionary::subscribeToNodeChangeEvents
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param onChangeEventFn The function to call when a change event occurs.
* @param userData User-specific data that will be provided to \p onChangeEventFn.
* @return A subscription handle that can be used with \ref unsubscribeToChangeEvents.
*/
dictionary::SubscriptionId*(CARB_ABI* subscribeToNodeChangeEvents)(const char* path,
dictionary::OnNodeChangeEventFn onChangeEventFn,
void* userData);
/**
* Subscribes to change events for all items in a subtree.
*
* All items including and under @p path will trigger change notifications.
*
* When finished with the subscription, call \ref unsubscribeToChangeEvents.
*
* @see carb::dictionary::IDictionary::subscribeToTreeChangeEvents
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param onChangeEventFn The function to call when a change event occurs.
* @param userData User-specific data that will be provided to \p onChangeEventFn.
* @return A subscription handle that can be used with \ref unsubscribeToChangeEvents.
*/
dictionary::SubscriptionId*(CARB_ABI* subscribeToTreeChangeEvents)(const char* path,
dictionary::OnTreeChangeEventFn onChangeEventFn,
void* userData);
/**
* Unsubscribes from change events.
*
* It is safe to call this function from within a subscription callback. Once it returns, this function guarantees
* that the subscription callback has exited (only if being called from another thread) and will never be called
* again.
*
* @param subscriptionId The subscription handle from \ref subscribeToNodeChangeEvents or
* \ref subscribeToTreeChangeEvents
*/
void(CARB_ABI* unsubscribeToChangeEvents)(dictionary::SubscriptionId* subscriptionId);
/**
* Merges the source item into the settings database. Destination path may be non-existing, then
* missing items in the path will be created as dictionaries.
*
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`. Used as the destination
* location within the settings database. "/" is considered to be the root.
* @param dictionary The \ref carb::dictionary::Item that is the base of the items to merge into the setting
* database.
* @param dictionaryPath A child path of @p dictionary to use as the root for merging. May be `nullptr` in order to
* use @p dictionary directly as the root.
* @param onUpdateItemFn Function that will tell whether the update should overwrite the destination item with the
* source item. See \ref carb::dictionary::keepOriginal(), \ref carb::dictionary::overwriteOriginal(), or
* \ref carb::dictionary::overwriteOriginalWithArrayHandling().
* @param userData User data pointer that will be passed into the onUpdateItemFn.
*/
void(CARB_ABI* update)(const char* path,
const dictionary::Item* dictionary,
const char* dictionaryPath,
dictionary::OnUpdateItemFn onUpdateItemFn,
void* userData);
/**
* Accesses the settings database as a dictionary Item.
*
* This allows use of \ref carb::dictionary::IDictionary functions directly.
*
* @warning The root \ref dictionary::Item is owned by \c ISettings and must not be altered or destroyed.
* @note It is highly recommended to take a \ref ScopedRead or \ref ScopedWrite lock while working with the setting
* database directly.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`. Used as the destination
* location within the settings database. "/" is considered to be the root.
* @returns A \ref carb::dictionary::Item that can be used directly with the \ref carb::dictionary::IDictionary
* interface.
*/
const dictionary::Item*(CARB_ABI* getSettingsDictionary)(const char* path);
/**
* Takes a snapshot of a portion of the settings database as a dictionary Item.
*
* @param path Settings database key path (i.e. "/log/level") to consider the root for the copy. "/" is considered
* to be the root (will copy the entire settings database).
* @returns A \ref carb::dictionary::Item that is a separate copy of the requested portion of the settings database.
* When no longer needed, this can be passed to \ref carb::dictionary::IDictionary::destroyItem.
*/
dictionary::Item*(CARB_ABI* createDictionaryFromSettings)(const char* path);
/**
* Destroys a setting item and queues change notifications.
*
* @warning Any string buffers or \ref carb::dictionary::Item pointers to the referenced path become invalid and
* their use is undefined behavior.
* @see carb::dictionary::IDictionary::destroyItem
* @param path Settings database key path (i.e. "/log/level") to destroy. "/" is considered
* to be the root (will clear the entire settings database without actually destroying the root).
*/
void(CARB_ABI* destroyItem)(const char* path);
/**
* Frees a string buffer.
*
* The string buffers are created by \ref createStringBufferFromItemValue() or
* \ref createStringBufferFromItemValueAt().
* @see carb::dictionary::IDictionary::destroyStringBuffer
* @param stringBuffer String buffer to destroy. Undefined behavior results if this is not a value returned from one
* of the functions listed above.
*/
void(CARB_ABI* destroyStringBuffer)(const char* stringBuffer);
/**
* Performs a one-time initialization from a given dictionary item.
*
* @note This function may only be called once. Subsequent calls will result in an error message logged.
* @param dictionary The \ref carb::dictionary::Item to initialize the settings database from. The items are copied
* into the root of the settings database. This item is not retained and may be destroyed immediately after this
* function returns.
*/
void(CARB_ABI* initializeFromDictionary)(const dictionary::Item* dictionary);
/**
* Sets a value at the given path, if and only if one does not already exist.
*
* Atomically checks if a value exists at the given @p path, and if so, exits without doing anything. Otherwise, any
* required dictionary items are created while walking @p path and @p value is stored. Change notifications are
* queued.
*
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param value Value that will be stored at the given @p path in the settings database.
*/
void setDefaultInt64(const char* path, int64_t value);
//! @copydoc setDefaultInt64
void setDefaultInt(const char* path, int32_t value);
//! @copydoc setDefaultInt64
void setDefaultFloat64(const char* path, double value);
//! @copydoc setDefaultInt64
void setDefaultFloat(const char* path, float value);
//! @copydoc setDefaultInt64
void setDefaultBool(const char* path, bool value);
//! @copydoc setDefaultInt64
void setDefaultString(const char* path, const char* value);
//! @copydoc setDefaultInt64
//! @tparam SettingType The type of @p value.
template <typename SettingType>
void setDefault(const char* path, SettingType value);
/**
* Copies values into the setting dictionary, if and only if they don't already exist.
*
* Values are checked and copied atomically, and change notifications are queued.
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`. This is the root location at
* which \p dictionary is copied in.
* @param dictionary The \ref dictionary::Item to copy defaults from.
*/
void setDefaultsFromDictionary(const char* path, const dictionary::Item* dictionary);
/**
* Sets an array of values at the given path, if and only if one does not already exist.
*
* Atomically checks if a value exists at the given @p path, and if so, exits without doing anything. Otherwise, any
* required dictionary items are created while walking @p path and @p array is stored. Change notifications are
* queued.
*
* @param path Settings database key path (i.e. "/log/level"). Must not be `nullptr`.
* @param array Array of values that will be stored at the given @p path in the settings database.
* @param arrayLength Number of values in @p array.
*/
void setDefaultInt64Array(const char* path, const int64_t* array, size_t arrayLength);
//! @copydoc setDefaultInt64Array
void setDefaultIntArray(const char* path, const int32_t* array, size_t arrayLength);
//! @copydoc setDefaultInt64Array
void setDefaultFloat64Array(const char* path, const double* array, size_t arrayLength);
//! @copydoc setDefaultInt64Array
void setDefaultFloatArray(const char* path, const float* array, size_t arrayLength);
//! @copydoc setDefaultInt64Array
void setDefaultBoolArray(const char* path, const bool* array, size_t arrayLength);
//! @copydoc setDefaultInt64Array
void setDefaultStringArray(const char* path, const char* const* array, size_t arrayLength);
//! @copydoc setDefaultInt64Array
//! @tparam SettingArrayType The type of the values in @p array.
template <typename SettingArrayType>
void setDefaultArray(const char* path, const SettingArrayType* array, size_t arrayLength);
};
/**
* A helper class for performing a scoped write lock on the settings database.
*/
class ScopedWrite : public carb::dictionary::ScopedWrite
{
public:
/**
* RAII constructor. Immediately takes a write lock and holds it until *this is destroyed.
* @note Settings locks are recursive.
* @warning If the current thread already owns a read lock (i.e. via \ref ScopedRead), promotion to a write lock
* necessitates *releasing* all locks and then waiting for a write lock. This can cause state to change. Always
* re-evaluate state if this is the case.
*/
ScopedWrite()
: carb::dictionary::ScopedWrite(
*carb::getCachedInterface<dictionary::IDictionary>(),
const_cast<dictionary::Item*>(carb::getCachedInterface<settings::ISettings>()->getSettingsDictionary("/")))
{
}
//! Destructor. Releases the write lock.
~ScopedWrite() = default;
CARB_PREVENT_COPY_AND_MOVE(ScopedWrite);
};
/**
* A helper class for performing a scoped read lock on the settings database.
*/
class ScopedRead : public carb::dictionary::ScopedRead
{
public:
/**
* RAII constructor. Immediately takes a read lock and holds it until *this is destroyed.
* @note Settings locks are recursive.
*/
ScopedRead()
: carb::dictionary::ScopedRead(*carb::getCachedInterface<dictionary::IDictionary>(),
carb::getCachedInterface<settings::ISettings>()->getSettingsDictionary("/"))
{
}
//! Destructor. Releases the read lock.
~ScopedRead() = default;
CARB_PREVENT_COPY_AND_MOVE(ScopedRead);
};
inline int32_t ISettings::getAsInt(const char* path)
{
auto val = getAsInt64(path);
CARB_ASSERT(val >= INT_MIN && val <= INT_MAX);
return int32_t(val);
}
inline void ISettings::setInt(const char* path, int32_t value)
{
setInt64(path, (int64_t)value);
}
inline float ISettings::getAsFloat(const char* path)
{
return (float)getAsFloat64(path);
}
inline void ISettings::setFloat(const char* path, float value)
{
setFloat64(path, (double)value);
}
inline int32_t ISettings::getAsIntAt(const char* path, size_t index)
{
auto val = getAsInt64At(path, index);
CARB_ASSERT(val >= INT_MIN && val <= INT_MAX);
return int32_t(val);
}
inline void ISettings::setIntAt(const char* path, size_t index, int32_t value)
{
setInt64At(path, index, (int64_t)value);
}
inline float ISettings::getAsFloatAt(const char* path, size_t index)
{
return (float)getAsFloat64At(path, index);
}
inline void ISettings::setFloatAt(const char* path, size_t index, float value)
{
setFloat64At(path, index, (double)value);
}
inline void ISettings::setDefaultInt64(const char* path, int64_t value)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setInt64(path, value);
}
}
inline void ISettings::setDefaultInt(const char* path, int32_t value)
{
setDefaultInt64(path, (int64_t)value);
}
inline void ISettings::setDefaultFloat64(const char* path, double value)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setFloat64(path, value);
}
}
inline void ISettings::setDefaultFloat(const char* path, float value)
{
setDefaultFloat64(path, (double)value);
}
inline void ISettings::setDefaultBool(const char* path, bool value)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setBool(path, value);
}
}
inline void ISettings::setDefaultString(const char* path, const char* value)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setString(path, value);
}
}
inline void ISettings::setDefaultsFromDictionary(const char* path, const dictionary::Item* dictionary)
{
if (dictionary)
{
update(path, dictionary, nullptr, dictionary::kUpdateItemKeepOriginal, nullptr);
}
}
inline void ISettings::setDefaultInt64Array(const char* path, const int64_t* array, size_t arrayLength)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setInt64Array(path, array, arrayLength);
}
}
inline void ISettings::setDefaultIntArray(const char* path, const int32_t* array, size_t arrayLength)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setIntArray(path, array, arrayLength);
}
}
inline void ISettings::setDefaultFloat64Array(const char* path, const double* array, size_t arrayLength)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setFloat64Array(path, array, arrayLength);
}
}
inline void ISettings::setDefaultFloatArray(const char* path, const float* array, size_t arrayLength)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setFloatArray(path, array, arrayLength);
}
}
inline void ISettings::setDefaultBoolArray(const char* path, const bool* array, size_t arrayLength)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setBoolArray(path, array, arrayLength);
}
}
inline void ISettings::setDefaultStringArray(const char* path, const char* const* array, size_t arrayLength)
{
ScopedWrite writeLock;
dictionary::ItemType itemType = getItemType(path);
if (itemType == dictionary::ItemType::eCount)
{
setStringArray(path, array, arrayLength);
}
}
#ifndef DOXYGEN_BUILD
template <>
inline int32_t ISettings::get<int>(const char* path)
{
return getAsInt(path);
}
template <>
inline int64_t ISettings::get<int64_t>(const char* path)
{
return getAsInt64(path);
}
template <>
inline float ISettings::get<float>(const char* path)
{
return getAsFloat(path);
}
template <>
inline double ISettings::get<double>(const char* path)
{
return getAsFloat64(path);
}
template <>
inline bool ISettings::get<bool>(const char* path)
{
return getAsBool(path);
}
template <>
inline const char* ISettings::get<const char*>(const char* path)
{
return getStringBuffer(path);
}
template <>
inline void ISettings::set<int32_t>(const char* path, int32_t value)
{
setInt(path, value);
}
template <>
inline void ISettings::set<int64_t>(const char* path, int64_t value)
{
setInt64(path, value);
}
template <>
inline void ISettings::set<float>(const char* path, float value)
{
setFloat(path, value);
}
template <>
inline void ISettings::set<double>(const char* path, double value)
{
setFloat64(path, value);
}
template <>
inline void ISettings::set<bool>(const char* path, bool value)
{
setBool(path, value);
}
template <>
inline void ISettings::set<const char*>(const char* path, const char* value)
{
setString(path, value);
}
template <>
inline void ISettings::setArray(const char* path, const bool* array, size_t arrayLength)
{
setBoolArray(path, array, arrayLength);
}
template <>
inline void ISettings::setArray(const char* path, const int32_t* array, size_t arrayLength)
{
setIntArray(path, array, arrayLength);
}
template <>
inline void ISettings::setArray(const char* path, const int64_t* array, size_t arrayLength)
{
setInt64Array(path, array, arrayLength);
}
template <>
inline void ISettings::setArray(const char* path, const float* array, size_t arrayLength)
{
setFloatArray(path, array, arrayLength);
}
template <>
inline void ISettings::setArray(const char* path, const double* array, size_t arrayLength)
{
setFloat64Array(path, array, arrayLength);
}
template <>
inline void ISettings::setArray(const char* path, const char* const* array, size_t arrayLength)
{
setStringArray(path, array, arrayLength);
}
template <>
inline void ISettings::setDefault(const char* path, bool value)
{
setDefaultBool(path, value);
}
template <>
inline void ISettings::setDefault(const char* path, int32_t value)
{
setDefaultInt(path, value);
}
template <>
inline void ISettings::setDefault(const char* path, int64_t value)
{
setDefaultInt64(path, value);
}
template <>
inline void ISettings::setDefault(const char* path, float value)
{
setDefaultFloat(path, value);
}
template <>
inline void ISettings::setDefault(const char* path, double value)
{
setDefaultFloat64(path, value);
}
template <>
inline void ISettings::setDefault(const char* path, const char* value)
{
setDefaultString(path, value);
}
template <>
inline void ISettings::setDefaultArray(const char* settingsPath, const bool* array, size_t arrayLength)
{
setDefaultBoolArray(settingsPath, array, arrayLength);
}
template <>
inline void ISettings::setDefaultArray(const char* settingsPath, const int32_t* array, size_t arrayLength)
{
setDefaultIntArray(settingsPath, array, arrayLength);
}
template <>
inline void ISettings::setDefaultArray(const char* settingsPath, const int64_t* array, size_t arrayLength)
{
setDefaultInt64Array(settingsPath, array, arrayLength);
}
template <>
inline void ISettings::setDefaultArray(const char* settingsPath, const float* array, size_t arrayLength)
{
setDefaultFloatArray(settingsPath, array, arrayLength);
}
template <>
inline void ISettings::setDefaultArray(const char* settingsPath, const double* array, size_t arrayLength)
{
setDefaultFloat64Array(settingsPath, array, arrayLength);
}
template <>
inline void ISettings::setDefaultArray(const char* settingsPath, const char* const* array, size_t arrayLength)
{
setDefaultStringArray(settingsPath, array, arrayLength);
}
#endif
} // namespace settings
} // namespace carb
|
omniverse-code/kit/include/carb/settings/SettingsUtils.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief carb.settings utilities
#pragma once
#include "../dictionary/DictionaryUtils.h"
#include "../dictionary/ISerializer.h"
#include "ISettings.h"
#include <atomic>
#include <string>
namespace carb
{
namespace settings
{
/**
* Retrieves a std::string from a setting key for simplicity.
*
* Typically to retrieve a string value from \ref carb::dictionary::Item,
* \ref ISettings::createStringBufferFromItemValue() must be called, but this means that
* \ref ISettings::destroyStringBuffer() must be called when finished. This function instead returns a `std::string`.
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path to retrieve.
* @param defaultValue The value that is returned if \p path is not a valid path.
* @returns A `std::string` representation of the item value.
* @see ISettings::createStringBufferFromItemValue(), getStringFromItemValueAt().
*/
inline std::string getStringFromItemValue(const ISettings* settings, const char* path, const std::string& defaultValue = "")
{
const char* stringBuf = settings->createStringBufferFromItemValue(path);
if (!stringBuf)
return defaultValue;
std::string returnString = stringBuf;
settings->destroyStringBuffer(stringBuf);
return returnString;
}
/**
* Retrieves a std::string from an array setting key for simplicity.
*
* Typically to retrieve a string value from an array of \ref carb::dictionary::Item objects,
* \ref ISettings::createStringBufferFromItemValueAt() must be called, but this means that
* \ref ISettings::destroyStringBuffer() must be called when finished. This function instead returns a `std::string`.
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path to retrieve (must be an array or \p defaultValue will be returned).
* @param index The array index to retrieve.
* @param defaultValue The value that is returned if \p path is not a valid path, not an array, or the index does not
* exist.
* @returns A `std::string` representation of the item value.
* @see ISettings::createStringBufferFromItemValueAt(), getStringFromItemValue().
*/
inline std::string getStringFromItemValueAt(const ISettings* settings,
const char* path,
size_t index,
const std::string& defaultValue = "")
{
const char* stringBuf = settings->createStringBufferFromItemValueAt(path, index);
if (!stringBuf)
return defaultValue;
std::string returnString = stringBuf;
settings->destroyStringBuffer(stringBuf);
return returnString;
}
/**
* Retrieves a std::string from a string-type setting for simplicity.
*
* Equivalent to:
* ```cpp
* auto p = settings->getStringBuffer(path); return p ? std::string(p) : defaultValue;
* ```
* @see ISettings::getStringBuffer, getStringAt()
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path to retrieve (must be a string or \p defaultValue will be returned).
* @param defaultValue The value that is returned if \p path is not a valid path or not a string setting.
* @returns A `std::string` representation of the item value.
*/
inline std::string getString(const ISettings* settings, const char* path, const std::string& defaultValue = "")
{
const char* value = settings->getStringBuffer(path);
if (!value)
return defaultValue;
return value;
}
/**
* Retrieves a std::string from an array of string-type setting for simplicity.
*
* Equivalent to:
* ```cpp
* auto p = settings->getStringBufferAt(path, index); return p ? std::string(p) : defaultValue;
* ```
* @see ISettings::getStringBuffer, getString()
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path to retrieve (must be an array of strings or \p defaultValue will be returned).
* @param index The array index to retrieve.
* @param defaultValue The value that is returned if \p path is not a valid path, not an array of strings, or the
* index does not exist.
* @returns A `std::string` representation of the item value.
*/
inline std::string getStringAt(const ISettings* settings,
const char* path,
size_t index,
const std::string& defaultValue = "")
{
const char* value = settings->getStringBufferAt(path, index);
if (!value)
return defaultValue;
return value;
}
/**
* A helper function for setting a `std::vector<int>` as an array of integers.
*
* Equivalent to:
* ```cpp
* settings->setIntArray(path, array.data(), array.size());
* ```
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. See \ref ISettings::setIntArray for details.
* @param array A vector containing the integer values for the setting value.
*/
inline void setIntArray(ISettings* settings, const char* path, const std::vector<int>& array)
{
settings->setIntArray(path, array.data(), array.size());
}
/**
* A helper function for setting a `std::vector<int64_t>` as an array of 64-bit integers.
*
* Equivalent to:
* ```cpp
* settings->setInt64Array(path, array.data(), array.size());
* ```
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. See \ref ISettings::setInt64Array for details.
* @param array A vector containing the 64-bit integer values for the setting value.
*/
inline void setIntArray(ISettings* settings, const char* path, const std::vector<int64_t>& array)
{
settings->setInt64Array(path, array.data(), array.size());
}
/**
* A helper function for setting a `std::vector<float>` as an array of floats.
*
* Equivalent to:
* ```cpp
* settings->setFloatArray(path, array.data(), array.size());
* ```
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. See \ref ISettings::setFloatArray for details.
* @param array A vector containing the float values for the setting value.
*/
inline void setFloatArray(ISettings* settings, const char* path, const std::vector<float>& array)
{
settings->setFloatArray(path, array.data(), array.size());
}
/**
* A helper function for setting a `std::vector<double>` as an array of doubles.
*
* Equivalent to:
* ```cpp
* settings->setFloatArray(path, array.data(), array.size());
* ```
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. See \ref ISettings::setFloat64Array for details.
* @param array A vector containing the double values for the setting value.
*/
inline void setFloatArray(ISettings* settings, const char* path, const std::vector<double>& array)
{
settings->setFloat64Array(path, array.data(), array.size());
}
/**
* A helper function for setting a `std::vector<bool>` as an array of bools.
*
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. See \ref ISettings::setBoolArray for details.
* @param array A vector containing the bool values for the setting value.
* @note \p array is first converted to an array of `bool` on the stack and then passed in to
* \ref ISettings::setBoolArray. If the stack is particularly small and \p array is particularly large, stack space
* may be exceeded. In this case, it is advised to call \ref ISettings::setBoolArray directly.
*/
inline void setBoolArray(ISettings* settings, const char* path, const std::vector<bool>& array)
{
const size_t arraySize = array.size();
// Since std::vector<bool> is typically specialized and doesn't function like normal vector (i.e. no data()), first
// convert to an array of bools on the stack.
bool* pbools = CARB_STACK_ALLOC(bool, arraySize);
for (size_t i = 0; i != arraySize; ++i)
pbools[i] = array[i];
settings->setBoolArray(path, pbools, arraySize);
}
/**
* A helper function for reading a setting value that is an array of string values as `std::vector<std::string>`.
*
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. If this path does not exist or is not an array, an empty vector will be returned.
* @param defaultValue The value that is returned for each array item if the array item is not a string value.
* @returns a `std::vector<std::string>` of all string array elements. If the value at \p path does not
* exist or is not an array type, an empty vector is returned. Otherwise, a vector is returned with the number of
* elements matching the number of elements in the value at \p path (as determined via
* \ref ISettings::getArrayLength). Any array elements that are not string types will instead be \p defaultValue.
* @see getStringArrayFromItemValues() for a function that handles values of mixed or non-string types.
*/
inline std::vector<std::string> getStringArray(ISettings* settings, const char* path, const std::string& defaultValue = "")
{
dictionary::ScopedRead readLock(
*carb::getCachedInterface<dictionary::IDictionary>(), settings->getSettingsDictionary(""));
std::vector<std::string> array(settings->getArrayLength(path));
for (size_t i = 0, arraySize = array.size(); i < arraySize; ++i)
{
array[i] = getStringAt(settings, path, i, defaultValue);
}
return array;
}
/**
* A helper function for reading a setting value that is an array of mixed values as `std::vector<std::string>`.
*
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. If this path does not exist or is not an array, an empty vector will be returned.
* @param defaultValue The value that is returned for each array item if the array item cannot be converted to a string
* value.
* @returns a `std::vector<std::string>` of all array elements converted to a string. If the value at \p path does not
* exist or is not an array type, an empty vector is returned. Otherwise, a vector is returned with the number of
* elements matching the number of elements in the value at \p path (as determined via
* \ref ISettings::getArrayLength). Any array elements that cannot be converted to a string will instead be
* \p defaultValue.
*/
inline std::vector<std::string> getStringArrayFromItemValues(ISettings* settings,
const char* path,
const std::string& defaultValue = "")
{
dictionary::ScopedRead readLock(
*carb::getCachedInterface<dictionary::IDictionary>(), settings->getSettingsDictionary(""));
std::vector<std::string> array(settings->getArrayLength(path));
for (size_t i = 0, arraySize = array.size(); i < arraySize; ++i)
{
array[i] = getStringFromItemValueAt(settings, path, i, defaultValue);
}
return array;
}
/**
* A helper function for setting a `std::vector<bool>` as an array of strings.
*
* @param settings The acquired \ref ISettings interface.
* @param path The setting key path. See \ref ISettings::setStringArray for details.
* @param array A vector containing the bool values for the setting value.
* @note \p array is first converted to an array of `const char*` on the stack and then passed in to
* \ref ISettings::setStringArray. If the stack is particularly small and \p array is particularly large, stack space
* may be exceeded. In this case, it is advised to call \ref ISettings::setStringArray directly.
*/
inline void setStringArray(ISettings* settings, const char* path, const std::vector<std::string>& array)
{
const size_t arraySize = array.size();
const char** pp = CARB_STACK_ALLOC(const char*, arraySize);
for (size_t i = 0; i != arraySize; ++i)
pp[i] = array[i].c_str();
settings->setStringArray(path, pp, arraySize);
}
/**
* A helper function to load settings from a file.
*
* This function first creates a dictionary from a file using the provided \p serializer passed to
* \ref carb::dictionary::createDictionaryFromFile(). The dictionary is then applied to the settings system with
* \ref ISettings::update at settings path \p path using the \ref carb::dictionary::overwriteOriginalWithArrayHandling()
* method. The created dictionary is then destroyed. When the function returns, the settings from the given \p filename
* are available to be queried through the settings system.
* @param settings The acquired \ref ISettings interface.
* @param path The path at which the loaded settings are placed. An empty string or "/" is considered the root of the
* settings tree.
* @param dictionary The acquired \ref dictionary::IDictionary interface.
* @param serializer The \ref dictionary::ISerializer interface to use. The file format should match the format of
* \p filename. I.e. if \p filename is a json file, the \ref dictionary::ISerializer from
* *carb.dictionary.serializer-json.plugin* should be used.
* @param filename The filename to read settings from.
*/
inline void loadSettingsFromFile(ISettings* settings,
const char* path,
dictionary::IDictionary* dictionary,
dictionary::ISerializer* serializer,
const char* filename)
{
carb::dictionary::Item* settingsFromFile = carb::dictionary::createDictionaryFromFile(serializer, filename);
if (settingsFromFile)
{
settings->update(path, settingsFromFile, nullptr, dictionary::overwriteOriginalWithArrayHandling, dictionary);
dictionary->destroyItem(settingsFromFile);
}
}
/**
* A helper function to save settings to a file.
*
* @see dictionary::saveFileFromDictionary()
* @param settings The acquired \ref ISettings interface.
* @param serializer The \ref dictionary::ISerializer interface to use. The serializer should match the desired output
* file format. I.e. if a json file is desired, the \ref dictionary::ISerializer from
* *carb.dictionary.serializer-json.plugin* should be used.
* @param path The settings path to save. An empty string or "/" is considered the root of the settings tree.
* @param filename The filename to write settings into. This file will be overwritten.
* @param serializerOptions Options that will be passed to \p serializer.
*/
inline void saveFileFromSettings(const ISettings* settings,
dictionary::ISerializer* serializer,
const char* path,
const char* filename,
dictionary::SerializerOptions serializerOptions)
{
const dictionary::Item* settingsDictionaryAtPath = settings->getSettingsDictionary(path);
dictionary::saveFileFromDictionary(serializer, settingsDictionaryAtPath, filename, serializerOptions);
}
/**
* A function for walking all of the settings from a given root.
*
* Similar to \ref dictionary::walkDictionary().
* @tparam ElementData Type of the second parameter passed to \p onItemFn.
* @tparam OnItemFnType Type of the invocable \p onItemFn.
* @param idict The acquired \ref dictionary::IDictionary interface.
* @param settings The acquired \ref ISettings interface.
* @param walkerMode See \ref dictionary::WalkerMode.
* @param rootPath The settings root to begin the walk at. An empty string or "/" is considered the root of the settings
* tree.
* @param rootElementData A value of type `ElementData` that is passed as the second parameter to \p onItemFn. This
* value is not used by `walkSettings()` and is intended to be used only by the caller and the \p onItemFn invocable.
* @param onItemFn An invocable that is invoked for each setting value encountered. The type of this invocable should be
* `ElementData(const char*, ElementData, void*)`: the encountered item path is the first parameter, followed by the
* parent's `ElementData`, followed by \p userData. The return value is only used for dictionary and array settings:
* the returned `ElementData` will be passed to \p onItemFn invocations for child settings; the return value is
* otherwise ignored.
* @param userData A caller-specific value that is not used but is passed to every \p onItemFn invocation.
*/
template <typename ElementData, typename OnItemFnType>
inline void walkSettings(carb::dictionary::IDictionary* idict,
carb::settings::ISettings* settings,
dictionary::WalkerMode walkerMode,
const char* rootPath,
ElementData rootElementData,
OnItemFnType onItemFn,
void* userData)
{
using namespace carb;
if (!rootPath)
{
return;
}
if (rootPath[0] == 0)
rootPath = "/";
struct ValueToParse
{
std::string srcPath;
ElementData elementData;
};
std::vector<ValueToParse> valuesToParse;
valuesToParse.reserve(100);
auto enqueueChildren = [&idict, &settings, &valuesToParse](const char* parentPath, ElementData parentElementData) {
if (!parentPath)
{
return;
}
const dictionary::Item* parentItem = settings->getSettingsDictionary(parentPath);
size_t numChildren = idict->getItemChildCount(parentItem);
for (size_t chIdx = 0; chIdx < numChildren; ++chIdx)
{
const dictionary::Item* childItem = idict->getItemChildByIndex(parentItem, numChildren - chIdx - 1);
const char* childItemName = idict->getItemName(childItem);
std::string childPath;
bool isRootParent = (idict->getItemParent(parentItem) == nullptr);
if (isRootParent)
{
childPath = std::string(parentPath) + childItemName;
}
else
{
childPath = std::string(parentPath) + "/" + childItemName;
}
valuesToParse.push_back({ childPath, parentElementData });
}
};
if (walkerMode == dictionary::WalkerMode::eSkipRoot)
{
const char* parentPath = rootPath;
ElementData parentElementData = rootElementData;
enqueueChildren(parentPath, parentElementData);
}
else
{
valuesToParse.push_back({ rootPath, rootElementData });
}
while (valuesToParse.size())
{
const ValueToParse& valueToParse = valuesToParse.back();
std::string curItemPathStorage = std::move(valueToParse.srcPath);
const char* curItemPath = curItemPathStorage.c_str();
ElementData elementData = std::move(valueToParse.elementData);
valuesToParse.pop_back();
dictionary::ItemType curItemType = settings->getItemType(curItemPath);
if (curItemType == dictionary::ItemType::eDictionary)
{
ElementData parentElementData = onItemFn(curItemPath, elementData, userData);
enqueueChildren(curItemPath, parentElementData);
}
else
{
onItemFn(curItemPath, elementData, userData);
}
}
}
/**
* A utility for caching a setting and automatically subscribing to changes of the value, as opposed to constantly
* polling.
*
* @thread_safety Despite the name, this class is not thread-safe except that another thread may change the setting
* value and `*this` will have the cached value updated in a thread-safe manner. Unless otherwise specified, assume that
* calls to all functions must be serialized externally.
*
* @tparam SettingType The type of the setting. Must be a supported setting value type or compilation errors will
* result: `bool`, `int32_t`, `int64_t`, `float`, `double`, `const char*`.
*/
template <typename SettingType>
class ThreadSafeLocalCache
{
public:
/**
* Constructor.
* @param initState The initial value to cache.
* @note The value is not read from \ref ISettings and tracking does not start until \ref startTracking() is called.
* Attempting to read the value before calling \ref startTracking() will result in an assert.
*/
ThreadSafeLocalCache(SettingType initState = SettingType{}) : m_value(initState), m_valueDirty(false)
{
}
/**
* Destructor.
*
* Calls \ref stopTracking().
*/
~ThreadSafeLocalCache()
{
stopTracking();
}
/**
* Reads the value from the settings database and subscribes to changes for the value.
*
* This function reads the setting value at the given \p settingPath and caches it. Then
* \ref ISettings::subscribeToNodeChangeEvents is called so that *this can be notified of changes to the value.
* @note Assertions will occur if \p settingPath is `nullptr` or tracking is already started without calling
* \ref stopTracking() first.
* @param settingPath The path of the setting to read. Must not be `nullptr`.
*/
void startTracking(const char* settingPath)
{
CARB_ASSERT(settingPath, "Must specify a valid setting name.");
CARB_ASSERT(m_subscription == nullptr,
"Already tracking this value, do not track again without calling stopTracking first.");
Framework* f = getFramework();
m_settings = f->tryAcquireInterface<settings::ISettings>();
m_dictionary = f->tryAcquireInterface<dictionary::IDictionary>();
if (!m_settings || !m_dictionary)
return;
m_valueSettingsPath = settingPath;
m_value.store(m_settings->get<SettingType>(settingPath), std::memory_order_relaxed);
m_valueDirty.store(false, std::memory_order_release);
m_subscription = m_settings->subscribeToNodeChangeEvents(
settingPath,
[](const dictionary::Item* changedItem, dictionary::ChangeEventType changeEventType, void* userData) {
if (changeEventType == dictionary::ChangeEventType::eChanged)
{
ThreadSafeLocalCache* thisClassInstance = reinterpret_cast<ThreadSafeLocalCache*>(userData);
thisClassInstance->m_value.store(
thisClassInstance->getDictionaryInterface()->template get<SettingType>(changedItem),
std::memory_order_relaxed);
thisClassInstance->m_valueDirty.store(true, std::memory_order_release);
}
},
this);
if (m_subscription != nullptr)
{
f->addReleaseHook(m_settings, sOnRelease, this);
}
}
/**
* Halts tracking changes on the setting key provided with \ref startTracking().
*
* It is safe to call this function even if tracking has already been stopped, or never started. Do not call
* \ref get() after calling this function without calling \ref startTracking() prior, otherwise an assertion will
* occur.
*/
void stopTracking()
{
if (m_subscription)
{
carb::getFramework()->removeReleaseHook(m_settings, sOnRelease, this);
m_settings->unsubscribeToChangeEvents(m_subscription);
m_subscription = nullptr;
}
}
/**
* Retrieves the cached value.
*
* @warning `get()` may only be called while a subscription is active. A subscription is only active once
* \ref startTracking() has been called (including on a newly constructed object), and only until
* \ref stopTracking() is called (at which point \ref startTracking() may be called to resume). Calling this
* function when a subscription is not active will result in an assertion and potentially reading a stale value.
* @thread_safety This function is safe to call from multiple threads, though if the setting value is changed by
* other threads, multiple threads calling this function may receive different results.
* @returns The cached value of the setting key provided in \ref startTracking().
*/
SettingType get() const
{
CARB_ASSERT(m_subscription, "Call startTracking before reading this variable.");
return m_value.load(std::memory_order_relaxed);
}
/**
* Syntactic sugar for \ref get().
*/
operator SettingType() const
{
return get();
}
/**
* Sets the value in the setting database.
*
* @note Do not call this function after \ref stopTracking() has been called and/or before \ref startTracking() has
* been called, otherwise an assertion will occur and the setting database may be corrupted.
* @param value The new value to set for the setting key given to \ref startTracking().
*/
void set(SettingType value)
{
CARB_ASSERT(m_subscription);
if (!m_valueSettingsPath.empty())
m_settings->set<SettingType>(m_valueSettingsPath.c_str(), value);
}
/**
* Checks to see if the cached value has been updated.
*
* The dirty flag must be manually reset by calling \ref clearValueDirty(). The dirty flag is set any time the
* cached value is updated through the subscription. This also includes calls to \ref set(SettingType).
* @returns \c true if the dirty flag is set; \c false otherwise.
*/
bool isValueDirty() const
{
return m_valueDirty.load(std::memory_order_relaxed);
}
/**
* Resets the dirty flag.
*
* After this function returns (and assuming that the subscription has not updated the cached value on a different
* thread), \ref isValueDirty() will return `false`.
*/
void clearValueDirty()
{
m_valueDirty.store(false, std::memory_order_release);
}
/**
* Retrieves the setting key previously given to \ref startTracking().
* @returns The setting key previously given to \ref startTracking().
*/
const char* getSettingsPath() const
{
return m_valueSettingsPath.c_str();
}
/**
* Retrieves the cached \ref dictionary::IDictionary pointer.
* @returns The cached \ref dictionary::IDictionary pointer.
*/
inline dictionary::IDictionary* getDictionaryInterface() const
{
return m_dictionary;
}
private:
static void sOnRelease(void* iface, void* user)
{
// Settings has gone away, so our subscription is defunct
static_cast<ThreadSafeLocalCache*>(user)->m_subscription = nullptr;
carb::getFramework()->removeReleaseHook(iface, sOnRelease, user);
}
// NOTE: The callback may come in on another thread so wrap it in an atomic to prevent a race.
std::atomic<SettingType> m_value;
std::atomic<bool> m_valueDirty;
std::string m_valueSettingsPath;
dictionary::SubscriptionId* m_subscription = nullptr;
dictionary::IDictionary* m_dictionary = nullptr;
settings::ISettings* m_settings = nullptr;
};
#ifndef DOXYGEN_SHOULD_SKIP_THIS
template <>
class ThreadSafeLocalCache<const char*>
{
public:
ThreadSafeLocalCache(const char* initState = "") : m_valueDirty(false)
{
std::lock_guard<std::mutex> guard(m_valueMutex);
m_value = initState;
}
~ThreadSafeLocalCache()
{
stopTracking();
}
void startTracking(const char* settingPath)
{
CARB_ASSERT(settingPath, "Must specify a valid setting name.");
CARB_ASSERT(m_subscription == nullptr,
"Already tracking this value, do not track again without calling stopTracking first.");
Framework* f = getFramework();
m_settings = f->tryAcquireInterface<settings::ISettings>();
m_dictionary = f->tryAcquireInterface<dictionary::IDictionary>();
m_valueSettingsPath = settingPath;
const char* valueRaw = m_settings->get<const char*>(settingPath);
m_value = valueRaw ? valueRaw : "";
m_valueDirty.store(false, std::memory_order_release);
m_subscription = m_settings->subscribeToNodeChangeEvents(
settingPath,
[](const dictionary::Item* changedItem, dictionary::ChangeEventType changeEventType, void* userData) {
if (changeEventType == dictionary::ChangeEventType::eChanged)
{
ThreadSafeLocalCache* thisClassInstance = reinterpret_cast<ThreadSafeLocalCache*>(userData);
{
const char* valueStringBuffer =
thisClassInstance->getDictionaryInterface()->template get<const char*>(changedItem);
std::lock_guard<std::mutex> guard(thisClassInstance->m_valueMutex);
thisClassInstance->m_value = valueStringBuffer ? valueStringBuffer : "";
}
thisClassInstance->m_valueDirty.store(true, std::memory_order_release);
}
},
this);
if (m_subscription)
{
f->addReleaseHook(m_settings, sOnRelease, this);
}
}
void stopTracking()
{
if (m_subscription)
{
m_settings->unsubscribeToChangeEvents(m_subscription);
m_subscription = nullptr;
carb::getFramework()->removeReleaseHook(m_settings, sOnRelease, this);
}
}
const char* get() const
{
// Not a safe operation
CARB_ASSERT(false);
CARB_LOG_ERROR("Shouldn't use unsafe get on a ThreadSafeLocalCache<const char*>");
return "";
}
operator const char*() const
{
// Not a safe operation
return get();
}
std::string getStringSafe() const
{
// Not a safe operation
CARB_ASSERT(m_subscription, "Call startTracking before reading this variable.");
std::lock_guard<std::mutex> guard(m_valueMutex);
return m_value;
}
void set(const char* value)
{
m_settings->set<const char*>(m_valueSettingsPath.c_str(), value);
}
bool isValueDirty() const
{
return m_valueDirty.load(std::memory_order_relaxed);
}
void clearValueDirty()
{
m_valueDirty.store(false, std::memory_order_release);
}
const char* getSettingsPath() const
{
return m_valueSettingsPath.c_str();
}
inline dictionary::IDictionary* getDictionaryInterface() const
{
return m_dictionary;
}
private:
static void sOnRelease(void* iface, void* user)
{
// Settings has gone away, so our subscription is defunct
static_cast<ThreadSafeLocalCache*>(user)->m_subscription = nullptr;
carb::getFramework()->removeReleaseHook(iface, sOnRelease, user);
}
// NOTE: The callback may come in on another thread so wrap it in a mutex to prevent a race.
std::string m_value;
mutable std::mutex m_valueMutex;
std::atomic<bool> m_valueDirty;
std::string m_valueSettingsPath;
dictionary::SubscriptionId* m_subscription = nullptr;
dictionary::IDictionary* m_dictionary = nullptr;
settings::ISettings* m_settings = nullptr;
};
#endif
} // namespace settings
} // namespace carb
|
omniverse-code/kit/include/carb/settings/SettingsBindingsPython.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../dictionary/DictionaryBindingsPython.h"
#include "ISettings.h"
#include "SettingsUtils.h"
#include <memory>
#include <string>
#include <vector>
namespace carb
{
namespace dictionary
{
// Must provide an empty definition for this class to satisfy pybind
struct SubscriptionId
{
};
} // namespace dictionary
namespace settings
{
namespace
{
template <typename T>
py::list toList(const std::vector<T>& v)
{
py::list list;
for (const T& e : v)
list.append(e);
return list;
}
template <typename T>
std::vector<T> toAllocatedArray(const py::sequence& s)
{
std::vector<T> v(s.size());
for (size_t i = 0, size = s.size(); i < size; ++i)
v[i] = s[i].cast<T>();
return v;
}
// std::vector<bool> is typically specialized, so avoid it
std::unique_ptr<bool[]> toBoolArray(const py::sequence& s, size_t& size)
{
size = s.size();
std::unique_ptr<bool[]> p(new bool[size]);
for (size_t i = 0; i < size; ++i)
p[i] = s[i].cast<bool>();
return p;
}
void setValueFromPyObject(ISettings* isregistry, const char* path, const py::object& value)
{
if (py::isinstance<py::bool_>(value))
{
auto val = value.cast<bool>();
py::gil_scoped_release nogil;
isregistry->setBool(path, val);
}
else if (py::isinstance<py::int_>(value))
{
auto val = value.cast<int64_t>();
py::gil_scoped_release nogil;
isregistry->setInt64(path, val);
}
else if (py::isinstance<py::float_>(value))
{
auto val = value.cast<double>();
py::gil_scoped_release nogil;
isregistry->setFloat64(path, val);
}
else if (py::isinstance<py::str>(value))
{
auto val = value.cast<std::string>();
py::gil_scoped_release nogil;
isregistry->setString(path, val.c_str());
}
else if (py::isinstance<py::tuple>(value) || py::isinstance<py::list>(value))
{
py::sequence valueSeq = value.cast<py::sequence>();
{
py::gil_scoped_release nogil;
isregistry->destroyItem(path);
}
for (size_t idx = 0, valueSeqSize = valueSeq.size(); idx < valueSeqSize; ++idx)
{
py::object valueSeqElement = valueSeq[idx];
if (py::isinstance<py::bool_>(valueSeqElement))
{
auto val = valueSeqElement.cast<bool>();
py::gil_scoped_release nogil;
isregistry->setBoolAt(path, idx, val);
}
else if (py::isinstance<py::int_>(valueSeqElement))
{
auto val = valueSeqElement.cast<int64_t>();
py::gil_scoped_release nogil;
isregistry->setInt64At(path, idx, val);
}
else if (py::isinstance<py::float_>(valueSeqElement))
{
auto val = valueSeqElement.cast<double>();
py::gil_scoped_release nogil;
isregistry->setFloat64At(path, idx, val);
}
else if (py::isinstance<py::str>(valueSeqElement))
{
auto val = valueSeqElement.cast<std::string>();
py::gil_scoped_release nogil;
isregistry->setStringAt(path, idx, val.c_str());
}
else if (py::isinstance<py::dict>(valueSeqElement))
{
std::string basePath = path ? path : "";
std::string elemPath = basePath + "/" + std::to_string(idx);
setValueFromPyObject(isregistry, elemPath.c_str(), valueSeqElement);
}
else
{
CARB_LOG_WARN("Unknown type in sequence being written to %s", path);
}
}
}
else if (py::isinstance<py::dict>(value))
{
{
py::gil_scoped_release nogil;
isregistry->destroyItem(path);
}
py::dict valueDict = value.cast<py::dict>();
for (auto kv : valueDict)
{
std::string basePath = path ? path : "";
if (!basePath.empty())
basePath = basePath + "/";
std::string subPath = basePath + kv.first.cast<std::string>().c_str();
setValueFromPyObject(isregistry, subPath.c_str(), kv.second.cast<py::object>());
}
}
}
void setDefaultValueFromPyObject(ISettings* isregistry, const char* path, const py::object& value)
{
if (py::isinstance<py::bool_>(value))
{
auto val = value.cast<bool>();
py::gil_scoped_release nogil;
isregistry->setDefaultBool(path, val);
}
else if (py::isinstance<py::int_>(value))
{
auto val = value.cast<int64_t>();
py::gil_scoped_release nogil;
isregistry->setDefaultInt64(path, val);
}
else if (py::isinstance<py::float_>(value))
{
auto val = value.cast<double>();
py::gil_scoped_release nogil;
isregistry->setDefaultFloat64(path, val);
}
else if (py::isinstance<py::str>(value))
{
auto val = value.cast<std::string>();
py::gil_scoped_release nogil;
isregistry->setDefaultString(path, val.c_str());
}
else if (py::isinstance<py::tuple>(value) || py::isinstance<py::list>(value))
{
py::sequence valueSeq = value.cast<py::sequence>();
if (valueSeq.size() == 0)
{
py::gil_scoped_release nogil;
isregistry->setDefaultArray<int>(path, nullptr, 0);
}
else
{
const py::object& firstElement = valueSeq[0];
if (py::isinstance<py::bool_>(firstElement))
{
size_t size;
auto array = toBoolArray(valueSeq, size);
py::gil_scoped_release nogil;
isregistry->setDefaultArray<bool>(path, array.get(), size);
}
else if (py::isinstance<py::int_>(firstElement))
{
auto array = toAllocatedArray<int64_t>(valueSeq);
py::gil_scoped_release nogil;
isregistry->setDefaultArray<int64_t>(path, &array.front(), array.size());
}
else if (py::isinstance<py::float_>(firstElement))
{
auto array = toAllocatedArray<double>(valueSeq);
py::gil_scoped_release nogil;
isregistry->setDefaultArray<double>(path, &array.front(), array.size());
}
else if (py::isinstance<py::str>(firstElement))
{
std::vector<std::string> strs(valueSeq.size());
std::vector<const char*> strPtrs(valueSeq.size());
for (size_t i = 0, size = valueSeq.size(); i < size; ++i)
{
strs[i] = valueSeq[i].cast<std::string>();
strPtrs[i] = strs[i].c_str();
}
py::gil_scoped_release nogil;
isregistry->setDefaultArray<const char*>(path, strPtrs.data(), strPtrs.size());
}
else if (py::isinstance<py::dict>(firstElement))
{
std::string basePath = path ? path : "";
for (size_t i = 0, size = valueSeq.size(); i < size; ++i)
{
std::string elemPath = basePath + "/" + std::to_string(i);
setDefaultValueFromPyObject(isregistry, elemPath.c_str(), valueSeq[i]);
}
}
else
{
CARB_LOG_WARN("Unknown type in sequence being set as default in '%s'", path);
}
}
}
else if (py::isinstance<py::dict>(value))
{
py::dict valueDict = value.cast<py::dict>();
for (auto kv : valueDict)
{
std::string basePath = path ? path : "";
if (!basePath.empty())
basePath = basePath + "/";
std::string subPath = basePath + kv.first.cast<std::string>().c_str();
setDefaultValueFromPyObject(isregistry, subPath.c_str(), kv.second.cast<py::object>());
}
}
}
} // namespace
inline void definePythonModule(py::module& m)
{
using namespace carb;
using namespace carb::settings;
m.doc() = "pybind11 carb.settings bindings";
py::class_<dictionary::SubscriptionId>(m, "SubscriptionId", R"(Representation of a subscription)");
py::enum_<dictionary::ChangeEventType>(m, "ChangeEventType")
.value("CREATED", dictionary::ChangeEventType::eCreated, R"(An Item was created)")
.value("CHANGED", dictionary::ChangeEventType::eChanged, R"(An Item was changed)")
.value("DESTROYED", dictionary::ChangeEventType::eDestroyed, R"(An Item was destroyed)");
static ScriptCallbackRegistryPython<dictionary::SubscriptionId*, void, const dictionary::Item*, dictionary::ChangeEventType>
s_nodeChangeEventCBs;
static ScriptCallbackRegistryPython<dictionary::SubscriptionId*, void, const dictionary::Item*,
const dictionary::Item*, dictionary::ChangeEventType>
s_treeChangeEventCBs;
using UpdateFunctionWrapper =
ScriptCallbackRegistryPython<void*, dictionary::UpdateAction, const dictionary::Item*, dictionary::ItemType,
const dictionary::Item*, dictionary::ItemType>;
defineInterfaceClass<ISettings>(m, "ISettings", "acquire_settings_interface", nullptr, R"(
The Carbonite Settings interface
Carbonite settings are built on top of the carb.dictionary interface (which is also required in order to use this
interface). Many dictionary functions are replicated in settings, but explicitly use the settings database instead of a
generic carb.dictionary.Item object.
carb.settings uses keys (or paths) that start with an optional forward-slash and are forward-slash separated (example:
"/log/level"). The settings database exists as a root-level carb.dictionary.Item (of type ItemType.DICTIONARY) that is
created and maintained by the carb.settings system (typically through the carb.settings.plugin plugin). The root level
settings carb.dictionary.Item is accessible through get_settings_dictionary().
Portions of the settings database hierarchy can be subscribed to with subscribe_to_tree_change_events() or individual
keys may be subscribed to with subscribe_to_tree_change_events().
)")
.def("is_accessible_as", wrapInterfaceFunction(&ISettings::isAccessibleAs),
py::call_guard<py::gil_scoped_release>(), R"(
Checks if the item could be accessible as the provided type, either directly or via a cast.
Parameters:
itemType: carb.dictionary.ItemType to check for.
path: Settings database key path (i.e. "/log/level").
Returns:
boolean: True if the item is accessible as the provided type; False otherwise.
)")
.def("get_as_int", wrapInterfaceFunction(&ISettings::getAsInt64), py::call_guard<py::gil_scoped_release>(), R"(
Attempts to get the supplied item as an integer, either directly or via conversion.
Parameters:
path: Settings database key path (i.e. "/log/level").
Returns:
Integer: an integer value representing the stored value. If conversion fails, 0 is returned.
)")
.def("set_int", wrapInterfaceFunction(&ISettings::setInt64), py::call_guard<py::gil_scoped_release>(), R"(
Sets the integer value at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: An integer value to store.
)")
.def("get_as_float", wrapInterfaceFunction(&ISettings::getAsFloat64), py::call_guard<py::gil_scoped_release>(), R"(
Attempts to get the supplied item as a floating-point value, either directly or via conversion.
Parameters:
path: Settings database key path (i.e. "/log/level").
Returns:
Float: a floating-point value representing the stored value. If conversion fails, 0.0 is returned.
)")
.def("set_float", wrapInterfaceFunction(&ISettings::setFloat64), py::call_guard<py::gil_scoped_release>(), R"(
Sets the floating-point value at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: A floating-point value to store.
)")
.def("get_as_bool", wrapInterfaceFunction(&ISettings::getAsBool), py::call_guard<py::gil_scoped_release>(), R"(
Attempts to get the supplied item as a boolean value, either directly or via conversion.
Parameters:
path: Settings database key path (i.e. "/log/level").
Returns:
Boolean: a boolean value representing the stored value. If conversion fails, False is returned.
)")
.def("set_bool", wrapInterfaceFunction(&ISettings::setBool), py::call_guard<py::gil_scoped_release>(), R"(
Sets the boolean value at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: A boolean value to store.
)")
.def("get_as_string",
[](const ISettings* isregistry, const char* path) { return getStringFromItemValue(isregistry, path); },
py::call_guard<py::gil_scoped_release>(), R"(
Attempts to get the supplied item as a string value, either directly or via conversion.
Parameters:
path: Settings database key path (i.e. "/log/level").
Returns:
String: a string value representing the stored value. If conversion fails, "" is returned.
)")
.def("set_string",
[](ISettings* isregistry, const char* path, const std::string& str) {
isregistry->setString(path, str.c_str());
},
py::call_guard<py::gil_scoped_release>(), R"(
Sets the string value at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: A string value.
)")
.def("get",
// The defaultValue here is DEPRECATED, some of the scripts out there still use it like that. TODO: remove
// it after some time.
[](const ISettings* isregistry, const char* path) -> py::object {
const dictionary::Item* item = isregistry->getSettingsDictionary(path);
auto obj = dictionary::getPyObject(getCachedInterfaceForBindings<dictionary::IDictionary>(), item);
if (py::isinstance<py::tuple>(obj))
{
// Settings wants a list instead of a tuple
return py::list(std::move(obj));
}
return obj;
},
py::arg("path"), R"(
Retrieve the stored value at the supplied path as a Python object.
An array value will be returned as a list. If the value does not exist, None will be returned.
Parameters:
path: Settings database key path (i.e. "/log/level").
Returns:
A Python object representing the stored value.
)")
.def("set", &setValueFromPyObject, py::arg("path"), py::arg("value"), R"(
Sets the given value at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: A Python object. The carb.dictionary.ItemType is inferred from the type of the object; if the type is not supported, the value is ignored. Both tuples and lists are treated as arrays (a special kind of ItemType.DICTIONARY).
)")
.def("set_default", &setDefaultValueFromPyObject, py::arg("path"), py::arg("value"))
.def("set_int_array",
[](ISettings* isregistry, const char* path, const std::vector<int32_t>& array) {
settings::setIntArray(isregistry, path, array);
},
py::call_guard<py::gil_scoped_release>(), R"(
Sets the given array at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
array: A tuple or list of integer values.
)")
.def("set_float_array",
[](ISettings* isregistry, const char* path, const std::vector<double>& array) {
settings::setFloatArray(isregistry, path, array);
},
py::call_guard<py::gil_scoped_release>(), R"(
Sets the given array at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
array: A tuple or list of floating-point values.
)")
.def("set_bool_array",
[](ISettings* isregistry, const char* path, const std::vector<bool>& array) {
settings::setBoolArray(isregistry, path, array);
},
py::call_guard<py::gil_scoped_release>(), R"(
Sets the given array at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
array: A tuple or list of boolean values.
)")
.def("set_string_array",
[](ISettings* isregistry, const char* path, const std::vector<std::string>& array) {
settings::setStringArray(isregistry, path, array);
},
py::call_guard<py::gil_scoped_release>(), R"(
Sets the given array at the supplied path.
Parameters:
path: Settings database key path (i.e. "/log/level").
array: A tuple or list of strings.
)")
.def("destroy_item", wrapInterfaceFunction(&ISettings::destroyItem), py::call_guard<py::gil_scoped_release>(), R"(
Destroys the item at the given path.
Any objects that reference the given path become invalid and their use is undefined behavior.
Parameters:
path: Settings database key path (i.e. "/log/level").
)")
.def("get_settings_dictionary", wrapInterfaceFunction(&ISettings::getSettingsDictionary),
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>(), R"(
Access the setting database as a dictionary.Item
Accesses the setting database as a dictionary.Item, which allows use of carb.dictionary functions directly.
WARNING: The root dictionary.Item is owned by carb.settings and must not be altered or destroyed.
Parameters:
path: An optional path from root to access. "/" or "" is interpreted to be the settings database root.
)",
py::arg("path") = "")
.def("create_dictionary_from_settings", wrapInterfaceFunction(&ISettings::createDictionaryFromSettings),
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>(), R"(
Takes a snapshot of a portion of the setting database as a dictionary.Item.
Parameters:
path: An optional path from root to access. "/" or "" is interpreted to be the settings database root.
)",
py::arg("path") = "")
.def("initialize_from_dictionary", wrapInterfaceFunction(&ISettings::initializeFromDictionary),
py::call_guard<py::gil_scoped_release>(), R"(
Performs a one-time initialization from a given dictionary.Item.
NOTE: This function may only be called once. Subsequent calls will result in an error message logged.
Parameters:
dictionary: A dictionary.Item to initialize the settings database from. The items are copied into the root of the settings database.
)")
.def("subscribe_to_node_change_events",
[](ISettings* isregistry, const char* path, const decltype(s_nodeChangeEventCBs)::FuncT& eventFn) {
auto eventFnCopy = s_nodeChangeEventCBs.create(eventFn);
dictionary::SubscriptionId* id =
isregistry->subscribeToNodeChangeEvents(path, s_nodeChangeEventCBs.call, eventFnCopy);
s_nodeChangeEventCBs.add(id, eventFnCopy);
return id;
},
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>(), R"(
Subscribes to node change events about a specific item.
When finished with the subscription, call unsubscribe_to_change_events().
Parameters:
path: Settings database key path (i.e. "/log/level") to subscribe to.
eventFn: A function that is called for each change event.
)")
.def("subscribe_to_tree_change_events",
[](ISettings* isregistry, const char* path, const decltype(s_treeChangeEventCBs)::FuncT& eventFn) {
auto eventFnCopy = s_treeChangeEventCBs.create(eventFn);
dictionary::SubscriptionId* id =
isregistry->subscribeToTreeChangeEvents(path, s_treeChangeEventCBs.call, eventFnCopy);
s_treeChangeEventCBs.add(id, eventFnCopy);
return id;
},
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>(), R"(
Subscribes to change events for all items in a subtree.
When finished with the subscription, call unsubscribe_to_change_events().
Parameters:
path: Settings database key path (i.e. "/log/level") to subscribe to.
eventFn: A function that is called for each change event.
)")
.def("unsubscribe_to_change_events",
[](ISettings* isregistry, dictionary::SubscriptionId* id) {
isregistry->unsubscribeToChangeEvents(id);
s_nodeChangeEventCBs.tryRemoveAndDestroy(id);
s_treeChangeEventCBs.tryRemoveAndDestroy(id);
},
py::call_guard<py::gil_scoped_release>(), R"(
Unsubscribes from change events.
Parameters:
id: The handle returned from subscribe_to_tree_change_events() or subscribe_to_node_change_events().
)",
py::arg("id"))
.def("set_default_int",
[](ISettings* isregistry, const char* path, int value) { isregistry->setDefaultInt(path, value); },
py::call_guard<py::gil_scoped_release>(), R"(
Sets a value at the given path, if and only if one does not already exist.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: Value that will be stored at the given path if a value does not already exist there.
)")
.def("set_default_float",
[](ISettings* isregistry, const char* path, float value) { isregistry->setDefaultFloat(path, value); },
py::call_guard<py::gil_scoped_release>(), R"(
Sets a value at the given path, if and only if one does not already exist.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: Value that will be stored at the given path if a value does not already exist there.
)")
.def("set_default_bool",
[](ISettings* isregistry, const char* path, bool value) { isregistry->setDefaultBool(path, value); },
py::call_guard<py::gil_scoped_release>(), R"(
Sets a value at the given path, if and only if one does not already exist.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: Value that will be stored at the given path if a value does not already exist there.
)")
.def("set_default_string",
[](ISettings* isregistry, const char* path, const std::string& str) {
isregistry->setDefaultString(path, str.c_str());
},
py::call_guard<py::gil_scoped_release>(), R"(
Sets a value at the given path, if and only if one does not already exist.
Parameters:
path: Settings database key path (i.e. "/log/level").
value: Value that will be stored at the given path if a value does not already exist there.
)")
.def("update",
[](ISettings* isregistry, const char* path, const dictionary::Item* dictionary, const char* dictionaryPath,
const py::object& updatePolicy) {
if (py::isinstance<dictionary::UpdateAction>(updatePolicy))
{
dictionary::UpdateAction updatePolicyEnum = updatePolicy.cast<dictionary::UpdateAction>();
py::gil_scoped_release nogil;
if (updatePolicyEnum == dictionary::UpdateAction::eOverwrite)
{
isregistry->update(path, dictionary, dictionaryPath, dictionary::overwriteOriginal, nullptr);
}
else if (updatePolicyEnum == dictionary::UpdateAction::eKeep)
{
isregistry->update(path, dictionary, dictionaryPath, dictionary::keepOriginal, nullptr);
}
else
{
CARB_LOG_ERROR("Unknown update policy type");
}
}
else
{
const UpdateFunctionWrapper::FuncT updateFn =
updatePolicy.cast<const UpdateFunctionWrapper::FuncT>();
py::gil_scoped_release nogil;
isregistry->update(path, dictionary, dictionaryPath, UpdateFunctionWrapper::call, (void*)&updateFn);
}
},
R"(
Merges the source dictionary.Item into the settings database.
Destination path need not exist and missing items in the path will be created as ItemType.DICTIONARY.
Parameters:
path: Settings database key path (i.e. "/log/level"). Used as the destination location within the setting database. "/" is considered to be the root.
dictionary: A dictionary.Item used as the base of the items to merge into the setting database.
dictionaryPath: A child path of `dictionary` to use as the root for merging. May be None or an empty string in order to use `dictionary` directly as the root.
updatePolicy: One of dictionary.UpdateAction to use as the policy for updating.
)");
}
} // namespace settings
} // namespace carb
|
omniverse-code/kit/include/carb/datasource/IDataSource.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Interface.h"
#include "../Types.h"
#include "DataSourceTypes.h"
namespace carb
{
namespace datasource
{
/**
* Defines a data source interface.
*/
struct IDataSource
{
/**
* 1.1 added "hash" field to carb::datasource::ItemInfo
*/
CARB_PLUGIN_INTERFACE("carb::datasource::IDataSource", 1, 1)
/**
* Gets a list of supported protocols for this interface.
*
* @return The comma-separated list of supported protocols.
*/
const char*(CARB_ABI* getSupportedProtocols)();
/**
* Connects to a datasource.
*
* @param desc The connection descriptor.
* @param onConnectionEvent The callback for handling connection events.
* @param userData The userData to be passed back to callback.
*/
void(CARB_ABI* connect)(const ConnectionDesc& desc, OnConnectionEventFn onConnectionEvent, void* userData);
/**
* Disconnects from a datasource.
*
* @param connection The connection to use.
*/
void(CARB_ABI* disconnect)(Connection* connection);
/**
* Attempts to stop processing a specified request on a connection.
*
* @param connection The connection to use.
* @param id The request id to stop processing.
*/
void(CARB_ABI* stopRequest)(Connection* connection, RequestId id);
/**
* Lists all the child relative data path entries from the specified path in the data source.
*
* You must delete the path returned.
*
* @param connection The connect to use.
* @param path The path to start the listing from.
* @param recursive true to recursively list items in directory and subdirectories.
* @param onListDataItem The callback for each item listed.
* @param onListDataDone The callback for when there are no more items listed.
* @param userData The userData to be pass to callback.
* @return The data request id or 0 if failed.
*/
RequestId(CARB_ABI* listData)(Connection* connection,
const char* path,
bool recursize,
OnListDataItemFn onListDataItem,
OnListDataDoneFn onListDataDone,
void* userData);
/**
* Creates a data block associated to the specified path to the data source.
*
* @param connection The connect to use.
* @param path The path to create the data. Must not exist.
* @param payload The payload data to be initialize to.
* @param payloadSize The size of the payload data to initialize.
* @param onCreateData Callback function use.
* @param userData The userData to be pass to callback.
* @return The data request id or 0 if failed.
*/
RequestId(CARB_ABI* createData)(Connection* connection,
const char* path,
uint8_t* payload,
size_t payloadSize,
OnCreateDataFn onCreateData,
void* userData);
/**
* Deletes a data block based on the specified path from the data source.
*
* @param connection The connect to use.
* @param path The path of the data to be destroyed(deleted).
* @param onFree The callback function to be used to free the data.
* @param onDeleteData The callback function to be called when the data is deleted.
* @param userData The userData to be pass to callback.
* @return The data request id or 0 if failed.
*/
RequestId(CARB_ABI* deleteData)(Connection* connection, const char* path, OnDeleteDataFn onDeleteData, void* userData);
/**
* Initiates an asynchronous read of data from the datasource. A callback is called when the read completes.
*
* @param connection The connection to use.
* @param path The path for the data.
* @param onMalloc The callback function to allocate the memory that will be returned in data
* @param onReadData The callback function called once the data is read.
* @param userData The userData to be pass to callback.
* @return The data request id or 0 if failed.
*/
RequestId(CARB_ABI* readData)(
Connection* connection, const char* path, OnMallocFn onMalloc, OnReadDataFn onReadData, void* userData);
/**
* Synchronously reads data from the data source.
*
* @param connection The connection to use.
* @param path The path for the data.
* @param onMalloc the callback function to allocate memory that will be returned
* @param block The allocated memory holding the data will be returned here
* @param size The size of the allocated block will be returned here
* @return One of the response codes to indicate the success of the call
*/
Response(CARB_ABI* readDataSync)(
Connection* connection, const char* path, OnMallocFn onMalloc, void** block, size_t* size);
/**
* Writes data to the data source.
*
* @param connection The connection to use.
* @param path The path for the data.
* @param payload The data that was written. *** This memory must be freed by the caller.
* @param payloadSize The size of the data written.
* @param version The version of the data written.
* @param onWriteData The callback function to call when payload data is written.
* @param userData The userData to be pass to callback.
* @return The data request id or 0 if failed.
*/
RequestId(CARB_ABI* writeData)(Connection* connection,
const char* path,
const uint8_t* payload,
size_t payloadSize,
const char* version,
OnWriteDataFn onWriteData,
void* userData);
/**
* Creates a subscription for modifications to data.
*
* @param connection The connection to use.
* @param path The path for the data.
* @param onModifyData The function to call when the data is modified.
* @param userData The user data ptr to be associated with the callback.
* @return The subscription id or 0 if failed.
*/
SubscriptionId(CARB_ABI* subscribeToChangeEvents)(Connection* connection,
const char* path,
OnChangeEventFn onChangeEvent,
void* userData);
/**
* Removes a subscription for modifications to data.
*
* @param connection The connection from which to remove the subscription.
* @param id The subscription id to unsubscribe from.
*/
void(CARB_ABI* unsubscribeToChangeEvents)(Connection* connection, SubscriptionId subscriptionId);
/**
* Gets the native handle from a datasource connection.
*
* @param The connection from which to native connection handle from.
* @return The native connection handle.
*/
void*(CARB_ABI* getConnectionNativeHandle)(Connection* connection);
/**
* Gets the url from a datasource connection.
*
* @param The connection from which to get url from.
* @return The connection url.
*/
const char*(CARB_ABI* getConnectionUrl)(Connection* connection);
/**
* Gets the username from a datasource connection.
*
* @param The connection from which to get username from.
* @return The connection username. nullptr if username is not applicable for the connection.
*/
const char*(CARB_ABI* getConnectionUsername)(Connection* connection);
/**
* Gets the unique connection id from a datasource connection.
* @param The connection from which to get id from.
* @return The connection id. kInvalidConnectionId if the datasource has no id implementation
* or the connection is invalid.
*/
ConnectionId(CARB_ABI* getConnectionId)(Connection* connection);
/**
* Tests whether it's possible to write data with the provided path.
*
* @param path The path to write the data.
* @return true if it's possible to write to this data.
*/
RequestId(CARB_ABI* isWritable)(Connection* connection, const char* path, OnIsWritableFn onIsWritable, void* userData);
/**
* Returns authentication token, which encapsulates the security identity of the connection.
* The token can be used to connect to other omniverse services.
*
* @param connection from which to get authentication token from.
* @return authentication token as a string.
*/
const char*(CARB_ABI* getConnectionAuthToken)(Connection* connection);
};
} // namespace datasource
} // namespace carb
|
omniverse-code/kit/include/carb/datasource/DataSourceBindingsPython.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "IDataSource.h"
#include <chrono>
#include <memory>
#include <string>
#include <vector>
namespace carb
{
namespace datasource
{
struct Connection
{
};
struct ConnectionDescPy
{
std::string url;
std::string username;
std::string password;
bool disableCache;
};
struct ItemInfoPy
{
std::string path;
std::string version;
std::chrono::system_clock::time_point modifiedTimestamp;
std::chrono::system_clock::time_point createdTimestamp;
size_t size;
bool isDirectory;
bool isWritable;
std::string hash;
};
inline void definePythonModule(py::module& m)
{
using namespace carb;
using namespace carb::datasource;
m.doc() = "pybind11 carb.datasource bindings";
py::class_<Connection>(m, "Connection");
m.attr("INVALID_CONNECTION_ID") = py::int_(kInvalidConnectionId);
m.attr("SUBSCRIPTION_FAILED") = py::int_(kSubscriptionFailed);
py::enum_<ChangeAction>(m, "ChangeAction", R"(
ChangeAction.
)")
.value("CREATED", ChangeAction::eCreated)
.value("DELETED", ChangeAction::eDeleted)
.value("MODIFIED", ChangeAction::eModified)
.value("CONNECTION_LOST", ChangeAction::eConnectionLost);
py::enum_<ConnectionEventType>(m, "ConnectionEventType", R"(
Connection event results.
)")
.value("CONNECTED", ConnectionEventType::eConnected)
.value("DISCONNECTED", ConnectionEventType::eDisconnected)
.value("FAILED", ConnectionEventType::eFailed)
.value("INTERUPTED", ConnectionEventType::eInterrupted);
py::enum_<Response>(m, "Response", R"(
Response results for data requests.
)")
.value("OK", Response::eOk)
.value("ERROR_INVALID_PATH", Response::eErrorInvalidPath)
.value("ERROR_ALREADY_EXISTS", Response::eErrorAlreadyExists)
.value("ERROR_INCOMPATIBLE_VERSION", Response::eErrorIncompatibleVersion)
.value("ERROR_TIMEOUT", Response::eErrorTimeout)
.value("ERROR_ACCESS", Response::eErrorAccess)
.value("ERROR_UNKNOWN", Response::eErrorUnknown);
py::class_<ConnectionDescPy>(m, "ConnectionDesc", R"(
Descriptor for a connection.
)")
.def(py::init<>())
.def_readwrite("url", &ConnectionDescPy::url)
.def_readwrite("username", &ConnectionDescPy::username)
.def_readwrite("password", &ConnectionDescPy::password)
.def_readwrite("disable_cache", &ConnectionDescPy::disableCache);
py::class_<ItemInfoPy>(m, "ItemInfo", R"(
Class holding the list data item information
)")
.def(py::init<>())
.def_readonly("path", &ItemInfoPy::path)
.def_readonly("version", &ItemInfoPy::version)
.def_readonly("hash", &ItemInfoPy::hash)
.def_readonly("modified_timestamp", &ItemInfoPy::modifiedTimestamp)
.def_readonly("created_timestamp", &ItemInfoPy::createdTimestamp)
.def_readonly("size", &ItemInfoPy::size)
.def_readonly("is_directory", &ItemInfoPy::isDirectory)
.def_readonly("is_writable", &ItemInfoPy::isWritable);
defineInterfaceClass<IDataSource>(m, "IDataSource", "acquire_datasource_interface")
.def("get_supported_protocols", wrapInterfaceFunction(&IDataSource::getSupportedProtocols))
.def("connect",
[](IDataSource* iface, const ConnectionDescPy& descPy,
std::function<void(Connection * connection, ConnectionEventType eventType)> fn) {
auto callable = createPyAdapter(std::move(fn));
using Callable = decltype(callable)::element_type;
ConnectionDesc desc = { descPy.url.c_str(), descPy.username.c_str(), descPy.password.c_str(),
descPy.disableCache };
iface->connect(desc,
[](Connection* connection, ConnectionEventType eventType, void* userData) {
Callable::callAndKeep(userData, connection, eventType);
if (eventType != ConnectionEventType::eConnected)
{
Callable::destroy(userData);
}
},
callable.release());
})
.def("disconnect", wrapInterfaceFunctionReleaseGIL(&IDataSource::disconnect))
.def("stop_request", wrapInterfaceFunction(&IDataSource::stopRequest))
.def("list_data",
[](IDataSource* iface, Connection* connection, const char* path, bool recursize,
std::function<bool(Response, const ItemInfoPy&)> onListDataItemFn,
std::function<void(Response, const std::string&)> onListDataDoneFn) {
auto pair = std::make_pair(
createPyAdapter(std::move(onListDataItemFn)), createPyAdapter(std::move(onListDataDoneFn)));
using Pair = decltype(pair);
auto pairHeap = new Pair(std::move(pair));
auto onListDataItemCppFn = [](Response response, const ItemInfo* const info, void* userData) -> bool {
auto pyCallbacks = static_cast<Pair*>(userData);
ItemInfoPy infoPy;
infoPy.path = info->path;
infoPy.version = info->version ? info->version : "";
infoPy.modifiedTimestamp = std::chrono::system_clock::from_time_t(info->modifiedTimestamp);
infoPy.createdTimestamp = std::chrono::system_clock::from_time_t(info->createdTimestamp);
infoPy.size = info->size;
infoPy.isDirectory = info->isDirectory;
infoPy.isWritable = info->isWritable;
infoPy.hash = info->hash ? info->hash : "";
return pyCallbacks->first->call(response, infoPy);
};
auto onListDataDoneCppFn = [](Response response, const char* path, void* userData) {
auto pyCallbacks = reinterpret_cast<Pair*>(userData);
pyCallbacks->second->call(response, path);
delete pyCallbacks;
};
return iface->listData(connection, path, recursize, onListDataItemCppFn, onListDataDoneCppFn, pairHeap);
})
.def("create_data",
[](IDataSource* iface, Connection* connection, const char* path, const py::bytes& payload,
std::function<void(Response response, const char* path, const char* version)> onCreateDataFn) {
auto callable = createPyAdapter(std::move(onCreateDataFn));
using Callable = decltype(callable)::element_type;
std::string payloadContent(payload);
static_assert(sizeof(std::string::value_type) == sizeof(uint8_t), "payload data size mismatch");
return iface->createData(connection, path, reinterpret_cast<uint8_t*>(&payloadContent[0]),
payloadContent.size(), Callable::adaptCallAndDestroy, callable.release());
})
.def("delete_data",
[](IDataSource* iface, Connection* connection, const char* path,
std::function<void(Response response, const char* path)> onDeleteDataFn) {
auto callable = createPyAdapter(std::move(onDeleteDataFn));
using Callable = decltype(callable)::element_type;
return iface->deleteData(connection, path, Callable::adaptCallAndDestroy, callable.release());
})
.def("read_data",
[](IDataSource* iface, Connection* connection, const char* path,
std::function<void(Response response, const char* path, const py::bytes& payload)> onReadDataFn) {
auto callable = createPyAdapter(std::move(onReadDataFn));
using Callable = decltype(callable)::element_type;
return iface->readData(
connection, path, std::malloc,
[](Response response, const char* path, uint8_t* data, size_t dataSize, void* userData) {
static_assert(sizeof(char) == sizeof(uint8_t), "payload data size mismatch");
py::gil_scoped_acquire gil; // make sure we own the GIL for creating py::bytes
const py::bytes payload(reinterpret_cast<const char*>(data), dataSize);
Callable::callAndDestroy(userData, response, path, payload);
// Data needs to be freed manually.
if (data)
{
std::free(data);
}
},
callable.release());
})
.def("read_data_sync",
[](IDataSource* iface, Connection* connection, const char* path) -> py::bytes {
void* data{ nullptr };
size_t size{ 0 };
Response response = iface->readDataSync(connection, path, std::malloc, &data, &size);
py::gil_scoped_acquire gil; // make sure we own the GIL for creating py::bytes
py::bytes bytes =
response == Response::eOk ? py::bytes(reinterpret_cast<const char*>(data), size) : py::bytes();
if (data)
{
std::free(data);
}
return bytes;
})
.def("write_data",
[](IDataSource* iface, Connection* connection, const char* path, const py::bytes& payload,
const char* version, std::function<void(Response response, const char* path)> onWriteDataFn) {
auto callable = createPyAdapter(std::move(onWriteDataFn));
using Callable = decltype(callable)::element_type;
std::string payloadContent(payload);
static_assert(sizeof(std::string::value_type) == sizeof(uint8_t), "payload data size mismatch");
return iface->writeData(connection, path, reinterpret_cast<const uint8_t*>(payloadContent.data()),
payloadContent.size(), version, Callable::adaptCallAndDestroy,
callable.release());
})
.def("subscribe_to_change_events",
[](IDataSource* iface, Connection* connection, const char* path,
std::function<void(const char* path, ChangeAction action)> fn) {
using namespace std::placeholders;
return createPySubscription(std::move(fn),
std::bind(iface->subscribeToChangeEvents, connection, path, _1, _2),
[iface, connection](SubscriptionId id) {
// Release the GIL since unsubscribe can block on a mutex and deadlock
py::gil_scoped_release gsr;
iface->unsubscribeToChangeEvents(connection, id);
});
})
.def("get_connection_native_handle", wrapInterfaceFunction(&IDataSource::getConnectionNativeHandle))
.def("get_connection_url", wrapInterfaceFunction(&IDataSource::getConnectionUrl))
.def("get_connection_username", wrapInterfaceFunction(&IDataSource::getConnectionUsername))
.def("get_connection_id", wrapInterfaceFunction(&IDataSource::getConnectionId))
.def("is_writable", [](IDataSource* iface, Connection* connection, const char* path,
std::function<void(Response response, const char* path, bool writable)> fn) {
auto callable = createPyAdapter(std::move(fn));
using Callable = decltype(callable)::element_type;
return iface->isWritable(connection, path, Callable::adaptCallAndDestroy, callable.release());
});
}
} // namespace datasource
} // namespace carb
|
omniverse-code/kit/include/carb/datasource/DataSourceTypes.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
namespace carb
{
namespace datasource
{
typedef uint64_t RequestId;
typedef uint64_t SubscriptionId;
typedef uint64_t ConnectionId;
constexpr uint64_t kInvalidConnectionId = ~0ull;
constexpr uint64_t kSubscriptionFailed = 0;
struct Connection;
/**
* Defines a descriptor for a connection.
*/
struct ConnectionDesc
{
const char* url;
const char* username;
const char* password;
bool disableCache;
};
/**
* Defines a struct holding the list data item information
*/
struct ItemInfo
{
const char* path;
const char* version;
time_t modifiedTimestamp;
time_t createdTimestamp;
size_t size;
bool isDirectory;
bool isWritable;
const char* hash;
};
enum class ChangeAction
{
eCreated,
eDeleted,
eModified,
eConnectionLost
};
/**
* Defines the connection event type.
*/
enum class ConnectionEventType
{
eConnected,
eFailed,
eDisconnected,
eInterrupted
};
/**
* Response results for data requests.
*/
enum class Response
{
eOk,
eErrorInvalidPath,
eErrorAlreadyExists,
eErrorIncompatibleVersion,
eErrorTimeout,
eErrorAccess,
eErrorUnknown
};
/**
* Function callback on connection events.
*
* @param connection The connection used.
* @param eventType The connection event type.
* @param userData The user data passed back.
*/
typedef void (*OnConnectionEventFn)(Connection* connection, ConnectionEventType eventType, void* userData);
/**
* Function callback on change events.
*
* @param path The path that has changed.
* @param action The change action that has occurred.
* @parm userData The user data passed back.
*/
typedef void (*OnChangeEventFn)(const char* path, ChangeAction action, void* userData);
/**
* Function callback on listed data items.
*
* This is called for each item returned from IDataSource::listData
*
* @param response The response result.
* @param path The path of the list item.
* @param version The version of the list item.
* @param userData The user data passed back.
* @return true to continue iteration, false to stop it. This can be useful when searching for a specific file
* or when iteration needs to be user interruptable.
*/
typedef bool (*OnListDataItemFn)(Response response, const ItemInfo* const info, void* userData);
/**
* Function callback on listed data items are done.
*
* @param response The response result.
* @param path The path the listing is complete listing items for.
* @param userData The user data passed back.
*/
typedef void (*OnListDataDoneFn)(Response response, const char* path, void* userData);
/**
* Function callback on data created.
*
* @param response The response result.
* @param path The path the data was created on.
* @param version The version of the data created.
* @param userData The user data passed back.
*/
typedef void (*OnCreateDataFn)(Response response, const char* path, const char* version, void* userData);
/**
* Function callback on data deleted.
*
* @param response The response result.
* @param path The path the data was created on.
* @param userData The user data passed back.
*/
typedef void (*OnDeleteDataFn)(Response response, const char* path, void* userData);
/**
* Function callback on data read.
*
* @param response The response result.
* @param path The path the data was created on.
* @param payload The payload data that was read. *** This must be freed when completed.
* @param payloadSize The size of the payload data read.
* @param userData The user data passed back.
*/
typedef void (*OnReadDataFn)(Response response, const char* path, uint8_t* payload, size_t payloadSize, void* userData);
/**
* Function callback on data written.
*
* @param response The response result.
* @param path The path the data was written at.
* @param userData The user data passed back.
*/
typedef void (*OnWriteDataFn)(Response response, const char* path, void* userData);
/**
* Function callback for allocation of data.
*
* @param size The size of data to allocate.
* @return The pointer to the data allocated.
*/
typedef void* (*OnMallocFn)(size_t size);
/**
* Function callback on data read.
*
* @param response The response result.
* @param path The path the data was created on.
* @param userData The user data passed back.
*/
typedef void (*OnIsWritableFn)(Response response, const char* path, bool writable, void* userData);
} // namespace datasource
} // namespace carb
|
omniverse-code/kit/include/carb/datasource/DataSourceUtils.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Framework.h"
#include "../Types.h"
#include "../logging/ILogging.h"
#include "IDataSource.h"
#include <future>
namespace carb
{
namespace datasource
{
inline Connection* connectAndWait(const ConnectionDesc& desc, const IDataSource* dataSource)
{
std::promise<Connection*> promise;
auto future = promise.get_future();
dataSource->connect(desc,
[](Connection* connection, ConnectionEventType eventType, void* userData) {
std::promise<Connection*>* promise = reinterpret_cast<std::promise<Connection*>*>(userData);
switch (eventType)
{
case ConnectionEventType::eConnected:
promise->set_value(connection);
break;
case ConnectionEventType::eFailed:
case ConnectionEventType::eInterrupted:
promise->set_value(nullptr);
break;
case ConnectionEventType::eDisconnected:
break;
}
},
&promise);
return future.get();
}
inline Connection* connectAndWait(const ConnectionDesc& desc, const char* pluginName = nullptr)
{
carb::Framework* framework = carb::getFramework();
IDataSource* dataSource = framework->acquireInterface<IDataSource>(pluginName);
return connectAndWait(desc, dataSource);
}
} // namespace datasource
} // namespace carb
|
omniverse-code/kit/include/carb/thread/FutexImpl.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "../cpp/Bit.h"
#include "../math/Util.h"
#include "../thread/Util.h"
#include <atomic>
#if CARB_PLATFORM_WINDOWS
# pragma comment(lib, "synchronization.lib") // must link with synchronization.lib
# include "../CarbWindows.h"
#elif CARB_PLATFORM_LINUX
# include <linux/futex.h>
# include <sys/syscall.h>
# include <sys/time.h>
# include <unistd.h>
#elif CARB_PLATFORM_MACOS
/* nothing for now */
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
namespace carb
{
namespace thread
{
namespace detail
{
template <class T, size_t S = sizeof(T)>
struct to_integral
{
};
template <class T>
struct to_integral<T, 1>
{
using type = int8_t;
};
template <class T>
struct to_integral<T, 2>
{
using type = int16_t;
};
template <class T>
struct to_integral<T, 4>
{
using type = int32_t;
};
template <class T>
struct to_integral<T, 8>
{
using type = int64_t;
};
template <class T>
using to_integral_t = typename to_integral<T>::type;
template <class As, class T>
CARB_NODISCARD std::enable_if_t<std::is_integral<T>::value && sizeof(As) == sizeof(T), As> reinterpret_as(const T& in) noexcept
{
static_assert(std::is_integral<As>::value, "Must be integral type");
return static_cast<As>(in);
}
template <class As, class T>
CARB_NODISCARD std::enable_if_t<std::is_pointer<T>::value && sizeof(As) == sizeof(T), As> reinterpret_as(const T& in) noexcept
{
static_assert(std::is_integral<As>::value, "Must be integral type");
return reinterpret_cast<As>(in);
}
template <class As, class T>
CARB_NODISCARD std::enable_if_t<(!std::is_pointer<T>::value && !std::is_integral<T>::value) || sizeof(As) != sizeof(T), As> reinterpret_as(
const T& in) noexcept
{
static_assert(std::is_integral<As>::value, "Must be integral type");
As out{}; // Init to zero
memcpy(&out, std::addressof(in), sizeof(in));
return out;
}
template <class Duration>
Duration clampDuration(Duration offset)
{
using namespace std::chrono;
constexpr static Duration Max = duration_cast<Duration>(milliseconds(0x7fffffff));
return ::carb_max(Duration(0), ::carb_min(Max, offset));
}
#if CARB_PLATFORM_WINDOWS
// Windows WaitOnAddress() supports 1, 2, 4 or 8 bytes, so it doesn't need to use ParkingLot. For testing ParkingLot
// or for specific modules this can be enabled though.
# ifndef CARB_USE_PARKINGLOT
# define CARB_USE_PARKINGLOT 0
# endif
using hundrednanos = std::chrono::duration<int64_t, std::ratio<1, 10'000'000>>;
template <class T>
inline bool WaitOnAddress(const std::atomic<T>& val, T compare, int64_t* timeout) noexcept
{
static_assert(sizeof(val) == sizeof(compare), "Invalid assumption about atomic");
// Use the NTDLL version of this function since we can give it relative or absolute times in 100ns units
using RtlWaitOnAddressFn = DWORD(__stdcall*)(volatile const void*, void*, size_t, int64_t*);
static RtlWaitOnAddressFn RtlWaitOnAddress =
(RtlWaitOnAddressFn)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlWaitOnAddress");
volatile const T* addr = reinterpret_cast<volatile const T*>(std::addressof(val));
switch (DWORD ret = RtlWaitOnAddress(addr, &compare, sizeof(compare), timeout))
{
case CARBWIN_STATUS_SUCCESS:
return true;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from RtlWaitOnAddress: %u, GetLastError=%u", ret, ::GetLastError());
CARB_FALLTHROUGH; // (not really, but the compiler doesn't know that CARB_FATAL_UNLESS doesn't return)
case CARBWIN_STATUS_TIMEOUT:
return false;
}
}
template <class T>
inline void futex_wait(const std::atomic<T>& val, T compare) noexcept
{
WaitOnAddress(val, compare, nullptr);
}
template <class T, class Rep, class Period>
inline bool futex_wait_for(const std::atomic<T>& val, T compare, std::chrono::duration<Rep, Period> duration)
{
// RtlWaitOnAddress treats negative timeouts as positive relative time
int64_t timeout = -std::chrono::duration_cast<hundrednanos>(clampDuration(duration)).count();
if (timeout >= 0)
{
// duration to wait is negative
return false;
}
CARB_ASSERT(timeout < 0);
return WaitOnAddress(val, compare, &timeout);
}
template <class T, class Clock, class Duration>
inline bool futex_wait_until(const std::atomic<T>& val, T compare, std::chrono::time_point<Clock, Duration> time_point)
{
int64_t absTime;
auto now = Clock::now();
// RtlWaitOnAddress is quite slow to return if the time has already elapsed. It's much faster for us to check first.
if (time_point <= now)
{
return false;
}
// Constrain the time to something that is well before the heat death of the universe
auto tp = now + clampDuration(time_point - now);
// if ((void*)std::addressof(Clock::now) != (void*)std::addressof(std::chrono::system_clock::now))
if (!std::is_same<Clock, std::chrono::system_clock>::value)
{
// If we're not using the system clock, then we need to convert to the system clock
absTime = std::chrono::duration_cast<detail::hundrednanos>(
(tp - now + std::chrono::system_clock::now()).time_since_epoch())
.count();
}
else
{
// Already in terms of system clock
// According to https://github.com/microsoft/STL/blob/master/stl/inc/chrono, the system_clock appears to
// use GetSystemTimePreciseAsFileTime minus an epoch value so that it lines up with 1/1/1970 midnight GMT.
// Unfortunately there's not an easy way to check for it here, but we have a unittest in TestSemaphore.cpp.
absTime = std::chrono::duration_cast<detail::hundrednanos>(tp.time_since_epoch()).count();
}
// Epoch value from https://github.com/microsoft/STL/blob/master/stl/src/xtime.cpp
// This is the number of 100ns units between 1 January 1601 00:00 GMT and 1 January 1970 00:00 GMT
constexpr int64_t kFiletimeEpochToUnixEpochIn100nsUnits = 0x19DB1DED53E8000LL;
absTime += kFiletimeEpochToUnixEpochIn100nsUnits;
CARB_ASSERT(absTime >= 0);
return detail::WaitOnAddress(val, compare, &absTime);
}
template <class T>
inline void futex_wake_one(std::atomic<T>& val) noexcept
{
WakeByAddressSingle(std::addressof(val));
}
template <class T>
inline void futex_wake_n(std::atomic<T>& val, size_t n) noexcept
{
while (n--)
futex_wake_one(val);
}
template <class T>
inline void futex_wake_all(std::atomic<T>& val) noexcept
{
WakeByAddressAll(std::addressof(val));
}
# if !CARB_USE_PARKINGLOT
template <class T, size_t S = sizeof(T)>
class Futex
{
static_assert(S == 1 || S == 2 || S == 4 || S == 8, "Unsupported size");
public:
using AtomicType = typename std::atomic<T>;
using Type = T;
static inline void wait(const AtomicType& val, Type compare) noexcept
{
futex_wait(val, compare);
}
template <class Rep, class Period>
static inline bool wait_for(const AtomicType& val, Type compare, std::chrono::duration<Rep, Period> duration)
{
return futex_wait_for(val, compare, duration);
}
template <class Clock, class Duration>
static inline bool wait_until(const AtomicType& val, Type compare, std::chrono::time_point<Clock, Duration> time_point)
{
return futex_wait_until(val, compare, time_point);
}
static inline void notify_one(AtomicType& a) noexcept
{
futex_wake_one(a);
}
static inline void notify_n(AtomicType& a, size_t n) noexcept
{
futex_wake_n(a, n);
}
static inline void notify_all(AtomicType& a) noexcept
{
futex_wake_all(a);
}
};
# endif
#elif CARB_PLATFORM_LINUX
# define CARB_USE_PARKINGLOT 1 // Linux only supports 4 byte futex so it must use the ParkingLot
constexpr int64_t kNsPerSec = 1'000'000'000;
inline int futex(const std::atomic_uint32_t& aval,
int futex_op,
uint32_t val,
const struct timespec* timeout,
uint32_t* uaddr2,
int val3) noexcept
{
static_assert(sizeof(aval) == sizeof(uint32_t), "Invalid assumption about atomic");
int ret = syscall(SYS_futex, std::addressof(aval), futex_op, val, timeout, uaddr2, val3);
return ret >= 0 ? ret : -errno;
}
inline void futex_wait(const std::atomic_uint32_t& val, uint32_t compare) noexcept
{
for (;;)
{
int ret = futex(val, FUTEX_WAIT_BITSET_PRIVATE, compare, nullptr, nullptr, FUTEX_BITSET_MATCH_ANY);
switch (ret)
{
case 0:
case -EAGAIN: // Valid or spurious wakeup
return;
case -ETIMEDOUT:
// Apparently on Windows Subsystem for Linux, calls to the kernel can timeout even when a timeout value
// was not specified. Fall through.
case -EINTR: // Interrupted by signal; loop again
break;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from futex(): %d/%s", -ret, strerror(-ret));
}
}
}
template <class Rep, class Period>
inline bool futex_wait_for(const std::atomic_uint32_t& val, uint32_t compare, std::chrono::duration<Rep, Period> duration)
{
// Relative time
int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(clampDuration(duration)).count();
if (ns <= 0)
{
return false;
}
struct timespec ts;
ts.tv_sec = time_t(ns / detail::kNsPerSec);
ts.tv_nsec = long(ns % detail::kNsPerSec);
// Since we're using relative time here, we can use FUTEX_WAIT_PRIVATE (see futex() man page)
int ret = futex(val, FUTEX_WAIT_PRIVATE, compare, &ts, nullptr, 0);
switch (ret)
{
case 0: // Valid wakeup
case -EAGAIN: // Valid or spurious wakeup
case -EINTR: // Interrupted by signal; treat as a spurious wakeup
return true;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from futex(): %d/%s", -ret, strerror(-ret));
CARB_FALLTHROUGH; // (not really but the compiler doesn't know that the above won't return)
case -ETIMEDOUT:
return false;
}
}
template <class Clock, class Duration>
inline bool futex_wait_until(const std::atomic_uint32_t& val,
uint32_t compare,
std::chrono::time_point<Clock, Duration> time_point)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
// Constrain the time to something that is well before the heat death of the universe
auto now = Clock::now();
auto tp = now + clampDuration(time_point - now);
// Get the number of nanoseconds to go
int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(tp - now).count();
if (ns <= 0)
{
return false;
}
ts.tv_sec += time_t(ns / kNsPerSec);
ts.tv_nsec += long(ns % kNsPerSec);
// Handle rollover
if (ts.tv_nsec >= kNsPerSec)
{
++ts.tv_sec;
ts.tv_nsec -= kNsPerSec;
}
for (;;)
{
// Since we're using absolute monotonic time, we use FUTEX_WAIT_BITSET_PRIVATE. See the man page for futex for
// more info.
int ret = futex(val, FUTEX_WAIT_BITSET_PRIVATE, compare, &ts, nullptr, FUTEX_BITSET_MATCH_ANY);
switch (ret)
{
case 0: // Valid wakeup
case -EAGAIN: // Valid or spurious wakeup
return true;
case -EINTR: // Interrupted by signal; loop again
break;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from futex(): %d/%s", -ret, strerror(-ret));
CARB_FALLTHROUGH; // (not really but the compiler doesn't know that the above won't return)
case -ETIMEDOUT:
return false;
}
}
}
inline void futex_wake_n(std::atomic_uint32_t& val, unsigned count) noexcept
{
int ret = futex(val, FUTEX_WAKE_BITSET_PRIVATE, count, nullptr, nullptr, FUTEX_BITSET_MATCH_ANY);
CARB_ASSERT(ret >= 0, "futex(FUTEX_WAKE) failed with errno=%d/%s", -ret, strerror(-ret));
CARB_UNUSED(ret);
}
inline void futex_wake_one(std::atomic_uint32_t& val) noexcept
{
futex_wake_n(val, 1);
}
inline void futex_wake_all(std::atomic_uint32_t& val) noexcept
{
futex_wake_n(val, INT_MAX);
}
#elif CARB_PLATFORM_MACOS
# define CARB_USE_PARKINGLOT 1
# define UL_COMPARE_AND_WAIT 1
# define UL_UNFAIR_LOCK 2
# define UL_COMPARE_AND_WAIT_SHARED 3
# define UL_UNFAIR_LOCK64_SHARED 4
# define UL_COMPARE_AND_WAIT64 5
# define UL_COMPARE_AND_WAIT64_SHARED 6
# define ULF_WAKE_ALL 0x00000100
# define ULF_WAKE_THREAD 0x00000200
# define ULF_NO_ERRNO 0x01000000
/** Undocumented OSX futex-like call.
* @param operation A combination of the UL_* and ULF_* flags.
* @param[in] addr The address to wait on.
* This is a 32 bit value unless UL_COMPARE_AND_WAIT64 is passed.
* @param value The address's previous value.
* @param timeout Timeout in microseconds.
* @returns 0 or a positive value (representing additional waiters) on success, or a negative value on error. If a
* negative value is returned, `errno` will be set, unless ULF_NO_ERRNO is provided, in which case the
* return value is the negated error value.
*/
extern "C" int __ulock_wait(uint32_t operation, void* addr, uint64_t value, uint32_t timeout);
/** Undocumented OSX futex-like call.
* @param operation A combination of the UL_* and ULF_* flags.
* @param[in] addr The address to wake, passed to __ulock_wait by other threads.
* @param wake_value An extra value to be interpreted based on \p operation. If `ULF_WAKE_THREAD` is provided,
* then this is the mach_port of the specific thread to wake.
* @returns 0 or a positive value (representing additional waiters) on success, or a negative value on error. If a
* negative value is returned, `errno` will be set, unless ULF_NO_ERRNO is provided, in which case the
* return value is the negated error value.
*/
extern "C" int __ulock_wake(uint32_t operation, void* addr, uint64_t wake_value);
inline void futex_wait(const std::atomic_uint32_t& val, uint32_t compare) noexcept
{
for (;;)
{
int rc = __ulock_wait(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO,
const_cast<uint32_t*>(reinterpret_cast<const uint32_t*>(std::addressof(val))), compare, 0);
if (rc >= 0)
{
// According to XNU source, the non-negative return value is the number of remaining waiters.
// See ulock_wait_cleanup in sys_ulock.c
return;
}
switch (-rc)
{
case EINTR: // According to XNU source, EINTR can be returned.
continue;
case ETIMEDOUT:
CARB_FALLTHROUGH;
case EFAULT:
CARB_FALLTHROUGH;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from __ulock_wait: %d/%s", -rc, strerror(-rc));
}
}
}
template <class Rep, class Period>
inline bool futex_wait_for(const std::atomic_uint32_t& val, uint32_t compare, std::chrono::duration<Rep, Period> duration)
{
// Relative time
int64_t usec = std::chrono::duration_cast<std::chrono::microseconds>(clampDuration(duration)).count();
if (usec <= 0)
{
return false;
}
if (usec > UINT32_MAX)
{
usec = UINT32_MAX;
}
int rc = __ulock_wait(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO,
const_cast<uint32_t*>(reinterpret_cast<const uint32_t*>(std::addressof(val))), compare, usec);
if (rc >= 0)
{
// According to XNU source, the non-negative return value is the number of remaining waiters.
// See ulock_wait_cleanup in sys_ulock.c
return true;
}
switch (-rc)
{
case EINTR: // Treat signal interrupt as a spurious wakeup
return true;
case ETIMEDOUT:
return false;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from __ulock_wait: %d/%s", -rc, strerror(-rc));
}
}
template <class Clock, class Duration>
inline bool futex_wait_until(const std::atomic_uint32_t& val,
uint32_t compare,
std::chrono::time_point<Clock, Duration> time_point)
{
// Constrain the time to something that is well before the heat death of the universe
auto now = Clock::now();
auto tp = now + clampDuration(time_point - now);
// Convert to number of microseconds from now
int64_t usec = std::chrono::duration_cast<std::chrono::microseconds>(tp - now).count();
if (usec <= 0)
{
return false;
}
if (usec > UINT32_MAX)
{
usec = UINT32_MAX;
}
int rc = __ulock_wait(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO,
const_cast<uint32_t*>(reinterpret_cast<const uint32_t*>(std::addressof(val))), compare, usec);
if (rc >= 0)
{
// According to XNU source, the non-negative return value is the number of remaining waiters.
// See ulock_wait_cleanup in sys_ulock.c
return true;
}
switch (-rc)
{
case EINTR: // Treat signal interrupt as a spurious wakeup
return true;
case ETIMEDOUT:
return false;
default:
CARB_FATAL_UNLESS(0, "Unexpected result from __ulock_wait: %d/%s", -rc, strerror(-rc));
}
}
inline void futex_wake_n(std::atomic_uint32_t& val, unsigned count) noexcept
{
for (unsigned i = 0; i < count; i++)
{
__ulock_wake(UL_COMPARE_AND_WAIT, std::addressof(val), 0);
}
}
inline void futex_wake_one(std::atomic_uint32_t& val) noexcept
{
__ulock_wake(UL_COMPARE_AND_WAIT, std::addressof(val), 0);
}
inline void futex_wake_all(std::atomic_uint32_t& val) noexcept
{
__ulock_wake(UL_COMPARE_AND_WAIT | ULF_WAKE_ALL, std::addressof(val), 0);
}
#endif
class NativeFutex
{
public:
using AtomicType = std::atomic_uint32_t;
using Type = uint32_t;
static inline void wait(const AtomicType& val, Type compare) noexcept
{
futex_wait(val, compare);
}
template <class Rep, class Period>
static inline bool wait_for(const AtomicType& val, Type compare, std::chrono::duration<Rep, Period> duration)
{
return futex_wait_for(val, compare, duration);
}
template <class Clock, class Duration>
static inline bool wait_until(const AtomicType& val, Type compare, std::chrono::time_point<Clock, Duration> time_point)
{
return futex_wait_until(val, compare, time_point);
}
static inline void notify_one(AtomicType& a) noexcept
{
futex_wake_one(a);
}
static inline void notify_n(AtomicType& a, size_t n) noexcept
{
futex_wake_n(a, n);
}
static inline void notify_all(AtomicType& a) noexcept
{
futex_wake_all(a);
}
};
#if CARB_USE_PARKINGLOT
struct ParkingLot
{
struct WaitEntry
{
const void* addr;
WaitEntry* next{ nullptr };
WaitEntry* prev{ nullptr };
uint32_t changeId{ 0 };
NativeFutex::AtomicType wakeup{ 0 };
enum Bits : uint32_t
{
kNoBits = 0,
kNotifyBit = 1,
kWaitBit = 2,
};
};
class WaitBucket
{
// In an effort to conserve size and implement appearsEmpty(), we use the least significant bit as a lock bit.
constexpr static size_t kUnlocked = 0;
constexpr static size_t kLock = 1;
union
{
std::atomic<WaitEntry*> m_head{ nullptr };
std::atomic_size_t m_lock;
// The native futex is only 32 bits, so m_lock must coincide with the LSBs of m_lock, hence we assert
// little-endian
NativeFutex::AtomicType m_futex;
static_assert(carb::cpp::endian::native == carb::cpp::endian::little, "Requires little endian");
};
WaitEntry* m_tail;
std::atomic_uint32_t m_waiters{ 0 };
std::atomic_uint32_t m_changeTracker{ 0 };
void setHead(WaitEntry* newHead) noexcept
{
assertLockState();
assertNoLockBits(newHead);
size_t val = size_t(newHead);
// Maintain bits but set to new value
// Relaxed semantics because we own the lock so shouldn't need to synchronize-with any other threads
m_lock.store(val | kLock, std::memory_order_relaxed);
}
void setHeadAndUnlock(WaitEntry* newHead) noexcept
{
assertLockState();
assertNoLockBits(newHead);
size_t val = size_t(newHead);
m_lock.store(val, std::memory_order_seq_cst);
if (m_waiters.load(std::memory_order_relaxed))
NativeFutex::notify_one(m_futex);
}
void assertLockState() const noexcept
{
// Relaxed because this should only be done within the lock
CARB_ASSERT(m_lock.load(std::memory_order_relaxed) & kLock);
}
static void assertNoLockBits(WaitEntry* e) noexcept
{
CARB_UNUSED(e);
CARB_ASSERT(!(size_t(e) & kLock));
}
void assertHead(WaitEntry* e) const noexcept
{
// Relaxed because this should only be done within the lock
CARB_UNUSED(e);
CARB_ASSERT((m_lock.load(std::memory_order_relaxed) & ~kLock) == size_t(e));
}
public:
constexpr WaitBucket() noexcept : m_head{ nullptr }, m_tail{ nullptr }
{
}
void incChangeTracker() noexcept
{
assertLockState(); // under lock
m_changeTracker.store(m_changeTracker.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed);
}
bool appearsEmpty() const noexcept
{
// fence-fence synchronization with wait functions
this_thread::atomic_fence_seq_cst();
return m_lock.load(std::memory_order_relaxed) == 0;
}
std::atomic_uint32_t& changeTracker() noexcept
{
return m_changeTracker;
}
WaitEntry* lock() noexcept
{
size_t val = m_lock.load(std::memory_order_relaxed);
for (;;)
{
if (!(val & kLock))
{
if (m_lock.compare_exchange_strong(val, val | kLock))
return reinterpret_cast<WaitEntry*>(val);
continue;
}
if (!this_thread::spinTryWait([&] { return !((val = m_lock.load(std::memory_order_relaxed)) & kLock); }))
{
++m_waiters;
while ((val = m_lock.load(std::memory_order_relaxed)) & kLock)
carb::thread::detail::NativeFutex::wait(m_futex, uint32_t(val));
--m_waiters;
}
}
}
void unlockHint(WaitEntry* head) noexcept
{
assertLockState();
assertNoLockBits(head);
assertHead(head);
m_lock.store(size_t(head), std::memory_order_seq_cst);
if (m_waiters.load(std::memory_order_relaxed))
NativeFutex::notify_one(m_futex);
}
void unlock() noexcept
{
unlockHint(reinterpret_cast<WaitEntry*>(m_lock.load(std::memory_order_relaxed) & ~kLock));
}
void appendAndUnlock(WaitEntry* e) noexcept
{
assertLockState();
assertNoLockBits(e);
e->prev = m_tail;
e->next = nullptr;
if (e->prev)
{
m_tail = e->prev->next = e;
unlock();
}
else
{
m_tail = e;
setHeadAndUnlock(e);
}
}
void remove(WaitEntry* e) noexcept
{
assertLockState();
if (e->next)
e->next->prev = e->prev;
else
{
CARB_ASSERT(m_tail == e);
m_tail = e->prev;
}
if (e->prev)
e->prev->next = e->next;
else
{
assertHead(e);
setHead(e->next);
}
}
void removeAndUnlock(WaitEntry* e) noexcept
{
assertLockState();
assertNoLockBits(e);
if (e->next)
e->next->prev = e->prev;
else
{
CARB_ASSERT(m_tail == e);
m_tail = e->prev;
}
if (e->prev)
{
e->prev->next = e->next;
unlock();
}
else
{
assertHead(e);
setHeadAndUnlock(e->next);
}
}
constexpr static size_t kNumWaitBuckets = 2048; // Must be a power of two
static_assert(carb::cpp::has_single_bit(kNumWaitBuckets), "Invalid assumption");
static inline WaitBucket& bucket(const void* addr) noexcept
{
static WaitBucket waitBuckets[kNumWaitBuckets];
# if 1
// FNV-1a hash is fast with really good distribution
// In "futex buckets" test, about ~70% on Windows and ~80% on Linux
auto hash = carb::hashBuffer(&addr, sizeof(addr));
return waitBuckets[hash & (kNumWaitBuckets - 1)];
# else
// Simple bitshift method
// In "futex buckets" test:
// >> 4 bits: ~71% on Windows, ~72% on Linux
// >> 5 bits: ~42% on Windows, ~71% on Linux
return waitBuckets[(size_t(addr) >> 4) & (kNumWaitBuckets - 1)];
# endif
}
};
template <typename T>
static void wait(const std::atomic<T>& val, T compare) noexcept
{
WaitEntry entry{ std::addressof(val) };
using I = to_integral_t<T>;
// Check before waiting
if (reinterpret_as<I>(val.load(std::memory_order_acquire)) != reinterpret_as<I>(compare))
{
return;
}
WaitBucket& b = WaitBucket::bucket(std::addressof(val));
auto hint = b.lock();
// Check inside the lock to reduce spurious wakeups
if (CARB_UNLIKELY(reinterpret_as<I>(val.load(std::memory_order_acquire)) != reinterpret_as<I>(compare)))
{
b.unlockHint(hint);
return;
}
entry.changeId = b.changeTracker().load(std::memory_order_relaxed);
b.appendAndUnlock(&entry);
// fence-fence synchronization with appearsEmpty()
this_thread::atomic_fence_seq_cst();
// Do the wait if everything is consistent
if (CARB_LIKELY(reinterpret_as<I>(val.load(std::memory_order_relaxed)) == reinterpret_as<I>(compare) &&
b.changeTracker().load(std::memory_order_relaxed) == entry.changeId))
{
NativeFutex::wait(entry.wakeup, uint32_t(WaitEntry::kNoBits));
}
// Speculatively see if we've been removed
uint32_t v = entry.wakeup.load(std::memory_order_acquire);
if (CARB_UNLIKELY(!v))
{
// Need to remove
hint = b.lock();
// Check again under the lock (relaxed because we're under the lock)
v = entry.wakeup.load(std::memory_order_relaxed);
if (!v)
{
b.removeAndUnlock(&entry);
return;
}
else
{
// Already removed
b.unlockHint(hint);
}
}
// Spin briefly while the wait bit is set, though this should be rare
this_thread::spinWait([&] { return !(entry.wakeup.load(std::memory_order_acquire) & WaitEntry::kWaitBit); });
}
template <typename T, typename Rep, typename Period>
static bool wait_for(const std::atomic<T>& val, T compare, std::chrono::duration<Rep, Period> duration)
{
WaitEntry entry{ std::addressof(val) };
using I = to_integral_t<T>;
// Check before waiting
if (reinterpret_as<I>(val.load(std::memory_order_acquire)) != reinterpret_as<I>(compare))
{
return true;
}
WaitBucket& b = WaitBucket::bucket(std::addressof(val));
auto hint = b.lock();
// Check inside the lock to reduce spurious wakeups
if (CARB_UNLIKELY(reinterpret_as<I>(val.load(std::memory_order_acquire)) != reinterpret_as<I>(compare)))
{
b.unlockHint(hint);
return true;
}
entry.changeId = b.changeTracker().load(std::memory_order_relaxed);
b.appendAndUnlock(&entry);
// fence-fence synchronization with appearsEmpty()
this_thread::atomic_fence_seq_cst();
// Do the wait if everything is consistent
bool finished = true;
if (CARB_LIKELY(reinterpret_as<I>(val.load(std::memory_order_relaxed)) == reinterpret_as<I>(compare) &&
b.changeTracker().load(std::memory_order_relaxed) == entry.changeId))
{
finished = NativeFutex::wait_for(entry.wakeup, uint32_t(WaitEntry::kNoBits), duration);
}
// Speculatively see if we've been removed
uint32_t v = entry.wakeup.load(std::memory_order_acquire);
if (CARB_UNLIKELY(!v))
{
// Need to remove
hint = b.lock();
// Check again under the lock (relaxed because we're under the lock)
v = entry.wakeup.load(std::memory_order_relaxed);
if (!v)
{
b.removeAndUnlock(&entry);
return finished;
}
else
{
// Already removed
b.unlockHint(hint);
finished = true;
}
}
// Spin briefly while the wait bit is set, though this should be rare
this_thread::spinWait([&] { return !(entry.wakeup.load(std::memory_order_acquire) & WaitEntry::kWaitBit); });
return finished;
}
template <typename T, typename Clock, typename Duration>
static bool wait_until(const std::atomic<T>& val, T compare, std::chrono::time_point<Clock, Duration> time_point)
{
WaitEntry entry{ std::addressof(val) };
using I = to_integral_t<T>;
// Check before waiting
if (reinterpret_as<I>(val.load(std::memory_order_acquire)) != reinterpret_as<I>(compare))
{
return true;
}
WaitBucket& b = WaitBucket::bucket(std::addressof(val));
auto hint = b.lock();
// Check inside the lock to reduce spurious wakeups
if (CARB_UNLIKELY(reinterpret_as<I>(val.load(std::memory_order_acquire)) != reinterpret_as<I>(compare)))
{
b.unlockHint(hint);
return true;
}
entry.changeId = b.changeTracker().load(std::memory_order_relaxed);
b.appendAndUnlock(&entry);
// fence-fence synchronization with appearsEmpty()
this_thread::atomic_fence_seq_cst();
// Do the wait if everything is consistent
bool finished = true;
if (CARB_LIKELY(reinterpret_as<I>(val.load(std::memory_order_relaxed)) == reinterpret_as<I>(compare) &&
b.changeTracker().load(std::memory_order_relaxed) == entry.changeId))
{
finished = NativeFutex::wait_until(entry.wakeup, uint32_t(WaitEntry::kNoBits), time_point);
}
// Speculatively see if we've been removed
uint32_t v = entry.wakeup.load(std::memory_order_acquire);
if (CARB_UNLIKELY(!v))
{
// Need to remove
hint = b.lock();
// Check again under the lock (relaxed because we're under the lock)
v = entry.wakeup.load(std::memory_order_relaxed);
if (!v)
{
b.removeAndUnlock(&entry);
return finished;
}
else
{
// Already removed
b.unlockHint(hint);
finished = true;
}
}
// Spin briefly while the wait bit is set, though this should be rare
this_thread::spinWait([&] { return !(entry.wakeup.load(std::memory_order_acquire) & WaitEntry::kWaitBit); });
return finished;
}
static void notify_one(void* addr) noexcept
{
WaitBucket& b = WaitBucket::bucket(addr);
// Read empty state with full fence to avoid locking
if (b.appearsEmpty())
return;
WaitEntry* head = b.lock();
b.incChangeTracker();
for (WaitEntry* e = head; e; e = e->next)
{
if (e->addr == addr)
{
// Remove before setting the wakeup flag
b.remove(e);
// Even though we're under the lock, we need release semantics to synchronize-with the wait not under
// the lock.
e->wakeup.store(WaitEntry::kNotifyBit, std::memory_order_release);
b.unlock();
// Wake the waiter
NativeFutex::notify_one(e->wakeup);
return;
}
}
b.unlockHint(head);
}
constexpr static size_t kWakeCacheSize = 128;
private:
static CARB_NOINLINE void notify_n_slow(
void* addr, size_t n, WaitBucket& b, WaitEntry* e, std::atomic_uint32_t** wakeCache) noexcept
{
// We are waking a lot of things and the wakeCache is completely full. Now we need to start building a list
WaitEntry *wake = nullptr, *end = nullptr;
for (WaitEntry* next; e; e = next)
{
next = e->next;
if (e->addr == addr)
{
b.remove(e);
e->next = nullptr;
// Don't bother with prev pointers
if (end)
end->next = e;
else
wake = e;
end = e;
// Even though we're under the lock we use release semantics here to synchronize-with the waking thread
// possibly outside the lock.
// Need to set the wait bit since we're still reading/writing to the WaitEntry
e->wakeup.store(WaitEntry::kWaitBit | WaitEntry::kNotifyBit, std::memory_order_release);
if (!--n)
break;
}
}
b.unlock();
// Wake the entire cache since we know it's full
auto wakeCacheEnd = (wakeCache + kWakeCacheSize);
do
{
NativeFutex::notify_one(**(wakeCache++));
} while (wakeCache != wakeCacheEnd);
for (WaitEntry* next; wake; wake = next)
{
next = wake->next;
// Clear the wait bit so that only the wake bit is set
wake->wakeup.store(WaitEntry::kNotifyBit, std::memory_order_release);
NativeFutex::notify_one(wake->wakeup);
}
}
static CARB_NOINLINE void notify_all_slow(void* addr, WaitBucket& b, WaitEntry* e, std::atomic_uint32_t** wakeCache) noexcept
{
// We are waking a lot of things and the wakeCache is completely full. Now we need to start building a list
WaitEntry *wake = nullptr, *end = nullptr;
for (WaitEntry* next; e; e = next)
{
next = e->next;
if (e->addr == addr)
{
b.remove(e);
e->next = nullptr;
// Don't bother with prev pointers
if (end)
end->next = e;
else
wake = e;
end = e;
// Even though we're under the lock we use release semantics here to synchronize-with the waking thread
// possibly outside the lock.
// Need to set the wait bit since we're still reading/writing to the WaitEntry
e->wakeup.store(WaitEntry::kWaitBit | WaitEntry::kNotifyBit, std::memory_order_release);
}
}
b.unlock();
// Wake the entire cache since we know it's full
auto wakeCacheEnd = (wakeCache + kWakeCacheSize);
do
{
NativeFutex::notify_one(**(wakeCache++));
} while (wakeCache != wakeCacheEnd);
for (WaitEntry* next; wake; wake = next)
{
next = wake->next;
// Clear the wait bit so that only the wake bit is set
wake->wakeup.store(WaitEntry::kNotifyBit, std::memory_order_release);
NativeFutex::notify_one(wake->wakeup);
}
}
public:
static void notify_n(void* addr, size_t n) noexcept
{
if (CARB_UNLIKELY(n == 0))
{
return;
}
// It is much faster overall to not set kWaitBit and force the woken threads to wait until we're clear of their
// WaitEntry, so keep a local cache of addresses to wake here that don't require a WaitEntry.
// Note that we do retain a pointer to the std::atomic_uint32_t *contained in* the WaitEntry and tell the
// underlying OS system to wake by that address, but this is safe as it does not read that memory. The address
// is used as a lookup to find any waiters that registered with that address. If the memory was quickly reused
// for a different wait operation, this will cause a spurious wakeup which is allowed, but this should be
// exceedingly rare.
size_t wakeCount = 0;
std::atomic_uint32_t* wakeCache[kWakeCacheSize];
WaitBucket& b = WaitBucket::bucket(addr);
// Read empty state with full fence to avoid locking
if (b.appearsEmpty())
return;
WaitEntry* e = b.lock();
b.incChangeTracker();
for (WaitEntry* next; e; e = next)
{
next = e->next;
if (e->addr == addr)
{
b.remove(e);
// Even though we're under the lock we use release semantics here to synchronize-with the waking thread
// possibly outside the lock.
wakeCache[wakeCount++] = &e->wakeup;
e->wakeup.store(WaitEntry::kNotifyBit, std::memory_order_release);
if (!--n)
break;
if (CARB_UNLIKELY(wakeCount == kWakeCacheSize))
{
// Cache is full => transition to a list for the rest
notify_n_slow(addr, n, b, next, wakeCache);
return;
}
}
}
b.unlock();
auto start = wakeCache;
auto const end = wakeCache + wakeCount;
while (start != end)
NativeFutex::notify_one(**(start++));
}
static void notify_all(void* addr) noexcept
{
// It is much faster overall to not set kWaitBit and force the woken threads to wait until we're clear of their
// WaitEntry, so keep a local cache of addresses to wake here that don't require a WaitEntry.
// Note that we do retain a pointer to the std::atomic_uint32_t *contained in* the WaitEntry and tell the
// underlying OS system to wake by that address, but this is safe as it does not read that memory. The address
// is used as a lookup to find any waiters that registered with that address. If the memory was quickly reused
// for a different wait operation, this will cause a spurious wakeup which is allowed, but this should be
// exceedingly rare.
size_t wakeCount = 0;
std::atomic_uint32_t* wakeCache[kWakeCacheSize];
WaitBucket& b = WaitBucket::bucket(addr);
// Read empty state with full fence to avoid locking
if (b.appearsEmpty())
return;
WaitEntry* e = b.lock();
b.incChangeTracker();
for (WaitEntry* next; e; e = next)
{
next = e->next;
if (e->addr == addr)
{
b.remove(e);
// Even though we're under the lock we use release semantics here to synchronize-with the waking thread
// possibly outside the lock.
wakeCache[wakeCount++] = &e->wakeup;
e->wakeup.store(WaitEntry::kNotifyBit, std::memory_order_release);
if (CARB_UNLIKELY(wakeCount == kWakeCacheSize))
{
// Full => transition to a list for the rest of the items
notify_all_slow(addr, b, next, wakeCache);
return;
}
}
}
b.unlock();
auto start = wakeCache;
const auto end = wakeCache + wakeCount;
while (start != end)
NativeFutex::notify_one(**(start++));
}
}; // struct ParkingLot
// Futex types that must use the ParkingLot
template <class T, size_t S = sizeof(T)>
class Futex
{
static_assert(S == 1 || S == 2 || S == 4 || S == 8, "Unsupported size");
public:
using AtomicType = typename std::atomic<T>;
using Type = T;
static void wait(const AtomicType& val, T compare) noexcept
{
ParkingLot::wait(val, compare);
}
template <class Rep, class Period>
static bool wait_for(const AtomicType& val, T compare, std::chrono::duration<Rep, Period> duration)
{
return ParkingLot::wait_for(val, compare, duration);
}
template <class Clock, class Duration>
static bool wait_until(const AtomicType& val, T compare, std::chrono::time_point<Clock, Duration> time_point)
{
return ParkingLot::wait_until(val, compare, time_point);
}
static void notify_one(AtomicType& val) noexcept
{
ParkingLot::notify_one(std::addressof(val));
}
static void notify_n(AtomicType& val, size_t count) noexcept
{
ParkingLot::notify_n(std::addressof(val), count);
}
static void notify_all(AtomicType& val) noexcept
{
ParkingLot::notify_all(std::addressof(val));
}
};
#endif
} // namespace detail
} // namespace thread
} // namespace carb
|
omniverse-code/kit/include/carb/thread/Futex.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite Futex implementation.
#pragma once
#include "FutexImpl.h"
#include <atomic>
namespace carb
{
namespace thread
{
/**
* Futex namespace.
*
* @warning Futex is a very low-level system; generally its use should be avoided. There are plenty of higher level
* synchronization primitives built on top of Futex that should be used instead, such as `carb::cpp::atomic`.
*
* FUTEX stands for Fast Userspace muTEX. Put simply, it's a way of efficiently blocking threads by waiting on an
* address as long as the value at that address matches the expected value. Atomically the value at the address is
* checked and if it matches the expected value, the thread enters a wait-state (until notified). If the value does not
* match expectation, the thread does not enter a wait-state. This low-level system is the foundation for many
* synchronization primitives.
*
* On Windows, this functionality is achieved through APIs `WaitOnAddress`, `WakeByAddressSingle` and
* `WakeByAddressAll` and support values of 1, 2, 4 or 8 bytes. Much of the functionality is implemented without
* requiring system calls, so attempting to wait when the value is different, or notifying without any waiting threads
* are very efficient--only a few nanoseconds each. Calls which wait or notify waiting threads will enter the kernel and
* be on the order of microseconds.
*
* The Linux kernel provides a `futex` syscall for this functionality, with two downsides. First, a `futex` can be only
* four bytes (32-bit), and second due to being a syscall even calls with no work can take nearly a microsecond. macOS
* has a similar feature in the undocumented `__ulock_wait` and `__ulock_wake` calls.
*
* For Linux and macOS, the Carbonite futex system has a user-space layer called `ParkingLot` that supports values of 1,
* 2, 4 or 8 bytes and eliminates most syscalls unless work must actually be done. This causes no-op work to be on the
* order of just a few nanoseconds with worst-case timing being comparable to syscall times.
*
* Linux information: http://man7.org/linux/man-pages/man2/futex.2.html
*
* Windows information: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitonaddress
*/
struct futex
{
/**
* Waits on a value until woken.
*
* The value at @p val is atomically compared with @p compare. If the values are not equal, this function returns
* immediately. Otherwise, if the values are equal, this function sleeps the current thread. Waking is not automatic
* when the value changes. The thread that changes the value must then call wake() to wake the waiting threads.
*
* @note Futexes are prone to spurious wakeups. It is the responsibility of the caller to determine whether a return
* from wait() is spurious or valid.
*
* @param val The value that is read atomically. If this matches @p compare, the thread sleeps.
* @param compare The expected value.
*/
template <class T>
inline static void wait(const std::atomic<T>& val, T compare) noexcept
{
detail::Futex<T>::wait(val, compare);
}
/**
* Waits on a value until woken or timed out.
*
* The value at @p val is atomically compared with @p compare. If the values are not equal, this function returns
* immediately. Otherwise, if the values are equal, this function sleeps the current thread. Waking is not automatic
* when the value changes. The thread that changes the value must then call wake() to wake the waiting threads.
*
* @note Futexes are prone to spurious wakeups. It is the responsibility of the caller to determine whether a return
* from wait() is spurious or valid.
*
* @note On Linux, interruptions by signals are treated as spurious wakeups.
*
* @param val The value that is read atomically. If this matches @p compare, the thread sleeps.
* @param compare The expected value.
* @param duration The relative time to wait.
* @return `true` if woken legitimately or spuriously; `false` if timed out.
*/
template <class T, class Rep, class Period>
inline static bool wait_for(const std::atomic<T>& val, T compare, std::chrono::duration<Rep, Period> duration)
{
return detail::Futex<T>::wait_for(val, compare, duration);
}
/**
* Waits on a value until woken or timed out.
*
* The value at @p val is atomically compared with @p compare. If the values are not equal, this function returns
* immediately. Otherwise, if the values are equal, this function sleeps the current thread. Waking is not automatic
* when the value changes. The thread that changes the value must then call wake() to wake the waiting threads.
*
* @note Futexes are prone to spurious wakeups. It is the responsibility of the caller to determine whether a return
* from wait() is spurious or valid.
*
* @param val The value that is read atomically. If this matches @p compare, the thread sleeps.
* @param compare The expected value.
* @param time_point The absolute time point to wait until.
* @return `true` if woken legitimately or spuriously; `false` if timed out.
*/
template <class T, class Clock, class Duration>
inline static bool wait_until(const std::atomic<T>& val, T compare, std::chrono::time_point<Clock, Duration> time_point)
{
return detail::Futex<T>::wait_until(val, compare, time_point);
}
/**
* Wakes threads that are waiting in one of the @p futex wait functions.
*
* @note To wake all threads waiting on @p val, use wake_all().
*
* @param val The same value that was passed to wait(), wait_for() or wait_until().
* @param count The number of threads to wake. To wake all threads, use wake_all().
* @param maxCount An optimization for Windows that specifies the total number of threads that are waiting on @p
* addr. If @p count is greater-than-or-equal-to @p maxCount then a specific API call that wakes all threads is
* used. Ignored on Linux.
*/
template <class T>
inline static void notify(std::atomic<T>& val, unsigned count, unsigned maxCount = unsigned(INT_MAX)) noexcept
{
if (count != 1 && count >= maxCount)
detail::Futex<T>::notify_all(val);
else
detail::Futex<T>::notify_n(val, count);
}
//! @copydoc notify()
template <class T>
CARB_DEPRECATED("use notify() instead")
inline static void wake(std::atomic<T>& val, unsigned count, unsigned maxCount = unsigned(INT_MAX)) noexcept
{
notify(val, count, maxCount);
}
/**
* Wakes one thread that is waiting in one of the @p futex wait functions.
*
* @param val The same value that was passed to wait(), wait_for() or wait_until().
*/
template <class T>
inline static void notify_one(std::atomic<T>& val) noexcept
{
detail::Futex<T>::notify_one(val);
}
//! @copydoc notify_one()
template <class T>
CARB_DEPRECATED("use notify_one() instead")
inline static void wake_one(std::atomic<T>& val) noexcept
{
notify_one(val);
}
/**
* Wakes all threads that are waiting in one of the @p futex wait functions
*
* @param val The same value that was passed to wait(), wait_for() or wait_until().
*/
template <class T>
inline static void notify_all(std::atomic<T>& val) noexcept
{
detail::Futex<T>::notify_all(val);
}
//! @copydoc notify_all()
template <class T>
CARB_DEPRECATED("Use notify_all() instead")
inline static void wake_all(std::atomic<T>& val) noexcept
{
notify_all(val);
}
}; // struct futex
} // namespace thread
} // namespace carb
|
omniverse-code/kit/include/carb/thread/IThreadUtil.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides an interface that handles various threading utility operations.
*/
#pragma once
#include "../Interface.h"
/** Namespace for all low level Carbonite functionality. */
namespace carb
{
/** Namespace for all threading operations. */
namespace thread
{
/** Base type for flags to the task relay system. These are the fRelayFlag* flags defined below.
* These are to be passed to the framework's runRelayTask() function through its descriptor.
*/
using RelayFlags = uint64_t;
/** Flag to indicate that a relay task should block until the task completes. When not used,
* the default behavior is to run the task as a fire-and-forget operation. In this case, the
* task descriptor will be shallow copied. It is the task's responsibility to clean up any
* resources used in the descriptor's @a context value before returning. When this flag is
* used, the runRelayTask() call will block until the task completes. In this case, either
* the task function itself or the caller can handle any resource clean up.
*
* Note that using this flag will effectively cause the task queue to be flushed. Any pending
* non-blocking calls will be completed before the new task is run.
*/
constexpr RelayFlags fRelayFlagBlocking = 0x8000000000000000ull;
/** Force the execution of the task even if a failure related to relaying the task occurs.
* This will effectively cause the task to run in the context of the thread that originally
* called Framework::runRelayTask() (and therefore imply the @ref fRelayFlagBlocking flag).
*/
constexpr RelayFlags fRelayFlagForce = 0x4000000000000000ull;
/** Flags available for use in the relay task itself. These flags will be passed to the relay
* function unmodified. The set bits in this mask may be used for any task-specific purpose.
* If any of the cleared bits in this mask are set in the task's flags (aside from the above
* defined flags), the runRelayTask() call will fail.
*/
constexpr RelayFlags fRelayAvailableFlagsMask = 0x0000ffffffffffffull;
/** Prototype for a relayed task function.
*
* @param[in] flags The flags controlling the behavior of this relay task. This may
* include either @ref fRelayFlagBlocking or any of the set bits in
* @ref fRelayAvailableFlagsMask. The bits in the mask may be used
* for any purpose specific to the task function.
* @param[inout] context An opaque value specific to this task. This will be passed unmodified
* to the task function from the task's descriptor when it is executed.
* If the task function needs to return a value, it may be done through
* this object.
* @returns No return value.
*
* @remarks The prototype for a task function to be executed on the relayed task thread. This
* function is expected to complete its task and return in a timely fashion. This
* should never block or perform a task that has the possibility of blocking for an
* extended period of time.
*
* @note Neither this function nor anything it calls may throw an exception unless the task
* function itself catches and handles that exception. Throwing an exception that goes
* uncaught by the task function will result in the process being terminated.
*/
using RelayTaskFn = void(CARB_ABI*)(RelayFlags flags, void* context);
/** A descriptor of the relay task to be performed. This provides the task function itself,
* the context value and flags to pass to it, and space to store the result for blocking
* task calls.
*
* For non-blocking tasks, this descriptor will be shallow copied and queued for
* execution. The caller must guarantee that any pointer parameters passed to the
* task function will remain valid until the task itself finishes execution. In this
* case the task function itself is also responsible for cleaning up any resources that
* are passed to the task function through its context object. As a result of this
* requirement, none of the values passed to the task should be allocated on the stack.
*
* For blocking calls, the task will be guaranteed to be completed by the time
* runRelayTask() returns. In this case, the result of the operation (if any) will be
* available in the task descriptor. Any of the task's objects may be allocated on the
* stack if needed since it is guaranteed to block until the task completes. Either the
* task or the caller may clean up any resources in this case.
*/
struct RelayTaskDesc
{
/** The task function to be executed. The task function itself is responsible for managing
* any thread safe access to any passed in values.
*/
RelayTaskFn task;
/** Flags that control the behavior of this task. This may be a combination of zero or
* more of the @ref RelayFlags flags and zero or more task-specific flags.
*/
RelayFlags flags;
/** An opaque context value to be passed to the task function when it executes. This will
* not be accessed or modified in any way before being passed to the task function. The
* task function itself is responsible for knowing how to properly interpret this value.
*/
void* context;
};
/** Possible result codes for Framework::runRelayTask(). */
enum class RelayResult
{
/** The task was executed successfully. */
eSuccess,
/** A bad flag bit was used by the caller. */
eBadParam,
/** The task thread failed to launch. */
eThreadFailure,
/** The relay system has been shutdown on process exit and will not accept any new tasks. */
eShutdown,
/** The task was successfully run, but had to be forced to run on the calling thread due to
* the relayed task thread failing to launch.
*/
eForced,
/** Failed to allocate memory for a non-blocking task. */
eNoMemory,
};
/** An interface to provide various thread utility operations. Currently the only defined
* operation is to run a task in a single common thread regardless of the thread that requests
* the operation.
*/
struct IThreadUtil
{
CARB_PLUGIN_INTERFACE("carb::thread::IThreadUtil", 1, 0)
/** Relays a task to run on an internal worker thread.
*
* @param[inout] desc The descriptor of the task to be run. This task includes a function
* to execute and a context value to pass to that function. This
* descriptor must remain valid for the entire lifetime of the execution
* of the task function. If the @ref fRelayFlagBlocking flag is used,
* this call will block until the task completes. In this case, the
* caller will be responsible for cleaning up any resources used or
* returned by the task function. If the flag is not used, the task
* function itself will be responsible for cleaning up any resources
* before it returns.
* @retval RelayResult::eSuccess if executing the task is successful.
* @returns An error code describing how the task relay failed.
*
* @remarks This relays a task to run on an internal worker thread. This worker thread will
* be guaranteed to continue running (in an efficient sleep state when not running
* a task) for the entire remaining lifetime of the process. The thread will be
* terminated during shutdown of the process.
*
* @remarks The intention of this function is to be able to run generic tasks on a worker
* thread that is guaranteed to live throughout the process's lifetime. Other
* similar systems in other plugins have the possibility of being unloaded before
* the end of the process which would lead to the task worker thread(s) being
* stopped early. Certain tasks such may require the instantiating thread to
* survive longer than the lifetime of a dynamic plugin.
*
* @remarks A task function may queue another task when it executes. However, the behavior
* may differ depending on whether the newly queued task is flagged as being
* blocking or non-blocking. A recursive blocking task will be executed immediately
* in the context of the task thread, but will interrupt any other pending tasks
* that were queued ahead of it. A recursive non-blocking task will always maintain
* queuing order however. Note that recursive tasks may require extra care to
* wait for or halt upon module shutdown or unload. In these cases, it is still
* the caller's responsibility to ensure all tasks queued by a module are safely
* and properly stopped before that module is unloaded.
*
* @note This should only be used in situations where it is absolutely necessary. In
* cases where performance or more flexibility are needed, other interfaces such as
* ITasking should be used instead.
*
* @note If a caller in another module queues a non-blocking task, it is that caller's
* responsibility to ensure that task has completed before its module is unloaded.
* This can be accomplished by queuing a do-nothing blocking task.
*/
RelayResult(CARB_ABI* runRelayTask)(RelayTaskDesc& desc);
};
} // namespace thread
} // namespace carb
|
omniverse-code/kit/include/carb/thread/ThreadLocal.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite dynamic thread-local storage implementation.
#pragma once
#include "../Defines.h"
#include <atomic>
#include <type_traits>
#if CARB_POSIX
# include <pthread.h>
#elif CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
# include "SharedMutex.h"
# include <map>
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
namespace carb
{
namespace thread
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
using TlsDestructor = void (*)(void*);
inline std::mutex& tlsMutex()
{
static std::mutex m;
return m;
}
# if CARB_POSIX
class ThreadLocalBase
{
pthread_key_t m_key;
public:
ThreadLocalBase(TlsDestructor destructor)
{
int res = pthread_key_create(&m_key, destructor);
CARB_FATAL_UNLESS(res == 0, "pthread_key_create failed: %d/%s", res, strerror(res));
}
~ThreadLocalBase()
{
pthread_key_delete(m_key);
}
// Not copyable or movable
CARB_PREVENT_COPY_AND_MOVE(ThreadLocalBase);
void* get() const
{
return pthread_getspecific(m_key);
}
void set(void* val) const
{
int res = pthread_setspecific(m_key, val);
CARB_CHECK(res == 0, "pthread_setspecific failed with %d/%s for key %u", res, strerror(res), m_key);
}
};
# elif CARB_PLATFORM_WINDOWS
__declspec(selectany) CARBWIN_SRWLOCK mutex = CARBWIN_SRWLOCK_INIT;
__declspec(selectany) bool destructed = false;
class CARB_VIZ ThreadLocalBase
{
CARB_VIZ DWORD m_key;
class Destructors
{
using DestructorMap = std::map<DWORD, TlsDestructor>;
DestructorMap m_map;
public:
Destructors() = default;
~Destructors()
{
AcquireSRWLockExclusive((PSRWLOCK)&mutex);
destructed = true;
// Destroy the map under the lock
DestructorMap{}.swap(m_map);
ReleaseSRWLockExclusive((PSRWLOCK)&mutex);
}
void add(DWORD slot, TlsDestructor fn)
{
// If there's no destructor, don't do anything
if (!fn)
return;
AcquireSRWLockExclusive((PSRWLOCK)&mutex);
m_map[slot] = fn;
ReleaseSRWLockExclusive((PSRWLOCK)&mutex);
}
void remove(DWORD slot)
{
AcquireSRWLockExclusive((PSRWLOCK)&mutex);
m_map.erase(slot);
ReleaseSRWLockExclusive((PSRWLOCK)&mutex);
}
void call()
{
AcquireSRWLockShared((PSRWLOCK)&mutex);
// It is possible for atexit destructors to run before other threads call destructors with thread-storage
// duration.
if (destructed)
{
ReleaseSRWLockShared((PSRWLOCK)&mutex);
return;
}
// This mimics the process of destructors with pthread_key_create which will iterate multiple (up to
// PTHREAD_DESTRUCTOR_ITERATIONS) times, which is typically 4.
bool again;
int iters = 0;
const int kMaxIters = 4;
do
{
again = false;
for (auto& pair : m_map)
{
if (void* val = ::TlsGetValue(pair.first))
{
// Set to nullptr and call destructor
::TlsSetValue(pair.first, nullptr);
pair.second(val);
again = true;
}
}
} while (again && ++iters < kMaxIters);
ReleaseSRWLockShared((PSRWLOCK)&mutex);
}
};
static Destructors& destructors()
{
static Destructors d;
return d;
}
public:
ThreadLocalBase(TlsDestructor destructor)
{
m_key = ::TlsAlloc();
CARB_FATAL_UNLESS(m_key != CARBWIN_TLS_OUT_OF_INDEXES, "TlsAlloc() failed: %" PRIu32 "", ::GetLastError());
destructors().add(m_key, destructor);
}
~ThreadLocalBase()
{
destructors().remove(m_key);
BOOL b = ::TlsFree(m_key);
CARB_CHECK(!!b);
}
// Not copyable or movable
CARB_PREVENT_COPY_AND_MOVE(ThreadLocalBase);
void* get() const
{
return ::TlsGetValue(m_key);
}
void set(void* val) const
{
BOOL b = ::TlsSetValue(m_key, val);
CARB_CHECK(!!b);
}
static void callDestructors(HINSTANCE, DWORD fdwReason, PVOID)
{
if (fdwReason == CARBWIN_DLL_THREAD_DETACH)
{
// Call for current thread
destructors().call();
}
}
};
extern "C"
{
// Hook the TLS destructors in the CRT
// see crt/src/vcruntime/tlsdtor.cpp
using TlsHookFunc = void(__stdcall*)(HINSTANCE, DWORD, PVOID);
// Reference these so that the linker knows to include them
extern DWORD _tls_used;
extern TlsHookFunc __xl_a[], __xl_z[];
# pragma comment(linker, "/include:pthread_thread_callback")
# pragma section(".CRT$XLD", long, read)
// Since this is a header file, the __declspec(selectany) enables weak linking so that the linker will throw away
// all the duplicates and leave only one instance of pthread_thread_callback in the binary.
// This is placed into the specific binary section used for TLS destructors
__declspec(allocate(".CRT$XLD")) __declspec(selectany)
TlsHookFunc pthread_thread_callback = carb::thread::detail::ThreadLocalBase::callDestructors;
}
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
} // namespace detail
#endif
/**
* Base template. See specializations for documentation.
*/
template <class T,
bool Trivial = std::is_trivial<T>::value&& std::is_trivially_destructible<T>::value && (sizeof(T) <= sizeof(void*))>
class ThreadLocal
{
};
// Specializations
// Trivial and can fit within a pointer
/**
* A class for declaring a dynamic thread-local variable (Trivial/Pointer/POD specialization).
*
* This is necessary since C++11 the `thread_local` storage class specifier can only be used at namespace scope. There
* is no way to declare a `thread_local` variable at class scope unless it is static. ThreadLocal is dynamic.
*
* @note Most systems have a limit to the number of thread-local variables available. Each instance of ThreadLocal will
* consume some of that storage. Therefore, if a class contains a non-static ThreadLocal member, each instance of that
* class will consume another slot. Use sparingly.
*
* There are two specializations for ThreadLocal: a trivial version and a non-trivial version. The trivial version is
* designed for types like plain-old-data that are pointer-sized or less. The non-trivial version supports classes and
* large types. The heap is used for non-trivial ThreadLocal types, however these are lazy-initialize, so the per-thread
* memory is only allocated when used for the first time. The type is automatically destructed (and the memory returned
* to the heap) when a thread exits.
*
* On Windows, this class is implemented using [Thread Local Storage
* APIs](https://docs.microsoft.com/en-us/windows/win32/procthread/thread-local-storage). On Linux, this class is
* implemented using [pthread_key_t](https://linux.die.net/man/3/pthread_key_create).
*/
template <class T>
class ThreadLocal<T, true> : private detail::ThreadLocalBase
{
struct Union
{
union
{
T t;
void* p;
};
Union(void* p_) : p(p_)
{
}
Union(std::nullptr_t, T t_) : t(t_)
{
}
};
public:
/**
* Constructor. Allocates a thread-local storage slot from the operating system.
*/
ThreadLocal() : ThreadLocalBase(nullptr)
{
}
/**
* Destructor. Returns the previously allocated thread-local storage slot to the operating system.
*/
~ThreadLocal() = default;
/**
* Returns the specific value of this ThreadLocal variable for this thread.
*
* @note If the calling thread has not yet set() a value for this thread-local storage, the value returned will be
* default-initialized. For POD types this will be initialized to zeros.
*
* @returns A value previously set for the calling thread by set(), or a zero-initialized value if set() has not
* been called by the calling thread.
*/
T get() const
{
Union u(ThreadLocalBase::get());
return u.t;
}
/**
* Sets the specific value of this ThreadLocal variable for this thread.
* @param t The specific value to set for this thread.
*/
void set(T t)
{
Union u(nullptr, t);
ThreadLocalBase::set(u.p);
}
/**
* Alias for get().
* @returns The value as if by get().
*/
operator T()
{
return get();
}
/**
* Alias for get().
* @returns The value as if by get().
*/
operator T() const
{
return get();
}
/**
* Assignment operator and alias for set().
* @returns `*this`
*/
ThreadLocal& operator=(T t)
{
set(t);
return *this;
}
/**
* For types where `T` is a pointer, allows dereferencing the thread-local value.
* @returns The value as if by get().
*/
T operator->() const
{
static_assert(std::is_pointer<T>::value, "Requires pointer type");
return get();
}
/**
* For types where `T` is a pointer, allows dereferencing the thread-local value.
* @returns The value as if by set().
*/
auto operator*() const
{
static_assert(std::is_pointer<T>::value, "Requires pointer type");
return *get();
}
/**
* Tests the thread-local value for equality with @p rhs.
*
* @param rhs The parameter to compare against.
* @returns `true` if the value stored for the calling thread (as if by get()) matches @p rhs; `false` otherwise.
*/
bool operator==(const T& rhs) const
{
return get() == rhs;
}
/**
* Tests the thread-local value for inequality with @p rhs.
*
* @param rhs The compare to compare against.
* @returns `true` if the value stored for the calling thread (as if by get()) does not match @p rhs; `false`
* otherwise.
*/
bool operator!=(const T& rhs) const
{
return get() != rhs;
}
};
// Non-trivial or needs more than a pointer (uses the heap)
/**
* A class for declaring a dynamic thread-local variable (Large/Non-trivial specialization).
*
* This is necessary since C++11 the `thread_local` storage class specifier can only be used at namespace scope. There
* is no way to declare a `thread_local` variable at class scope unless it is static. ThreadLocal is dynamic.
*
* @note Most systems have a limit to the number of thread-local variables available. Each instance of ThreadLocal will
* consume some of that storage. Therefore, if a class contains a non-static ThreadLocal member, each instance of that
* class will consume another slot. Use sparingly.
*
* There are two specializations for ThreadLocal: a trivial version and a non-trivial version. The trivial version is
* designed for types like plain-old-data that are pointer-sized or less. The non-trivial version supports classes and
* large types. The heap is used for non-trivial ThreadLocal types, however these are lazy-initialize, so the per-thread
* memory is only allocated when used for the first time. The type is automatically destructed (and the memory returned
* to the heap) when a thread exits.
*
* On Windows, this class is implemented using [Thread Local Storage
* APIs](https://docs.microsoft.com/en-us/windows/win32/procthread/thread-local-storage). On Linux, this class is
* implemented using [pthread_key_t](https://linux.die.net/man/3/pthread_key_create).
*/
template <class T>
class ThreadLocal<T, false> : private detail::ThreadLocalBase
{
public:
/**
* Constructor. Allocates a thread-local storage slot from the operating system.
*/
ThreadLocal() : ThreadLocalBase(destructor), m_head(&m_head)
{
detail::tlsMutex(); // make sure this is constructed since we'll need it at shutdown
}
/**
* Destructor. Returns the previously allocated thread-local storage slot to the operating system.
*/
~ThreadLocal()
{
// Delete all instances for threads created by this object
ListNode n = m_head;
m_head.next = m_head.prev = _end();
while (n.next != _end())
{
Wrapper* w = reinterpret_cast<Wrapper*>(n.next);
n.next = n.next->next;
delete w;
}
// It would be very bad if a thread was using this while we're destroying it
CARB_ASSERT(m_head.next == _end() && m_head.prev == _end());
}
/**
* Returns the value of this ThreadLocal variable for this specific thread, if it has been constructed.
* \details If the calling thread has not called \ref get() or \ref set(const T&) on `*this` yet, calling this
* function will return `nullptr`. \note This function is only available for the non-trivial specialization of
* `ThreadLocal`.
* @returns `nullptr` if \ref set(const T&) or \ref get() has not been called by this thread on `*this` yet;
* otherwise returns `std::addressof(get())`.
*/
T* get_if()
{
return _get_if();
}
//! @copydoc get_if()
const T* get_if() const
{
return _get_if();
}
/**
* Returns the specific value of this ThreadLocal variable for this thread.
*
* @note If the calling thread has not yet set() a value for this thread-local storage, the value returned will be
* default-constructed.
*
* @returns A value previously set for the calling thread by set(), or a default-constructed value if set() has not
* been called by the calling thread.
*/
T& get()
{
return *_get();
}
/**
* Returns the specific value of this ThreadLocal variable for this thread.
*
* @note If the calling thread has not yet set() a value for this thread-local storage, the value returned will be
* default-constructed.
*
* @returns A value previously set for the calling thread by set(), or a default-constructed value if set() has not
* been called by the calling thread.
*/
const T& get() const
{
return *_get();
}
/**
* Sets the specific value of this ThreadLocal variable for this thread.
*
* @note If this is the first time set() has been called for this thread, the stored value is first default-
* constructed and then @p t is copy-assigned to the thread-local value.
* @param t The specific value to set for this thread.
*/
void set(const T& t)
{
*_get() = t;
}
/**
* Sets the specific value of this ThreadLocal variable for this thread.
*
* @note If this is the first time set() has been called for this thread, the stored value is first default-
* constructed and then @p t is move-assigned to the thread-local value.
* @param t The specific value to set for this thread.
*/
void set(T&& t)
{
*_get() = std::move(t);
}
/**
* Clears the specific value of this ThreadLocal variable for this thread.
*
* @note This function is only available on the non-trivial specialization of `ThreadLocal`.
* Postcondition: \ref get_if() returns `nullptr`.
*/
void reset()
{
if (auto p = get_if())
{
destructor(p);
ThreadLocalBase::set(nullptr);
}
}
/**
* Alias for get().
* @returns The value as if by get().
*/
operator T()
{
return get();
}
/**
* Alias for get().
* @returns The value as if by get().
*/
operator T() const
{
return get();
}
/**
* Assignment operator and alias for set().
* @returns `*this`
*/
ThreadLocal& operator=(const T& rhs)
{
set(rhs);
return *this;
}
/**
* Assignment operator and alias for set().
* @returns `*this`
*/
ThreadLocal& operator=(T&& rhs)
{
set(std::move(rhs));
return *this;
}
/**
* Pass-through support for operator->.
* @returns the value of operator->.
*/
auto operator->()
{
return get().operator->();
}
/**
* Pass-through support for operator->.
* @returns the value of operator->.
*/
auto operator->() const
{
return get().operator->();
}
/**
* Pass-through support for operator*.
* @returns the value of operator*.
*/
auto operator*()
{
return get().operator*();
}
/**
* Pass-through support for operator*.
* @returns the value of operator*.
*/
auto operator*() const
{
return get().operator*();
}
/**
* Pass-through support for operator[].
* @param u The value to pass to operator[].
* @returns the value of operator[].
*/
template <class U>
auto operator[](const U& u) const
{
return get().operator[](u);
}
/**
* Tests the thread-local value for equality with @p rhs.
*
* @param rhs The parameter to compare against.
* @returns `true` if the value stored for the calling thread (as if by get()) matches @p rhs; `false` otherwise.
*/
bool operator==(const T& rhs) const
{
return get() == rhs;
}
/**
* Tests the thread-local value for inequality with @p rhs.
*
* @param rhs The compare to compare against.
* @returns `true` if the value stored for the calling thread (as if by get()) does not match @p rhs; `false`
* otherwise.
*/
bool operator!=(const T& rhs) const
{
return get() != rhs;
}
private:
struct ListNode
{
ListNode* next;
ListNode* prev;
ListNode() = default;
ListNode(ListNode* init) : next(init), prev(init)
{
}
};
struct Wrapper : public ListNode
{
T t;
};
ListNode m_head;
ListNode* _tail() const
{
return const_cast<ListNode*>(m_head.prev);
}
ListNode* _end() const
{
return const_cast<ListNode*>(&m_head);
}
static void destructor(void* p)
{
// Can't use offsetof because of "offsetof within non-standard-layout type 'Wrapper' is undefined"
Wrapper* w = reinterpret_cast<Wrapper*>(reinterpret_cast<uint8_t*>(p) - size_t(&((Wrapper*)0)->t));
{
// Remove from the list
std::lock_guard<std::mutex> g(detail::tlsMutex());
w->next->prev = w->prev;
w->prev->next = w->next;
}
delete w;
}
T* _get_if() const
{
T* p = reinterpret_cast<T*>(ThreadLocalBase::get());
return p;
}
T* _get() const
{
T* p = _get_if();
return p ? p : _create();
}
T* _create() const
{
Wrapper* w = new Wrapper;
// Add to end of list
{
std::lock_guard<std::mutex> g(detail::tlsMutex());
w->next = _end();
w->prev = _tail();
w->next->prev = w;
w->prev->next = w;
}
T* p = std::addressof(w->t);
ThreadLocalBase::set(p);
return p;
}
};
} // namespace thread
} // namespace carb
|
omniverse-code/kit/include/carb/thread/SharedMutex.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief C++17-compatible Shared Mutex implementation for C++14 or higher.
#pragma once
#include "../Defines.h"
#include <mutex>
#include <shared_mutex>
#if CARB_ASSERT_ENABLED
# include <algorithm>
# include <thread>
# include <vector>
#endif
#if CARB_COMPILER_GNUC && (CARB_TEGRA || CARB_PLATFORM_LINUX)
# include <pthread.h>
#endif
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#endif
namespace carb
{
namespace thread
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
# if CARB_PLATFORM_WINDOWS
class SharedMutexBase
{
protected:
constexpr SharedMutexBase() noexcept = default;
~SharedMutexBase()
{
// NOTE: This assert can happen after main() has exited, since ExitProcess() kills all threads before running
// any destructors. In this case, a thread could have the shared_mutex locked and be terminated, abandoning the
// shared_mutex but leaving it in a busy state. This is not ideal. There is no easy way to determine if
// ExitProcess() has been called and the program is in this state. Therefore, if this assert happens after
// ExitProcess() has been called, ignore this assert.
CARB_ASSERT(!m_lock.Ptr); // Destroyed while busy
}
void lockExclusive()
{
AcquireSRWLockExclusive((PSRWLOCK)&m_lock);
}
bool tryLockExclusive()
{
return !!TryAcquireSRWLockExclusive((PSRWLOCK)&m_lock);
}
void unlockExclusive()
{
ReleaseSRWLockExclusive((PSRWLOCK)&m_lock);
}
void lockShared()
{
AcquireSRWLockShared((PSRWLOCK)&m_lock);
}
bool tryLockShared()
{
return !!TryAcquireSRWLockShared((PSRWLOCK)&m_lock);
}
void unlockShared()
{
ReleaseSRWLockShared((PSRWLOCK)&m_lock);
}
private:
CARBWIN_SRWLOCK m_lock = CARBWIN_SRWLOCK_INIT;
};
# else
class SharedMutexBase
{
protected:
constexpr SharedMutexBase() noexcept = default;
~SharedMutexBase()
{
int result = pthread_rwlock_destroy(&m_lock);
CARB_UNUSED(result);
CARB_ASSERT(result == 0); // Destroyed while busy
}
void lockExclusive()
{
int result = pthread_rwlock_wrlock(&m_lock);
CARB_CHECK(result == 0);
}
bool tryLockExclusive()
{
return pthread_rwlock_trywrlock(&m_lock) == 0;
}
void unlockExclusive()
{
int result = pthread_rwlock_unlock(&m_lock);
CARB_CHECK(result == 0);
}
void lockShared()
{
int result = pthread_rwlock_rdlock(&m_lock);
CARB_CHECK(result == 0);
}
bool tryLockShared()
{
return pthread_rwlock_tryrdlock(&m_lock) == 0;
}
void unlockShared()
{
int result = pthread_rwlock_unlock(&m_lock);
CARB_CHECK(result == 0);
}
private:
pthread_rwlock_t m_lock = PTHREAD_RWLOCK_INITIALIZER;
};
# endif
} // namespace detail
#endif
/**
* A shared mutex implementation conforming to C++17's
* [shared_mutex](https://en.cppreference.com/w/cpp/thread/shared_mutex).
*
* This implementation is non-recursive. See carb::thread::recursive_shared_mutex if a recursive shared_mutex is
* desired.
*
* @note The underlying implementations are based on [Slim Reader/Writer (SRW)
* Locks](https://docs.microsoft.com/en-us/windows/win32/sync/slim-reader-writer--srw--locks) for Windows, and [POSIX
* read/write lock objects](https://linux.die.net/man/3/pthread_rwlock_init) on Linux.
*/
class shared_mutex : private detail::SharedMutexBase
{
public:
/**
* Constructor.
*/
#if !CARB_ASSERT_ENABLED
constexpr
#endif
shared_mutex() = default;
/**
* Destructor.
*
* Debug builds assert that the mutex is not busy (locked) when destroyed.
*/
~shared_mutex() = default;
CARB_PREVENT_COPY(shared_mutex);
/**
* Blocks until an exclusive lock can be obtained.
*
* When this function returns, the calling thread exclusively owns the mutex. At some later point the calling thread
* will need to call unlock() to release the exclusive lock.
*
* @warning Debug builds will assert that the calling thread does not already own the lock.
*/
void lock();
/**
* Attempts to immediately take an exclusive lock, but will not block if one cannot be obtained.
*
* @warning Debug builds will assert that the calling thread does not already own the lock.
* @returns `true` if an exclusive lock could be obtained, and at some later point unlock() will need to be called
* to release the lock. If an exclusive lock could not be obtained immediately, `false` is returned.
*/
bool try_lock();
/**
* Releases an exclusive lock held by the calling thread.
*
* @warning Debug builds will assert that the calling thread owns the lock exclusively.
*/
void unlock();
/**
* Blocks until a shared lock can be obtained.
*
* When this function returns, the calling thread has obtained a shared lock on the resources protected by the
* mutex. At some later point the calling thread must call unlock_shared() to release the shared lock.
*
* @warning Debug builds will assert that the calling thread does not already own the lock.
*/
void lock_shared();
/**
* Attempts to immediately take a shared lock, but will not block if one cannot be obtained.
*
* @warning Debug builds will assert that the calling thread does not already own the lock.
* @returns `true` if a shared lock could be obtained, and at some later point unlock_shared() will need to be
* called to release the lock. If a shared lock could not be obtained immediately, `false` is returned.
*/
bool try_lock_shared();
/**
* Releases a shared lock held by the calling thread.
*
* @warning Debug builds will assert that the calling thread owns a shared lock.
*/
void unlock_shared();
private:
using Base = detail::SharedMutexBase;
#if CARB_ASSERT_ENABLED
using LockGuard = std::lock_guard<std::mutex>;
mutable std::mutex m_ownerLock;
std::vector<std::thread::id> m_owners;
void addThread()
{
LockGuard g(m_ownerLock);
m_owners.push_back(std::this_thread::get_id());
}
void removeThread()
{
LockGuard g(m_ownerLock);
auto current = std::this_thread::get_id();
auto iter = std::find(m_owners.begin(), m_owners.end(), current);
if (iter != m_owners.end())
{
*iter = m_owners.back();
m_owners.pop_back();
return;
}
// Thread not found
CARB_ASSERT(false);
}
void assertNotLockedByMe() const
{
LockGuard g(m_ownerLock);
CARB_ASSERT(std::find(m_owners.begin(), m_owners.end(), std::this_thread::get_id()) == m_owners.end());
}
#else
inline void addThread()
{
}
inline void removeThread()
{
}
inline void assertNotLockedByMe() const
{
}
#endif
};
inline void shared_mutex::lock()
{
assertNotLockedByMe();
Base::lockExclusive();
addThread();
}
inline bool shared_mutex::try_lock()
{
assertNotLockedByMe();
return Base::tryLockExclusive() ? (addThread(), true) : false;
}
inline void shared_mutex::unlock()
{
removeThread();
Base::unlockExclusive();
}
inline void shared_mutex::lock_shared()
{
assertNotLockedByMe();
Base::lockShared();
addThread();
}
inline bool shared_mutex::try_lock_shared()
{
assertNotLockedByMe();
return Base::tryLockShared() ? (addThread(), true) : false;
}
inline void shared_mutex::unlock_shared()
{
removeThread();
Base::unlockShared();
}
/**
* Alias for `std::shared_lock`.
*/
template <class Mutex>
using shared_lock = ::std::shared_lock<Mutex>;
} // namespace thread
} // namespace carb
|
omniverse-code/kit/include/carb/thread/Mutex.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Carbonite mutex and recursive_mutex implementation.
#pragma once
#include "Futex.h"
#include "Util.h"
#include "../cpp/Atomic.h"
#include <system_error>
#if CARB_PLATFORM_WINDOWS
# include "../CarbWindows.h"
#endif
namespace carb
{
namespace thread
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
# if CARB_PLATFORM_WINDOWS
template <bool Recursive>
class BaseMutex
{
public:
constexpr static bool kRecursive = Recursive;
CARB_PREVENT_COPY_AND_MOVE(BaseMutex);
constexpr BaseMutex() noexcept = default;
~BaseMutex()
{
CARB_FATAL_UNLESS(m_count == 0, "Mutex destroyed while busy");
}
void lock()
{
uint32_t const tid = this_thread::getId();
if (!Recursive)
{
CARB_FATAL_UNLESS(tid != m_owner, "Recursion not allowed");
}
else if (tid == m_owner)
{
++m_count;
return;
}
AcquireSRWLockExclusive((PSRWLOCK)&m_lock);
m_owner = tid;
m_count = 1;
}
bool try_lock()
{
uint32_t const tid = this_thread::getId();
if (!Recursive)
{
CARB_FATAL_UNLESS(tid != m_owner, "Recursion not allowed");
}
else if (tid == m_owner)
{
++m_count;
return true;
}
if (CARB_LIKELY(TryAcquireSRWLockExclusive((PSRWLOCK)&m_lock)))
{
m_owner = tid;
m_count = 1;
return true;
}
return false;
}
void unlock()
{
uint32_t tid = this_thread::getId();
CARB_FATAL_UNLESS(m_owner == tid, "Not owner");
if (--m_count == 0)
{
m_owner = kInvalidOwner;
ReleaseSRWLockExclusive((PSRWLOCK)&m_lock);
}
}
bool is_current_thread_owner() const noexcept
{
// We don't need this to be an atomic op because one of the following must be true during this call:
// - m_owner is equal to this_thread::getId() and cannot change
// - m_owner is not equal and cannot become equal to this_thread::getId()
return m_owner == this_thread::getId();
}
private:
constexpr static uint32_t kInvalidOwner = uint32_t(0);
CARBWIN_SRWLOCK m_lock{ CARBWIN_SRWLOCK_INIT };
uint32_t m_owner{ kInvalidOwner };
int m_count{ 0 };
};
# else
template <bool Recursive>
class BaseMutex;
// BaseMutex (non-recursive)
template <>
class BaseMutex<false>
{
public:
constexpr static bool kRecursive = false;
constexpr BaseMutex() noexcept = default;
~BaseMutex()
{
CARB_FATAL_UNLESS(m_lock.load(std::memory_order_relaxed) == Unlocked, "Mutex destroyed while busy");
}
void lock()
{
// Blindly attempt to lock
LockState val = Unlocked;
if (CARB_UNLIKELY(
!m_lock.compare_exchange_strong(val, Locked, std::memory_order_acquire, std::memory_order_relaxed)))
{
CARB_FATAL_UNLESS(m_owner != this_thread::getId(), "Recursive locking not allowed");
// Failed to lock and need to wait
if (val == LockedMaybeWaiting)
{
m_lock.wait(LockedMaybeWaiting, std::memory_order_relaxed);
}
while (m_lock.exchange(LockedMaybeWaiting, std::memory_order_acquire) != Unlocked)
{
m_lock.wait(LockedMaybeWaiting, std::memory_order_relaxed);
}
CARB_ASSERT(m_owner == kInvalidOwner);
}
// Now inside the lock
m_owner = this_thread::getId();
}
bool try_lock()
{
// Blindly attempt to lock
LockState val = Unlocked;
if (CARB_LIKELY(m_lock.compare_exchange_strong(val, Locked, std::memory_order_acquire, std::memory_order_relaxed)))
{
m_owner = this_thread::getId();
return true;
}
CARB_FATAL_UNLESS(m_owner != this_thread::getId(), "Recursive locking not allowed");
return false;
}
void unlock()
{
CARB_FATAL_UNLESS(is_current_thread_owner(), "Not owner");
m_owner = kInvalidOwner;
LockState val = m_lock.exchange(Unlocked, std::memory_order_release);
if (val == LockedMaybeWaiting)
{
m_lock.notify_one();
}
}
bool is_current_thread_owner() const noexcept
{
// We don't need this to be an atomic op because one of the following must be true during this call:
// - m_owner is equal to this_thread::getId() and cannot change
// - m_owner is not equal and cannot become equal to this_thread::getId()
return m_owner == this_thread::getId();
}
private:
enum LockState : uint8_t
{
Unlocked = 0,
Locked = 1,
LockedMaybeWaiting = 2,
};
constexpr static uint32_t kInvalidOwner = 0;
cpp::atomic<LockState> m_lock{ Unlocked };
uint32_t m_owner{ kInvalidOwner };
};
// BaseMutex (recursive)
template <>
class BaseMutex<true>
{
public:
constexpr static bool kRecursive = true;
constexpr BaseMutex() noexcept = default;
~BaseMutex()
{
CARB_FATAL_UNLESS(m_lock.load(std::memory_order_relaxed) == 0, "Mutex destroyed while busy");
}
void lock()
{
// Blindly attempt to lock
uint32_t val = Unlocked;
if (CARB_UNLIKELY(
!m_lock.compare_exchange_strong(val, Locked, std::memory_order_acquire, std::memory_order_relaxed)))
{
// Failed to lock (or recursive)
if (m_owner == this_thread::getId())
{
val = m_lock.fetch_add(DepthUnit, std::memory_order_relaxed);
CARB_FATAL_UNLESS((val & DepthMask) != DepthMask, "Recursion overflow");
return;
}
// Failed to lock and need to wait
if ((val & ~DepthMask) == LockedMaybeWaiting)
{
m_lock.wait(val, std::memory_order_relaxed);
}
for (;;)
{
// Atomically set to LockedMaybeWaiting in a loop since the owning thread could be changing the depth
while (!m_lock.compare_exchange_weak(
val, (val & DepthMask) | LockedMaybeWaiting, std::memory_order_acquire, std::memory_order_relaxed))
CARB_HARDWARE_PAUSE();
if ((val & ~DepthMask) == Unlocked)
break;
m_lock.wait((val & DepthMask) | LockedMaybeWaiting, std::memory_order_relaxed);
}
CARB_ASSERT(m_owner == kInvalidOwner);
}
// Now inside the lock
m_owner = this_thread::getId();
}
bool try_lock()
{
// Blindly attempt to lock
uint32_t val = Unlocked;
if (CARB_LIKELY(m_lock.compare_exchange_strong(val, Locked, std::memory_order_acquire, std::memory_order_relaxed)))
{
// Succeeded, we now own the lock
m_owner = this_thread::getId();
return true;
}
// Failed (or recursive)
if (m_owner == this_thread::getId())
{
// Recursive, increment the depth
val = m_lock.fetch_add(DepthUnit, std::memory_order_acquire);
CARB_FATAL_UNLESS((val & DepthMask) != DepthMask, "Recursion overflow");
return true;
}
return false;
}
void unlock()
{
CARB_FATAL_UNLESS(is_current_thread_owner(), "Not owner");
uint32_t val = m_lock.load(std::memory_order_relaxed);
if (!(val & DepthMask))
{
// Depth count is at zero, so this is the last unlock().
m_owner = kInvalidOwner;
uint32_t val = m_lock.exchange(Unlocked, std::memory_order_release);
if (val == LockedMaybeWaiting)
{
m_lock.notify_one();
}
}
else
m_lock.fetch_sub(DepthUnit, std::memory_order_release);
}
bool is_current_thread_owner() const noexcept
{
// We don't need this to be an atomic op because one of the following must be true during this call:
// - m_owner is equal to this_thread::getId() and cannot change
// - m_owner is not equal and cannot become equal to this_thread::getId()
return m_owner == this_thread::getId();
}
private:
enum LockState : uint32_t
{
Unlocked = 0,
Locked = 1,
LockedMaybeWaiting = 2,
DepthUnit = 1 << 2, // Each recursion count increment
DepthMask = 0xFFFFFFFC // The 30 MSBs are used for the recursion count
};
constexpr static uint32_t kInvalidOwner = 0;
cpp::atomic_uint32_t m_lock{ Unlocked };
uint32_t m_owner{ kInvalidOwner };
};
# endif
} // namespace detail
#endif
/**
* A Carbonite implementation of [std::mutex](https://en.cppreference.com/w/cpp/thread/mutex).
*
* @note Windows: `std::mutex` uses `SRWLOCK` for Win 7+, `CONDITION_VARIABLE` for Vista and the massive
* `CRITICAL_SECTION` for pre-Vista. Due to this, the `std::mutex` class is about 80 bytes. Since Carbonite supports
* Windows 10 and later, `SRWLOCK` is used exclusively. This implementation is 16 bytes. This version that uses
* `SRWLOCK` is significantly faster on Windows than the portable implementation used for the linux version.
*
* @note Linux: `sizeof(std::mutex)` is 40 bytes on GLIBC 2.27, which is based on the size of `pthread_mutex_t`. The
* Carbonite implementation of mutex is 8 bytes and at least as performant as `std::mutex` in the contended case.
*/
class mutex : public detail::BaseMutex<false>
{
using Base = detail::BaseMutex<false>;
public:
/**
* Constructor.
*
* @note Unlike `std::mutex`, this implementation can be declared `constexpr`.
*/
constexpr mutex() noexcept = default;
/**
* Destructor.
* @warning `std::terminate()` is called if mutex is locked by a thread.
*/
~mutex() = default;
/**
* Locks the mutex, blocking until it becomes available.
* @warning `std::terminate()` is called if the calling thread already has the mutex locked. Use recursive_mutex if
* recursive locking is desired.
* The calling thread must call unlock() at a later time to release the lock.
*/
void lock()
{
Base::lock();
}
/**
* Attempts to immediately lock the mutex.
* @warning `std::terminate()` is called if the calling thread already has the mutex locked. Use recursive_mutex if
* recursive locking is desired.
* @returns `true` if the mutex was available and the lock was taken by the calling thread (unlock() must be called
* from the calling thread at a later time to release the lock); `false` if the mutex could not be locked by the
* calling thread.
*/
bool try_lock()
{
return Base::try_lock();
}
/**
* Unlocks the mutex.
* @warning `std::terminate()` is called if the calling thread does not own the mutex.
*/
void unlock()
{
Base::unlock();
}
/**
* Checks if the current thread owns the mutex.
* @note This is a non-standard Carbonite extension.
* @returns `true` if the current thread owns the mutex; `false` otherwise.
*/
bool is_current_thread_owner() const noexcept
{
return Base::is_current_thread_owner();
}
};
/**
* A Carbonite implementation of [std::recursive_mutex](https://en.cppreference.com/w/cpp/thread/recursive_mutex).
*
* @note Windows: `std::recursive_mutex` uses `SRWLOCK` for Win 7+, `CONDITION_VARIABLE` for Vista and the massive
* `CRITICAL_SECTION` for pre-Vista. Due to this, the `std::recursive_mutex` class is about 80 bytes. Since Carbonite
* supports Windows 10 and later, `SRWLOCK` is used exclusively. This implementation is 16 bytes. This version that uses
* `SRWLOCK` is significantly faster on Windows than the portable implementation used for the linux version.
*
* @note Linux: `sizeof(std::recursive_mutex)` is 40 bytes on GLIBC 2.27, which is based on the size of
* `pthread_mutex_t`. The Carbonite implementation of mutex is 8 bytes and at least as performant as
* `std::recursive_mutex` in the contended case.
*/
class recursive_mutex : public detail::BaseMutex<true>
{
using Base = detail::BaseMutex<true>;
public:
/**
* Constructor.
*
* @note Unlike `std::recursive_mutex`, this implementation can be declared `constexpr`.
*/
constexpr recursive_mutex() noexcept = default;
/**
* Destructor.
* @warning `std::terminate()` is called if recursive_mutex is locked by a thread.
*/
~recursive_mutex() = default;
/**
* Locks the recursive_mutex, blocking until it becomes available.
*
* The calling thread must call unlock() at a later time to release the lock. There must be symmetrical calls to
* unlock() for each call to lock() or successful call to try_lock().
*/
void lock()
{
Base::lock();
}
/**
* Attempts to immediately lock the recursive_mutex.
* @returns `true` if the recursive_mutex was available and the lock was taken by the calling thread (unlock() must
* be called from the calling thread at a later time to release the lock); `false` if the recursive_mutex could not
* be locked by the calling thread. If the lock was already held by the calling thread, `true` is always returned.
*/
bool try_lock()
{
return Base::try_lock();
}
/**
* Unlocks the recursive_mutex.
* @warning `std::terminate()` is called if the calling thread does not own the recursive_mutex.
*/
void unlock()
{
Base::unlock();
}
/**
* Checks if the current thread owns the mutex.
* @note This is a non-standard Carbonite extension.
* @returns `true` if the current thread owns the mutex; `false` otherwise.
*/
bool is_current_thread_owner() const noexcept
{
return Base::is_current_thread_owner();
}
};
} // namespace thread
} // namespace carb
|
Subsets and Splits