file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
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
30,838
C
46.886646
101
0.676049
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, &params); } void setVolume(float volume) { VoiceParams params = {}; params.volume = volume; m_iface->setVoiceParameters(m_voice, fVoiceParamVolume, &params); } void setMute(bool muted) { VoiceParams params = {}; params.playbackMode = muted ? fPlaybackModeMuted : 0; m_iface->setVoiceParameters(m_voice, fVoiceParamMute, &params); } void setBalance(float pan, float fade) { VoiceParams params = {}; params.balance.pan = pan; params.balance.fade = fade; m_iface->setVoiceParameters(m_voice, fVoiceParamBalance, &params); } void setFrequencyRatio(float ratio) { VoiceParams params = {}; params.frequencyRatio = ratio; m_iface->setVoiceParameters(m_voice, fVoiceParamFrequencyRatio, &params); } void setPriority(int32_t priority) { VoiceParams params = {}; params.priority = priority; m_iface->setVoiceParameters(m_voice, fVoiceParamPriority, &params); } void setSpatialMixLevel(float level) { VoiceParams params = {}; params.spatialMixLevel = level; m_iface->setVoiceParameters(m_voice, fVoiceParamSpatialMixLevel, &params); } void setDopplerScale(float scale) { VoiceParams params = {}; params.dopplerScale = scale; m_iface->setVoiceParameters(m_voice, fVoiceParamDopplerScale, &params); } void setOcclusion(float direct, float reverb) { VoiceParams params = {}; params.occlusion.direct = direct; params.occlusion.reverb = reverb; m_iface->setVoiceParameters(m_voice, fVoiceParamOcclusionFactor, &params); } 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, &params); } void setPosition(Float3 position) { VoiceParams params = {}; params.emitter.flags = fEntityFlagPosition; params.emitter.position = position; m_iface->setVoiceParameters(m_voice, fVoiceParamEmitter, &params); } void setVelocity(Float3 velocity) { VoiceParams params = {}; params.emitter.flags = fEntityFlagVelocity; params.emitter.velocity = velocity; m_iface->setVoiceParameters(m_voice, fVoiceParamEmitter, &params); } 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, &params); } 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
122,136
C
46.321581
119
0.627988
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
12,206
C
48.82449
115
0.642225
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
125,893
C
54.192459
123
0.671626
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
30,988
C
54.936823
105
0.654608
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
152,738
C
57.319588
119
0.702333
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
39,920
C
48.591304
121
0.698272
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
42,355
C
59.76901
107
0.655696
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
33,667
C
38.843787
123
0.60739
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
2,673
C
29.386363
113
0.716423
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
8,039
C
42.934426
151
0.670481
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
1,058
C
26.153845
80
0.743856
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)
18,410
C
29.28125
121
0.605323
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
1,225
C
24.020408
93
0.675102
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
9,066
C
33.60687
120
0.643393
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
3,808
C
33.008928
145
0.705357
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
67,156
C
45.636806
121
0.690586
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
31,598
C
40.687335
124
0.67077
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
25,769
C
40.902439
234
0.619077
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
9,359
C
39.695652
123
0.639278
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
12,737
C
48.372093
121
0.579022
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
4,928
C
25.643243
120
0.726664
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
2,118
C
36.175438
120
0.586874
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
42,914
C
33.059524
139
0.581162
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
8,265
C
42.505263
124
0.690381
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
10,109
C
51.113402
98
0.69354
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
20,022
C
28.018841
126
0.597693
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
8,345
C
26.27451
120
0.649371
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
14,595
C
30.456896
123
0.604591
omniverse-code/kit/include/carb/thread/Spinlock.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 Spinlock implementation. #pragma once #include "../Defines.h" #include <atomic> #include <thread> namespace carb { namespace thread { /** Namespace for Carbonite private threading details. */ namespace detail { #ifndef DOXYGEN_SHOULD_SKIP_THIS class RecursionPolicyDisallow { public: constexpr RecursionPolicyDisallow() = default; bool ownsLock() const { return std::this_thread::get_id() == m_owner; } void enter() { auto cur = std::this_thread::get_id(); CARB_FATAL_UNLESS(cur != m_owner, "Recursion is not allowed"); m_owner = cur; } bool tryLeave() { CARB_FATAL_UNLESS(ownsLock(), "Not owning thread"); m_owner = std::thread::id(); // clear the owner return true; } private: std::thread::id m_owner{}; }; class RecursionPolicyAllow { public: constexpr RecursionPolicyAllow() = default; bool ownsLock() const { return std::this_thread::get_id() == m_owner; } void enter() { auto cur = std::this_thread::get_id(); if (cur == m_owner) ++m_recursion; else { CARB_ASSERT(m_owner == std::thread::id()); // owner should be clear m_owner = cur; m_recursion = 1; } } bool tryLeave() { CARB_FATAL_UNLESS(ownsLock(), "Not owning thread"); if (--m_recursion == 0) { m_owner = std::thread::id(); // clear the owner return true; } return false; } private: std::thread::id m_owner{}; size_t m_recursion{ 0 }; }; #endif /** * Spinlock and RecursiveSpinlock are locking primitives that never enter the kernel to wait. * * @note Do not use SpinlockImpl directly; instead use Spinlock or RecursiveSpinlock. * * This class meets Cpp17BasicLockable and Cpp17Lockable named requirements. * * @warning Using Spinlock is generally discouraged and can lead to worse performance than using carb::thread::mutex or * another synchronization primitive that can wait. */ template <class RecursionPolicy> class SpinlockImpl { public: /** * Constructor. */ constexpr SpinlockImpl() = default; /** * Destructor. */ ~SpinlockImpl() = default; CARB_PREVENT_COPY(SpinlockImpl); /** * Locks the spinlock, spinning the current thread until it becomes available. * If not called from RecursiveSpinlock and the calling thread already owns the lock, `std::terminate()` is called. * The calling thread must call unlock() at a later time to release the lock. */ void lock() { if (!m_rp.ownsLock()) { // Spin trying to set the lock bit while (CARB_UNLIKELY(!!m_lock.fetch_or(1, std::memory_order_acquire))) { CARB_HARDWARE_PAUSE(); } } m_rp.enter(); } /** * Unlocks the spinlock. * @warning `std::terminate()` is called if the calling thread does not own the spinlock. */ void unlock() { if (m_rp.tryLeave()) { // Released the lock m_lock.store(0, std::memory_order_release); } } /** * Attempts to immediately lock the spinlock. * If not called from RecursiveSpinlock and the calling thread already owns the lock, `std::terminate()` is called. * @returns `true` if the spinlock 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 spinlock could not be locked * by the calling thread. */ bool try_lock() { if (!m_rp.ownsLock()) { // See if we can set the lock bit if (CARB_UNLIKELY(!!m_lock.fetch_or(1, std::memory_order_acquire))) { // Failed! return false; } } m_rp.enter(); return true; } /** * Returns true if the calling thread owns this spinlock. * @returns `true` if the calling thread owns this spinlock; `false` otherwise. */ bool isLockedByThisThread() const { return m_rp.ownsLock(); } private: std::atomic<size_t> m_lock{ 0 }; RecursionPolicy m_rp; }; } // namespace detail /** * A spinlock implementation that allows recursion. */ using RecursiveSpinlock = detail::SpinlockImpl<detail::RecursionPolicyAllow>; /** * A spinlock implementation that does not allow recursion. * @warning Attempts to use this class in a recursive manner will call `std::terminate()`. */ using Spinlock = detail::SpinlockImpl<detail::RecursionPolicyDisallow>; } // namespace thread } // namespace carb
5,246
C
24.847291
119
0.613992
omniverse-code/kit/include/carb/thread/IpcLock.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_WINDOWS # include "../CarbWindows.h" #elif CARB_POSIX # include <sys/stat.h> # include <errno.h> # include <fcntl.h> # include <semaphore.h> # include <string.h> #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace carb { namespace thread { /** defines an implementation of an intra-process lock. This lock will only be functional within * the threads of the process that creates it. The lock implementation will always be recursive. * When a lock with the given name is created, it will initially be unlocked. */ #if CARB_PLATFORM_WINDOWS /** defines an implementation of an inter-process lock. These locks are given a unique name * to allow other processes to open a lock of the same name. The name may be any ASCII string * that does not contain the slash character ('/'). The name may be limited to an implementation * defined length. Lock names should be less than 250 characters in general. The name of the * lock will be removed from the system when all processes that use that name destroy their * objects. When a lock with the given name is created, it will initially be unlocked. */ class IpcLock { public: IpcLock(const char* name) { m_mutex = CreateMutexA(nullptr, CARBWIN_FALSE, name); CARB_FATAL_UNLESS(m_mutex != nullptr, "CreateMutex() failed: %u", ::GetLastError()); } ~IpcLock() { CloseHandle(m_mutex); } void lock() { WaitForSingleObject(m_mutex, CARBWIN_INFINITE); } void unlock() { ReleaseMutex(m_mutex); } bool try_lock() { return WaitForSingleObject(m_mutex, 0) == CARBWIN_WAIT_OBJECT_0; } private: HANDLE m_mutex; }; #elif CARB_POSIX /** defines an implementation of an inter-process lock. These locks are given a unique name * to allow other processes to open a lock of the same name. The name may be any string that * does not contain the slash character ('/'). The name may be limited to an implementation * defined length. Lock names should be less than 250 characters in general. The name of the * lock will be removed from the system when all processes that use that name destroy their * objects. When a lock with the given name is created, it will initially be unlocked. */ class IpcLock { public: IpcLock(const char* name) { // create the name for the semaphore and remove all slashes within it (slashes are not // allowed after the first character and the first character must always be a slash). snprintf(m_name, CARB_COUNTOF(m_name) - 4, "/%s", name); for (size_t i = 1; m_name[i] != 0; i++) { if (m_name[i] == '/') m_name[i] = '_'; } // create the named semaphore. m_semaphore = sem_open(m_name, O_CREAT | O_RDWR, 0644, 1); CARB_ASSERT(m_semaphore != SEM_FAILED); } ~IpcLock() { sem_close(m_semaphore); sem_unlink(m_name); } void lock() { int ret; // keep trying the wait operation as long as we get interrupted by a signal. do { ret = sem_wait(m_semaphore); // Oddly enough, on Windows Subsystem for Linux, sem_wait can fail with ETIMEDOUT. Handle that case here } while (ret == -1 && (errno == EINTR || errno == ETIMEDOUT)); } void unlock() { sem_post(m_semaphore); } bool try_lock() { // keep trying the wait operation as long as we get interrupted by a signal. int ret = CARB_RETRY_EINTR(sem_trywait(m_semaphore)); // if the lock was acquired, the return value will always be zero. If if failed either // due to a non-signal error or because it would block, 'ret' will be -1. If the call // was valid but would block, 'errno' is set to EAGAIN. return ret == 0; } private: sem_t* m_semaphore; char m_name[NAME_MAX + 10]; }; #else CARB_UNSUPPORTED_PLATFORM(); #endif } // namespace thread } // namespace carb
4,541
C
29.07947
116
0.652059
omniverse-code/kit/include/carb/thread/Util.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 thread utilities. #pragma once #include "../Defines.h" #include "../extras/ScopeExit.h" #include "../math/Util.h" #include "../process/Util.h" #include "../profiler/IProfiler.h" #include "../../omni/extras/ContainerHelper.h" #if CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" # include "../extras/Unicode.h" #elif CARB_POSIX # include <sys/syscall.h> # include <pthread.h> # include <sched.h> # include <unistd.h> # include <time.h> #else CARB_UNSUPPORTED_PLATFORM(); #endif #if CARB_PLATFORM_MACOS # pragma push_macro("min") # pragma push_macro("max") # undef min # undef max # include <mach/thread_policy.h> # include <mach/thread_act.h> # pragma pop_macro("max") # pragma pop_macro("min") #endif #include <atomic> #include <thread> namespace carb { namespace thread { /** The type for a process ID. */ using ProcessId = process::ProcessId; /** The type for a thread ID. */ using ThreadId = uint32_t; /** * Each entry in the vector is a bitmask for a set of CPUs. * * On Windows each entry corresponds to a Processor Group. * * On Linux the entries are contiguous, like cpu_set_t. */ using CpuMaskVector = std::vector<uint64_t>; /** The number of CPUs represented by an individual cpu mask. */ constexpr uint64_t kCpusPerMask = std::numeric_limits<CpuMaskVector::value_type>::digits; #if CARB_PLATFORM_WINDOWS static_assert(sizeof(ThreadId) >= sizeof(DWORD), "ThreadId type is too small"); #elif CARB_POSIX static_assert(sizeof(ThreadId) >= sizeof(pid_t), "ThreadId type is too small"); #else CARB_UNSUPPORTED_PLATFORM(); #endif /** The printf format macro to print a thread ID. */ #define OMNI_PRItid PRIu32 /** The printf format macro to print a thread ID in hexadecimal. */ #define OMNI_PRIxtid PRIx32 #if CARB_PLATFORM_WINDOWS # ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { const DWORD MS_VC_EXCEPTION = 0x406D1388; # pragma pack(push, 8) typedef struct tagTHREADNAME_INFO { DWORD dwType; LPCSTR szName; DWORD dwThreadID; DWORD dwFlags; } THREADNAME_INFO; # pragma pack(pop) inline void setDebuggerThreadName(DWORD threadId, LPCSTR name) { // Do it the old way, which is only really useful if the debugger is running if (::IsDebuggerPresent()) { detail::THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name; info.dwThreadID = threadId; info.dwFlags = 0; # pragma warning(push) # pragma warning(disable : 6320 6322) __try { ::RaiseException(detail::MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except (CARBWIN_EXCEPTION_EXECUTE_HANDLER) { } # pragma warning(pop) } } } // namespace detail # endif //! The definition of a NativeHandleType. On Windows this is a `HANDLE` and on Linux it is a `pthread_t`. using NativeHandleType = HANDLE; #elif CARB_POSIX //! The definition of a NativeHandleType. On Windows this is a `HANDLE` and on Linux it is a `pthread_t`. using NativeHandleType = pthread_t; #else CARB_UNSUPPORTED_PLATFORM(); #endif /** * Sets the name of the given thread. * * @note The length of the name is limited by the system. * * @param h The native handle to the thread. * @param name The desired name for the thread. * * @note On Mac OS, it is not possible to name a thread that is not the current * executing thread. */ inline void setName(NativeHandleType h, const char* name) { #if CARB_PLATFORM_WINDOWS // Emulate CARB_NAME_THREAD but don't include Profile.h which would create a circular dependency. if (g_carbProfiler) g_carbProfiler->nameThreadDynamic(::GetThreadId(h), "%s", name); // SetThreadDescription is only available starting with Windows 10 1607 using PSetThreadDescription = HRESULT(CARBWIN_WINAPI*)(HANDLE, PCWSTR); static PSetThreadDescription SetThreadDescription = (PSetThreadDescription)::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription"); if (SetThreadDescription) { bool b = CARBWIN_SUCCEEDED(SetThreadDescription(h, extras::convertUtf8ToWide(name).c_str())); CARB_UNUSED(b); CARB_ASSERT(b); } else { detail::setDebuggerThreadName(::GetThreadId(h), name); } #elif CARB_PLATFORM_LINUX if (h == pthread_self()) { // Emulate CARB_NAME_THREAD but don't include Profile.h which would create a circular dependency. if (g_carbProfiler) g_carbProfiler->nameThreadDynamic(0, "%s", name); } if (pthread_setname_np(h, name) != 0) { // This is limited to 16 characters including NUL according to the man page. char buffer[16]; strncpy(buffer, name, 15); buffer[15] = '\0'; pthread_setname_np(h, buffer); } #elif CARB_PLATFORM_MACOS if (h == pthread_self()) { pthread_setname_np(name); } // not possible to name an external thread on mac #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Retrieves the name of the thread previously set with setName(). * * @note The length of the name is limited by the system. * * @param h The native handle to the thread. * @return The name of the thread. */ inline std::string getName(NativeHandleType h) { #if CARB_PLATFORM_WINDOWS // GetThreadDescription is only available starting with Windows 10 1607 using PGetThreadDescription = HRESULT(CARBWIN_WINAPI*)(HANDLE, PWSTR*); static PGetThreadDescription GetThreadDescription = (PGetThreadDescription)::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"); if (GetThreadDescription) { PWSTR threadName; if (CARBWIN_SUCCEEDED(GetThreadDescription(h, &threadName))) { std::string s = extras::convertWideToUtf8(threadName); ::LocalFree(threadName); return s; } } return std::string(); #elif CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS char buffer[64]; if (pthread_getname_np(h, buffer, CARB_COUNTOF(buffer)) == 0) { return std::string(buffer); } return std::string(); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Sets the CPU affinity for the given thread handle * * Each bit represents a logical CPU; bit 0 for CPU 0, bit 1 for CPU 1, etc. * * @param h The native handle to the thread * @param mask The bitmask representing the desired CPU affinity. Zero (no bits set) is ignored. * * @note On Mac OS, the CPU affinity works differently than on other systems. * The mask is treated as a unique ID for groups of threads that should run * on the same core, rather than specific CPUs. * For single CPU masks, this will function similarly to other systems * (aside from the fact that the specific core the threads are running on * being different). * * @note M1 Macs do not support thread affinity so this will do nothing on those systems. */ inline void setAffinity(NativeHandleType h, size_t mask) { #if CARB_PLATFORM_WINDOWS ::SetThreadAffinityMask(h, mask); #elif CARB_PLATFORM_LINUX // From the man page: The cpu_set_t data type is implemented as a bit mask. However, the data structure should be // treated as opaque: all manipulation of the CPU sets should be done via the macros described in this page. if (!mask) return; cpu_set_t cpuSet; CPU_ZERO(&cpuSet); static_assert(sizeof(cpuSet) >= sizeof(mask), "Invalid assumption: use CPU_ALLOC"); do { int bit = __builtin_ctz(mask); CPU_SET(bit, &cpuSet); mask &= ~(size_t(1) << bit); } while (mask != 0); pthread_setaffinity_np(h, sizeof(cpu_set_t), &cpuSet); #elif CARB_PLATFORM_MACOS thread_affinity_policy policy{ static_cast<integer_t>(mask) }; thread_policy_set(pthread_mach_thread_np(h), THREAD_AFFINITY_POLICY, reinterpret_cast<thread_policy_t>(&policy), THREAD_AFFINITY_POLICY_COUNT); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Sets the CPU Affinity for the thread. * * On Windows each entry in the CpuMaskVector represents a Processor Group. Each thread can only belong to a single * Processor Group, so this function will only set the CPU Affinity to the first non-zero entry in the provided * CpuMaskVector. That is to say, if both \c masks[0] and \c masks[1] both have bits sets, only the CPUs in \c masks[0] * will be set for the affinity. * * On Linux, the CpuMaskVector is analogous to a cpu_set_t. There are no restrictions on the number of CPUs that the * affinity mask can contain. * * @param h The thread to set CPU Affinity for. * @param masks Affinity masks to set. * * @return True if the function succeeded, false otherwise. If \c masks is empty, or has no bits set, false will be * returned. If the underlying function for setting affinity failed, then \c errno or \c last-error will be set. * * @note On Mac OS, the CPU affinity works differently than on other systems. * The mask is treated as a unique ID for groups of threads that should run * on cores that share L2 cache, rather than specific CPUs. * For single CPU masks, this will function somewhat similarly to other * systems, but threads won't be pinned to a specific core. */ inline bool setAffinity(NativeHandleType h, const CpuMaskVector& masks) { if (masks.empty()) { return false; } #if CARB_PLATFORM_WINDOWS // Find the lowest mask with a value set. That is the CPU Group that we'll set the affinity for. for (uint64_t i = 0; i < masks.size(); ++i) { if (masks[i]) { CARBWIN_GROUP_AFFINITY affinity{}; affinity.Group = (WORD)i; affinity.Mask = masks[i]; return ::SetThreadGroupAffinity(h, (const GROUP_AFFINITY*)&affinity, nullptr); } } // Would only reach here if no affinity mask had a cpu set. return false; #elif CARB_PLATFORM_LINUX uint64_t numCpus = kCpusPerMask * masks.size(); cpu_set_t* cpuSet = CPU_ALLOC(numCpus); if (!cpuSet) { return false; } CARB_SCOPE_EXIT { CPU_FREE(cpuSet); }; CPU_ZERO_S(CPU_ALLOC_SIZE(numCpus), cpuSet); for (uint64_t i = 0; i < masks.size(); ++i) { CpuMaskVector::value_type mask = masks[i]; while (mask != 0) { int bit = cpp::countr_zero(mask); CPU_SET(bit + (i * kCpusPerMask), cpuSet); mask &= ~(CpuMaskVector::value_type(1) << bit); } } if (pthread_setaffinity_np(h, CPU_ALLOC_SIZE(numCpus), cpuSet) != 0) { return false; } else { return true; } #elif CARB_PLATFORM_MACOS size_t mask = 0; for (uint64_t i = 0; i < masks.size(); ++i) { mask |= 1ULL << masks[i]; } setAffinity(h, mask); return true; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Gets the current CPU Affinity for the thread. * * On Windows each entry in the CpuMaskVector represents a Processor Group. * On Linux, the CpuMaskVector is analogous to a cpu_set_t. * * @param h The thread to get CPU Affinity for. * * @return A CpuMaskVector containing the cpu affinities for the thread. If the underlying functions to get thread * affinity return an error, the returned CpuMaskVector will be empty and \c errno or \c last-error will be set. * * @note M1 Macs do not support thread affinity so this will always return an * empty vector. */ inline CpuMaskVector getAffinity(NativeHandleType h) { CpuMaskVector results; #if CARB_PLATFORM_WINDOWS CARBWIN_GROUP_AFFINITY affinity; if (!::GetThreadGroupAffinity(h, (PGROUP_AFFINITY)&affinity)) { return results; } results.resize(affinity.Group + 1, 0); results.back() = affinity.Mask; return results; #elif CARB_PLATFORM_LINUX // Get the current affinity cpu_set_t cpuSet; CPU_ZERO(&cpuSet); if (pthread_getaffinity_np(h, sizeof(cpu_set_t), &cpuSet) != 0) { return results; } // Convert the cpu_set_t to a CpuMaskVector results.reserve(sizeof(cpu_set_t) / sizeof(CpuMaskVector::value_type)); CpuMaskVector::value_type* ptr = reinterpret_cast<CpuMaskVector::value_type*>(&cpuSet); for (uint64_t i = 0; i < (sizeof(cpu_set_t) / sizeof(CpuMaskVector::value_type)); i++) { results.push_back(ptr[i]); } return results; #elif CARB_PLATFORM_MACOS boolean_t def = false; // if the value retrieved was the default mach_msg_type_number_t count = 0; // the length of the returned struct in integer_t thread_affinity_policy policy{ 0 }; int res = thread_policy_get( pthread_mach_thread_np(h), THREAD_AFFINITY_POLICY, reinterpret_cast<thread_policy_t>(&policy), &count, &def); if (res != 0 || def) { return results; } for (uint64_t i = 0; i < (sizeof(policy.affinity_tag) * CHAR_BIT); i++) { if ((policy.affinity_tag & (1ULL << i)) != 0) { results.push_back(i); } } return results; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * A utility class for providing a growing number of pause instructions, followed by yielding. * * The pause instruction is effectively \ref CARB_HARDWARE_PAUSE(). * * Very fast to construct, often used in a loop such as: * ```cpp * for (AtomicBackoff<> b;; b.pause()) * if (condition()) * break; * ``` * @tparam PausesBeforeYield the number of pauses that will occur before yielding begins. See * \ref AtomicBackoff::pause(). */ template <size_t PausesBeforeYield = 16> class AtomicBackoff { public: //! The number of pauses that should be executed before yielding the thread. static constexpr size_t kPausesBeforeYield = PausesBeforeYield; static_assert(carb::cpp::has_single_bit(kPausesBeforeYield), "Must be a power of 2"); //! Constructor. constexpr AtomicBackoff() noexcept = default; CARB_PREVENT_COPY_AND_MOVE(AtomicBackoff); /** * A helper function for executing the CPU pause instruction `count` times. * @param count The number of times to execute \ref CARB_HARDWARE_PAUSE(). */ static void pauseLoop(size_t count) noexcept { while (count-- > 0) CARB_HARDWARE_PAUSE(); } /** * Resets `*this`. */ void reset() noexcept { m_growth = 1; } /** * Every time called, will pause for exponentially longer, and after a certain amount will instead yield. * * Pause is as via \ref CARB_HARDWARE_PAUSE. Yield is as via `std::this_thread::yield()`. * The pause count starts at 1 when \ref reset() or newly constructed. Each time this function is called, the CPU * pause instruction is executed `count` times and `count` is doubled. If called when `count` exceeds * \ref kPausesBeforeYield, a yield occurs instead. Calling \ref reset() resets the `count` to 1. */ void pause() noexcept { if (m_growth <= kPausesBeforeYield) { // Execute pauses pauseLoop(m_growth); // Pause twice as many times next time m_growth *= 2; } else { // Too much contention; just yield to the OS std::this_thread::yield(); } } /** * Similar to \ref pause() but if would yield, instead returns false. * @returns true if the internal `count` is less than \ref kPausesBeforeYield; `false` otherwise. */ bool pauseWithoutYield() noexcept { pauseLoop(m_growth); if (m_growth >= kPausesBeforeYield) return false; // Pause twice as many times next time m_growth *= 2; return true; } private: size_t m_growth{ 1 }; }; /** * Similar to `std::thread::hardware_concurrency()`, but pays attention to docker cgroup config and CPU limits. * * Docker container CPU limits are based on the ratio of `/sys/fs/cgroup/cpu/cpu.cfs_quota_us` to * `/sys/fs/cgroup/cpu/cpu.cfs_period_us`. Fractional CPUs of a half or larger will round up to a full CPU. It is * possible to have an odd number reported by this function. * Examples: * * Docker `--cpus="3.75"` will produce `4` (rounds fractional up) * * Docker `--cpus="3.50"` will produce `4` (rounds fractional up) * * Docker `--cpus="3.25"` will produce `3` (rounds fractional down) * * Docker `--cpus="0.25"` will produce `1` (minimum of 1) * * @returns The number of CPUs available on the current system or within the current container, if applicable. */ inline unsigned hardware_concurrency() noexcept { #if CARB_PLATFORM_LINUX static auto dockerLimit = omni::extras::getDockerCpuLimit(); if (dockerLimit > 0) { return unsigned(dockerLimit); } #endif return std::thread::hardware_concurrency(); } } // namespace thread /** * Namespace for utilities that operate on the current thread specifically. */ namespace this_thread { /** * A simple sleep for the current thread that does not include the overhead of `std::chrono`. * * @param microseconds The number of microseconds to sleep for */ inline void sleepForUs(uint32_t microseconds) noexcept { #if CARB_PLATFORM_WINDOWS ::Sleep(microseconds / 1000); #elif CARB_POSIX uint64_t nanos = uint64_t(microseconds) * 1'000; struct timespec rem, req{ time_t(nanos / 1'000'000'000), long(nanos % 1'000'000'000) }; while (nanosleep(&req, &rem) != 0 && errno == EINTR) req = rem; // Complete remaining sleep #else CARB_PLATFORM_UNSUPPORTED() #endif } #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { inline unsigned contentionSpins() { // These must be power-of-two-minus-one so that they function as bitmasks constexpr static unsigned kSpinsMax = 128 - 1; constexpr static unsigned kSpinsMin = 32 - 1; // Use randomness to prevent threads from resonating at the same frequency and permanently contending. Use a // simple LCG for randomness. static std::atomic_uint _seed; // Use random initialization value as the starting seed unsigned int next = _seed.load(std::memory_order_relaxed); _seed.store(next * 1103515245 + 12345, std::memory_order_relaxed); return ((next >> 24) & kSpinsMax) | kSpinsMin; } // This function name breaks naming paradigms so that it shows up prominently in stack traces. As the name implies, this // function waits until f() returns true. template <class Func> void __CONTENDED_WAIT__(Func&& f) noexcept(noexcept(f())) { thread::AtomicBackoff<> backoff; while (CARB_UNLIKELY(!f())) backoff.pause(); } } // namespace detail #endif /** * Returns the native handle for the current thread. * * @note Windows: This handle is not unique to the thread but instead is a pseudo-handle representing "current thread". * To obtain a unique handle to the current thread, use the Windows API function `DuplicateHandle()`. * * @return The native handle for the current thread. */ inline thread::NativeHandleType get() { #if CARB_PLATFORM_WINDOWS return ::GetCurrentThread(); #elif CARB_POSIX return pthread_self(); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Returns the ID of the currently executing process. * @returns The current ID of the process. */ CARB_DEPRECATED("Use this_process::getId() instead") static inline thread::ProcessId getProcessId() { return this_process::getId(); } /** * 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. */ CARB_DEPRECATED("Use this_process::getIdCached() instead") static inline thread::ProcessId getProcessIdCached() { return this_process::getIdCached(); } /** * Retrieve the thread ID for the current thread. * @return The thread ID for the current thread. */ inline thread::ThreadId getId() { #if CARB_PLATFORM_WINDOWS return thread::ThreadId(::GetCurrentThreadId()); #elif CARB_PLATFORM_LINUX // This value is stored internally within the pthread_t, but this is opaque and there is no public API for // retrieving it. Therefore, we can only do this for the current thread. // NOTE: We do not store this in a thread_local because on older versions of glibc (especially 2.17, which is what // Centos7 uses), this will require a lock that is also shared with loading shared libraries, which can cause a // deadlock. thread::ThreadId tid = (thread::ThreadId)(pid_t)syscall(SYS_gettid); return tid; #elif CARB_PLATFORM_MACOS return thread::ThreadId(pthread_mach_thread_np(pthread_self())); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Sets the name for the current thread. * * @note The length of the name is limited by the system and may be truncated. * * @param name The desired name for the current thread. */ inline void setName(const char* name) { thread::setName(get(), name); } /** * Retrieves the name of the current thread. * * @return The name of the current thread. */ inline std::string getName() { return thread::getName(get()); } /** * Sets the affinity of the current thread. * * Each bit represents a logical CPU; bit 0 for CPU 0, bit 1 for CPU 1, etc. * * @note This function is limited to the first 64 CPUs in a system. * * @param mask The bitmask representing the desired CPU affinity. Zero (no bits set) is ignored. */ inline void setAffinity(size_t mask) { thread::setAffinity(get(), mask); } /** * Sets the CPU Affinity for the current thread. * * On Windows each entry in the CpuMaskVector represents a Processor Group. Each thread can only belong to a single * Processor Group, so this function will only set the CPU Affinity to the first non-zero entry in the provided * CpuMaskVector. That is to say, if both \c masks[0] and \c masks[1] have bits sets, only the CPUs in \c masks[0] * will be set for the affinity. * * On Linux, the CpuMaskVector is analogous to a cpu_set_t. There are no restrictions on the number of CPUs that the * affinity mask can contain. * * @param masks Affinity masks to set. * * @return True if the function succeeded, false otherwise. If \c masks is empty, or has no bits set, false will be * returned. If the underlying function for setting affinity failed, then \c errno or \c last-error will be set. */ inline bool setAffinity(const thread::CpuMaskVector& masks) { return thread::setAffinity(get(), masks); } /** * Gets the current CPU Affinity for the current thread. * * On Windows each entry in the CpuMaskVector represents a Processor Group. * On Linux, the CpuMaskVector is analogous to a cpu_set_t. * * @return A CpuMaskVector containing the cpu affinities for the thread. If the underlying functions to get thread * affinity return an error, the returned CpuMaskVector will be empty and \c errno or \c last-error will be set. */ inline thread::CpuMaskVector getAffinity() { return thread::getAffinity(get()); } /** * Calls a predicate repeatedly until it returns \c true. * * This function is recommended only for situations where exactly one thread is waiting on another thread. For multiple * threads waiting on a predicate, use \ref spinWaitWithBackoff(). * * @param f The predicate to call repeatedly until it returns `true`. */ template <class Func> void spinWait(Func&& f) noexcept(noexcept(f())) { while (!CARB_LIKELY(f())) { CARB_HARDWARE_PAUSE(); } } /** * Calls a predicate until it returns true with progressively increasing delays between calls. * * This function is a low-level utility for high-contention cases where multiple threads will be calling @p f * simultaneously, @p f needs to succeed (return `true`) before continuing, but @p f will only succeed for one thread at * a time. This function does not return until @p f returns `true`, at which point this function returns immediately. * High contention is assumed when @p f returns `false` for several calls, at which point the calling thread will * progressively sleep between bursts of calls to @p f. This is a back-off mechanism to allow one thread to move forward * while other competing threads wait their turn. * * @param f The predicate to call repeatedly until it returns `true`. */ template <class Func> void spinWaitWithBackoff(Func&& f) noexcept(noexcept(f())) { if (CARB_UNLIKELY(!f())) { detail::__CONTENDED_WAIT__(std::forward<Func>(f)); } } /** * Calls a predicate until it returns true or a random number of attempts have elapsed. * * This function is a low-level utility for high-contention cases where multiple threads will be calling @p f * simultaneously, and @p f needs to succeed (return `true`) before continuing, but @p f will only succeed for one * thread at a time. This function picks a pseudo-random maximum number of times to call the function (the randomness is * so that multiple threads will not choose the same number and perpetually block each other) and repeatedly calls the * function that number of times. If @p f returns `true`, spinTryWait() immediately returns `true`. * * @param f The predicate to call repeatedly until it returns `true`. * @returns `true` immediately when @p f returns `true`. If a random number of attempts to call @p f all return `false` * then `false` is returned. */ template <class Func> bool spinTryWait(Func&& f) noexcept(noexcept(f())) { thread::AtomicBackoff<> backoff; while (CARB_UNLIKELY(!f())) if (!backoff.pauseWithoutYield()) return false; return true; } /** * A replacement function for `std::atomic_thread_fence(std::memory_order_seq_cst)` that performs better on some older * compilers. */ inline void atomic_fence_seq_cst() noexcept { #if CARB_X86_64 && CARB_COMPILER_GNUC && __GNUC__ < 11 // On x86_64 CPUs we can use any lock-prefixed instruction as a StoreLoad operation to achieve sequential // consistency (see https://shipilev.net/blog/2014/on-the-fence-with-dependencies/). The 'notb' instruction here has // the added benefit of not affecting flags or other registers (see https://www.felixcloutier.com/x86/not). // It is also likely that our 'unused' variable at the top of the stack is in L1 cache. unsigned char unused{}; __asm__ __volatile__("lock; notb %0" : "+m"(unused)::"memory"); #else std::atomic_thread_fence(std::memory_order_seq_cst); #endif } } // namespace this_thread } // namespace carb
27,229
C
31.455304
120
0.676705
omniverse-code/kit/include/carb/thread/RecursiveSharedMutex.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 Recursive Shared Mutex implementation. #pragma once #include "SharedMutex.h" #include "ThreadLocal.h" #include <algorithm> #include <vector> namespace carb { namespace thread { #ifndef DOXYGEN_SHOULD_SKIP_THIS class recursive_shared_mutex; namespace detail { using LockEntry = std::pair<recursive_shared_mutex*, ptrdiff_t>; using LockList = std::vector<LockEntry>; // TL;DR: Gymnastics to get around SIOF (Static Initialization Order Fiasco) with supported compilers // // For GCC this is pretty easy. The init_priority attribute allows us to specify a priority value to use for // initialization order. For recursive_shared_mutex's lockList, we really only care that it's constructed before // application initializers run. // // We have to jump through some hoops here for MSVC since this is a header-only class. MSVC does have pragma init_seg, // BUT a given translation unit (i.e. cpp files) may have only one. Since this exists as a header-only class and we // don't want to force linkage of a cpp file specifically for this, we can get around it by injecting our initializer // function into the appropriate segment for initializer order at link time. // // This is a fairly good reference for the various C-Runtime initializer sections: // https://gist.github.com/vaualbus/622099d88334fbba1d4ae703642c2956 // // #pragma init_seg(lib) corresponds to section .CRT$XCL (the L seems to indicate `lib`). Ironically, C=compiler, // L=lib, and U=user are also in alphabetical order and make nice delimiters between .CRT$XCA (__xc_a) and .CRT$XCZ // (__xc_z). # if CARB_COMPILER_MSC // If we just specified a variable of type carb::thread::ThreadLocal<LockList> (even allocating it into a specific // custom section) the compiler will still try to instantiate it during the init_seg(user) order. To circumvent this // behavior, we instead contain this variable inside `DataContainer`, but are careful to have the DataContainer() // constructor well defined with zero side-effects. This is because constructLockList() will be called first (during the // compiler's init_seg(lib) initialization order), which will construct the TLS member inside of DataContainer, but the // DataContainer() constructor for lockListData runs after (during the compiler's init_seg(user) initialization order). // clang-format off // (for brevity) struct DataContainer { struct DummyType { constexpr DummyType() noexcept {} }; union { DummyType empty; carb::thread::ThreadLocal<LockList> tls; }; constexpr DataContainer() noexcept : empty() {} ~DataContainer() noexcept {} } __declspec(selectany) lockListData; // clang-format on __declspec(selectany) bool constructed{ false }; inline carb::thread::ThreadLocal<LockList>& lockList() noexcept { // Should have been constructed with either pConstructLockList (initializer) or ensureLockList() CARB_ASSERT(constructed); return lockListData.tls; } inline void constructLockList() noexcept { // Construct the lock list and then register a function to destroy it at exit time CARB_ASSERT(!constructed); new (&lockListData.tls) carb::thread::ThreadLocal<LockList>(); constructed = true; ::atexit([] { lockList().~ThreadLocal(); constructed = false; }); } inline void ensureLockList() noexcept { // OVCC-1298: With LTCG turned on sometimes the linker doesn't obey the segment information below and puts // pConstructLockList that is supposed to construct the lock list into the wrong segment, not in the initializer // list. Which means it gets skipped at startup. As a work-around we can construct it when the // recursive_shared_mutex constructor is called, though this may be late and cause SIOF issues (see OM-18917). if (CARB_UNLIKELY(!constructed)) { static std::once_flag flag; std::call_once(flag, [] { if (!constructed) constructLockList(); }); CARB_ASSERT(constructed); } } extern "C" { // Declare these so the linker knows to include them using CRTConstructor = void(__cdecl*)(); extern CRTConstructor __xc_a[], __xc_z[]; // Force the linker to include this symbol # pragma comment(linker, "/include:pConstructLockList") // Inject a pointer to our constructLockList() function at XCL, the same section that #pragma init_seg(lib) uses # pragma section(".CRT$XCL", long, read) __declspec(allocate(".CRT$XCL")) __declspec(selectany) CRTConstructor pConstructLockList = constructLockList; } # else // According to this GCC bug: https://gcc.gnu.org/bugzilla//show_bug.cgi?id=65115 // The default priority if init_priority is not specified is 65535. So we use one value lower than that. # define DEFAULT_INIT_PRIORITY (65535) # define LIBRARY_INIT_PRIORITY (DEFAULT_INIT_PRIORITY - 1) struct Constructed { bool constructed; constexpr Constructed() : constructed{ true } { } ~Constructed() { constructed = false; } explicit operator bool() const { return constructed; } } constructed CARB_ATTRIBUTE(weak, init_priority(LIBRARY_INIT_PRIORITY)); carb::thread::ThreadLocal<LockList> lockListTls CARB_ATTRIBUTE(weak, init_priority(LIBRARY_INIT_PRIORITY)); inline carb::thread::ThreadLocal<LockList>& lockList() { CARB_ASSERT(constructed); return lockListTls; } constexpr inline void ensureLockList() noexcept { } # endif } // namespace detail #endif /** * A recursive shared mutex. Similar to `std::shared_mutex` or carb::thread::shared_mutex, but can be used recursively. * * This primitive supports lock conversion: If a thread already holds one or more shared locks and attempts to take an * exclusive lock, the shared locks are released and the same number of exclusive locks are added. However, this is not * done atomically. @see recursive_shared_mutex::lock() for more info. * * A single thread-local storage entry is used to track the list of recursive_shared_mutex objects that a thread has * locked and their recursive lock depth. However, as this is a header-only class, all modules that use this class will * allocate their own thread-local storage entry. */ class recursive_shared_mutex : private carb::thread::shared_mutex { public: /** * Constructor. */ #if !CARB_DEBUG && !CARB_COMPILER_MSC constexpr #endif recursive_shared_mutex() { detail::ensureLockList(); } /** * Destructor. * * Debug builds assert that the mutex is not busy (locked) when destroyed. */ ~recursive_shared_mutex() = default; /** * 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. * * @note If the calling thread has taken shared locks on this mutex, all of the shared locks are converted to * exclusive locks. * * @warning If existing shared locks must be converted to exclusive locks, the mutex must convert these shared locks * to exclusive locks. In order to do this, it must first release all shared locks which potentially allows another * thread to gain exclusive access and modify the shared resource. Therefore, any time an exclusive lock is taken, * assume that the shared resource may have been modified, even if the calling thread held a shared lock before. */ void lock(); /** * Attempts to immediately take an exclusive lock, but will not block if one cannot be obtained. * * @note If the calling thread has taken shared locks on this mutex, `false` is returned and no attempt to convert * the locks is made. If the calling thread already has an exclusive lock on this mutex, `true` is always returned. * * @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 either a single shared or exclusive lock on this mutex. Synonymous with unlock_shared(). * * @note If the calling thread has recursively locked this mutex, unlock() will need to be called symmetrically for * each call to a successful locking function. * * @warning `std::terminate()` will be called if the calling thread does not have the mutex locked. */ 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. * * @note If the calling thread already owns an exclusive lock, then calling lock_shared() will actually increase the * exclusive lock count. */ void lock_shared(); /** * Attempts to immediately take a shared lock, but will not block if one cannot be obtained. * * @note If the calling thread already owns an exclusive lock, then calling try_lock_shared() will always return * `true` and will actually increase the exclusive lock count. * * @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 either a single shared or exclusive lock on this mutex. Synonymous with unlock(). * * @note If the calling thread has recursively locked this mutex, unlock() or unlock_shared() will need to be called * symmetrically for each call to a successful locking function. * * @warning `std::terminate()` will be called if calling thread does not have the mutex locked. */ void unlock_shared(); /** * Returns true if the calling thread owns the lock. * @note Use \ref owns_lock_shared() or \ref owns_lock_exclusive() for a more specific check. * @returns `true` if the calling thread owns the lock, either exclusively or shared; `false` otherwise. */ bool owns_lock() const; /** * Returns true if the calling thread owns a shared lock. * @returns `true` if the calling thread owns a shared lock; `false` otherwise. */ bool owns_lock_shared() const; /** * Returns true if the calling thread owns an exclusive lock. * @returns `true` if the calling thread owns an exclusive lock; `false` otherwise. */ bool owns_lock_exclusive() const; private: const detail::LockEntry* hasLockEntry() const { auto& list = detail::lockList().get(); auto iter = std::find_if(list.begin(), list.end(), [this](detail::LockEntry& e) { return e.first == this; }); return iter == list.end() ? nullptr : std::addressof(*iter); } detail::LockEntry& lockEntry() { auto& list = detail::lockList().get(); auto iter = std::find_if(list.begin(), list.end(), [this](detail::LockEntry& e) { return e.first == this; }); if (iter == list.end()) iter = (list.emplace_back(this, 0), list.end() - 1); return *iter; } void removeLockEntry(detail::LockEntry& e) { auto& list = detail::lockList().get(); CARB_ASSERT(std::addressof(e) >= std::addressof(list.front()) && std::addressof(e) <= std::addressof(list.back())); e = list.back(); list.pop_back(); } }; // Function implementations inline void recursive_shared_mutex::lock() { detail::LockEntry& e = lockEntry(); if (e.second < 0) { // Already locked exclusively (negative lock count). Increase the negative count. --e.second; } else { if (e.second > 0) { // This thread already has shared locks for this lock. We need to convert to exclusive. shared_mutex::unlock_shared(); } // Acquire the lock exclusively shared_mutex::lock(); // Now inside the lock e.second = -(e.second + 1); } } inline bool recursive_shared_mutex::try_lock() { detail::LockEntry& e = lockEntry(); if (e.second < 0) { // Already locked exclusively (negative lock count). Increase the negative count. --e.second; return true; } else if (e.second == 0) { if (shared_mutex::try_lock()) { // Inside the lock e.second = -1; return true; } // Lock failed removeLockEntry(e); } // Either we already have shared locks (that can't be converted to exclusive without releasing the lock and possibly // not being able to acquire it again) or the try_lock failed. return false; } inline void recursive_shared_mutex::unlock() { detail::LockEntry& e = lockEntry(); CARB_CHECK(e.second != 0); if (e.second > 0) { if (--e.second == 0) { shared_mutex::unlock_shared(); removeLockEntry(e); } } else if (e.second < 0) { if (++e.second == 0) { shared_mutex::unlock(); removeLockEntry(e); } } else { // unlock() without being locked! std::terminate(); } } inline void recursive_shared_mutex::lock_shared() { detail::LockEntry& e = lockEntry(); if (e.second < 0) { // We already own an exclusive lock, which is stronger than shared. So just increase the exclusive lock. --e.second; } else { if (e.second == 0) { shared_mutex::lock_shared(); // Now inside the lock } ++e.second; } } inline bool recursive_shared_mutex::try_lock_shared() { detail::LockEntry& e = lockEntry(); if (e.second < 0) { // We already own an exclusive lock, which is stronger than shared. So just increase the exclusive lock. --e.second; return true; } else if (e.second == 0 && !shared_mutex::try_lock_shared()) { // Failed to get the shared lock removeLockEntry(e); return false; } ++e.second; return true; } inline void recursive_shared_mutex::unlock_shared() { unlock(); } inline bool recursive_shared_mutex::owns_lock() const { auto entry = hasLockEntry(); return entry ? entry->second != 0 : false; } inline bool recursive_shared_mutex::owns_lock_exclusive() const { auto entry = hasLockEntry(); return entry ? entry->second < 0 : false; } inline bool recursive_shared_mutex::owns_lock_shared() const { auto entry = hasLockEntry(); return entry ? entry->second > 0 : false; } } // namespace thread } // namespace carb
15,467
C
33.916478
123
0.666128
omniverse-code/kit/include/carb/l10n/IL10n.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 L10n interface. */ #pragma once #include "../Defines.h" #include "../logging/Log.h" namespace carb { /** Utilities for localizing text. */ namespace l10n { /** The return type for @ref IL10n::getHashFromKeyString(). */ using StringIdentifier = uint64_t; /** An opaque struct representing a localization table. */ struct LanguageTable { }; /** An opaque struct representing a language ID. */ struct LanguageIdentifier { }; /** Use the main language table for the process if this is passed. */ const LanguageTable* const kLanguageTableMain = nullptr; /** The currently set language will be used when this is passed. */ const LanguageIdentifier* const kLanguageCurrent = nullptr; /** The entry point to getLocalizedStringFromHash(). * @copydoc IL10n::getLocalizedStringFromHash */ using localizeStringFn = const char*(CARB_ABI*)(const LanguageTable* table, StringIdentifier id, const LanguageIdentifier* language); /** The default language will be used when this is passed. * The default language will always be US English. */ const LanguageIdentifier* const kLanguageDefault = reinterpret_cast<const LanguageIdentifier*>(0xFFFFFFFFFFFFFFFF); /** This is returned from some interface functions when an unknown language is * requested. */ const LanguageIdentifier* const kLanguageUnknown = reinterpret_cast<const LanguageIdentifier*>(0xFFFFFFFFFFFFFFFE); /** A definition that can be used for loading a language table embedded in C++ code. */ struct LanguageTableData { /** The number of languages in the table. */ size_t languagesLength; /** The number of translation entries in the table. * Any valid language table will have at least 4 rows, since the first 4 * rows have special meanings. */ size_t keysLength; /** The list of translation languages. These are specified as POSIX locale identifiers. * The length of this array is @ref languagesLength. * The first language in this array must be "en_US*" */ const char* const* languages; /** The hashes of the key strings for the translations. * The length of this array is @ref keysLength. * Note that this contains keys for the first 4 rows in the table, even * though the first 4 rows have a special purpose. The first 4 keys are * never read. */ const uint64_t* keys; /** The translation table. * This is a matrix with @ref languagesLength columns and @ref keysLength rows. * languageTable[i][j] refers to the translation of keys[i] in languages[j]. * The first 4 rows have special usages: * 0: The language names for each column in US English * 1: The territory names for each column in US English * 2: The language names for each column in the language for that column * 3: The territory names for each column in the language for that column */ const char* const* languageTable; }; /** Boolean value tags for the getLanguageName() and getTerritoryName() * functions. These determine how the language and territory names will be * returned. Note, returning the name of the language in any other arbitrary * supported language is beyond the scope of the automatic behavior of the * tables. If such an arbitrary translation is needed, the language's name * would have to be added to each table and translated into each target * language. Accessing the arbitrary translations in that case would end up * as a lookupString() call. */ enum class LocalizedName { /** Retrieve the name in US English (ie: "Polish"). Note that this will * always be the first or second string entries in any given translation * table. */ eUsEnglish, /** Retrieve the name in the language the identifier specifies (ie: * "Polski"). Note that this will always be the third or fourth string * entries in any given translation table. */ eLocalized, }; /** The localization interface. */ struct IL10n { CARB_PLUGIN_INTERFACE("carb::l10n::IL10n", 1, 0) /** Calculates the lookup hash for a US English key string. * * @param[in] keyString The string to calculate the hash identifier for. * This may not be nullptr or an empty string. * @returns The calculated hash of the string. This will be the same * algorithm that is used by the `String Table Conversion Tool` * to generate the table and mapping structure. * @returns 0 if the input string is nullptr or empty. * * @remarks This calculates the hash value for a string. This is useful * for scripts to be able to pre-hash and cache their string * identifiers for quicker lookups later. * * @note This is not intended to be directly used in most situations. * Typical C++ code should use CARB_LOCALIZE() and typical python * code should use carb_localize() or carb_localize_hashed(). */ StringIdentifier(CARB_ABI* getHashFromKeyString)(const char* keyString) noexcept; /** Looks up a string's translation in the localization system. * * @param[in] table The optional local language table to search first * for the requested key string. If this is * non-nullptr and the key string is not found in this * table or the requested language is not supported by * this table, the framework's registered main table * will be checked as well. This may be nullptr to * only search the framework's main table. * @param[in] id The hashed string identifier of the string to look * up. * @param[in] language The language to retrieve the translated string in. * This may be set to @ref kLanguageCurrent to use the * current language for the localization system (this * is the default behavior). This can also be any * specific language identifier to retrieve the string * in another supported language. This may also be * @ref kLanguageDefault to retrieve the string in the * system's default language if a translation is * available. * @returns The translated string is a supported language is requested and * the string with the requested hash is found in the table. * @returns nullptr if no translation is found in the table, if an * unsupported language is requested, or if the key string has no * mapping in the table. * @returns An error message if the config setting to return noticeable * failure strings is enabled. * * @note This is not intended to be directly used in most situations. * Typical C++ code should use CARB_LOCALIZE() and typical python * code should use carb_localize() or carb_localize_hashed(). */ const char*(CARB_ABI* getLocalizedStringFromHash)(const LanguageTable* table, StringIdentifier id, const LanguageIdentifier* language) noexcept; /** Retrieves the current system locale information. * * @returns A language identifier for the current system language if it * matches one or more of the supported translation tables. * @returns The language identifier for US English if no matching * translation tables are found. */ const LanguageIdentifier*(CARB_ABI* getSystemLanguage)() noexcept; /** Enumerates available/supported language identifiers in the localization system. * * @param[in] table The optional local table to also search for unique * language identifiers to return. If this is * non-nullptr, the supported language identifiers in * this table will be enumerated first, followed by any * new unique language identifiers in the framework's * registered main table. This may be nullptr to only * enumerate identifiers in the main table. * @param[in] index The index of the language identifier number to be * returned. Set this to 0 to retrieve the first * supported language (this will always return the * language identifier corresponding to US English as the * first supported language identifier). Set this to * increasing consecutive indices to retrieve following * supported language codes. * @returns The language identifier corresponding to the supported * language at index @p index. * @retval kLanguageUnknown if the given index is out of range of * the supported languages. */ const LanguageIdentifier*(CARB_ABI* enumLanguageIdentifiers)(const LanguageTable* table, size_t index) noexcept; /** Retrieves the language identifier for a given locale name. * * @param[in] table The optional local table to also search for a * matching language identifier in. This may be * nullptr to only search the framework's 'main' * table. * @param[in] language The standard Unix locale name in the format * "<language>_<territory>" where "<language>" is a * two character ISO-639-1 language code and * "<territory>" is a two-character ISO-3166-1 * Alpha-2 territory code. An optional encoding * string may follow this but will be ignored. This * must not be nullptr or an empty string. * @returns The language identifier corresponding to the selected Unix * locale name if a table for the requested language and * territory is found. If multiple matching supported tables are * found for the requested language (ie: Canadian French, France * French, Swiss French, etc), the one for the matching territory * will be returned instead. If no table exists for the * requested territory in the given language, the language * identifier for an arbitrary table for the requested language * will be returned instead. This behavior may be modified by a * runtime config setting that instead causes @ref * kLanguageUnknown to be returned if no exact language/territory * match exists. * @retval kLanguageUnknown if the requested language does not have * a translation table for it in the localization system, or if * the config setting to only allow exact matches is enabled and * no exact language/territory match could be found. */ const LanguageIdentifier*(CARB_ABI* getLanguageIdentifier)(const LanguageTable* table, const char* language) noexcept; /** Retrieves a language's or territory's name as a friendly string. * * @param[in] table The optional local language table to check for * the requested name first. If this is nullptr * or the requested language identifier is not * supported by the given table, the framework's * main registered table will be checked. * @param[in] language The language identifier of the language or * territory name to retrieve. This may not be * @ref kLanguageUnknown. This may be @ref * kLanguageCurrent to retrieve the name for the * currently selected language. * @param[in] retrieveIn The language to return the string in. This can * be used to force the language's or territory's * name to be returned in US English or the name * of @p language in @p language. * @returns The name of the language or territory in the specified * localization. * @returns An empty string if the no translation table exists for the * requested language or an invalid language identifier is given. * @returns An error message if the config setting to return noticeable * failure strings is enabled. * * @note This will simply return the strings in the second and third, or * fourth and fifth rows of the CSV table (which should have become * properties of the table once loaded). */ const char*(CARB_ABI* getLanguageName)(const LanguageTable* table, const LanguageIdentifier* language, LocalizedName retrieveIn) noexcept; /** @copydoc getLanguageName */ const char*(CARB_ABI* getTerritoryName)(const LanguageTable* table, const LanguageIdentifier* language, LocalizedName retrieveIn) noexcept; /** Retrieves the standard Unix locale name for the requested language identifier. * * @param[in] table The optional local language table to retrieve the * locale identifier from. This may be nullptr to * only search the framework's registered main * language table. * @param[in] language The language identifier to retrieve the Unix locale * name for. This may not be @ref kLanguageUnknown. * This may be @ref kLanguageCurrent to retrieve the * locale name for the currently selected language. * @returns The standard Unix locale name for the requested language * identifier. * @returns an empty string if the language identifier is invalid or no translation table exist * for it. * @returns an error message if the config setting to return noticeable failure string is * enabled. */ const char*(CARB_ABI* getLocaleIdentifierName)(const LanguageTable* table, const LanguageIdentifier* language) noexcept; /** Sets the new current language from a standard Unix locale name or language identifier. * * @param[in] table The optional local language table to check to see * if the requested language is supported or not. * This may be nullptr to only search the framework's * registered main table. If the local table doesn't * support the requested language, the framework's * main table will still be searched. * @param[in] language Either the locale name or identifier for the new * language to set as current for the calling process. * For the string version, this may be nullptr or an * empty string to switch back to the system default * language. For the language identifier version, * this may be set to @ref kLanguageDefault to switch * back to the system default language. * @returns true if the requested language is supported and is * successfully set. * @returns false if the requested language is not supported. * In this case, the current language will not be modified. * * @note the variant that takes a string locale identifier will just be a * convenience helper function that first looks up the language * identifier for the locale then passes it to the other variant. * If the locale lookup fails, the call will fail since it would be * requesting an unsupported language. */ bool(CARB_ABI* setCurrentLanguage)(const LanguageTable* table, const LanguageIdentifier* language) noexcept; /** @copydoc setCurrentLanguage */ bool(CARB_ABI* setCurrentLanguageFromString)(const LanguageTable* table, const char* language) noexcept; /** Retrieves the language identifier for the current language. * * @returns The identifier for the current language. * @retval kLanguageDefault if an error occurs. */ const LanguageIdentifier*(CARB_ABI* getCurrentLanguage)() noexcept; /** Registers the host app's main language translation table. * * @param[in] table The table to register as the app's main lookup table. * This may be nullptr to indicate that no language table * should be used and that only US English strings will * be used by the app. * @returns true if the new main language table is successfully set. * @returns false if the new main language table could not be set. * * @note This is a per-process setting. */ bool(CARB_ABI* setMainLanguageTable)(const LanguageTable* table) noexcept; /** Creates a new local language translation table. * * @param[in] data The language table to load. * This language table must remain valid and constant * until unloadLanguageTable() is called. * The intended use of this function is to load a static * constant data table. * @returns The newly loaded and created language table if the data file * exists and was successfully loaded. This must be destroyed * with unloadLanguageTable() when it is no longer needed. * @returns nullptr if an unrecoverable error occurred. */ LanguageTable*(CARB_ABI* loadLanguageTable)(const LanguageTableData* data) noexcept; /** Creates a new local language translation table from a data file. * * @param[in] filename The name of the data file to load as a language * translation table. This may not be nullptr or an * empty string. If this does not have an extension, * both the given filename and one ending in ".lang" * will be tried. * @returns The newly loaded and created language table if the data file * exists and was successfully loaded. This must be destroyed * with unloadLanguageTable() when it is no longer needed. * @returns nullptr if the data file was not found with or without the * ".lang" extension, or the file was detected as corrupt while * loading. * * @note The format of the localization file is as follows: * byte count | segment description * [0-13] | File signature. The exact UTF-8 text: "nvlocalization". * [14-15] | File format version. Current version is 00. * | This version number is 2 hex characters. * [16-19] | Number of languages. * | This corresponds to @ref LanguageTableData::languagesLength. * [20-23] | Number of keys. * | This corresponds to @ref LanguageTableData::keysLength. * [24-..] | Table of @ref LanguageTableData::keysLength 64 bit keys. * | This is @ref LanguageTableData::keysLength * 8 bytes long. * | This corresponds to @ref LanguageTableData::keys. * [..-..] | Block of @ref LanguageTableData::languagesLength null * | terminated language names. * | This will contain exactly @ref LanguageTableData::languagesLength * | 0x00 bytes; each of those bytes indicates the end of a string. * | The length of this segment depends on the data within it; * | the full segment must be read to find the start of the * | next section. * | This corresponds to @ref LanguageTableData::languages. * [..-..] | Block of @ref LanguageTableData::languagesLength * * | @ref LanguageTableData::keysLength * | null terminated translations. * | This will contain exactly @ref LanguageTableData::languagesLength * * | @ref LanguageTableData::keysLength 0x00 bytes; each of those bytes * | indicates the end of a string. * | The last byte of the file should be the null terminator of the last * | string in the file. * | The length of this section also depends on the length of * | the data contained within these strings. * | If the end of the file is past the final 0x00 byte in this * | segment, the reader will assume the file is corrupt. * | This corresponds to @ref LanguageTableData::languageTable. */ LanguageTable*(CARB_ABI* loadLanguageTableFromFile)(const char* fileName) noexcept; /** The language table to be destroyed. * * @param[in] table The language table to be destroyed. * This must not be nullptr. * This should be a table that was previously returned * from loadLanguageTable(). * It is the caller's responsibility to ensure this table * will no longer be needed or accessed. */ void(CARB_ABI* unloadLanguageTable)(LanguageTable* table) noexcept; /** Sets the current search path for finding localization files for a module. * * @param[in] searchPath The search path for where to look for * localization data files. * This can be an absolute or relative path. * @returns true if the new search path is successfully set. * @returns false if the new search path could not be set. * * @remarks This sets the search path to use for finding localization * files when modules load. By default, only the same directory * as the loaded module or script will be searched. This can be * used to specify additional directories to search for * localization files in. For example, the localization files * may be stored in the 'lang/' folder for the app instead of in * the 'bin/' folder. */ bool(CARB_ABI* addLanguageSearchPath)(const char* searchPath) noexcept; /** Sets the current search path for finding localization files for a module. * * @param[in] searchPath The search path to remove from the search path * list. * @returns true if the search path was successfully removed. * @returns false if the search path was not found. * * @remarks This removes a search path added by addLanguageSearchPath(). * If the same path was added multiple times, it will have to be * removed multiple times. * * @note The executable directory can be removed from the search path * list, if that is desired. */ bool(CARB_ABI* removeLanguageSearchPath)(const char* searchPath) noexcept; /** Enumerate the search paths that are currently set. * @param[in] index The index of the search path to retrieve. * The first search path index will always be 0. * The valid search paths are a contiguous range of * indices, so the caller can pass incrementing values * beginning at 0 for @p index to enumerate all of the * search paths. * * @returns The search path corresponding to @p index if one exists at index. * @returns nullptr if there is no search path corresponding to @p index. * * @remarks The example usage of this function would be to call this in a * loop where @p index starts at 0 and increments until a call to * enumLanguageSearchPaths(@p index) returns nullptr. This would * enumerate all search paths that are currently set. * The index is no longer valid if the search path list has been * modified. */ const char*(CARB_ABI* enumLanguageSearchPaths)(size_t index) noexcept; }; /** A version of getLocalizedStringFromHash() for when the localization plugin is unloaded. * @param[in] table The localization table to use for the lookup. * @param[in] id The hash of @p string. * @param[in] language The language to perform the lookup in. * @returns nullptr. */ inline const char* CARB_ABI getLocalizedStringFromHashNoPlugin(const LanguageTable* table, StringIdentifier id, const LanguageIdentifier* language) noexcept { CARB_UNUSED(table, id, language); CARB_LOG_ERROR("localization is being used with carb.l10n.plugin not loaded"); return nullptr; } } // namespace l10n } // namespace carb /** Pointer to the interface for use from CARB_LOCALIZE(). Defined in @ref CARB_LOCALIZATION_GLOBALS. */ CARB_WEAKLINK CARB_HIDDEN carb::l10n::IL10n* g_carbLocalization; /** Pointer to the function called by CARB_LOCALIZE(). Defined in @ref CARB_LOCALIZATION_GLOBALS. */ CARB_WEAKLINK CARB_HIDDEN carb::l10n::localizeStringFn g_localizationFn = carb::l10n::getLocalizedStringFromHashNoPlugin; /* Exhale can't handle these for some reason and they aren't meant to be used directly */ #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace carb { namespace l10n { /** An internal helper for CARB_LOCALIZE() * @param[in] id The hash of @p string. * @param[in] string The localization keystring. * @returns The translated string is a supported language is requested and * the string with the requested hash is found in the table. * @returns @p string if no translation is found in the table, if an * unsupported language is requested, or if the key string has no * mapping in the table. * @returns An error message if the config setting to return noticeable * failure strings is enabled. * * @note This is an internal implementation for CARB_LOCALIZE() as well as the * script bindings. Do not directly call this function. */ inline const char* getLocalizedString(StringIdentifier id, const char* string) noexcept { const char* s = g_localizationFn(kLanguageTableMain, id, kLanguageCurrent); return (s != nullptr) ? s : string; } } // namespace l10n } // namespace carb #endif /** Look up a string from the localization database for the current plugin. * @param string A string literal. * This must not be nullptr. * This is the key string to look up in the database. * * @returns The localized string for the keystring @p string, given the current * localization that has been set for the process. * @returns If there is no localized string for the given keystring @p string, * the US English string will be returned. * @returns If @p string is not found in the localization database at all, * @p string will be returned. * @returns An error message if the localized string is found and the config * setting to return noticeable failure strings is enabled. */ #define CARB_LOCALIZE(string) carb::l10n::getLocalizedString(CARB_HASH_STRING(string), string)
29,066
C
51.467509
122
0.617113
omniverse-code/kit/include/carb/l10n/L10nUtils.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 L10n interface. */ #pragma once #include "../Framework.h" #include "IL10n.h" /** Placeholder for global scope work that needs to be done for localization. Do not call * this directly. This is called by @ref CARB_GLOBALS(). */ #define CARB_LOCALIZATION_GLOBALS() namespace carb { namespace l10n { /** Called during client initialization to obtain the globals needed for localization. */ inline void registerLocalizationForClient() noexcept { g_carbLocalization = getFramework()->tryAcquireInterface<IL10n>(); if (g_carbLocalization != nullptr) g_localizationFn = g_carbLocalization->getLocalizedStringFromHash; } /** Called during client shutdown to clear out the global state. */ inline void deregisterLocalizationForClient() noexcept { g_carbLocalization = nullptr; g_localizationFn = carb::l10n::getLocalizedStringFromHashNoPlugin; } } // namespace l10n } // namespace carb
1,378
C
28.97826
90
0.755443
omniverse-code/kit/include/carb/l10n/L10nBindingsPython.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 "IL10n.h" #include "L10nUtils.h" namespace carb { namespace l10n { inline void definePythonModule(py::module& m) { m.doc() = "pybind11 carb.l10n bindings"; py::class_<LanguageTable>(m, "LanguageTable"); py::class_<LanguageIdentifier>(m, "LanguageIdentifier"); m.def("register_for_client", carb::l10n::registerLocalizationForClient, R"(Register the l10n plugin for the current client. This must be called before using any of the localization plugins, if carb::startupFramework() has not been called. This use case is only encountered in the tests. Standard Carbonite applications call carb::startupFramework() so they should never have to call this. If this is not called, the localization system will be non-functional.)", py::call_guard<py::gil_scoped_release>()); m.def("deregister_localization_for_client", carb::l10n::deregisterLocalizationForClient, R"(Deregister the localization plugin for the current client. This can be called to deregister the localization plugin for the current client, if carb::shutdownFramework will not be called.)", py::call_guard<py::gil_scoped_release>()); m.def("get_localized_string", [](const char* string) { return carb::l10n::getLocalizedString( (g_carbLocalization == nullptr) ? 0 : g_carbLocalization->getHashFromKeyString(string), string); }, R"(Retrieve a string from the localization database, given its hash. This function retrieves a localized string based on the hash of the keystring. This should be used on all strings found in the UI, so that they can automatically be shown in the correct language. Strings returned from this function should never be cached, so that changing the language at runtime will not result in stale strings being shown in the UI. Args: string: The keystring that identifies the set of localized strings to return. This will typically correspond to the US English string for this UI text. This string will be returned if there is no localization table entry for this key. Returns: The localized string for the input hash in the currently set language, if a string exists for that language. If no localized string from the currently set language exists for the hash, the US English string will be returned. If the hash is not found in the localization database, the string parameter will be returned. Alternatively, if a config setting is enabled, error messages will be returned in this case.)", py::call_guard<py::gil_scoped_release>()); m.def("get_hash_from_key_string", [](const char* string) { return (g_carbLocalization == nullptr) ? 0 : g_carbLocalization->getHashFromKeyString(string); }, R"(Hash a keystring for localization. This hashes a keystring that can be looked up with carb_localize_hashed(). Strings must be hashed before passing them into carb_localize_hashed(); this is done largely so that automated tools can easily find all of the localized strings in scripts by searching for this function name. In cases where a string will be looked up many times, it is ideal to cache the hash returned, so that it is not recalculated excessively. Args: string: The keystring to hash. This must be a string. This must not be None. Returns: The hash for the string argument. This hash can be used in carb_localize_hashed().)", py::call_guard<py::gil_scoped_release>()); m.def("get_localized_string_from_hash", [](StringIdentifier id, const char* string) { return carb::l10n::getLocalizedString(id, string); }, R"(Retrieve a string from the localization database, given its hash. This function retrieves a localized string based on the hash of the keystring. This should be used on all strings found in the UI, so that they can automatically be shown in the correct language. Strings returned from this function should never be cached, so that changing the language at runtime will not result in stale strings being shown in the UI. Args: id: A hash that was previously returned by hash_localization_string(). string: The keystring that was hashed with hash_localization_string(). This is passed to ensure that a readable string is returned if the hash is not found in the localization table. Returns: The localized string for the input hash in the currently set language, if a string exists for that language. If no localized string from the currently set language exists for the hash, the US English string will be returned. If the hash is not found in the localization database, the string parameter will be returned. Alternatively, if a config setting is enabled, error messages will be returned in this case.)", py::arg("id") = 0, py::arg("string") = "{TRANSLATION NOT FOUND}", py::call_guard<py::gil_scoped_release>()); } } // namespace l10n } // namespace carb
5,576
C
40.619403
118
0.720947
omniverse-code/kit/include/carb/crashreporter/ICrashReporter.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 Main interface header for ICrashReporter and related types and values. #pragma once #include "../Interface.h" #include "../Types.h" namespace carb { /** Namespace for the crash reporter. */ namespace crashreporter { /** Prototype for a callback that indicates when a crash dump upload has completed. * * @param[in] userData The opaque user data object that was originally passed to the * @ref ICrashReporter::sendAndRemoveLeftOverDumpsAsync() function * in the @a userData parameter. * @returns No return value. * * @remarks This callback function will be performed when the upload of old crash dump files * has completed, successfully or otherwise. At this point, the upload request made * by the corresponding @ref ICrashReporter::sendAndRemoveLeftOverDumpsAsync() call * has completed. However, this does not necessarily mean that the thread created * by it has exited. If another call was made, a new request would have been queued * on that same thread and would be serviced next by the same thread. * * @note This callback is both separate and different from the callback specified by the * @ref OnCrashSentFn prototype. This particular callback is only performed when the * full upload request of all existing old crash dump files completes whereas the * @ref OnCrashSentFn callback is performed every time any single upload completes. */ using OnDumpSubmittedFn = void (*)(void* userData); /** Result codes used to notify subscribers of crash dump uploads whether an upload succeed * or not. These result codes are passed to the callback function specified in calls to * @ref ICrashReporter::addCrashSentCallback(). */ enum class CrashSentResult { eSuccess, ///< The upload completed successfully. eFailure ///< The upload failed for some unspecified reason. }; /** Possible types that a volatile metadata value could be. These are used to determine which * type of value is to be returned from a volatile metadata callback function and how that value * is to be converted into a string to be sent as metadata. The return type of the callback is * split into common primitive types to discourage implementors of the callbacks from using their * own potentially dangerous methods of converting the metadata value to a string. */ enum class MetadataValueType { eInteger, ///< The callback will return a signed 64-bit integer value. eUInteger, ///< The callback will return an unsigned 64-bit integer value. eFloat, ///< The callback will return a 64-bit floating point value. eString, ///< The callback will return an arbitrary length UTF-8 encoded string. eWideString, ///< The callback will return an arbitrary length wide string (`wchar_t` characters). }; /** Provides a single piece of additional information or context to a crash upload complete * callback function. This is stored as a key/value pair. An array of these objects is * passed to the @ref OnCrashSentFn callback to provide extra context to why a crash dump * upload may have failed or additional information about a successful upload. This * information is typically only useful for display to a user or to be output to a log. */ struct CrashSentInfo { const char* key; ///< The key name for this piece of information. const char* value; ///< The specific value associated with the given key. }; /** Prototype for a callback function that is performed any time a dump is successfully uploaded. * * @param[in] crashSentResult The result code of the upload operation. Currently this only * indicates whether the upload was successful or failed. Further * information about the upload operation can be found in the * @p infoData array. * @param[in] infoData An array of zero or more key/value pairs containing additional * information for the upload operation. On failure, this may * include the status code or status message from the server. On * success, this may include a unique fingerprint for the crash * dump that was uploaded. This array will contain exactly * @p infoDataCount items. * @param[in] infoDataCount The total number of items in the @p infoData array. * @param[in] userData The opaque caller specified data object that was provided when * this callback was originally registered. It is the callee's * responsibility to know how to successfully make use of this * value. * @returns No return value. * * @remarks This callback is performed every time a crash dump file upload completes. This * will be called whether the upload is successful or not. This will not however * be called if crash dump uploads are disabled (ie: the * `/crashreporter/devOnlyOverridePrivacyAndForceUpload` setting is false and the * user has not provided 'performance' consent) or the file that an upload was requested * for was missing some required metadata (ie: the `/crashreporter/product` and * `/crashreporter/version` settings). In both those cases, no upload attempt will be * made. * * @remarks The following key/value pair is defined for this callback when using the * `carb.crashreporter-breakpad.plugin` implementation: * * "response": A string containing the HTTP server's response to the upload * attempt. If this string needs to persist, it must be copied * by the callee. * * @thread_safety Calls to this callback will be serialized. It is however the callee's * responsibility to safely access any additional objects including the * @p userData object and any global resources. */ using OnCrashSentFn = void (*)(CrashSentResult crashSentResult, const CrashSentInfo* infoData, size_t infoDataCount, void* userData); /** Opaque handle for a single registered @ref OnCrashSentFn callback function. This is * returned from ICrashReporter::addCrashSentCallback() and can be passed back to * ICrashReporter::removeCrashSentCallback() to unregister it. */ struct CrashSentCallbackId; /** Prototype for a callback function used to resolve symbol information. * * @param[in] address The address of the symbol being resolved. * @param[in] name If the symbol resolution was successful, this will be the name of the * symbol that @p address is contained in. If the resolution fails, this * will be `nullptr`. If non-`nullptr`, this string must be copied before * returning from the callback function if it needs to persist. * @param[in] userData The opaque user data passed to the @ref ICrashReporter::resolveSymbol() * function. * @returns No return value. * * @remarks This callback is used to deliver the results of an attempt to resolve the name of * a symbol in the current process. This callback is always performed synchronously * to the call to ICrashReporter::resolveSymbol(). */ using ResolveSymbolFn = void (*)(const void* address, const char* name, void* userData); /** Metadata value callback function prototype. * * @param[in] context The opaque context value that was used when the metadata value was * originally registered. * @returns The current value of the metadata at the time of the call. * * @note Because these callbacks may be called during the handling of a crash, the calling thread * and other threads may be in an unstable or undefined state when these are called. * Implementations of these callbacks should avoid any allocations and locks if in any way * avoidable. See ICrashReporter::addVolatileMetadataValue() for more information on how * these callbacks should behave. */ using OnGetMetadataIntegerFn = int64_t (*)(void* context); /** @copydoc OnGetMetadataIntegerFn */ using OnGetMetadataUIntegerFn = uint64_t (*)(void* context); /** @copydoc OnGetMetadataIntegerFn */ using OnGetMetadataFloatFn = double (*)(void* context); /** Metadata value callback function prototype. * * @param[out] buffer Receives the string value. This must be UTF-8 encoded and must not * exceed @p maxLength bytes including the null terminator. This buffer * will never be `nullptr`. Writing a null terminator is optional. * @param[in] maxLength The maximum number of bytes including the null terminator that can fit * in the buffer @p buffer. This will never be 0. It is the callback's * responsibility to ensure no more than this many bytes is written to * the output buffer. * @param[in] context The opaque context value that was used when the metadata value was * originally registered. * @returns The total number of bytes **not including the null terminator character** that were * written to the output buffer. This value **MUST** not exceed \p maxLength. */ using OnGetMetadataStringFn = size_t (*)(char* buffer, size_t maxLength, void* context); /** Metadata value callback function prototype. * * @param[out] buffer Receives the string value. This must be wide characters (`wchar_t`) and not * exceed @p maxLength *characters* including the null terminator. This buffer * will never be `nullptr`. Writing a null terminator is optional. * @param[in] maxLength The maximum number of *characters* including the null terminator that can fit * in the buffer @p buffer. This will never be 0. It is the callback's * responsibility to ensure no more than this many characters is written to * the output buffer. * @param[in] context The opaque context value that was used when the metadata value was * originally registered. * @returns The total number of *characters* **not including any null terminator** that were * written to the output buffer. This value **MUST** not exceed \p maxLength. */ using OnGetMetadataWideStringFn = size_t (*)(wchar_t* buffer, size_t maxLength, void* context); /** Descriptor of a single metadata callback function. This describes which type of callback is * being contained and the pointer to the function to call. */ struct MetadataValueCallback { /** The type of the callback. This indicates which of the callbacks in the @ref fn union * below will be called to retrieve the value. */ MetadataValueType type; /** A union containing the different types of function pointers for this callback. Exactly * one of these will be chosen based on @ref type. */ union { OnGetMetadataIntegerFn getInteger; ///< Callback returning a signed 64-bit integer. OnGetMetadataUIntegerFn getUInteger; ///< Callback returning an unsigned 64-bit integer. OnGetMetadataFloatFn getFloat; ///< Callback returning a 64-bit floating point value. OnGetMetadataStringFn getString; ///< Callback returning an arbitrary length string. OnGetMetadataWideStringFn getWString; ///< Callback returning an arbitrary length wide string. } fn; }; /** Registration identifier for a single metadata value. This is only used to unregister the * callback that was registered with the original metadata. */ using MetadataId = size_t; /** Special metadata identifier to indicate an invalid metadata value or general failure in * registering the value with addVolatileMetadata*(). */ constexpr MetadataId kInvalidMetadataId = (MetadataId)(-1ll); /** Special metadata identifier to indicate that a bad parameter was passed into one of the * ICrashReporter::addVolatileMetadata*() functions. This is not a valid identifier and will be * ignored if passed to ICrashReporter::removeVolatileMetadataValue(). */ constexpr MetadataId kMetadataFailBadParameter = (MetadataId)(-2ll); /** Special metadata identifier to indicate that the key being registered is either a known * reserved key or has already been registered as a volatile metadata key. This is not a valid * identifier and will be ignored if passed to ICrashReporter::removeVolatileMetadataValue(). */ constexpr MetadataId kMetadataFailKeyAlreadyUsed = (MetadataId)(-3ll); /** ICrashReporter is the interface to implement a plugin that catches and reports information * about the crash to either a local file, a server, or both. * * ICrashReporter is an optional plugin that is automatically loaded by the framework and doesn't * need to be specifically listed in the configuration. If an ICrashReporter plugin is found, * it's enabled. Only one ICrashReporter instance is supported at a time. * * The crash report itself consists of multiple parts. Some parts are only present on certain * supported platforms. All generated crash dump files will appear in the directory named by the * "/crashreporter/dumpDir" setting. If no value is provided, the current working directory * is used instead. The following parts could be expected: * * A minidump file. This is only generated on Windows. This file will contain the state of * the process's threads, stack memory, global memory space, register values, etc at the time * of the crash. This file will end in '.dmp'. * * A stack trace of the crash point file. This could be produced on all platforms. This * file will end in '.txt'. * * A metadata file. This is a TOML formatted file that contains all the metadata values that * were known by the crash reporter at the time of the crash. This file will end in '.toml'. * * The crash reporter may have any number of arbitrary metadata values associated with it. These * values are defined as key/value pair strings. There are two ways a metadata value can be * defined: * * Add a value to the `/crashreporter/data/` branch of the settings registry. This can be * done directly through the ISettings interface, adding a value to one of the app's config * files, or by using the addCrashMetadata() utility function. These values should be set * once and either never or very rarely modified. There is a non-trivial amount of work * related to collecting a new metadata value in this manner that could lead to an overall * performance impact if done too frequently. * * Add a key and data callback to collect the current value of a metadata key for something * that changes frequently. This type of metadata value is added with addVolatileMetadata() * on this interface. These values may change as frequently as needed. The current value * will only ever be collected when a crash does occur or when the callback is removed. * * Once a metadata value has been added to the crash reporter, it cannot be removed. The value * will remain even if the key is removed from `/crashreporter/data/` or its value callback is * removed. This is intentional so that as much data as possible can be collected to be sent * with the crash report as is possible. * * If a metadata key is registered as a volatile value, it will always override a key of the * same name that is found under the `/crashreporter/data/` branch of the settings registry. * Even if the volatile metadata value is removed or unregistered, it will still override any * key of the same name found in the settings registry. * * Metadata key names may or may not be case sensitive depending on their origin. If a metadata * value comes from the settings registry, its name is case sensitive since the settings registry * is also case sensitive. Metadata values that are registered as volatile metadata values do * not have case sensitive names. Attempting to register a new value under the same key but with * different casing will fail since it would overwrite an existing name. This difference is * intentional to avoid confusion in the metadata output. When adding metadata values through * the settings registry, care should be taken to use consistent casing to avoid confusion in * the output. */ struct ICrashReporter { // 2.3: Added MetadataValueType::eWideString CARB_PLUGIN_INTERFACE("carb::crashreporter::ICrashReporter", 2, 3) /** * Upon crash, a crash dump is written to disk, uploaded, and then removed. However, due to settings or because the * application is in an undefined state, the upload may fail. This method can be used on subsequent runs of the * application to attempt to upload/cleanup previous failed uploads. * * This method returns immediately, performing all uploads/removals asynchronously. Supply an optional callback to * be notified when the uploads/removals have been completed. The callback will be performed regardless of whether * the upload is successful. However, each crash dump file will only be removed from the local file system if its * upload was successful and the "/crashreporter/preserveDump" setting is `false`. A future call to this function * will try the upload again on failed crash dumps. * * The callback will be performed on the calling thread before return if there is no upload task to perform or if * the crash reporter is currently disabled. In all other cases, the callback will be performed in the context of * another thread. It is the caller's responsibility to ensure all accesses made in the callback are thread safe. * The supplied callback may neither directly nor indirectly access this instance of ICrashReporter. * * @thread_safety This method is thread safe and can be called concurrently. * * @param onDumpSubmitted The callback function to be called when the dumps are uploaded and deleted. * @param userData The user data to be passed to the callback function. */ void(CARB_ABI* sendAndRemoveLeftOverDumpsAsync)(OnDumpSubmittedFn onDumpSubmitted, void* userData); /** * Adds a new callback that is called after sending (successfully or not) a crash dump to a server. * * Registration of multiple callbacks is allowed and all registered callbacks will be called serially (the order in * which callbacks are called is undefined). It is allowed to use the same callback function (and userData) multiple * times. * * This method is thread safe and can be called concurrently. * * The supplied callback may neither directly nor indirectly access this instance of ICrashReporter. * * @param onCrashSent The new callback to register, must not be nullptr. * @param userData The user data to be passed to the callback function, can be nullptr. * * @return Not null if the provided callback was successfully registered, nullptr otherwise. */ CrashSentCallbackId*(CARB_ABI* addCrashSentCallback)(OnCrashSentFn onCrashSent, void* userData); /** * Removes previously registered callback. * * This method is thread safe and can be called concurrently. * * The given parameter is the id returned from addCrashSentCallback. * * The given callback id can be nullptr or an invalid id. * * @param callbackId The callback to remove. A null or invalid pointer is accepted (though may produce an error * message). */ void(CARB_ABI* removeCrashSentCallback)(CrashSentCallbackId* callbackId); /** * Attempts to resolve a given address to a symbolic name using debugging features available to the system. * * If symbol resolution fails or is not available, @p func is called with a `nullptr` name. * * @note This function can be extremely slow. Use for debugging only. * * @param address The address to attempt to resolve. * @param func The func to call upon resolution * @param user User-specific data to be passed to @p func * * @thread_safety The callback function is always performed synchronously to this call. It * is the callee's responsibility to ensure safe access to both the @p user * pointer and any global resources. */ void(CARB_ABI* resolveSymbol)(const void* address, ResolveSymbolFn func, void* user); /** Adds a new volatile metadata value to the crash report. * * @param[in] keyName The name of the metadata key to set. This must only contain * printable ASCII characters except for a double quote ('"'), * slash ('/'), or whitespace. It is the caller's responsibility * to ensure the key name will not be overwriting another system's * metadata value. One way to do this is to prefix the key name * with the name of the extension or plugin (sanitized to follow * the above formatting rules). Volatile metadata key names are * not case sensitive. This may not be nullptr or an empty string. * @param[in] maxLength The maximum number of characters, including the null terminator, * that the metadata's value will occupy when its value is retrieved. * This is ignored for integer and floating point values (the maximum * size for those types will always be used regardless of the value). * When retrieved, if the value is longer than this limit, the new * metadata value will truncated. This may be 0 for integer and * floating point value types. For string values, there may be * an arbitrary amount of extra space added internally. This is * often for padding or alignment purposes. Callers should however * neither count on this space being present nor expect any strings * to always be truncated at an exact length. * @param[in] callback The callback and data type that will provide the value for the new * metadata key. This may not contain a `nullptr` callback function. * See below for notes on what the callback function may and may not * do. * @param[in] context An opaque context pointer that will be passed to the callback * function when called. This will not be accessed or evaluated in * any way, but must remain valid for the entire duration that the * callback is registered here. * @returns An identifier that can be used to unregister the callback in the event that the * owning module needs to be unloaded. It is the caller's responsibility to ensure * that the metadata callback is properly unregistered with a call to * removeVolatileMetadataValue() before it unloads. * * @retval kMetadataFailBadParameter if an invalid parameter is passed in. * @retval kMetadataFailKeyAlreadyUsed if the given key name is already in use or is a reserved name. * @retval kInvalidMetadataId if a crash dump is currently in progress during this call. * * @remarks This registers a new volatile metadata value with the crash reporter. This new * value includes a callback that will be used to acquire the most recent value of * the metadata key when a crash does occur. The value may be provided as either a * signed or unsigned integer (64 bit), a floating point value (64 bit), or a string * of arbitrary length. Callback types are intentionally provided for each type to * discourage the implementations from doing their own string conversions that could * be dangerous while handling a crash event. * * @remarks Because the process may be in an unstable or delicate state when the callback * is performed to retrieve the metadata values, there are several restrictions on * what the callback function can and cannot do. In general, the callback function * should provide the metadata value as quickly and simply as possible. An ideal * case would be just to return the current value of a local, global, or member * variable. Some guidelines are: * * Do not perform any allocations or call into anything that may perform an * allocation. At the time of a crash many things could have gone wrong and the * allocations could fail or hang for various reasons. * * Do not use any STL container classes other than to retrieve a current value. * Many STL container class operations can implicitly perform an allocation * to resize a buffer, array, new node, etc. If a resize, copy, or assign * operation is unavoidable, try to use a container class that provides the * possibility to reserve space for expected operations early (ie: string, * vector, etc). * * Avoid doing anything that may use a mutex or other locking primitive that * is not in a strictly known state at the time. During a crash, the state of * any lock could be undefined leading to a hang if an attempt is made to * acquire it. If thread safety is a concern around accessing the value, try * using an atomic variable instead of depending on a lock. * * Do not make any calls into ICrashReporter from the callback function. This * will result in a deadlock. * * Under no circumstances should a new thread be created by the callback. * * @note The addVolatileMetadata() helper functions have been provided to make it easier * to register callbacks for each value type. Using these is preferable to calling * into internalAddVolatileMetadata() directly. * * @sa internalAddVolatileMetadata(), addVolatileMetadata(). */ /** @private */ MetadataId(CARB_ABI* internalAddVolatileMetadata)(const char* keyName, size_t maxLength, MetadataValueCallback* callback, void* context); /** Adds a new volatile metadata value to the crash report. * * @param[in] keyName The name of the metadata key to set. This must only contain * printable ASCII characters except for a double quote ('"'), * slash ('/'), or whitespace. It is the caller's responsibility * to ensure the key name will not be overwriting another system's * metadata value. One way to do this is to prefix the key name * with the name of the extension or plugin (sanitized to follow * the above formatting rules). Volatile metadata key names are * not case sensitive. This may not be `nullptr` or an empty string. * @param[in] callback The callback function that will provide the value for the new * metadata key. This may not be a `nullptr` callback function. * See below for notes on what the callback function may and may not * do. * @param[in] context An opaque context pointer that will be passed to the callback * function when called. This will not be accessed or evaluated in * any way, but must remain valid for the entire duration that the * callback is registered here. * @returns An identifier that can be used to unregister the callback in the event that the * owning module needs to be unloaded. It is the caller's responsibility to ensure * that the metadata callback is properly unregistered with a call to * removeVolatileMetadataValue() before it unloads. * * @retval kMetadataFailBadParameter if an invalid parameter is passed in. * @retval kMetadataFailKeyAlreadyUsed if the given key name is already in use or is a reserved name. * @retval kInvalidMetadataId if a crash dump is currently in progress during this call. * * @remarks This registers a new volatile metadata value with the crash reporter. This new * value includes a callback that will be used to acquire the most recent value of * the metadata key when a crash does occur. The value may be provided as either a * signed or unsigned integer (64 bit), a floating point value (64 bit), or a string * of arbitrary length. Callback types are intentionally provided for each type to * discourage the implementations from doing their own string conversions that could * be dangerous while handling a crash event. * * @remarks Because the process may be in an unstable or delicate state when the callback * is performed to retrieve the metadata values, there are several restrictions on * what the callback function can and cannot do. In general, the callback function * should provide the metadata value as quickly and simply as possible. An ideal * case would be just to return the current value of a local, global, or member * variable. Some guidelines are: * * Do not perform any allocations or call into anything that may perform an * allocation. At the time of a crash, many things could have gone wrong and * allocations could fail or hang for various reasons. * * Do not use any STL container classes other than to retrieve a current value. * Many STL container class operations can implicitly perform an allocation * to resize a buffer, array, new node, etc. If a resize, copy, or assign * operation is unavoidable, try to use a container class that provides the * possibility to reserve space for expected operations early (ie: string, * vector, etc). * * Avoid doing anything that may use a mutex or other locking primitive that * is not in a strictly known state at the time. During a crash, the state of * any lock could be undefined leading to a hang if an attempt is made to * acquire it. If thread safety is a concern around accessing the value, try * using an atomic variable instead of depending on a lock. * * Do not make any calls into ICrashReporter from the callback function. This * will result in a deadlock. * * Under no circumstances should a new thread be created by the callback. * * @thread_safety This call is thread safe. */ MetadataId addVolatileMetadata(const char* keyName, OnGetMetadataIntegerFn callback, void* context); /** @copydoc addVolatileMetadata(const char*,OnGetMetadataIntegerFn,void*) */ MetadataId addVolatileMetadata(const char* keyName, OnGetMetadataUIntegerFn callback, void* context); /** @copydoc addVolatileMetadata(const char*,OnGetMetadataIntegerFn,void*) */ MetadataId addVolatileMetadata(const char* keyName, OnGetMetadataFloatFn callback, void* context); /** @copydoc addVolatileMetadata(const char*,OnGetMetadataIntegerFn,void*) * @param[in] maxLength The maximum number of characters, including the null terminator, * that the metadata's value will occupy when its value is retrieved. * When retrieved, if the value is longer than this limit, this new * metadata value will be truncated. There may be an arbitrary * amount of extra space added internally. This is often done for * padding or alignment purposes. Callers should however neither * count on this space being present nor expect any strings to always * be truncated at an exact length. */ MetadataId addVolatileMetadata(const char* keyName, size_t maxLength, OnGetMetadataStringFn callback, void* context); /** @copydoc addVolatileMetadata(const char*,size_t,OnGetMetadataStringFn,void*) */ MetadataId addVolatileMetadata(const char* keyName, size_t maxLength, OnGetMetadataWideStringFn callback, void* context); /** Removes a previously registered volatile metadata value. * * @param[in] id The identifier of the metadata value to remove. This was returned from * a previous successful call to addVolatileMetadata*(). This call will be * ignored if the identifier is invalid. * @returns No return value. * * @remarks This removes a volatile metadata value from the crash reporter. The value will * be retrieved from the callback and stored internally before it is removed from * the crash reporter. The given identifier will be invalid upon return. * * @sa internalAddVolatileMetadata(), addVolatileMetadata(). */ void(CARB_ABI* removeVolatileMetadataValue)(MetadataId id); }; inline MetadataId ICrashReporter::addVolatileMetadata(const char* keyName, OnGetMetadataIntegerFn callback, void* context) { MetadataValueCallback data; data.type = MetadataValueType::eInteger; data.fn.getInteger = callback; return internalAddVolatileMetadata(keyName, 0, &data, context); } inline MetadataId ICrashReporter::addVolatileMetadata(const char* keyName, OnGetMetadataUIntegerFn callback, void* context) { MetadataValueCallback data; data.type = MetadataValueType::eUInteger; data.fn.getUInteger = callback; return internalAddVolatileMetadata(keyName, 0, &data, context); } inline MetadataId ICrashReporter::addVolatileMetadata(const char* keyName, OnGetMetadataFloatFn callback, void* context) { MetadataValueCallback data; data.type = MetadataValueType::eFloat; data.fn.getFloat = callback; return internalAddVolatileMetadata(keyName, 0, &data, context); } inline MetadataId ICrashReporter::addVolatileMetadata(const char* keyName, size_t maxLength, OnGetMetadataStringFn callback, void* context) { MetadataValueCallback data; data.type = MetadataValueType::eString; data.fn.getString = callback; return internalAddVolatileMetadata(keyName, maxLength, &data, context); } inline MetadataId ICrashReporter::addVolatileMetadata(const char* keyName, size_t maxLength, OnGetMetadataWideStringFn callback, void* context) { MetadataValueCallback data; data.type = MetadataValueType::eWideString; data.fn.getWString = callback; return internalAddVolatileMetadata(keyName, maxLength, &data, context); } } // namespace crashreporter } // namespace carb
37,221
C
59.62215
125
0.665834
omniverse-code/kit/include/carb/crashreporter/CrashReporterUtils.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 Utility helper functions for the crash reporter. #pragma once #include "../Framework.h" #include "../InterfaceUtils.h" #include "../logging/Log.h" #include "../settings/ISettings.h" #include "ICrashReporter.h" #if CARB_PLATFORM_WINDOWS && !defined(_DLL) # include "../CarbWindows.h" # include "../extras/Library.h" #endif #include <signal.h> #include <string.h> #include <future> /** Global accessor object for the loaded ICrashReporter object. This is intended to be used * as a shortcut for accessing the @ref carb::crashreporter::ICrashReporter instance if the * crash reporter plugin has been loaded in the process. This will be `nullptr` if the * crash reporter plugin is not loaded. This symbol is unique to each plugin module and * will be filled in by the framework upon load if the crash reporter plugin is present. * Callers should always check if this value is `nullptr` before accessing it. This should * not be accessed during or after framework shutdown. */ CARB_WEAKLINK carb::crashreporter::ICrashReporter* g_carbCrashReporter; #ifdef DOXYGEN_BUILD /** Defines global symbols specifically related to the crash reporter. */ # define CARB_CRASH_REPORTER_GLOBALS() #else // only install the signal handler for modules that have been statically linked to the // Windows CRT (OVCC-1379). This is done because plugins that statically link to the // CRT have their own copies of the signal handlers table and the crash reporter is // unable to directly manipulate those. By setting the signal handler here in the // context of the statically linked plugin, we provide a way to relay that abort // signal to the crash reporter. # if CARB_PLATFORM_WINDOWS && !defined(_DLL) # if !CARB_COMPILER_MSC static_assert(false, "Unsupported compiler!"); # endif # define CARB_CRASH_REPORTER_GLOBALS() \ bool g_carbSignalHandlerInstalled = carb::crashreporter::detail::installSignalHandler(); namespace carb { namespace crashreporter { namespace detail { /** Installs a SIGABRT signal handler to act as a relay. * * @returns `true` if the signal handler is successfully installed. Returns `false` otherwise. * * @remarks This installs a SIGABRT signal handler to act as an event relay for plugins and apps * that are statically linked to the Windows CRT. This allows each statically linked * module's own signal handler chain to catch `abort()` and `std::terminate()` calls * and pass that on to a special handler function in `carb.dll` that will then relay * the event to the crash reporter plugin. * * @note This signal handler can be disabled by defining the `CARB_DISABLE_ABORT_HANDLER` * environment variable and setting its value to '1'. * * @note This should not be called directly. This is called automatically as needed during * plugin and app load. */ inline bool installSignalHandler() { using SignalHandlerFn = void (*)(int); static bool disableHandler = []() { WCHAR envVarValue[32] = { 0 }; return GetEnvironmentVariableW(L"CARB_DISABLE_ABORT_HANDLER", envVarValue, CARB_COUNTOF32(envVarValue)) != 0 && envVarValue[0] == '1' && envVarValue[1] == '\0'; }(); if (disableHandler) return false; static SignalHandlerFn handler = []() -> SignalHandlerFn { SignalHandlerFn fn; carb::extras::LibraryHandle handle = carb::extras::loadLibrary( "carb", carb::extras::fLibFlagMakeFullLibName | carb::extras::fLibFlagLoadExisting); if (handle == carb::extras::kInvalidLibraryHandle) return nullptr; fn = carb::extras::getLibrarySymbol<SignalHandlerFn>(handle, "carbSignalHandler"); if (fn == nullptr) { carb::extras::unloadLibrary(handle); return nullptr; } return fn; }(); if (handler == nullptr) return false; // install the signal handler for this thread in this module. Since signals on Windows // are a bonus feature and rarely used, we don't care about preserving the previous // signal handler. signal(SIGABRT, handler); return true; } } // namespace detail } // namespace crashreporter } // namespace carb # else # define CARB_CRASH_REPORTER_GLOBALS() # endif #endif namespace carb { /** Namespace for the crash reporter. */ namespace crashreporter { /** Base magic signature value used to verify crash reporter resources. The lower 8 bits of this * value can be incremented to allow for different versions of this resources this signature * protects. */ constexpr uintptr_t kBaseMagicSignature = 0xc7a547e907137700ull; /** Current magic signature used to verify crash reporter resources. This value is intended to * be incremented for versioning purposes if the handling of the crash reporter resources needs * to change in the future. */ constexpr uintptr_t kMagicSignature = kBaseMagicSignature; #if CARB_PLATFORM_LINUX || defined(DOXYGEN_BUILD) /** Signal number to use to handle external termination requests. This signal is intentionally * a seldom used one so that it is unlikely to interfere with other normal signal usage in the * process. Even with the rarely used signal, we'll still include other safety checks on the * received signal before scheduling an intentional termination. */ static int kExternalTerminationSignal = SIGRTMAX - 1; #elif CARB_PLATFORM_MACOS /** MacOS doesn't support realtime signals. We'll use SIGUSR2 instead. */ constexpr int kExternalTerminationSignal = SIGUSR2; #endif /** Registers the crash reporter for this process and sets it up. * * @returns No return value. * * @remarks This installs the crash reporter in the calling process. This will include * installing the crash handler hook and setting up its state according to the * current values in the `/crashreporter/` branch of the settings registry. * If the ISettings interface is not available, the crash reporter will only * use its default settings and many features will be disabled. In this case * the disabled features will include monitoring for changes to the various * `/crashreporter/` settings, specifying metadata to include in crash reports, * and controlling how and where the crash dump files are written out. * * @note When the process is shutting down, the crash reporter should be disabled * by calling @ref carb::crashreporter::deregisterCrashReporterForClient(). * It is the host app's responsibility to properly disable the crash reporter * before the plugin is unloaded. * * @thread_safety This operation is not thread safe. It is the caller's responsibility * to ensure this is only called from a single thread at any given time. * However, this will be automatically called during Carbonite framework * startup (in carb::startupFramework()) and does not necessarily need * to be called directly. */ inline void registerCrashReporterForClient() { g_carbCrashReporter = getFramework()->tryAcquireInterface<ICrashReporter>(); } /** Deregisters and disables the crash reporter for the calling process. * * @returns No return value. * * @remarks This removes the crash reporter interface from the global variable * @ref g_carbCrashReporter so that callers cannot access it further. * The crash reporter plugin is also potentially unloaded. * * @thread_safety This operation is not thread safe. It is the caller's responsibility * to ensure this is only called from a single thread at any given time. * However, this will be automatically called during Carbonite framework * shutdown (in carb::shutdownFramework()) and does not necessarily need * to be called directly. */ inline void deregisterCrashReporterForClient() { if (g_carbCrashReporter) { getFramework()->releaseInterface(g_carbCrashReporter); g_carbCrashReporter = nullptr; } } /** Attempts to upload any crash dump files left by a previously crashed process. * * @returns A future that can be used to check on the completion of the upload operation. * The operation is fully asynchronous and will proceed on its own. The future * object will be signaled once the operation completes, successfully or otherwise. * * @remarks This starts off the process of checking for and uploading old crash dump files * that may have been left over by a previous crashed process. This situation can * occur if the upload failed in the previous process (ie: network connection * issue, etc), or the process crashed again during the upload. A list of old * crash dump files will be searched for in the currently set dump directory * (as set by `/crashreporter/dumpDir`). If any are found, they will be uploaded * one by one to the currently set upload URL (`/crashreporter/url`). Each * crash dump file will be uploaded with its original metadata if the matching * metadata file can be found. Once a file has been successfully uploaded to * the given upload URL, it will be deleted from local storage unless the * `/crashreporter/preserveDump` setting is `true`. This entire process will * be skipped if the `/crashreporter/skipOldDumpUpload` setting is `true` and * this call will simply return immediately. * * @thread_safety This function is thread safe. If multiple calls are made while an upload * is still in progress, a new task will just be added to the upload queue * instead of starting off another upload thread. * * @note If an upload is in progress when the process tries to exit or the crash reporter * plugin tries to unload, any remaining uploads will be canceled, but the current * upload operation will wait to complete. If this is a large file being uploaded * or the internet connection's upload speed is particularly slow, this could potentially * take a long time. There is unfortunately no reliable way to cancel this upload * in progress currently. */ inline std::future<void> sendAndRemoveLeftOverDumpsAsync() { std::unique_ptr<std::promise<void>> sentPromise(new std::promise<void>()); std::future<void> sentFuture(sentPromise->get_future()); if (g_carbCrashReporter) { const auto finishCallback = [](void* promisePtr) { auto sentPromise = reinterpret_cast<std::promise<void>*>(promisePtr); sentPromise->set_value(); delete sentPromise; }; g_carbCrashReporter->sendAndRemoveLeftOverDumpsAsync(finishCallback, sentPromise.release()); } else { CARB_LOG_WARN("No crash reporter present, dumps uploading isn't available."); sentPromise->set_value(); } return sentFuture; } /** Namespace for internal helper functions. */ namespace detail { /** Sanitizes a string to be usable as a key name in the settings registry. * * @param[in] keyName The key string to be sanitized. This may be any string in theory, but * should really be a short descriptive name for a crash metadata value or * extra crash file. All non-ASCII, non-numeric characters will be replaced * with underscores. * @returns A string containing the sanitized key name. * * @note This is called internally by the addExtraCrashFile() and isExtraCrashFileKeyUsed() * functions and should not be called directly. */ inline std::string sanitizeExtraCrashFileKey(const char* keyName) { std::string key = keyName; // sanitize the key name so that it contains only database friendly characters. for (auto& c : key) { if (c <= ' ' || c >= 127 || strchr("\"'\\/,#$%^&*()!~`[]{}|<>?;:=+.\t\b\n\r ", c) != nullptr) { c = '_'; } } return key; } } // namespace detail /** Adds a metadata value to the crash reporter. * * @tparam T The type of the value to set. This may be any value type that is * compatible with @a std::to_string(). * @param[in] keyName The name of the metadata key to set. This must only contain printable * ASCII characters except for a double quote ('"'), slash ('/'), or * whitespace. These rules get the key to a format that can be accepted * by the settings registry. Note that further sanitization on the key * name may also occur later. Any character that is not suitable for a * database key name will be replaced by an underscore ('_'). It is the * caller's responsibility to ensure the key name will not be overwriting * another system's metadata value. One way to do this is to prefix the * key name with the name of the extension or plugin (sanitized to follow * the above formatting rules). * @param[in] value The value to add to the crash reporter's metadata table. This may be * any string that is accepted by carb::settings::ISettings::setString() * as a new value. Note that this will remove the metadata value if it is * set to `nullptr` or an empty string. * @returns `true` if the new metadata value is successfully set. Returns `false` otherwise. * * @remarks This adds a new metadata value to the crash reporter. When a crash occurs, all * values added through here will be collected and transmitted as metadata to * accompany the crash report. The metadata value will value will be added (or * updated) to the crash reporter by adding (or updating) a key under the * "/crashreporter/data/" settings branch. * * @note This should not be called frequently to update the value of a piece of metadata. * Doing so will be likely to incur a performance hit since the crash reporter watches * for changes on the "/crashreporter/data/" settings branch that is modified here. * Each time the branch changes, the crash reporter's metadata list is updated. If * possible, the value for any given piece of metadata should only be updated when * it either changes or just set once on startup and left alone. */ template <typename T> inline bool addCrashMetadata(const char* keyName, T value) { return addCrashMetadata(keyName, std::to_string(value).c_str()); } /** @copydoc carb::crashreporter::addCrashMetadata(const char*,T). */ template <> inline bool addCrashMetadata(const char* keyName, const char* value) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string key; if (settings == nullptr) return false; key = detail::sanitizeExtraCrashFileKey(keyName); settings->setString((std::string("/crashreporter/data/") + key).c_str(), value); return true; } /** Retrieves the value of a crash metadata value (if defined). * * @param[in] keyName The name of the metadata key to retrieve the value for. This must only * contain printable ASCII characters except for a double quote ('"'), slash * ('/'), or whitespace. These rules get the key to a format that can be * accepted by the settings registry. Note that further sanitization on the * key name may also occur later. Any character that is not suitable for a * database key name will be replaced by an underscore ('_'). It is the * caller's responsibility to ensure the key name will not be overwriting * another system's metadata value. One way to do this is to prefix the * key name with the name of the extension or plugin (sanitized to follow * the above formatting rules). * @returns The value of the requested crash metadata if it is defined. Returns `nullptr` if * the requested metadata value has not been defined. This will not modify any existing * crash metadata keys or values. */ inline const char* getCrashMetadataValue(const char* keyName) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string key; if (settings == nullptr) return nullptr; key = "/crashreporter/data/" + detail::sanitizeExtraCrashFileKey(keyName); return settings->getStringBuffer(key.c_str()); } /** Adds an extra file to be uploaded when a crash occurs. * * @param[in] keyName The name of the key to give to the file. This is what the file will be * uploaded as. Using the file's original name should be fine in most * cases, however it should not contain characters such as '/' or '\' * at the very least. Non-ASCII characters should be avoided if possible * too. It is the caller's responsibility to ensure adding this new file * will not overwrite another upload file with the same key name. This * may not use the reserved name 'upload_file_minidump'. This key name * string will always be sanitized to only contain database friendly * characters. All invalid characters will be replaced by an underscore * ('_'). * @param[in] filename The full path to the file to upload. This may be a relative or absolute * path. The file may or may not exist at the time of this call, it will * still be added to the list of files to be uploaded. If the file does not * exist at the time of the crash, it will be filtered out of the list at * that point. A warnings message will be written out for each listed file * that is missing at the time of the crash however. * @returns `true` if the new entry is added to the list. Returns `false` if the file could * not be added. This failure will only occur if the \ref carb::settings::ISettings interface is not * available. Note that a `true` return does not necessarily mean that the new file * was fully added to the list. It would have been written to the list in the settings * registry, but may have been ignored by the crash reporter if the same key was given * as a previous file. * * @remarks This adds a filename to be tracked to upload with the next crash report that is * generated. This setting is not persistent across sessions. If no crash occurs, * the file will not be uploaded anywhere. This cannot be used to rename a file that * has already been added to the upload list (ie: change the filename under an existing * key). If a second filename is specified with the same key, it will be ignored. * * @note Extra files added with this function will not be deleted once a crash report is * successfully uploaded. Only the crash report's main dump file and metadata files * will be deleted in this case. */ inline bool addExtraCrashFile(const char* keyName, const char* filename) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string key; if (settings == nullptr) return false; // sanitize the key name so that it contains only database friendly characters. key = detail::sanitizeExtraCrashFileKey(keyName); settings->setString(("/crashreporter/files/" + key).c_str(), filename); return true; } /** Checks whether a key for an extra crash report file has already been used. * * @param[in] keyName The name of the key to be used. This will be used to identify the extra * file in the settings registry. See addExtraCrashFile() for more * information on how this value is used. * @returns `true` if the crash file key has been used already. Returns `false` otherwise. * * @remarks When adding new extra files to a crash report, it is the caller's responsibility * that an existing filename will not be overwritten by addExtraCrashFile(). This * function can be used to check whether a given key had already been used to add * an extra file to the crash report. */ inline bool isExtraCrashFileKeyUsed(const char* keyName) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string key; if (settings == nullptr) return false; // sanitize the key name so that it contains only database friendly characters. key = detail::sanitizeExtraCrashFileKey(keyName); return settings->isAccessibleAs(carb::dictionary::ItemType::eString, ("/crashreporter/files/" + key).c_str()); } } // namespace crashreporter } // namespace carb
22,003
C
46.938998
120
0.671454
omniverse-code/kit/include/carb/input/InputTypes.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 "../Types.h" namespace carb { namespace input { struct InputDevice; struct Keyboard; struct Mouse; struct Gamepad; /** * Type used as an identifier for all subscriptions. */ typedef uint32_t SubscriptionId; /** * Subscription order. * * [0..N-1] requires to insert before the position from the beginning and shift tail on the right. * [-1..-N] requires to insert after the position relative from the end and shift head on the left. * * Please look at the examples below: * * Assume we initially have a queue of N subscribers a b c .. y z: * +---+---+---+-- --+---+---+ * | a | b | c | | y | z | -----events--flow---> * +---+---+---+-- --+---+---+ * | 0 | 1 | 2 | |N-2|N-1| ---positive-order---> * +---+---+---+-- --+---+---+ * | -N| | | | -2| -1| <---negative-order--- * +---+---+---+-- --+---+---+ * first last * * After inserting subscriber e with the order 1: * +---+---+---+---+-- --+---+---+ * | a | e | b | c | | y | z | * +---+---+---+---+-- --+---+---+ * | 0 | 1 | 2 | 3 | |N-1| N | * +---+---+---+---+-- --+---+---+ * first last * * After inserting subscriber f with the order -1: * +---+---+---+---+-- --+---+---+---+ * | a | e | b | c | | y | z | f | * +---+---+---+---+-- --+---+---+---+ * | 0 | 1 | 2 | 3 | |N-1| N |N+1| * +---+---+---+---+-- --+---+---+---+ * | 0 | 1 | 2 | 3 | |M-3|M-2|M-1| * +---+---+---+---+-- --+---+---+---+ * first last * */ using SubscriptionOrder = int32_t; /** * Default subscription order. */ static constexpr SubscriptionOrder kSubscriptionOrderFirst = 0; static constexpr SubscriptionOrder kSubscriptionOrderLast = -1; static constexpr SubscriptionOrder kSubscriptionOrderDefault = kSubscriptionOrderLast; /** * Defines possible input event types. * TODO: This is not supported yet. */ enum class EventType : uint32_t { eUnknown }; /** * Defines event type mask. * TODO: Flags are not customized yet. */ typedef uint32_t EventTypeMask; static constexpr EventTypeMask kEventTypeAll = EventTypeMask(-1); /** * Defines possible press states. */ typedef uint32_t ButtonFlags; const uint32_t kButtonFlagTransitionUp = 1; const uint32_t kButtonFlagStateUp = (1 << 1); const uint32_t kButtonFlagTransitionDown = (1 << 2); const uint32_t kButtonFlagStateDown = (1 << 3); /** * Defines possible device types. */ enum class DeviceType { eKeyboard, eMouse, eGamepad, eCount, eUnknown = eCount }; /** * Defines keyboard modifiers. */ typedef uint32_t KeyboardModifierFlags; const uint32_t kKeyboardModifierFlagShift = 1 << 0; const uint32_t kKeyboardModifierFlagControl = 1 << 1; const uint32_t kKeyboardModifierFlagAlt = 1 << 2; const uint32_t kKeyboardModifierFlagSuper = 1 << 3; const uint32_t kKeyboardModifierFlagCapsLock = 1 << 4; const uint32_t kKeyboardModifierFlagNumLock = 1 << 5; /** * Defines totl number of keyboard modifiers. */ const uint32_t kKeyboardModifierFlagCount = 6; /** * Defines keyboard event type. */ enum class KeyboardEventType { eKeyPress, ///< Sent when key is pressed the first time. eKeyRepeat, ///< Sent after a platform-specific delay if key is held down. eKeyRelease, ///< Sent when the key is released. eChar, ///< Sent when a character is produced by the input actions, for example during key presses. // Must always be last eCount ///< The number of KeyboardEventType elements. }; /** * Defines input code type. * */ typedef uint32_t InputType; /** * Defines keyboard key codes * * The key code represents the physical key location in the standard US keyboard layout keyboard, if they exist * in the US keyboard. * * eUnknown is sent for key events that do not have a key code. */ enum class KeyboardInput : InputType { eUnknown, eSpace, eApostrophe, eComma, eMinus, ePeriod, eSlash, eKey0, eKey1, eKey2, eKey3, eKey4, eKey5, eKey6, eKey7, eKey8, eKey9, eSemicolon, eEqual, eA, eB, eC, eD, eE, eF, eG, eH, eI, eJ, eK, eL, eM, eN, eO, eP, eQ, eR, eS, eT, eU, eV, eW, eX, eY, eZ, eLeftBracket, eBackslash, eRightBracket, eGraveAccent, eEscape, eTab, eEnter, eBackspace, eInsert, eDel, eRight, eLeft, eDown, eUp, ePageUp, ePageDown, eHome, eEnd, eCapsLock, eScrollLock, eNumLock, ePrintScreen, ePause, eF1, eF2, eF3, eF4, eF5, eF6, eF7, eF8, eF9, eF10, eF11, eF12, eNumpad0, eNumpad1, eNumpad2, eNumpad3, eNumpad4, eNumpad5, eNumpad6, eNumpad7, eNumpad8, eNumpad9, eNumpadDel, eNumpadDivide, eNumpadMultiply, eNumpadSubtract, eNumpadAdd, eNumpadEnter, eNumpadEqual, eLeftShift, eLeftControl, eLeftAlt, eLeftSuper, eRightShift, eRightControl, eRightAlt, eRightSuper, eMenu, eCount }; /** * UTF8 RFC3629 - max 4 bytes per character */ const uint32_t kCharacterMaxNumBytes = 4; /** * Defines a keyboard event. */ struct KeyboardEvent { union { Keyboard* keyboard; InputDevice* device; }; KeyboardEventType type; union { KeyboardInput key; InputType inputType; char character[kCharacterMaxNumBytes]; }; KeyboardModifierFlags modifiers; }; /** * Defines the mouse event types. */ enum class MouseEventType { eLeftButtonDown, eLeftButtonUp, eMiddleButtonDown, eMiddleButtonUp, eRightButtonDown, eRightButtonUp, eMove, eScroll, // Must always be last eCount ///< The number of MouseEventType elements. }; /** * Defines the mouse event. * * normalizedCoords - mouse coordinates only active in move events, normalized to [0.0, 1.0] relative to the * associated window size. * unscaledCoords - mouse coordinates only active in move events, not normalized. * scrollDelta - scroll delta, only active in scroll events. */ struct MouseEvent { union { Mouse* mouse; InputDevice* device; }; MouseEventType type; union { Float2 normalizedCoords; Float2 scrollDelta; }; KeyboardModifierFlags modifiers; Float2 pixelCoords; }; /** * Defines a mouse input. */ enum class MouseInput : InputType { eLeftButton, eRightButton, eMiddleButton, eForwardButton, eBackButton, eScrollRight, eScrollLeft, eScrollUp, eScrollDown, eMoveRight, eMoveLeft, eMoveUp, eMoveDown, eCount }; /** * Defines a gamepad input. * * Expected ABXY buttons layout: * Y * X B * A * eMenu1 - maps to View (XBone) / Share (DS4) * eMenu2 - maps to Menu (XBone) / Options (DS4) */ enum class GamepadInput : InputType { eLeftStickRight, eLeftStickLeft, eLeftStickUp, eLeftStickDown, eRightStickRight, eRightStickLeft, eRightStickUp, eRightStickDown, eLeftTrigger, eRightTrigger, eA, eB, eX, eY, eLeftShoulder, eRightShoulder, eMenu1, eMenu2, eLeftStick, eRightStick, eDpadUp, eDpadRight, eDpadDown, eDpadLeft, eCount }; /** * Defines a gamepad event. */ struct GamepadEvent { union { Gamepad* gamepad; InputDevice* device; }; union { GamepadInput input; InputType inputType; }; float value; }; /** * Defines the gamepad connection event types. */ enum class GamepadConnectionEventType { eCreated, eConnected, eDisconnected, eDestroyed }; /** * Defines the gamepad connection event. */ struct GamepadConnectionEvent { union { Gamepad* gamepad; InputDevice* device; }; GamepadConnectionEventType type; }; /** * Defines the unified input event. */ struct InputEvent { DeviceType deviceType; union { KeyboardEvent keyboardEvent; MouseEvent mouseEvent; GamepadEvent gamepadEvent; InputDevice* device; }; }; /** * Defines action mapping description. */ struct ActionMappingDesc { DeviceType deviceType; union { Keyboard* keyboard; Mouse* mouse; Gamepad* gamepad; InputDevice* device; }; union { KeyboardInput keyboardInput; MouseInput mouseInput; GamepadInput gamepadInput; InputType inputType; }; KeyboardModifierFlags modifiers; }; /** * Defines an action event. */ struct ActionEvent { const char* action; float value; ButtonFlags flags; }; /** * Function type that describes keyboard event callback. * * @param evt The event description. * @param userData Pointer to the user data. * @return Whether event should be processed by subsequent event subscribers. */ typedef bool (*OnActionEventFn)(const ActionEvent& evt, void* userData); /** * Function type that describes keyboard event callback. * * @param evt The event description. * @param userData Pointer to the user data. * @return Whether event should be processed by subsequent event subscribers. */ typedef bool (*OnKeyboardEventFn)(const KeyboardEvent& evt, void* userData); /** * Function type that describes mouse event callback. * * @param evt The event description. * @param userData Pointer to the user data. * @return Whether event should be processed by subsequent event subscribers. */ typedef bool (*OnMouseEventFn)(const MouseEvent& evt, void* userData); /** * Function type that describes gamepad event callback. * * @param evt The event description. * @param userData Pointer to the user data. * @return Whether event should be processed by subsequent event subscribers. */ typedef bool (*OnGamepadEventFn)(const GamepadEvent& evt, void* userData); /** * Function type that describes gamepad connection event callback. * * @param evt The event description. * @param userData Pointer to the user data. * @return Whether event should not be processed anymore by subsequent event subscribers. */ typedef void (*OnGamepadConnectionEventFn)(const GamepadConnectionEvent& evt, void* userData); /** * Function type that describes input event callback. * * @param evt The event description. * @param userData Pointer to the user data. * @return Whether event should be processed by subsequent event subscribers. */ typedef bool (*OnInputEventFn)(const InputEvent& evt, void* userData); /** * The result returned by InputEventFilterFn. */ enum class FilterResult : uint8_t { //! The event should be retained and sent later when IInput::distributeBufferedEvents() is called. eRetain = 0, //! The event has been fully processed by InputEventFilterFn and should NOT be sent later when //! IInput::distributeBufferedEvents() is called. eConsume = 1, }; /** * Callback function type for filtering events. * * @see IInput::filterBufferedEvents() for more information. * * @param evt A reference to the unified event description. The event may be modified. * @param userData A pointer to the user data passed to IInput::filterBufferedEvents(). * @return The FilterResult indicating what should happen with the event. */ typedef FilterResult (*InputEventFilterFn)(InputEvent& evt, void* userData); static const char* const kAnyDevice = nullptr; } // namespace input } // namespace carb
12,006
C
20.101933
111
0.637181
omniverse-code/kit/include/carb/input/InputBindingsPython.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 "../BindingsPythonUtils.h" #include "../BindingsPythonTypes.h" #include "../Framework.h" #include "IInput.h" #include "InputProvider.h" #include "InputUtils.h" #include <memory> #include <string> #include <vector> namespace carb { namespace input { struct InputDevice { }; struct Gamepad { }; class ActionMappingSet { }; } // namespace input namespace input { namespace detail { inline ActionMappingDesc toMouseMapping(Mouse* mouse, MouseInput input, KeyboardModifierFlags modifiers) { ActionMappingDesc mapping{}; mapping.deviceType = DeviceType::eMouse; mapping.mouse = mouse; mapping.mouseInput = input; mapping.modifiers = modifiers; return mapping; } inline ActionMappingDesc toGamepadMapping(Gamepad* gamepad, GamepadInput input) { ActionMappingDesc mapping{}; mapping.deviceType = DeviceType::eGamepad; mapping.gamepad = gamepad; mapping.gamepadInput = input; return mapping; } } // namespace detail inline void definePythonModule(py::module& m) { m.doc() = "pybind11 carb.input bindings"; py::class_<InputDevice> device(m, "InputDevice"); py::class_<Keyboard>(m, "Keyboard", device); py::class_<Mouse>(m, "Mouse", device); py::class_<Gamepad>(m, "Gamepad", device); py::class_<ActionMappingSet>(m, "ActionMappingSet"); py::enum_<EventType>(m, "EventType").value("UNKNOWN", EventType::eUnknown); m.attr("EVENT_TYPE_ALL") = py::int_(kEventTypeAll); m.attr("SUBSCRIPTION_ORDER_FIRST") = py::int_(kSubscriptionOrderFirst); m.attr("SUBSCRIPTION_ORDER_LAST") = py::int_(kSubscriptionOrderLast); m.attr("SUBSCRIPTION_ORDER_DEFAULT") = py::int_(kSubscriptionOrderDefault); py::enum_<DeviceType>(m, "DeviceType") .value("KEYBOARD", DeviceType::eKeyboard) .value("MOUSE", DeviceType::eMouse) .value("GAMEPAD", DeviceType::eGamepad); py::enum_<KeyboardEventType>(m, "KeyboardEventType") .value("KEY_PRESS", KeyboardEventType::eKeyPress) .value("KEY_REPEAT", KeyboardEventType::eKeyRepeat) .value("KEY_RELEASE", KeyboardEventType::eKeyRelease) .value("CHAR", KeyboardEventType::eChar); py::enum_<KeyboardInput>(m, "KeyboardInput") .value("UNKNOWN", KeyboardInput::eUnknown) .value("SPACE", KeyboardInput::eSpace) .value("APOSTROPHE", KeyboardInput::eApostrophe) .value("COMMA", KeyboardInput::eComma) .value("MINUS", KeyboardInput::eMinus) .value("PERIOD", KeyboardInput::ePeriod) .value("SLASH", KeyboardInput::eSlash) .value("KEY_0", KeyboardInput::eKey0) .value("KEY_1", KeyboardInput::eKey1) .value("KEY_2", KeyboardInput::eKey2) .value("KEY_3", KeyboardInput::eKey3) .value("KEY_4", KeyboardInput::eKey4) .value("KEY_5", KeyboardInput::eKey5) .value("KEY_6", KeyboardInput::eKey6) .value("KEY_7", KeyboardInput::eKey7) .value("KEY_8", KeyboardInput::eKey8) .value("KEY_9", KeyboardInput::eKey9) .value("SEMICOLON", KeyboardInput::eSemicolon) .value("EQUAL", KeyboardInput::eEqual) .value("A", KeyboardInput::eA) .value("B", KeyboardInput::eB) .value("C", KeyboardInput::eC) .value("D", KeyboardInput::eD) .value("E", KeyboardInput::eE) .value("F", KeyboardInput::eF) .value("G", KeyboardInput::eG) .value("H", KeyboardInput::eH) .value("I", KeyboardInput::eI) .value("J", KeyboardInput::eJ) .value("K", KeyboardInput::eK) .value("L", KeyboardInput::eL) .value("M", KeyboardInput::eM) .value("N", KeyboardInput::eN) .value("O", KeyboardInput::eO) .value("P", KeyboardInput::eP) .value("Q", KeyboardInput::eQ) .value("R", KeyboardInput::eR) .value("S", KeyboardInput::eS) .value("T", KeyboardInput::eT) .value("U", KeyboardInput::eU) .value("V", KeyboardInput::eV) .value("W", KeyboardInput::eW) .value("X", KeyboardInput::eX) .value("Y", KeyboardInput::eY) .value("Z", KeyboardInput::eZ) .value("LEFT_BRACKET", KeyboardInput::eLeftBracket) .value("BACKSLASH", KeyboardInput::eBackslash) .value("RIGHT_BRACKET", KeyboardInput::eRightBracket) .value("GRAVE_ACCENT", KeyboardInput::eGraveAccent) .value("ESCAPE", KeyboardInput::eEscape) .value("TAB", KeyboardInput::eTab) .value("ENTER", KeyboardInput::eEnter) .value("BACKSPACE", KeyboardInput::eBackspace) .value("INSERT", KeyboardInput::eInsert) .value("DEL", KeyboardInput::eDel) .value("RIGHT", KeyboardInput::eRight) .value("LEFT", KeyboardInput::eLeft) .value("DOWN", KeyboardInput::eDown) .value("UP", KeyboardInput::eUp) .value("PAGE_UP", KeyboardInput::ePageUp) .value("PAGE_DOWN", KeyboardInput::ePageDown) .value("HOME", KeyboardInput::eHome) .value("END", KeyboardInput::eEnd) .value("CAPS_LOCK", KeyboardInput::eCapsLock) .value("SCROLL_LOCK", KeyboardInput::eScrollLock) .value("NUM_LOCK", KeyboardInput::eNumLock) .value("PRINT_SCREEN", KeyboardInput::ePrintScreen) .value("PAUSE", KeyboardInput::ePause) .value("F1", KeyboardInput::eF1) .value("F2", KeyboardInput::eF2) .value("F3", KeyboardInput::eF3) .value("F4", KeyboardInput::eF4) .value("F5", KeyboardInput::eF5) .value("F6", KeyboardInput::eF6) .value("F7", KeyboardInput::eF7) .value("F8", KeyboardInput::eF8) .value("F9", KeyboardInput::eF9) .value("F10", KeyboardInput::eF10) .value("F11", KeyboardInput::eF11) .value("F12", KeyboardInput::eF12) .value("NUMPAD_0", KeyboardInput::eNumpad0) .value("NUMPAD_1", KeyboardInput::eNumpad1) .value("NUMPAD_2", KeyboardInput::eNumpad2) .value("NUMPAD_3", KeyboardInput::eNumpad3) .value("NUMPAD_4", KeyboardInput::eNumpad4) .value("NUMPAD_5", KeyboardInput::eNumpad5) .value("NUMPAD_6", KeyboardInput::eNumpad6) .value("NUMPAD_7", KeyboardInput::eNumpad7) .value("NUMPAD_8", KeyboardInput::eNumpad8) .value("NUMPAD_9", KeyboardInput::eNumpad9) .value("NUMPAD_DEL", KeyboardInput::eNumpadDel) .value("NUMPAD_DIVIDE", KeyboardInput::eNumpadDivide) .value("NUMPAD_MULTIPLY", KeyboardInput::eNumpadMultiply) .value("NUMPAD_SUBTRACT", KeyboardInput::eNumpadSubtract) .value("NUMPAD_ADD", KeyboardInput::eNumpadAdd) .value("NUMPAD_ENTER", KeyboardInput::eNumpadEnter) .value("NUMPAD_EQUAL", KeyboardInput::eNumpadEqual) .value("LEFT_SHIFT", KeyboardInput::eLeftShift) .value("LEFT_CONTROL", KeyboardInput::eLeftControl) .value("LEFT_ALT", KeyboardInput::eLeftAlt) .value("LEFT_SUPER", KeyboardInput::eLeftSuper) .value("RIGHT_SHIFT", KeyboardInput::eRightShift) .value("RIGHT_CONTROL", KeyboardInput::eRightControl) .value("RIGHT_ALT", KeyboardInput::eRightAlt) .value("RIGHT_SUPER", KeyboardInput::eRightSuper) .value("MENU", KeyboardInput::eMenu) .value("COUNT", KeyboardInput::eCount); py::enum_<MouseEventType>(m, "MouseEventType") .value("LEFT_BUTTON_DOWN", MouseEventType::eLeftButtonDown) .value("LEFT_BUTTON_UP", MouseEventType::eLeftButtonUp) .value("MIDDLE_BUTTON_DOWN", MouseEventType::eMiddleButtonDown) .value("MIDDLE_BUTTON_UP", MouseEventType::eMiddleButtonUp) .value("RIGHT_BUTTON_DOWN", MouseEventType::eRightButtonDown) .value("RIGHT_BUTTON_UP", MouseEventType::eRightButtonUp) .value("MOVE", MouseEventType::eMove) .value("SCROLL", MouseEventType::eScroll); py::enum_<MouseInput>(m, "MouseInput") .value("LEFT_BUTTON", MouseInput::eLeftButton) .value("RIGHT_BUTTON", MouseInput::eRightButton) .value("MIDDLE_BUTTON", MouseInput::eMiddleButton) .value("FORWARD_BUTTON", MouseInput::eForwardButton) .value("BACK_BUTTON", MouseInput::eBackButton) .value("SCROLL_RIGHT", MouseInput::eScrollRight) .value("SCROLL_LEFT", MouseInput::eScrollLeft) .value("SCROLL_UP", MouseInput::eScrollUp) .value("SCROLL_DOWN", MouseInput::eScrollDown) .value("MOVE_RIGHT", MouseInput::eMoveRight) .value("MOVE_LEFT", MouseInput::eMoveLeft) .value("MOVE_UP", MouseInput::eMoveUp) .value("MOVE_DOWN", MouseInput::eMoveDown) .value("COUNT", MouseInput::eCount); py::enum_<GamepadInput>(m, "GamepadInput") .value("LEFT_STICK_RIGHT", GamepadInput::eLeftStickRight) .value("LEFT_STICK_LEFT", GamepadInput::eLeftStickLeft) .value("LEFT_STICK_UP", GamepadInput::eLeftStickUp) .value("LEFT_STICK_DOWN", GamepadInput::eLeftStickDown) .value("RIGHT_STICK_RIGHT", GamepadInput::eRightStickRight) .value("RIGHT_STICK_LEFT", GamepadInput::eRightStickLeft) .value("RIGHT_STICK_UP", GamepadInput::eRightStickUp) .value("RIGHT_STICK_DOWN", GamepadInput::eRightStickDown) .value("LEFT_TRIGGER", GamepadInput::eLeftTrigger) .value("RIGHT_TRIGGER", GamepadInput::eRightTrigger) .value("A", GamepadInput::eA) .value("B", GamepadInput::eB) .value("X", GamepadInput::eX) .value("Y", GamepadInput::eY) .value("LEFT_SHOULDER", GamepadInput::eLeftShoulder) .value("RIGHT_SHOULDER", GamepadInput::eRightShoulder) .value("MENU1", GamepadInput::eMenu1) .value("MENU2", GamepadInput::eMenu2) .value("LEFT_STICK", GamepadInput::eLeftStick) .value("RIGHT_STICK", GamepadInput::eRightStick) .value("DPAD_UP", GamepadInput::eDpadUp) .value("DPAD_RIGHT", GamepadInput::eDpadRight) .value("DPAD_DOWN", GamepadInput::eDpadDown) .value("DPAD_LEFT", GamepadInput::eDpadLeft) .value("COUNT", GamepadInput::eCount); m.attr("BUTTON_FLAG_RELEASED") = py::int_(kButtonFlagTransitionUp); m.attr("BUTTON_FLAG_UP") = py::int_(kButtonFlagStateUp); m.attr("BUTTON_FLAG_PRESSED") = py::int_(kButtonFlagTransitionDown); m.attr("BUTTON_FLAG_DOWN") = py::int_(kButtonFlagStateDown); m.attr("KEYBOARD_MODIFIER_FLAG_SHIFT") = py::int_(kKeyboardModifierFlagShift); m.attr("KEYBOARD_MODIFIER_FLAG_CONTROL") = py::int_(kKeyboardModifierFlagControl); m.attr("KEYBOARD_MODIFIER_FLAG_ALT") = py::int_(kKeyboardModifierFlagAlt); m.attr("KEYBOARD_MODIFIER_FLAG_SUPER") = py::int_(kKeyboardModifierFlagSuper); m.attr("KEYBOARD_MODIFIER_FLAG_CAPS_LOCK") = py::int_(kKeyboardModifierFlagCapsLock); m.attr("KEYBOARD_MODIFIER_FLAG_NUM_LOCK") = py::int_(kKeyboardModifierFlagNumLock); py::class_<KeyboardEvent>(m, "KeyboardEvent") .def_readonly("device", &KeyboardEvent::device) .def_readonly("keyboard", &KeyboardEvent::keyboard) .def_readonly("type", &KeyboardEvent::type) .def_property_readonly("input", [](const KeyboardEvent& desc) { switch (desc.type) { case KeyboardEventType::eChar: return pybind11::cast(std::string( desc.character, strnlen(desc.character, kCharacterMaxNumBytes))); default: return pybind11::cast(desc.key); } }) .def_readonly("modifiers", &KeyboardEvent::modifiers); py::class_<MouseEvent>(m, "MouseEvent") .def_readonly("device", &MouseEvent::device) .def_readonly("mouse", &MouseEvent::mouse) .def_readonly("type", &MouseEvent::type) .def_readonly("normalized_coords", &MouseEvent::normalizedCoords) .def_readonly("pixel_coords", &MouseEvent::pixelCoords) .def_readonly("scrollDelta", &MouseEvent::scrollDelta) .def_readonly("modifiers", &MouseEvent::modifiers); py::class_<GamepadEvent>(m, "GamepadEvent") .def_readonly("device", &GamepadEvent::device) .def_readonly("gamepad", &GamepadEvent::gamepad) .def_readonly("input", &GamepadEvent::input) .def_readonly("value", &GamepadEvent::value); py::enum_<GamepadConnectionEventType>(m, "GamepadConnectionEventType") .value("CREATED", GamepadConnectionEventType::eCreated) .value("CONNECTED", GamepadConnectionEventType::eConnected) .value("DISCONNECTED", GamepadConnectionEventType::eDisconnected) .value("DESTROYED", GamepadConnectionEventType::eDestroyed); py::class_<GamepadConnectionEvent>(m, "GamepadConnectionEvent") .def_readonly("type", &GamepadConnectionEvent::type) .def_readonly("gamepad", &GamepadConnectionEvent::gamepad) .def_readonly("device", &GamepadConnectionEvent::device); py::class_<InputEvent>(m, "InputEvent") .def_readonly("deviceType", &InputEvent::deviceType) .def_readonly("device", &InputEvent::device) .def_property_readonly("event", [](const InputEvent& desc) { switch (desc.deviceType) { case DeviceType::eKeyboard: return pybind11::cast(desc.keyboardEvent); case DeviceType::eMouse: return pybind11::cast(desc.mouseEvent); case DeviceType::eGamepad: return pybind11::cast(desc.gamepadEvent); default: return py::cast(nullptr); } }); py::class_<ActionMappingDesc>(m, "ActionMappingDesc") .def_readonly("deviceType", &ActionMappingDesc::deviceType) .def_readonly("modifiers", &ActionMappingDesc::modifiers) .def_property_readonly("device", [](const ActionMappingDesc& desc) { switch (desc.deviceType) { case DeviceType::eKeyboard: return pybind11::cast(desc.keyboard); case DeviceType::eMouse: return pybind11::cast(desc.mouse); case DeviceType::eGamepad: return pybind11::cast(desc.gamepad); default: return py::cast(nullptr); } }) .def_property_readonly("input", [](const ActionMappingDesc& desc) { switch (desc.deviceType) { case DeviceType::eKeyboard: return pybind11::cast(desc.keyboardInput); case DeviceType::eMouse: return pybind11::cast(desc.mouseInput); case DeviceType::eGamepad: return pybind11::cast(desc.gamepadInput); default: return py::cast(nullptr); } }); py::class_<ActionEvent>(m, "ActionEvent") .def_readonly("action", &ActionEvent::action) .def_readonly("value", &ActionEvent::value) .def_readonly("flags", &ActionEvent::flags); m.def("get_action_mapping_desc_from_string", [](const std::string& str) { std::string deviceId; ActionMappingDesc actionMappingDesc; { py::gil_scoped_release nogil; actionMappingDesc = getActionMappingDescFromString(str.c_str(), &deviceId); } py::tuple t(4); t[0] = actionMappingDesc.deviceType; t[1] = actionMappingDesc.modifiers; switch (actionMappingDesc.deviceType) { case DeviceType::eKeyboard: { t[2] = actionMappingDesc.keyboardInput; break; } case DeviceType::eMouse: { t[2] = actionMappingDesc.mouseInput; break; } case DeviceType::eGamepad: { t[2] = actionMappingDesc.gamepadInput; break; } default: { t[2] = py::none(); break; } } t[3] = deviceId; return t; }); m.def("get_string_from_action_mapping_desc", [](KeyboardInput keyboardInput, KeyboardModifierFlags modifiers) { ActionMappingDesc actionMappingDesc = {}; actionMappingDesc.deviceType = DeviceType::eKeyboard; actionMappingDesc.keyboardInput = keyboardInput; actionMappingDesc.modifiers = modifiers; return getStringFromActionMappingDesc(actionMappingDesc, nullptr); }, py::call_guard<py::gil_scoped_release>()) .def("get_string_from_action_mapping_desc", [](MouseInput mouseInput, KeyboardModifierFlags modifiers) { ActionMappingDesc actionMappingDesc = {}; actionMappingDesc.deviceType = DeviceType::eMouse; actionMappingDesc.mouseInput = mouseInput; actionMappingDesc.modifiers = modifiers; return getStringFromActionMappingDesc(actionMappingDesc, nullptr); }, py::call_guard<py::gil_scoped_release>()) .def("get_string_from_action_mapping_desc", [](GamepadInput gamepadInput) { ActionMappingDesc actionMappingDesc = {}; actionMappingDesc.deviceType = DeviceType::eGamepad; actionMappingDesc.gamepadInput = gamepadInput; actionMappingDesc.modifiers = 0; return getStringFromActionMappingDesc(actionMappingDesc, nullptr); }, py::call_guard<py::gil_scoped_release>()); static ScriptCallbackRegistryPython<size_t, bool, const InputEvent&> s_inputEventCBs; static ScriptCallbackRegistryPython<size_t, bool, const KeyboardEvent&> s_keyboardEventCBs; static ScriptCallbackRegistryPython<size_t, bool, const MouseEvent&> s_mouseEventCBs; static ScriptCallbackRegistryPython<size_t, bool, const GamepadEvent&> s_gamepadEventCBs; static ScriptCallbackRegistryPython<size_t, void, const GamepadConnectionEvent&> s_gamepadConnectionEventCBs; static ScriptCallbackRegistryPython<size_t, bool, const ActionEvent&> s_actionEventCBs; defineInterfaceClass<IInput>(m, "IInput", "acquire_input_interface") .def("get_device_name", wrapInterfaceFunction(&IInput::getDeviceName), py::call_guard<py::gil_scoped_release>()) .def("get_device_type", wrapInterfaceFunction(&IInput::getDeviceType), py::call_guard<py::gil_scoped_release>()) .def("subscribe_to_input_events", [](IInput* iface, const decltype(s_inputEventCBs)::FuncT& eventFn, EventTypeMask eventTypes, InputDevice* device, SubscriptionOrder order) { auto eventFnCopy = s_inputEventCBs.create(eventFn); SubscriptionId id = iface->subscribeToInputEvents(device, eventTypes, s_inputEventCBs.call, eventFnCopy, order); s_inputEventCBs.add(hashPair(0x3e1, id), eventFnCopy); return id; }, py::arg("eventFn"), py::arg("eventTypes") = kEventTypeAll, py::arg("device") = nullptr, py::arg("order") = kSubscriptionOrderDefault, py::call_guard<py::gil_scoped_release>()) .def("unsubscribe_to_input_events", [](IInput* iface, SubscriptionId id) { iface->unsubscribeToInputEvents(id); s_inputEventCBs.removeAndDestroy(hashPair(0x3e1, id)); }, py::call_guard<py::gil_scoped_release>()) .def("get_keyboard_name", wrapInterfaceFunction(&IInput::getKeyboardName), py::call_guard<py::gil_scoped_release>()) .def("subscribe_to_keyboard_events", [](IInput* iface, Keyboard* keyboard, const decltype(s_keyboardEventCBs)::FuncT& eventFn) { auto eventFnCopy = s_keyboardEventCBs.create(eventFn); SubscriptionId id = iface->subscribeToKeyboardEvents(keyboard, s_keyboardEventCBs.call, eventFnCopy); s_keyboardEventCBs.add(hashPair(keyboard, id), eventFnCopy); return id; }, py::call_guard<py::gil_scoped_release>()) .def("unsubscribe_to_keyboard_events", [](IInput* iface, Keyboard* keyboard, SubscriptionId id) { iface->unsubscribeToKeyboardEvents(keyboard, id); s_keyboardEventCBs.removeAndDestroy(hashPair(keyboard, id)); }, py::call_guard<py::gil_scoped_release>()) .def("get_keyboard_value", wrapInterfaceFunction(&IInput::getKeyboardValue), py::call_guard<py::gil_scoped_release>()) .def("get_keyboard_button_flags", wrapInterfaceFunction(&IInput::getKeyboardButtonFlags), py::call_guard<py::gil_scoped_release>()) .def("get_mouse_name", wrapInterfaceFunction(&IInput::getMouseName), py::call_guard<py::gil_scoped_release>()) .def("get_mouse_value", wrapInterfaceFunction(&IInput::getMouseValue), py::call_guard<py::gil_scoped_release>()) .def("get_mouse_button_flags", wrapInterfaceFunction(&IInput::getMouseButtonFlags), py::call_guard<py::gil_scoped_release>()) .def("get_mouse_coords_normalized", wrapInterfaceFunction(&IInput::getMouseCoordsNormalized), py::call_guard<py::gil_scoped_release>()) .def("get_mouse_coords_pixel", wrapInterfaceFunction(&IInput::getMouseCoordsPixel), py::call_guard<py::gil_scoped_release>()) .def("subscribe_to_mouse_events", [](IInput* iface, Mouse* mouse, const decltype(s_mouseEventCBs)::FuncT& eventFn) { auto eventFnCopy = s_mouseEventCBs.create(eventFn); SubscriptionId id = iface->subscribeToMouseEvents(mouse, s_mouseEventCBs.call, eventFnCopy); s_mouseEventCBs.add(hashPair(mouse, id), eventFnCopy); return id; }, py::call_guard<py::gil_scoped_release>()) .def("unsubscribe_to_mouse_events", [](IInput* iface, Mouse* mouse, SubscriptionId id) { iface->unsubscribeToMouseEvents(mouse, id); s_mouseEventCBs.removeAndDestroy(hashPair(mouse, id)); }, py::call_guard<py::gil_scoped_release>()) .def("get_gamepad_name", wrapInterfaceFunction(&IInput::getGamepadName), py::call_guard<py::gil_scoped_release>()) .def("get_gamepad_guid", wrapInterfaceFunction(&IInput::getGamepadGuid), py::call_guard<py::gil_scoped_release>()) .def("get_gamepad_value", wrapInterfaceFunction(&IInput::getGamepadValue), py::call_guard<py::gil_scoped_release>()) .def("get_gamepad_button_flags", wrapInterfaceFunction(&IInput::getGamepadButtonFlags), py::call_guard<py::gil_scoped_release>()) .def("subscribe_to_gamepad_events", [](IInput* iface, Gamepad* gamepad, const decltype(s_gamepadEventCBs)::FuncT& eventFn) { auto eventFnCopy = s_gamepadEventCBs.create(eventFn); SubscriptionId id = iface->subscribeToGamepadEvents(gamepad, s_gamepadEventCBs.call, eventFnCopy); s_gamepadEventCBs.add(hashPair(gamepad, id), eventFnCopy); return id; }, py::call_guard<py::gil_scoped_release>()) .def("unsubscribe_to_gamepad_events", [](IInput* iface, Gamepad* gamepad, SubscriptionId id) { iface->unsubscribeToGamepadEvents(gamepad, id); s_gamepadEventCBs.removeAndDestroy(hashPair(gamepad, id)); }, py::call_guard<py::gil_scoped_release>()) .def("subscribe_to_gamepad_connection_events", [](IInput* iface, const decltype(s_gamepadConnectionEventCBs)::FuncT& eventFn) { auto eventFnCopy = s_gamepadConnectionEventCBs.create(eventFn); SubscriptionId id = iface->subscribeToGamepadConnectionEvents(s_gamepadConnectionEventCBs.call, eventFnCopy); s_gamepadConnectionEventCBs.add(id, eventFnCopy); return id; }, py::call_guard<py::gil_scoped_release>()) .def("unsubscribe_to_gamepad_connection_events", [](IInput* iface, SubscriptionId id) { iface->unsubscribeToGamepadConnectionEvents(id); s_gamepadConnectionEventCBs.removeAndDestroy(id); }, py::call_guard<py::gil_scoped_release>()) .def("get_actions", [](const IInput* iface, ActionMappingSet* actionMappingSet) { std::vector<std::string> res(iface->getActionCount(actionMappingSet)); auto actions = iface->getActions(actionMappingSet); for (size_t i = 0; i < res.size(); i++) { res[i] = actions[i]; } return res; }, py::call_guard<py::gil_scoped_release>()) .def("add_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, Keyboard* keyboard, KeyboardInput keyboardInput, KeyboardModifierFlags modifiers) { return iface->addActionMapping( actionMappingSet, action, ActionMappingDesc{ DeviceType::eKeyboard, { keyboard }, { keyboardInput }, modifiers }); }, py::call_guard<py::gil_scoped_release>()) .def("add_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, Gamepad* gamepad, GamepadInput gamepadInput) { return iface->addActionMapping( actionMappingSet, action, detail::toGamepadMapping(gamepad, gamepadInput)); }, py::call_guard<py::gil_scoped_release>()) .def("add_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, Mouse* mouse, MouseInput mouseInput, KeyboardModifierFlags modifiers) { return iface->addActionMapping( actionMappingSet, action, detail::toMouseMapping(mouse, mouseInput, modifiers)); }, py::call_guard<py::gil_scoped_release>()) .def("set_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, uint32_t index, Keyboard* keyboard, KeyboardInput keyboardInput, KeyboardModifierFlags modifiers) { return iface->setActionMapping( actionMappingSet, action, index, ActionMappingDesc{ DeviceType::eKeyboard, { keyboard }, { keyboardInput }, modifiers }); }, py::call_guard<py::gil_scoped_release>()) .def("set_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, uint32_t index, Gamepad* gamepad, GamepadInput gamepadInput) { return iface->setActionMapping( actionMappingSet, action, index, detail::toGamepadMapping(gamepad, gamepadInput)); }, py::call_guard<py::gil_scoped_release>()) .def("set_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, uint32_t index, Mouse* mouse, MouseInput mouseInput, KeyboardModifierFlags modifiers) { return iface->setActionMapping( actionMappingSet, action, index, detail::toMouseMapping(mouse, mouseInput, modifiers)); }, py::call_guard<py::gil_scoped_release>()) .def("remove_action_mapping", wrapInterfaceFunction(&IInput::removeActionMapping), py::call_guard<py::gil_scoped_release>()) .def("clear_action_mappings", wrapInterfaceFunction(&IInput::clearActionMappings), py::call_guard<py::gil_scoped_release>()) .def("get_action_mappings", [](const IInput* iface, ActionMappingSet* actionMappingSet, const char* action) { auto size = iface->getActionMappingCount(actionMappingSet, action); std::vector<ActionMappingDesc> res; res.reserve(size); auto mappings = iface->getActionMappings(actionMappingSet, action); std::copy(mappings, mappings + size, std::back_inserter(res)); return res; }, py::call_guard<py::gil_scoped_release>()) .def("get_action_mapping_count", wrapInterfaceFunction(&IInput::getActionMappingCount), py::call_guard<py::gil_scoped_release>()) .def("set_default_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, Keyboard* keyboard, KeyboardInput keyboardInput, KeyboardModifierFlags modifiers) { return setDefaultActionMapping( iface, actionMappingSet, action, ActionMappingDesc{ DeviceType::eKeyboard, { keyboard }, { keyboardInput }, modifiers }); }, py::call_guard<py::gil_scoped_release>()) .def("set_default_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, Gamepad* gamepad, GamepadInput gamepadInput) { return setDefaultActionMapping( iface, actionMappingSet, action, detail::toGamepadMapping(gamepad, gamepadInput)); }, py::call_guard<py::gil_scoped_release>()) .def("set_default_action_mapping", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, Mouse* mouse, MouseInput mouseInput, KeyboardModifierFlags modifiers) { return setDefaultActionMapping( iface, actionMappingSet, action, detail::toMouseMapping(mouse, mouseInput, modifiers)); }, py::call_guard<py::gil_scoped_release>()) .def("get_action_value", wrapInterfaceFunction(&IInput::getActionValue), py::call_guard<py::gil_scoped_release>()) .def("get_action_button_flags", wrapInterfaceFunction(&IInput::getActionButtonFlags), py::call_guard<py::gil_scoped_release>()) .def("subscribe_to_action_events", [](IInput* iface, ActionMappingSet* actionMappingSet, const char* action, const decltype(s_actionEventCBs)::FuncT& eventFn) { auto eventFnCopy = s_actionEventCBs.create(eventFn); SubscriptionId id = iface->subscribeToActionEvents(actionMappingSet, action, s_actionEventCBs.call, eventFnCopy); s_actionEventCBs.add(id, eventFnCopy); return id; }, py::call_guard<py::gil_scoped_release>()) .def("unsubscribe_to_action_events", [](IInput* iface, SubscriptionId id) { iface->unsubscribeToActionEvents(id); s_actionEventCBs.removeAndDestroy(id); }, py::call_guard<py::gil_scoped_release>()) .def("get_action_mapping_set_by_path", wrapInterfaceFunction(&IInput::getActionMappingSetByPath), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_modifier_flags", [](IInput* iface, KeyboardModifierFlags modifierFlags, const std::vector<const InputDevice*>& inputDev, const std::vector<DeviceType>& inputDevTypes, const std::vector<MouseInput>& mouseButtons) { return iface->getModifierFlags(modifierFlags, inputDev.data(), inputDev.size(), inputDevTypes.data(), inputDevTypes.size(), mouseButtons.data(), mouseButtons.size()); }, py::arg("modifiers") = KeyboardModifierFlags(0), py::arg("input_devices") = std::vector<const InputDevice*>(), py::arg("device_types") = std::vector<DeviceType>(), py::arg("mouse_buttons") = std::vector<MouseInput>(), py::call_guard<py::gil_scoped_release>()) .def("get_global_modifier_flags", [](IInput* iface, KeyboardModifierFlags modifierFlags, const std::vector<MouseInput>& mouseButtons) { return iface->getGlobalModifierFlags(modifierFlags, mouseButtons.data(), mouseButtons.size()); }, py::arg("modifiers") = KeyboardModifierFlags(0), py::arg("mouse_buttons") = std::vector<MouseInput>(), py::call_guard<py::gil_scoped_release>()) ; m.def("acquire_input_provider", [](const char* pluginName, const char* libraryPath) { return libraryPath ? acquireInterfaceFromLibraryForBindings<IInput>(libraryPath)->getInputProvider() : acquireInterfaceForBindings<IInput>(pluginName)->getInputProvider(); }, py::arg("plugin_name") = nullptr, py::arg("library_path") = nullptr, py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()); py::class_<InputProvider>(m, "InputProvider") .def("create_keyboard", wrapInterfaceFunction(&InputProvider::createKeyboard), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("destroy_keyboard", wrapInterfaceFunction(&InputProvider::destroyKeyboard), py::call_guard<py::gil_scoped_release>()) .def("update_keyboard", wrapInterfaceFunction(&InputProvider::updateKeyboard), py::call_guard<py::gil_scoped_release>()) .def("buffer_keyboard_key_event", [](InputProvider* iface, Keyboard* keyboard, KeyboardEventType type, KeyboardInput key, KeyboardModifierFlags modifiers) { KeyboardEvent event; event.keyboard = keyboard; event.type = type; event.key = key; event.modifiers = modifiers; iface->bufferKeyboardEvent(event); }, py::call_guard<py::gil_scoped_release>()) .def("buffer_keyboard_char_event", [](InputProvider* iface, Keyboard* keyboard, py::str character, KeyboardModifierFlags modifiers) { // Cast before releasing GIL auto characterStr = character.cast<std::string>(); py::gil_scoped_release nogil; KeyboardEvent event{}; event.keyboard = keyboard; event.type = KeyboardEventType::eChar; event.modifiers = modifiers; size_t maxCopyBytes = ::carb_min(characterStr.length(), size_t(kCharacterMaxNumBytes)); memcpy((void*)event.character, characterStr.c_str(), maxCopyBytes); iface->bufferKeyboardEvent(event); }) .def("create_mouse", wrapInterfaceFunction(&InputProvider::createMouse), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("destroy_mouse", wrapInterfaceFunction(&InputProvider::destroyMouse), py::call_guard<py::gil_scoped_release>()) .def("update_mouse", wrapInterfaceFunction(&InputProvider::updateMouse), py::call_guard<py::gil_scoped_release>()) .def("buffer_mouse_event", [](InputProvider* iface, Mouse* mouse, MouseEventType type, Float2 value, KeyboardModifierFlags modifiers, Float2 pixelValue) { MouseEvent event; event.mouse = mouse; event.type = type; if (type == MouseEventType::eScroll) { event.scrollDelta = value; } else { event.normalizedCoords = value; } event.pixelCoords = pixelValue; event.modifiers = modifiers; iface->bufferMouseEvent(event); }, py::call_guard<py::gil_scoped_release>()) .def("create_gamepad", wrapInterfaceFunction(&InputProvider::createGamepad), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("set_gamepad_connected", wrapInterfaceFunction(&InputProvider::setGamepadConnected), py::call_guard<py::gil_scoped_release>()) .def("destroy_gamepad", wrapInterfaceFunction(&InputProvider::destroyGamepad), py::call_guard<py::gil_scoped_release>()) .def("update_gamepad", wrapInterfaceFunction(&InputProvider::updateGamepad), py::call_guard<py::gil_scoped_release>()) .def("buffer_gamepad_event", [](InputProvider* iface, Gamepad* gamepad, GamepadInput input, float value) { GamepadEvent event; event.gamepad = gamepad; event.input = input; event.value = value; iface->bufferGamepadEvent(event); }, py::call_guard<py::gil_scoped_release>()); } } // namespace input } // namespace carb
38,370
C
49.822516
122
0.603284
omniverse-code/kit/include/carb/input/InputProvider.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 "../Defines.h" #include "InputTypes.h" namespace carb { namespace input { /** * Defines an input provider interface. * This interface is meant to be used only by the input providers. Hence it is in the separate file. * The examples of input providers could be windowing system or network input stream. */ struct InputProvider { /** * Create a logical keyboard. * * @param name Logical keyboard name. * @return The keyboard created. */ Keyboard*(CARB_ABI* createKeyboard)(const char* name); /** * Destroys the keyboard. * * @param keyboard The logical keyboard. */ void(CARB_ABI* destroyKeyboard)(Keyboard* keyboard); /** * Input "tick" for specific keyboard. Is meant to be called in the beginning of a new frame, right before sending * events. It saves old device state, allowing to differentiate pressed and released state of the buttons. @see * ButtonFlags. * * @param keyboard Logical keyboard to update. */ void(CARB_ABI* updateKeyboard)(Keyboard* keyboard); /** * Sends keyboard event. * * @param evt Keyboard event. */ void(CARB_ABI* bufferKeyboardEvent)(const KeyboardEvent& evt); /** * Create a logical mouse. * * @param name Logical mouse name. * @return The mouse created. */ Mouse*(CARB_ABI* createMouse)(const char* name); /** * Destroys the mouse. * * @param mouse The logical mouse. */ void(CARB_ABI* destroyMouse)(Mouse* mouse); /** * Input "tick" for specific mouse. Is meant to be called in the beginning of a new frame, right before sending * events. It saves old device state, allowing to differentiate pressed and released state of the buttons. @see * ButtonFlags. * * @param mouse Logical mouse to update. */ void(CARB_ABI* updateMouse)(Mouse* mouse); /** * Sends mouse event. * * @param evt Mouse event. */ void(CARB_ABI* bufferMouseEvent)(const MouseEvent& evt); /** * Create a logical gamepad. * * @param name Logical gamepad name. * @param guid Device GUID. * @return The gamepad created. */ Gamepad*(CARB_ABI* createGamepad)(const char* name, const char* guid); /** * Create a logical gamepad. * * @param gamepad The logical gamepad. * @param connected Is the gamepad connected?. */ void(CARB_ABI* setGamepadConnected)(Gamepad* gamepad, bool connected); /** * Destroys the gamepad. * * @param gamepad The logical gamepad. */ void(CARB_ABI* destroyGamepad)(Gamepad* gamepad); /** * Input "tick" for specific gamepad. Is meant to be called in the beginning of a new frame, right before sending * events. It saves old device state, allowing to differentiate pressed and released state of the buttons. @see * ButtonFlags. * * @param gamepad Logical gamepad to update. */ void(CARB_ABI* updateGamepad)(Gamepad* gamepad); /** * Send gamepad event. * * @param evt Mouse event. */ void(CARB_ABI* bufferGamepadEvent)(const GamepadEvent& evt); /** * Sends unified input event. * * @param evt A reference to unified input event description. */ void(CARB_ABI* bufferInputEvent)(const InputEvent& evt); }; } // namespace input } // namespace carb
3,890
C
27.195652
118
0.650643
omniverse-code/kit/include/carb/input/InputUtils.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 "../logging/Log.h" #include "IInput.h" #include <map> #include <string> #include <cstring> #include <functional> namespace carb { namespace input { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Name Mapping // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace detail { template <typename Key, typename LessFn, typename ExtractKeyFn, typename StaticMappingDesc, size_t count> const StaticMappingDesc* getMappingByKey(Key key, const StaticMappingDesc (&items)[count]) { static std::map<Key, const StaticMappingDesc*, LessFn> s_mapping; static bool s_isInitialized = false; if (!s_isInitialized) { for (size_t i = 0; i < count; ++i) { s_mapping.insert(std::make_pair(ExtractKeyFn().operator()(items[i]), &items[i])); } s_isInitialized = true; } auto found = s_mapping.find(key); if (found != s_mapping.end()) { return found->second; } return nullptr; } template <typename T> struct Less { bool operator()(const T& a, const T& b) const { return std::less<T>(a, b); } }; template <> struct Less<const char*> { bool operator()(const char* a, const char* b) const { return std::strcmp(a, b) < 0; } }; template <typename Struct, typename String> struct ExtractName { String operator()(const Struct& item) const { return item.name; } }; template <typename Struct, typename Ident> struct ExtractIdent { Ident operator()(const Struct& item) const { return item.ident; } }; template <typename Ident, typename String, typename StaticMappingDesc, size_t count> Ident getIdentByName(String name, const StaticMappingDesc (&items)[count], Ident defaultIdent) { using LessFn = Less<String>; using ExtractNameFn = ExtractName<StaticMappingDesc, String>; using ExtractIdentFn = ExtractIdent<StaticMappingDesc, Ident>; const auto* item = getMappingByKey<String, LessFn, ExtractNameFn, StaticMappingDesc, count>(name, items); return (item != nullptr) ? ExtractIdentFn().operator()(*item) : defaultIdent; } template <typename String, typename Ident, typename StaticMappingDesc, size_t count> String getNameByIdent(Ident ident, const StaticMappingDesc (&items)[count], String defaultName) { using LessFn = std::less<Ident>; using ExtractIdentFn = ExtractIdent<StaticMappingDesc, Ident>; using ExtractNameFn = ExtractName<StaticMappingDesc, String>; const auto* item = getMappingByKey<Ident, LessFn, ExtractIdentFn, StaticMappingDesc, count>(ident, items); return (item != nullptr) ? ExtractNameFn().operator()(*item) : defaultName; } } // namespace detail static constexpr struct { DeviceType ident; const char* name; } g_deviceTypeToName[] = { // clang-format off { DeviceType::eKeyboard, "Keyboard" }, { DeviceType::eMouse, "Mouse" }, { DeviceType::eGamepad, "Gamepad" } // clang-format on }; inline const char* getDeviceTypeString(DeviceType deviceType) { using namespace detail; return getNameByIdent(deviceType, g_deviceTypeToName, "Unknown"); } inline DeviceType getDeviceTypeFromString(const char* deviceTypeString) { using namespace detail; return getIdentByName(deviceTypeString, g_deviceTypeToName, DeviceType::eUnknown); } static constexpr struct { KeyboardInput ident; const char* name; } kKeyboardInputCodeName[] = { // clang-format off { KeyboardInput::eUnknown, "Unknown" }, { KeyboardInput::eSpace, "Space" }, { KeyboardInput::eApostrophe, "'" }, { KeyboardInput::eComma, "," }, { KeyboardInput::eMinus, "-" }, { KeyboardInput::ePeriod, "." }, { KeyboardInput::eSlash, "/" }, { KeyboardInput::eKey0, "0" }, { KeyboardInput::eKey1, "1" }, { KeyboardInput::eKey2, "2" }, { KeyboardInput::eKey3, "3" }, { KeyboardInput::eKey4, "4" }, { KeyboardInput::eKey5, "5" }, { KeyboardInput::eKey6, "6" }, { KeyboardInput::eKey7, "7" }, { KeyboardInput::eKey8, "8" }, { KeyboardInput::eKey9, "9" }, { KeyboardInput::eSemicolon, ";" }, { KeyboardInput::eEqual, "=" }, { KeyboardInput::eA, "A" }, { KeyboardInput::eB, "B" }, { KeyboardInput::eC, "C" }, { KeyboardInput::eD, "D" }, { KeyboardInput::eE, "E" }, { KeyboardInput::eF, "F" }, { KeyboardInput::eG, "G" }, { KeyboardInput::eH, "H" }, { KeyboardInput::eI, "I" }, { KeyboardInput::eJ, "J" }, { KeyboardInput::eK, "K" }, { KeyboardInput::eL, "L" }, { KeyboardInput::eM, "M" }, { KeyboardInput::eN, "N" }, { KeyboardInput::eO, "O" }, { KeyboardInput::eP, "P" }, { KeyboardInput::eQ, "Q" }, { KeyboardInput::eR, "R" }, { KeyboardInput::eS, "S" }, { KeyboardInput::eT, "T" }, { KeyboardInput::eU, "U" }, { KeyboardInput::eV, "V" }, { KeyboardInput::eW, "W" }, { KeyboardInput::eX, "X" }, { KeyboardInput::eY, "Y" }, { KeyboardInput::eZ, "Z" }, { KeyboardInput::eLeftBracket, "[" }, { KeyboardInput::eBackslash, "\\" }, { KeyboardInput::eRightBracket, "]" }, { KeyboardInput::eGraveAccent, "`" }, { KeyboardInput::eEscape, "Esc" }, { KeyboardInput::eTab, "Tab" }, { KeyboardInput::eEnter, "Enter" }, { KeyboardInput::eBackspace, "Backspace" }, { KeyboardInput::eInsert, "Insert" }, { KeyboardInput::eDel, "Del" }, { KeyboardInput::eRight, "Right" }, { KeyboardInput::eLeft, "Left" }, { KeyboardInput::eDown, "Down" }, { KeyboardInput::eUp, "Up" }, { KeyboardInput::ePageUp, "PageUp" }, { KeyboardInput::ePageDown, "PageDown" }, { KeyboardInput::eHome, "Home" }, { KeyboardInput::eEnd, "End" }, { KeyboardInput::eCapsLock, "CapsLock" }, { KeyboardInput::eScrollLock, "ScrollLock" }, { KeyboardInput::eNumLock, "NumLock" }, { KeyboardInput::ePrintScreen, "PrintScreen" }, { KeyboardInput::ePause, "Pause" }, { KeyboardInput::eF1, "F1" }, { KeyboardInput::eF2, "F2" }, { KeyboardInput::eF3, "F3" }, { KeyboardInput::eF4, "F4" }, { KeyboardInput::eF5, "F5" }, { KeyboardInput::eF6, "F6" }, { KeyboardInput::eF7, "F7" }, { KeyboardInput::eF8, "F8" }, { KeyboardInput::eF9, "F9" }, { KeyboardInput::eF10, "F10" }, { KeyboardInput::eF11, "F11" }, { KeyboardInput::eF12, "F12" }, { KeyboardInput::eNumpad0, "Num0" }, { KeyboardInput::eNumpad1, "Num1" }, { KeyboardInput::eNumpad2, "Num2" }, { KeyboardInput::eNumpad3, "Num3" }, { KeyboardInput::eNumpad4, "Num4" }, { KeyboardInput::eNumpad5, "Num5" }, { KeyboardInput::eNumpad6, "Num6" }, { KeyboardInput::eNumpad7, "Num7" }, { KeyboardInput::eNumpad8, "Num8" }, { KeyboardInput::eNumpad9, "Num9" }, { KeyboardInput::eNumpadDel, "NumDel" }, { KeyboardInput::eNumpadDivide, "NumDivide" }, { KeyboardInput::eNumpadMultiply, "NumMultiply" }, { KeyboardInput::eNumpadSubtract, "NumSubtract" }, { KeyboardInput::eNumpadAdd, "NumAdd" }, { KeyboardInput::eNumpadEnter, "NumEnter" }, { KeyboardInput::eNumpadEqual, "NumEqual" }, { KeyboardInput::eLeftShift, "LeftShift" }, { KeyboardInput::eLeftControl, "LeftControl" }, { KeyboardInput::eLeftAlt, "LeftAlt" }, { KeyboardInput::eLeftSuper, "LeftSuper" }, { KeyboardInput::eRightShift, "RightShift" }, { KeyboardInput::eRightControl, "RightControl" }, { KeyboardInput::eRightAlt, "RightAlt" }, { KeyboardInput::eRightSuper, "RightSuper" }, { KeyboardInput::eMenu, "Menu" } // clang-format on }; inline const char* getKeyboardInputString(KeyboardInput key) { using namespace detail; return getNameByIdent(key, kKeyboardInputCodeName, ""); } inline KeyboardInput getKeyboardInputFromString(const char* inputString) { using namespace detail; return getIdentByName(inputString, kKeyboardInputCodeName, KeyboardInput::eUnknown); } static constexpr struct { KeyboardModifierFlags ident; const char* name; } kModifierFlagName[] = { // clang-format off { kKeyboardModifierFlagShift, "Shift" }, { kKeyboardModifierFlagControl, "Ctrl" }, { kKeyboardModifierFlagAlt, "Alt" }, { kKeyboardModifierFlagSuper, "Super" }, { kKeyboardModifierFlagCapsLock, "CapsLock" }, { kKeyboardModifierFlagNumLock, "NumLock" } // clang-format on }; inline const char* getModifierFlagString(KeyboardModifierFlags flag) { using namespace detail; return getNameByIdent(flag, kModifierFlagName, ""); } inline KeyboardModifierFlags getModifierFlagFromString(const char* inputString) { using namespace detail; return getIdentByName(inputString, kModifierFlagName, 0); } const char kDeviceNameSeparator[] = "::"; const char kModifierSeparator[] = " + "; inline std::string getModifierFlagsString(KeyboardModifierFlags mod) { std::string res = ""; for (const auto& desc : kModifierFlagName) { const auto& flag = desc.ident; if ((mod & flag) != flag) continue; if (!res.empty()) res += kModifierSeparator; res += desc.name; } return res; } inline KeyboardModifierFlags getModifierFlagsFromString(const char* modString) { KeyboardModifierFlags res = KeyboardModifierFlags(0); const size_t kModifierSeparatorSize = strlen(kModifierSeparator); std::string modifierNameString; const char* modifierName = modString; while (true) { const char* modifierNameEnd = strstr(modifierName, kModifierSeparator); if (modifierNameEnd) { modifierNameString = std::string(modifierName, modifierNameEnd - modifierName); } else { modifierNameString = std::string(modifierName); } KeyboardModifierFlags mod = getModifierFlagFromString(modifierNameString.c_str()); if (mod) { res = (KeyboardModifierFlags)((uint32_t)res | (uint32_t)mod); } else { CARB_LOG_VERBOSE("Unknown hotkey modifier encountered: %s in %s", modifierNameString.c_str(), modString); } if (!modifierNameEnd) { break; } modifierName = modifierNameEnd; modifierName += kModifierSeparatorSize; } return res; } static constexpr struct { MouseInput ident; const char* name; } kMouseInputCodeName[] = { // clang-format off { MouseInput::eLeftButton, "LeftButton" }, { MouseInput::eRightButton, "RightButton" }, { MouseInput::eMiddleButton, "MiddleButton" }, { MouseInput::eForwardButton, "ForwardButton" }, { MouseInput::eBackButton, "BackButton" }, { MouseInput::eScrollRight, "ScrollRight" }, { MouseInput::eScrollLeft, "ScrollLeft" }, { MouseInput::eScrollUp, "ScrollUp" }, { MouseInput::eScrollDown, "ScrollDown" }, { MouseInput::eMoveRight, "MoveRight" }, { MouseInput::eMoveLeft, "MoveLeft" }, { MouseInput::eMoveUp, "MoveUp" }, { MouseInput::eMoveDown, "MoveDown" } // clang-format on }; inline const char* getMouseInputString(MouseInput key) { using namespace detail; return getNameByIdent(key, kMouseInputCodeName, ""); } inline MouseInput getMouseInputFromString(const char* inputString) { using namespace detail; return getIdentByName(inputString, kMouseInputCodeName, MouseInput::eCount); } static constexpr struct { GamepadInput ident; const char* name; } kGamepadInputCodeName[] = { // clang-format off { GamepadInput::eLeftStickRight, "LeftStickRight" }, { GamepadInput::eLeftStickLeft, "LeftStickLeft" }, { GamepadInput::eLeftStickUp, "LeftStickUp" }, { GamepadInput::eLeftStickDown, "LeftStickDown" }, { GamepadInput::eRightStickRight, "RightStickRight" }, { GamepadInput::eRightStickLeft, "RightStickLeft" }, { GamepadInput::eRightStickUp, "RightStickUp" }, { GamepadInput::eRightStickDown, "RightStickDown" }, { GamepadInput::eLeftTrigger, "LeftTrigger" }, { GamepadInput::eRightTrigger, "RightTrigger" }, { GamepadInput::eA, "ButtonA" }, { GamepadInput::eB, "ButtonB" }, { GamepadInput::eX, "ButtonX" }, { GamepadInput::eY, "ButtonY" }, { GamepadInput::eLeftShoulder, "LeftShoulder" }, { GamepadInput::eRightShoulder, "RightShoulder" }, { GamepadInput::eMenu1, "Menu1" }, { GamepadInput::eMenu2, "Menu2" }, { GamepadInput::eLeftStick, "LeftStick" }, { GamepadInput::eRightStick, "RightStick" }, { GamepadInput::eDpadUp, "DpadUp" }, { GamepadInput::eDpadRight, "DpadRight" }, { GamepadInput::eDpadDown, "DpadDown" }, { GamepadInput::eDpadLeft, "DpadLeft" } // clang-format on }; inline const char* getGamepadInputString(GamepadInput key) { using namespace detail; return getNameByIdent(key, kGamepadInputCodeName, ""); } inline GamepadInput getGamepadInputFromString(const char* inputString) { using namespace detail; return getIdentByName(inputString, kGamepadInputCodeName, GamepadInput::eCount); } enum class PreviousButtonState { kUp, kDown }; inline PreviousButtonState toPreviousButtonState(bool wasDown) { return wasDown ? PreviousButtonState::kDown : PreviousButtonState::kUp; } enum class CurrentButtonState { kUp, kDown }; inline CurrentButtonState toCurrentButtonState(bool isDown) { return isDown ? CurrentButtonState::kDown : CurrentButtonState::kUp; } inline ButtonFlags toButtonFlags(PreviousButtonState previousButtonState, CurrentButtonState currentButtonState) { ButtonFlags flags = 0; if (currentButtonState == CurrentButtonState::kDown) { flags = kButtonFlagStateDown; if (previousButtonState == PreviousButtonState::kUp) flags |= kButtonFlagTransitionDown; } else { flags = kButtonFlagStateUp; if (previousButtonState == PreviousButtonState::kDown) flags |= kButtonFlagTransitionUp; } return flags; } inline std::string getDeviceNameString(DeviceType deviceType, const char* deviceId) { if ((size_t)deviceType >= (size_t)DeviceType::eCount) return ""; std::string result = getDeviceTypeString(deviceType); if (deviceId) { result.append("["); result.append(deviceId); result.append("]"); } return result; } inline void parseDeviceNameString(const char* deviceName, DeviceType* deviceType, std::string* deviceId) { if (!deviceName) { CARB_LOG_WARN("parseDeviceNameString: Empty device name"); if (deviceType) { *deviceType = DeviceType::eCount; } return; } const char* deviceIdString = strstr(deviceName, "["); if (deviceType) { if (deviceIdString) { std::string deviceTypeString(deviceName, deviceIdString - deviceName); *deviceType = getDeviceTypeFromString(deviceTypeString.c_str()); } else { *deviceType = getDeviceTypeFromString(deviceName); } } if (deviceId) { if (deviceIdString) { const char* deviceNameEnd = deviceIdString + strlen(deviceIdString); *deviceId = std::string(deviceIdString + 1, deviceNameEnd - deviceIdString - 2); } else { *deviceId = ""; } } } inline bool getDeviceInputFromString(const char* deviceInputString, DeviceType* deviceTypeOut, KeyboardInput* keyboardInputOut, MouseInput* mouseInputOut, GamepadInput* gamepadInputOut, std::string* deviceIdOut = nullptr) { if (!deviceTypeOut) return false; const char* deviceInputStringTrimmed = deviceInputString; // Skip initial spaces while (*deviceInputStringTrimmed == ' ') ++deviceInputStringTrimmed; // Skip device name const char* inputNameString = strstr(deviceInputStringTrimmed, kDeviceNameSeparator); std::string deviceName; // No device name specified - fall back if (!inputNameString) inputNameString = deviceInputStringTrimmed; else { deviceName = std::string(deviceInputStringTrimmed, inputNameString - deviceInputStringTrimmed); const size_t kDeviceNameSeparatorLen = strlen(kDeviceNameSeparator); inputNameString += kDeviceNameSeparatorLen; } parseDeviceNameString(deviceName.c_str(), deviceTypeOut, deviceIdOut); if ((*deviceTypeOut == DeviceType::eKeyboard) && keyboardInputOut) { KeyboardInput keyboardInput = getKeyboardInputFromString(inputNameString); *keyboardInputOut = keyboardInput; return (keyboardInput != KeyboardInput::eCount); } if ((*deviceTypeOut == DeviceType::eMouse) && mouseInputOut) { MouseInput mouseInput = getMouseInputFromString(inputNameString); *mouseInputOut = mouseInput; return (mouseInput != MouseInput::eCount); } if ((*deviceTypeOut == DeviceType::eGamepad) && gamepadInputOut) { GamepadInput gamepadInput = getGamepadInputFromString(inputNameString); *gamepadInputOut = gamepadInput; return (gamepadInput != GamepadInput::eCount); } return false; } inline ActionMappingDesc getActionMappingDescFromString(const char* hotkeyString, std::string* deviceId) { const size_t kModifierSeparatorSize = strlen(kModifierSeparator); ActionMappingDesc actionMappingDesc; actionMappingDesc.keyboard = nullptr; actionMappingDesc.mouse = nullptr; actionMappingDesc.gamepad = nullptr; actionMappingDesc.modifiers = (KeyboardModifierFlags)0; std::string modifierNameString; const char* modifierName = hotkeyString; while (true) { const char* modifierNameEnd = strstr(modifierName, kModifierSeparator); if (modifierNameEnd) { modifierNameString = std::string(modifierName, modifierNameEnd - modifierName); } else { modifierNameString = std::string(modifierName); } KeyboardModifierFlags mod = getModifierFlagFromString(modifierNameString.c_str()); if (mod) { actionMappingDesc.modifiers = (KeyboardModifierFlags)((uint32_t)actionMappingDesc.modifiers | (uint32_t)mod); } else { getDeviceInputFromString(modifierNameString.c_str(), &actionMappingDesc.deviceType, &actionMappingDesc.keyboardInput, &actionMappingDesc.mouseInput, &actionMappingDesc.gamepadInput, deviceId); } if (!modifierNameEnd) { break; } modifierName = modifierNameEnd; modifierName += kModifierSeparatorSize; } return actionMappingDesc; } inline std::string getStringFromActionMappingDesc(const ActionMappingDesc& actionMappingDesc, const char* deviceName = nullptr) { std::string result = getModifierFlagsString(actionMappingDesc.modifiers); if (!result.empty()) { result.append(kModifierSeparator); } if (deviceName) { result.append(deviceName); } else { result.append(getDeviceTypeString(actionMappingDesc.deviceType)); } result.append(kDeviceNameSeparator); switch (actionMappingDesc.deviceType) { case DeviceType::eKeyboard: { result.append(getKeyboardInputString(actionMappingDesc.keyboardInput)); break; } case DeviceType::eMouse: { result.append(getMouseInputString(actionMappingDesc.mouseInput)); break; } case DeviceType::eGamepad: { result.append(getGamepadInputString(actionMappingDesc.gamepadInput)); break; } default: { break; } } return result; } inline bool setDefaultActionMapping(IInput* input, ActionMappingSet* actionMappingSet, const char* actionName, const ActionMappingDesc& desc) { size_t actionMappingsCount = input->getActionMappingCount(actionMappingSet, actionName); if (actionMappingsCount > 0) { return false; } input->addActionMapping(actionMappingSet, actionName, desc); return true; } /** * Subscribes to the keyboard event stream for a specified keyboard. * * @param input A pointer to input interface. * @param keyboard A pointer to Logical keyboard, or nullptr if subscription to events from all keyboards is desired. * @param functor A universal reference to function-like callable object to be called on each keyboard event. * @return Subscription identifier. */ template <typename Functor> inline SubscriptionId subscribeToKeyboardEvents(IInput* input, Keyboard* keyboard, Functor&& functor) { return input->subscribeToKeyboardEvents( keyboard, [](const KeyboardEvent& evt, void* userData) -> bool { return (*static_cast<Functor*>(userData))(evt); }, &functor); } /** * Subscribes to the mouse event stream for a specified mouse. * * @param input A pointer to input interface. * @param mouse A pointer to Logical mouse, or nullptr if subscription to events from all mice is desired. * @param functor A universal reference to function-like callable object to be called on each mouse event. * @return Subscription identifier. */ template <typename Functor> inline SubscriptionId subscribeToMouseEvents(IInput* input, Mouse* mouse, Functor&& functor) { return input->subscribeToMouseEvents( mouse, [](const MouseEvent& evt, void* userData) -> bool { return (*static_cast<Functor*>(userData))(evt); }, &functor); } /** * Subscribes to the gamepad event stream for a specified gamepad. * * @param input A pointer to input interface. * @param gamepad A pointer to Logical gamepad, or nullptr if subscription to events from all gamepads is desired. * @param functor A universal reference to function-like callable object to be called on each gamepad event. * @return Subscription identifier. */ template <typename Functor> inline SubscriptionId subscribeToGamepadEvents(IInput* input, Gamepad* gamepad, Functor&& functor) { return input->subscribeToGamepadEvents( gamepad, [](const GamepadEvent& evt, void* userData) -> bool { return (*static_cast<Functor*>(userData))(evt); }, &functor); } /** * Subscribes to the gamepad connection event stream. * Once subscribed callback is called for all previously created gamepads. * * @param input A pointer to input interface. * @param functor A universal reference to function-like callable object to be called on each gamepad connection event. * @return Subscription identifier. */ template <typename Functor> inline SubscriptionId subscribeToGamepadConnectionEvents(IInput* input, Functor&& functor) { return input->subscribeToGamepadConnectionEvents( [](const GamepadConnectionEvent& evt, void* userData) { (*static_cast<Functor*>(userData))(evt); }, &functor); } /** * Subscribes to the action event stream for a specified action. * Event is triggered on any action value change. * * @param input A pointer to input interface. * @param actionMappingSet A pointer to action mapping set * @param actionName A pointer to action string identifier. * @param functor A universal reference to function-like callable object to be called on the action event. * @return Subscription identifier. */ template <typename Functor> inline SubscriptionId subscribeToActionEvents(IInput* input, ActionMappingSet* actionMappingSet, const char* actionName, Functor&& functor) { return input->subscribeToActionEvents( actionMappingSet, actionName, [](const ActionEvent& evt, void* userData) -> bool { return (*static_cast<Functor*>(userData))(evt); }, &functor); } /** * Filter and modify a unified input events in the event buffer. * * @param input A pointer to input interface. * @param functor A universal reference to function-like callable object to be called on each input event. */ template <typename Callable> inline void filterBufferedEvents(IInput* input, Callable&& callable) { using Func = std::decay_t<Callable>; input->filterBufferedEvents( [](InputEvent& evt, void* userData) { return (*static_cast<Func*>(userData))(evt); }, &callable); } } // namespace input } // namespace carb
25,506
C
30.725124
122
0.647299
omniverse-code/kit/include/carb/input/IInput.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 "InputTypes.h" namespace carb { namespace input { struct InputProvider; class ActionMappingSet; /** * Defines an input interface. * * Input plugin allows user to listen to the input devices, but it * is not intended to work with the input hardware. The input hardware processing * is delegated to the input providers, which should be implemented as a separate * plugins. * Input providers create logical input devices. For example, a window may have a keyboard and mouse associated * with it, i.e. a physical keyboard state may be different from a logical * keyboard associated with a window, due to some physical key state changes * being sent to a different window. * * Everything to be used by input providers is put into the InputProvider struct in the separate file. * All the functions from Input.h is meant to be used by input consumers (end user). * * User can subscribe to the device events, as well as device connection events, * and upon subscribing to device connection events, user immediately receives * "connect" notifications for all already present events of the kind. Similar is * true for unsubscribing - user will immediately get "disconnect" notifications * for all still present events. * * One notable feature of device handling is that there is no logical difference * between a button(key) and an axis: both can be either polled by value, producing * floating-point value, or by button flags, which allow to treat analog inputs * as buttons (one example is treat gamepad stick as discrete d-pad). * * The plugins also allows to map actions to device inputs, allowing to * set up multiple slots per action mapping. Those actions could be polled in * a similar manner (i.e. by value or as button flags). */ struct IInput { CARB_PLUGIN_INTERFACE("carb::input::IInput", 1, 1) /** * Gets the input provider's part of the input interface. * * @return Input provider interface. */ InputProvider*(CARB_ABI* getInputProvider)(); /** * Start processing input. */ void(CARB_ABI* startup)(); /** * Shutdown and stop processing input. */ void(CARB_ABI* shutdown)(); /** * Get keyboard logical device name. * * @param keyboard Logical keyboard. * @return Specified keyboard logical device name string. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use getDeviceName instead. @endrst */ const char*(CARB_ABI* getKeyboardName)(Keyboard* keyboard); /** * Subscribes plugin user to the keyboard event stream for a specified keyboard. * * @param keyboard Logical keyboard, or nullptr if subscription to events from all keyboards is desired. * @param fn Callback function to be called on received event. * @param userData Pointer to the user data to be passed into the callback. * @return Subscription identifier. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use subscribeToInputEvents instead. @endrst */ SubscriptionId(CARB_ABI* subscribeToKeyboardEvents)(Keyboard* keyboard, OnKeyboardEventFn fn, void* userData); /** * Unsubscribes plugin user from the keyboard event stream for a specified keyboard. * * @param keyboard Logical keyboard. * @param subscriptionId Subscription identifier. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use unsubscribeToInputEvents instead. @endrst */ void(CARB_ABI* unsubscribeToKeyboardEvents)(Keyboard* keyboard, SubscriptionId id); /** * Gets the value for the specified keyboard input kind or number of keys that are pressed. * * @param keyboard Logical keyboard or nullptr to test all keyboards. * @param input Keyboard input kind (key) to test, or KeyboardInput::eCount to count the number of keys down. * @return Specified keyboard input value when key is specific, or count of keys pressed for KeyboardInput::eCount. */ float(CARB_ABI* getKeyboardValue)(Keyboard* keyboard, KeyboardInput input); /** * Gets the button flag for the specified keyboard input kind. * Each input is treated as button, based on the press threshold. * * @param keyboard Logical keyboard. * @param input Keyboard input kind (key). * @return Specified keyboard input as button flags. */ ButtonFlags(CARB_ABI* getKeyboardButtonFlags)(Keyboard* keyboard, KeyboardInput input); /** * Get mouse logical device name. * * @param mouse Logical mouse. * @return Specified mouse logical device name string. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use getDeviceName instead. @endrst */ const char*(CARB_ABI* getMouseName)(Mouse* mouse); /** * Gets the value for the specified mouse input kind. * * @param mouse Logical mouse. * @param input Mouse input kind (button/axis). * @return Specified mouse input value. */ float(CARB_ABI* getMouseValue)(Mouse* mouse, MouseInput input); /** * Gets the button flag for the specified mouse input kind. * Each input is treated as button, based on the press threshold. * * @param mouse Logical mouse. * @param input Mouse input kind (button/axis). * @return Specified mouse input as button flags. */ ButtonFlags(CARB_ABI* getMouseButtonFlags)(Mouse* mouse, MouseInput input); /** * Gets the mouse coordinates for the specified mouse, normalized by the associated window size. * * @param mouse Logical mouse. * @return Coordinates. */ Float2(CARB_ABI* getMouseCoordsNormalized)(Mouse* mouse); /** * Gets the absolute mouse coordinates for the specified mouse. * * @param mouse Logical mouse. * @return Coordinates. */ Float2(CARB_ABI* getMouseCoordsPixel)(Mouse* mouse); /** * Subscribes plugin user to the mouse event stream for a specified mouse. * * @param mouse Logical mouse, or nullptr if subscription to events from all mice is desired. * @param fn Callback function to be called on received event. * @param userData Pointer to the user data to be passed into the callback. * @return Subscription identifier. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use subscribeToInputEvents instead. @endrst */ SubscriptionId(CARB_ABI* subscribeToMouseEvents)(Mouse* mouse, OnMouseEventFn fn, void* userData); /** * Unsubscribes plugin user from the mouse event stream for a specified mouse. * * @param mouse Logical mouse. * @param subscriptionId Subscription identifier. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use unsubscribeToInputEvents instead. @endrst */ void(CARB_ABI* unsubscribeToMouseEvents)(Mouse* mouse, SubscriptionId id); /** * Get gamepad logical device name. * * @param gamepad Logical gamepad. * @return Specified gamepad logical device name string. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use getDeviceName instead. @endrst */ const char*(CARB_ABI* getGamepadName)(Gamepad* gamepad); /** * Get gamepad GUID. * * @param gamepad Logical gamepad. * @return Specified gamepad logical device GUID. */ const char*(CARB_ABI* getGamepadGuid)(Gamepad* gamepad); /** * Gets the value for the specified gamepad input kind. * * @param gamepad Logical gamepad. * @param input Gamepad input kind (button/axis). * @return Specified gamepad input value. */ float(CARB_ABI* getGamepadValue)(Gamepad* gamepad, GamepadInput input); /** * Gets the button flag for the specified gamepad input kind. * Each input is treated as button, based on the press threshold. * * @param gamepad Logical gamepad. * @param input Gamepad input kind (button/axis). * @return Specified gamepad input as button flags. */ ButtonFlags(CARB_ABI* getGamepadButtonFlags)(Gamepad* gamepad, GamepadInput input); /** * Subscribes plugin user to the gamepad event stream for a specified gamepad. * * @param gamepad Logical gamepad, or nullptr if subscription to events from all gamepads is desired. * @param fn Callback function to be called on received event. * @param userData Pointer to the user data to be passed into the callback. * @return Subscription identifier. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use subscribeToInputEvents instead. @endrst */ SubscriptionId(CARB_ABI* subscribeToGamepadEvents)(Gamepad* gamepad, OnGamepadEventFn fn, void* userData); /** * Unsubscribes plugin user from the gamepad event stream for a specified gamepad. * * @param gamepad Logical gamepad. * @param subscriptionId Subscription identifier. * * @rst .. deprecated:: 100.1 This method is deprecated and will be removed soon, please use unsubscribeToInputEvents instead. @endrst */ void(CARB_ABI* unsubscribeToGamepadEvents)(Gamepad* gamepad, SubscriptionId id); /** * Subscribes plugin user to the gamepad connection event stream. * Once subscribed callback is called for all previously created gamepads. * * @param fn Callback function to be called on received event. * @param userData Pointer to the user data to be passed into the callback. * @return Subscription identifier. */ SubscriptionId(CARB_ABI* subscribeToGamepadConnectionEvents)(OnGamepadConnectionEventFn fn, void* userData); /** * Unsubscribes plugin user from the gamepad connection event stream. * Unsubscription triggers callback to be called with all devices left as being destroyed. * * @param subscriptionId Subscription identifier. */ void(CARB_ABI* unsubscribeToGamepadConnectionEvents)(SubscriptionId id); /** * Processes buffered events queue and sends unconsumed events as device events, action mapping events, and * updates device states. Clears buffered events queues. */ void(CARB_ABI* distributeBufferedEvents)(); /** * Create action mapping set - a place in settings where named action mappings are stored. * * @param settingsPath Path in settings where the set mappings are stored. * @return Opaque pointer to the action mapping set. */ ActionMappingSet*(CARB_ABI* createActionMappingSet)(const char* settingsPath); /** * Get existing action mapping set from the settings path provided. * * @param settingsPath Path in settings where the set mappings are stored. * @return Opaque pointer to the action mapping set. */ ActionMappingSet*(CARB_ABI* getActionMappingSetByPath)(const char* settingsPath); /** * Destroy action mapping set. * * @param actionMappingSet Opaque pointer to the action mapping set. */ void(CARB_ABI* destroyActionMappingSet)(ActionMappingSet* actionMappingSet); /** * Get total action count registered in the plugin with 1 or more action mapping. * * @return The number of the actions. */ size_t(CARB_ABI* getActionCount)(ActionMappingSet* actionMappingSet); /** * Get array of all actions. * The size of an array is equal to the Input::getActionCount(). * * @return The array of actions. */ const char* const*(CARB_ABI* getActions)(ActionMappingSet* actionMappingSet); /** * Adds action mapping to the specified action. * Each action keeps a list of mappings. This function push mapping to the end of the list. * * @param actionName Action string identifier. * @param desc Action mapping description. * @return The index of added mapping. */ size_t(CARB_ABI* addActionMapping)(ActionMappingSet* actionMappingSet, const char* actionName, const ActionMappingDesc& desc); /** * Sets and overrides the indexed action mapping for the specified action. * Each action keeps a list of mappings. This function sets list item according by the index. * * @param actionName Action string identifier. * @param index The index of mapping to override. It should be in range [0, mapping count). * @param desc Action mapping description. */ void(CARB_ABI* setActionMapping)(ActionMappingSet* actionMappingSet, const char* actionName, size_t index, const ActionMappingDesc& desc); /** * Remove indexed action mapping for the specified action. * Each action keeps a list of mappings. This function removes list item by the index. * * @param actionName Action string identifier. * @param index The index of mapping to remove. It should be in range [0, mapping count). */ void(CARB_ABI* removeActionMapping)(ActionMappingSet* actionMappingSet, const char* actionName, size_t index); /** * Clears and removes all mappings associated with the action. * * @param actionName Action string identifier. */ void(CARB_ABI* clearActionMappings)(ActionMappingSet* actionMappingSet, const char* actionName); /** * Get mappings count associated with the action. * * @param action Action string identifier. * @return The number of the mapping in the list for an action. */ size_t(CARB_ABI* getActionMappingCount)(ActionMappingSet* actionMappingSet, const char* actionName); /** * Get array of mappings associated with the action. * The size of an array is equal to the Input::getMappingCount(). * * @param actionName Action string identifier. * @return The array of mappings for an action. */ const ActionMappingDesc*(CARB_ABI* getActionMappings)(ActionMappingSet* actionMappingSet, const char* actionName); /** * Gets the value for the specified action. * If multiple mapping are associated with the action the biggest value is returned. * * @param actionName Action string identifier. * @return Specified action value. */ float(CARB_ABI* getActionValue)(ActionMappingSet* actionMappingSet, const char* actionName); /** * Gets the button flag for the specified action. * Each mapping is treated as button, based on the press threshold. * * @param actionName Action string identifier. * @return Specified action value as button flags. */ ButtonFlags(CARB_ABI* getActionButtonFlags)(ActionMappingSet* actionMappingSet, const char* actionName); /** * Subscribes plugin user to the action event stream for a specified action. * Event is triggered on any action value change. * * @param action Action string identifier. * @param fn Callback function to be called on received event. * @param userData Pointer to the user data to be passed into the callback. * @return Subscription identifier. */ SubscriptionId(CARB_ABI* subscribeToActionEvents)(ActionMappingSet* actionMappingSet, const char* actionName, OnActionEventFn fn, void* userData); /** * Unsubscribes plugin user from the action event stream for a specified action. * * @param action Action string identifier. * @param subscriptionId Subscription identifier. */ void(CARB_ABI* unsubscribeToActionEvents)(SubscriptionId id); /** * Filters all buffered events by calling the specified filter function on each event. * * The given @p fn may modify events in-place and/or may add additional events via the InputProvider obtained from * getInputProvider(). Any additional events that are added during a call to filterBufferedEvents() will not be * passed to @p fn during that call. However, future calls to filterBufferedEvents() will pass the events to @p fn. * Any new buffered events added by InputProvider during @p fn will be added to the end of the event list. Events * modified during @p fn remain in their relative position in the event list. * * The outcome of an event is based on what @p fn returns for that event. If FilterResult::eConsume is returned, the * event is considered processed and is removed from the list of buffered events. Future calls to * filterBufferedEvents() will not receive the event and it will not be sent when distributeBufferedEvents() is * called. If FilterResult::eRetain is returned, the (possibly modified) event remains in the list of buffered * events. Future calls to filterBufferedEvents() will receive the event and it will be sent when * distributeBufferedEvents() is called. * * This function may be called multiple times to re-filter events. For instance, the given @p fn may be interested * in only certain types of events. * * The remaining buffered events are sent when distributeBufferedEvents() is called, at which point the list of * buffered events is cleared. * * @warning Calling filterBufferedEvents() or distributeBufferedEvents() from @p fn is expressly disallowed. * * @thread_safety An internal lock is held while @p fn is called on all events, which synchronizes-with * distributeBufferedEvents() and the various InputProvider functions to buffer events. Although the lock provides * thread safety to synchronize these operations, if buffered events are added from other threads it is conceivable * that events could be added between filterBufferedEvents() and distributeBufferedEvents(), causing them to be sent * before being filtered. If this is a cause for concern, use of an external lock is recommended. * * @param fn A pointer to a callback function to be called on each input event. * @param userData A pointer to the user data to be passed into the callback. */ void(CARB_ABI* filterBufferedEvents)(InputEventFilterFn fn, void* userData); /** * Get input device name. * * @param device Input device. * @return Specified input device name string. */ const char*(CARB_ABI* getDeviceName)(InputDevice* device); /** * Get input device type. * * @param device Input device. * @return Specified input device type or DeviceType::eUnknown. */ DeviceType(CARB_ABI* getDeviceType)(InputDevice* device); /** * Subscribes plugin user to the input event stream for a specified device. * * @param device Input device, or nullptr if subscription to events from all devices is desired. * @param events A bit mask to event types to subscribe to. Currently kEventTypeAll is only supported. * @param fn Callback function to be called on received event. * @param userData Pointer to the user data to be passed into the callback. * @param order Subscriber position hint [0..N-1] from the beginning, [-1, -N] from the end (-1 is default). * @return Subscription identifier. */ SubscriptionId(CARB_ABI* subscribeToInputEvents)( InputDevice* device, EventTypeMask events, OnInputEventFn fn, void* userData, SubscriptionOrder order); /** * Unsubscribes plugin user from the input event stream for a specified device. * * @param subscriptionId Subscription identifier. */ void(CARB_ABI* unsubscribeToInputEvents)(SubscriptionId id); /** * Gets the modifer state on specific devices and/or device-types. * * @param modifierFlags The modifiers to check against, or 0 to check against all modifiers. * @param devices An array of InputDevice pointers. * @param nDevices The number of devices in the devices array. * @param deviceTypes An array of device-types to check against. * @param nDeviceTypes The number of device-types in the devices array. * @param mouseButtons An array of mouse buttons to test against. * @param numMouseButtons The number of buttons in the mouseButtons array. * @return KeyboardModifierFlags for all devices queried. */ KeyboardModifierFlags(CARB_ABI* getModifierFlags)(KeyboardModifierFlags modifierFlags, const InputDevice* const* devices, size_t nDevices, const DeviceType* const deviceTypes, size_t nDeviceTypes, const MouseInput* mouseButtons, size_t numMouseButtons); /** * Gets the modifer state on all known keyboard and mouse devices. * * @param modifierFlags The modifiers to check against, or 0 to check against all modifiers. * @param mouseButtons An array of mouse buttons to test against (providing nullptr will test against all mouse * buttons). * @param numMouseButtons The number of buttons in the mouseButtons array. * @return KeyboardModifierFlags for all devices queried. */ KeyboardModifierFlags(CARB_ABI* getGlobalModifierFlags)(KeyboardModifierFlags modifierFlags, const MouseInput* mouseButtons, size_t numMouseButtons); }; } // namespace input } // namespace carb
22,764
C
41.001845
120
0.672685
omniverse-code/kit/include/carb/delegate/Delegate.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 Delegate implementation. #pragma once #include "../Defines.h" #include "../Strong.h" #include "../container/IntrusiveList.h" #include "../cpp/Tuple.h" #include "../thread/Mutex.h" #include "../thread/Util.h" #include <type_traits> #include <vector> #include <memory> namespace carb { //! Namespace for Carbonite delegate implementation. namespace delegate { template <class T> class Delegate; template <class T> class DelegateRef; /** * Implements a thread-safe callback system that can have multiple subscribers. * * A delegate is a weak-coupling callback system. Essentially, a system uses Delegate to have a callback that can * be received by multiple subscribers. * * Delegate has two ways to uniquely identify a bound callback: \ref Bind() will output a \ref Handle, or the * caller can provide a key of any type with BindWithKey(). Either the \ref Handle or the given key can be passed to * \ref Unbind() in order to remove a callback. * * Delegate can call all bound callbacks with the Call() function. Recursive calling is allowed with caveats listed * below. * * Delegate is thread-safe for all operations. Call() can occur simultaneously in multiple threads. An Unbind() * will wait if the bound callback is currently executing in another thread. * * Delegate can be destroyed from a binding (during \ref Call()) as the internal state is not disposed of * until all active calls have been completed. See ~Delegate(). * * Delegate does not hold any internal locks while calling bound callbacks. It is strongly recommended to avoid * holding locks when invoking Delegate's \ref Call() function. * * These tenets make up the basis of Carbonite's Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}. */ template <class... Args> class Delegate<void(Args...)> { public: //! A type representing the function type using FunctionType = void(Args...); /** * A quasi-unique identifier outputted from Bind() * * \ref Handle is unique as long as it has not rolled over. */ CARB_STRONGTYPE(Handle, size_t); CARB_DOC_CONSTEXPR static Handle kInvalidHandle{ 0 }; //!< A value representing an invalid \ref Handle value /** * Constructs an empty delegate */ Delegate() = default; /** * Move constructor. * * @param other The Delegate to move from. This Delegate will be left in a valid but empty state. */ Delegate(Delegate&& other); /** * Move-assign operator * * @param other The Delegate to move-assign from. Will be swapped with `*this`. * * @returns `*this` */ Delegate& operator=(Delegate&& other); /** * Destructor. * * The destructor unbinds all bindings and follows the waiting paradigm explained by \ref UnbindAll(). As the * internal state of the delegate is held until all active calls have completed, it is valid to destroy Delegate * from a callback. */ ~Delegate(); /** * Binds a callable (with optional additional arguments) to the delegate. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * \note This function can be done from within a callback. If done during a callback, the newly bound callable will * not be available to be called until \ref Call() returns, at which point the callback can be called by other * threads or outer \ref Call() calls (in the case of recursive calls to \ref Call()). * * @param hOut An optional pointer that receives a \ref Handle representing the binding to \c Callable. This can * be \c nullptr to ignore the \ref Handle. The same \ref Handle is also returned. In a multi-threaded environment, * it is possible for \p func to be called before \ref Bind() returns, but \p hOut will have already been assigned. * @param func A callable object, such as lambda, functor or [member-]function. Return values are ignored. The * callable must take as parameters \p args followed by the \c Args declared in the delegate template signature. * @param args Additional optional arguments to bind with \p func. If \p func is a member function pointer the * first argument must be the \c this pointer to call the member function with. * @return The \ref Handle also passed to \p hOut. */ template <class Callable, class... BindArgs> Handle Bind(Handle* hOut, Callable&& func, BindArgs&&... args); /** * Binds a callable (with optional additional arguments) to the delegate with a user-defined key. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * \note This function can be done from within a callback. If done during a callback, the newly bound callable will * not be available to be called until \ref Call() returns, at which point the callback can be called by other * threads or outer \ref Call() calls (in the case of recursive calls to \ref Call()). * * @param key A user-defined key of any type that supports equality (==) to identify this binding. Although multiple * bindings can be referenced by the same key, Unbind() will only remove a single binding. * @param func A callable object, such as lambda, functor or [member-]function. Return values are ignored. The * callable must take as parameters \p args followed by the \c Args declared in the delegate template signature. * @param args Additional optional arguments to bind with \p func. If \p func is a member function pointer the * first argument must be the \c this pointer to call the member function with. */ template <class KeyType, class Callable, class... BindArgs> void BindWithKey(KeyType&& key, Callable&& func, BindArgs&&... args); /** * Unbinds any single binding referenced by the given key. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * This function can be done from within a callback. If the referenced binding is currently executing in * another thread, Unbind() will not return until it has finished. Any binding can be safely unbound during a * callback. If a binding un-binds itself, the captured arguments and callable object will not be destroyed * until just before \ref Call() returns. * * \note It is guaranteed that when \ref Unbind() returns, the callback is not running and will never run in any * threads. * * @param key A \ref Handle or user-defined key previously passed to \ref BindWithKey(). * @return \c true if a binding was un-bound; \c false if no binding matching key was found. */ template <class KeyType> bool Unbind(KeyType&& key); /** * Indicates if a binding exists in `*this` with the given key or Handle. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * However, without external synchronization, it is possible for the result of this function to be incorrect by the * time it is used. * * @param key A \ref Handle or user-defined key previously passed to \ref BindWithKey(). * @returns \c true if a binding exists with the given \p key; \c false if no binding matching key was found. */ template <class KeyType> bool HasKey(KeyType&& key) const noexcept; /** * Unbinds the currently executing callback without needing an identifying key. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * \note If not done within the context of a callback, this function has no effect. * * @return \c true if a binding was un-bound; \c false if there is no current binding. */ bool UnbindCurrent(); /** * Unbinds all bound callbacks, possibly waiting for active calls to complete. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * Unbinds all currently bound callbacks. This function will wait to return until bindings that it unbinds have * completed all calls in other threads. It is safe to perform this operation from within a callback. */ void UnbindAll(); /** * Returns the number of active bound callbacks. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * \note This function returns the count of \a active bound callbacks only. Pending callbacks (that were added with * \ref Bind() during \ref Call()) are not counted. Use \ref HasPending() to determine if pending bindings exist. * * @returns the number of active bound callbacks. */ size_t Count() const noexcept; /** * Checks whether the Delegate has any pending bindings. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * The nature of this function is such that the result may be stale by the time it is read in the calling thread, * unless the calling thread has at least one pending binding. * * \note This function returns \c true if any \a pending bound callbacks exist. This will only ever be non-zero if * one or more threads are currently in the \ref Call() function. * * @returns \c true if any pending bindings exist; \c false otherwise. */ bool HasPending() const noexcept; /** * Checks whether the Delegate contains no pending or active bound callbacks. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * However, without external synchronization, it is possible for the result of this function to be incorrect by the * time it is used. * * @returns \c true if there are no active or pending callbacks present in `*this`; \c false otherwise. */ bool IsEmpty() const noexcept; /** * Given a type, returns a \c std::vector containing a copy of all keys used for bindings. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * \note This function can be done from within a callback. Pending callbacks (that were added with \ref Bind() * during \ref Call()) are included, even if they are pending in other threads. Note that in a multi-threaded * environment, the actual keys in use by Delegate may change after this function returns; in such cases, an * external mutex is recommended. \c KeyType must be Copyable in order for this function to compile. * * @tparam KeyType \ref Handle or a type previously passed to \ref BindWithKey() * @return a \c std::vector of copies of keys of the given type in use by this Delegate. */ template <class KeyType> std::vector<std::decay_t<KeyType>> GetKeysByType() const; /** * Calls all bound callbacks for this Delegate. * * \thread_safety: Thread-safe with respect to other Delegate operations except for construction and destruction. * * \note This function can be done concurrently in multiple threads simultaneously. Recursive calls to \ref Call() * are allowed but the caller must take care to avoid endless recursion. Callbacks are free to call \ref Bind(), * \ref Unbind() or any other Delegate function. No internal locks are held while callbacks are called. * * @param args The arguments to pass to the callbacks. */ void Call(Args... args); /** * Syntactic sugar for \ref Call() */ void operator()(Args... args); /** * Swaps with another Delegate. * * @param other The Delegate to swap with. */ void swap(Delegate& other); CARB_PREVENT_COPY(Delegate); private: template <class U> friend class DelegateRef; struct BaseBinding; template <class Key> struct KeyedBinding; using Container = carb::container::IntrusiveList<BaseBinding, &BaseBinding::link>; struct ActiveCall; using ActiveCallList = carb::container::IntrusiveList<ActiveCall, &ActiveCall::link>; struct Impl : public std::enable_shared_from_this<Impl> { mutable carb::thread::mutex m_mutex; Container m_entries; ActiveCallList m_activeCalls; ~Impl(); }; constexpr Delegate(std::nullptr_t); Delegate(std::shared_ptr<Impl> pImpl); ActiveCall* lastCurrentThreadCall(); const ActiveCall* lastCurrentThreadCall() const; void UnbindInternal(std::unique_lock<carb::thread::mutex>& g, typename Container::iterator iter); static size_t nextHandle(); std::shared_ptr<Impl> m_impl{ std::make_shared<Impl>() }; }; /** * Holds a reference to a Delegate. * * Though Delegate is non-copyable, \c DelegateRef can be thought of as a `std::shared_ptr` for Delegate. * This allows a Delegate's bindings to remain active even though the original Delegate has been destroyed, which can * allow calls in progress to complete, or a mutex protecting the original Delegate to be unlocked. */ template <class... Args> class DelegateRef<void(Args...)> { public: //! The Delegate type that is referenced. using DelegateType = Delegate<void(Args...)>; /** * Default constructor. * * Creates an empty DelegateRef such that `bool(*this)` would be `false`. */ constexpr DelegateRef() noexcept; /** * Constructor. * * Constructs a DelegateRef that holds a strong reference to \p delegate. * @param delegate The Delegate object to hold a reference to. */ explicit DelegateRef(DelegateType& delegate); /** * Copy constructor. * * References the same underlying Delegate that \p other references. If \p other is empty, `*this` will also be * empty. * @param other A DelegateRef to copy. */ DelegateRef(const DelegateRef& other); /** * Move constructor. * * Moves the reference from \p other to `*this`. If \p other is empty, `*this` will also be empty. \p other is left * in a valid but empty state. * @param other A DelegateRef to move. */ DelegateRef(DelegateRef&& other) = default; /** * Destructor */ ~DelegateRef(); /** * Copy-assign. * * References the same underlying Delegate that \p other references and releases any existing reference. The order * of these operations is unspecified, so assignment from `*this` is undefined behavior. * @param other A DelegateRef to copy. * @returns `*this`. */ DelegateRef& operator=(const DelegateRef& other); /** * Move-assign. * * Moves the reference from \p other to `*this` and releases any existing reference. The order of these operations * is unspecified, so assignment from `*this` is undefined behavior. If \p other is empty, `*this` will also be * empty. \p other is left in a valid but empty state. * @param other A DelegateRef to move. * @returns `*this`. */ DelegateRef& operator=(DelegateRef&& other) = default; /** * Checks whether the DelegateRef holds a valid reference. * @returns `true` if `*this` holds a valid reference; `false` otherwise. */ explicit operator bool() const noexcept; /** * Clears the DelegateRef to an empty reference. * * Postcondition: `bool(*this)` will be `false`. */ void reset(); /** * References a different Delegate and releases any existing reference. * @param delegate The Delegate to reference. */ void reset(DelegateType& delegate); /** * Swaps the reference with another DelegateRef. * @param other A DelegateRef to swap with. */ void swap(DelegateRef& other); /** * Retrieves the underlying DelegateType. * @returns a pointer to the referenced Delegate, or `nullptr` if `bool(*this)` would return false. */ DelegateType* get() const noexcept; /** * Dereferences *this. * @returns a reference to the referenced Delegate. If `bool(*this)` would return false, behavior is undefined. */ DelegateType& operator*() const noexcept; /** * Dereferences *this. * @returns a pointer to the referenced Delegate. If `bool(*this)` would return false, behavior is undefined. */ DelegateType* operator->() const noexcept; private: DelegateType m_delegate; }; //! A helper class for determining the type of a \ref carb::delegate::DelegateRef based on a //! \ref carb::delegate::Delegate. @tparam Del a \ref carb::delegate::Delegate template <class Del> struct RefFromDelegate { //! The type of \ref DelegateRef that should be used for a \ref Delegate of type `Del` using type = DelegateRef<typename Del::FunctionType>; }; //! Definition helper for `RefFromDelegate<Del>::type` template <class Del> using RefFromDelegate_t = typename RefFromDelegate<Del>::type; } // namespace delegate } // namespace carb #include "DelegateImpl.inl" CARB_INCLUDE_PURIFY_TEST({ using namespace carb::delegate; Delegate<void()> d, d2{ Delegate<void()>{} }, d3 = Delegate<void()>(); auto b = d.Bind(nullptr, [] {}); d.Bind(nullptr, [](bool) {}, true); d.BindWithKey(0, [] {}); d.BindWithKey(1, [](bool) {}, false); d.Unbind(1); d.Unbind(b); d.HasKey(0); d.UnbindCurrent(); d2.UnbindAll(); d.Count(); d.HasPending(); d.IsEmpty(); d.GetKeysByType<int>(); d.Call(); d(); d.swap(d3); DelegateRef<void()> dr(d), dr2{}; DelegateRef<void()> dr3(dr); DelegateRef<void()> dr4(std::move(dr2)); DelegateRef<void()> dr5 = std::move(dr4); DelegateRef<void()> dr6 = dr5; CARB_UNUSED(bool(dr6)); dr6.reset(); dr5.reset(d); dr5.get(); (*dr).Call(); dr->Call(); });
18,622
C
37.240246
120
0.679519
omniverse-code/kit/include/carb/launcher/ILauncher.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 Simple external process launcher helper interface. */ #pragma once #include "../Interface.h" #if CARB_PLATFORM_LINUX # include <sys/prctl.h> # include <sys/signal.h> #endif namespace carb { /** Namespace for the Carbonite process launch helper interface. */ namespace launcher { // ****************************** structs, enums, and constants *********************************** /** Opaque object used to represent a process that has been launched using the ILauncher * interface. A value of `nullptr` indicates an invalid process object. */ struct Process; /** Base type for a process exit code. Process exit codes differ between Windows and Linux - on * Windows a process exit code is a DWORD, while on Linux it is an int. This type should be able * to successfully hold any value from either platform. */ using ExitCode = int64_t; /** Base type for the identifier of a process. This does not conform directly to the local * definitions of a process ID for either Windows or Linux, but it should at least be large * enough to properly contain either. */ using ProcessId = uint64_t; /** Format code to use for the @ref carb::launcher::ProcessId data type in printf() style format * strings. */ #define OMNI_ILauncher_PRIpid PRIu64 /** Special value to indicate a bad process identifier. This can be returned from * ILauncher::getProcessId() if the given child process is no longer running. */ constexpr ProcessId kBadId = ~0ull; /** Prototype for a stream read callback function. * * @param[in] data The buffer of data that was read from the child process's stream. This * will never be `nullptr`. Only the first @p bytes bytes of data in this * buffer will contain valid data. Any data beyond that should be considered * undefined and not accessed. * @param[in] bytes The number of bytes of valid data in the @p data buffer. This will never * be 0 as long as the connection to the child process is active. When the * child process exits and the read thread has read all of the data from the * child process, one final callback will be performed passing 0 for the byte * count to indicate the end of the stream. This count will not exceed the * buffer size specified in the original call to ILauncher::openProcess(). * @param[in] context The context value that was originally passed to ILauncher::openProcess() * when the child process was created. * @returns No return value. * * @remarks This callback will be performed any time data is successfully read from one of the * child process's output streams (ie: `stdout` or `stderr`). The call will be performed * on a worker thread that was created specifically for the child process. This * callback will be performed as soon after reading the data as possible. The reader * thread will remain in an efficient wait state while there is no data read to be * read. It is the callback's responsibility to ensure any shared resources that are * accessed in the callback are appropriately protected from race conditions and * general thread safety issues. * * @remarks When reading from one of the child process' output streams, every effort will be * taken to ensure the contents of at least one 'message' is delivered to the callback * at a time. A message can be thought of as the unit of data that was last written * to the stream on the child process's side - for example, the output of a single call * to fwrite() or fprintf(). However, there are a some caveats to this behavior that * the callback and its owner need to be able to handle: * * It is possible that depending on the size and arrival times of messages, multiple * messages may be concatenated into a single callback call. The callback needs to * be able to handle this by being able to identify expected message ends and * properly parse them out if needed. * * If the current message or set of messages fills up the read buffer, the buffer * as it is will be delivered to the callback with the last message truncated. The * remainder of the message will be sent in the next callback. The callback needs * to be able to handle this by either using a buffer size appropriate for the * expected output of the child process, or by having the callback simply concatenate * incoming data onto a data queue that is then processed elsewhere. * * @remarks This callback should attempt to complete its task as quickly as possible to avoid * blocking the read thread. If the callback blocks or takes a long time to process * it may result in blocking the child process's attempts to write to the stream. The * child process' thread will be effectively stopped until buffer space is freed up * on the parent's read side. It is best practice to have the callback simply queue * up new data for later consumption on another thread in the parent process or to do * a few simple string or data checks if searching for a specific incoming data message. * * @remarks When the stream for this callback ends due to either the child or parent process * closing it, one final callback will be performed. The last callback will always * have a @p bytes value of 0 in this case. All other callbacks during the stream * will have a non-zero @p bytes value. Even in this final callback case however, * a non-`nullptr` @p data buffer will still be provided. Once the zero sized buffer * has been delivered, the parent process can safely assume that the child process * is done transmitting any data to the parent. */ using OnProcessReadFn = void (*)(const void* data, size_t bytes, void* context); /** A default buffer size to use for reading from a child process's `stdout` or `stderr` streams. */ constexpr size_t kDefaultProcessBufferSize = 1ull << 17; /** Launcher flags * @{ */ /** Base type for flags to the @ref carb::launcher::ILauncher::launchProcess function. Valid flags for this * type are the carb::launcher::fLaunchFlag* flags. */ using LauncherFlags = uint32_t; /** Flag to indicate that the stdin stream for the child process should be opened and accessible * on the side of the parent process. If this flag is not present, any attempts to call * ILauncher::writeProcessStdin() will fail immediately. If this flag is present, the parent * process may write information to the child process through its stdin stream. The child * process will be able to poll its stdin stream for input and read it. If this is used, the * child process will only be able to read input from the parent process. If not used, the * child process should assume that stdin cannot be read (though the actual behavior may * differ by platform following native stdin inheritance rules). */ constexpr LauncherFlags fLaunchFlagOpenStdin = 0x00000001; /** Flag to indicate that the new child process should be killed when the calling parent process * exits. If this flag is not present, the child process will only exit when it naturally exits * on its own or is explicitly killed by another process. If this flag is present, if the parent * process exits in any way (ie: ends naturally, crashes, is killed, etc), the child process * will also be killed. Note that the child process will be killed without warning or any * chance to clean up. Any state in the child process that was not already saved to persistent * storage will be lost. Also, if the child process is in the middle of modifying persistent * storage when it is killed, that resource may be left in an undefined state. * * @note This flag is not supported on Mac. It will be ignored if used on Mac and the child * process(es) must be manually terminated by the parent process if necessary. */ constexpr LauncherFlags fLaunchFlagKillOnParentExit = 0x00000002; /** When the @ref fLaunchFlagKillOnParentExit flag is also used, this indicates that the child * process should be forcibly terminated instead of just being asked to exit when the parent * process dies. This flag is only used on Linux where there is the possibility of a child * process catching and handling a SIGTERM signal. If the child process generally installs * a SIGTERM handler and doesn't exit as a result, this flag should be used to allow a SIGKILL * to be sent instead (which can neither be caught nor ignored). Generally, sending a SIGTERM * is considered the 'correct' or 'appropriate' way to kill a process on Linux. This flag is * ignored on Windows. */ constexpr LauncherFlags fLaunchFlagForce = 0x00000004; /** Flag to indicate that reading from the `stdout` or `stderr` streams of the child process should * be handled as a byte stream. Data will be delivered to the stream callback as soon as it is * available. The delivered bytes may only be a small portion of a complete message sent from * the child process. At least one byte will be sent when in this mode. This is the default * mode for all child processes. This flag may not be combined with @ref fLaunchFlagMessageMode. * When using this read mode, it is the callback's responsibility to process the incoming data * and wait for any delimiters to arrive as is necessary for the task. The message mode may not * be changed after the child process has been launched. * * @note [Windows] This mode is the only mode that is currently supported on Windows. This may * be fixed in a future version of the interface. */ constexpr LauncherFlags fLaunchFlagByteMode = 0x00000000; /** Flag to indicate that reading from the `stdout` or `stderr` streams of the child process should * be handled as a message stream. Data will not be delivered to the stream callback until a * complete message has been received. A message is considered to be the contents of a single * write call on the child's process side (up to a reasonable limit). The data passed to the * callbacks may be split into multiple messages if a very large message is sent in a single * write call. On Linux at least, this message limit is 4KB. The message mode may not be * changed after the child process has been launched. * * @note [Windows] This mode is not currently supported on Windows. This may be fixed in a * future version of the interface. */ constexpr LauncherFlags fLaunchFlagMessageMode = 0x00000008; /** Flag to indicate that the calling process's environment should not be inherited by the child * process in addition to the new environment variables specified in the launch descriptor. When * no environment block is given in the descriptor, the default behavior is for the child * process to inherit the parent's (ie: this calling process) environment block. Similarly for * when a non-empty environment block is specified in the launch descriptor - the environment * block of the calling process will be prepended to the environment variables given in the * launch descriptor. However, when this flag is used, that will indicate that the new child * process should only get the environment block that is explicitly given in the launch * descriptor. */ constexpr LauncherFlags fLaunchFlagNoInheritEnv = 0x00000010; /** Flag to indicate that the child process should still continue to be launched even if the * environment block for it could not be created for any reason. This flag is ignored if * @ref LaunchDesc::env is `nullptr` or the block environment block object is successfully * created. The most common cause for failing to create the environment block is an out of * memory situation or invalid UTF-8 codepoints being used in the given environment block. * This flag is useful when the additional environment variables for the child process are * optional to its functionality. */ constexpr LauncherFlags fLaunchFlagAllowBadEnv = 0x00000020; /** Flag to indicate that the requested command should be launched as a script. An attempt * will be made to determine an appropriate command interpreter for it based on its file * extension if no interpreter command is explicitly provided in @ref LaunchDesc::interpreter. * When this flag is not present, the named command will be assumed to be a binary executable. * * @note [Linux] This flag is not necessary when launching a script that contains a shebang * on its first line. The shebang indicates the command interpreter to be used when * executing the script. In this case, the script will also need to have its executable * permission bit set for the current user. If the shebang is missing however, this * flag will be needed. */ constexpr LauncherFlags fLaunchFlagScript = 0x00000040; /** Flags to indicate that the child process' standard output streams should be closed upon * launch. This is useful if the output from the child is not interesting or would otherwise * garble up the parent process' standard streams log. An alternative to this would be to * create a dummy read function for both `stdout` and `stderr` where the parent process just drops * all incoming messages from the child process. This however also has its drawbacks since it * would create one to two threads to listen for messages that would just otherwise be * ignored. If these flags are not used, the OS's default behavior of inheriting the parent * process' standard streams will be used. Each standard output stream can be disabled * individually or together if needed depending on which flag(s) are used. * * @note Any callbacks specified for @ref LaunchDesc::onReadStdout or * @ref LaunchDesc::onReadStderr will be ignored if the corresponding flag(s) to disable * those streams is also used. */ constexpr LauncherFlags fLaunchFlagNoStdOut = 0x00000080; /** @copydoc fLaunchFlagNoStdOut */ constexpr LauncherFlags fLaunchFlagNoStdErr = 0x00000100; /** @copydoc fLaunchFlagNoStdOut */ constexpr LauncherFlags fLaunchFlagNoStdStreams = fLaunchFlagNoStdOut | fLaunchFlagNoStdErr; /** Flag to indicate that launching the child process should not fail if either of the log * files fails to open for write. This flag is ignored if the @ref LaunchDesc::stdoutLog * and @ref LaunchDesc::stderrLog log filenames are `nullptr` or empty strings. If either * log file fails to open, the child process will still be launched but the default behavior * of inheriting the parent's standard output streams will be used instead. If this flag * is not used, the default behavior is to fail the operation and not launch the child * process. */ constexpr LauncherFlags fLaunchFlagAllowBadLog = 0x00000200; /** Flag to indicate that the child process should be launched fully detached from the launching * (ie: parent) process. This flag only has an effect on Linux and Mac OS. On Windows this * flag is simply ignored. This intentionally orphans the child process so that the terminal * session or @a initd becomes the one responsible for waiting on the orphaned child process * instead of the launching parent process. This allows the child process to be a fully fire- * and-forget process on all platforms. Note that using this flag may make communication * with the child process difficult or impossible. This flag should generally not be used * in combination with child processes that need to read stdout and stderr output. */ constexpr LauncherFlags fLaunchFlagLaunchDetached = 0x00000400; /** @} */ /** Stream waiting flags * @{ */ /** Base type for flags to the @ref carb::launcher::ILauncher::waitForStreamEnd() function. * Valid flags for this type are the carb::launcher::fWaitFlag* flags. */ using WaitFlags = uint32_t; /** Flag to indicate that the `stdout` stream should be waited on. The stream will be signaled * when it is closed by either the child process and all of the data on the stream has been * consumed, or by using the @ref fWaitFlagCloseStdOutStream flag. */ constexpr WaitFlags fWaitFlagStdOutStream = 0x00000001; /** Flag to indicate that the `stderr` stream should be waited on. The stream will be signaled * when it is closed by either the child process and all of the data on the stream has been * consumed, or by using the @ref fWaitFlagCloseStdErrStream flag. */ constexpr WaitFlags fWaitFlagStdErrStream = 0x00000002; /** Flag to indicate that the `stdout` stream for a child should be closed before waiting on it. * Note that doing so will truncate any remaining incoming data on the stream. This is useful * for closing the stream and exiting the reader thread when the parent process is no longer * interested in the output of the child process (ie: the parent only wanted to wait on a * successful startup signal from the child). This flag has no effect if no read callback was * provided for the `stdout` stream when the child process was launched. * * @note [Linux] If this is used on a child process to close the parent process's end of the * `stdout` stream, the child process will be terminated with SIGPIPE if it ever tries * to write to `stdout` again. This is the default handling of writing to a broken * pipe or socket on Linux. The only way around this default behavior is to ensure * that the child process ignores SIGPIPE signals. Alternatively, the parent could * just wait for the child process to exit before destroying its process handle or * closing the stream. */ constexpr WaitFlags fWaitFlagCloseStdOutStream = 0x00000004; /** Flag to indicate that the `stderr` stream for a child should be closed before waiting on it. * Note that doing so will truncate any remaining incoming data on the stream. This is useful * for closing the stream and exiting the reader thread when the parent process is no longer * interested in the output of the child process (ie: the parent only wanted to wait on a * successful startup signal from the child). This flag has no effect if no read callback was * provided for the `stderr` stream when the child process was launched. * * @note [Linux] If this is used on a child process to close the parent process's end of the * `stderr` stream, the child process will be terminated with SIGPIPE if it ever tries * to write to `stderr` again. This is the default handling of writing to a broken * pipe or socket on Linux. The only way around this default behavior is to ensure * that the child process ignores SIGPIPE signals. Alternatively, the parent could * just wait for the child process to exit before destroying its process handle or * closing the stream. */ constexpr WaitFlags fWaitFlagCloseStdErrStream = 0x00000008; /** Flag to indicate that the wait should succeed when any of the flagged streams have been * successfully waited on. The default behavior is to wait for all flagged streams to be * completed before returning or timing out. */ constexpr WaitFlags fWaitFlagAnyStream = 0x00000010; /** @} */ /** Process kill flags. * @{ */ /** Base type for flags to the @ref carb::launcher::ILauncher::killProcess() function. Valid flags for this * type are the carb::launcher::fKillFlag* flags. */ using KillFlags = uint32_t; /** Flag to indicate that any direct child processes of the process being terminated should * also be terminated. Note that this will not cause the full hierarchy of the process's * ancestors to be terminated as well. The caller should manage its process tree directly * if multiple generations are to be terminated as well. */ constexpr KillFlags fKillFlagKillChildProcesses = 0x00000001; /** Flag to indicate that a child process should be force killed. This only has an effect * on Linux where a SIGKILL signal will be sent to the process instead of SIGTERM. This * flag is ignored on Windows. The potential issue with SIGTERM is that a process can * trap and handle that signal in a manner other than terminating the process. The SIGKILL * signal however cannot be trapped and will always terminate the process. */ constexpr KillFlags fKillFlagForce = 0x00000002; /** Flag to indicate that ILauncher::killProcess() or ILauncher::killProcessWithTimeout() calls * should simply fail if a debugger is currently attached to the child process being terminated. * The default behavior is to still attempt to kill the child process and wait for it to exit. * On Linux, this will work as intended. On Windows however, a process being debugged cannot * be terminated without first detaching the debugger. The attempt to terminate the child * process will be queued for after the debugger has been attached. */ constexpr KillFlags fKillFlagFailOnDebugger = 0x00000004; /** Flag to indicate that the ILauncher::killProcess() or ILauncher::killProcessWithTimeout() * calls should not wait for the child process to fully exit before returning. This allows * calls to return more quickly, but could result in other functions such as * ILauncher::isProcessActive() and ILauncher::getProcessExitCode() returning false results * for a short period after ILauncher::killProcess() returns. This period is usually only a * few milliseconds, but may be inconsistent due to other system behavior and load. */ constexpr KillFlags fKillFlagSkipWait = 0x00000008; /** @} */ /** Special value that can be passed to ILauncher::writeProcessStdin() for the @a bytes parameter * to indicate that the input is a null terminated UTF-8 string. When this special length value * is used, it is the caller's responsibility to ensure the input string is actually null * terminated. */ constexpr size_t kNullTerminated = ~0ull; /** Special exit code to indicate that the process is still running and has not exited yet. * This can be returned from ILauncher::waitProcessExit() and ILauncher::getProcessExitCode(). */ constexpr ExitCode kStillActive = 0x8000000000000000ll; /** Indicates an infinite timeout for use in the ILauncher::waitProcessExit() function in its * @a timeout parameter. The call will block until the requested process ends. */ constexpr uint64_t kInfiniteTimeout = ~0ull; /** Return statuses for ILauncher::killProcessWithTimeout(). These indicate how the termination * attempt completed. */ enum class KillStatus { /** The child process was successfully terminated. It will also have been confirmed to * have exited fully if the @ref fKillFlagSkipWait flag was not used. If the * @ref fKillFlagSkipWait flag is used in the call, this status only indicates that the * signal to terminate the child process was successfully sent. The child process will * exit at some point in the near future. If a very short timeout was used in a call to * ILauncher::killProcessWithTimeout(), and the child process had exited within that * period, this will be returned, otherwise @ref KillStatus::eWaitFailed will be returned. * In most situations, the time period between termination and when the child process fully * exits will only be a few milliseconds. However, within that time period, calls to * functions such as ILauncher::isProcessActive() or ILauncher::getProcessExitCode() may * return false results. */ eSuccess, /** A debugger was attached to the child process at the time the termination attempt was * made. This will only be returned if the @ref fKillFlagFailOnDebugger flag is used * and a debugger is attached to the child process. No attempt to terminate the process * will be made in this case. A future call to ILauncher::killProcess() or * ILauncher::killProcessWithTimeout() (once the debugger has been detached) will be * needed to actually terminate the child process. */ eDebuggerAttached, /** A debugger was attached to the child process and that prevented it from being terminated. * This will only be returned on Windows. A similar situation can still occur on Linux, * except that on Linux the child process will be terminated successfully. In that case, * the debugger process will just be left in an invalid state where the only course of action * is to detach from the terminated process. Note that when this value is returned, the * child process will be marked for termination by the system, but it will not actually be * terminated until the debugger is detached from it. */ eDebuggerFail, /** The attempt to signal the child process to terminate failed. This can occur if the * child process' handle is invalid or there is a permission problem. This will not * happen in most common situations. */ eTerminateFailed, /** Waiting for the child process to exit failed or timed out. When this is returned, the * child process has still been successfully signaled to exit, but it didn't fully exit * before the timeout expired. This may still be viewed as a successful result however. * This status code can be suppressed in successful cases with the @ref fKillFlagSkipWait * flag. That flag is especially useful when a zero timeout is desired but a successful * result should still be returned. If this value is returned, the caller is responsible * for ensuring the child process successfully exits. This state can be verified with * calls such as ILauncher::isProcessActive(), ILauncher::getProcessExitCode(), and * ILauncher::waitProcessExit(). */ eWaitFailed, /** An invalid parameter was passed into ILauncher::killProcessWithTimeout(). */ eInvalidParameter, }; /** Standard command interpreters for Windows and Linux. These can be used in the launch * descriptor's @ref LaunchDesc::interpreter value to override some default interpreter * detection functionality. * * @note These interpreter names are just 'safe' interpreters. If a caller has additional * knowledge of the functional requirements of a script (ie: requires python 3.6+, * requires a specific install of python, requires additional options for the interpreter, * etc), it is the caller's responsibility to ensure an appropriate interpreter path and * command is provided in @ref LaunchDesc::interpreter. If no interpreter path is given * in the launch descriptor, one of these interpreters will be chosen based on the * extension of the script file. * * @note If you need to use `cmd /C`, you must use @ref kInterpreterShellScript so that ILauncher * can properly quote your arguments, since `cmd /C` does not interpret a command argument * in the way that almost every other interpreter does. */ #if CARB_PLATFORM_WINDOWS constexpr const char* const kInterpreterShellScript = "cmd /C"; constexpr const char* const kInterpreterShellScript2 = "cmd /C"; #else constexpr const char* const kInterpreterShellScript = "sh"; /** @copydoc kInterpreterShellScript */ constexpr const char* const kInterpreterShellScript2 = "bash"; #endif /** Interpreter names for python scripts. Using this command assumes that at least one version * of python is installed locally on the system and is available through the system PATH * variable. It is the caller's responsibility to ensure that a global python instance is * installed on the calling system before either using this interpreter string in a launch * descriptor or attempting to run a python script with a `nullptr` interpreter. * * To check if the global python interpreter is installed on the calling system, a call to * ILauncher::launchProcess() with a @ref kInterpreterPythonCommand as the interpreter and * the simple script "quit" can be used. If ILauncher::launchProcess() succeeds, the global * python interpreter is installed. If it fails, it is not installed. In the latter case, * it is the caller's responsibility to either find or install an appropriate python interpreter * before attempting to launch a python script. */ constexpr const char* const kInterpreterPythonScript = "python"; /** @copydoc kInterpreterPythonScript */ constexpr const char* const kInterpreterPythonCommand = "python -c"; /** Descriptor of the new process to be launched by ILauncher::openProcess(). This contains * all the information needed to launch and communicate with the new child process. */ struct LaunchDesc { /** A vector of command line arguments for the new process to launch. This may not be * `nullptr`. The first argument in the vector must be the path to the executable to run. * This may be a relative or absolute path. All following arguments will be passed to the * executable as command line arguments. Each string must be UTF-8 encoded. Note that if * a relative path is used for the first argument, it must be given relative to the current * working directory for the parent (ie: calling) process, not the path given by @ref path. * The @ref path value will become the current working directory for the child process, not * the path to find the executable image at. */ const char* const* argv = nullptr; /** The total number of arguments in the @ref argv vector. */ size_t argc = 0; /** The optional initial working directory of the new process. If not specified, this will * default to the calling process's current working directory. Once the child process has * been successfully started, its current working directory will be set to this path. This * will neither affect the current working directory of the parent process nor will it be * used as the path to find the child process' executable. */ const char* path = nullptr; /** Callback to be performed whenever data is successfully read from the child process's * `stdout` or `stderr` streams. These may be `nullptr` if nothing needs to be read from the * child process's `stdout` or `stderr` streams. Note that providing a callback here will * spawn a new thread per callback to service read requests on the child process's `stdout` * or `stderr` streams. See @ref OnProcessReadFn for more information on how these callbacks * should be implemented and what their responsibilities are. * * @note [Linux] If this is non-`nullptr` and the parent process destroys its process handle * for the child process before the child process exits, the child process will be * terminated with SIGPIPE if it ever tries to write to the corresponding stream again * This is the default Linux kernel behavior for writing to a broken pipe or socket. * It is best practice to first wait for the child process to exit before destroying * the process handle in the parent process. */ OnProcessReadFn onReadStdout = nullptr; /** @copydoc onReadStdout */ OnProcessReadFn onReadStderr = nullptr; /** The opaque context value to be passed to the read callbacks when they are performed. This * will never be accessed directly by the process object, just passed along to the callbacks. * It is the responsibility of the callbacks to know how to appropriately interpret these * values. These values are ignored if both @ref onReadStdout and @ref onReadStderr are * `nullptr`. */ void* readStdoutContext = nullptr; /** @copydoc readStdoutContext */ void* readStderrContext = nullptr; /** Flags to control the behavior of the new child process. This is zero or more of the * @ref LauncherFlags flags. */ LauncherFlags flags = 0; /** A hint for the size of the buffer to use when reading from the child process's `stdout` * and `stderr` streams. This represents the maximum amount of data that can be read at * once and returned through the onRead*() callbacks. This is ignored if both * @ref onReadStdout and @ref onReadStderr are `nullptr`. * * Note that this buffer size is only a hint and may be adjusted internally to meet a * reasonable minimum read size for the platform. */ size_t bufferSize = kDefaultProcessBufferSize; /** A block of environment variables to pass to the child process. If the @ref flags * include the @ref fLaunchFlagNoInheritEnv flag, this environment block will be used * explicitly if non-`nullptr`. If that flag is not used, the calling process's current * environment will be prepended to the block specified here. Any environment variables * specified in here will replace any variables in the calling process's environment * block. Each string in this block must be UTF-8 encoded. If this is `nullptr`, the * default behavior is for the child process to inherit the entire environment of the * parent process. If an empty non-`nullptr` environment block is specified here, the * child process will be launched without any environment. */ const char* const* env = nullptr; /** The number of environment variables specified in the environment block @ref env. This * may only be 0 if the environment block is empty or `nullptr`. */ size_t envCount = 0; /** An optional command interpreter name to use when launching the new process. This can be * used when launching a script file (ie: shell script, python script, etc). This must be * `nullptr` if the command being launched is a binary executable. If this is `nullptr` * and a script file is being executed, an attempt will be made to determine the appropriate * command interpreter based on the file extension of the first argument in @ref argv. * The ILauncher::launchProcess() call may fail if this is `nullptr`, an appropriate * interpreter could not be found for the named script, and the named script could not * be launched directly on the calling platform (ie: a script using a shebang on its * first line will internally specify its own command interpreter). This value is ignored * if the @ref fLaunchFlagScript flag is not present in @ref flags. * * This can be one of the kInterpreter* names to use a standard command interpreter that * is [presumably] installed on the system. If a specific command interpreter is to be * used instead, it is the caller's responsibility to set this appropriately. * * @note This interpreter process will be launched with a search on the system's 'PATH' * variable. On Windows this is always the behavior for launching any process. * However, on Linux a process must always be identified by its path (relative or * absolute) except in the case of launching a command interpreter. */ const char* interpreter = nullptr; /** Optional names of log files to redirect `stdout` and `stderr` output from the child process * to in lieu of a callback. The output from these streams won't be visible to the parent * process (unless it is also reading from the log file). If either of these are * non-`nullptr` and not an empty string, and the callbacks (@ref onReadStdout or * @ref onReadStderr) are also `nullptr`, the corresponding stream from the child process * will be redirected to these files(s) on disk. It is the caller's responsibility to ensure * the requested filename is valid and writable. If the log fails to open, launching the * child process will be silently ignored or fail depending on whether the * @ref fLaunchFlagAllowBadLog flag is used or not. These logs will be ignored if any * of the @ref fLaunchFlagNoStdStreams flags are used. The log file corresponding to the * flag(s) used will be disabled. * * When a log is requested, it will be opened in a sharing mode. The log will be opened * with shared read and write permissions. If the named log file already exists, it will * always be truncated when opened. It is the caller's responsibility to ensure the previous * file is moved or renamed if its contents need to be preserved. The log will also be * opened in 'append' mode (ie: as if "a+" had been passed to fopen()) so that all new * messages are written at the end of the file. It is the child process's responsibility * to ensure that all messages written to the log files are synchronized so that messages * do not get incorrectly interleaved. If both log files are given the same name, it is * also the child process's responsibility to ensure writes to `stdout` and `stderr` are * appropriately serialized. * * Setting log file names here will behave roughly like shell redirection to a file. The * two streams can be independently specified (as in "> out.txt & err.txt"), or they can * both be redirected to the same file (as in "&> log.txt" or > log.txt & log.txt"). The * files will behave as expected in the child process - writing to `stdout` will be buffered * while writing to `stderr` will be unbuffered. If the named log file already exists, it * will always be overwritten and truncated. * * This filename can be either an absolute or relative path. Relative paths will be opened * relative to the current working directory at the time. The caller is responsible for * ensuring all path components leading up to the log filename exist before calling. Note * that the log file(s) will be created before the child process is launched. If the child * process fails to launch, it will be the caller's responsibility to clean up the log file * if necessary. * * @note if a non-`nullptr` callback is given for either `stdout` or `stderr`, that will * override the log file named here. Each log file will only be created if its * corresponding callback is not specified. */ const char* stdoutLog = nullptr; /** @copydoc stdoutLog */ const char* stderrLog = nullptr; /** Reserved for future expansion. This must be `nullptr`. */ void* ext = nullptr; }; // ********************************** interface declaration *************************************** /** A simple process launcher helper interface. This is responsible for creating child processes, * tracking their lifetime, and communicating with the child processes. All operations on this * interface are thread safe within themselves. It is the caller's responsibility to manage the * lifetime of and any multi-threaded access to each process handle object that is returned from * launchProcess(). For example, destroying a process handle object while another thread is * operating on it will result in undefined behavior. * * Linux notes: * * If any other component of the software using this plugin sets the SIGCHLD handler back to * default behavior (ie: SIG_DFL) or installs a SIGCHLD handler function, any child process * that exits while the parent is still running will become a zombie process. The only way * to remove a zombie process in this case is to wait on it in the parent process with * waitProcessExit() or getProcessExitCode() at some point after the child process has * exited. Explicitly killing the child process with killProcess() will also avoid creating * a zombie process. * * Setting the SIGCHLD handler to be ignored (ie: SIG_IGN) will completely break the ability * to wait on the exit of any child process for this entire process. Any call to wait on a * child process such as waitProcessExit() or getProcessExitCode() will fail immediately. * There is no way to detect or work around this situation on the side of this interface * since signal handlers are process-wide and can be installed at any time by any component * of the process. * * The problem with leaving a zombie processes hanging around is that it continues to take * up a slot in the kernel's process table. If this process table fills up, the kernel * will not be able to launch any new processes (or threads). All of the zombie children * of a process will be automatically cleaned up when the parent exits however. * * If a read callback is provided for either `stdout` or `stderr` of the child process and * the parent process destroys its process handle for the child process before the child * process exits, the child process will be terminated with SIGPIPE if it ever tries to * write to either stream again. This is the default Linux kernel behavior for writing * to a broken pipe or socket. The only portable way around this is to ensure the child * process will ignore SIGPIPE signals. It is generally best practice to ensure the parent * process waits on all child processes before destroying its process handle. This also * prevents the appearance of zombie processes as mentioned above. * * Windows notes: * * Reading from a child process's `stdout` or `stderr` streams will not necessarily be * aligned to the end of a single 'message' (ie: the contents of a single write call on the * child process's end of the stream). This means that a partial message may be received in * the callbacks registered during the launch of a child process. It is left up to the * caller to accumulate input from these streams until an appropriate delimiter has been * reached and the received data can be fully parsed. This may be fixed in a future version * of this interface. */ struct ILauncher { CARB_PLUGIN_INTERFACE("carb::launcher::ILauncher", 1, 3) /** Launches a new child process. * * @param[in] desc A descriptor of the child process to launch. At least the * @ref LaunchDesc::argc and @ref LaunchDesc::argv members must be * filled in. Default values on all other members are sufficient. * @returns A new process object if the child process is successfully launched. This must * be destroyed with destroyProcessHandle() when it is no longer needed by the * caller. Note that closing the process object will not terminate the child * process. It simply means that the calling process can no longer communicate * with or kill the child process. If the child process needs to be killed first, * it is the caller's responsibility to call kill() before destroying the handle. * @returns `nullptr` if the new process could not be launched for any reason. This may * include insufficient permissions, failed memory or resource allocations, etc. * * @remarks This attempts to launch a new child process. The new process will be created * and start to run before successful return here. Depending on what flags and * callbacks are provided in the launch descriptor, it may be possible for this * process to communicate with the new child process. * * @note On Linux, the child process's executable should not have the set-user-ID or set- * group-ID capabilities set on it when using the @ref carb::launcher::fLaunchFlagKillOnParentExit * flag. These executables will clear the setting that allows the child process * to receive a signal when the parent process exits for any reason (ie: exits * gracefully, crashes, is externally terminated, etc). Setting these capabilities * on an executable file requires running something along the lines of: * * @code{.sh} * sudo setcap cap_setuid+ep <filename> * sudo setcap cap_setgid+ep <filename> * @endcode * * @note Any built executable will, be default, not have any of these capabilities set. * They will have to be explicitly set by a user, installer, or script. These * executables can be identified in an "ls -laF" output by either being highlighted * in red (default bash color scheme), or by having the '-rwsr-xr-x' permissions * (or similar) instead of '-rwxr-xr-x', or by passing the executable path to * 'capsh --print' to see what it's effective or permissive capabilities are. * * @note If a set-user-ID or set-group-ID executable needs to be launched as a child process * and the @ref fLaunchFlagKillOnParentExit flag is desired for it, the child process * should call @code{.cpp}prctl(PR_SET_PDEATHSIG, SIGTERM)@endcode early in its main() * function to regain this behavior. The restoreParentDeathSignal() helper function * is also offered here to make that call easier in Carbonite apps. Note however that * there will be a possible race condition in this case - if the parent exits before * the child process calls prctl(), the child process will not be signaled. Also note * that unconditionally calling one of these functions in a child process will result * in the @ref fLaunchFlagKillOnParentExit behavior being imposed on that child * process regardless of whether the flag was used by the parent process. * * @note Since we can neither guarantee the child process will be a Carbonite app nor that * it will even be source under control of the same developer (ie: a command line * tool), resetting this death signal is unfortunately not handled as a task in this * interface. */ Process*(CARB_ABI* launchProcess)(LaunchDesc& desc); /** Launches a detached child process. * * @param[in] desc A descriptor of the child process to launch. At least the * @ref LaunchDesc::argc and @ref LaunchDesc::argv members must be * filled in. Default values on all other members are sufficient. * Note that setting a read callback for `stdout` or `stderr` is * not allowed in a detached process. The @ref LaunchDesc::onReadStderr * and @ref LaunchDesc::onReadStdout parameters will be cleared to * `nullptr` before launching the child process. Callers may still * redirect `stdout` and `stderr` to log files however. The * @ref fLaunchFlagLaunchDetached flag will also be added to the * descriptor so that zombie processes are not inadvertently created * on Unix based platforms. * @returns The process ID of the new child process if successfully launched. * @retval kBadId if the new process could not be launched for any reason. This may * include insufficient permissions, failed memory or resource allocations, etc. * * @remarks This is a convenience version of launchProcess() that launches a child process * but does not return the process handle. Instead the operating system's process * ID for the new child process is returned. This is intended to be used for * situations where the parent process neither needs to communicate with the child * process nor know when it has exited. Using this should be reserved for child * processes that manage their own lifetime and communication with the parent in * another prearranged manner. The returned process ID may be used in OS level * process management functions, but is not useful to pass into any other ILauncher * functions. */ ProcessId launchProcessDetached(LaunchDesc& desc) { ProcessId id; Process* proc; // registering read callbacks is not allowed in a detached process since we'll be // immediately destroying the handle before return. If there were set the child // process would be killed on Linux if it ever tried to write to one of its streams. // On both Windows and Linux having these as non-`nullptr` would also cause a lot // of unnecessary additional work to be done both during and after the launch. desc.onReadStderr = nullptr; desc.onReadStdout = nullptr; // add the 'launch detached' flag to ensure we don't need to wait on the child process // on Linux. This is to avoid leaving a zombie process lying around. desc.flags |= fLaunchFlagLaunchDetached; proc = launchProcess(desc); if (proc == nullptr) return kBadId; id = getProcessId(proc); destroyProcessHandle(proc); return id; } /** Destroys a process handle when it is no longer needed. * * @param[in] process The process handle to destroy. This will no longer be valid upon * return. This call will be silently ignored if `nullptr` is passed in. * @returns No return value. * * @remarks This destroys a process handle object that was previously returned by a call * to launchProcess(). The process handle will no longer be valid upon return. * * @note Calling this does *not* kill the child process the process handle refers to. * It simply recovers the resources taken up by the process handle object. In order * to kill the child process, the caller must call killProcess() first. * * @note [Linux] If the child process was started with a read callback for one or both of * its standard streams, destroying the handle here will cause the child process to * be terminated with SIGPIPE if it ever tries to write to any of the standard streams * that were redirected to the read callbacks. This is the default Linux kernel * behavior for attempting to write to a broken pipe or socket. The only portable * way to work around this is to ensure the child process ignores SIGPIPE signals. * However, the general best practice is for the parent process to wait for the * child process to exit (or explicitly kill it) before destroying the process handle. */ void(CARB_ABI* destroyProcessHandle)(Process* process); /** Retrieves the process identifier for a child process. * * @param[in] process The process handle object representing the child process to retrieve * the identifier for. This may not be `nullptr`. * @returns The integer identifier of the child process if it is still running. * @retval kBadId if the child process if it is not running. * * @remarks This retrieves the process identifier for a child process. This can be used * to gain more advanced platform specific access to the child process if needed, * or simply for debugging or logging identification purposes. */ ProcessId(CARB_ABI* getProcessId)(Process* process); /** Waits for a child process to exit. * * @param[in] process The process handle object representing the child process to wait * for. This may not be `nullptr`. This is returned from a previous * call to launchProcess(). * @param[in] timeout The maximum time in milliseconds to wait for the child process to * exit. This may be @ref kInfiniteTimeout to specify that this should * block until the child process exits. This may be 0 to simply poll * whether the child process has exited or not. * @returns The exit code of the child process if it successfully exited in some manner. * @retval kStillActive if the wait timed out and the child process had not exited yet. * @returns `EXIT_FAILURE` if @p process is `nullptr`. * * @remarks This waits for a child process to exit and retrieves its exit code if the exit * has occurred. Note that this does not in any way signal the child process to * exit. That is left up to the caller since that method would be different for * each child process. This simply waits for the exit to occur. If the child * process doesn't exit within the allotted timeout period, it will remain running * and the special @ref kStillActive exit code will be returned. * * @note Despite the timeout value being a 64-bit value, on Windows this will only wait * for up to ~49.7 days at a time (ie: 32 bits) for the child process to exit. This * is due to all the underlying timing functions only taking a 32-bit timeout value. * If a longer wait is required, the wait will be repeated with the remaining time. * However, if this process is blocking for that long waiting for the child process, * that might not be the most desirable behavior and a redesign might be warranted. * * @note [Linux] if the calling process sets a SIG_IGN signal handler for the SIGCHLD signal, * this call will fail immediately regardless of the child process's current running * state. If a handler function is installed for SIGCHLD or that signal's handler is * still set to its default behavior (ie: SIG_DFL), the child process will become a * zombie process once it exits. This will continue to occupy a slot in the kernel's * process table until the child process is waited on by the parent process. If the * kernel's process table fills up with zombie processes, the system will no longer * be able to create new processes or threads. * * @note [Linux] It is considered an programming error to allow a child process to be leaked * or to destroy the process handle without first waiting on the child process. If * the handle is destroyed without waiting for the child process to [successfully] exit * first, a zombie process will be created. The only exception to this is if the * parent process exits before the child process. In this case, any zombie child * child processes will be inherited by the init (1) system process which will wait * on them and recover their resources. * * @note In general it is best practice to always wait on all child processes before * destroying the process handle object. This guarantees that any zombie children * will be removed and that all resources will be cleaned up from the child process. */ ExitCode(CARB_ABI* waitProcessExit)(Process* process, uint64_t timeout); /** Attempts to retrieve the exit code for a child process. * * @param[in] process The process handle object representing the child process to retrieve * the exit code for. The child process may or may not still be running. * This may not be `nullptr`. * @returns The exit code of the child process if it has already exited in some manner. * @retval kStillActive if the child process is still running. * @returns `EXIT_FAILURE` if @p process is `nullptr`. * * @remarks This attempts to retrieve the exit code for a child process if it has exited. * The exit code isn't set until the child process exits, is killed, or crashes. * The special exit code @ref kStillActive will be returned if the child process * is still running. * * @note [Linux] see the notes about zombie processes in waitProcessExit(). These also * apply to this function since it will also perform a short wait to see if the * child process has exited. If it has exited already, calling this will also * effectively clean up the child zombie process. However, if another component * of this process has set the SIGCHLD signal handler to be ignored (ie: SIG_IGN), * this call will also fail immediately. */ ExitCode(CARB_ABI* getProcessExitCode)(Process* process); /** Writes a buffer of data to the stdin stream of a child process. * * @param[in] process The process handle object representing the child process to write * the data to. This may not be `nullptr`. The child process must * have been opened using the @ref fLaunchFlagOpenStdin flag in * order for this to succeed. * @param[in] data The buffer of data to write to the child process. * @param[in] bytes The total number of bytes to write to the child process or the * special value @ref kNullTerminated to indicate that the buffer * @p data is a null-terminated UTF-8 string. If the latter value * is used, it is the caller's responsibility to ensure the data * buffer is indeed null terminated. * @returns `true` if the buffer of data is successfully written to the child process's * stdin stream. * @returns `false` if the entire data buffer could not be written to the child process's * stdin stream. In this case, the child process's stdin stream will be left * in an unknown state. It is the responsibility of the caller and the child * process to negotiate a way to resynchronize the stdin stream. * @returns `false` if @p process is `nullptr`. * * @remarks This attempts to write a buffer of data to a child process's stdin stream. * This call will be ignored if the child process was not launched using the * @ref fLaunchFlagOpenStdin flag or if the stdin handle for the process has * since been closed with closeProcessStdin(). The entire buffer will be * written to the child process's stdin stream. If even one byte cannot be * successfully written, this call will fail. This can handle data buffers * larger than 4GB if needed. This will block until all data is written. * * @remarks When the @ref kNullTerminated value is used in @p bytes, the data buffer is * expected to contain a null terminated UTF-8 string. The caller is responsible * for ensuring this. In the case of a null terminated string, all of the string * up to but not including the null terminator will be sent to the child process. * If the null terminator is to be sent as well, the caller must specify an * explicit byte count. */ bool(CARB_ABI* writeProcessStdin)(Process* process, const void* data, size_t bytes); /** Closes the stdin stream of a child process. * * @param[in] process The process handle object representing the child process to close * the stdin stream for. This may not be `nullptr`. * @returns No return value. * * @remarks This closes the stdin stream of a child process. This call will be ignored if * the stdin stream for the child process either was never opened or if it has * already been closed by a previous call to closeProcessStdin(). Closing the * stdin stream only closes the side of the stream that is owned by the calling * process. It will not close the actual stream owned by the child process itself. * Other processes may still retrieve the child process's stdin stream handle in * other ways if needed to communicate with it. */ void(CARB_ABI* closeProcessStdin)(Process* process); /** Kills a running child process. * * @param[in] process The process handle object representing the child process to kill. * This may not be `nullptr`. * @param[in] flags Flags to affect the behavior of this call. This may be zero or * more of the @ref KillFlags flags. * @returns No return value. * * @remarks This kills a running child process. If the process has already exited on its * own, this call will be ignored. The child process will be terminated without * being given any chance for it to clean up any of its state or save any * information to persistent storage. This could result in corrupted data if * the child process is in the middle of writing to persistent storage when it * is terminated. It is the caller's responsibility to ensure the child process * is as safe as possible to terminate before calling. * * @remarks On both Windows and Linux, this will set an exit code of either 137 if the * @ref fKillFlagForce flag is used or 143 otherwise. These values are the * exit codes that are set in Linux by default for a terminated process. They * are 128 plus the signal code used to terminate the process. In the case of * a forced kill, this sends SIGKILL (9). In the case of a normal kill, this * sends SIGTERM (15). On Windows, this behavior is simply mimicked. * * @note On Linux, the @ref fKillFlagForce flag is available to cause the child process to * be sent a SIGKILL signal instead of the default SIGTERM. The difference between * the two signals is that SIGTERM can be caught and handled by the process whereas * SIGKILL cannot. Having SIGTERM be sent to end the child process on Linux does * allow for the possibility of a graceful shutdown for apps that handle the signal. * On Linux, it is recommended that if a child process needs to be killed, it is * first sent SIGTERM (by not using the @ref fKillFlagForce flag), then if after a * short time (ie: 2-5 seconds, depending on the app's shutdown behavior) has not * exited, kill it again using the @ref fKillFlagForce flag. */ void(CARB_ABI* killProcess)(Process* process, KillFlags flags); /** Tests whether a process is still running. * * @param[in] process The process handle object representing the child process to query. * This may not be `nullptr`. * @returns `true` if the given child process is still running. * @returns `false` if the child process has exited. */ inline bool isProcessActive(Process* process) { return getProcessExitCode(process) == kStillActive; } /** @copydoc killProcess(). * * @param[in] timeout The time in milliseconds to wait for the child process to fully * exit. This may be 0 to indicate that no wait should occur after * signaling the child process to terminate. This may also be * @ref kInfiniteTimeout to wait indefinitely for the child process * to exit. * @retval KillStatus::eSuccess if the child process is successfully terminated * and was confirmed to have exited or the @ref fKillFlagSkipWait flag is used * and the child process is successfully signaled to exit, or if the child process * had already terminated on its own or was otherwise killed before this call. * @retval KillStatus::eWaitFailed if the child process was successfully signaled to * exit but the timeout for the wait for it to fully exit expired before it exited. * This may still indicate successful termination, but it is left up to the caller * to determine that. * @returns Another @ref KillStatus code if the termination failed in any way. * * @remarks This variant of killProcess() can be used to have more control over how the * child process is terminated and whether it was successful or not. The timeout * allows the caller control over how long the call should wait for the child * process to exit. This can also be used in combination with other functions * such as ILauncher::isDebuggerAttached() to figure out how and when a child * process should be terminated. */ KillStatus(CARB_ABI* killProcessWithTimeout)(Process* process, KillFlags flags, uint64_t timeout); /** Tests whether a debugger is currently attached to a child process. * * @param[in] process The child process to check the debugger status for. This may not be * `nullptr`. This may be a handle to a child process that has already * exited. * @returns `true` if there is a debugger currently attached to the given child process. * @returns `false` if the child process has exited or no debugger is currently attached to * it. * @returns `false` if @p process is `nullptr`. * * @remarks This tests whether a debugger is currently attached to the given child process. * On Windows at least, having a debugger attached to a child process will prevent * it from being terminated with killProcess(). This can be queried to see if the * debugger task has completed before attempting to kill it. */ bool(CARB_ABI* isDebuggerAttached)(Process* process); /** Waits for one or more standard streams from a child process to end. * * @param[in] process The child process to wait on the standard streams for. This may not * be `nullptr`. This may be a handle to a child process that has * already exited. This call will be ignored if the flagged stream(s) * were not opened for the given child process. * @param[in] flags Flags to control how the operation occurs and which stream(s) to wait * on. At least one flag must be specified. This may not be 0. It is * not an error to specify flags for a stream that was not opened by the * child process. In this case, the corresponding flag(s) will simply be * ignored. * @param[in] timeout The maximum amount of time in milliseconds to wait for the flagged * streams to end. This may be @ref kInfiniteTimeout to wait infinitely * for the stream(s) to end. A stream ends when it is closed by either * the child process (by it exiting or explicitly closing its standard * streams) or by the parent process closing it by using one of the * @ref fWaitFlagCloseStdOutStream or @ref fWaitFlagCloseStdErrStream * flags. When a stream ends due to the child process closing it, all * of the pending data will have been consumed by the reader thread and * already delivered to the read callback function for that stream. * @returns `true` if the wait operation specified by @p flags completed successfully. This * means that at least one, possibly both, streams have ended and been fully * consumed. * @returns `false` if the flagged streams did not end within the timeout period. * * @remarks This is used to wait on one or more of the standard streams (`stdout` or `stderr`) * from the child process to end. This ensures that all data coming from the * child process has been consumed and delivered to the reader callbacks. * * @note This does not allow for waiting on the standard streams of child processes that * are writing directly to log files (ie: using the @ref LaunchDesc::stdoutLog and * @ref LaunchDesc::stderrLog parameters). This only affects child processes that * were launched with a read callback specified for `stdout`, `stderr`, or both. */ bool(CARB_ABI* waitForStreamEnd)(Process* process, WaitFlags flags, uint64_t timeout); }; /** Restores the parent death signal on set-user-ID and set-group-ID images. * * @param[in] flags Flags to indicate which signal should be sent on on parent process * exit. This may be 0 to cause the child process to be asked to * gracefully terminate or @ref fKillFlagForce to forcibly terminate * the child process. In the latter case, the child process will not * get any chance to clean up or release resources. * @returns No return value. * * @remarks This restores the parent death signal on Linux after executing an image file * that has a set-user-ID or set-group-ID capability set on it. Unfortunately, * executing one of these image files has the result of clearing the parent * death signal attribute that is set when using the @ref fLaunchFlagKillOnParentExit * flag. These capabilities are set on the image file with the "setcap" command * line tool and require super user access. The capabilities of an executable image * file can be discovered with the "capsh --print" command line tool. See the notes * on ILauncher::launch() for more information. * * @note This only needs to be called when a child process's image file has a set-user-ID * or set-group-ID capability set on it on Linux and the @ref fLaunchFlagKillOnParentExit * flag was used when launching the child process. This is still safe to call on * Windows and will simply do nothing. Note that calling this when the child was not * launched with the @ref fLaunchFlagKillOnParentExit flag will cause that behavior * to be imposed on the child process. Communicating the need for this call is left * as an exercise for both the child and parent processes. */ inline void restoreParentDeathSignal(KillFlags flags = 0) { CARB_UNUSED(flags); #if CARB_PLATFORM_LINUX prctl(PR_SET_PDEATHSIG, (flags & fKillFlagForce) != 0 ? SIGKILL : SIGTERM); #endif } } // namespace launcher } // namespace carb
72,024
C
62.069177
109
0.692866
omniverse-code/kit/include/carb/launcher/LauncherUtils.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 Helper classes and functions for the ILauncher interface. */ #pragma once #include "../Defines.h" #include "../extras/StringSafe.h" #include "../../omni/extras/PathMap.h" #include "../settings/SettingsUtils.h" #include <string> #include <unordered_map> #include <vector> #include <sstream> #if CARB_PLATFORM_LINUX # include <unistd.h> #elif CARB_PLATFORM_MACOS # include <crt_externs.h> #else # include "../CarbWindows.h" # include "../extras/Unicode.h" #endif namespace carb { /** Namespace for the Carbonite process launch helper interface. */ namespace launcher { /** Base type for the flags used when adding a settings tree to an argument collector object. */ using SettingsEnumFlags = uint32_t; /** Flag to indicate that the settings in the requested tree should be added recursively to * the argument collector. If this flag is not present, only the settings directly in the * named path will be added to the object. */ constexpr SettingsEnumFlags fSettingsEnumFlagRecursive = 0x01; /** Prototype for a callback function used to check if a setting should be added. * * @param[in] path The full path to the setting being queried. This will never be `nullptr`. * @param[in] context A caller specified context value that is passed to the callback. * @returns `true` if the setting should be added to the argument collector. Returns `false` * if the setting should not be added to the argument collector. * * @remarks Prototype for a callback predicate function that is used to allow the caller to * determine if a particular setting value should be added to the argument collector. * This is called for each value setting (ie: for `int`, `bool`, `float` and `string` * items). The return value gives the caller an opportunity to provide more fine * grained control over which settings are added to the argument collector than just * the full tree. */ using AddSettingPredicateFn = bool (*)(const char* path, void* context); /** A simple child process argument collector helper class. This allows arguments of different * types to be accumulated into a list that can then later be retrieved as a Unix style argument * list that can be passed to ILauncher::launchProcess() in its @ref LaunchDesc::argv descriptor * member. This allows for string arguments and various integer type arguments to be trivially * added to the argument list without needing to locally convert all of them to strings. The * argument count is also tracked as the arguments are collected. Once all arguments have been * collected, the final Unix style argument list can be retrieved with getArgs() and the count * with getCount(). All collected arguments will remain in the order they are originally * added in. * * The basic usage of this is to create a new object, add one or more arguments of various * types to it using the '+=' operators, then retrieve the Unix style argument list with * getArgs() to assign to @ref LaunchDesc::argv and getCount() to assign to * @ref LaunchDesc::argc before calling ILauncher::launchProcess(). Copy and move operators * and constructors are also provided to make it easier to assign other argument lists to * another object to facilitate more advanced multiple process launches (ie: use a set of * base arguments for each child process then add other child specific arguments to each * one before launching). * * This helper class is not thread safe. It is the caller's responsibility to ensure thread * safe access to objects of this class if needed. */ class ArgCollector { public: ArgCollector() = default; /** Copy constructor: copies another argument collector object into this one. * * @param[in] rhs The argument collector object to copy from. This will be left unmodified. */ ArgCollector(const ArgCollector& rhs) { *this = rhs; } /** Move constructor: moves the contents of another argument collector object into this one. * * @param[in] rhs The argument collector object to move from. This object will be reset to * an empty state. */ ArgCollector(ArgCollector&& rhs) { *this = std::move(rhs); } ~ArgCollector() { clear(); } /** Clears out this object and resets it back to its initially constructed state. * * @returns No return value. * * @remarks This clears out all content collected into this object so far. This object * will be reset back to its original constructed state and will be suitable * for reuse. */ void clear() { m_argList.reset(); m_args.clear(); m_allocCount = 0; } /** Retrieves the final argument list as a Unix style null terminated list. * * @param[out] argCountOut Optionally receives the number of arguments as by via getCount(). * @returns A Unix style argument list. This list will always be terminated by a `nullptr` * entry so that it can be self-counted if needed. This returned argument list * object is owned by this object and should not be deleted or freed. See the * remarks below for more information on the lifetime and use of this object. * @returns `nullptr` if the buffer for the argument list could not be allocated. * * @remarks This retrieves the final argument list for this object. The list object is * owned by this object and should not be freed or deleted. The returned list * will be valid until this object is destroyed or until getArgs() is called * again after adding new arguments. If the caller needs to keep a copy of the * returned argument list, the caller must perform a deep copy on the returned * object. This task is out of the scope of this object and is left as an * exercise for the caller. */ const char* const* getArgs(size_t* argCountOut = nullptr) { if (argCountOut) { *argCountOut = m_args.size(); } if (m_args.empty()) { return emptyArgList(); } if (m_allocCount < m_args.size()) { m_allocCount = m_args.size(); m_argList.reset(new (std::nothrow) const char*[m_args.size() + 1]); if (CARB_UNLIKELY(m_argList == nullptr)) { if (argCountOut) { *argCountOut = 0; } m_allocCount = 0; return nullptr; } } for (size_t i = 0; i < m_args.size(); i++) { m_argList[i] = m_args[i].c_str(); } // null terminate the list since some platforms and apps expect that behavior. m_argList[m_args.size()] = nullptr; return m_argList.get(); } /** Retrieves the argument count for this object. * * @returns The number of arguments that have been collected into this object so far. This * is incremented each time the '+=' operator is used. */ size_t getCount() const { return m_args.size(); } /** Copy assignment operator. * * @param[in] rhs The argument collector object to copy from. This object will receive a * copy of all the arguments currently listed in the @p rhs argument * collector object. The @p rhs object will not be modified. * @returns A reference to this object suitable for chaining other operators or calls. */ ArgCollector& operator=(const ArgCollector& rhs) { if (this == &rhs) return *this; clear(); if (rhs.m_args.size() == 0) return *this; m_args = rhs.m_args; return *this; } /** Move assignment operator. * * @param[inout] rhs The argument collector object to move from. This object will * steal all arguments from @p rhs and will clear out the other * object before returning. * @returns A reference to this object suitable for chaining other operators or calls. */ ArgCollector& operator=(ArgCollector&& rhs) { if (this == &rhs) return *this; clear(); m_args = std::move(rhs.m_args); return *this; } /** Compare this object to another argument collector object for equality. * * @param[in] rhs The argument collector object to compare to this one. * @returns `true` if the two objects contain the same list of arguments. Note that each * object must contain the same arguments in the same order in order for them * to match. * @returns `false` if the argument lists in the two objects differ. */ bool operator==(const ArgCollector& rhs) { size_t count = m_args.size(); if (&rhs == this) return true; if (count != rhs.m_args.size()) return false; for (size_t i = 0; i < count; i++) { if (m_args[i] != rhs.m_args[i]) return false; } return true; } /** Compare this object to another argument collector object for inequality. * * @param[in] rhs The argument collector object to compare to this one. * @returns `true` if the two objects contain a different list of arguments. Note that each * object must contain the same arguments in the same order in order for them * to match. If either the argument count differs or the order of the arguments * differs, this will succeed. * @returns `false` if the argument lists in the two objects match. */ bool operator!=(const ArgCollector& rhs) { return !(*this == rhs); } /** Tests whether this argument collector is empty. * * @returns `true` if this argument collector object is empty. * @returns `false` if argument collector has at least one argument in its list. */ bool operator!() const { return m_args.size() == 0; } /** Tests whether this argument collector is non-empty. * * @returns `true` if argument collector has at least one argument in its list. * @returns `false` if this argument collector object is empty. */ explicit operator bool() const { return !m_args.empty(); } /** Adds a formatted string as an argument. * * @param[in] fmt The printf-style format string to use to create the new argument. This * may not be `nullptr`. * @param[in] ... The arguments required by the format string. * @returns A references to this object suitable for chaining other operators or calls. */ ArgCollector& format(const char* fmt, ...) CARB_PRINTF_FUNCTION(2, 3) { CARB_FORMATTED(fmt, [&](const char* p) { add(p); }); return *this; } /** Adds a new argument or set of arguments to the end of the list. * * @param[in] value The value to add as a new argument. This may be a string or any * primitive integer or floating point type value. For integer and * floating point values, they will be converted to a string before * being added to the argument list. For the variants that add * another argument collector list or a `nullptr` terminated string * list, or a vector of strings to this one, all arguments in the * other object will be copied into this one in the same order. All * new argument(s) will always be added at the end of the list. * @returns A reference to this object suitable for chaining other operators or calls. */ ArgCollector& add(const char* value) { m_args.push_back(value); return *this; } /** @copydoc add(const char*) */ ArgCollector& add(const std::string& value) { m_args.push_back(value); return *this; } /** @copydoc add(const char*) */ ArgCollector& add(const ArgCollector& value) { for (auto& arg : value.m_args) m_args.push_back(arg); return *this; } /** @copydoc add(const char*) */ ArgCollector& add(const char* const* value) { for (const char* const* arg = value; arg[0] != nullptr; arg++) m_args.push_back(arg[0]); return *this; } /** @copydoc add(const char*) */ ArgCollector& add(const std::vector<const char*>& value) { for (auto& v : value) add(v); return *this; } /** @copydoc add(const char*) */ ArgCollector& add(const std::vector<std::string>& value) { for (auto& v : value) add(v); return *this; } /** @copydoc add(const char*) */ ArgCollector& operator+=(const char* value) { return add(value); } /** @copydoc add(const char*) */ ArgCollector& operator+=(const std::string& value) { return add(value); } /** @copydoc add(const char*) */ ArgCollector& operator+=(const ArgCollector& value) { return add(value); } /** @copydoc add(const char*) */ ArgCollector& operator+=(const char* const* value) { return add(value); } /** @copydoc add(const char*) */ ArgCollector& operator+=(const std::vector<const char*>& value) { return add(value); } /** @copydoc add(const char*) */ ArgCollector& operator+=(const std::vector<std::string>& value) { return add(value); } /** Macro to add other [almost identical] variants of the add() and operator+=() functions. * Note that this unfortunately can't be a template because a 'const char*' value is not * allowed as a template argument since it doesn't lead to a unique instantiation. This * is similar to the reasoning for a float value not being allowed as a template argument. * Using a macro here saves 140+ lines of code (mostly duplicated) and documentation. * @private */ #define ADD_PRIMITIVE_HANDLER(type, fmt) \ /** Adds a new primitive value to this argument collector object. \ @param[in] value The primitive numerical value to add to this argument collector \ object. This will be converted to a string before adding to the \ collector. \ @returns A reference to this argument collector object. \ */ \ ArgCollector& add(type value) \ { \ char buffer[128]; \ carb::extras::formatString(buffer, CARB_COUNTOF(buffer), fmt, value); \ m_args.push_back(buffer); \ return *this; \ } \ /** @copydoc add(type) */ \ ArgCollector& operator+=(type value) \ { \ return add(value); \ } // unsigned integer handlers. ADD_PRIMITIVE_HANDLER(unsigned char, "%u") ADD_PRIMITIVE_HANDLER(unsigned short, "%u") ADD_PRIMITIVE_HANDLER(unsigned int, "%u") ADD_PRIMITIVE_HANDLER(unsigned long, "%lu") ADD_PRIMITIVE_HANDLER(unsigned long long, "%llu") // signed integer handlers. ADD_PRIMITIVE_HANDLER(char, "%d") ADD_PRIMITIVE_HANDLER(short, "%d") ADD_PRIMITIVE_HANDLER(int, "%d") ADD_PRIMITIVE_HANDLER(long, "%ld") ADD_PRIMITIVE_HANDLER(long long, "%lld") // other numerical handlers. Note that some of these can be trivially implicitly cast to // other primitive types so we can't define them again. Specifically the size_t, // intmax_t, and uintmax_t types often match other types with handlers defined above. // Which handler each of these matches to will differ by platform however. ADD_PRIMITIVE_HANDLER(float, "%.10f") ADD_PRIMITIVE_HANDLER(double, "%.20f") #undef ADD_PRIMITIVE_HANDLER /** Adds all settings under a branch in the settings registry to this object. * * @param[in] root The root of the settings tree to copy into this argument * collector. This may be `nullptr` or an empty string to * add all settings starting from the root of the settings * registry. This string should start with a '/' so that it is * always an absolute settings path. * @param[in] prefix The prefix to add to each option before adding it to this * argument collector. This may be `nullptr` or an empty string * to not use any prefix. * @param[in] flags Flags to control the behavior of this operation. This may be * zero or more of the @ref SettingsEnumFlags flags. This defaults * to 0. * @param[in] predicate A predicate function that will be called for each value to give * the caller a chance to decide whether it should be added to this * object or not. This may be `nullptr` if all settings under the * given root should always be added. This defaults to `nullptr`. * @param[in] context An opaque context value that will be passed to the predicate * function @p predicate. This will not be accessed or used in * any way except to pass to the predicate function. This defaults * to `nullptr`. * @returns A reference to this argument collector object. * * @remarks This adds echoes of all settings under a given root branch as arguments in this * argument collector. Each setting that is found is given the prefix @p prefix * (typically something like "--/"). This is useful for passing along certain * subsets of a parent process's settings tree to a child process. * * @note It is the caller's responsibility to ensure that only expected settings are added * to this argument collector. A predicate function can be provided to allow per-item * control over which settings get added. By default, the search is not recursive. * This is intentional since adding a full tree could potentially add a lot of new * arguments to this object. */ ArgCollector& add(const char* root, const char* prefix, SettingsEnumFlags flags = 0, AddSettingPredicateFn predicate = nullptr, void* context = nullptr) { dictionary::IDictionary* dictionary = getCachedInterface<dictionary::IDictionary>(); settings::ISettings* settings = getCachedInterface<settings::ISettings>(); std::string rootPath; auto addSetting = [&](const char* path, int32_t elementData, void* context) -> int32_t { dictionary::ItemType type; CARB_UNUSED(context); type = settings->getItemType(path); // skip dictionaries since we're only interested in leaves here. if (type == dictionary::ItemType::eDictionary) return elementData + 1; if ((flags & fSettingsEnumFlagRecursive) == 0 && elementData > 1) return elementData; // verify that the caller wants this setting added. if (predicate != nullptr && !predicate(path, context)) return elementData + 1; switch (type) { case dictionary::ItemType::eBool: format("%s%s=%s", prefix, &path[1], settings->getAsBool(path) ? "true" : "false"); break; case dictionary::ItemType::eInt: format("%s%s=%" PRId64, prefix, &path[1], settings->getAsInt64(path)); break; case dictionary::ItemType::eFloat: format("%s%s=%g", prefix, &path[1], settings->getAsFloat64(path)); break; case dictionary::ItemType::eString: format("%s%s=\"%s\"", prefix, &path[1], settings->getStringBuffer(path)); break; default: break; } return elementData; }; // unexpected root prefix (not an absolute settings path) => fail. if (root == nullptr || root[0] == 0) root = "/"; // avoid a `nullptr` check later. if (prefix == nullptr) prefix = ""; // make sure to strip off any trailing separators since that would break the lookups. rootPath = root; if (rootPath.size() > 1 && rootPath[rootPath.size() - 1] == '/') rootPath = rootPath.substr(0, rootPath.size() - 1); // walk the settings tree to collect all the requested settings. settings::walkSettings( dictionary, settings, dictionary::WalkerMode::eIncludeRoot, rootPath.c_str(), 0, addSetting, context); return *this; } /** Retrieves the argument string at a given index. * * @param[in] index The zero based index of the argument to retrieve. This must be * strictly less than the number of arguments in the list as returned * by getCount(). If this index is out of range, an empty string * will be returned instead. * @returns A reference to the string contained in the requested argument in the list. * This returned string should not be modified by the caller. * * @remarks This retrieves the argument string stored at the given index in the argument * list. This string will be the one stored in the list itself and should not * be modified. */ const std::string& at(size_t index) const { if (index >= m_args.size()) return m_empty; return m_args[index]; } /** @copydoc at() */ const std::string& operator[](size_t index) const { return at(index); } /** Removes the last argument from the list. * * @returns No return value. * * @remarks This removes the last argument from the list. If this is called, any previous * returned object from getArgs() will no longer be valid. The updated list object * must be retrieved again with another call to getArgs(). */ void pop() { if (m_args.empty()) return; m_args.pop_back(); } /** Removes an argument from the list by its index. * * @returns `true` if the item is successfully removed. * @returns `false` if the given index is out of range of the argument list's size. * * @remarks This removes an argument from the list. If this is called, any previous returned * object from getArgs() will no longer be valid. The updated list object must be * retrieved again with another call to getArgs(). */ bool erase(size_t index) { if (index >= m_args.size()) return false; m_args.erase(m_args.begin() + index); return true; } /** Returns a string of all arguments for debugging purposes. * @returns A `std::string` of all arguments concatenated. This is for debugging/logging purposes only. */ std::string toString() const { std::ostringstream stream; for (auto& arg : m_args) { size_t index = size_t(-1); for (;;) { size_t start = index + 1; index = arg.find_first_of("\\\" '", start); // Characters that must be escaped stream << arg.substr(start, index - start); if (index == std::string::npos) break; stream << '\\' << arg[index]; } // Always add a trailing space. It will be popped before return. stream << ' '; } std::string out = stream.str(); if (!out.empty()) out.pop_back(); // Remove the extra space return out; } private: static const char* const* emptyArgList() { static const char* const empty{ nullptr }; return &empty; } /** An empty string to be retrieved from operator[] in the event of an out of range index. * This is used to avoid the undesirable behavior of having an exception thrown by the * underlying implementation of std::vector<>. */ std::string m_empty; /** The vector of collected arguments. This represents the most current list of arguments * for this object. The list in @p m_argList may be out of date if new arguments are * added or existing ones removed. The argument count is always taken from the size of * this vector. */ std::vector<std::string> m_args; /** The Unix style list of arguments as last retrieved by getArgs(). This is only updated * when getArgs() is called. This object may be destroyed and recreated in subsequent * calls to getArgs() if the argument list is modified. */ std::unique_ptr<const char*[]> m_argList; /** The last allocation size of the @p m_argList object in items. This is used to avoid * reallocating the previous object if it is already large enough for a new call to * getArgs(). */ size_t m_allocCount = 0; }; /** A simple environment variable collector helper class. This provides a way to collect a set of * environment variables and their values for use in ILauncher::launchProcess(). Each variable * in the table will be unique. Attempting to add a variable multiple times will simply replace * any previous value. Specifying a variable without a value will remove it from the table. * Values for variables may be specified in any primitive integer or floating point type as * well as string values. Once all desired variables have been collected into the object, a * Unix style environment table can be retrieved with getEnv(). and the could with getCount(). * The order of the variables in the environment block will be undefined. * * The basic usage of this is to create a new object, add one or more variables and their * values (of various types) using the various add() or '+=' operators, the retrieve the Unix * style environment block with getEnv() to assign to @ref LaunchDesc::env, and getCount() to * assign to @ref LaunchDesc::envCount. This environment block is then passed through the * launch descriptor to ILauncher::launchProcess(). Copy and move constructors are also * provided to make it easier to assign and combine other environment lists. * * The calling process's current environment can also be added using the add() function without * any arguments. This can be used to allow a child process to explicitly inherit the parent * process's environment block while also adding other variables or changing existing ones. * * On Windows all environment variable names used in this object are treated as case insensitive. * All values set set for the variables will be case preserving. This matches Windows' native * behavior in handling environment variables. If multiple casings are used in specifying the * variable name when modifying any given variable, the variable's name will always keep the * casing from when it was first added. Later changes to that variable regardless of the casing * will only modify the variable's value. * * On Linux, all environment variable names used in this object are treated as case sensitive. * All values set for the variables will be case preserving. This matches Linux's native * behavior in handling environment variables. It is the caller's responsibility to ensure * the proper casing is used when adding or modifying variables. Failure to match the case * of an existing variable for example will result in two variables with the same name but * different casing being added. This can be problematic for example when attempting to * modify a standard variable such as "PATH" or "LD_LIBRARY_PATH". * * Also note that using this class does not affect or modify the calling process's environment * variables in any way. This only collects variables and their values in a format suitable * for setting as a child process's new environment. * * This helper class is not thread safe. It is the caller's responsibility to ensure thread * safe access to objects of this class if needed. */ class EnvCollector { public: EnvCollector() = default; /** Copy constructor: copies another environment collector object into this one. * * @param[in] rhs The other environment collector object whose contents will be copied * into this one. This other object will not be modified. */ EnvCollector(const EnvCollector& rhs) { *this = rhs; } /** Move constructor: moves the contents of an environment collector object into this one. * * @param[in] rhs The other environment collector object whose contents will be moved * into this one. Upon return, this other object will be reset to an * empty state. */ EnvCollector(EnvCollector&& rhs) { *this = std::move(rhs); } ~EnvCollector() { clear(); } /** Clears out this environment block object. * * @returns No return value. * * @remarks This clears out this environment block object. Any existing variables and their * values will be lost and the object will be reset to its default constructed * state for reuse. */ void clear() { m_env.clear(); m_args.clear(); } /** Retrieves the Unix style environment block representing the variables in this object. * * @returns A Unix style environment block. This will be an array of string pointers. * The last entry in the array will always be a `nullptr` string. This can be * used to count the length of the environment block without needing to explicitly * pass in its size as well. * @returns `nullptr` if the buffer for the environment block could not be allocated. * * @remarks This retrieves the Unix style environment block for this object. The environment * block object is owned by this object and should not be freed or deleted. The * returned block will be valid until this object is destroyed or until getEnv() * is called again. If the caller needs to keep a copy of the returned environment * block object, the caller must perform a deep copy on the returned object. This * task is out of the scope of this object and is left as an exercise for the caller. */ const char* const* getEnv() { m_args.clear(); for (auto& var : m_env) m_args.format("%s=%s", var.first.c_str(), var.second.c_str()); return m_args.getArgs(); } /** Retrieves the number of unique variables in the environment block. * * @returns The total number of unique variables in this environment block. * @returns `0` if this environment block object is empty. */ size_t getCount() const { return m_env.size(); } /** Copy assignment operator. * * @param[in] rhs The environment collector object to copy from. This object will receive * a copy of all the variables currently listed in the @p rhs environment * collector object. The @p rhs object will not be modified. * @returns A reference to this object suitable for chaining other operators or calls. */ EnvCollector& operator=(const EnvCollector& rhs) { if (this == &rhs) return *this; clear(); if (rhs.m_env.size() == 0) return *this; m_env = rhs.m_env; return *this; } /** Move assignment operator. * * @param[inout] rhs The argument collector object to move from. This object will * steal all arguments from @p rhs and will clear out the other * object before returning. * @returns A reference to this object suitable for chaining other operators or calls. */ EnvCollector& operator=(EnvCollector&& rhs) { if (this == &rhs) return *this; clear(); m_env = std::move(rhs.m_env); return *this; } /** Compare this object to another argument collector object for equality. * * @param[in] rhs The argument collector object to compare to this one. * @returns `true` if the two objects contain the same list of arguments. Note that each * object must contain the same arguments in the same order in order for them * to match. * @returns `false` if the argument lists in the two objects differ. */ bool operator==(const EnvCollector& rhs) { size_t count = m_env.size(); if (&rhs == this) return true; if (count != rhs.m_env.size()) return false; for (auto var : m_env) { auto other = rhs.m_env.find(var.first); if (other == rhs.m_env.end()) return false; if (other->second != var.second) return false; } return true; } /** Compare this object to another argument collector object for inequality. * * @param[in] rhs The argument collector object to compare to this one. * @returns `true` if the two objects contain a different list of arguments. Note that each * object must contain the same arguments in the same order in order for them * to match. If either the argument count differs or the order of the arguments * differs, this will succeed. * @returns `false` if the argument lists in the two objects match. */ bool operator!=(const EnvCollector& rhs) { return !(*this == rhs); } /** Tests whether this argument collector is empty. * * @returns `true` if this argument collector object is empty. * @returns `false` if argument collector has at least one argument in its list. */ bool operator!() { return m_env.size() == 0; } /** Tests whether this argument collector is non-empty. * * @returns `true` if argument collector has at least one argument in its list. * @returns `false` if this argument collector object is empty. */ operator bool() { return !m_env.empty(); } /** Adds a new environment variable by name and value. * * @param[in] name The name of the environment variable to add or replace. This may * not be an empty string or `nullptr`, and should not contain an '=' * except as the first character. * @param[in] value The value to assign to the variable @p name. This may be `nullptr` * or an empty string to add a variable with no value. * @returns A reference to this object suitable for chaining multiple calls. * * @remarks These functions allow various combinations of name and value types to be used * to add new environment variables to this object. Values may be set as strings, * integers, or floating point values. */ EnvCollector& add(const char* name, const char* value) { m_env[name] = value == nullptr ? "" : value; return *this; } /** @copydoc add(const char*,const char*) */ EnvCollector& add(const std::string& name, const std::string& value) { m_env[name] = value; return *this; } /** @copydoc add(const char*,const char*) */ EnvCollector& add(const std::string& name, const char* value) { m_env[name] = value == nullptr ? "" : value; return *this; } /** @copydoc add(const char*,const char*) */ EnvCollector& add(const char* name, const std::string& value) { m_env[name] = value; return *this; } #define ADD_PRIMITIVE_HANDLER(type, fmt) \ /** Adds a new name and primitive value to this environment collector object. \ @param[in] name The name of the new environment variable to be added. This may \ not be `nullptr` or an empty string. \ @param[in] value The primitive numerical value to set as the environment variable's \ value. This will be converted to a string before adding to the \ collector. \ @returns A reference to this environment collector object. \ */ \ EnvCollector& add(const char* name, type value) \ { \ char buffer[128]; \ carb::extras::formatString(buffer, CARB_COUNTOF(buffer), fmt, value); \ return add(name, buffer); \ } \ /** @copydoc add(const char*,type) */ \ EnvCollector& add(const std::string& name, type value) \ { \ return add(name.c_str(), value); \ } // unsigned integer handlers. ADD_PRIMITIVE_HANDLER(uint8_t, "%" PRIu8) ADD_PRIMITIVE_HANDLER(uint16_t, "%" PRIu16) ADD_PRIMITIVE_HANDLER(uint32_t, "%" PRIu32) ADD_PRIMITIVE_HANDLER(uint64_t, "%" PRIu64) // signed integer handlers. ADD_PRIMITIVE_HANDLER(int8_t, "%" PRId8) ADD_PRIMITIVE_HANDLER(int16_t, "%" PRId16) ADD_PRIMITIVE_HANDLER(int32_t, "%" PRId32) ADD_PRIMITIVE_HANDLER(int64_t, "%" PRId64) // other numerical handlers. Note that some of these can be trivially implicitly cast to // other primitive types so we can't define them again. Specifically the size_t, // intmax_t, and uintmax_t types often match other types with handlers defined above. // Which handler each of these matches to will differ by platform however. ADD_PRIMITIVE_HANDLER(float, "%.10f") ADD_PRIMITIVE_HANDLER(double, "%.20f") #undef ADD_PRIMITIVE_HANDLER /** Adds or replaces a variable specified in a single string. * * @param[in] var The variable name and value to set. This may not be `nullptr` or an empty * string. This must be in the format `<name>=<value>`. There should not * be any spaces between the name, '=' and value portions of the string. * If the '=' is missing or no value is given after the '=', the value of * the named variable will be cleared out, but the variable will still * remain valid. * @returns A reference to this object suitable for chaining multiple calls. */ EnvCollector& add(const char* var) { const char* sep; #if CARB_PLATFORM_WINDOWS // Windows' environment sets variables such as "=C:=C:\". We need to handle this case. // Here the variable's name is "=C:" and its value is "C:\". This similar behavior is // not allowed on Linux however. if (var[0] == '=') sep = strchr(var + 1, '='); else #endif sep = strchr(var, '='); // no assignment in the string => clear out that variable. if (sep == nullptr) { m_env[var] = ""; return *this; } m_env[std::string(var, sep - var)] = sep + 1; return *this; } /** @copydoc add(const char*) */ EnvCollector& add(const std::string& var) { return add(var.c_str()); } /** @copydoc add(const char*) */ EnvCollector& operator+=(const char* var) { return add(var); } /** @copydoc add(const char*) */ EnvCollector& operator+=(const std::string& var) { return add(var.c_str()); } /** Adds a set of environment variables to this object. * * @param[in] vars The set of variables to add to this object. This may not be * `nullptr`. * The string table variant is intended to be a Unix style `nullptr` * terminated string list. The other variants add the full contents * of another environment collector object. * @returns A reference to this object suitable for chaining multiple calls. */ EnvCollector& add(const char* const* vars) { for (const char* const* var = vars; var[0] != nullptr; var++) add(var[0]); return *this; } /** @copydoc add(const char* const*) */ EnvCollector& add(const std::vector<const char*>& vars) { for (auto& v : vars) add(v); return *this; } /** @copydoc add(const char* const*) */ EnvCollector& add(const std::vector<std::string>& vars) { for (auto& v : vars) add(v); return *this; } /** @copydoc add(const char* const*) */ EnvCollector& add(const EnvCollector& vars) { for (auto& var : vars.m_env) m_env[var.first] = var.second; return *this; } /** @copydoc add(const char* const*) */ EnvCollector& operator+=(const char* const* vars) { return add(vars); } /** @copydoc add(const char* const*) */ EnvCollector& operator+=(const std::vector<const char*>& vars) { return add(vars); } /** @copydoc add(const char* const*) */ EnvCollector& operator+=(const std::vector<std::string>& vars) { return add(vars); } /** @copydoc add(const char* const*) */ EnvCollector& operator+=(const EnvCollector& vars) { return add(vars); } /** Adds the environment variables from the calling process. * * @returns A reference to this object suitable for chaining multiple calls. * * @remarks This adds all of the current environment variables of the calling process to * this environment block. Any variables with the same name that already existed * in this object will be replaced. This is suitable for inheriting the calling * process's current environment when launching a child process while still allowing * changes or additions before launch. */ #if CARB_POSIX EnvCollector& add() { # if CARB_PLATFORM_MACOS char*** tmp = _NSGetEnviron(); // see man 7 environ if (tmp == nullptr) { CARB_LOG_ERROR("_NSGetEnviron() returned nullptr"); return *this; } char** environ = *tmp; # endif for (char** env = environ; env[0] != nullptr; env++) add(env[0]); return *this; } #else EnvCollector& add() { LPWCH origEnv = GetEnvironmentStringsW(); LPWCH env = origEnv; std::string var; size_t len; // walk the environment strings table and add each variable to this object. for (len = wcslen(env); env[0] != 0; env += len + 1, len = wcslen(env)) { var = extras::convertWideToUtf8(env); add(var); } FreeEnvironmentStringsW(origEnv); return *this; } #endif /** Removes a variable and its value from this object. * * @param[in] name The name of the variable to be removed. This may not be `nullptr` or * an empty string. The named variable will no longer be present in * this object upon return and its value will be lost. * @returns A reference to this object suitable for chaining multiple calls. */ EnvCollector& remove(const char* name) { m_env.erase(name); return *this; } /** @copydoc remove(const char*) */ EnvCollector& remove(const std::string& name) { return remove(name.c_str()); } /** @copydoc remove(const char*) */ EnvCollector& operator-=(const char* name) { return remove(name); } /** @copydoc remove(const char*) */ EnvCollector& operator-=(const std::string& name) { return remove(name.c_str()); } /** Retrieves the value for a named variable in this environment block object. * * @param[in] name The name of the variable to retrieve the value of. This may not be * `nullptr` or an empty string. The value of the variable will not be * modified by this lookup nor can its value be changed by assigning * a new string to the returned string. To change the value, one of * the add() functions or '+=()' operators should be used instead. * @returns The value of the named variable if present in this environment block. * @returns An empty string if the variable is not present in this environment block. */ const std::string& at(const char* name) { auto var = m_env.find(name); if (var == m_env.end()) return m_empty; return var->second; } /** @copydoc at(const char*) */ const std::string& at(const std::string& name) { return at(name.c_str()); } /** @copydoc at(const char*) */ const std::string& operator[](const char* name) { return at(name); } /** @copydoc at(const char*) */ const std::string& operator[](const std::string& name) { return at(name.c_str()); } private: /** The table of argument names and values. This behaves differently in terms of case * sensitivity depending on the platform. On Windows, environment variable names are * treated as case insensitive to match local OS behavior. In contrast, on Linux * environment variable names are treated as case sensitive. */ omni::extras::UnorderedPathMap<std::string> m_env; /** The argument collector used to generate the environment block for getEnv(). */ ArgCollector m_args; /** An empty string to return in case a variable is not found in the table. */ std::string m_empty; }; } // namespace launcher } // namespace carb
50,272
C
39.026274
120
0.571531
omniverse-code/kit/include/carb/cpp17/Tuple.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 "Functional.h" #include "../cpp/Tuple.h" CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead") namespace carb { namespace cpp17 { using ::carb::cpp::apply; } } // namespace carb CARB_INCLUDE_PURIFY_TEST({ carb::cpp17::apply([](int) {}, std::make_tuple(5)); });
817
C
26.266666
85
0.747858
omniverse-code/kit/include/carb/cpp17/Utility.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/Utility.h" CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead") namespace carb { namespace cpp17 { using ::carb::cpp::in_place; using ::carb::cpp::in_place_index; using ::carb::cpp::in_place_index_t; using ::carb::cpp::in_place_t; using ::carb::cpp::in_place_type; using ::carb::cpp::in_place_type_t; } // namespace cpp17 } // namespace carb CARB_INCLUDE_PURIFY_TEST({ static_assert(sizeof(carb::cpp17::in_place), ""); static_assert(sizeof(carb::cpp17::in_place_index<0>), ""); static_assert(sizeof(carb::cpp17::in_place_index_t<0>), ""); static_assert(sizeof(carb::cpp17::in_place_t), ""); static_assert(sizeof(carb::cpp17::in_place_type<int>), ""); static_assert(sizeof(carb::cpp17::in_place_type_t<int>), ""); });
1,306
C
30.878048
85
0.712098
omniverse-code/kit/include/carb/cpp17/StringView.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 "../cpp20/TypeTraits.h" #include "../cpp/StringView.h" CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead") namespace carb { namespace cpp17 { using ::carb::cpp::basic_string_view; using ::carb::cpp::string_view; using ::carb::cpp::wstring_view; #if CARB_HAS_CPP20 using ::carb::cpp::u8string_view; #endif using ::carb::cpp::u16string_view; using ::carb::cpp::u32string_view; using ::carb::cpp::operator""_sv; } // namespace cpp17 } // namespace carb CARB_INCLUDE_PURIFY_TEST({ static_assert(sizeof(carb::cpp17::basic_string_view<char>), ""); static_assert(sizeof(carb::cpp17::string_view), ""); static_assert(sizeof(carb::cpp17::wstring_view), ""); static_assert(sizeof(carb::cpp17::u16string_view), ""); static_assert(sizeof(carb::cpp17::u32string_view), ""); });
1,343
C
29.545454
85
0.726731
omniverse-code/kit/include/carb/cpp17/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 "../cpp/TypeTraits.h" CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead") namespace carb { //! (Deprecated) Namespace for C++17 features using C++14 semantics. Use \ref carb::cpp instead. namespace cpp17 { using ::carb::cpp::bool_constant; using ::carb::cpp::conjunction; using ::carb::cpp::disjunction; using ::carb::cpp::invoke_result; using ::carb::cpp::invoke_result_t; using ::carb::cpp::is_convertible; using ::carb::cpp::is_invocable; using ::carb::cpp::is_invocable_r; using ::carb::cpp::is_nothrow_invocable; using ::carb::cpp::is_nothrow_invocable_r; using ::carb::cpp::is_nothrow_swappable; using ::carb::cpp::is_nothrow_swappable_with; using ::carb::cpp::is_swappable; using ::carb::cpp::is_swappable_with; using ::carb::cpp::is_void; using ::carb::cpp::negation; using ::carb::cpp::void_t; } // namespace cpp17 } // namespace carb CARB_INCLUDE_PURIFY_TEST({ using True = carb::cpp17::bool_constant<true>; using False = carb::cpp17::bool_constant<false>; static_assert(carb::cpp17::conjunction<True, True>::value, "1"); static_assert(carb::cpp17::disjunction<True, False>::value, "2"); auto foo = []() noexcept { return true; }; static_assert(std::is_same<carb::cpp17::invoke_result<decltype(foo)>::type, bool>::value, "3"); static_assert(std::is_same<carb::cpp17::invoke_result_t<decltype(foo)>, bool>::value, "4"); static_assert(carb::cpp17::is_convertible<bool, int>::value, "5"); static_assert(carb::cpp17::is_invocable<decltype(foo)>::value, "6"); static_assert(carb::cpp17::is_invocable_r<bool, decltype(foo)>::value, "7"); static_assert(carb::cpp17::is_nothrow_invocable<decltype(foo)>::value, "9"); static_assert(carb::cpp17::is_nothrow_invocable_r<bool, decltype(foo)>::value, "10"); static_assert(std::is_class<carb::cpp17::is_nothrow_swappable<int>>::value, "11"); static_assert(std::is_class<carb::cpp17::is_nothrow_swappable_with<int, int>>::value, "12"); static_assert(std::is_class<carb::cpp17::is_swappable<int>>::value, "13"); static_assert(std::is_class<carb::cpp17::is_swappable_with<int, int>>::value, "14"); static_assert(carb::cpp17::is_void<void>::value, "15"); static_assert(carb::cpp17::negation<False>::value, "16"); });
2,789
C
41.923076
99
0.702044
omniverse-code/kit/include/carb/cpp17/Optional.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 "Utility.h" #include "../cpp/Optional.h" CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead") namespace carb { namespace cpp17 { using ::carb::cpp::bad_optional_access; using ::carb::cpp::make_optional; using ::carb::cpp::nullopt; using ::carb::cpp::nullopt_t; using ::carb::cpp::optional; } // namespace cpp17 } // namespace carb CARB_INCLUDE_PURIFY_TEST({ carb::cpp17::optional<int> opt{ carb::cpp17::nullopt }; carb::cpp17::optional<int> opt2 = carb::cpp17::make_optional<int>(5); CARB_UNUSED(opt, opt2); static_assert(sizeof(carb::cpp17::nullopt_t), ""); static_assert(sizeof(carb::cpp17::bad_optional_access), ""); });
1,201
C
29.049999
85
0.727727
omniverse-code/kit/include/carb/profiler/IProfileMonitor.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 Monitor interface for carb.profiler. #pragma once #include "../Defines.h" #include "../Types.h" namespace carb { namespace profiler { /** * A struct describing a specific profiling event. */ struct ProfileEvent { //! A human-readable name for the event. const char* eventName; //! The thread ID that recorded this event. Comparable with `GetCurrentThreadID()` on Windows or `gettid()` on //! Linux. uint64_t threadId; //! The start timestamp for this event. Based on 10 nanoseconds units since IProfiler::startup() was called. uint64_t startTime; //! The total time in milliseconds elapsed for this event. float timeInMs; //! The stack depth for this event. uint16_t level; }; //! An opaque pointer used by IProfileMonitor. using ProfileEvents = struct ProfileEventsImpl*; /** * Defines an interface to monitor profiling events. */ struct IProfileMonitor { CARB_PLUGIN_INTERFACE("carb::profiler::IProfileMonitor", 1, 1) /** * Returns the profiled events for the previous frame (up to the previous \ref markFrameEnd() call). * * @returns an opaque pointer that refers to the previous frame's profiling information. This pointer must be * released with releaseLastProfileEvents() when the caller is finished with it. */ ProfileEvents(CARB_ABI* getLastProfileEvents)(); /** * Returns the number of profiling events for a ProfileEvents instance. * * @param events The ProfileEvents instance returned from getLastProfileEvents(). * @returns The number of profiling events in the array returned by getLastProfileEventsData(). */ size_t(CARB_ABI* getLastProfileEventCount)(ProfileEvents events); /** * Returns an array of profiling events for a ProfileEvents instance. * * @param events The ProfileEvents instance returned from getLastProfileEvents(). * @returns An array of ProfileEvent objects. The size of the array is returned by getLastProfileEventCount(). */ ProfileEvent*(CARB_ABI* getLastProfileEventsData)(ProfileEvents events); /** * Returns the number of thread IDs known to the ProfileEvents instance. * * @param events The ProfileEvents instance returned from getLastProfileEvents(). * @returns The number of thread IDs in the array returned by getProfileThreadIds(). */ uint32_t(CARB_ABI* getProfileThreadCount)(ProfileEvents events); /** * Returns an array of thread IDs known to a ProfileEvents instance. * * @param events The ProfileEvents instance returned from getLastProfileEvents(). * @returns An array of thread IDs. The size of the array is returned by getProfileThreadCount(). The thread IDs * are comparable with `GetCurrentThreadID()` on Windows and `gettid()` on Linux. */ uint64_t const*(CARB_ABI* getProfileThreadIds)(ProfileEvents events); /** * Destroys a ProfileEvents instance. * * The data returned getLastProfileEventsData() and getProfileThreadIds() must not be referenced after this function * is called. * * @param events The ProfileEvents instance returned from getLastProfileEvents(). */ void(CARB_ABI* releaseLastProfileEvents)(ProfileEvents events); /** * Returns the thread ID that called \ref markFrameEnd() event. * * @param events The ProfileEvents instance returned from getLastProfileEvents(). * @returns The thread ID that last called \ref markFrameEnd(). This thread ID is comparable with * `GetCurrentThreadID()` on Windows and `gettid()` on Linux. */ uint64_t(CARB_ABI* getMainThreadId)(ProfileEvents events); /** * Marks the end of a frame's profile events. * * After this call, the previous frame's profile events are available via \ref getLastProfileEvents(). */ void(CARB_ABI* markFrameEnd)(); }; } // namespace profiler } // namespace carb
4,405
C
33.968254
120
0.708967
omniverse-code/kit/include/carb/profiler/ProfilerBindingsPython.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 "../Framework.h" #include "IProfileMonitor.h" #include <memory> #include <string> #include <vector> using namespace pybind11::literals; namespace carb { namespace profiler { namespace { class ScopedProfileEvents { public: ScopedProfileEvents(const IProfileMonitor* profileMonitor) : m_profileMonitor(profileMonitor) { m_profileEvents = m_profileMonitor->getLastProfileEvents(); } ScopedProfileEvents(ScopedProfileEvents&& rhs) : m_profileEvents(rhs.m_profileEvents), m_profileMonitor(rhs.m_profileMonitor) { rhs.m_profileEvents = nullptr; } ~ScopedProfileEvents() { if (m_profileEvents) m_profileMonitor->releaseLastProfileEvents(m_profileEvents); } ScopedProfileEvents& operator=(ScopedProfileEvents&& rhs) { std::swap(m_profileEvents, rhs.m_profileEvents); std::swap(m_profileMonitor, rhs.m_profileMonitor); return *this; } CARB_PREVENT_COPY(ScopedProfileEvents); const IProfileMonitor* mon() const { return m_profileMonitor; } operator ProfileEvents() const { return m_profileEvents; } private: ProfileEvents m_profileEvents; const IProfileMonitor* m_profileMonitor; }; inline void definePythonModule(py::module& m) { using namespace carb::profiler; m.doc() = "pybind11 carb.profiler bindings"; py::enum_<InstantType>(m, "InstantType").value("THREAD", InstantType::Thread).value("PROCESS", InstantType::Process) /**/; py::enum_<FlowType>(m, "FlowType").value("BEGIN", FlowType::Begin).value("END", FlowType::End) /**/; m.def("is_profiler_active", []() -> bool { return (g_carbProfiler != nullptr); }, py::call_guard<py::gil_scoped_release>()); m.def("supports_dynamic_source_locations", []() -> bool { return (g_carbProfiler && g_carbProfiler->supportsDynamicSourceLocations()); }, py::call_guard<py::gil_scoped_release>()); // This is an extended helper with location, the shorter `begin` method is defined in __init__.py m.def("begin_with_location", [](uint64_t mask, std::string name, std::string functionStr, std::string filepathStr, uint32_t line) { if (g_carbProfiler) { static carb::profiler::StaticStringType sfunction{ g_carbProfiler->registerStaticString("Py::func") }; static carb::profiler::StaticStringType sfilepath{ g_carbProfiler->registerStaticString("Py::code") }; auto function = sfunction, filepath = sfilepath; if (g_carbProfiler->supportsDynamicSourceLocations()) { if (!functionStr.empty()) { function = carb::profiler::StaticStringType(functionStr.c_str()); } if (!filepathStr.empty()) { filepath = carb::profiler::StaticStringType(filepathStr.c_str()); } } uint32_t linenumber = line; g_carbProfiler->beginDynamic(mask, function, filepath, linenumber, "%s", name.c_str()); } }, py::arg("mask"), py::arg("name"), py::arg("function") = "", py::arg("filepath") = "", py::arg("lineno") = 0, py::call_guard<py::gil_scoped_release>()); m.def("end", [](uint64_t mask) { if (g_carbProfiler) { g_carbProfiler->end(mask); } }, py::arg("mask"), py::call_guard<py::gil_scoped_release>()); defineInterfaceClass<IProfiler>(m, "IProfiler", "acquire_profiler_interface") // .def("get_item", wrapInterfaceFunction(&IDictionary::getItem), py::arg("base_item"), py::arg("path") = "", // py::return_value_policy::reference) .def("startup", [](IProfiler* self) { self->startup(); }, py::call_guard<py::gil_scoped_release>()) .def("shutdown", [](IProfiler* self) { self->shutdown(); }, py::call_guard<py::gil_scoped_release>()) .def("set_capture_mask", [](IProfiler* self, uint64_t mask) { return self->setCaptureMask(mask); }, py::arg("mask"), py::call_guard<py::gil_scoped_release>()) .def("get_capture_mask", [](IProfiler* self) { return self->getCaptureMask(); }, py::call_guard<py::gil_scoped_release>()) .def("begin", [](IProfiler* self, uint64_t mask, std::string name) { static auto function = self->registerStaticString("pyfunc"); static auto file = self->registerStaticString("python"); self->beginDynamic(mask, function, file, 1, "%s", name.c_str()); }, py::arg("mask"), py::arg("name"), py::call_guard<py::gil_scoped_release>()) .def("frame", [](IProfiler* self, uint64_t mask, const char* name) { self->frameDynamic(mask, "%s", name); }, py::call_guard<py::gil_scoped_release>()) .def("end", [](IProfiler* self, uint64_t mask) { self->end(mask); }, py::arg("mask"), py::call_guard<py::gil_scoped_release>()) .def("value_float", [](IProfiler* self, uint64_t mask, float value, std::string name) { self->valueFloatDynamic(mask, value, "%s", name.c_str()); }, py::arg("mask"), py::arg("value"), py::arg("name"), py::call_guard<py::gil_scoped_release>()) .def("value_int", [](IProfiler* self, uint64_t mask, int32_t value, std::string name) { self->valueIntDynamic(mask, value, "%s", name.c_str()); }, py::arg("mask"), py::arg("value"), py::arg("name"), py::call_guard<py::gil_scoped_release>()) .def("value_uint", [](IProfiler* self, uint64_t mask, uint32_t value, std::string name) { self->valueUIntDynamic(mask, value, "%s", name.c_str()); }, py::arg("mask"), py::arg("value"), py::arg("name"), py::call_guard<py::gil_scoped_release>()) .def("instant", [](IProfiler* self, uint64_t mask, InstantType type, const char* name) { static auto function = self->registerStaticString("pyfunc"); static auto file = self->registerStaticString("python"); self->emitInstantDynamic(mask, function, file, 1, type, "%s", name); }, py::call_guard<py::gil_scoped_release>()) .def("flow", [](IProfiler* self, uint64_t mask, FlowType type, uint64_t id, const char* name) { static auto function = self->registerStaticString("pyfunc"); static auto file = self->registerStaticString("python"); self->emitFlowDynamic(mask, function, file, 1, type, id, "%s", name); }, py::call_guard<py::gil_scoped_release>()); /**/; py::class_<ScopedProfileEvents>(m, "ProfileEvents", R"(Profile Events holder)") .def("get_main_thread_id", [](const ScopedProfileEvents& events) { return events.mon()->getMainThreadId(events); }, py::call_guard<py::gil_scoped_release>()) .def("get_profile_thread_ids", [](const ScopedProfileEvents& profileEvents) { size_t threadCount; const uint64_t* ids; { py::gil_scoped_release nogil; const IProfileMonitor* monitor = profileEvents.mon(); threadCount = monitor->getProfileThreadCount(profileEvents); ids = monitor->getProfileThreadIds(profileEvents); } py::tuple threadIds(threadCount); for (size_t i = 0; i < threadCount; i++) { threadIds[i] = ids[i]; } return threadIds; }) .def("get_profile_events", [](const ScopedProfileEvents& profileEvents, uint64_t threadId) { size_t eventCount; ProfileEvent* events; uint32_t validEventCount{ 0 }; { py::gil_scoped_release nogil; const IProfileMonitor* monitor = profileEvents.mon(); eventCount = monitor->getLastProfileEventCount(profileEvents); events = monitor->getLastProfileEventsData(profileEvents); if (threadId == 0) { validEventCount = static_cast<uint32_t>(eventCount); } else { for (size_t i = 0; i < eventCount; i++) { if (events[i].threadId == threadId) validEventCount++; } } } py::tuple nodeList(validEventCount); validEventCount = 0; for (size_t i = 0; i < eventCount; i++) { if (threadId != 0 && events[i].threadId != threadId) continue; nodeList[validEventCount++] = py::dict("name"_a = events[i].eventName, "thread_id"_a = events[i].threadId, "start_time"_a = events[i].startTime, "duration"_a = events[i].timeInMs, "indent"_a = events[i].level); } return nodeList; }, py::arg("thread_id") = 0) /**/; defineInterfaceClass<IProfileMonitor>(m, "IProfileMonitor", "acquire_profile_monitor_interface") .def("get_last_profile_events", [](const IProfileMonitor* monitor) { return ScopedProfileEvents(monitor); }, py::call_guard<py::gil_scoped_release>()) .def("mark_frame_end", [](const IProfileMonitor* monitor) { return monitor->markFrameEnd(); }, py::call_guard<py::gil_scoped_release>()) /**/; } } // namespace } // namespace profiler } // namespace carb
10,771
C
42.967347
120
0.545075
omniverse-code/kit/include/carb/profiler/IProfiler.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 carb.profiler interface definition file. #pragma once #include "../Interface.h" #include <atomic> #include <cstdint> namespace carb { //! Namespace for *carb.profiler* and related utilities. namespace profiler { constexpr uint64_t kCaptureMaskNone = 0; ///< Captures no events, effectively disabling the profiler. constexpr uint64_t kCaptureMaskAll = (uint64_t)-1; ///< Captures all events constexpr uint64_t kCaptureMaskDefault = uint64_t(1); ///< If zero is provided to an event function, it becomes this. constexpr uint64_t kCaptureMaskProfiler = uint64_t(1) << 63; ///< The mask used by the profiler for profiling itself. /// A type representing a static string returned by IProfiler::registerStaticString(). using StaticStringType = size_t; /// Returned as an error by IProfiler::registerStaticString() if the string could not be registered. constexpr StaticStringType kInvalidStaticString = StaticStringType(0); /// An opaque ID returned by IProfiler::beginStatic() / IProfiler::beginDynamic() that should be returned in /// IProfiler::endEx() to validate that the zone was closed properly. using ZoneId = size_t; /// A marker that is returned IProfiler::beginStatic() / IProfiler::beginDynamic() on error and can be passed to /// IProfiler::endEx() to prevent zone validation checking. constexpr ZoneId kUnknownZoneId = 0; /// A marker returned by IProfiler::beginStatic() / IProfiler::beginDynamic() to indicate that the zone /// should be discarded, typically because it doesn't match the current capture mask. constexpr ZoneId kNoZoneId = ZoneId(-1); /// The type of flow event passed to IProfiler::emitFlowStatic() / IProfiler::emitFlowDynamic(). Typically used only by /// profiler macros. enum class FlowType : uint8_t { Begin, ///< A flow begin point. End ///< A flow end point. }; /// The type of instant event passed to IProfiler::emitInstantStatic() / IProfiler::emitInstantDynamic(). enum class InstantType : uint8_t { Thread, ///< Draws a vertical line through the entire process. Process ///< Similar to a thread profile zone with zero duration. }; /// ID for a GPU context created with IProfiler::createGpuContext using GpuContextId = uint8_t; /// Special value to indicate that a GPU context ID is invalid. constexpr uint8_t kInvalidGpuContextId = (uint8_t)-1; /// ID for a Lockable context created with IProfiler::createLockable using LockableId = uint32_t; /// Special value to indicate that a LockableId is invalid. constexpr uint32_t kInvalidLockableId = (uint32_t)-1; /// The type of lockable operation event enum class LockableOperationType : uint8_t { BeforeLock, ///< This notes on the timeline immediately before locking a non shared lock AfterLock, ///< This notes on the timeline immediately after locking a non shared lock AfterUnlock, ///< This notes on the timeline immediately after unlocking a non shared lock AfterSuccessfulTryLock, ///< This notes on the timeline immediately after successfully try locking a non shared lock BeforeLockShared, ///< This notes on the timeline immediately before locking a shared lock AfterLockShared, ///< This notes on the timeline immediately after locking a shared lock AfterUnlockShared, ///< This notes on the timeline immediately after unlocking a shared lock AfterSuccessfulTryLockShared, ///< This notes on the timeline immediately after successfully try locking a shared ///< lock }; //! A callback used for \ref IProfiler::setMaskCallback(). Typically handled automatically by //! \ref carb::profiler::registerProfilerForClient(). using MaskCallbackFn = void (*)(uint64_t); /** * Defines the profiler system that is associated with the Framework. * * It is not recommended to use this interface directly, rather use macros provided in Profile.h, such as * @ref CARB_PROFILE_ZONE(). * * Event names are specified as string which can have formatting, which provides string behavior hints, but whether * to use those hints is up to the profiler backend implementation. */ struct IProfiler { CARB_PLUGIN_INTERFACE("carb::profiler::IProfiler", 1, 4) /** * Starts up the profiler for use. */ void(CARB_ABI* startup)(); /** * Shuts down the profiler and cleans up resources. */ void(CARB_ABI* shutdown)(); /** * Set capture mask. Capture mask provides a way to filter out certain profiling events. * Condition (eventMask & captureMask) == eventMask is evaluated, and if true, event * is recorded. The default capture mask is kCaptureMaskAll * * @note Calling from multiple threads is not recommended as threads will overwrite each values. Calls to this * function should be serialized. * * @warning Changing the capture mask after the profiler has been started causes undefined behavior. * * @param mask Capture mask. * @returns the previous Capture mask. */ uint64_t(CARB_ABI* setCaptureMask)(const uint64_t mask); /** * Gets the current capture mask * * @returns The current capture mask */ uint64_t(CARB_ABI* getCaptureMask)(); /** * Starts the profiling event. This event could be a fiber-based event (i.e. could yield and resume on * another thread) if tasking scheduler provides proper `startFiber`/`stopFiber` calls. * * @param mask Event capture mask. * @param function Static string (see @ref registerStaticString()) of the function where the profile zone is located * (usually `__func__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param file Static string (see @ref registerStaticString()) of the filename where the profile zone was started * (usually `__FILE__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param line Line number in the file where the profile zone was started (usually __LINE__). * @param nameFmt The event name format, followed by args. For beginStatic() this must be a \ref StaticStringType * from registerStaticString(). * @returns An opaque ZoneId that should be passed to endEx(). */ ZoneId(CARB_ABI* beginStatic)( const uint64_t mask, StaticStringType function, StaticStringType file, int line, StaticStringType nameFmt); //! @copydoc IProfiler::beginStatic() ZoneId(CARB_ABI* beginDynamic)( const uint64_t mask, StaticStringType function, StaticStringType file, int line, const char* nameFmt, ...) CARB_PRINTF_FUNCTION(5, 6); /** * Stops the profiling event. This event could be a fiber-based event (i.e. could yield and resume on * another thread) if tasking scheduler provides proper `startFiber`/`stopFiber` calls. * * @warning This call is deprecated. Please use endEx() instead. This function will not be removed * but should also not be called in new code. * * @param mask Event capture mask. */ void(CARB_ABI* end)(const uint64_t mask); /** * Inserts a frame marker for the calling thread in the profiling output, for profilers that support frame markers. * * @note The name provided below must be the same for each set of frames, and called each time from the same thread. * For example you might have main thread frames that all are named "frame" and GPU frames that are named "GPU * frame". Some profilers (i.e. profiler-cpu to Tracy conversion) require that the name contain the word "frame." * * @param mask Deprecated and ignored for frame events. * @param nameFmt The frame set name format, followed by args. For frameStatic() this must be a * \ref StaticStringType from registerStaticString(). */ void(CARB_ABI* frameStatic)(const uint64_t mask, StaticStringType nameFmt); /// @copydoc frameStatic void(CARB_ABI* frameDynamic)(const uint64_t mask, const char* nameFmt, ...) CARB_PRINTF_FUNCTION(2, 3); /** * Send floating point value to the profiler. * * @param mask Value capture mask. * @param value Value. * @param valueFmt The value name format, followed by args. For valueFloatStatic() this must be a * \ref StaticStringType * from registerStaticString(). */ void(CARB_ABI* valueFloatStatic)(const uint64_t mask, float value, StaticStringType valueFmt); /// @copydoc valueFloatStatic void(CARB_ABI* valueFloatDynamic)(const uint64_t mask, float value, const char* valueFmt, ...) CARB_PRINTF_FUNCTION(3, 4); /** * Send signed integer value to the profiler. * * @param mask Value capture mask. * @param value Value. * @param valueFmt The value name format, followed by args. For valueIntStatic() this must be a * \ref StaticStringType from registerStaticString(). */ void(CARB_ABI* valueIntStatic)(const uint64_t mask, int32_t value, StaticStringType valueFmt); /// @copydoc valueIntStatic void(CARB_ABI* valueIntDynamic)(const uint64_t mask, int32_t value, const char* valueFmt, ...) CARB_PRINTF_FUNCTION(3, 4); /** * Send unsigned integer value to the profiler. * * @param mask Value capture mask. * @param value Value. * @param valueFmt The value name format, followed by args. For valueUIntStatic() this must be a \ref * StaticStringType from registerStaticString(). */ void(CARB_ABI* valueUIntStatic)(const uint64_t mask, uint32_t value, StaticStringType valueFmt); /// @copydoc valueUIntStatic void(CARB_ABI* valueUIntDynamic)(const uint64_t mask, uint32_t value, const char* valueFmt, ...) CARB_PRINTF_FUNCTION(3, 4); /** * Sets a threads name. * * @param tidOrZero The thread ID to name, or 0 to name the current thread. * @param nameFmt The thread name format, followed by args. For nameThreadStatic() this must be a * \ref StaticStringType from registerStaticString(). */ void(CARB_ABI* nameThreadStatic)(uint64_t tidOrZero, StaticStringType threadName); /// @copydoc nameThreadStatic void(CARB_ABI* nameThreadDynamic)(uint64_t tidOrZero, const char* threadName, ...) CARB_PRINTF_FUNCTION(2, 3); /** * Checks if the profiler supports dynamic source locations. * * Dynamic source locations allow the `file` and `func` parameters to functions such as beginStatic() and * beginDynamic() to be a transient non-literal string on the heap or stack. * * @returns `true` if dynamic source locations are supported; `false` if they are not supported. */ bool(CARB_ABI* supportsDynamicSourceLocations)(); /** * Helper functions to send a arbitrary type to the profiler. * * @tparam T The type of the parameter to send to the profiler. * @param mask Value capture mask. * @param value Value. * @param valueFmt The value name format, followed by args. For valueStatic() this must be a \ref StaticStringType * from registerStaticString(). */ template <typename T> void valueStatic(uint64_t mask, T value, StaticStringType valueFmt); /// @copydoc valueStatic /// @param args Additional arguments that correspond to printf-style format string @p valueFmt. template <typename T, typename... Args> void valueDynamic(uint64_t mask, T value, const char* valueFmt, Args&&... args); /** * Helper function for registering a static string. * * @note The profiler must copy all strings. By registering a static string, you are making a contract with the * profiler that the string at the provided address will never change. This allows the string to be passed by * pointer as an optimization without needing to copy the string. * * @note This function should be called only once per string. The return value should be captured in a variable and * passed to the static function such as beginStatic(), frameStatic(), valueStatic(), etc. * * @param string The static string to register. This must be a string literal or otherwise a string whose address * will never change. * @returns A \ref StaticStringType that represents the registered static string. If the string could not be * registered, kInvalidStaticString is returned. */ StaticStringType(CARB_ABI* registerStaticString)(const char* string); /** * Send memory allocation event to the profiler for custom pools. * * @param mask Value capture mask. * @param ptr Memory address. * @param size Amount of bytes allocated. * @param name Static or formatted string which contains the name of the pool. */ void(CARB_ABI* allocNamedStatic)(const uint64_t mask, const void* ptr, uint64_t size, StaticStringType name); /// @copydoc allocNamedStatic void(CARB_ABI* allocNamedDynamic)(const uint64_t mask, const void* ptr, uint64_t size, const char* nameFmt, ...) CARB_PRINTF_FUNCTION(4, 5); /** * Send memory free event to the profiler for custom pools. * * @param mask Value capture mask. * @param ptr Memory address. * @param name Static or formatted string which contains the name of the pool. */ void(CARB_ABI* freeNamedStatic)(const uint64_t mask, const void* ptr, StaticStringType valueFmt); /// @copydoc freeNamedStatic void(CARB_ABI* freeNamedDynamic)(const uint64_t mask, const void* ptr, const char* nameFmt, ...) CARB_PRINTF_FUNCTION(3, 4); /** * Send memory allocation event to the profiler on the default pool. * * @param mask Value capture mask. * @param ptr Memory address. * @param size Amount of bytes allocated. */ void(CARB_ABI* allocStatic)(const uint64_t mask, const void* ptr, uint64_t size); /** * Send memory free event to the profiler on the default pool. * * @param mask Value capture mask. * @param ptr Memory address. */ void(CARB_ABI* freeStatic)(const uint64_t mask, const void* ptr); /** * Stops the profiling event that was initiated by beginStatic() or beginDynamic(). * * @param mask Event capture mask. * @param zoneId The ZoneId returned from beginStatic() or beginDynamic(). */ void(CARB_ABI* endEx)(const uint64_t mask, ZoneId zoneId); /** * Records an instant event on a thread's timeline at the current time. Generally not used directly; instead use the * @ref CARB_PROFILE_EVENT() macro. * * @param mask Event capture mask. * @param function Static string (see @ref registerStaticString()) of the name of the function containing this event * (typically `__func__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param file Static string (see @ref registerStaticString()) of the name of the source file containing this event * (typically `__FILE__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param line The line number in @p file containing this event (typically `__LINE__`). * @param type The type of instant event. * @param nameFmt The name for the event. */ void(CARB_ABI* emitInstantStatic)(const uint64_t mask, StaticStringType function, StaticStringType file, int line, InstantType type, StaticStringType nameFmt); /// @copydoc emitInstantStatic /// @note This function is slower than using emitInstanceStatic(). /// @param ... `printf`-style varargs for @p nameFmt. void(CARB_ABI* emitInstantDynamic)(const uint64_t mask, StaticStringType function, StaticStringType file, int line, InstantType type, const char* nameFmt, ...) CARB_PRINTF_FUNCTION(6, 7); /** * Puts a flow event on the timeline at the current line. Generally not used directly; instead use the * @ref CARB_PROFILE_FLOW_BEGIN() and @ref CARB_PROFILE_FLOW_END() macros. * * Flow events draw an arrow from one point (the @ref FlowType::Begin location) to another point (the @ref * FlowType::End location). These two points can be in different threads but must have a matching @p id field. Only * the @ref FlowType::Begin event must specify a @p name. The @p id field is meant to be unique across profiler * runs, but may be reused as long as the @p name field matches across all @ref FlowType::Begin events and events * occur on the global timeline as @ref FlowType::Begin followed by @ref FlowType::End. * * A call with @ref FlowType::Begin will automatically insert an instant event on the current thread's timeline. * * @param mask Event capture mask. * @param function Static string (see @ref registerStaticString()) of the name of the function containing this * event. If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref StaticStringType. * @param file Static string (see @ref registerStaticString()) of the name of the source file containing this event * (typically `__FILE__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param line The line number in @p file containing this event (typically `__LINE__`). * @param type The type of flow marker. * @param id A unique identifier to tie `Begin` and `End` events together. * @param name The name for the flow event. Only required for @ref FlowType::Begin; if specified for * @ref FlowType::End it must match exactly or be `nullptr`. */ void(CARB_ABI* emitFlowStatic)(const uint64_t mask, StaticStringType function, StaticStringType file, int line, FlowType type, uint64_t id, StaticStringType name); /// @copydoc emitFlowStatic /// @note This function is slower than using emitFlowStatic(). /// @param ... `printf`-style varargs for @p nameFmt. void(CARB_ABI* emitFlowDynamic)(const uint64_t mask, StaticStringType function, StaticStringType file, int line, FlowType type, uint64_t id, const char* name, ...) CARB_PRINTF_FUNCTION(7, 8); /** * Create a new GPU profiling context that allows injecting timestamps coming from a GPU in a deferred manner * * @param name name of the context * @param correlatedCpuTimestampNs correlated GPU clock timestamp (in nanoseconds) * @param correlatedGpuTimestamp correlated GPU clock timestamp (raw value) * @param gpuTimestampPeriodNs is the number of nanoseconds required for a GPU timestamp query to be incremented * by 1. * @param graphicApi string of graphic API used ['vulkan'/'d3d12'] * @returns a valid ID or kInvalidGpuContextId if creation fails */ GpuContextId(CARB_ABI* createGpuContext)(const char* name, int64_t correlatedCpuTimestampNs, int64_t correlatedGpuTimestamp, float gpuTimestampPeriodNs, const char* graphicApi); /** * Destroy a previously created GPU Context * * @param contextId id of the context, returned by createGpuContext */ void(CARB_ABI* destroyGpuContext)(GpuContextId contextId); /** * Submit context calibration information that allows correlating CPU and GPU clocks * * @param contextId id of the context, returned by createGpuContext * @param correlatedCpuTimestampNs the new CPU timestamp at the time of correlation (in nanoseconds) * @param previousCorrelatedCpuTimestamp the CPU timestamp at the time of previous correlation (in nanoseconds) * @param correlatedGpuTimestamp the new raw GPU timestamp at the time of correlation */ bool(CARB_ABI* calibrateGpuContext)(GpuContextId contextId, int64_t correlatedCpuTimestampNs, int64_t previousCorrelatedCpuTimestampNs, int64_t correlatedGpuTimestamp); /** * Record the beginning of a new GPU timestamp query * * @param mask Event capture mask. * @param function Static string (see @ref registerStaticString()) of the name of the function containing this event * (typically `__func__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param file Static string (see @ref registerStaticString()) of the name of the source file containing this event * (typically `__FILE__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param line The line number in @p file containing this event (typically `__LINE__`). * @param contextId the id of the context as returned by @ref createGpuContext * @param queryId unique query id (for identification when passing to setGpuQueryValue) * @param name The name for the event. */ void(CARB_ABI* beginGpuQueryStatic)(const uint64_t mask, StaticStringType functionName, StaticStringType fileName, int line, GpuContextId contextId, uint32_t queryId, StaticStringType name); //! @copydoc IProfiler::beginGpuQueryStatic() void(CARB_ABI* beginGpuQueryDynamic)(const uint64_t mask, StaticStringType functionName, StaticStringType fileName, int line, GpuContextId contextId, uint32_t queryId, const char* nameFmt, ...) CARB_PRINTF_FUNCTION(7, 8); /** * Record the end of a new GPU timestamp query * * @param mask Event capture mask. * @param contextId the id of the context as returned by @ref createGpuContext * @param queryId unique query id (for identification when passing to setGpuQueryValue) */ void(CARB_ABI* endGpuQuery)(const uint64_t mask, GpuContextId contextId, uint32_t queryId); /** * Set the value we've received from the GPU for a query (begin or end) we've issued in the past * * @param contextId the id of the context as returned by @ref createGpuContext * @param queryId unique query id specified at begin/end time * @param gpuTimestamp raw GPU timestamp value */ void(CARB_ABI* setGpuQueryValue)(const uint64_t mask, GpuContextId contextId, uint32_t queryId, int64_t gpuTimestamp); /** * Create a lockable context which we can use to tag lock operation * * @param mask Event capture mask. If the mask does not match the current capture mask, the lockable is not created * and \ref kInvalidLockableId is returned. * @param name context name * @param isSharedLock if this shared for a shared lock * @param functionName Static string (see @ref registerStaticString()) of the name of the function containing this * event (typically `__func__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param fileName Static string (see @ref registerStaticString()) of the name of the source file containing this * event (typically `__FILE__`). If supportsDynamicSourceLocations(), this may be a `const char*` cast to @ref * StaticStringType. * @param line The line number in @p file containing this event (typically `__LINE__`). */ LockableId(CARB_ABI* createLockable)(const uint64_t mask, const char* name, const bool isSharedLock, StaticStringType functionName, StaticStringType fileName, int line); /** * Destroy a lockable context * * @param lockableId the id of the lockable as returned by @ref createLockable */ void(CARB_ABI* destroyLockable)(LockableId lockableId); /** * Record a lockable operation * * @param lockableId the id of the lockable as returned by @ref createLockable * @param operation which lock operation to tag */ void(CARB_ABI* lockableOperation)(LockableId lockableId, LockableOperationType operation); /** * Used by \ref carb::profiler::registerProfilerForClient() and \ref carb::profiler::deregisterProfilerForClient() * to register a callback for keeping the profiler mask up to date. * * @param func The callback function to register. * @param enabled \c true to register the callback, \c false to unregister the callback. * @returns The current profiler mask. */ uint64_t(CARB_ABI* setMaskCallback)(MaskCallbackFn func, bool enabled); }; #ifndef DOXYGEN_BUILD namespace detail { template <typename T> class ValueInvoker; template <> class ValueInvoker<float> { public: static void invokeStatic(IProfiler& profiler, uint64_t mask, float value, StaticStringType valueFmt) { profiler.valueFloatStatic(mask, value, valueFmt); } template <typename... Args> static void invokeDynamic(IProfiler& profiler, uint64_t mask, float value, const char* valueFmt, Args&&... args) { profiler.valueFloatDynamic(mask, value, valueFmt, std::forward<Args>(args)...); } }; template <> class ValueInvoker<int32_t> { public: static void invokeStatic(IProfiler& profiler, uint64_t mask, int32_t value, StaticStringType valueFmt) { profiler.valueIntStatic(mask, value, valueFmt); } template <typename... Args> static void invokeDynamic(IProfiler& profiler, uint64_t mask, int32_t value, const char* valueFmt, Args&&... args) { profiler.valueIntDynamic(mask, value, valueFmt, std::forward<Args>(args)...); } }; template <> class ValueInvoker<uint32_t> { public: static void invokeStatic(IProfiler& profiler, uint64_t mask, uint32_t value, StaticStringType valueFmt) { profiler.valueUIntStatic(mask, value, valueFmt); } template <typename... Args> static void invokeDynamic(IProfiler& profiler, uint64_t mask, uint32_t value, const char* valueFmt, Args&&... args) { profiler.valueUIntDynamic(mask, value, valueFmt, std::forward<Args>(args)...); } }; } // namespace detail #endif template <typename T> inline void IProfiler::valueStatic(uint64_t mask, T value, StaticStringType valueFmt) { using ValueInvoker = typename detail::ValueInvoker<T>; ValueInvoker::invokeStatic(*this, mask, value, valueFmt); } template <typename T, typename... Args> inline void IProfiler::valueDynamic(uint64_t mask, T value, const char* valueFmt, Args&&... args) { using ValueInvoker = typename detail::ValueInvoker<T>; ValueInvoker::invokeDynamic(*this, mask, value, valueFmt, std::forward<Args>(args)...); } } // namespace profiler } // namespace carb /** * Global pointer used to store the @ref carb::profiler::IProfiler interface. * * A copy of this pointer is stored in each Carbonite client (i.e. plugin/app). For applications, this pointer is * declared by @ref OMNI_APP_GLOBALS. For plugins, this pointer is declared by @ref CARB_PROFILER_GLOBALS via @ref * OMNI_MODULE_GLOBALS. * * This pointer is an implementation detail transparent to users. However, a linker error pointing to this variable * usually indicates one of the `_GLOBALS` macros mentioned above were not called. */ CARB_WEAKLINK carb::profiler::IProfiler* g_carbProfiler; /** * A global variable used as a cache for the result of \ref carb::profiler::IProfiler::getCaptureMask(). * * \ref carb::profiler::registerProfilerForClient() will register a callback function with the profiler (if supported) * that will keep this variable updated. This variable can be checked inline before calling into the IProfiler * interface. */ CARB_WEAKLINK std::atomic_uint64_t g_carbProfilerMask;
29,711
C
45.643642
122
0.661136
omniverse-code/kit/include/carb/profiler/ProfilerUtils.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 carb.profiler helper utilities. #pragma once #include "IProfiler.h" #include "../cpp/Atomic.h" #include "../settings/ISettings.h" #include "../InterfaceUtils.h" namespace carb { namespace profiler { //! \cond DEV namespace detail { struct String2 { carb::profiler::StaticStringType first; carb::profiler::StaticStringType second; constexpr String2(StaticStringType first, StaticStringType second) noexcept : first(first), second(second) { } }; constexpr String2 makeString2(StaticStringType first, StaticStringType second) noexcept { return String2{ first, second }; } struct String3 { carb::profiler::StaticStringType first; carb::profiler::StaticStringType second; carb::profiler::StaticStringType third; constexpr String3(StaticStringType first, StaticStringType second, StaticStringType third) noexcept : first(first), second(second), third(third) { } }; constexpr String3 makeString3(StaticStringType first, StaticStringType second, StaticStringType third) noexcept { return String3{ first, second, third }; } } // namespace detail //! \endcond /** * Profiler channel which can be configured via \ref carb::settings::ISettings. * * @warning Do not use this class directly. Instead, use \ref CARB_PROFILE_DECLARE_CHANNEL(). */ class Channel final { uint64_t m_mask; bool m_enabled; const char* m_name; Channel* m_next; struct ModuleData { Channel* head{ nullptr }; LoadHookHandle onSettingsLoadHandle{ kInvalidLoadHook }; dictionary::SubscriptionId* changeSubscription{ nullptr }; #if CARB_ASSERT_ENABLED ~ModuleData() { // If these weren't unregistered we could crash later CARB_ASSERT(onSettingsLoadHandle == kInvalidLoadHook); CARB_ASSERT(changeSubscription == nullptr); } #endif }; static ModuleData& moduleData() { static ModuleData s_moduleData; return s_moduleData; } static void onSettingsLoad(const PluginDesc&, void*) { // DO NOT USE getCachedInterface here! This is called by a load hook, which can be triggered by // getCachedInterface in this module. This means if we were to recursively call getCachedInterface() here, we // could hang indefinitely as this thread is the thread responsible for loading the cached interface. if (loadSettings(getFramework()->tryAcquireInterface<settings::ISettings>(), true)) { g_carbFramework->removeLoadHook(moduleData().onSettingsLoadHandle); moduleData().onSettingsLoadHandle = kInvalidLoadHook; } } static void onSettingsUnload(void*, void*) { // Settings was unloaded. Make sure we no longer have a subscription callback. moduleData().changeSubscription = nullptr; } static void onSettingsChange(const dictionary::Item*, const dictionary::Item* changedItem, dictionary::ChangeEventType eventType, void*) { if (eventType == dictionary::ChangeEventType::eDestroyed) return; auto dict = getCachedInterface<dictionary::IDictionary>(); // Only care about elements that can change at runtime. const char* name = dict->getItemName(changedItem); if (strcmp(name, "enabled") != 0 && strcmp(name, "mask") != 0) return; loadSettings( getCachedInterface<settings::ISettings>(), false, dict->getItemName(dict->getItemParent(changedItem))); } static bool loadSettings(settings::ISettings* settings, bool initial, const char* channelName = nullptr) { // Only proceed if settings is already initialized if (!settings) return false; auto dict = carb::getCachedInterface<dictionary::IDictionary>(); if (!dict) return false; auto root = settings->getSettingsDictionary("/profiler/channels"); if (root) { for (Channel* c = moduleData().head; c; c = c->m_next) { if (channelName && strcmp(c->m_name, channelName) != 0) continue; auto channelRoot = dict->getItem(root, c->m_name); if (!channelRoot) continue; auto enabled = dict->getItem(channelRoot, "enabled"); if (enabled) { c->setEnabled(dict->getAsBool(enabled)); } auto mask = dict->getItem(channelRoot, "mask"); if (mask) { c->setMask(uint64_t(dict->getAsInt64(mask))); } } } // Register a change subscription on initial setup if we have any channels. if (initial && !moduleData().changeSubscription && moduleData().head) { moduleData().changeSubscription = settings->subscribeToTreeChangeEvents("/profiler/channels", onSettingsChange, nullptr); ::g_carbFramework->addReleaseHook(settings, onSettingsUnload, nullptr); } return true; } public: /** * Constructor * * @warning Do not call this directly. Instead use \ref CARB_PROFILE_DECLARE_CHANNEL(). * * @warning Instances of this class must have static storage and module-lifetime, therefore they may only exist at * file-level scope, class-level (static) scope, or namespace-level scope only. Anything else is undefined behavior. * * @param mask The default profiler mask for this channel. * @param enabled Whether this channel is enabled by default. * @param name A literal string that is used to look up settings keys. */ Channel(uint64_t mask, bool enabled, const char* name) : m_mask(mask), m_enabled(enabled), m_name(name) { // Add ourselves to the list of channels for this module auto& head = moduleData().head; m_next = head; head = this; } /** * Returns the name of this channel. * @returns the channel name. */ const char* getName() const noexcept { return m_name; } /** * Returns the current mask for this channel. * @returns the current mask. */ uint64_t getMask() const noexcept { return m_mask; } /** * Sets the mask value for *this. * @param mask The new profiler mask value. */ void setMask(uint64_t mask) noexcept { cpp::atomic_ref<uint64_t>(m_mask).store(mask, std::memory_order_release); } /** * Returns whether this channel is enabled. * @returns \c true if this channel is enabled; \c false otherwise. */ bool isEnabled() const noexcept { return m_enabled; } /** * Sets *this to enabled or disabled. * * @param enabled Whether to enable (\c true) or disable (\c false) the channel. */ void setEnabled(bool enabled) noexcept { cpp::atomic_ref<bool>(m_enabled).store(enabled, std::memory_order_release); } /** * Called by profiler::registerProfilerForClient() to initialize all channels. * * If ISettings is available, it is queried for this module's channel's settings, and a subscription is installed to * be notified when settings change. If ISettings is not available, a load hook is installed with the framework in * order to be notified if and when ISettings becomes available. */ static void onProfilerRegistered() { // example-begin acquire-without-init // Don't try to load settings, but if it's already available we will load settings from it. auto settings = g_carbFramework->tryAcquireExistingInterface<settings::ISettings>(); // example-end acquire-without-init if (!loadSettings(settings, true)) { // If settings isn't available, wait for it to load. moduleData().onSettingsLoadHandle = g_carbFramework->addLoadHook<settings::ISettings>(nullptr, onSettingsLoad, nullptr); } } /** * Called by profiler::deregisterProfilerForClient() to uninitialize all channels. * * Any load hooks and subscriptions installed with ISettings are removed. */ static void onProfilerUnregistered() { if (moduleData().onSettingsLoadHandle != kInvalidLoadHook) { g_carbFramework->removeLoadHook(moduleData().onSettingsLoadHandle); moduleData().onSettingsLoadHandle = kInvalidLoadHook; } if (moduleData().changeSubscription) { // Don't re-initialize settings if it's already been unloaded (though in this case we should've gotten a // callback) auto settings = g_carbFramework->tryAcquireExistingInterface<settings::ISettings>(); CARB_ASSERT(settings); if (settings) { settings->unsubscribeToChangeEvents(moduleData().changeSubscription); g_carbFramework->removeReleaseHook(settings, onSettingsUnload, nullptr); } moduleData().changeSubscription = nullptr; } } }; /** * Helper class that allows to automatically stop profiling upon leaving block. * @note Typically this is not used by an application. It is generated automatically by the CARB_PROFILE_ZONE() macro. */ class ProfileZoneStatic final { const uint64_t m_mask; ZoneId m_zoneId; public: /** * Constructor. * * @param mask Profiling bitmask. * @param tup A `String3` of registered static strings for `__func__`, `__FILE__` and event name. * @param line Line number in the file where the profile zone was started (usually `__LINE__`). */ ProfileZoneStatic(const uint64_t mask, const ::carb::profiler::detail::String3& tup, int line) : m_mask(mask) { if (g_carbProfiler && ((mask ? mask : kCaptureMaskDefault) & g_carbProfilerMask.load(std::memory_order_acquire))) m_zoneId = g_carbProfiler->beginStatic(m_mask, tup.first, tup.second, line, tup.third); else m_zoneId = kNoZoneId; } /** * Constructor. * * @param channel A profiling channel. * @param tup A `String3` of registered static strings for `__func__`, `__FILE__` and event name. * @param line Line number in the file where the profile zone was started (usually `__LINE__`). */ ProfileZoneStatic(const Channel& channel, const ::carb::profiler::detail::String3& tup, int line) : m_mask(channel.getMask()) { if (g_carbProfiler && channel.isEnabled()) m_zoneId = g_carbProfiler->beginStatic(m_mask, tup.first, tup.second, line, tup.third); else m_zoneId = kNoZoneId; } /** * Destructor. */ ~ProfileZoneStatic() { if (g_carbProfiler && m_zoneId != kNoZoneId) g_carbProfiler->endEx(m_mask, m_zoneId); } }; //! @copydoc ProfileZoneStatic class ProfileZoneDynamic final { const uint64_t m_mask; ZoneId m_zoneId; public: /** * Constructor. * * @param mask Profiling bitmask. * @param tup A `String2` of registered static strings for `__func__` and `__FILE__`. * @param line Line number in the file where the profile zone was started (usually `__LINE__`). * @param nameFmt Profile zone name with printf-style formatting followed by arguments * @param args Printf-style arguments used with @p nameFmt. */ template <typename... Args> ProfileZoneDynamic( const uint64_t mask, const ::carb::profiler::detail::String2& tup, int line, const char* nameFmt, Args&&... args) : m_mask(mask) { if (g_carbProfiler && ((mask ? mask : kCaptureMaskDefault) & g_carbProfilerMask.load(std::memory_order_acquire))) m_zoneId = g_carbProfiler->beginDynamic(m_mask, tup.first, tup.second, line, nameFmt, std::forward<Args>(args)...); else m_zoneId = kNoZoneId; } /** * Constructor. * * @param channel A profiling channel. * @param tup A `String2` of registered static strings for `__func__` and `__FILE__`. * @param line Line number in the file where the profile zone was started (usually `__LINE__`). * @param nameFmt Profile zone name with printf-style formatting followed by arguments * @param args Printf-style arguments used with @p nameFmt. */ template <typename... Args> ProfileZoneDynamic(const Channel& channel, const ::carb::profiler::detail::String2& tup, int line, const char* nameFmt, Args&&... args) : m_mask(channel.getMask()) { if (g_carbProfiler && channel.isEnabled()) m_zoneId = g_carbProfiler->beginDynamic(m_mask, tup.first, tup.second, line, nameFmt, std::forward<Args>(args)...); else m_zoneId = kNoZoneId; } /** * Destructor. */ ~ProfileZoneDynamic() { if (g_carbProfiler && m_zoneId != kNoZoneId) g_carbProfiler->endEx(m_mask, m_zoneId); } }; } // namespace profiler } // namespace carb
13,862
C
32.648058
121
0.622421
omniverse-code/kit/include/carb/profiler/Profile.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 carb.profiler macros and helpers #pragma once #include "../Defines.h" #include "../Framework.h" #include "../cpp/Atomic.h" #include "IProfiler.h" #include <cstdarg> #include <cstdio> #include "ProfilerUtils.h" /** * Declares a channel that can be used with the profiler. * * Channels can be used in place of a mask for macros such as \ref CARB_PROFILE_ZONE. Channels allow enabling and * disabling at runtime, or based on a settings configuration. * * Channels must have static storage and module lifetime, therefore this macro should be used at file-level, class-level * or namespace-level scope only. Any other use is undefined behavior. * * Channels must be declared in exactly one compilation unit for a given module. References to the channel can be * accomplished with \ref CARB_PROFILE_EXTERN_CHANNEL for other compilation units that desire to reference the channel. * * Channel settings are located under `/profiler/channels/<name>` and may have the following values: * - `enabled` - (bool) whether this channel is enabled (reports to the profiler) or not * - `mask` - (uint64_t) the mask used with the profiler * * @param name_ A string name for this channel. This is used to look up settings keys for this channel. * @param defaultMask_ The profiler works with the concept of masks. The profiler must have the capture mask enabled for * this channel to report to the profiler. A typical value for this could be * \ref carb::profiler::kCaptureMaskDefault. * @param defaultEnabled_ Whether this channel is enabled to report to the profiler by default. * @param symbol_ The symbol name that code would refer to this channel by. */ #define CARB_PROFILE_DECLARE_CHANNEL(name_, defaultMask_, defaultEnabled_, symbol_) \ ::carb::profiler::Channel symbol_((defaultMask_), (defaultEnabled_), "" name_) /** * References a channel declared in another compilation unit. * * @param symbol_ The symbol name given to the \ref CARB_PROFILE_DECLARE_CHANNEL */ #define CARB_PROFILE_EXTERN_CHANNEL(symbol_) extern ::carb::profiler::Channel symbol_ #if CARB_PROFILING || defined(DOXYGEN_BUILD) /** * @defgroup Profiler Helper Macros * * All of the following macros do nothing if @ref g_carbProfiler is `nullptr` (i.e. * carb::profiler::registerProfilerForClient() has not been called). * @{ */ # ifndef DOXYGEN_BUILD // The following are helper macros for the profiler. # define CARB_PROFILE_IF(cond, true_case, false_case) CARB_PROFILE_IF_HELPER(cond, true_case, false_case) // Note: CARB_PROFILE_HAS_VARARGS only supports up to 10 args now. If more are desired, increase the sequences below // and add test cases to TestProfiler.cpp // This trick is from https://stackoverflow.com/a/36015150/1450686 # if CARB_COMPILER_MSC # define CARB_PROFILE_HAS_VARARGS(x, ...) CARB_PROFILE_EXPAND_ARGS(CARB_PROFILE_AUGMENT_ARGS(__VA_ARGS__)) # elif CARB_COMPILER_GNUC # define CARB_PROFILE_HAS_VARARGS(...) \ CARB_PROFILE_ARGCHK_PRIVATE2(0, ##__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0) # else # error Unsupported Compiler! # endif // The following are implementation helpers not intended to be used # define CARB_PROFILE_IF_HELPER(cond, true_case, false_case) \ CARB_JOIN(CARB_PROFILE_IF_HELPER_, cond)(true_case, false_case) # define CARB_PROFILE_IF_HELPER_0(true_case, false_case) false_case # define CARB_PROFILE_IF_HELPER_1(true_case, false_case) true_case # define CARB_PROFILE_AUGMENT_ARGS(...) unused, __VA_ARGS__ # define CARB_PROFILE_EXPAND_ARGS(...) \ CARB_PROFILE_EXPAND(CARB_PROFILE_ARGCHK_PRIVATE(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)) # define CARB_PROFILE_EXPAND(x) x # define CARB_PROFILE_ARGCHK_PRIVATE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, count, ...) count # define CARB_PROFILE_ARGCHK_PRIVATE2(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, count, ...) count # define CARB_PROFILE_UFUNCFILE(func) \ [](const char* pfunc) -> const auto& \ { \ static auto tup = ::carb::profiler::detail::makeString2( \ ::g_carbProfiler->registerStaticString(pfunc), ::g_carbProfiler->registerStaticString(__FILE__)); \ return tup; \ } \ (func) # define CARB_PROFILE_UFUNCFILESTR(func, str) \ [](const char* pfunc, const char* pstr) -> const auto& \ { \ static auto tup = ::carb::profiler::detail::makeString3( \ ::g_carbProfiler->registerStaticString(pfunc), ::g_carbProfiler->registerStaticString(__FILE__), \ ::g_carbProfiler->registerStaticString(pstr)); \ return tup; \ } \ (func, str) # define CARB_PROFILE_FUNCFILE(func) \ [](const char* pfunc) -> const auto& \ { \ if (::g_carbProfiler) \ { \ static auto tup = \ ::carb::profiler::detail::makeString2(::g_carbProfiler->registerStaticString(pfunc), \ ::g_carbProfiler->registerStaticString(__FILE__)); \ return tup; \ } \ return ::carb::profiler::detail::emptyTuple2(); \ } \ (func) # define CARB_PROFILE_FUNCFILESTR(func, str) \ [](const char* pfunc, const char* pstr) -> const auto& \ { \ if (::g_carbProfiler) \ { \ static auto tup = \ ::carb::profiler::detail::makeString3(::g_carbProfiler->registerStaticString(pfunc), \ ::g_carbProfiler->registerStaticString(__FILE__), \ ::g_carbProfiler->registerStaticString(pstr)); \ return tup; \ } \ return ::carb::profiler::detail::emptyTuple3(); \ } \ (func, str) # define CARB_PROFILE_CHECKMASK(mask) \ (((mask) ? (mask) : carb::profiler::kCaptureMaskDefault) & \ g_carbProfilerMask.load(std::memory_order_acquire)) namespace carb { namespace profiler { namespace detail { // Helper functions for begin that take the tuples created by CARB_PROFILE_UFUNCFILE and CARB_PROFILE_UFUNCFILESTR template <class... Args> carb::profiler::ZoneId beginDynamicHelper( const uint64_t mask, const ::carb::profiler::detail::String2& tup, int line, const char* fmt, Args&&... args) { if (!CARB_PROFILE_CHECKMASK(mask)) return kNoZoneId; return ::g_carbProfiler->beginDynamic(mask, tup.first, tup.second, line, fmt, std::forward<Args>(args)...); } template <class... Args> carb::profiler::ZoneId beginDynamicHelper(const carb::profiler::Channel& channel, const ::carb::profiler::detail::String2& tup, int line, const char* fmt, Args&&... args) { if (!channel.isEnabled()) return kNoZoneId; return ::g_carbProfiler->beginDynamic( channel.getMask(), tup.first, tup.second, line, fmt, std::forward<Args>(args)...); } inline carb::profiler::ZoneId beginStaticHelper(const uint64_t mask, const ::carb::profiler::detail::String3& tup, int line) { if (!CARB_PROFILE_CHECKMASK(mask)) return kNoZoneId; return ::g_carbProfiler->beginStatic(mask, tup.first, tup.second, line, tup.third); } inline carb::profiler::ZoneId beginStaticHelper(const carb::profiler::Channel& channel, const ::carb::profiler::detail::String3& tup, int line) { if (!channel.isEnabled()) return kNoZoneId; return ::g_carbProfiler->beginStatic(channel.getMask(), tup.first, tup.second, line, tup.third); } inline uint64_t maskHelper(uint64_t mask) { return mask; } inline uint64_t maskHelper(const carb::profiler::Channel& channel) { return channel.getMask(); } inline bool enabled(uint64_t mask) { return CARB_PROFILE_CHECKMASK(mask); } inline bool enabled(const carb::profiler::Channel& channel) { return channel.isEnabled(); } inline const ::carb::profiler::detail::String2& emptyTuple2() { static constexpr auto tup = ::carb::profiler::detail::makeString2(kInvalidStaticString, kInvalidStaticString); return tup; } inline const ::carb::profiler::detail::String3& emptyTuple3() { static constexpr auto tup = ::carb::profiler::detail::makeString3(kInvalidStaticString, kInvalidStaticString, kInvalidStaticString); return tup; } } // namespace detail } // namespace profiler } // namespace carb # endif /** * Starts the profiler that has been registered with carb::profiler::registerProfilerForClient(). * * When finished with the profiler it should be stopped with CARB_PROFILE_SHUTDOWN(). * * @note This is typically done immediately after carb::profiler::registerProfilerForClient(). */ # define CARB_PROFILE_STARTUP() \ do \ { \ if (::g_carbProfiler) \ { \ ::g_carbProfiler->startup(); \ } \ } while (0) /** * Shuts down the profiler that has been registered with carb::profiler::registerProfilerForClient() and previously * started with CARB_PROFILE_STARTUP(). * * @note This is typically done immediately before carb::profiler::deregisterProfilerForClient(). */ # define CARB_PROFILE_SHUTDOWN() \ do \ { \ if (::g_carbProfiler) \ { \ ::g_carbProfiler->shutdown(); \ } \ } while (0) /** * Registers a static string for use with the profiler. * * The profiler works by capturing events very quickly in the thread of execution that they happen in, and then * processing them later in a background thread. Since static/literal strings are contained in memory that may be * invalid once the module unloads, these static/literal strings are registered and copied by the profiler and this * macro returns a handle to the string that can be passed to the "static" function such as * @ref carb::profiler::IProfiler::beginStatic(). * * @note This macro is used by other helper macros and is typically not used by applications. * * @warning Undefined behavior occurs if the given string is not a literal or static string. * * @returns A handle to the static string registered with the profiler. There is no need to unregister this string. */ # define CARB_PROFILE_REGISTER_STRING(str) \ [](const char* pstr) { \ if (::g_carbProfiler) \ { \ static ::carb::profiler::StaticStringType p = ::g_carbProfiler->registerStaticString(pstr); \ return p; \ } \ return ::carb::profiler::kInvalidStaticString; \ }(str) /** * A helper to set the capture mask. * * The capture mask is a set of 64 bits. Each profiling zone is *bitwise-and*'d with the capture mask. If the operation * matches the profiling zone mask then the event is included in the profiling output. Otherwise, the event is ignored. * * The default capture mask is profiler-specific, but typically has all bits set (i.e. includes everything). * @see carb::profiler::IProfiler::setCaptureMask() * * @warning Changing the capture mask after the profiler has been started causes undefined behavior. */ # define CARB_PROFILE_SET_CAPTURE_MASK(mask) \ do \ { \ if (::g_carbProfiler) \ { \ ::g_carbProfiler->setCaptureMask(mask); \ } \ } while (0) /** * Marks the beginning of a profiling zone. * * To end the profiling zone, use CARB_PROFILE_END(). * * @warning Consider using CARB_PROFILE_ZONE() to automatically profile a scope. Manual begin and end sections can cause * programming errors and confuse the profiler if an end is skipped. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a channel symbol name. * @param eventName The name of the profiling zone. This must be either a literal string or a printf-style format * string. Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p eventName. * @returns A carb::profiler::ZoneId that is unique to this zone and should be passed to CARB_PROFILE_END(). */ # define CARB_PROFILE_BEGIN(maskOrChannel, eventName, ...) \ ::g_carbProfiler ? \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(eventName, ##__VA_ARGS__), \ ::carb::profiler::detail::beginDynamicHelper( \ maskOrChannel, CARB_PROFILE_UFUNCFILE(__func__), __LINE__, eventName, ##__VA_ARGS__), \ ::carb::profiler::detail::beginStaticHelper( \ maskOrChannel, CARB_PROFILE_UFUNCFILESTR(__func__, eventName), __LINE__)) : \ (0 ? /*compiler validate*/ printf(eventName, ##__VA_ARGS__) : 0) /** * Marks the end of a profiling zone previously started with CARB_PROFILE_BEGIN(). * * @warning Consider using CARB_PROFILE_ZONE() to automatically profile a scope. Manual begin and end sections can cause * programming errors and confuse the profiler if an end is skipped. * * @param maskOrChannel The event mask or a channel symbol. This should match the value passed to CARB_PROFILE_BEGIN(). * @param ... The carb::profiler::ZoneId returned from CARB_PROFILE_BEGIN(), if known. This will help the profiler to * validate that the proper zone was ended. */ # define CARB_PROFILE_END(maskOrChannel, ...) \ do \ { \ if (::g_carbProfiler) \ { \ ::g_carbProfiler->CARB_PROFILE_IF( \ CARB_PROFILE_HAS_VARARGS(maskOrChannel, ##__VA_ARGS__), \ endEx(::carb::profiler::detail::maskHelper(maskOrChannel), ##__VA_ARGS__), \ end(::carb::profiler::detail::maskHelper(maskOrChannel))); \ } \ } while (0) /** * Inserts a frame marker for the calling thread in the profiling output, for profilers that support frame markers. * * @note The name provided below must be the same for each set of frames, and called each time from the same thread. * For example you might have main thread frames that all are named "frame" and GPU frames that are named "GPU * frame". Some profilers (i.e. profiler-cpu to Tracy conversion) require that the name contain the word "frame." * * @param mask Deprecated and ignored for frame events. * @param frameName A name for the frame. This must either be a literal string or a printf-style format string. Literal * strings are far more efficient. See the note above about frame names. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p frameName. */ # define CARB_PROFILE_FRAME(mask, frameName, ...) \ do \ { \ /* Use printf to validate the format string */ \ if (0) \ { \ printf(frameName, ##__VA_ARGS__); \ } \ if (::g_carbProfiler) \ { \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(frameName, ##__VA_ARGS__), \ ::g_carbProfiler->frameDynamic(mask, frameName, ##__VA_ARGS__), \ ::g_carbProfiler->frameStatic(mask, []() { \ static ::carb::profiler::StaticStringType p = \ ::g_carbProfiler->registerStaticString("" frameName); \ return p; \ }())); \ } \ } while (0) /** * Creates a profiling zone over a scope. * * This macro creates a temporary object on the stack that automatically begins a profiling zone at the point where this * macro is used, and automatically ends the profiling zone when it goes out of scope. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a channel symbol. * @param zoneName The name of the profiling zone. This must be either a literal string or a printf-style format string. * Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p zoneName. */ # define CARB_PROFILE_ZONE(maskOrChannel, zoneName, ...) \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(zoneName, ##__VA_ARGS__), \ ::carb::profiler::ProfileZoneDynamic CARB_JOIN(_carbZone, __LINE__)( \ (maskOrChannel), CARB_PROFILE_FUNCFILE(__func__), __LINE__, zoneName, ##__VA_ARGS__), \ ::carb::profiler::ProfileZoneStatic CARB_JOIN(_carbZone, __LINE__)( \ (maskOrChannel), CARB_PROFILE_FUNCFILESTR(__func__, zoneName), __LINE__)) /** * A helper for CARB_PROFILE_ZONE() that automatically uses the function name as from `CARB_PRETTY_FUNCTION`. * * Equivalent, but faster than: `CARB_PROFILE_ZONE(mask, "%s", CARB_PRETTY_FUNCTION)`. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. */ # define CARB_PROFILE_FUNCTION(maskOrChannel) \ ::carb::profiler::ProfileZoneStatic CARB_JOIN(_carbZoneFunction, __LINE__)( \ (maskOrChannel), CARB_PROFILE_FUNCFILESTR(__func__, CARB_PRETTY_FUNCTION), __LINE__) /** * Writes a named numeric value to the profiling output for profilers that support them. * * @note Supported types for @p value are `float`, `uint32_t` and `int32_t`. * * @param value The value to record. * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. * @param valueName The name of the value. This must be either a literal string or a printf-style format string. Literal * strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p valueName. */ # define CARB_PROFILE_VALUE(value, maskOrChannel, valueName, ...) \ do \ { \ /* Use printf to validate the format string */ \ if (0) \ { \ printf(valueName, ##__VA_ARGS__); \ } \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ CARB_PROFILE_IF( \ CARB_PROFILE_HAS_VARARGS(valueName, ##__VA_ARGS__), \ ::g_carbProfiler->valueDynamic( \ ::carb::profiler::detail::maskHelper(maskOrChannel), value, valueName, ##__VA_ARGS__), \ ::g_carbProfiler->valueStatic(::carb::profiler::detail::maskHelper(maskOrChannel), value, []() { \ static ::carb::profiler::StaticStringType p = \ ::g_carbProfiler->registerStaticString("" valueName); \ return p; \ }())); \ } \ } while (0) /** * Records an allocation event for a named memory pool for profilers that support them. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. * @param ptr The memory address that was allocated. * @param size The size of the memory region beginning at @p ptr. * @param poolName The name of the memory pool. This must be either a literal string or a printf-style format string. * Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p poolName. */ # define CARB_PROFILE_ALLOC_NAMED(maskOrChannel, ptr, size, poolName, ...) \ do \ { \ /* Use printf to validate the format string */ \ if (0) \ { \ printf(poolName, ##__VA_ARGS__); \ } \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(poolName, ##__VA_ARGS__), \ ::g_carbProfiler->allocNamedDynamic(::carb::profiler::detail::maskHelper(maskOrChannel), \ ptr, size, poolName, ##__VA_ARGS__), \ ::g_carbProfiler->allocNamedStatic( \ ::carb::profiler::detail::maskHelper(maskOrChannel), ptr, size, []() { \ static ::carb::profiler::StaticStringType p = \ ::g_carbProfiler->registerStaticString("" poolName); \ return p; \ }())); \ } \ } while (0) /** * Records a free event for a named memory pool for profilers that support them. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. This should match * the value passed to CARB_PROFILE_ALLOC_NAMED() for the same allocation. * @param ptr The memory address that was freed. * @param poolName The name of the memory pool. This must be either a literal string or a printf-style format string. * Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p poolName. */ # define CARB_PROFILE_FREE_NAMED(maskOrChannel, ptr, poolName, ...) \ do \ { \ /* Use printf to validate the format string */ \ if (0) \ { \ printf(poolName, ##__VA_ARGS__); \ } \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ CARB_PROFILE_IF( \ CARB_PROFILE_HAS_VARARGS(poolName, ##__VA_ARGS__), \ ::g_carbProfiler->freeNamedDynamic( \ ::carb::profiler::detail::maskHelper(maskOrChannel), ptr, poolName, ##__VA_ARGS__), \ ::g_carbProfiler->freeNamedStatic(::carb::profiler::detail::maskHelper(maskOrChannel), ptr, []() { \ static ::carb::profiler::StaticStringType p = \ ::g_carbProfiler->registerStaticString("" poolName); \ return p; \ }())); \ } \ } while (0) /** * Records an allocation event for profilers that support them. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. * @param ptr The memory address that was allocated. * @param size The size of the memory region beginning at @p ptr. */ # define CARB_PROFILE_ALLOC(maskOrChannel, ptr, size) \ do \ { \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ ::g_carbProfiler->allocStatic(::carb::profiler::detail::maskHelper(maskOrChannel), ptr, size); \ } \ } while (0) /** * Records a free event for profilers that support them. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. * @param ptr The memory address that was freed. */ # define CARB_PROFILE_FREE(maskOrChannel, ptr) \ do \ { \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ ::g_carbProfiler->freeStatic(::carb::profiler::detail::maskHelper(maskOrChannel), ptr); \ } \ } while (0) /** * Records the name of a thread. * * @param tidOrZero The thread ID that is being named. A value of `0` indicates the current thread. Not all profilers * support values other than `0`. * @param threadName The name of the thread. This must be either a literal string or a printf-style format string. * Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p threadName. */ # define CARB_NAME_THREAD(tidOrZero, threadName, ...) \ do \ { \ /* Use printf to validate the format string */ \ if (0) \ { \ printf((threadName), ##__VA_ARGS__); \ } \ if (::g_carbProfiler) \ { \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(threadName, ##__VA_ARGS__), \ ::g_carbProfiler->nameThreadDynamic((tidOrZero), (threadName), ##__VA_ARGS__), \ ::g_carbProfiler->nameThreadStatic((tidOrZero), []() { \ static ::carb::profiler::StaticStringType p = \ ::g_carbProfiler->registerStaticString("" threadName); \ return p; \ }())); \ } \ } while (0) /** * Records an instant event on a thread's timeline at the current time. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. * @param type The type of the instant event that will be passed to carb::profiler::emitInstantStatic() or * carb::profiler::emitInstantDynamic(). * @param name The name of the event. This must either be a literal string or a printf-style format string with variadic * arguments. Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p name. */ # define CARB_PROFILE_EVENT(maskOrChannel, type, name, ...) \ do \ { \ if (0) \ printf((name), ##__VA_ARGS__); \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ CARB_PROFILE_IF( \ CARB_PROFILE_HAS_VARARGS(name, ##__VA_ARGS__), \ static auto tup = ::carb::profiler::detail::makeString2( \ ::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__)); \ ::g_carbProfiler->emitInstantDynamic(::carb::profiler::detail::maskHelper(maskOrChannel), tup.first, \ tup.second, __LINE__, (type), (name), ##__VA_ARGS__), \ static auto tup = ::carb::profiler::detail::makeString3( \ ::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__), ::g_carbProfiler->registerStaticString(name)); \ ::g_carbProfiler->emitInstantStatic(::carb::profiler::detail::maskHelper(maskOrChannel), \ tup.first, tup.second, __LINE__, (type), tup.third)); \ } \ } while (0) /** * Records the beginning of a flow event on the timeline at the current time for the current thread. * * Flow events draw an arrow from one point (the `BEGIN` location) to another point (the `END` location). * These two points can be in different threads but must have a matching @p id field. The @p id field is meant to be * unique across profiler runs, but may be reused as long as the @p name field matches across all `BEGIN` events and * events occur on the global timeline as `BEGIN` followed by `END`. * * This macro will automatically insert an instant event on the current thread's timeline. * * @param maskOrChannel The event mask (see carb::profiler::setCaptureMask()) or a profiling channel. * @param id A unique identifier that must also be passed to CARB_PROFILE_FLOW_END(). * @param name The name of the event. This must either be a literal string or a printf-style format string with variadic * arguments. Literal strings are far more efficient. * @param ... Optional printf-style variadic arguments corresponding to format specifiers in @p name. */ # define CARB_PROFILE_FLOW_BEGIN(maskOrChannel, id, name, ...) \ do \ { \ if (0) \ printf((name), ##__VA_ARGS__); \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(name, ##__VA_ARGS__), \ static auto tup = ::carb::profiler::detail::makeString2( \ ::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__)); \ ::g_carbProfiler->emitFlowDynamic( \ ::carb::profiler::detail::maskHelper(maskOrChannel), tup.first, tup.second, \ __LINE__, ::carb::profiler::FlowType::Begin, (id), (name), ##__VA_ARGS__), \ static auto tup = ::carb::profiler::detail::makeString3( \ ::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__), \ ::g_carbProfiler->registerStaticString("" name)); \ ::g_carbProfiler->emitFlowStatic(::carb::profiler::detail::maskHelper(maskOrChannel), \ tup.first, tup.second, __LINE__, \ ::carb::profiler::FlowType::Begin, (id), tup.third)); \ } \ } while (0) /** * Records the end of a flow event on the timeline at the current time for the current thread. * * @see CARB_PROFILE_FLOW_BEGIN() * * @param maskOrChannel The event mask or profiling channel. Must match the value given to CARB_PROFILE_FLOW_BEGIN(). * @param id Th unique identifier passed to CARB_PROFILE_FLOW_BEGIN(). */ # define CARB_PROFILE_FLOW_END(maskOrChannel, id) \ do \ { \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ static auto tup = \ ::carb::profiler::detail::makeString2(::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__)); \ ::g_carbProfiler->emitFlowStatic(::carb::profiler::detail::maskHelper(maskOrChannel), tup.first, \ tup.second, __LINE__, ::carb::profiler::FlowType::End, (id), \ ::carb::profiler::kInvalidStaticString); \ } \ } while (0) /** * Create a new GPU profiling context that allows injecting timestamps coming from a GPU in a deferred manner * * @param name name of the context * @param correlatedCpuTimestampNs correlated GPU clock timestamp (in nanoseconds) * @param correlatedGpuTimestamp correlated GPU clock timestamp (raw value) * @param gpuTimestampPeriodNs is the number of nanoseconds required for a GPU timestamp query to be incremented * by 1. * @param graphicApi string of graphic API used ['vulkan'/'d3d12'] * @returns a valid ID or kInvalidGpuContextId if creation fails */ # define CARB_PROFILE_CREATE_GPU_CONTEXT( \ name, correlatedCpuTimestampNs, correlatedGpuTimestamp, gpuTimestampPeriodNs, graphicApi) \ (::g_carbProfiler ? ::g_carbProfiler->createGpuContext(name, correlatedCpuTimestampNs, correlatedGpuTimestamp, \ gpuTimestampPeriodNs, graphicApi) : \ carb::profiler::kInvalidGpuContextId) /** * Destroy a previously created GPU Context * * @param contextId ID of the context, returned by createGpuContext */ # define CARB_PROFILE_DESTROY_GPU_CONTEXT(contextId) \ do \ { \ if (::g_carbProfiler) \ { \ ::g_carbProfiler->destroyGpuContext(contextId); \ } \ } while (0) /** * Submit context calibration information that allows correlating CPU and GPU clocks * * @param contextId ID of the context, returned by @ref carb::profiler::IProfiler::createGpuContext() * @param correlatedCpuTimestampNs The new CPU timestamp at the time of correlation (in nanoseconds) * @param previousCorrelatedCpuTimestampNs The CPU timestamp at the time of previous correlation (in nanoseconds) * @param correlatedGpuTimestamp The new raw GPU timestamp at the time of correlation */ # define CARB_PROFILE_CALIBRATE_GPU_CONTEXT( \ contextId, correlatedCpuTimestampNs, previousCorrelatedCpuTimestampNs, correlatedGpuTimestamp) \ ((::g_carbProfiler) ? \ (::g_carbProfiler->calibrateGpuContext( \ contextId, correlatedCpuTimestampNs, previousCorrelatedCpuTimestampNs, correlatedGpuTimestamp)) : \ false) /** * Record the beginning of a new GPU timestamp query * * @param maskOrChannel Event capture mask or profiling channel. * @param contextId The id of the context as returned by @ref carb::profiler::IProfiler::createGpuContext() * @param queryId Unique query id (for identification when passing to @ref * carb::profiler::IProfiler::setGpuQueryValue()) * @param eventName The name for the event. */ # define CARB_PROFILE_GPU_QUERY_BEGIN(maskOrChannel, contextId, queryId, eventName, ...) \ do \ { \ if (0) \ printf((eventName), ##__VA_ARGS__); \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ CARB_PROFILE_IF(CARB_PROFILE_HAS_VARARGS(eventName, ##__VA_ARGS__), \ static auto tup = ::carb::profiler::detail::makeString2( \ ::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__)); \ ::g_carbProfiler->beginGpuQueryDynamic( \ ::carb::profiler::detail::maskHelper(maskOrChannel), tup.first, tup.second, \ __LINE__, contextId, queryId, eventName, ##__VA_ARGS__), \ static auto tup = ::carb::profiler::detail::makeString3( \ ::g_carbProfiler->registerStaticString(CARB_PRETTY_FUNCTION), \ ::g_carbProfiler->registerStaticString(__FILE__), \ ::g_carbProfiler->registerStaticString("" eventName)); \ ::g_carbProfiler->beginGpuQueryStatic( \ ::carb::profiler::detail::maskHelper(maskOrChannel), tup.first, tup.second, \ __LINE__, contextId, queryId, tup.third)); \ } \ } while (0) /** * Record the end of a new GPU timestamp query * * @param maskOrChannel Event capture mask or profiling channel. * @param contextId The id of the context as returned by @ref carb::profiler::IProfiler::createGpuContext() * @param queryId Unique query id (for identification when passing to @ref * carb::profiler::IProfiler::setGpuQueryValue()) */ # define CARB_PROFILE_GPU_QUERY_END(maskOrChannel, contextId, queryId) \ do \ { \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ ::g_carbProfiler->endGpuQuery(::carb::profiler::detail::maskHelper(maskOrChannel), contextId, queryId); \ } \ } while (0) /** * Set the value we've received from the GPU for a query (begin or end) we've issued in the past * * @param maskOrChannel Event capture mask or profiling channel * @param contextId The id of the context as returned by @ref carb::profiler::IProfiler::createGpuContext() * @param queryId Unique query id specified at begin/end time * @param gpuTimestamp Raw GPU timestamp value */ # define CARB_PROFILE_GPU_SET_QUERY_VALUE(maskOrChannel, contextId, queryId, gpuTimestamp) \ do \ { \ if (::g_carbProfiler && ::carb::profiler::detail::enabled(maskOrChannel)) \ { \ ::g_carbProfiler->setGpuQueryValue( \ ::carb::profiler::detail::maskHelper(maskOrChannel), contextId, queryId, gpuTimestamp); \ } \ } while (0) /** * Create a lockable context which we can use to tag lock operation * @note Do not use this macro directly. Use \ref carb::profiler::ProfiledMutex or * \ref carb::profiler::ProfiledSharedMutex instead. * @param maskOrChannel Event capture mask or profiling channel * @param isSharedLock If this shared for a shared lock * @param name The lockable context name */ # define CARB_PROFILE_LOCKABLE_CREATE(maskOrChannel, isSharedLock, name) \ [](bool enabled, const uint64_t maskParam, const bool isSharedLockParam, const char* nameParam, \ const char* function) { \ if (::g_carbProfiler && enabled) \ { \ static auto tup = ::carb::profiler::detail::makeString2( \ ::g_carbProfiler->registerStaticString(function), ::g_carbProfiler->registerStaticString(__FILE__)); \ return ::g_carbProfiler->createLockable( \ maskParam, nameParam, isSharedLockParam, tup.first, tup.second, __LINE__); \ } \ return ::carb::profiler::kInvalidLockableId; \ }(::carb::profiler::detail::enabled(maskOrChannel), ::carb::profiler::detail::maskHelper(maskOrChannel), \ (isSharedLock), (name), CARB_PRETTY_FUNCTION) /** * Destroy a lockable context * @note Do not use this macro directly. Use \ref carb::profiler::ProfiledMutex or * \ref carb::profiler::ProfiledSharedMutex instead. * @param lockableId the id of the lockable as returned by @ref carb::profiler::IProfiler::createLockable() */ # define CARB_PROFILE_LOCKABLE_DESTROY(lockableId) \ do \ { \ if (::g_carbProfiler && lockableId != carb::profiler::kInvalidLockableId) \ { \ ::g_carbProfiler->destroyLockable((lockableId)); \ } \ } while (0) /** * Records a lockable operation on a thread's timeline at the current time. * @note Do not use this macro directly. Use \ref carb::profiler::ProfiledMutex or * \ref carb::profiler::ProfiledSharedMutex instead. * @param lockableId the id of the lockable as returned by @ref carb::profiler::IProfiler::createLockable() * @param operation which lock operation to tag */ # define CARB_PROFILE_LOCKABLE_OPERATION(lockableId, operation) \ do \ { \ if (::g_carbProfiler && lockableId != carb::profiler::kInvalidLockableId) \ { \ ::g_carbProfiler->lockableOperation((lockableId), (operation)); \ } \ } while (0) /// @} #else # define CARB_PROFILE_STARTUP() (void(0)) # define CARB_PROFILE_SHUTDOWN() (void(0)) # define CARB_PROFILE_REGISTER_STRING(str) (CARB_UNUSED(str), ::carb::profiler::kInvalidStaticString) # define CARB_PROFILE_SET_CAPTURE_MASK(mask) CARB_UNUSED(mask) # define CARB_PROFILE_BEGIN(maskOrChannel, eventName, ...) \ (CARB_UNUSED((maskOrChannel), (eventName), ##__VA_ARGS__), ::carb::profiler::kNoZoneId) # define CARB_PROFILE_END(maskOrChannel, ...) CARB_UNUSED((maskOrChannel), ##__VA_ARGS__) # define CARB_PROFILE_FRAME(mask, frameName, ...) CARB_UNUSED((mask), (frameName), ##__VA_ARGS__) # define CARB_PROFILE_ZONE(maskOrChannel, zoneName, ...) CARB_UNUSED((maskOrChannel), (zoneName), ##__VA_ARGS__) # define CARB_PROFILE_FUNCTION(maskOrChannel) CARB_UNUSED(maskOrChannel) # define CARB_PROFILE_VALUE(value, maskOrChannel, valueName, ...) \ CARB_UNUSED((value), (maskOrChannel), (valueName), ##__VA_ARGS__) # define CARB_PROFILE_ALLOC_NAMED(maskOrChannel, ptr, size, poolName, ...) \ CARB_UNUSED((maskOrChannel), (ptr), (size), (poolName), ##__VA_ARGS__) # define CARB_PROFILE_FREE_NAMED(maskOrChannel, ptr, poolName, ...) \ CARB_UNUSED((maskOrChannel), (ptr), (poolName), ##__VA_ARGS__) # define CARB_PROFILE_ALLOC(maskOrChannel, ptr, size) CARB_UNUSED((maskOrChannel), (ptr), (size)) # define CARB_PROFILE_FREE(maskOrChannel, ptr) CARB_UNUSED((maskOrChannel), (ptr)) # define CARB_NAME_THREAD(tidOrZero, threadName, ...) CARB_UNUSED((tidOrZero), (threadName), ##__VA_ARGS__) # define CARB_PROFILE_EVENT(maskOrChannel, type, name, ...) \ CARB_UNUSED((maskOrChannel), (type), (name), ##__VA_ARGS__) # define CARB_PROFILE_FLOW_BEGIN(maskOrChannel, id, name, ...) \ CARB_UNUSED((maskOrChannel), (id), (name), ##__VA_ARGS__) # define CARB_PROFILE_FLOW_END(maskOrChannel, id) CARB_UNUSED((maskOrChannel), (id)) # define CARB_PROFILE_CREATE_GPU_CONTEXT( \ name, correlatedCpuTimestampNs, correlatedGpuTimestamp, gpuTimestampPeriodNs, graphicApi) \ (CARB_UNUSED( \ (name), (correlatedCpuTimestampNs), (correlatedGpuTimestamp), (gpuTimestampPeriodNs), (graphicsApi)), \ carb::profiler::kInvalidGpuContextId) # define CARB_PROFILE_DESTROY_GPU_CONTEXT(contextId) CARB_UNUSED(contextId) # define CARB_PROFILE_CALIBRATE_GPU_CONTEXT( \ contextId, correlatedCpuTimestampNs, previousCorrelatedCpuTimestampNs, correlatedGpuTimestamp) \ CARB_UNUSED( \ (contextId), (correlatedCpuTimestampNs), (previousCorrelatedCpuTimestampNs), (correlatedGpuTimestamp)) # define CARB_PROFILE_GPU_QUERY_BEGIN(maskOrChannel, contextId, queryId, eventName, ...) \ CARB_UNUSED((maskOrChannel), (contextId), (queryId), (eventName), ##__VA_ARGS__) # define CARB_PROFILE_GPU_QUERY_END(maskOrChannel, contextId, queryId) \ (CARB_UNUSED((maskOrChannel), (contextId), (queryId))) # define CARB_PROFILE_GPU_SET_QUERY_VALUE(maskOrChannel, contextId, queryId, gpuTimestamp) \ CARB_UNUSED((maskOrChannel), (contextId), (queryId), (gpuTimestamp)) # define CARB_PROFILE_LOCKABLE_CREATE(maskOrChannel, isSharedLock, name) \ (CARB_UNUSED((maskOrChannel), (isSharedLock), (name)), ::carb::profiler::kInvalidLockableId) # define CARB_PROFILE_LOCKABLE_DESTROY(lockableId) CARB_UNUSED(lockableId) # define CARB_PROFILE_LOCKABLE_OPERATION(lockableId, operation) CARB_UNUSED((lockableId), (operation)) #endif /** * Placeholder macro for any work that needs to be done at the global scope for the profiler. * @note This is typically not used as it is included in the @ref CARB_GLOBALS_EX macro. */ #define CARB_PROFILER_GLOBALS() namespace carb { namespace profiler { /** * Wrapper to add automatic profiling to a mutex */ template <class Mutex> class ProfiledMutex { public: /** * Constructor. * @param profileMask The mask used to determine if events from this mutex are captured. * @param name The name of the mutex */ ProfiledMutex(const uint64_t profileMask, const char* name) : ProfiledMutex(profileMask, false, name) { } /** * Constructor. * @param channel The profiling channel used to determine if events from this mutex are captured. * @param name The name of the mutex */ ProfiledMutex(const carb::profiler::Channel& channel, const char* name) : ProfiledMutex(channel, false, name) { } /** * Destructor. */ ~ProfiledMutex() { CARB_PROFILE_LOCKABLE_DESTROY(m_lockableId); } /** * Locks the underlying mutex and reports the event to the profiler. */ void lock() { CARB_PROFILE_LOCKABLE_OPERATION(m_lockableId, LockableOperationType::BeforeLock); m_mutex.lock(); CARB_PROFILE_LOCKABLE_OPERATION(m_lockableId, LockableOperationType::AfterLock); } /** * Attempts a lock on the underlying mutex and reports the event to the profiler if successful. * @returns \c true if successfully locked; \c false otherwise. */ bool try_lock() { bool acquired = m_mutex.try_lock(); if (acquired) { CARB_PROFILE_LOCKABLE_OPERATION(m_lockableId, LockableOperationType::AfterSuccessfulTryLock); } return acquired; } /** * Unlocks the underlying mutex and reports the event to the profiler. */ void unlock() { m_mutex.unlock(); CARB_PROFILE_LOCKABLE_OPERATION(m_lockableId, LockableOperationType::AfterUnlock); } /** * Returns a reference to the underlying mutex. * @returns a reference to the underlying mutex. */ Mutex& getMutex() { return m_mutex; } /** * Returns a reference to the underlying mutex. * @returns a reference to the underlying mutex. */ const Mutex& getMutex() const { return m_mutex; } protected: /** * Protected Constructor. * @param profileMask The mask used to determine if events from this mutex are captured. * @param isSharedMutex A boolean representing whether `*this` represents a shared mutex. * @param name The name of the mutex */ ProfiledMutex(const uint64_t profileMask, bool isSharedMutex, const char* name) { m_lockableId = CARB_PROFILE_LOCKABLE_CREATE(profileMask, isSharedMutex, name); } /** * Protected Constructor. * @param channel The channel used to determine if events from this mutex are captured. * @param isSharedMutex A boolean representing whether `*this` represents a shared mutex. * @param name The name of the mutex */ ProfiledMutex(const carb::profiler::Channel& channel, bool isSharedMutex, const char* name) { m_lockableId = CARB_PROFILE_LOCKABLE_CREATE(channel, isSharedMutex, name); } //! The underlying mutex instance Mutex m_mutex; //! The lockable ID as returned by \ref carb::profiler::IProfiler::createLockable() LockableId m_lockableId; }; /** * Wrapper to add automatic profiling to a shared mutex */ template <class Mutex> class ProfiledSharedMutex : public ProfiledMutex<Mutex> { using Base = ProfiledMutex<Mutex>; public: /** * Constructor. * @param profileMask The mask used to determine if events from this mutex are captured. * @param name The name of the mutex */ ProfiledSharedMutex(const uint64_t profileMask, const char* name) : Base(profileMask, true, name) { } /** * Constructor. * @param channel The profiling channel used to determine if events from this mutex are captured. * @param name The name of the mutex */ ProfiledSharedMutex(const carb::profiler::Channel& channel, const char* name) : Base(channel, true, name) { } /** * Destructor. */ ~ProfiledSharedMutex() { } /** * Locks the underlying mutex (shared) and reports the event to the profiler. */ void lock_shared() { CARB_PROFILE_LOCKABLE_OPERATION(this->m_lockableId, LockableOperationType::BeforeLockShared); this->m_mutex.lock_shared(); CARB_PROFILE_LOCKABLE_OPERATION(this->m_lockableId, LockableOperationType::AfterLockShared); } /** * Attempts a shared lock on the underlying mutex and reports the event to the profiler if successful. * @returns \c true if successfully locked; \c false otherwise. */ bool try_lock_shared() { bool acquired = this->m_mutex.try_lock_shared(); if (acquired) { CARB_PROFILE_LOCKABLE_OPERATION(this->m_lockableId, LockableOperationType::AfterSuccessfulTryLockShared); } return acquired; } /** * Unlocks (shared) the underlying mutex and reports the event to the profiler. */ void unlock_shared() { this->m_mutex.unlock_shared(); CARB_PROFILE_LOCKABLE_OPERATION(this->m_lockableId, LockableOperationType::AfterUnlockShared); } }; void deregisterProfilerForClient() noexcept; #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { inline void updateMask(uint64_t mask) { g_carbProfilerMask.store(mask, std::memory_order_release); } inline void releaseHook(void* iface, void*) { cpp::atomic_ref<IProfiler*>(g_carbProfiler).store(nullptr); // sequentially consistent getFramework()->removeReleaseHook(iface, &releaseHook, nullptr); } inline void frameworkReleaseHook(void*, void*) { // Framework is going away, so make sure we get fully deregistered. deregisterProfilerForClient(); } inline void loadHook(const PluginDesc&, void*) { if (!g_carbProfiler) { IProfiler* profiler = getFramework()->tryAcquireInterface<IProfiler>(); if (profiler) { if (profiler->setMaskCallback) { // Relaxed semantics since we will shortly be synchronizing on g_carbProfiler. g_carbProfilerMask.store(profiler->setMaskCallback(updateMask, true), std::memory_order_relaxed); } else { g_carbProfilerMask.store(uint64_t(-1), std::memory_order_relaxed); // not supported; let everything // through } getFramework()->addReleaseHook(profiler, &detail::releaseHook, nullptr); cpp::atomic_ref<IProfiler*>(g_carbProfiler).store(profiler, std::memory_order_seq_cst); // sequentially // consistent } } } inline bool& registered() { static bool r{ false }; return r; } inline LoadHookHandle& loadHookHandle() { static carb::LoadHookHandle handle{}; return handle; } } // namespace detail #endif /** * Allows access to the @ref g_carbProfiler global variable previously registered with @ref registerProfilerForClient(). * @returns The value of @ref g_carbProfiler. */ inline IProfiler* getProfiler() { return g_carbProfiler; } /** * Clears the @ref g_carbProfiler global variable and unregisters load and release hooks with the \ref Framework. */ inline void deregisterProfilerForClient() noexcept { if (std::exchange(detail::registered(), false)) { auto fw = getFramework(); auto handle = std::exchange(detail::loadHookHandle(), kInvalidLoadHook); IProfiler* profiler = cpp::atomic_ref<IProfiler*>(g_carbProfiler).exchange(nullptr, std::memory_order_seq_cst); if (fw) { if (profiler && fw->verifyInterface(profiler) && profiler->setMaskCallback) { profiler->setMaskCallback(detail::updateMask, false); } if (handle) { fw->removeLoadHook(handle); } fw->removeReleaseHook(nullptr, &detail::frameworkReleaseHook, nullptr); if (profiler) { fw->removeReleaseHook(profiler, &detail::releaseHook, nullptr); } // Unregister channels Channel::onProfilerUnregistered(); } } } /** * Acquires the default IProfiler interface and assigns it to the @ref g_carbProfiler global variable. * * If a profiler is not yet loaded, a load hook is registered with the \ref Framework and when the profiler is loaded, * \ref g_carbProfiler will be automatically set for this module. If the profiler is unloaded, \ref g_carbProfiler will * be automatically set to `nullptr`. */ inline void registerProfilerForClient() noexcept { if (!std::exchange(detail::registered(), true)) { auto fw = getFramework(); fw->addReleaseHook(nullptr, &detail::frameworkReleaseHook, nullptr); IProfiler* profiler = fw->tryAcquireInterface<IProfiler>(); if (profiler) { if (profiler->setMaskCallback) { // Relaxed semantics since we will shortly be synchronizing on g_carbProfiler. g_carbProfilerMask.store(profiler->setMaskCallback(detail::updateMask, true), std::memory_order_relaxed); } else { g_carbProfilerMask.store(uint64_t(-1), std::memory_order_relaxed); // let everything through } bool b = fw->addReleaseHook(profiler, &detail::releaseHook, nullptr); CARB_ASSERT(b); CARB_UNUSED(b); } cpp::atomic_ref<IProfiler*>(g_carbProfiler).store(profiler, std::memory_order_seq_cst); // sequentially // consistent detail::loadHookHandle() = fw->addLoadHook<IProfiler>(nullptr, &detail::loadHook, nullptr); // Register channels Channel::onProfilerRegistered(); // Make sure this only happens once even if re-registered. static bool ensureDeregister = (atexit(&deregisterProfilerForClient), true); CARB_UNUSED(ensureDeregister); } } } // namespace profiler } // namespace carb
77,631
C
62.528642
124
0.427239
omniverse-code/kit/include/carb/cpp/Tuple.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 C++14-compatible implementation of select functionality from C++ `<tuple>` library. #pragma once #include <tuple> #include "Functional.h" namespace carb { namespace cpp { namespace detail { template <class F, class Tuple, size_t... I> constexpr decltype(auto) applyImpl(F&& f, Tuple&& t, std::index_sequence<I...>) { return carb::cpp::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...); } } // namespace detail template <class F, class Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) { return detail::applyImpl(std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size<std::remove_reference_t<Tuple>>::value>{}); } } // namespace cpp } // namespace carb
1,210
C
27.833333
113
0.703306
omniverse-code/kit/include/carb/cpp/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. // //! \file //! \brief C++14-compatible implementation of select functionality from C++ `<semaphore>` library. #pragma once #include "Atomic.h" #include "../thread/Futex.h" #include <algorithm> #include <thread> namespace carb { namespace cpp { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { # if CARB_PLATFORM_WINDOWS constexpr ptrdiff_t kSemaphoreValueMax = LONG_MAX; # else constexpr ptrdiff_t kSemaphoreValueMax = INT_MAX; # endif } // namespace detail #endif // Handle case where Windows.h may have defined 'max' #pragma push_macro("max") #undef max /** * C++20-compatible counting semaphore class. * * A counting_semaphore is a lightweight synchronization primitive that can control access to a shared resource. Unlike * a mutex, a counting_semaphore allows more than one concurrent access to the same resource, for at least * `least_max_value` concurrent accessors. The program is ill-formed if `least_max_value` is negative. * * This is a C++14-compatible implementation of std::counting_semaphore from C++20 draft spec dated 11/13/2019. * * @note `sizeof(counting_semaphore)` is 8 bytes for `least_max_value > 1`. A specialization exists for * `least_max_value == 1` where the size is only 1 byte, also known as @ref binary_semaphore. * * @tparam least_max_value The maximum count value that this semaphore can reach. This * indicates the number of threads or callers that can simultaneously * successfully acquire this semaphore. May not be less than or equal to zero. * * @thread_safety This class is thread-safe. However, attempting to destruct before all threads have returned from any * function (especially the wait functions) is malformed and will lead to undefined behavior. */ template <ptrdiff_t least_max_value = detail::kSemaphoreValueMax> class CARB_VIZ counting_semaphore { CARB_PREVENT_COPY_AND_MOVE(counting_semaphore); public: /** Constructor: initializes a new semaphore object with a given count. * * @param[in] desired The initial count value for the semaphore. This must be a positive * value or zero. If set to zero, the semaphore will be 'unowned' on * creation. If set to any other value, the semaphore will only be able * to be acquired by at most @a least_max_value minus @p desired other * threads or callers until it is released @p desired times. */ constexpr explicit counting_semaphore(ptrdiff_t desired) noexcept : m_data(::carb_min(::carb_max(ptrdiff_t(0), desired), least_max_value)) { static_assert(least_max_value >= 1, "semaphore needs a count of at least 1"); static_assert(least_max_value <= detail::kSemaphoreValueMax, "semaphore count too high"); } /** * Destructor * * On Linux, performs a `CARB_CHECK` to verify that no waiters are present when `*this` is destroyed. * * @note On Windows, `ExitProcess()` (or returning from `main()`) causes all threads to be terminated before * `atexit()` registered functions are called (and static objects are cleaned up). This has the unpleasant side * effect of potentially terminating threads that are waiting on a semaphore and will never get the chance to clean * up their waiting count. Therefore, this check is linux only. */ ~counting_semaphore() noexcept { #if CARB_PLATFORM_LINUX // Make sure we don't have any waiters when we are destroyed CARB_CHECK((m_data.load(std::memory_order_acquire) >> kWaitersShift) == 0, "Semaphore destroyed with waiters"); #endif } /** Retrieves the maximum count value this semaphore can reach. * * @returns The maximum count value for this semaphore. This will never be zero. * * @thread_safety This call is thread safe. */ static constexpr ptrdiff_t max() noexcept { return least_max_value; } /** Releases references on this semaphore and potentially wakes another waiting thread. * * @param[in] update The number of references to atomically increment this semaphore's * counter by. This number of waiting threads will be woken as a * result. * @return No return value. * * @remarks This releases zero or more references on this semaphore. If a reference is * released, another waiting thread could potentially be woken and acquire this * semaphore again. * * @thread_safety This call is thread safe. */ void release(ptrdiff_t update = 1) noexcept { CARB_ASSERT(update >= 0); uint64_t d = m_data.load(std::memory_order_relaxed), u; for (;;) { // The standard is somewhat unclear here. Preconditions are that update >= 0 is true and update <= max() - // counter is true. And it throws system_error when an exception is required. So I supposed that it's likely // that violating the precondition would cause a system_error exception which doesn't completely make sense // (I would think runtime_error would make more sense). However, throwing at all is inconvenient, as is // asserting/crashing/etc. Therefore, we clamp the update value here. u = ::carb_min(update, max() - ptrdiff_t(d & kValueMask)); if (CARB_LIKELY(m_data.compare_exchange_weak(d, d + u, std::memory_order_release, std::memory_order_relaxed))) break; } // At this point, the Semaphore could be destroyed by another thread. Therefore, we shouldn't access any other // members (taking the address of m_data below is okay because that would not actually read any memory that // may be destroyed) // waiters with a value have been notified already by whatever thread added the value. Only wake threads that // haven't been woken yet. ptrdiff_t waiters = ptrdiff_t(d >> kWaitersShift); ptrdiff_t value = ptrdiff_t(d & kValueMask); ptrdiff_t wake = ::carb_min(ptrdiff_t(u), waiters - value); if (wake > 0) { // cpp::atomic only has notify_one() and notify_all(). Call the futex system directly to wake N. thread::futex::notify(m_data, unsigned(size_t(wake)), unsigned(size_t(waiters))); } } /** Acquires a reference to this semaphore. * * @returns No return value. * * @remarks This blocks until a reference to this semaphore can be successfully acquired. * This is done by atomically decrementing the semaphore's counter if it is greater * than zero. If the counter is zero, this will block until the counter is greater * than zero. The counter is incremented by calling release(). * * @thread_safety This call is thread safe. */ void acquire() noexcept { if (CARB_LIKELY(fast_acquire(false))) return; // Register as a waiter uint64_t d = m_data.fetch_add(uint64_t(1) << kWaitersShift, std::memory_order_relaxed) + (uint64_t(1) << kWaitersShift); for (;;) { if ((d & kValueMask) == 0) { // Need to wait m_data.wait(d, std::memory_order_relaxed); // Reload d = m_data.load(std::memory_order_relaxed); } else { // Try to unregister as a waiter and grab a token at the same time if (CARB_LIKELY(m_data.compare_exchange_weak(d, d - 1 - (uint64_t(1) << kWaitersShift), std::memory_order_acquire, std::memory_order_relaxed))) return; } } } /** Attempts to acquire a reference to this semaphore. * * @returns `true` if the semaphore's counter was greater than zero and it was successfully * atomically decremented. Returns `false` if the counter was zero and the * semaphore could not be acquired. This will never block even if the semaphore * could not be acquired. * * @thread_safety This call is thread safe. */ bool try_acquire() noexcept { return fast_acquire(true); } /** Attempts to acquire a reference to this semaphore for a specified relative time. * * @tparam Rep The representation primitive type for the duration value. * @tparam Period The duration's time scale value (ie: milliseconds, seconds, etc). * @param[in] duration The amount of time to try to acquire this semaphore for. This is * specified as a duration relative to the call time. * @returns `true` if the semaphore's counter was greater than zero and it was successfully * atomically decremented within the specified time limit. Returns `false` if the * counter was zero and the semaphore could not be acquired within the time limit. * This will only block for up to approximately the specified time limit. * * @thread_safety This call is thread safe. */ template <class Rep, class Period> bool try_acquire_for(const std::chrono::duration<Rep, Period>& duration) noexcept { if (CARB_LIKELY(fast_acquire(false))) return true; if (duration.count() <= 0) return false; // Register as a waiter uint64_t d = m_data.fetch_add(uint64_t(1) << kWaitersShift, std::memory_order_relaxed) + (uint64_t(1) << kWaitersShift); while ((d & kValueMask) != 0) { // Try to unregister as a waiter and grab a token at the same time if (CARB_LIKELY(m_data.compare_exchange_weak( d, d - 1 - (uint64_t(1) << kWaitersShift), std::memory_order_acquire, std::memory_order_relaxed))) return true; } // Now we need to wait, but do it with absolute time so that we properly handle spurious futex wakeups auto time_point = std::chrono::steady_clock::now() + thread::detail::clampDuration(duration); for (;;) { if (!m_data.wait_until(d, time_point, std::memory_order_relaxed)) { // Timed out. Unregister as a waiter m_data.fetch_sub(uint64_t(1) << kWaitersShift, std::memory_order_relaxed); return false; } // Reload after wait d = m_data.load(std::memory_order_relaxed); if ((d & kValueMask) != 0) { // Try to unreference as a waiter and grab a token at the same time if (CARB_LIKELY(m_data.compare_exchange_weak(d, d - 1 - (uint64_t(1) << kWaitersShift), std::memory_order_acquire, std::memory_order_relaxed))) return true; } } } /** Attempts to acquire a reference to this semaphore until a specified absolute time. * * @tparam Clock The clock to use as a time source to compare the time limit to. * @tparam Duration The duration type associated with the specified clock. * @param[in] time_point The absolute time to try to acquire this semaphore for. This is * specified as a time point from the given clock @a Clock. * @returns `true` if the semaphore's counter was greater than zero and it was successfully * atomically decremented before the specified time limit. Returns `false` if the * counter was zero and the semaphore could not be acquired before the time limit. * This will only block up until approximately the specified time limit. * * @thread_safety This call is thread safe. */ template <class Clock, class Duration> bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& time_point) noexcept { if (CARB_LIKELY(fast_acquire(false))) return true; // Register as a waiter uint64_t d = m_data.fetch_add(uint64_t(1) << kWaitersShift, std::memory_order_relaxed) + (uint64_t(1) << kWaitersShift); for (;;) { if ((d & kValueMask) == 0) { // Need to wait if (!m_data.wait_until(d, time_point, std::memory_order_relaxed)) { // Timed out. Unregister as a waiter m_data.fetch_sub(uint64_t(1) << kWaitersShift, std::memory_order_relaxed); return false; } // Reload after wait d = m_data.load(std::memory_order_relaxed); } else { // Try to unregister as a waiter and grab a token at the same time if (CARB_LIKELY(m_data.compare_exchange_weak(d, d - 1 - (uint64_t(1) << kWaitersShift), std::memory_order_acquire, std::memory_order_relaxed))) return true; } } } #ifndef DOXYGEN_SHOULD_SKIP_THIS protected: // The 32 most significant bits are the waiters; the lower 32 bits is the value of the semaphore CARB_VIZ cpp::atomic_uint64_t m_data; constexpr static int kWaitersShift = 32; constexpr static unsigned kValueMask = 0xffffffff; CARB_ALWAYS_INLINE bool fast_acquire(bool needResolution) noexcept { uint64_t d = m_data.load(needResolution ? std::memory_order_acquire : std::memory_order_relaxed); for (;;) { if (uint32_t(d & kValueMask) == 0) return false; if (CARB_LIKELY(m_data.compare_exchange_weak(d, d - 1, std::memory_order_acquire, std::memory_order_relaxed))) return true; if (!needResolution) return false; } } #endif }; #ifndef DOXYGEN_SHOULD_SKIP_THIS /** Specialization for the case of a semaphore with a maximum count of 1. This is treated as * a binary semaphore - it can only be acquired by one caller at a time. */ template <> class CARB_VIZ counting_semaphore<1> { CARB_PREVENT_COPY_AND_MOVE(counting_semaphore); public: static constexpr ptrdiff_t max() noexcept { return 1; } constexpr explicit counting_semaphore(ptrdiff_t desired) noexcept : m_val(uint8_t(size_t(::carb_min(::carb_max(ptrdiff_t(0), desired), max())))) { } void release(ptrdiff_t update = 1) noexcept { if (CARB_UNLIKELY(update <= 0)) return; CARB_ASSERT(update == 1); // precondition failure if (!m_val.exchange(1, std::memory_order_release)) m_val.notify_one(); } void acquire() noexcept { for (;;) { uint8_t old = m_val.exchange(0, std::memory_order_acquire); if (CARB_LIKELY(old == 1)) break; CARB_ASSERT(old == 0); // m_val can only be 0 or 1 m_val.wait(0, std::memory_order_relaxed); } } bool try_acquire() noexcept { uint8_t old = m_val.exchange(0, std::memory_order_acquire); CARB_ASSERT(old <= 1); // m_val can only be 0 or 1 return old == 1; } template <class Rep, class Period> bool try_acquire_for(const std::chrono::duration<Rep, Period>& duration) noexcept { return try_acquire_until(std::chrono::steady_clock::now() + thread::detail::clampDuration(duration)); } template <class Clock, class Duration> bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& time_point) noexcept { for (;;) { uint8_t old = m_val.exchange(0, std::memory_order_acquire); if (CARB_LIKELY(old == 1)) return true; CARB_ASSERT(old == 0); // m_val can only be 0 or 1 if (!m_val.wait_until(0, time_point, std::memory_order_relaxed)) return false; } } protected: CARB_VIZ cpp::atomic_uint8_t m_val; }; #endif /** Alias for a counting semaphore that can only be acquired by one caller at a time. */ using binary_semaphore = counting_semaphore<1>; #pragma pop_macro("max") } // namespace cpp } // namespace carb
17,044
C
39.680191
122
0.606724
omniverse-code/kit/include/carb/cpp/Functional.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 C++14-compatible implementation of select functionality from C++ `<functional>` library. #pragma once #include "TypeTraits.h" #include "detail/ImplInvoke.h" #include "../detail/NoexceptType.h" namespace carb { namespace cpp { CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE() //! Invoke the function \a f with the given \a args pack. //! //! This is equivalent to the C++20 \c std::invoke function. It was originally added in C++17, but is marked as //! \c constexpr per the C++20 Standard. template <typename Func, typename... TArgs> constexpr invoke_result_t<Func, TArgs...> invoke(Func&& f, TArgs&&... args) noexcept(is_nothrow_invocable<Func, TArgs...>::value) { return detail::invoke_impl<std::decay_t<Func>>::eval(std::forward<Func>(f), std::forward<TArgs>(args)...); } //! \cond DEV namespace detail { // This is needed to handle calling a function which returns a non-void when `R` is void. The only difference is the // lack of a return statement. template <typename R, typename Func, typename... TArgs> constexpr std::enable_if_t<is_void<R>::value> invoke_r_impl(Func&& f, TArgs&&... args) noexcept( is_nothrow_invocable_r<R, Func, TArgs...>::value) { detail::invoke_impl<std::decay_t<Func>>::eval(std::forward<Func>(f), std::forward<TArgs>(args)...); } template <typename R, typename Func, typename... TArgs> constexpr std::enable_if_t<!is_void<R>::value, R> invoke_r_impl(Func&& f, TArgs&&... args) noexcept( is_nothrow_invocable_r<R, Func, TArgs...>::value) { return detail::invoke_impl<std::decay_t<Func>>::eval(std::forward<Func>(f), std::forward<TArgs>(args)...); } } // namespace detail //! \endcond //! Invoke the function with the given arguments with the explicit return type \c R. This follows the same rules as //! \ref carb::cpp::invoke(). //! //! This is equivalent to the C++23 \c std::invoke_r function. It lives here because people would expect an \c invoke_r //! function to live next to an \c invoke function. template <typename R, typename Func, typename... TArgs> constexpr R invoke_r(Func&& f, TArgs&&... args) noexcept(is_nothrow_invocable_r<R, Func, TArgs...>::value) { return detail::invoke_r_impl<R>(std::forward<Func>(f), std::forward<TArgs>(args)...); } CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE() } // namespace cpp } // namespace carb
2,806
C
36.426666
119
0.694227
omniverse-code/kit/include/carb/cpp/Utility.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 C++14-compatible implementation of select functionality from C++ `<utility>` library. #pragma once #include "../Defines.h" #include <utility> namespace carb { namespace cpp { #if !CARB_HAS_CPP17 struct in_place_t { explicit in_place_t() = default; }; static constexpr in_place_t in_place{}; template <class> struct in_place_type_t { explicit in_place_type_t() = default; }; template <class T> static constexpr in_place_type_t<T> in_place_type{}; template <std::size_t I> struct in_place_index_t { explicit in_place_index_t() = default; }; template <std::size_t I> static constexpr in_place_index_t<I> in_place_index{}; #else using std::in_place; using std::in_place_index; using std::in_place_index_t; using std::in_place_t; using std::in_place_type; using std::in_place_type_t; #endif } // namespace cpp } // namespace carb
1,312
C
19.84127
96
0.723323
omniverse-code/kit/include/carb/cpp/StringView.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 C++14-compatible implementation of select functionality from C++ `<string_view>` library. #pragma once #include "../Defines.h" #include "../../omni/detail/PointerIterator.h" #include "TypeTraits.h" #include <algorithm> #include <string> #include <typeindex> // for std::hash #include <utility> namespace carb { namespace cpp { template <class CharT, class Traits> class basic_string_view; //! \cond DEV namespace detail { template <class T> struct IsBasicStringView : public std::false_type { }; template <class T, class Traits> struct IsBasicStringView<basic_string_view<T, Traits>> : public std::true_type { }; template <class T, class OpType, class = void> struct HasOperator : public std::false_type { }; template <class T, class OpType> struct HasOperator<T, OpType, void_t<decltype(std::declval<T>().operator OpType())>> : public std::true_type { }; template <class CharT, class T> struct IsCharArrayLiteral : public std::false_type { }; template <class CharT, size_t N> struct IsCharArrayLiteral<CharT, const CharT (&)[N]> : public std::true_type { }; // GCC instantiates some functions always so they cannot use static_assert, but throwing an exception is allowed from a // constexpr function (which will act as a compile failure if constexpr) so fall back to that. #if CARB_EXCEPTIONS_ENABLED # define CARB_ALWAYS_FAIL(msg) throw std::out_of_range(msg) # define CARB_THROW_OR_CHECK(check, msg) \ if (!CARB_LIKELY(check)) \ throw std::out_of_range(msg) #else # define CARB_THROW_OR_CHECK(check, msg) CARB_CHECK((check), msg) # if CARB_COMPILER_MSC # define CARB_ALWAYS_FAIL(msg) static_assert(false, msg) # else # define CARB_ALWAYS_FAIL(msg) CARB_FATAL_UNLESS(false, msg) # endif #endif } // namespace detail //! \endcond DEV /** * The class template basic_string_view describes an object that can refer to a constant contiguous sequence of elements * with the first element of the sequence at position zero. * * This implementation of \c string_view is a guaranteed @rstref{ABI- and interop-safe <abi-compatibility>} type. * * @see https://en.cppreference.com/w/cpp/string/basic_string_view * @tparam CharT character type * @tparam Traits A traits class specifying the operations on the character type. Like for `std::basic_string`, * `Traits::char_type` must name the same type as `CharT` or the program is ill-formed. */ template <class CharT, class Traits = std::char_traits<CharT>> class CARB_VIZ basic_string_view { public: //! `Traits` using traits_type = Traits; //! `CharT` using value_type = CharT; //! `CharT*` using pointer = CharT*; //! `const CharT*` using const_pointer = const CharT*; //! `CharT&` using reference = CharT&; //! `const CharT&` using const_reference = const CharT&; //! implementation defined constant LegacyRandomAccessIterator and LegacyContiguousIterator whose value_type //! is CharT. using const_iterator = omni::detail::PointerIterator<const_pointer, basic_string_view>; //! `const_iterator` //! \note `iterator` and `const_iterator` are the same type because string views are views into constant character //! sequences. using iterator = const_iterator; //! `std::reverse_iterator<const_iterator>` using const_reverse_iterator = std::reverse_iterator<const_iterator>; //! `const_reverse_iterator` using reverse_iterator = const_reverse_iterator; //! `std::size_t` using size_type = std::size_t; //! `std::ptrdiff_t` using difference_type = std::ptrdiff_t; //! Special value. The exact meaning depends on the context. static constexpr size_type npos = size_type(-1); //! Constructs a basic_string_view. //! \details Constructs an empty basic_string_view. After construction, \ref data() is equal to `nullptr` and //! \ref size() is equal to `0`. constexpr basic_string_view() noexcept = default; //! Constructs a basic_string_view. //! \details Constructs a view of the same content as \p other. After construction, \ref data() is equal to //! `other.data()` and \ref size() is equal to `other.size()`. //! @param other The string view to copy. constexpr basic_string_view(const basic_string_view& other) noexcept = default; //! Constructs a basic_string_view. //! \details Constructs a view of the first count characters of the character array starting with the element //! pointed by \p s. \p s can contain null characters. The behavior is undefined if `[s, s + count)` is not a valid //! range (even though the constructor may not access any of the elements of this range). After construction, //! \ref data() is equal to \p s, and \ref size() is equal to \p count. //! @param s The character array to view. //! @param count The number of characters in \p s to view. constexpr basic_string_view(const CharT* s, size_type count) : m_data(s), m_count(count) { } //! Constructs a basic_string_view. //! \details Constructs a view of the null-terminated character string pointed to by \p s, not including the //! terminating null character. The length of the view is determined as if by `Traits::length(s)`. The behavior is //! undefined if `[s, s + Traits::length(s))` is not a valid range. After construction, \ref data() is equal to //! \p s, and \ref size() is equal to `Traits::length(s)`. //! \note As a Carbonite extension, this constructor will not participate in overload resolution if \p s is a //! literal `CharT` array. Instead, see \ref basic_string_view(const CharT(&literal)[N]). //! @param s The null-terminated character string to view. #ifdef DOXYGEN_BUILD constexpr basic_string_view(const CharT* s) : m_data(s), m_count(traits_type::length(s)) #else template <class T, std::enable_if_t<!detail::IsCharArrayLiteral<CharT, T>::value && std::is_convertible<T, const_pointer>::value, bool> = false> constexpr basic_string_view(T&& s) : m_data(s), m_count(traits_type::length(s)) #endif { } //! Constructs a basic_string_view. //! \details Constructs a view of the literal string \p literal, not including the terminating null character. The //! length of the view is determined by `N - 1` as literal strings will have a terminating null character. After //! construction, \ref data() is equal to \p literal, and \ref size() is equal to `N - 1`. //! \note This constructor is a Carbonite extension and provided as an optimization. For `std::basic_string_view`, //! the \ref basic_string_view(const CharT*) constructor would be invoked instead. This allows string views to be //! constructed as a constant expression from string literals without using the `_sv` literal extension. //! @param literal A string literal to view. template <size_t N> constexpr basic_string_view(const CharT (&literal)[N]) noexcept : m_data(literal), m_count(N - 1) { } //! Constructs a basic_string_view. //! \details Constructs a basic_string_view over the range `[first, last)`. The behavior is undefined if //! `[first, last)` is not a valid range or if `It` is not a random-access iterator. This function differs //! significantly from the C++20 definition since the concepts of `contiguous_iterator` and `sized_sentinel_for` are //! not available. Since these concepts are not available until C++20, instead this function does not participate in //! overload resolution unless //! `std::iterator_traits<It>::iterator_category == std::random_access_iterator_tag`. Also \p first and \p last must //! be a matching iterator type. After construction, \ref data() is equal to `std::to_address(first)`, and //! \ref size() is equal to `last - first`. //! @param first Iterator to the beginning of the view. //! @param last Iterator to the end of the view (non-inclusive). template <class It CARB_NO_DOC( , std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false)> constexpr basic_string_view(It first, It last) : m_data(std::addressof(*first)), m_count(std::distance(first, last)) { } //! Constructs a basic_string_view. //! \details Constructs a basic_string_view over the "range" \p r. After construction \ref data() is equal to //! `r.data()` and \ref size() is equal to `r.size()`. //! @tparam R A range type. Since this implementation is for pre-C++20 and ranges are not available, this is an //! approximation of a `range`: This type must have `data()` and `size()` member functions that must be //! convertible to \ref const_pointer and \ref size_type respectively. (e.g. a `std::vector`). //! @param r The range to view. Behavior is undefined if `[range.data(), range.size())` is not a contiguous range or //! cannot be borrowed (i.e. it is a temporary that will expire leaving a dangling pointer). template <class R CARB_NO_DOC(, std::enable_if_t<cpp::detail::IsConvertibleRange<cpp::remove_cvref_t<R>, const_pointer>::value && !detail::IsBasicStringView<cpp::remove_cvref_t<R>>::value && !std::is_convertible<R, const char*>::value && !detail::HasOperator<cpp::remove_cvref_t<R>, basic_string_view>::value, bool> = false)> constexpr explicit basic_string_view(R&& r) : m_data(r.data()), m_count(r.size()) { } //! Implicit conversion from `std::basic_string` to basic_string_view. //! //! \details Construct a basic_string_view from a `std::basic_string`. The construction is implicit to mimic the //! behavior of <a //! href="https://en.cppreference.com/w/cpp/string/basic_string/operator_basic_string_view">std::basic_string<CharT,Traits,Allocator>::operator //! basic_string_view</a>. //! //! @tparam S An instance of `std::basic_string`. template <class S, class Allocator = typename S::allocator_type, std::enable_if_t<std::is_same<std::basic_string<CharT, Traits, Allocator>, std::decay_t<S>>::value, bool> = false> constexpr basic_string_view(const S& s) : m_data(s.data()), m_count(s.size()) { } //! basic_string_view cannot be constructed from nullptr. constexpr basic_string_view(std::nullptr_t) = delete; //! Assigns a view. //! @param view The view to replace `*this` with. //! @returns `*this` constexpr basic_string_view& operator=(const basic_string_view& view) noexcept = default; //! Returns an iterator to the beginning. //! @returns A \ref const_iterator to the first character of the view. constexpr const_iterator begin() const noexcept { return const_iterator(m_data); } //! Returns an iterator to the beginning. //! @returns A \ref const_iterator to the first character of the view. constexpr const_iterator cbegin() const noexcept { return const_iterator(m_data); } //! Returns an iterator to the end. //! @returns A \ref const_iterator to the character following the last character of the view. This character acts as //! a placeholder, attempting to access it results in undefined behavior. constexpr const_iterator end() const noexcept { return const_iterator(m_data + m_count); } //! Returns an iterator to the end. //! @returns A \ref const_iterator to the character following the last character of the view. This character acts as //! a placeholder, attempting to access it results in undefined behavior. constexpr const_iterator cend() const noexcept { return const_iterator(m_data + m_count); } //! Returns a reverse iterator to the beginning. //! @returns A \ref const_reverse_iterator to the first character of the reversed view. It corresponds to the last //! character of the non-reversed view. constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } //! Returns a reverse iterator to the beginning. //! @returns A \ref const_reverse_iterator to the first character of the reversed view. It corresponds to the last //! character of the non-reversed view. constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } //! Returns a reverse iterator to the end. //! @returns a \ref const_reverse_iterator to the character following the last character of the reversed view. It //! corresponds to the character preceding the first character of the non-reversed view. This character acts as a //! placeholder, attempting to access it results in undefined behavior. constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } //! Returns a reverse iterator to the end. //! @returns a \ref const_reverse_iterator to the character following the last character of the reversed view. It //! corresponds to the character preceding the first character of the non-reversed view. This character acts as a //! placeholder, attempting to access it results in undefined behavior. constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } //! Accesses the specified character. //! \details Returns a const reference to the character at the specified position. No bounds checking is performed: //! the behavior is undefined if `pos >= size()`. //! @param pos The position of the character to return. //! @returns A \ref const_reference to the requested character. constexpr const_reference operator[](size_type pos) const noexcept /*strengthened*/ { // Though the standard says no bounds checking we do assert CARB_ASSERT(pos < m_count); return m_data[pos]; } //! Accesses the specified character with bounds checking. //! \details Returns a const reference to the character at the specified position. Bounds checking is performed. //! \throws std::out_of_range Invalid access: \p pos is at or after \ref size(). //! @param pos The position of the character to return. //! @returns A \ref const_reference to the requested character constexpr const_reference at(size_type pos) const { CARB_THROW_OR_CHECK(pos < m_count, "pos >= size()"); return m_data[pos]; } //! Accesses the first character. //! @returns A \ref const_reference to the first character in the view. The behavior is undefined if empty() is //! `true`. constexpr const_reference front() const noexcept /*strengthened*/ { CARB_ASSERT(!empty(), "Undefined since empty()"); return *m_data; } //! Accesses the last character. //! @returns A \ref const_reference to the last character in the view. The behavior is undefined if empty() is //! `true`. constexpr const_reference back() const noexcept /*strengthened*/ { CARB_ASSERT(!empty(), "Undefined since empty()"); return m_data[m_count - 1]; } //! Returns a pointer to the first character of a view. //! \details Returns a pointer to the underlying character array. The pointer is such that the range //! `[data(), data() + size())` is valid and the values in it correspond to the values of the view. //! \note Unlike `std::basic_string::data()` and string literals, this function returns a pointer to a buffer that //! is not necessarily null-terminated, for example a substring view (e.g. from \ref remove_suffix()). Therefore, //! it is typically a mistake to pass `data()` to a routine that takes just a `const CharT*` and expects a null- //! terminated string. //! @returns A \ref const_pointer to the underlying character array. constexpr const_pointer data() const noexcept { return m_data; } //! Returns the number of characters. //! \details Returns the number of `CharT` characters in the view, i.e. `std::distance(begin(), end())`. //! @returns The number of `CharT` elements in the view. constexpr size_type size() const noexcept { return m_count; } //! Returns the number of characters. //! \details Returns the number of `CharT` characters in the view, i.e. `std::distance(begin(), end())`. //! @returns The number of `CharT` elements in the view. constexpr size_type length() const noexcept { return m_count; } //! Returns the maximum number of characters. //! \details The largest possible number of char-like objects that can be referred to by a basic_string_view. //! @returns Maximum number of characters. constexpr size_type max_size() const noexcept { return npos - 1; } //! Checks whether the view is empty. //! \details Checks if the view has no characters, i.e. whether \ref size() is `​0`​. //! @returns `true` if the view is empty, `false` otherwise. CARB_NODISCARD constexpr bool empty() const noexcept { return m_count == 0; } //! Shrinks the view by moving its start forward. //! \details Moves the start of the view forward by \p n characters. The behavior is undefined if `n > size()`. //! @param n Number of characters to remove from the start of the view. constexpr void remove_prefix(size_type n) noexcept /*strengthened*/ { CARB_ASSERT(n <= size(), "Undefined since n > size()"); m_data += n; m_count -= n; } //! Shrinks the view by moving its end backward. //! \details Moves the end of the view back by \p n characters. The behavior is undefined if `n > size()`. //! @param n Number of characters to remove from the end of the view. constexpr void remove_suffix(size_type n) noexcept /*strengthened*/ { CARB_ASSERT(n <= size(), "Undefined since n > size()"); m_count = m_count - n; } //! Swaps the contents. //! \details Exchanges the view with that of \p v. //! @param v View to swap with. constexpr void swap(basic_string_view& v) noexcept { std::swap(m_data, v.m_data); std::swap(m_count, v.m_count); } //! Copies characters. //! \details Copies the substring `[pos, pos + rcount)` to the character array pointed to by \p dest, where `rcount` //! is the smaller of \p count and `size() - pos`. Equivalent to `Traits::copy(dest, data() + pos, rcount)`. //! \throws std::out_of_range if `pos > size()`. //! @param dest Pointer to the destination character string. //! @param count Requested substring length. //! @param pos Position of first character. //! @returns Number of characters copied. constexpr size_type copy(CharT* dest, size_type count, size_type pos = 0) const { CARB_THROW_OR_CHECK(pos <= size(), "pos > size()"); size_type rcount = ::carb_min(count, size() - pos); Traits::copy(dest, m_data + pos, rcount); return rcount; } //! Returns a substring. //! \details Returns a view of the substring `[pos, pos + rcount)`, where `rcount` is the smaller of \p count and //! `size() - pos.` //! \throws std::out_of_range if `pos > size()`. //! @param pos Position of the first character. //! @param count Requested length. //! @returns View of the substring `[pos, pos + count)`. constexpr basic_string_view substr(size_t pos, size_t count = npos) const { CARB_THROW_OR_CHECK(pos <= size(), "pos > size()"); size_t rcount = ::carb_min(count, size() - pos); return { m_data + pos, rcount }; } //! Compares two views. //! \details The length rlen of the sequences to compare is the smaller of \ref size() and `v.size()`. The function //! compares the two views by calling `traits::compare(data(), v.data(), rlen)`, and returns as follows: //! * A value less than zero (`<0`) if: //! * `Traits::compare(data(), v.data(), rlen) < 0`, or //! * `Traits::compare(data(), v.data(), rlen) == 0` and `size() < v.size()`. //! * A value of zero (`0`) if: //! * `Traits::compare(data(), v.data(), rlen) == 0` and `size() == v.size()`. //! * A value greater than zero (`>0`) if: //! * `Traits::compare(data(), v.data(), rlen) > 0`, or //! * `Traits::compare(data(), v.data(), rlen) == 0` and `size() > v.size()`. //! @param v View to compare //! @returns A negative value if `*this` is less than the other character sequence, `0` if both character sequences //! are equal, positive value if `*this` is greater than the other character sequence. See above. constexpr int compare(basic_string_view v) const noexcept { size_type rlen = ::carb_min(size(), v.size()); int result = traits_type::compare(data(), v.data(), rlen); if (result != 0 || size() == v.size()) return result; return (size() < v.size()) ? -1 : 1; } //! Compares two views. //! \details Equivalent to `substr(pos1, count1).compare(v)`. //! \see compare(basic_string_view) const noexcept, substr() //! \throws std::out_of_range if `pos1 > size()`. //! @param pos1 Position of the first character in this view to compare. //! @param count1 Number of characters of this view to compare. //! @param v View to compare. //! @returns see \ref compare(basic_string_view) const noexcept constexpr int compare(size_type pos1, size_type count1, basic_string_view v) const { return substr(pos1, count1).compare(v); } //! Compares two views. //! \details Equivalent to `substr(pos1, count1).compare(v.substr(pos2, count2))`. //! \see compare(basic_string_view) const noexcept, substr() //! \throws std::out_of_range if `pos1 > size()` or if `pos2 > v.size()`. //! @param pos1 Position of the first character in this view to compare. //! @param count1 Number of characters of this view to compare. //! @param v View to compare. //! @param pos2 Position of the first character of the given view to compare. //! @param count2 Number of characters of the given view to compare. //! @returns see \ref compare(basic_string_view) const noexcept constexpr int compare(size_type pos1, size_type count1, basic_string_view v, size_type pos2, size_type count2) const { return substr(pos1, count1).compare(v.substr(pos2, count2)); } //! Compares two views. //! \details Equivalent to `compare(basic_string_view(s))`. //! \see compare(basic_string_view) const noexcept //! @param s Pointer to the null-terminated character string to compare to. //! @returns see \ref compare(basic_string_view) const noexcept constexpr int compare(const CharT* s) const { return compare(basic_string_view(s)); } //! Compares two views. //! \details Equivalent to `substr(pos1, count1).compare(basic_string_view(s))`. //! \see compare(basic_string_view) const noexcept, substr() //! \throws std::out_of_range if `pos1 > size()`. //! @param pos1 Position of the first character in this view to compare. //! @param count1 Number of characters of this view to compare. //! @param s Pointer to the null-terminated character string to compare to. //! @returns see \ref compare(basic_string_view) const noexcept constexpr int compare(size_type pos1, size_type count1, const CharT* s) const { return substr(pos1, count1).compare(basic_string_view(s)); } //! Compares two views. //! \details Equivalent to `substr(pos1, count1).compare(basic_string_view(s, count2))`. Behavior is undefined if //! `[s, s+count2)` is not a valid contiguous range. //! \see compare(basic_string_view) const noexcept, substr() //! \throws std::out_of_range if `pos1 > size()`. //! @param pos1 Position of the first character in this view to compare. //! @param count1 Number of characters of this view to compare. //! @param s Pointer to the character string to compare to. //! @param count2 Number of characters of \p s to compare. //! @returns see \ref compare(basic_string_view) const noexcept constexpr int compare(size_type pos1, size_type count1, const CharT* s, size_type count2) const { return substr(pos1, count1).compare(basic_string_view(s, count2)); } //! Checks if the string view starts with the given prefix. //! \details Effectively returns `substr(0, sv.size()) == sv`. //! @param sv A string view which may be a result of implicit conversion from `std::basic_string`. //! @returns `true` if the string view begins with the provided prefix, `false` otherwise. constexpr bool starts_with(basic_string_view sv) const noexcept { return substr(0, sv.size()) == sv; } //! Checks if the string view starts with the given prefix. //! \details Effectively returns `!empty() && Traits::eq(front(), ch)`. //! @param ch A single character. //! @returns `true` if the string view begins with the provided prefix, `false` otherwise. constexpr bool starts_with(CharT ch) const noexcept { return !empty() && traits_type::eq(front(), ch); } //! Checks if the string view starts with the given prefix. //! \details Effectively returns `starts_with(basic_string_view(s))`. //! @param s A null-terminated character string. //! @returns `true` if the string view begins with the provided prefix, `false` otherwise. constexpr bool starts_with(const CharT* s) const { return starts_with(basic_string_view(s)); } //! Checks if the string view ends with the given suffix. //! \details Effectively returns `size() >= sv.size() && compare(size() - sv.size(), npos, sv) == 0`. //! @param sv A string view which may be a result of implicit conversion from `std::basic_string`. //! @returns `true` if the string view ends with the provided suffix, `false` otherwise. constexpr bool ends_with(basic_string_view sv) const noexcept { return size() >= sv.size() && compare(size() - sv.size(), npos, sv) == 0; } //! Checks if the string view ends with the given suffix. //! \details Effectively returns `!empty() && Traits::eq(back(), ch)`. //! @param ch A single character. //! @returns `true` if the string view ends with the provided suffix, `false` otherwise. constexpr bool ends_with(CharT ch) const noexcept { return !empty() && traits_type::eq(back(), ch); } //! Checks if the string view ends with the given suffix. //! \details Effectively returns `ends_with(basic_string_view(s))`. //! @param s A null-terminated character string. //! @returns `true` if the string view ends with the provided suffix, `false` otherwise. constexpr bool ends_with(const CharT* s) const { return ends_with(basic_string_view(s)); } //! Checks if the string view contains the given substring or character. //! \details Effectively `find(sv) != npos`. //! @param sv A string view. //! @returns `true` if the string view contains the provided substring, `false` otherwise. constexpr bool contains(basic_string_view sv) const noexcept { return find(sv) != npos; } //! Checks if the string view contains the given substring or character. //! \details Effectively `find(c) != npos`. //! @param c A single character. //! @returns `true` if the string view contains the provided substring, `false` otherwise. constexpr bool contains(CharT c) const noexcept { return find(c) != npos; } //! Checks if the string view contains the given substring or character. //! \details Effectively `find(s) != npos`. //! @param s A null-terminated character string. //! @returns `true` if the string view contains the provided substring, `false` otherwise. constexpr bool contains(const CharT* s) const { return find(s) != npos; } //! Find characters in the view. //! \details Finds the first substring equal to the given character sequence. Complexity is `O(size() * v.size())` //! at worst. //! @param v View to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type find(basic_string_view v, size_type pos = 0) const noexcept { // [strings.view.find] in the Standard. size_type xpos = pos; while (xpos + v.size() <= size()) { if (traits_type::compare(v.data(), data() + xpos, v.size()) == 0) { return xpos; } xpos++; } return npos; } //! Find characters in the view. //! \details Finds the first substring equal to the given character sequence. Equivalent to //! `find(basic_string_view(std::addressof(ch), 1))`. Complexity is `O(size())` at worst. //! @param ch Character to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type find(CharT ch, size_type pos = 0) const noexcept { size_type xpos = pos; while (xpos < size()) { if (traits_type::eq(data()[xpos], ch)) { return xpos; } xpos++; } return npos; } //! Find characters in the view. //! \details Finds the first substring equal to the given character sequence. Equivalent to //! `find(basic_string_view(s, count), pos)`. Complexity is `O(size() * count)` at worst. //! @param s Pointer to a character string to search for. //! @param pos Position at which to start the search. //! @param count Length of substring to search for. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type find(const CharT* s, size_type pos, size_type count) const { return find(basic_string_view(s, count), pos); } //! Find characters in the view. //! \details Finds the first substring equal to the given character sequence. Equivalent to //! `find(basic_string_view(s), pos)`. Complexity is `O(size() * Traits::length(s))` at worst. //! @param s Pointer to a character string to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type find(const CharT* s, size_type pos = 0) const { return find(basic_string_view(s), pos); } //! Find the last occurrence of a substring. //! \details Finds the last substring equal to the given character sequence. Search begins at \p pos, i.e. the found //! substring must not being is a position following \p pos. If \ref npos or any value not smaller than `size()-1` //! is passed as pos, the whole string will be searched. Complexity is `O(size() * v.size())` at worst. //! @param v View to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type rfind(basic_string_view v, size_type pos = npos) const noexcept { if (v.size() > size()) { return npos; } // Clip the position to our string length. for (size_type xpos = ::carb_min(pos, size() - v.size());; xpos--) { if (traits_type::compare(v.data(), data() + xpos, v.size()) == 0) { return xpos; } if (xpos == 0) { break; } } return npos; } //! Find the last occurrence of a substring. //! \details Finds the last substring equal to the given character sequence. Search begins at \p pos, i.e. the found //! substring must not being is a position following \p pos. If \ref npos or any value not smaller than `size()-1` //! is passed as pos, the whole string will be searched. Equivalent to //! `rfind(basic_string_view(std::addressof(ch), 1), pos)`. Complexity is `O(size())` at worst. //! @param ch Character to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type rfind(CharT ch, size_type pos = npos) const noexcept { if (empty()) { return npos; } // Clip the position to our string length. for (size_type xpos = ::carb_min(pos, size() - 1);; xpos--) { if (traits_type::eq(ch, data()[xpos])) { return xpos; } if (xpos == 0) { break; } } return npos; } //! Find the last occurrence of a substring. //! \details Finds the last substring equal to the given character sequence. Search begins at \p pos, i.e. the found //! substring must not being is a position following \p pos. If \ref npos or any value not smaller than `size()-1` //! is passed as pos, the whole string will be searched. Equivalent to `rfind(basic_string_view(s, count), pos)`. //! Complexity is `O(size() * count)` at worst. //! @param s Pointer to a character string to search for. //! @param pos Position at which to start the search. //! @param count Length of substring to search for. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type rfind(const CharT* s, size_type pos, size_type count) const { return rfind(basic_string_view(s, count), pos); } //! Find the last occurrence of a substring. //! \details Finds the last substring equal to the given character sequence. Search begins at \p pos, i.e. the found //! substring must not being is a position following \p pos. If \ref npos or any value not smaller than `size()-1` //! is passed as pos, the whole string will be searched. Equivalent to `rfind(basic_string_view(s), pos)`. //! Complexity is `O(size() * Traits::length(s))` at worst. //! @param s Pointer to a null-terminated character string to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character of the found substring, or \ref npos if no such substring is found. constexpr size_type rfind(const CharT* s, size_type pos = npos) const { return rfind(basic_string_view(s), pos); } //! Find first occurrence of characters. //! \details Finds the first occurrence of any of the characters of \p v in this view, starting as position \p pos. //! Complexity is `O(size() * v.size())` at worst. //! @param v View to search for. //! @param pos Position at which to start the search. //! @returns Position of the first occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_first_of(basic_string_view v, size_type pos = 0) const noexcept { if (v.empty()) { return npos; } size_type xpos = pos; while (xpos < size()) { if (v.find(m_data[xpos]) != npos) { return xpos; } xpos++; } return npos; } //! Find first occurrence of characters. //! \details Equivalent to `find_first_of(basic_string_view(std::addressof(ch), 1), pos)`. //! Complexity is `O(size())` at worst. //! \see find_first_of(basic_string_view,size_type) const noexcept //! @param ch Character to search for. //! @param pos Position at which to start the search. //! @returns Position of the first occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_first_of(CharT ch, size_type pos = 0) const noexcept { return find(ch, pos); } //! Find first occurrence of characters. //! \details Equivalent to `find_first_of(basic_string_view(s, count), pos)`. Complexity is `O(size() * count)` at //! worst. //! \see find_first_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a string of characters to search for. //! @param pos Position at which to start the search. //! @param count Length of the string of characters to search for. //! @returns Position of the first occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_first_of(const CharT* s, size_type pos, size_type count) const { return find_first_of(basic_string_view(s, count), pos); } //! Find first occurrence of characters. //! \details Equivalent to `find_first_of(basic_string_view(s, Traits::length(s)), pos)`. Complexity is //! `O(size() * count)` at worst. //! \see find_first_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a null-terminated string of characters to search for. //! @param pos Position at which to start the search. //! @returns Position of the first occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_first_of(const CharT* s, size_type pos = 0) const { return find_first_of(basic_string_view(s), pos); } //! Find last occurrence of characters. //! \details Finds the last character equal to one of characters in the given character sequence. Exact search //! algorithm is not specified. The search considers only the interval `[0, pos]`. If the character is not present //! in the interval, \ref npos will be returned. Complexity is `O(size() * v.size())` at worst. //! @param v View to search for. //! @param pos Position at which the search is to finish. //! @returns Position of the last occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_last_of(basic_string_view v, size_type pos = npos) const noexcept { if (v.empty() || empty()) { return npos; } // Clip the position to our string length. for (size_type xpos = ::carb_min(pos, size() - 1);; xpos--) { if (v.find(data()[xpos]) != npos) { return xpos; } if (xpos == 0) { break; } } return npos; } //! Find last occurrence of characters. //! \details Finds the last character equal to one of characters in the given character sequence. Exact search //! algorithm is not specified. The search considers only the interval `[0, pos]`. If the character is not present //! in the interval, \ref npos will be returned. Equivalent to //! `find_last_of(basic_string_view(std::addressof(ch), 1), pos)`. Complexity is `O(size())` at worst. //! \see find_last_of(basic_string_view,size_type) const noexcept //! @param ch Character to search for. //! @param pos Position at which the search is to finish. //! @returns Position of the last occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_last_of(CharT ch, size_type pos = npos) const noexcept { return rfind(ch, pos); } //! Find last occurrence of characters. //! \details Finds the last character equal to one of characters in the given character sequence. Exact search //! algorithm is not specified. The search considers only the interval `[0, pos]`. If the character is not present //! in the interval, \ref npos will be returned. Equivalent to //! `find_last_of(basic_string_view(s, count), pos)`. Complexity is `O(size() * count)` at worst. //! \see find_last_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a string of characters to search for. //! @param pos Position at which the search is to finish. //! @param count Length of the string of characters to search for. //! @returns Position of the last occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_last_of(const CharT* s, size_type pos, size_type count) const { return find_last_of(basic_string_view(s, count), pos); } //! Find last occurrence of characters. //! \details Finds the last character equal to one of characters in the given character sequence. Exact search //! algorithm is not specified. The search considers only the interval `[0, pos]`. If the character is not present //! in the interval, \ref npos will be returned. Equivalent to //! `find_last_of(basic_string_view(s), pos)`. Complexity is `O(size() * Traits::length(s))` at worst. //! \see find_last_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a null-terminated string of characters to search for. //! @param pos Position at which the search is to finish. //! @returns Position of the last occurrence of any character of the substring, or \ref npos if no such character //! is found. constexpr size_type find_last_of(const CharT* s, size_type pos = npos) const { return find_last_of(basic_string_view(s), pos); } //! Find first absence of characters. //! \details Finds the first character not equal to any of the characters in the given character sequence. //! Complexity is `O(size() * v.size())` at worst. //! @param v View to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_first_not_of(basic_string_view v, size_type pos = 0) const noexcept { size_type xpos = pos; while (xpos < size()) { if (v.find(data()[xpos]) == npos) { return xpos; } xpos++; } return npos; } //! Find first absence of characters. //! \details Finds the first character not equal to any of the characters in the given character sequence. //! Equivalent to `find_first_not_of(basic_string_view(std::addressof(ch), 1), pos)`. Complexity is `O(size())` at //! worst. //! \see find_first_not_of(basic_string_view,size_type) const noexcept //! @param ch Character to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_first_not_of(CharT ch, size_type pos = 0) const noexcept { size_type xpos = pos; while (xpos < size()) { if (!traits_type::eq(ch, m_data[xpos])) { return xpos; } xpos++; } return npos; } //! Find first absence of characters. //! \details Finds the first character not equal to any of the characters in the given character sequence. //! Equivalent to `find_first_not_of(basic_string_view(s, count), pos)`. Complexity is `O(size() * count)` at worst. //! \see find_first_not_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a string of characters to search for. //! @param pos Position at which to start the search. //! @param count Length of the string of characters to compare. //! @returns Position of the first character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_first_not_of(const CharT* s, size_type pos, size_type count) const { return find_first_not_of(basic_string_view(s, count), pos); } //! Find first absence of characters. //! \details Finds the first character not equal to any of the characters in the given character sequence. //! Equivalent to `find_first_not_of(basic_string_view(s), pos)`. Complexity is `O(size() * Traits::length(s))` at //! worst. //! \see find_first_not_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a null-terminated string of characters to search for. //! @param pos Position at which to start the search. //! @returns Position of the first character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_first_not_of(const CharT* s, size_type pos = 0) const { return find_first_not_of(basic_string_view(s), pos); } //! Find last absence of characters. //! \details Finds the last character not equal to any of the characters in the given character sequence. The search //! considers only the interval `[0, pos]`. Complexity is `O(size() * v.size())` at worst. //! @param v View to search for. //! @param pos Position at which to start the search. //! @returns Position of the last character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_last_not_of(basic_string_view v, size_type pos = 0) const noexcept { if (empty()) { return npos; } // Clip the position to our string length. for (size_type xpos = ::carb_min(pos, size() - 1);; xpos--) { if (v.find(data()[xpos]) == npos) { return xpos; } if (xpos == 0) { break; } } return npos; } //! Find last absence of characters. //! \details Finds the last character not equal to any of the characters in the given character sequence. The search //! considers only the interval `[0, pos]`. Equivalent to //! `find_last_not_of(basic_string_view(std::addressof(ch), 1), pos)`, Complexity is `O(size())` at worst. //! \see find_last_not_of(basic_string_view,size_type) const noexcept //! @param ch Character to search for. //! @param pos Position at which to start the search. //! @returns Position of the last character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_last_not_of(CharT ch, size_type pos = 0) const noexcept { if (empty()) { return npos; } // Clip the position to our string length. for (size_type xpos = ::carb_min(pos, size() - 1);; xpos--) { if (!traits_type::eq(data()[xpos], ch)) { return xpos; } if (xpos == 0) { break; } } return npos; } //! Find last absence of characters. //! \details Finds the last character not equal to any of the characters in the given character sequence. The search //! considers only the interval `[0, pos]`. Equivalent to //! `find_last_not_of(basic_string_view(s, count), pos)`, Complexity is `O(size() * count)` at worst. //! \see find_last_not_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a string of characters to compare. //! @param pos Position at which to start the search. //! @param count Length of the string of characters to compare. //! @returns Position of the last character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_last_not_of(const CharT* s, size_type pos, size_type count) const { return find_last_not_of(basic_string_view(s, count), pos); } //! Find last absence of characters. //! \details Finds the last character not equal to any of the characters in the given character sequence. The search //! considers only the interval `[0, pos]`. Equivalent to //! `find_last_not_of(basic_string_view(s), pos)`, Complexity is `O(size() * Traits::length(s))` at worst. //! \see find_last_not_of(basic_string_view,size_type) const noexcept //! @param s Pointer to a null-terminated string of characters to compare. //! @param pos Position at which to start the search. //! @returns Position of the last character not equal to any of the characters in the given string, or \ref npos if //! no such character is found. constexpr size_type find_last_not_of(const CharT* s, size_type pos = 0) const { return find_last_not_of(basic_string_view(s), pos); } private: CARB_VIZ const_pointer m_data = nullptr; CARB_VIZ size_type m_count = 0; }; //! basic_string_view<char> //! @see basic_string_view using string_view = basic_string_view<char>; //! basic_string_view<wchar_t> //! @see basic_string_view using wstring_view = basic_string_view<wchar_t>; #if CARB_HAS_CPP20 //! basic_string_view<char8_t> //! @see basic_string_view using u8string_view = basic_string_view<char8_t>; #endif //! basic_string_view<char16_t> //! @see basic_string_view using u16string_view = basic_string_view<char16_t>; //! basic_string_view<char32_t> //! @see basic_string_view using u32string_view = basic_string_view<char32_t>; // Ensure these for ABI safety //! \cond SKIP #define CARB_IMPL_ENSURE_ABI(cls) \ static_assert(std::is_standard_layout<cls>::value, #cls " must be standard layout"); \ static_assert(std::is_trivially_copyable<cls>::value, #cls " must be trivially copyable"); /* C++23 requirement */ \ static_assert(sizeof(cls) == (2 * sizeof(size_t)), #cls "ABI change violation") CARB_IMPL_ENSURE_ABI(string_view); CARB_IMPL_ENSURE_ABI(wstring_view); CARB_IMPL_ENSURE_ABI(u16string_view); CARB_IMPL_ENSURE_ABI(u32string_view); #undef CARB_IMPL_ENSURE_ABI //! \endcond SKIP //! @defgroup string_view_compare Lexicographically compare two string views. //! \details. All comparisons are done via the \ref basic_string_view::compare() member function (which itself is //! defined in terms of `Traits::compare()`): //! * Two views are equal if both the size of \p a and \p b are equal and each character in \p a has an equivalent //! character in \p b at the same position. //! * The ordering comparisons are done lexicographically -- the comparison is performed by a function equivalent to //! `std::lexicographical_compare`. //! Complexity is linear in the size of the views. //! @{ //! Lexicographically compare two string views. template <class CharT, class Traits = std::char_traits<CharT>> bool operator==(const basic_string_view<CharT, Traits>& a, const basic_string_view<CharT, Traits>& b) { return a.compare(b) == 0; } //! Lexicographically compare two string views. template <class CharT, class Traits = std::char_traits<CharT>> bool operator!=(const basic_string_view<CharT, Traits>& a, const basic_string_view<CharT, Traits>& b) { return a.compare(b) != 0; } //! Lexicographically compare two string views. template <class CharT, class Traits = std::char_traits<CharT>> bool operator<(const basic_string_view<CharT, Traits>& a, const basic_string_view<CharT, Traits>& b) { return a.compare(b) < 0; } //! Lexicographically compare two string views. template <class CharT, class Traits = std::char_traits<CharT>> bool operator<=(const basic_string_view<CharT, Traits>& a, const basic_string_view<CharT, Traits>& b) { return a.compare(b) <= 0; } //! Lexicographically compare two string views. template <class CharT, class Traits = std::char_traits<CharT>> bool operator>(const basic_string_view<CharT, Traits>& a, const basic_string_view<CharT, Traits>& b) { return a.compare(b) > 0; } //! Lexicographically compare two string views. template <class CharT, class Traits = std::char_traits<CharT>> bool operator>=(const basic_string_view<CharT, Traits>& a, const basic_string_view<CharT, Traits>& b) { return a.compare(b) >= 0; } // [string.view.comparison] //! Lexicographically compare two string views. inline bool operator==(const char* t, string_view sv) { return string_view(t) == sv; } //! Lexicographically compare two string views. inline bool operator==(string_view sv, const char* t) { return sv == string_view(t); } //! Lexicographically compare two string views. inline bool operator!=(const char* t, string_view sv) { return string_view(t) != sv; } //! Lexicographically compare two string views. inline bool operator!=(string_view sv, const char* t) { return sv != string_view(t); } //! Lexicographically compare two string views. inline bool operator<(const char* t, string_view sv) { return string_view(t) < sv; } //! Lexicographically compare two string views. inline bool operator<(string_view sv, const char* t) { return sv < string_view(t); } //! Lexicographically compare two string views. inline bool operator<=(const char* t, string_view sv) { return string_view(t) <= sv; } //! Lexicographically compare two string views. inline bool operator<=(string_view sv, const char* t) { return sv <= string_view(t); } //! Lexicographically compare two string views. inline bool operator>(const char* t, string_view sv) { return string_view(t) > sv; } //! Lexicographically compare two string views. inline bool operator>(string_view sv, const char* t) { return sv > string_view(t); } //! Lexicographically compare two string views. inline bool operator>=(const char* t, string_view sv) { return string_view(t) >= sv; } //! Lexicographically compare two string views. inline bool operator>=(string_view sv, const char* t) { return sv >= string_view(t); } //! Lexicographically compare two string views. inline bool operator==(const wchar_t* t, wstring_view sv) { return wstring_view(t) == sv; } //! Lexicographically compare two string views. inline bool operator==(wstring_view sv, const wchar_t* t) { return sv == wstring_view(t); } //! Lexicographically compare two string views. inline bool operator!=(const wchar_t* t, wstring_view sv) { return wstring_view(t) != sv; } //! Lexicographically compare two string views. inline bool operator!=(wstring_view sv, const wchar_t* t) { return sv != wstring_view(t); } //! Lexicographically compare two string views. inline bool operator<(const wchar_t* t, wstring_view sv) { return wstring_view(t) < sv; } //! Lexicographically compare two string views. inline bool operator<(wstring_view sv, const wchar_t* t) { return sv < wstring_view(t); } //! Lexicographically compare two string views. inline bool operator<=(const wchar_t* t, wstring_view sv) { return wstring_view(t) <= sv; } //! Lexicographically compare two string views. inline bool operator<=(wstring_view sv, const wchar_t* t) { return sv <= wstring_view(t); } //! Lexicographically compare two string views. inline bool operator>(const wchar_t* t, wstring_view sv) { return wstring_view(t) > sv; } //! Lexicographically compare two string views. inline bool operator>(wstring_view sv, const wchar_t* t) { return sv > wstring_view(t); } //! Lexicographically compare two string views. inline bool operator>=(const wchar_t* t, wstring_view sv) { return wstring_view(t) >= sv; } //! Lexicographically compare two string views. inline bool operator>=(wstring_view sv, const wchar_t* t) { return sv >= wstring_view(t); } //! Lexicographically compare two string views. inline bool operator==(const char16_t* t, u16string_view sv) { return u16string_view(t) == sv; } //! Lexicographically compare two string views. inline bool operator==(u16string_view sv, const char16_t* t) { return sv == u16string_view(t); } //! Lexicographically compare two string views. inline bool operator!=(const char16_t* t, u16string_view sv) { return u16string_view(t) != sv; } //! Lexicographically compare two string views. inline bool operator!=(u16string_view sv, const char16_t* t) { return sv != u16string_view(t); } //! Lexicographically compare two string views. inline bool operator<(const char16_t* t, u16string_view sv) { return u16string_view(t) < sv; } //! Lexicographically compare two string views. inline bool operator<(u16string_view sv, const char16_t* t) { return sv < u16string_view(t); } //! Lexicographically compare two string views. inline bool operator<=(const char16_t* t, u16string_view sv) { return u16string_view(t) <= sv; } //! Lexicographically compare two string views. inline bool operator<=(u16string_view sv, const char16_t* t) { return sv <= u16string_view(t); } //! Lexicographically compare two string views. inline bool operator>(const char16_t* t, u16string_view sv) { return u16string_view(t) > sv; } //! Lexicographically compare two string views. inline bool operator>(u16string_view sv, const char16_t* t) { return sv > u16string_view(t); } //! Lexicographically compare two string views. inline bool operator>=(const char16_t* t, u16string_view sv) { return u16string_view(t) >= sv; } //! Lexicographically compare two string views. inline bool operator>=(u16string_view sv, const char16_t* t) { return sv >= u16string_view(t); } //! Lexicographically compare two string views. inline bool operator==(const char32_t* t, u32string_view sv) { return u32string_view(t) == sv; } //! Lexicographically compare two string views. inline bool operator==(u32string_view sv, const char32_t* t) { return sv == u32string_view(t); } //! Lexicographically compare two string views. inline bool operator!=(const char32_t* t, u32string_view sv) { return u32string_view(t) != sv; } //! Lexicographically compare two string views. inline bool operator!=(u32string_view sv, const char32_t* t) { return sv != u32string_view(t); } //! Lexicographically compare two string views. inline bool operator<(const char32_t* t, u32string_view sv) { return u32string_view(t) < sv; } //! Lexicographically compare two string views. inline bool operator<(u32string_view sv, const char32_t* t) { return sv < u32string_view(t); } //! Lexicographically compare two string views. inline bool operator<=(const char32_t* t, u32string_view sv) { return u32string_view(t) <= sv; } //! Lexicographically compare two string views. inline bool operator<=(u32string_view sv, const char32_t* t) { return sv <= u32string_view(t); } //! Lexicographically compare two string views. inline bool operator>(const char32_t* t, u32string_view sv) { return u32string_view(t) > sv; } //! Lexicographically compare two string views. inline bool operator>(u32string_view sv, const char32_t* t) { return sv > u32string_view(t); } //! Lexicographically compare two string views. inline bool operator>=(const char32_t* t, u32string_view sv) { return u32string_view(t) >= sv; } //! Lexicographically compare two string views. inline bool operator>=(u32string_view sv, const char32_t* t) { return sv >= u32string_view(t); } //! @} // Note that literal suffixes that don't start with _ are reserved, in addition we probably don't want to compete with // the C++17 suffix either. //! Creates a string view of a character array literal. //! \note The literal suffix operator `sv` is reserved by C++, so this is `_sv`. //! @param str Pointer to the beginning of the raw character array literal. //! @param len Length of the raw character array literal. //! @returns The \ref basic_string_view literal. constexpr string_view operator""_sv(const char* str, std::size_t len) noexcept { return string_view(str, len); } // C++ 20 and above have char8_t. #if CARB_HAS_CPP20 //! \copydoc operator""_sv(const char*,std::size_t) noexcept constexpr u8string_view operator""_sv(const char8_t* str, std::size_t len) noexcept { return u8string_view(str, len); } #endif //! \copydoc operator""_sv(const char*,std::size_t) noexcept constexpr u16string_view operator""_sv(const char16_t* str, std::size_t len) noexcept { return u16string_view(str, len); } //! \copydoc operator""_sv(const char*,std::size_t) noexcept constexpr u32string_view operator""_sv(const char32_t* str, std::size_t len) noexcept { return u32string_view(str, len); } //! \copydoc operator""_sv(const char*,std::size_t) noexcept constexpr wstring_view operator""_sv(const wchar_t* str, std::size_t len) noexcept { return wstring_view(str, len); } // Non-standard function? //! Swaps two string views. //! @param a String view to swap. //! @param b String view to swap. template <class CharT, class Traits> constexpr void swap(carb::cpp::basic_string_view<CharT, Traits>& a, carb::cpp::basic_string_view<CharT, Traits>& b) noexcept { a.swap(b); }; } // namespace cpp } // namespace carb //! Hash support for string views. template <class CharT, class Traits> struct std::hash<carb::cpp::basic_string_view<CharT, Traits>> { //! @private size_t operator()(const carb::cpp::basic_string_view<CharT, Traits>& v) const { return carb::hashBuffer(v.data(), (uintptr_t)(v.data() + v.size()) - (uintptr_t)(v.data())); } }; #undef CARB_ALWAYS_FAIL #undef CARB_THROW_OR_CHECK
62,925
C
40.208906
147
0.65122
omniverse-code/kit/include/carb/cpp/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 C++14-compatible implementation of select functionality from C++ `<memory>` library. #pragma once #include "../Defines.h" #include <memory> #include <type_traits> namespace carb { namespace cpp { #if !CARB_HAS_CPP17 || defined DOXYGEN_BUILD //! Get the address of \a arg, even if \c operator& is overloaded. This is generally only useful in memory management //! functions -- \c to_address is almost always preferable. //! //! \note //! This function is \c constexpr even in C++14 mode. template <typename T> constexpr T* addressof(T& arg) noexcept { return __builtin_addressof(arg); } //! Taking the address of a \c const rvalue is never correct. template <typename T> T const* addressof(T const&&) = delete; #else using std::addressof; #endif //! Call the destructor of \a p. template <typename T> constexpr std::enable_if_t<!std::is_array<T>::value> destroy_at(T* const p) noexcept(std::is_nothrow_destructible<T>::value) { p->~T(); } //! Call the destructor of all \a array elements. //! //! \tparam T The element type of the array must have a \c noexcept destructor. There no mechanism to safely use this //! function if an element throws. This is a departure from the C++20, wherein an exception thrown from a //! destructor will result in either \c std::terminate or an "implementation defined manner." Instead, we force //! you to handle potential exceptions by disallowing it. template <typename T, std::size_t N> constexpr void destroy_at(T (*array)[N]) noexcept { static_assert(noexcept(carb::cpp::destroy_at(array[0])), "destroy_at for array requires elements to have noexcept destructor"); for (T& elem : *array) { carb::cpp::destroy_at(carb::cpp::addressof(elem)); } } #if !CARB_HAS_CPP20 || defined DOXYGEN_BUILD //! Construct a \c T in \a place using the provided \a args. //! //! \note //! This differs from the C++20 definition by not being \c constexpr, since placement new is not \c constexpr before //! C++20. When C++20 is enabled, this function disappears in favor of \c std::construct_at. template <typename T, typename... TArgs> T* construct_at(T* place, TArgs&&... args) noexcept CARB_NO_DOC((noexcept(::new (static_cast<void*>(place)) T(std::forward<TArgs>(args)...)))) { return ::new (static_cast<void*>(place)) T(std::forward<TArgs>(args)...); } #else using std::construct_at; #endif } // namespace cpp } // namespace carb
2,908
C
29.946808
124
0.698418
omniverse-code/kit/include/carb/cpp/TypeTraits.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 C++14-compatible implementation of select functionality from C++ `<type_traits>` library. #pragma once #include "../Defines.h" #include "../detail/NoexceptType.h" #include "detail/ImplInvoke.h" #include <functional> #include <type_traits> namespace carb { namespace cpp { CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE() //! An integral constant with \c bool type and value \c B. template <bool B> using bool_constant = std::integral_constant<bool, B>; //! \cond DEV namespace detail { template <typename... B> struct conjunction_impl; template <> struct conjunction_impl<> : std::true_type { }; template <typename B> struct conjunction_impl<B> : B { }; template <typename BHead, typename... BRest> struct conjunction_impl<BHead, BRest...> : std::conditional_t<bool(BHead::value), conjunction_impl<BRest...>, BHead> { }; } // namespace detail //! \endcond //! A conjunction is the logical \e and of all \c B traits. //! //! An empty list results in a \c true value. This meta-function is short-circuiting. //! //! \tparam B The series of traits to evaluate the \c value member of. Each \c B must have a member constant \c value //! which is convertible to \c bool. Use of carb::cpp::bool_constant is helpful here. template <typename... B> struct conjunction : detail::conjunction_impl<B...> { }; //! \cond DEV namespace detail { template <typename... B> struct disjunction_impl; template <> struct disjunction_impl<> : std::false_type { }; template <typename B> struct disjunction_impl<B> : B { }; template <typename BHead, typename... BRest> struct disjunction_impl<BHead, BRest...> : std::conditional_t<bool(BHead::value), BHead, disjunction_impl<BRest...>> { }; } // namespace detail //! \endcond //! A disjunction is the logical \e or of all \c B traits. //! //! An empty list results in a \c false value. This metafunction is short-circuiting. //! //! \tparam B The series of traits to evaluate the \c value member of. Each \c B must have a member constant \c value //! which is convertible to \c bool. Use of \ref cpp::bool_constant is helpful here. template <typename... B> struct disjunction : detail::disjunction_impl<B...> { }; //! A logical \e not of \c B trait. //! //! \tparam B The trait to evaluate the \c value member of. This must have a member constant \c value which is //! convertible to \c bool. Use of \ref cpp::bool_constant is helpful here. template <typename B> struct negation : bool_constant<!bool(B::value)> { }; //! Void type template <class...> using void_t = void; using std::is_convertible; using std::is_void; //! \cond DEV namespace detail { // Base case matches where either `To` or `From` is void or if `is_convertible<From, To>` is false. The conversion in // this case is only non-throwing if both `From` and `To` are `void`. template <typename From, typename To, typename = void> struct is_nothrow_convertible_impl : conjunction<is_void<From>, is_void<To>> { }; // If neither `From` nor `To` are void and `From` is convertible to `To`, then we test that such a conversion is // non-throwing. template <typename From, typename To> struct is_nothrow_convertible_impl< From, To, std::enable_if_t<conjunction<negation<is_void<From>>, negation<is_void<To>>, is_convertible<From, To>>::value>> { static void test(To) noexcept; static constexpr bool value = noexcept(test(std::declval<From>())); }; } // namespace detail //! \endcond //! Determine if \c From can be implicitly-converted to \c To without throwing an exception. //! //! This is equivalent to the C++20 \c std::is_nothrow_convertible meta query. While added in C++20, it is required for //! the C++17 \ref is_nothrow_invocable_r meta query. template <typename From, typename To> struct is_nothrow_convertible : bool_constant<detail::is_nothrow_convertible_impl<From, To>::value> { }; //! \cond DEV namespace detail { template <class T> struct IsSwappable; template <class T> struct IsNothrowSwappable; template <class T, class U, class = void> struct SwappableWithHelper : std::false_type { }; template <class T, class U> struct SwappableWithHelper<T, U, void_t<decltype(swap(std::declval<T>(), std::declval<U>()))>> : std::true_type { }; template <class T, class U> struct IsSwappableWith : bool_constant<conjunction<SwappableWithHelper<T, U>, SwappableWithHelper<U, T>>::value> { }; template <class T> struct IsSwappable : IsSwappableWith<std::add_lvalue_reference_t<T>, std::add_lvalue_reference_t<T>>::type { }; using std::swap; // enable ADL template <class T, class U> struct SwapCannotThrow : bool_constant<noexcept(swap(std::declval<T>(), std::declval<U>()))&& noexcept( swap(std::declval<U>(), std::declval<T>()))> { }; template <class T, class U> struct IsNothrowSwappableWith : bool_constant<conjunction<IsSwappableWith<T, U>, SwapCannotThrow<T, U>>::value> { }; template <class T> struct IsNothrowSwappable : IsNothrowSwappableWith<std::add_lvalue_reference_t<T>, std::add_lvalue_reference_t<T>>::type { }; } // namespace detail //! \endcond template <class T, class U> struct is_swappable_with : detail::IsSwappableWith<T, U>::type { }; template <class T> struct is_swappable : detail::IsSwappable<T>::type { }; template <class T, class U> struct is_nothrow_swappable_with : detail::IsNothrowSwappableWith<T, U>::type { }; template <class T> struct is_nothrow_swappable : detail::IsNothrowSwappable<T>::type { }; //! \cond DEV namespace detail { // The base case is matched in cases where `invoke_uneval` is an invalid expression. The `Qualify` is always set to void // by users. template <typename Qualify, typename Func, typename... TArgs> struct invoke_result_impl { }; template <typename Func, typename... TArgs> struct invoke_result_impl<decltype(void(invoke_uneval(std::declval<Func>(), std::declval<TArgs>()...))), Func, TArgs...> { using type = decltype(invoke_uneval(std::declval<Func>(), std::declval<TArgs>()...)); }; template <typename Qualify, typename Func, typename... TArgs> struct is_invocable_impl : std::false_type { }; template <typename Func, typename... TArgs> struct is_invocable_impl<void_t<typename invoke_result_impl<void, Func, TArgs...>::type>, Func, TArgs...> : std::true_type { }; template <typename Qualify, typename Func, typename... TArgs> struct is_nothrow_invocable_impl : std::false_type { }; template <typename Func, typename... TArgs> struct is_nothrow_invocable_impl<void_t<typename invoke_result_impl<void, Func, TArgs...>::type>, Func, TArgs...> : bool_constant<noexcept(invoke_uneval(std::declval<Func>(), std::declval<TArgs>()...))> { }; } // namespace detail //! \endcond //! Get the result type of calling \c Func with the \c TArgs pack. //! //! If \c Func is callable with the given \c TArgs pack, then this structure has a member typedef named \c type with the //! return of that call. If \c Func is not callable, then the member typedef does not exist. //! //! \code //! static_assert(std::is_same<int, typename invoke_result<int(*)(char), char>::type>::value); //! \endcode //! //! This is equivalent to the C++17 \c std::invoke_result meta transformation. //! //! \see carb::cpp::invoke_result_t template <typename Func, typename... TArgs> struct invoke_result : detail::invoke_result_impl<void, Func, TArgs...> { }; //! Helper for \ref carb::cpp::invoke_result which accesses the \c type member. //! //! \code //! // Get the proper return type and SFINAE-safe disqualify `foo` when `f(10)` is not valid. //! template <typename Func> //! invoke_result_t<Func, int> foo(Func&& f) //! { //! return invoke(std::forward<Func>(f), 10); //! } //! \endcode //! //! This is equivalent to the C++ \c std::invoke_result_t helper typedef. template <typename Func, typename... TArgs> using invoke_result_t = typename invoke_result<Func, TArgs...>::type; //! Check if the \c Func is invocable with the \c TArgs pack. //! //! If \c Func is callable with the given \c TArgs pack, then this structure will derive from \c true_type; otherwise, //! it will be \c false_type. If \c value is \c true, then `invoke(func, args...)` is a valid expression. //! //! \code //! static_assert(is_invocable<void(*)()>::value); //! static_assert(!is_invocable<void(*)(int)>::value); //! static_assert(is_invocable<void(*)(int), int>::value); //! static_assert(is_invocable<void(*)(long), int>::value); //! \endcode //! //! This is equivalent to the C++20 \c std::is_invocable meta query. The query was added in C++17, but this additionally //! supports invoking a pointer to a `const&` member function on an rvalue reference. template <typename Func, typename... TArgs> struct is_invocable : detail::is_invocable_impl<void, Func, TArgs...> { }; //! Check if invoking \c Func with the \c TArgs pack will not throw. //! //! If \c Func called with the given \c TArgs pack is callable and marked \c noexcept, then this structure will derive //! from \c true_type; otherwise, it will be \c false_type. If \c Func is not callable at all, then this will also be //! \c false_type. //! //! This is equivalent to the C++17 \c is_nothrow_invocable meta query. template <typename Func, typename... TArgs> struct is_nothrow_invocable : detail::is_nothrow_invocable_impl<void, Func, TArgs...> { }; //! \cond DEV namespace detail { template <typename Qualify, typename R, typename Func, typename... TArgs> struct invocable_r_impl { using invocable_t = std::false_type; using invocable_nothrow_t = std::false_type; }; template <typename Func, typename... TArgs> struct invocable_r_impl<std::enable_if_t<is_invocable<Func, TArgs...>::value>, void, Func, TArgs...> { using invocable_t = std::true_type; using invocable_nothrow_t = is_nothrow_invocable<Func, TArgs...>; }; // The is_void as part of the qualifier is to workaround an MSVC issue where it thinks this partial specialization and // the one which explicitly lists `R` as void are equally-qualified. template <typename R, typename Func, typename... TArgs> struct invocable_r_impl<std::enable_if_t<is_invocable<Func, TArgs...>::value && !is_void<R>::value>, R, Func, TArgs...> { private: // Can't use declval for conversion checks, as it adds an rvalue ref to the type. We want to make sure the result of // a returned function can be converted. static invoke_result_t<Func, TArgs...> get_val() noexcept; template <typename Target> static void convert_to(Target) noexcept; template <typename TR, typename = decltype(convert_to<TR>(get_val()))> static std::true_type test(int) noexcept; template <typename TR> static std::false_type test(...) noexcept; template <typename TR, typename = decltype(convert_to<TR>(get_val()))> static bool_constant<noexcept(convert_to<TR>(get_val()))> test_nothrow(int) noexcept; template <typename TR> static std::false_type test_nothrow(...) noexcept; public: using invocable_t = decltype(test<R>(0)); using invocable_nothrow_t = decltype(test_nothrow<R>(0)); }; } // namespace detail //! \endcond //! Check if invoking \c Func with the \c TArgs pack will return \c R. //! //! Similar to \ref is_invocable, but additionally checks that the result type is convertible to \c R and that the //! conversion does not bind a reference to a temporary object. If \c R is \c void, the result can be any type (as any //! type can be converted to \c void by discarding it). If \c value is \c true, then `invoke_r<R>(func, args...)` is a //! valid expression. //! //! This is equivalent to the C++23 definition of \c is_invocable_r. The function was originally added in C++17, but the //! specification was altered in C++23 to avoid undefined behavior. template <typename R, typename Func, typename... TArgs> struct is_invocable_r : detail::invocable_r_impl<void, R, Func, TArgs...>::invocable_t { }; //! Check that invoking \c Func with the \c TArgs pack and converting it to \c R will not throw. //! //! This is equivalent to the C++23 definition of \c is_nothrow_invocable_r. The function was originally added in C++17, //! but the specification was altered in C++23 to avoid undefined behavior. template <typename R, typename Func, typename... TArgs> struct is_nothrow_invocable_r : detail::invocable_r_impl<void, R, Func, TArgs...>::invocable_nothrow_t { }; CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE() //! Provides the member typedef type that names T (i.e. the identity transformation). //! This can be used to establish non-deduced contexts in template argument deduction. template <class T> struct type_identity { //! The identity transformation. using type = T; }; //! Helper type for \ref type_identity template <class T> using type_identity_t = typename type_identity<T>::type; //! If the type T is a reference type, provides the member typedef type which is the type referred to by T with its //! topmost cv-qualifiers removed. Otherwise type is T with its topmost cv-qualifiers removed. template <class T> struct remove_cvref { //! The type `T` or referred to by `T` (in the case of a reference) with topmost cv-qualifiers removed. using type = std::remove_cv_t<std::remove_reference_t<T>>; }; //! Helper type for \ref remove_cvref template <class T> using remove_cvref_t = typename remove_cvref<T>::type; //! \cond DEV namespace detail { template <class T, class P, class = void> struct IsConvertibleRange : public std::false_type { }; template <class T, class P> struct IsConvertibleRange<T, P, cpp::void_t<decltype(std::declval<T>().size()), std::enable_if_t<std::is_convertible<decltype(std::declval<T>().data()), P>::value>>> : public std::true_type { }; } // namespace detail //! \endcond DEV } // namespace cpp } // namespace carb
14,234
C
30.91704
123
0.69615
omniverse-code/kit/include/carb/cpp/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. // //! \file //! \brief C++14-compatible implementation of select functionality from C++ `<barrier>` library. #pragma once #include "Atomic.h" #include "Bit.h" #include <utility> namespace carb { //! Namespace for C++ standard library types after C++14 implemented and usable by C++14 compilers. namespace cpp { //! \cond DEV namespace detail { constexpr uint32_t kInvalidPhase = 0; struct NullFunction { constexpr NullFunction() noexcept = default; constexpr void operator()() noexcept { } }; } // namespace detail //! \endcond // Handle case where Windows.h may have defined 'max' #pragma push_macro("max") #undef max /** * Implements a C++20 barrier in C++14 semantics. * * A barrier is a thread coordination mechanism whose lifetime consists of a sequence of barrier phases, where * each phase allows at most an expected number of threads to block until the expected number of threads * arrive at the barrier. A barrier is useful for managing repeated tasks that are handled by multiple * threads. * * @see https://en.cppreference.com/w/cpp/thread/barrier * @tparam CompletionFunction A function object type that must meet the requirements of MoveConstructible and * Destructible. `std::is_nothrow_invocable_v<CompletionFunction&>` must be `true`. The default template argument is an * unspecified function object type that additionally meets the requirements of DefaultConstructible. Calling an lvalue * of it with no arguments has no effects. Every barrier behaves as if it holds an exposition-only non-static data * member `completion_` of type `CompletionFunction` and calls it by `completion_()` on every phase completion step. */ template <class CompletionFunction = detail::NullFunction> class barrier { CARB_PREVENT_COPY_AND_MOVE(barrier); public: /** * Returns the maximum value of expected count supported by the implementation. * @returns the maximum value of expected count supported by the implementation. */ static constexpr ptrdiff_t max() noexcept { return ptrdiff_t(INT_MAX); } /** * Constructor * * Sets both the initial expected count for each phase and the current expected count for the first phase to * @p expected, initializes the completion function object with `std::move(f)`, and then starts the first phase. The * behavior is undefined if @p expected is negative or greater than @ref max(). * * @param expected Initial value of the expected count. * @param f Completion function object to be called on phase completion step. * @throws std::exception Any exception thrown by CompletionFunction's move constructor. */ constexpr explicit barrier(ptrdiff_t expected, CompletionFunction f = CompletionFunction{}) : m_emo(InitBoth{}, std::move(f), (uint64_t(1) << kPhaseBitShift) + uint32_t(::carb_min(expected, max()))), m_expected(uint32_t(::carb_min(expected, max()))) { CARB_ASSERT(expected >= 0 && expected <= max()); } /** * Destructor * * The behavior is undefined if any thread is concurrently calling a member function of the barrier. * * @note This implementation waits until all waiting threads have woken, but this is a stronger guarantee than the * standard. */ ~barrier() { // Wait for destruction until all waiters are clear while (m_waiters.load(std::memory_order_acquire) != 0) std::this_thread::yield(); } /** * An object type meeting requirements of MoveConstructible, MoveAssignable and Destructible. * @see arrive() wait() */ class arrival_token { CARB_PREVENT_COPY(arrival_token); friend class barrier; uint32_t m_token{ detail::kInvalidPhase }; arrival_token(uint32_t token) : m_token(token) { } public: //! Constructor arrival_token() = default; //! Move constructor //! @param rhs Other @c arrival_token to move from. @c rhs is left in a valid but empty state. arrival_token(arrival_token&& rhs) : m_token(std::exchange(rhs.m_token, detail::kInvalidPhase)) { } //! Move-assign operator //! @param rhs Other @c arrival_token to move from. @c rhs is left in a valid but empty state. //! @returns @c *this arrival_token& operator=(arrival_token&& rhs) { m_token = std::exchange(rhs.m_token, detail::kInvalidPhase); return *this; } }; /** * Arrives at barrier and decrements the expected count * * Constructs an @ref arrival_token object associated with the phase synchronization point for the current phase. * Then, decrements the expected count by @p update. * * This function executes atomically. The call to this function strongly happens-before the start of the phase * completion step for the current phase. * * The behavior is undefined if @p update is less than or equal zero or greater than the expected count for the * current barrier phase. * * @param update The value by which the expected count is decreased. * @returns The constructed @ref arrival_token object. * @throws std::system_error According to the standard, but this implementation does not throw. Instead an assertion * occurs. * @see wait() */ CARB_NODISCARD arrival_token arrive(ptrdiff_t update = 1) { return arrival_token(uint32_t(_arrive(update).first >> kPhaseBitShift)); } /** * Blocks at the phase synchronization point until its phase completion step is run. * * If @p arrival is associated with the phase synchronization point for the current phase of @c *this, blocks at the * synchronization point associated with @p arrival until the phase completion step of the synchronization point's * phase is run. * * Otherwise if @p arrival is associated with the phase synchronization point for the immediately preceding phase of * @c *this, returns immediately. * * Otherwise, i.e. if @p arrival is associated with the phase synchronization point for an earlier phase of @c *this * or any phase of a barrier object other than @c *this, the behavior is undefined. * * @param arrival An @ref arrival_token obtained by a previous call to @ref arrive() on the same barrier. * @throws std::system_error According to the standard, but this implementation does not throw. Instead an assertion * occurs. */ void wait(arrival_token&& arrival) const { // Precondition: arrival is associated with the phase synchronization point for the current phase or the // immediately preceding phase. CARB_CHECK(arrival.m_token != 0); // No invalid tokens uint64_t data = m_emo.second.load(std::memory_order_acquire); uint32_t phase = uint32_t(data >> kPhaseBitShift); CARB_CHECK((phase - arrival.m_token) <= 1, "arrival %u is not the previous or current phase %u", arrival.m_token, phase); if (phase != arrival.m_token) return; // Register as a waiter m_waiters.fetch_add(1, std::memory_order_relaxed); do { // Wait for the phase to change m_emo.second.wait(data, std::memory_order_relaxed); // Reload after waiting data = m_emo.second.load(std::memory_order_acquire); phase = uint32_t(data >> kPhaseBitShift); } while (phase == arrival.m_token); // Unregister as a waiter m_waiters.fetch_sub(1, std::memory_order_release); } /** * Arrives at barrier and decrements the expected count by one, then blocks until the current phase completes. * * Atomically decrements the expected count by one, then blocks at the synchronization point for the current phase * until the phase completion step of the current phase is run. Equivalent to `wait(arrive())`. * * The behavior is undefined if the expected count for the current phase is zero. * * @note If the current expected count is decremented to zero in the call to this function, the phase completion * step is run and this function does not block. If the current expected count is zero before calling this function, * the initial expected count for all subsequent phases is also zero, which means the barrier cannot be reused. * * @throws std::system_error According to the standard, but this implementation does not throw. Instead an assertion * occurs. */ void arrive_and_wait() { // Two main differences over just doing arrive(wait()): // - We return immediately if _arrive() did the phase shift // - We don't CARB_CHECK that the phase is the current or preceding one since it is guaranteed auto result = _arrive(1); if (result.second) return; // Register as a waiter m_waiters.fetch_add(1, std::memory_order_relaxed); uint64_t data = result.first; uint32_t origPhase = uint32_t(data >> kPhaseBitShift), phase; do { // Wait for the phase to change m_emo.second.wait(data, std::memory_order_relaxed); // Reload after waiting data = m_emo.second.load(std::memory_order_acquire); phase = uint32_t(data >> kPhaseBitShift); } while (phase == origPhase); // Unregister as a waiter m_waiters.fetch_sub(1, std::memory_order_release); } /** * Decrements both the initial expected count for subsequent phases and the expected count for current phase by one. * * This function is executed atomically. The call to this function strongly happens-before the start of the phase * completion step for the current phase. * * The behavior is undefined if the expected count for the current phase is zero. * * @note This function can cause the completion step for the current phase to start. If the current expected count * is zero before calling this function, the initial expected count for all subsequent phases is also zero, which * means the barrier cannot be reused. * * @throws std::system_error According to the standard, but this implementation does not throw. Instead an assertion * occurs. */ void arrive_and_drop() { uint32_t prev = m_expected.fetch_sub(1, std::memory_order_relaxed); CARB_CHECK(prev != 0); // Precondition failure: expected count for the current barrier phase must be greater // than zero. _arrive(1); } private: constexpr static int kPhaseBitShift = 32; constexpr static uint64_t kCounterMask = 0xffffffffull; CARB_ALWAYS_INLINE std::pair<uint64_t, bool> _arrive(ptrdiff_t update) { CARB_CHECK(update > 0 && update <= max()); uint64_t pre = m_emo.second.fetch_sub(uint32_t(update), std::memory_order_acq_rel); CARB_CHECK(ptrdiff_t(int32_t(uint32_t(pre & kCounterMask))) >= update); // Precondition check bool completed = false; if (uint32_t(pre & kCounterMask) == uint32_t(update)) { // Phase is now complete std::atomic_thread_fence(std::memory_order_acquire); _completePhase(pre - uint32_t(update)); completed = true; } return std::make_pair(pre - uint32_t(update), completed); } void _completePhase(uint64_t data) { uint32_t expected = m_expected.load(std::memory_order_relaxed); // Run the completion routine before releasing threads m_emo.first()(); // Increment the phase and don't allow the invalid phase uint32_t phase = uint32_t(data >> kPhaseBitShift); if (++phase == detail::kInvalidPhase) ++phase; #if CARB_ASSERT_ENABLED // Should not have changed during completion function. uint64_t old = m_emo.second.exchange((uint64_t(phase) << kPhaseBitShift) + expected, std::memory_order_release); CARB_ASSERT(old == data); #else m_emo.second.store((uint64_t(phase) << kPhaseBitShift) + expected, std::memory_order_release); #endif // Release all waiting threads m_emo.second.notify_all(); } // The MSB 32 bits of the atomic_uint64_t are the Phase; the other bits are the Counter EmptyMemberPair<CompletionFunction, atomic_uint64_t> m_emo; std::atomic_uint32_t m_expected; mutable std::atomic_uint32_t m_waiters{ 0 }; }; #pragma pop_macro("max") } // namespace cpp } // namespace carb
13,176
C
38.452096
120
0.662417
omniverse-code/kit/include/carb/cpp/Optional.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 std::optional from C++17 using C++14 paradigms. // Heavily borrowed from MS STL: https://github.com/microsoft/STL/blob/master/stl/inc/optional //! \file //! \brief C++14-compatible implementation of select functionality from C++ `<optional>` library. #pragma once #include "../Defines.h" #include "Utility.h" #define CARB_IMPLOPTIONAL #include "detail/ImplOptional.h" #undef CARB_IMPLOPTIONAL namespace carb { namespace cpp { struct nullopt_t { struct Tag { }; explicit constexpr nullopt_t(Tag) { } }; static constexpr nullopt_t nullopt{ nullopt_t::Tag{} }; class bad_optional_access final : public std::exception { public: bad_optional_access() noexcept = default; bad_optional_access(const bad_optional_access&) noexcept = default; bad_optional_access& operator=(const bad_optional_access&) noexcept = default; virtual const char* what() const noexcept override { return "bad optional access"; } }; template <class T> class CARB_VIZ optional : private detail::SelectHierarchy<detail::OptionalConstructor<T>, T> { using BaseClass = detail::SelectHierarchy<detail::OptionalConstructor<T>, T>; static_assert(!std::is_same<std::remove_cv_t<T>, nullopt_t>::value && !std::is_same<std::remove_cv_t<T>, in_place_t>::value, "T may not be nullopt_t or inplace_t"); static_assert(std::is_object<T>::value && std::is_destructible<T>::value && !std::is_array<T>::value, "T does not meet Cpp17Destructible requirements"); // Essentially: !is_same(U, optional) && !is_same(U, in_place_t) && is_constructible(T from U) template <class U> using AllowDirectConversion = bool_constant< conjunction<negation<std::is_same<typename std::remove_reference_t<typename std::remove_cv_t<U>>, optional>>, negation<std::is_same<typename std::remove_reference_t<typename std::remove_cv_t<U>>, in_place_t>>, std::is_constructible<T, U>>::value>; // Essentially: !(is_same(T, U) || is_constructible(T from optional<U>) || is_convertible(optional<U> to T)) template <class U> struct AllowUnwrapping : bool_constant<!disjunction<std::is_same<T, U>, std::is_constructible<T, optional<U>&>, std::is_constructible<T, const optional<U>&>, std::is_constructible<T, const optional<U>>, std::is_constructible<T, optional<U>>, std::is_convertible<optional<U>&, T>, std::is_convertible<const optional<U>&, T>, std::is_convertible<const optional<U>, T>, std::is_convertible<optional<U>, T>>::value> { }; // Essentially: !(is_same(T, U) || is_assignable(T& from optional<U>)) template <class U> struct AllowUnwrappingAssignment : bool_constant<!disjunction<std::is_same<T, U>, std::is_assignable<T&, optional<U>&>, std::is_assignable<T&, const optional<U>&>, std::is_assignable<T&, const optional<U>>, std::is_assignable<T&, optional<U>>>::value> { }; [[noreturn]] static void onBadAccess() { #if CARB_EXCEPTIONS_ENABLED throw bad_optional_access(); #else CARB_FATAL_UNLESS(0, "bad optional access"); #endif } public: using value_type = T; constexpr optional() noexcept { } constexpr optional(nullopt_t) noexcept { } optional(const optional& other) : BaseClass(static_cast<const BaseClass&>(other)) { } optional(optional&& other) noexcept(std::is_nothrow_move_constructible<T>::value) : BaseClass(static_cast<BaseClass&&>(std::move(other))) { } optional& operator=(const optional& other) { if (other) this->assign(*other); else reset(); return *this; } optional& operator=(optional&& other) noexcept( std::is_nothrow_move_assignable<T>::value&& std::is_nothrow_move_constructible<T>::value) { if (other) this->assign(std::move(*other)); else reset(); return *this; } // The spec states that this is conditionally-explicit, which is a C++20 feature, so we have to work around it by // having two functions with SFINAE template <class U, typename std::enable_if_t< conjunction<AllowUnwrapping<U>, std::is_constructible<T, const U&>, std::is_convertible<const U&, T>>::value, int> = 0> optional(const optional<U>& other) { if (other) this->construct(*other); } template < class U, typename std::enable_if_t< conjunction<AllowUnwrapping<U>, std::is_constructible<T, const U&>, negation<std::is_convertible<const U&, T>>>::value, int> = 0> explicit optional(const optional<U>& other) { if (other) this->construct(*other); } // The spec states that this is conditionally-explicit, which is a C++20 feature, so we have to work around it by // having two functions with SFINAE template < class U, typename std::enable_if_t<conjunction<AllowUnwrapping<U>, std::is_constructible<T, U>, std::is_convertible<U, T>>::value, int> = 0> optional(optional<U>&& other) { if (other) this->construct(std::move(*other)); } template <class U, typename std::enable_if_t< conjunction<AllowUnwrapping<U>, std::is_constructible<T, U>, negation<std::is_convertible<U, T>>>::value, int> = 0> explicit optional(optional<U>&& other) { if (other) this->construct(std::move(*other)); } template <class... Args, typename std::enable_if_t<std::is_constructible<T, Args...>::value, int> = 0> optional(in_place_t, Args&&... args) : BaseClass(in_place, std::forward<Args>(args)...) { } template <class U, class... Args, typename std::enable_if_t<std::is_constructible<T, std::initializer_list<U>&, Args...>::value, int> = 0> optional(in_place_t, std::initializer_list<U> ilist, Args&&... args) : BaseClass(in_place, ilist, std::forward<Args>(args)...) { } // The spec states that this is conditionally-explicit, which is a C++20 feature, so we have to work around it by // having two functions with SFINAE template <class U = value_type, typename std::enable_if_t<conjunction<AllowDirectConversion<U>, std::is_convertible<U, T>>::value, int> = 0> constexpr optional(U&& value) : BaseClass(in_place, std::forward<U>(value)) { } template <class U = value_type, typename std::enable_if_t<conjunction<AllowDirectConversion<U>, negation<std::is_convertible<U, T>>>::value, int> = 0> constexpr explicit optional(U&& value) : BaseClass(in_place, std::forward<U>(value)) { } ~optional() = default; optional& operator=(nullopt_t) noexcept { reset(); return *this; } template <class U = T, typename std::enable_if_t< conjunction<negation<std::is_same<optional, typename std::remove_cv_t<typename std::remove_reference_t<U>>>>, negation<conjunction<std::is_scalar<T>, std::is_same<T, typename std::decay_t<U>>>>, std::is_constructible<T, U>, std::is_assignable<T&, U>>::value, int> = 0> optional& operator=(U&& value) { this->assign(std::forward<U>(value)); return *this; } template < class U, typename std::enable_if_t< conjunction<AllowUnwrappingAssignment<U>, std::is_constructible<T, const U&>, std::is_assignable<T&, const U&>>::value, int> = 0> optional& operator=(const optional<U>& other) { if (other) this->assign(*other); else reset(); return *this; } template <class U, typename std::enable_if_t< conjunction<AllowUnwrappingAssignment<U>, std::is_constructible<T, U>, std::is_assignable<T&, U>>::value, int> = 0> optional& operator=(optional<U>&& other) { if (other) this->assign(std::move(*other)); else reset(); return *this; } constexpr const T* operator->() const { return std::addressof(this->val()); } constexpr T* operator->() { return std::addressof(this->val()); } constexpr const T& operator*() const& { return this->val(); } constexpr T& operator*() & { return this->val(); } constexpr const T&& operator*() const&& { return std::move(this->val()); } constexpr T&& operator*() && { return std::move(this->val()); } constexpr explicit operator bool() const noexcept { return this->hasValue; } constexpr bool has_value() const noexcept { return this->hasValue; } constexpr const T& value() const& { if (!this->hasValue) onBadAccess(); return this->val(); } constexpr T& value() & { if (!this->hasValue) onBadAccess(); return this->val(); } constexpr const T&& value() const&& { if (!this->hasValue) onBadAccess(); return std::move(this->val()); } constexpr T&& value() && { if (!this->hasValue) onBadAccess(); return std::move(this->val()); } template <class U> constexpr typename std::remove_cv_t<T> value_or(U&& default_value) const& { static_assert( std::is_convertible<const T&, typename std::remove_cv_t<T>>::value, "The const overload of optional<T>::value_or() requires const T& to be convertible to std::remove_cv_t<T>"); static_assert(std::is_convertible<U, T>::value, "optional<T>::value_or() requires U to be convertible to T"); if (this->hasValue) return this->val(); return static_cast<typename std::remove_cv_t<T>>(std::forward<U>(default_value)); } template <class U> constexpr typename std::remove_cv_t<T> value_or(U&& default_value) && { static_assert( std::is_convertible<T, typename std::remove_cv_t<T>>::value, "The rvalue overload of optional<T>::value_or() requires T to be convertible to std::remove_cv_t<T>"); static_assert(std::is_convertible<U, T>::value, "optional<T>::value_or() requires U to be convertible to T"); if (this->hasValue) return this->val(); return static_cast<typename std::remove_cv_t<T>>(std::forward<U>(default_value)); } void swap(optional& other) noexcept(std::is_nothrow_move_constructible<T>::value&& is_nothrow_swappable<T>::value) { static_assert(std::is_move_constructible<T>::value, "T must be move constructible"); static_assert(!std::is_move_constructible<T>::value || is_swappable<T>::value, "T must be swappable"); const bool engaged = this->hasValue; if (engaged == other.hasValue) { if (engaged) { using std::swap; // Enable ADL swap(**this, *other); } } else { optional& source = engaged ? *this : other; optional& target = engaged ? other : *this; target.construct(std::move(*source)); source.reset(); } } using BaseClass::reset; template <class... Args> T& emplace(Args&&... args) { reset(); return this->construct(std::forward<Args>(args)...); } template <class U, class... Args, typename std::enable_if_t<std::is_constructible<T, std::initializer_list<U>&, Args...>::value, int> = 0> T& emplace(std::initializer_list<U> ilist, Args&&... args) { reset(); return this->construct(ilist, std::forward<Args>(args)...); } }; template <class T, class U> constexpr bool operator==(const optional<T>& lhs, const optional<U>& rhs) { const bool lhv = lhs.has_value(); return lhv == rhs.has_value() && (!lhv || *lhs == *rhs); } template <class T, class U> constexpr bool operator!=(const optional<T>& lhs, const optional<U>& rhs) { const bool lhv = lhs.has_value(); return lhv != rhs.has_value() || (lhv && *lhs != *rhs); } template <class T, class U> constexpr bool operator<(const optional<T>& lhs, const optional<U>& rhs) { return rhs.has_value() && (!lhs.has_value() || *lhs < *rhs); } template <class T, class U> constexpr bool operator<=(const optional<T>& lhs, const optional<U>& rhs) { return !lhs.has_value() || (rhs.has_value() && *lhs <= *rhs); } template <class T, class U> constexpr bool operator>(const optional<T>& lhs, const optional<U>& rhs) { return lhs.has_value() && (!rhs.has_value() || *lhs > *rhs); } template <class T, class U> constexpr bool operator>=(const optional<T>& lhs, const optional<U>& rhs) { return !rhs.has_value() || (lhs.has_value() && *lhs >= *rhs); } template <class T> constexpr bool operator==(const optional<T>& opt, nullopt_t) noexcept { return !opt.has_value(); } template <class T> constexpr bool operator==(nullopt_t, const optional<T>& opt) noexcept { return !opt.has_value(); } template <class T> constexpr bool operator!=(const optional<T>& opt, nullopt_t) noexcept { return opt.has_value(); } template <class T> constexpr bool operator!=(nullopt_t, const optional<T>& opt) noexcept { return opt.has_value(); } template <class T> constexpr bool operator<(const optional<T>& opt, nullopt_t) noexcept { CARB_UNUSED(opt); return false; } template <class T> constexpr bool operator<(nullopt_t, const optional<T>& opt) noexcept { return opt.has_value(); } template <class T> constexpr bool operator<=(const optional<T>& opt, nullopt_t) noexcept { return !opt.has_value(); } template <class T> constexpr bool operator<=(nullopt_t, const optional<T>& opt) noexcept { CARB_UNUSED(opt); return true; } template <class T> constexpr bool operator>(const optional<T>& opt, nullopt_t) noexcept { return opt.has_value(); } template <class T> constexpr bool operator>(nullopt_t, const optional<T>& opt) noexcept { CARB_UNUSED(opt); return false; } template <class T> constexpr bool operator>=(const optional<T>& opt, nullopt_t) noexcept { CARB_UNUSED(opt); return true; } template <class T> constexpr bool operator>=(nullopt_t, const optional<T>& opt) noexcept { return !opt.has_value(); } template <class T, class U, detail::EnableIfComparableWithEqual<T, U> = 0> constexpr bool operator==(const optional<T>& opt, const U& value) { return opt ? *opt == value : false; } template <class T, class U, detail::EnableIfComparableWithEqual<T, U> = 0> constexpr bool operator==(const T& value, const optional<U>& opt) { return opt ? *opt == value : false; } template <class T, class U, detail::EnableIfComparableWithNotEqual<T, U> = 0> constexpr bool operator!=(const optional<T>& opt, const U& value) { return opt ? *opt != value : true; } template <class T, class U, detail::EnableIfComparableWithNotEqual<T, U> = 0> constexpr bool operator!=(const T& value, const optional<U>& opt) { return opt ? *opt != value : true; } template <class T, class U, detail::EnableIfComparableWithLess<T, U> = 0> constexpr bool operator<(const optional<T>& opt, const U& value) { return opt ? *opt < value : true; } template <class T, class U, detail::EnableIfComparableWithLess<T, U> = 0> constexpr bool operator<(const T& value, const optional<U>& opt) { return opt ? value < *opt : false; } template <class T, class U, detail::EnableIfComparableWithLessEqual<T, U> = 0> constexpr bool operator<=(const optional<T>& opt, const U& value) { return opt ? *opt <= value : true; } template <class T, class U, detail::EnableIfComparableWithLessEqual<T, U> = 0> constexpr bool operator<=(const T& value, const optional<U>& opt) { return opt ? value <= *opt : false; } template <class T, class U, detail::EnableIfComparableWithGreater<T, U> = 0> constexpr bool operator>(const optional<T>& opt, const U& value) { return opt ? *opt > value : false; } template <class T, class U, detail::EnableIfComparableWithGreater<T, U> = 0> constexpr bool operator>(const T& value, const optional<U>& opt) { return opt ? value > *opt : true; } template <class T, class U, detail::EnableIfComparableWithGreaterEqual<T, U> = 0> constexpr bool operator>=(const optional<T>& opt, const U& value) { return opt ? *opt >= value : false; } template <class T, class U, detail::EnableIfComparableWithGreaterEqual<T, U> = 0> constexpr bool operator>=(const T& value, const optional<U>& opt) { return opt ? value >= *opt : true; } template <class T, typename std::enable_if_t<std::is_move_constructible<T>::value && is_swappable<T>::value, int> = 0> void swap(optional<T>& lhs, optional<T>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } template <class T> constexpr optional<typename std::decay_t<T>> make_optional(T&& value) { return optional<typename std::decay_t<T>>{ std::forward<T>(value) }; } template <class T, class... Args> constexpr optional<T> make_optional(Args&&... args) { return optional<T>{ in_place, std::forward<Args>(args)... }; } template <class T, class U, class... Args> constexpr optional<T> make_optional(std::initializer_list<U> il, Args&&... args) { return optional<T>{ in_place, il, std::forward<Args>(args)... }; } } // namespace cpp } // namespace carb
18,873
C
31.824348
132
0.592169
omniverse-code/kit/include/carb/cpp/Variant.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 C++14-compatible implementation of select functionality from C++ `<variant>` library. #pragma once #include "../Defines.h" #include "TypeTraits.h" #include "Utility.h" #include <cstdint> #include <exception> #include <new> #include <tuple> #include <utility> // This class is a not quite standards conformant implementation of std::variant. Where it doesn't comply it is // in the sense that it doesn't support everything. Such as all constexpr usages. Part of this is because it // isn't possible on a C++14 compiler, the other part is full coverage of this class is difficult. Feel free // to expand this class and make it more conforming to all use cases the standard version can given it will // still compile on C++14. The long term intention is we will move to a C++17 compiler, and import the std // version of this class, removing this code from our codebase. Therefore it is very important that this class // doesn't do anything that the std can't, though the opposite is permissible. namespace carb { namespace cpp { static constexpr std::size_t variant_npos = (std::size_t)-1; // Forward define. template <typename... Types> class variant; template <std::size_t I, typename T> struct variant_alternative; class bad_variant_access final : public std::exception { public: bad_variant_access() noexcept = default; bad_variant_access(const bad_variant_access&) noexcept = default; bad_variant_access& operator=(const bad_variant_access&) noexcept = default; virtual const char* what() const noexcept override { return "bad variant access"; } }; namespace detail { // Common pathway for bad_variant_access. [[noreturn]] inline void on_bad_variant_access() { #if CARB_EXCEPTIONS_ENABLED throw bad_variant_access(); #else std::terminate(); #endif } template <bool IsTriviallyDesctructable, typename... Types> class VariantHold; template <bool IsTriviallyDesctructable> class VariantHold<IsTriviallyDesctructable> { static constexpr size_t size = 0; }; template <typename T, typename... Types> class VariantHold<true, T, Types...> { public: static constexpr size_t size = 1 + sizeof...(Types); using Next = VariantHold<true, Types...>; union { CARB_VIZ std::remove_const_t<T> m_value; CARB_VIZ Next m_next; }; constexpr VariantHold() noexcept { } template <class... Args> constexpr VariantHold(in_place_index_t<0>, Args&&... args) noexcept : m_value(std::forward<Args>(args)...) { } template <size_t I, class... Args> constexpr VariantHold(in_place_index_t<I>, Args&&... args) noexcept : m_next(in_place_index<I - 1>, std::forward<Args>(args)...) { } constexpr T& get() & noexcept { return m_value; } constexpr const T& get() const& noexcept { return m_value; } constexpr T&& get() && noexcept { return std::move(m_value); } constexpr const T&& get() const&& noexcept { return std::move(m_value); } }; template <typename T, typename... Types> class VariantHold<false, T, Types...> { public: static constexpr size_t size = 1 + sizeof...(Types); using Next = VariantHold<false, Types...>; union { CARB_VIZ std::remove_const_t<T> m_value; CARB_VIZ Next m_next; }; constexpr VariantHold() noexcept { } template <class... Args> constexpr VariantHold(in_place_index_t<0>, Args&&... args) noexcept : m_value(std::forward<Args>(args)...) { } template <size_t I, class... Args> constexpr VariantHold(in_place_index_t<I>, Args&&... args) noexcept : m_next(in_place_index<I - 1>, std::forward<Args>(args)...) { } ~VariantHold() { } constexpr T& get() & noexcept { return m_value; } constexpr const T& get() const& noexcept { return m_value; } constexpr T&& get() && noexcept { return std::move(m_value); } constexpr const T&& get() const&& noexcept { return std::move(m_value); } }; template <size_t I> struct VariantGetFromHold { template <class Hold> static decltype(auto) get(Hold&& hold) { return VariantGetFromHold<I - 1>::get(hold.m_next); } }; template <> struct VariantGetFromHold<0> { template <class Hold> static decltype(auto) get(Hold&& hold) { return hold.get(); } }; template <size_t I, typename Hold> constexpr decltype(auto) variant_get_from_hold(Hold&& hold) { constexpr size_t size = std::remove_reference_t<Hold>::size; return VariantGetFromHold < I < size ? I : size - 1 > ::get(hold); } // Visitor with index feedback. template <size_t I, typename Functor, typename Hold> static decltype(auto) visitWithIndex(Functor&& functor, Hold&& hold) { return std::forward<Functor>(functor)(I, VariantGetFromHold<I>::get(static_cast<Hold&&>(hold))); } template <int I> struct VisitWithIndexHelper; template <typename Functor, typename Hold, typename Ids = std::make_index_sequence<std::remove_reference<Hold>::type::size>> struct VisitWithIndexTable; template <typename Functor, typename Hold, size_t... Ids> struct VisitWithIndexTable<Functor, Hold, std::index_sequence<Ids...>> { using return_type = decltype(std::declval<Functor>()(VariantGetFromHold<0>::get(std::declval<Hold>()))); using f_table_type = return_type (*)(Functor&&, Hold&&); static f_table_type& table(size_t id) { static f_table_type tbl[] = { &visitWithIndex<Ids, Functor, Hold>... }; return tbl[id]; } }; template <> struct VisitWithIndexHelper<-1> { template <typename Functor, typename Hold> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold&& hold) { auto& entry = VisitWithIndexTable<Functor, Hold>::table(index); return entry(std::forward<Functor>(functor), std::forward<Hold>(hold)); } }; #define VISIT_WITH_INDEX_1(n) \ case (n): \ return std::forward<Functor>(functor)( \ n, VariantGetFromHold < n < size ? n : size - 1 > ::get(static_cast<Hold&&>(hold))); #define VISIT_WITH_INDEX_2(n) \ VISIT_WITH_INDEX_1(n) \ VISIT_WITH_INDEX_1(n + 1) #define VISIT_WITH_INDEX_4(n) \ VISIT_WITH_INDEX_2(n) \ VISIT_WITH_INDEX_2(n + 2) #define VISIT_WITH_INDEX_8(n) \ VISIT_WITH_INDEX_4(n) \ VISIT_WITH_INDEX_4(n + 4) #define VISIT_WITH_INDEX_16(n) \ VISIT_WITH_INDEX_8(n) \ VISIT_WITH_INDEX_8(n + 8) template <> struct VisitWithIndexHelper<0> { template <typename Functor, typename Hold> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold&& hold) { constexpr size_t size = std::remove_reference_t<Hold>::size; switch (index) { default: VISIT_WITH_INDEX_1(0); } } }; template <> struct VisitWithIndexHelper<1> { template <typename Functor, typename Hold> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold&& hold) { constexpr size_t size = std::remove_reference_t<Hold>::size; switch (index) { default: VISIT_WITH_INDEX_2(0); } } }; template <> struct VisitWithIndexHelper<2> { template <typename Functor, typename Hold> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold&& hold) { constexpr size_t size = std::remove_reference_t<Hold>::size; switch (index) { default: VISIT_WITH_INDEX_4(0); } } }; template <> struct VisitWithIndexHelper<3> { template <typename Functor, typename Hold> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold&& hold) { constexpr size_t size = std::remove_reference_t<Hold>::size; switch (index) { default: VISIT_WITH_INDEX_8(0); } } }; template <> struct VisitWithIndexHelper<4> { template <typename Functor, typename Hold> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold&& hold) { constexpr size_t size = std::remove_reference_t<Hold>::size; switch (index) { default: VISIT_WITH_INDEX_16(0); } } }; #undef VISIT_WITH_INDEX_1 #undef VISIT_WITH_INDEX_2 #undef VISIT_WITH_INDEX_4 #undef VISIT_WITH_INDEX_8 #undef VISIT_WITH_INDEX_16 // Use this as the definition so that the template parameters can auto-deduce. template <typename Functor, typename Hold> decltype(auto) visitorWithIndex(Functor&& functor, size_t typeIndex, Hold&& hold) { constexpr int size = std::remove_reference<Hold>::type::size; constexpr int version = size <= 1 ? 0 : size <= 2 ? 1 : size <= 4 ? 2 : size <= 8 ? 3 : size <= 16 ? 4 : -1; return VisitWithIndexHelper<version>::issue(std::forward<Functor>(functor), typeIndex, std::forward<Hold>(hold)); } // Visitor without index feedback. template <size_t I> struct Dispatcher; template <> struct Dispatcher<1> { template <typename Functor, typename Impl> using return_type = decltype(std::declval<Functor>()(VariantGetFromHold<0>::get(std::declval<Impl>()))); template <size_t I, typename Functor, typename Impl> static decltype(auto) issue(Functor&& functor, Impl&& impl) { return std::forward<Functor>(functor)(variant_get_from_hold<I>(std::forward<Impl>(impl))); } }; template <> struct Dispatcher<2> { template <typename Functor, typename Impl1, typename Impl2> using return_type = decltype(std::declval<Functor>()( VariantGetFromHold<0>::get(std::declval<Impl1>()), VariantGetFromHold<0>::get(std::declval<Impl2>()))); template <size_t I, typename Functor, typename Impl1, typename Impl2> static decltype(auto) issue(Functor&& functor, Impl1&& impl1, Impl2&& impl2) { constexpr size_t size1 = std::remove_reference<Impl1>::type::size; constexpr size_t I1 = I % size1; constexpr size_t I2 = I / size1; return functor(variant_get_from_hold<I1>(std::forward<Impl1>(impl1)), variant_get_from_hold<I2>(std::forward<Impl2>(impl2))); } }; template <typename... Impl> struct TotalStates; template <typename Impl> struct TotalStates<Impl> { static constexpr size_t value = std::remove_reference<Impl>::type::size; }; template <typename Impl, typename... Rem> struct TotalStates<Impl, Rem...> { static constexpr size_t value = std::remove_reference<Impl>::type::size * TotalStates<Rem...>::value; }; template <typename... Ts> struct Package { }; template <typename Functor, typename... Impl> struct VisitHelperTable { template <typename Ids> struct Instance; }; template <typename Functor, typename... Impl> template <size_t... Ids> struct VisitHelperTable<Functor, Impl...>::Instance<std::index_sequence<Ids...>> { using dispatcher = Dispatcher<sizeof...(Impl)>; using return_type = typename dispatcher::template return_type<Functor, Impl...>; using f_table_type = return_type (*)(Functor&&, Impl&&...); static f_table_type& table(size_t id) { static f_table_type tbl[] = { &Dispatcher<sizeof...(Impl)>::template issue<Ids, Functor>... }; return tbl[id]; } }; inline size_t computeIndex() { return 0; } template <class Impl, class... Impls> constexpr size_t computeIndex(Impl&& impl, Impls&&... impls) { if (impl.index() != variant_npos) { constexpr size_t size = std::remove_reference<Impl>::type::size; return impl.index() + size * computeIndex(impls...); } on_bad_variant_access(); } template <int I> struct VisitHelper; template <> struct VisitHelper<-1> { template <typename Functor, typename... Impl> static constexpr decltype(auto) issue(Functor&& functor, Impl&&... impl) { constexpr size_t size = TotalStates<Impl...>::value; size_t index = computeIndex(impl...); auto& entry = VisitHelperTable<Functor, Impl...>::template Instance<std::make_index_sequence<size>>::table(index); return entry(std::forward<Functor>(functor), std::forward<Impl>(impl)...); } }; #define VISIT_1(n) \ case (n): \ return dispatcher::template issue<n, Functor>(std::forward<Functor>(functor), std::forward<Impl>(impl)...); #define VISIT_2(n) \ VISIT_1(n) \ VISIT_1(n + 1) #define VISIT_4(n) \ VISIT_2(n) \ VISIT_2(n + 2) #define VISIT_8(n) \ VISIT_4(n) \ VISIT_4(n + 4) #define VISIT_16(n) \ VISIT_8(n) \ VISIT_8(n + 8) template <> struct VisitHelper<0> { template <typename Functor, typename... Impl> static constexpr decltype(auto) issue(Functor&& functor, Impl&&... impl) { size_t index = computeIndex(impl...); using dispatcher = Dispatcher<sizeof...(Impl)>; switch (index) { default: VISIT_1(0); } } }; template <> struct VisitHelper<1> { template <typename Functor, typename... Impl> static constexpr decltype(auto) issue(Functor&& functor, Impl&&... impl) { size_t index = computeIndex(impl...); using dispatcher = Dispatcher<sizeof...(Impl)>; switch (index) { default: VISIT_2(0); } } }; template <> struct VisitHelper<2> { template <typename Functor, typename... Impl> static constexpr decltype(auto) issue(Functor&& functor, Impl&&... impl) { size_t index = computeIndex(impl...); using dispatcher = Dispatcher<sizeof...(Impl)>; switch (index) { default: VISIT_4(0); } } }; template <> struct VisitHelper<3> { template <typename Functor, typename... Impl> static constexpr decltype(auto) issue(Functor&& functor, Impl&&... impl) { size_t index = computeIndex(impl...); using dispatcher = Dispatcher<sizeof...(Impl)>; switch (index) { default: VISIT_8(0); } } }; template <> struct VisitHelper<4> { template <typename Functor, typename... Impl> static constexpr decltype(auto) issue(Functor&& functor, Impl&&... impl) { size_t index = computeIndex(impl...); using dispatcher = Dispatcher<sizeof...(Impl)>; switch (index) { default: VISIT_16(0); } } }; #undef VISIT_1 #undef VISIT_2 #undef VISIT_4 #undef VISIT_8 #undef VISIT_16 // Use this as the definition so that the template parameters can auto-deduce. template <typename Functor, typename... Impl> decltype(auto) visitor(Functor&& functor, Impl&&... impl) { constexpr size_t size = TotalStates<Impl...>::value; constexpr int version = size <= 1 ? 0 : size <= 2 ? 1 : size <= 4 ? 2 : size <= 8 ? 3 : size <= 16 ? 4 : -1; return VisitHelper<version>::issue(std::forward<Functor>(functor), std::forward<Impl>(impl)...); } // Internal helper that generates smaller code when scanning two variants. template <size_t I, typename Functor, typename Hold1, typename Hold2> decltype(auto) visitSameOnce(Functor&& functor, Hold1&& hold1, Hold2&& hold2) { return std::forward<Functor>(functor)( variant_get_from_hold<I>(std::forward<Hold1>(hold1)), variant_get_from_hold<I>(std::forward<Hold2>(hold2))); } template <typename Functor, typename Hold1, typename Hold2, typename Ids = std::make_index_sequence<std::remove_reference<Hold1>::type::size>> struct VisitSameHelperTable; template <typename Functor, typename Hold1, typename Hold2, size_t... Ids> struct VisitSameHelperTable<Functor, Hold1, Hold2, std::index_sequence<Ids...>> { using return_type = decltype(std::declval<Functor>()( VariantGetFromHold<0>::get(std::declval<Hold1>()), VariantGetFromHold<0>::get(std::declval<Hold2>()))); using f_table_type = return_type (*)(Functor&&, Hold1&&, Hold2&&); static f_table_type& table(size_t id) { static f_table_type tbl[] = { &visitSameOnce<Ids, Functor, Hold1, Hold2>... }; return tbl[id]; } }; template <int I> struct VisitSameHelper; template <> struct VisitSameHelper<-1> { template <typename Functor, typename Hold1, typename Hold2> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold1&& hold1, Hold2&& hold2) { constexpr auto& entry = VisitSameHelperTable<Functor, Hold1, Hold2>::table(index); return entry(std::forward<Functor>(functor), std::forward<Hold1>(hold1), std::forward<Hold2>(hold2)); } }; #define VISIT_SAME_1(n) \ case (n): \ return functor(variant_get_from_hold<n>(std::forward<Hold1>(hold1)), \ variant_get_from_hold<n>(std::forward<Hold2>(hold2))); #define VISIT_SAME_2(n) \ VISIT_SAME_1(n) \ VISIT_SAME_1(n + 1) #define VISIT_SAME_4(n) \ VISIT_SAME_2(n) \ VISIT_SAME_2(n + 2) #define VISIT_SAME_8(n) \ VISIT_SAME_4(n) \ VISIT_SAME_4(n + 4) #define VISIT_SAME_16(n) \ VISIT_SAME_8(n) \ VISIT_SAME_8(n + 8) template <> struct VisitSameHelper<0> { template <typename Functor, typename Hold1, typename Hold2> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold1&& hold1, Hold2&& hold2) { switch (index) { default: VISIT_SAME_1(0); } } }; template <> struct VisitSameHelper<1> { template <typename Functor, typename Hold1, typename Hold2> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold1&& hold1, Hold2&& hold2) { switch (index) { default: VISIT_SAME_2(0); } } }; template <> struct VisitSameHelper<2> { template <typename Functor, typename Hold1, typename Hold2> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold1&& hold1, Hold2&& hold2) { switch (index) { default: VISIT_SAME_4(0); } } }; template <> struct VisitSameHelper<3> { template <typename Functor, typename Hold1, typename Hold2> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold1&& hold1, Hold2&& hold2) { switch (index) { default: VISIT_SAME_8(0); } } }; template <> struct VisitSameHelper<4> { template <typename Functor, typename Hold1, typename Hold2> static constexpr decltype(auto) issue(Functor&& functor, size_t index, Hold1&& hold1, Hold2&& hold2) { switch (index) { default: VISIT_SAME_16(0); } } }; #undef VISIT_SAME_1 #undef VISIT_SAME_2 #undef VISIT_SAME_4 #undef VISIT_SAME_8 #undef VISIT_SAME_16 // Use this as the definition so that the template parameters can auto-deduce. template <typename Functor, typename Hold1, typename Hold2> decltype(auto) visitor_same(Functor&& functor, size_t typeIndex, Hold1&& hold1, Hold2&& hold2) { constexpr int size = std::remove_reference<Hold1>::type::size; constexpr int version = size <= 1 ? 0 : size <= 2 ? 1 : size <= 4 ? 2 : size <= 8 ? 3 : size <= 16 ? 4 : -1; return VisitSameHelper<version>::issue( std::forward<Functor>(functor), typeIndex, std::forward<Hold1>(hold1), std::forward<Hold2>(hold2)); } template <std::size_t I, typename T, typename... Candiates> struct GetIndexOfHelper; template <std::size_t I, typename T, typename Candiate> struct GetIndexOfHelper<I, T, Candiate> { static constexpr size_t value = I; }; template <std::size_t I, typename T, typename FirstCandiate, typename... Candiates> struct GetIndexOfHelper<I, T, FirstCandiate, Candiates...> { static constexpr size_t value = std::is_same<T, FirstCandiate>::value ? I : GetIndexOfHelper<I + 1, T, Candiates...>::value; }; template <typename T, typename... Candiates> static constexpr size_t index_of_v = GetIndexOfHelper<0, T, Candiates...>::value; template <typename T, typename... Candiates> static constexpr size_t index_of_init_v = GetIndexOfHelper<0, std::remove_const_t<std::remove_reference_t<T>>, std::remove_const_t<Candiates>...>::value; template <bool IsTriviallyDesctructable, typename... Types> class VariantBaseImpl; template <typename... Types> class VariantBaseImpl<true, Types...> : public VariantHold<true, Types...> { public: using hold = VariantHold<true, Types...>; static constexpr size_t size = VariantHold<false, Types...>::size; CARB_VIZ size_t m_index; constexpr VariantBaseImpl() noexcept : hold{}, m_index(variant_npos) { } template <size_t I, class... Args> constexpr VariantBaseImpl(in_place_index_t<I>, Args&&... args) noexcept : hold{ in_place_index<I>, std::forward<Args>(args)... }, m_index(I) { } constexpr size_t index() const { return m_index; } void destroy() { m_index = variant_npos; } }; template <typename... Types> class VariantBaseImpl<false, Types...> : public VariantHold<false, Types...> { public: static constexpr size_t size = VariantHold<false, Types...>::size; using hold = VariantHold<false, Types...>; CARB_VIZ size_t m_index; constexpr VariantBaseImpl() noexcept : hold{}, m_index(variant_npos) { } template <size_t I, class... Args> constexpr VariantBaseImpl(in_place_index_t<I>, Args&&... args) noexcept : hold{ in_place_index<I>, std::forward<Args>(args)... }, m_index(I) { } constexpr size_t index() const { return m_index; } void destroy() { if (m_index != variant_npos) { detail::visitor( [](auto& obj) { using type = typename std::remove_reference<decltype(obj)>::type; obj.~type(); }, *this); } m_index = variant_npos; } ~VariantBaseImpl() { destroy(); } }; template <typename... Types> using VariantBase = VariantBaseImpl<conjunction<std::is_trivially_destructible<Types>...>::value, Types...>; } // namespace detail struct monostate { constexpr monostate() { } }; constexpr bool operator==(monostate, monostate) noexcept { return true; } constexpr bool operator!=(monostate, monostate) noexcept { return false; } constexpr bool operator<(monostate, monostate) noexcept { return false; } constexpr bool operator>(monostate, monostate) noexcept { return false; } constexpr bool operator<=(monostate, monostate) noexcept { return true; } constexpr bool operator>=(monostate, monostate) noexcept { return true; } template <typename Type> struct variant_alternative<0, variant<Type>> { using type = Type; }; template <typename Type, typename... OtherTypes> struct variant_alternative<0, variant<Type, OtherTypes...>> { using type = Type; }; template <size_t I, typename Type, typename... OtherTypes> struct variant_alternative<I, variant<Type, OtherTypes...>> { using type = typename variant_alternative<I - 1, variant<OtherTypes...>>::type; }; template <std::size_t I, typename T> using variant_alternative_t = typename variant_alternative<I, T>::type; template <typename... Types> class CARB_VIZ variant : public detail::VariantBase<Types...> { private: using base = detail::VariantBase<Types...>; using hold = typename base::hold; using self_type = variant<Types...>; public: constexpr variant() noexcept : base(in_place_index_t<0>()) { } constexpr variant(const variant& other) noexcept { base::m_index = other.index(); if (base::m_index != variant_npos) { detail::visitor_same( [](auto& dest, auto& src) { using type = typename std::remove_reference<decltype(src)>::type; new (&dest) type(src); }, other.index(), *this, other); base::m_index = other.index(); } } constexpr variant(variant&& other) noexcept { base::m_index = other.index(); if (base::m_index != variant_npos) { CARB_ASSERT(base::m_index < sizeof...(Types)); detail::visitor_same( [](auto& dest, auto&& src) { using type = typename std::remove_reference<decltype(src)>::type; new (&dest) type(std::move(src)); }, other.index(), *this, other); other.base::m_index = variant_npos; } } template <class T> constexpr variant(const T& value) noexcept : base{ in_place_index_t<detail::index_of_init_v<T, Types...>>(), value } { } template <class T, typename std::enable_if<!std::is_same<variant, std::remove_reference_t<std::remove_const_t<T>>>::value, bool>::type = true> constexpr variant(T&& value) noexcept : base{ in_place_index_t<detail::index_of_init_v<T, Types...>>(), std::move(value) } { } template <class T, class... Args> constexpr explicit variant(in_place_type_t<T>, Args&&... args) : base{ in_place_index_t<detail::index_of_init_v<T, Types...>>(), std::forward<Args>(args)... } { } template <std::size_t I, class... Args> constexpr explicit variant(in_place_index_t<I>, Args&&... args) : base{ in_place_index_t<I>(), std::forward<Args>(args)... } { } constexpr variant& operator=(const variant& rhs) { if (this != &rhs) { if (base::m_index != variant_npos) { base::destroy(); } if (rhs.base::m_index != variant_npos) { detail::visitor_same( [](auto& dest, auto& src) { using type = typename std::remove_reference<decltype(src)>::type; new (&dest) type(src); }, rhs.index(), *this, rhs); base::m_index = rhs.base::m_index; } } return *this; } constexpr variant& operator=(variant&& rhs) { if (this == &rhs) return *this; if (base::m_index != variant_npos) { base::destroy(); } base::m_index = rhs.base::m_index; if (base::m_index != variant_npos) { CARB_ASSERT(base::m_index < sizeof...(Types)); detail::visitor_same( [](auto& dest, auto&& src) { using type = typename std::remove_reference<decltype(src)>::type; new (&dest) type(std::move(src)); }, rhs.index(), *this, rhs); rhs.base::m_index = variant_npos; } return *this; } template <class T, typename std::enable_if<!std::is_same<variant, std::remove_reference_t<std::remove_const_t<T>>>::value, bool>::type = true> variant& operator=(T&& t) noexcept { constexpr size_t I = detail::index_of_init_v<T, Types...>; using type = variant_alternative_t<I, self_type>; type& v = detail::variant_get_from_hold<I>(*static_cast<hold*>(this)); if (index() == I) { v = std::move(t); } else { base::destroy(); new (&v) type(std::move(t)); base::m_index = I; } return *this; } constexpr bool valueless_by_exception() const noexcept { return base::m_index == variant_npos; } template <class T, class... Args> auto emplace(Args&&... args) -> std::remove_const_t<std::remove_reference_t<T>>& { base::destroy(); using place_type = std::remove_const_t<std::remove_reference_t<T>>; base::m_index = detail::index_of_v<place_type, Types...>; return *(new (&detail::variant_get_from_hold<detail::index_of_v<T, Types...>>(static_cast<hold&>(*this))) place_type(std::forward<Args>(args)...)); } constexpr std::size_t index() const noexcept { return base::m_index; } }; template <class T, class... Types> constexpr bool holds_alternative(const variant<Types...>& v) noexcept { return v.index() == detail::index_of_v<T, Types...>; } template <std::size_t I, class... Types> constexpr std::add_pointer_t<variant_alternative_t<I, variant<Types...>>> get_if(variant<Types...>* pv) noexcept { return (pv && I == pv->index()) ? &detail::variant_get_from_hold<I>(*pv) : nullptr; } template <std::size_t I, class... Types> constexpr std::add_pointer_t<const variant_alternative_t<I, variant<Types...>>> get_if(const variant<Types...>* pv) noexcept { return (pv && I == pv->index()) ? &detail::variant_get_from_hold<I>(*pv) : nullptr; } template <class T, class... Types> constexpr std::add_pointer_t<T> get_if(variant<Types...>* pv) noexcept { return get_if<detail::index_of_v<T, Types...>>(pv); } template <class T, class... Types> constexpr std::add_pointer_t<const T> get_if(const variant<Types...>* pv) noexcept { return get_if<detail::index_of_v<T, Types...>>(pv); } // Don't support moves yet... template <std::size_t I, class... Types> constexpr variant_alternative_t<I, variant<Types...>>& get(variant<Types...>& v) { auto o = get_if<I>(&v); if (o) { return *o; } detail::on_bad_variant_access(); } template <std::size_t I, class... Types> constexpr const variant_alternative_t<I, variant<Types...>>& get(const variant<Types...>& v) { auto o = get_if<I>(&v); if (o) { return *o; } detail::on_bad_variant_access(); } template <class T, class... Types> constexpr T& get(variant<Types...>& v) { auto o = get_if<T>(&v); if (o) { return *o; } detail::on_bad_variant_access(); } template <class T, class... Types> constexpr const T& get(const variant<Types...>& v) { auto o = get_if<T>(&v); if (o) { return *o; } detail::on_bad_variant_access(); } // Comparison template <class... Types> constexpr bool operator==(const variant<Types...>& v, const variant<Types...>& w) { return v.index() == w.index() && detail::visitor_same([](const auto& a, const auto& b) { return a == b; }, v.index(), v, w); } template <class... Types> constexpr bool operator!=(const variant<Types...>& v, const variant<Types...>& w) { return v.index() != w.index() || detail::visitor_same([](const auto& a, const auto& b) { return a != b; }, v.index(), v, w); } template <class... Types> constexpr bool operator<(const variant<Types...>& v, const variant<Types...>& w) { // If w.valueless_by_exception(), false; otherwise if v.valueless_by_exception(), true if (w.valueless_by_exception()) return false; if (v.valueless_by_exception()) return true; return v.index() < w.index() || (v.index() == w.index() && detail::visitor_same([](const auto& a, const auto& b) { return a < b; }, v.index(), v, w)); } template <class... Types> constexpr bool operator>(const variant<Types...>& v, const variant<Types...>& w) { // If v.valueless_by_exception(), false; otherwise if w.valueless_by_exception(), true if (v.valueless_by_exception()) return false; if (w.valueless_by_exception()) return true; return v.index() > w.index() || (v.index() == w.index() && detail::visitor_same([](const auto& a, const auto& b) { return a > b; }, v.index(), v, w)); } template <class... Types> constexpr bool operator<=(const variant<Types...>& v, const variant<Types...>& w) { // If v.valueless_by_exception(), true; otherwise if w.valueless_by_exception(), false if (v.valueless_by_exception()) return true; if (w.valueless_by_exception()) return false; return v.index() < w.index() || (v.index() == w.index() && detail::visitor_same([](const auto& a, const auto& b) { return a <= b; }, v.index(), v, w)); } template <class... Types> constexpr bool operator>=(const variant<Types...>& v, const variant<Types...>& w) { // If w.valueless_by_exception(), true; otherwise if v.valueless_by_exception(), false if (w.valueless_by_exception()) return true; if (v.valueless_by_exception()) return false; return v.index() > w.index() || (v.index() == w.index() && detail::visitor_same([](const auto& a, const auto& b) { return a >= b; }, v.index(), v, w)); } // Currently we only support one Variant and not a list. template <class Visitor, class... Variants> constexpr decltype(auto) visit(Visitor&& vis, Variants&&... variants) { return detail::visitor(std::forward<Visitor>(vis), std::forward<Variants>(variants)...); } } // namespace cpp } // namespace carb namespace std { template <> struct hash<carb::cpp::monostate> { CARB_NODISCARD size_t operator()(const carb::cpp::monostate&) const { // Just return something reasonable, there is not state with monostate. // This is just a random hex value. return 0x5f631327531c2962ull; } }; template <typename... Types> struct hash<carb::cpp::variant<Types...>> { CARB_NODISCARD size_t operator()(const carb::cpp::variant<Types...>& vis) const { // Valueless if (vis.index() == carb::cpp::variant_npos) { return 0; } return carb::hashCombine(std::hash<size_t>{}(vis.index()), carb::cpp::visit( // Invoking dohash directly is a compile // error. [](const auto& s) { return dohash(s); }, vis)); } private: // This is a simple way to remove the C-Ref qualifiers. template <class T> static size_t dohash(const T& t) { return std::hash<T>{}(t); } }; } // namespace std
37,739
C
30.45
124
0.556321
omniverse-code/kit/include/carb/cpp/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. // //! \file //! \brief C++14-compatible implementation of select functionality from C++ `<latch>` library. #pragma once #include "Atomic.h" #include <algorithm> #include <thread> namespace carb { namespace cpp { // Handle case where Windows.h may have defined 'max' #pragma push_macro("max") #undef max /** * Implements a C++20 latch in C++14 semantics. * * The latch class is a downward counter of type @c std::ptrdiff_t which can be used to synchronize threads. The value * of the counter is initialized on creation. Threads may block on the latch until the counter is decremented to zero. * There is no possibility to increase or reset the counter, which makes the latch a single-use @ref barrier. * * @thread_safety Concurrent invocations of the member functions of @c latch, except for the destructor, do not * introduce data races. * * Unlike @ref barrier, @c latch can be decremented by a participating thread more than once. */ class latch { CARB_PREVENT_COPY_AND_MOVE(latch); public: /** * The maximum value of counter supported by the implementation * @returns The maximum value of counter supported by the implementation. */ static constexpr ptrdiff_t max() noexcept { return ptrdiff_t(UINT_MAX); } /** * Constructor * * Constructs a latch and initializes its internal counter. The behavior is undefined if @p expected is negative or * greater than @ref max(). * @param expected The initial value of the internal counter. */ constexpr explicit latch(ptrdiff_t expected) noexcept : m_counter(uint32_t(::carb_min(max(), expected))) { CARB_ASSERT(expected >= 0 && expected <= max()); } /** * Destructor * * The behavior is undefined if any thread is concurrently calling a member function of the latch. * * @note This implementation waits until all waiting threads have woken, but this is a stronger guarantee than the * standard. */ ~latch() noexcept { // Wait until we have no waiters while (m_waiters.load(std::memory_order_acquire) != 0) std::this_thread::yield(); } /** * Decrements the counter in a non-blocking manner * * Atomically decrements the internal counter by @p update without blocking the caller. If the count reaches zero, * all blocked threads are unblocked. * * If @p update is greater than the value of the internal counter or is negative, the behavior is undefined. * * This operation strongly happens-before all calls that are unblocked on this latch. * * @param update The value by which the internal counter is decreased. * @throws std::system_error According to the standard, but this implementation does not throw. Instead an assertion * occurs. */ void count_down(ptrdiff_t update = 1) noexcept { CARB_ASSERT(update >= 0); // `fetch_sub` returns value before operation uint32_t count = m_counter.fetch_sub(uint32_t(update), std::memory_order_release); CARB_CHECK((count - uint32_t(update)) <= count); // Malformed if we go below zero or overflow if ((count - uint32_t(update)) == 0) { // Wake all waiters m_counter.notify_all(); } } // Returns whether the latch has completed. Allowed to return spuriously false with very low probability. /** * Tests if the internal counter equals zero * * Returns @c true only if the internal counter has reached zero. This function may spuriously return @c false with * very low probability even if the internal counter has reached zero. * * @note The reason why a spurious result is permitted is to allow implementations to use a memory order more * relaxed than @c std::memory_order_seq_cst. * * @return With very low probability @c false, otherwise `cnt == 0` where `cnt` is the value of the internal * counter. */ bool try_wait() const noexcept { return m_counter.load(std::memory_order_acquire) == 0; } /** * Blocks until the counter reaches zero * * Blocks the calling thread until the internal counter reaches zero. If it is zero already, returns immediately. * @throws std::system_error According to the standard, but this implementation does not throw. */ void wait() const noexcept { uint32_t count = m_counter.load(std::memory_order_acquire); if (count != 0) { // Register as a waiter m_waiters.fetch_add(1, std::memory_order_relaxed); _wait(count); } } /** * Decrements the counter and blocks until it reaches zero * * Atomically decrements the internal counter by @p update and (if necessary) blocks the calling thread until the * counter reaches zero. Equivalent to `count_down(update); wait();`. * * If @p update is greater than the value of the internal counter or is negative, the behavior is undefined. * * @param update The value by which the internal counter is decreased. * @throws std::system_error According to the standard, but this implementation does not throw. Instead an assertion * occurs. */ void arrive_and_wait(ptrdiff_t update = 1) noexcept { uint32_t original = m_counter.load(std::memory_order_acquire); if (original == uint32_t(update)) { // We're the last and won't be waiting. #if CARB_ASSERT_ENABLED uint32_t updated = m_counter.exchange(0, std::memory_order_release); CARB_ASSERT(updated == original); #else m_counter.store(0, std::memory_order_release); #endif // Wake all waiters m_counter.notify_all(); return; } // Speculatively register as a waiter m_waiters.fetch_add(1, std::memory_order_relaxed); original = m_counter.fetch_sub(uint32_t(update), std::memory_order_release); if (CARB_UNLIKELY(original == uint32_t(update))) { // Wake all waiters and unregister as a waiter m_counter.notify_all(); m_waiters.fetch_sub(1, std::memory_order_release); } else { CARB_CHECK(original >= uint32_t(update)); // Malformed if we underflow _wait(original - uint32_t(update)); } } private: mutable atomic_uint32_t m_counter; mutable atomic_uint32_t m_waiters{ 0 }; CARB_ALWAYS_INLINE void _wait(uint32_t count) const noexcept { CARB_ASSERT(count != 0); do { m_counter.wait(count, std::memory_order_relaxed); count = m_counter.load(std::memory_order_acquire); } while (count != 0); // Done waiting m_waiters.fetch_sub(1, std::memory_order_release); } }; #pragma pop_macro("max") } // namespace cpp } // namespace carb
7,433
C
33.901408
120
0.64698
omniverse-code/kit/include/carb/cpp/StdDef.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 C++14-compatible implementation of select functionality from C++ `<cstddef>` library. #pragma once #include "TypeTraits.h" namespace carb { namespace cpp { //! A byte is a distinct type that implements the concept of byte as specified in the C++ language definition. //! Like `char` and `unsigned char`, it can be used to access raw memory occupied by other objects, but unlike those //! types it is not a character type and is not an arithmetic type. A byte is only a collection of bits, and only //! bitwise operators are defined for it. enum class byte : unsigned char { }; #ifndef DOXYGEN_BUILD template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = false> constexpr IntegerType to_integer(byte b) noexcept { return static_cast<IntegerType>(b); } constexpr byte operator|(byte l, byte r) noexcept { return byte(static_cast<unsigned char>(l) | static_cast<unsigned char>(r)); } constexpr byte operator&(byte l, byte r) noexcept { return byte(static_cast<unsigned char>(l) & static_cast<unsigned char>(r)); } constexpr byte operator^(byte l, byte r) noexcept { return byte(static_cast<unsigned char>(l) ^ static_cast<unsigned char>(r)); } constexpr byte operator~(byte b) noexcept { return byte(~static_cast<unsigned char>(b)); } template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = false> constexpr byte operator<<(byte b, IntegerType shift) noexcept { return byte(static_cast<unsigned char>(b) << shift); } template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = false> constexpr byte operator>>(byte b, IntegerType shift) noexcept { return byte(static_cast<unsigned char>(b) >> shift); } template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = false> constexpr byte& operator<<=(byte& b, IntegerType shift) noexcept { b = b << shift; return b; } template <class IntegerType, std::enable_if_t<std::is_integral<IntegerType>::value, bool> = false> constexpr byte& operator>>=(byte& b, IntegerType shift) noexcept { b = b >> shift; return b; } constexpr byte& operator|=(byte& l, byte r) noexcept { l = l | r; return l; } constexpr byte& operator&=(byte& l, byte r) noexcept { l = l & r; return l; } constexpr byte& operator^=(byte& l, byte r) noexcept { l = l ^ r; return l; } #endif } // namespace cpp } // namespace carb
2,914
C
27.028846
116
0.713452
omniverse-code/kit/include/carb/cpp/Exception.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 C++14-compatible implementation of select functionality from C++ `<exception>` library. #pragma once #include "../Defines.h" #include <exception> #if CARB_PLATFORM_LINUX # include <cxxabi.h> # include <cstring> #elif CARB_PLATFORM_WINDOWS # include <cstring> extern "C" { void* __cdecl _getptd(void); } #endif // __cpp_lib_uncaught_exceptions -> https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros // Visual Studio 14.0+ supports N4152 std::uncaught_exceptions() but doesn't define __cpp_lib_uncaught_exceptions #if (defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411) || \ (defined(_MSC_VER) && _MSC_VER >= 1900) # define CARB_HAS_UNCAUGHT_EXCEPTIONS 1 #else # define CARB_HAS_UNCAUGHT_EXCEPTIONS 0 #endif namespace carb { namespace cpp { // // various ways to backport this, mainly come from accessing the systems thread local data and knowing // the exact offset the exception count is stored in. // // * https://beta.boost.org/doc/libs/develop/boost/core/uncaught_exceptions.hpp // * https://github.com/facebook/folly/blob/master/folly/lang/UncaughtExceptions.h // * https://github.com/bitwizeshift/BackportCpp/blob/master/include/bpstd/exception.hpp // inline int uncaught_exceptions() noexcept { #if CARB_HAS_UNCAUGHT_EXCEPTIONS return static_cast<int>(std::uncaught_exceptions()); #elif CARB_PLATFORM_LINUX using byte = unsigned char; int count{}; // __cxa_eh_globals::uncaughtExceptions, x32 offset - 0x4, x64 - 0x8 const auto* ptr = reinterpret_cast<const byte*>(::abi::__cxa_get_globals()) + sizeof(void*); std::memcpy(&count, ptr, sizeof(count)); return count; #elif CARB_PLATFORM_WINDOWS using byte = unsigned char; int count{}; const auto offset = (sizeof(void*) == 8u ? 0x100 : 0x90); const auto* ptr = static_cast<const byte*>(::_getptd()) + offset; // _tiddata::_ProcessingThrow, x32 offset - 0x90, x64 - 0x100 std::memcpy(&count, ptr, sizeof(count)); return count; #else // return C++11/14 uncaught_exception() is basically broken for any nested exceptions // as only going from 0 exceptions to 1 exception will be detected return static_cast<int>(std::uncaught_exception()); #endif } } // namespace cpp } // namespace carb
2,777
C
33.725
120
0.707238
omniverse-code/kit/include/carb/cpp/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 C++14-compatible implementation of select functionality from C++ `<span>` library. #pragma once #include "../Defines.h" #include "TypeTraits.h" #include "detail/ImplData.h" #include "StdDef.h" #include "../../omni/detail/PointerIterator.h" #include <array> namespace carb { namespace cpp { //! A constant of type size_t that is used to differentiate carb::cpp::span of static and dynamic extent //! @see span constexpr size_t dynamic_extent = size_t(-1); template <class T, size_t Extent> class span; //! \cond DEV namespace detail { template <class T> constexpr T* to_address(T* p) noexcept { static_assert(!std::is_function<T>::value, "Ill-formed if T is function type"); return p; } template <class Ptr, std::enable_if_t<std::is_pointer<decltype(std::declval<Ptr>().operator->())>::value, bool> = false> constexpr auto to_address(const Ptr& p) noexcept { return to_address(p.operator->()); } template <size_t Extent, size_t Offset, size_t Count> struct DetermineSubspanExtent { constexpr static size_t value = Count; }; template <size_t Extent, size_t Offset> struct DetermineSubspanExtent<Extent, Offset, dynamic_extent> { constexpr static size_t value = Extent - Offset; }; template <size_t Offset> struct DetermineSubspanExtent<dynamic_extent, Offset, dynamic_extent> { constexpr static size_t value = dynamic_extent; }; template <class T> struct IsStdArray : public std::false_type { }; template <class T, size_t N> struct IsStdArray<std::array<T, N>> : public std::true_type { }; template <class T> struct IsSpan : public std::false_type { }; template <class T, size_t N> struct IsSpan<span<T, N>> : public std::true_type { }; // GCC instantiates some functions always so they cannot use static_assert, but throwing an exception is allowed from a // constexpr function (which will act as a compile failure if constexpr) so fall back to that. #if CARB_EXCEPTIONS_ENABLED # define CARB_ALWAYS_FAIL(msg) throw std::out_of_range(msg) # define CARB_THROW_OR_CHECK(check, msg) \ if (!CARB_LIKELY(check)) \ throw std::out_of_range(msg) #else # define CARB_THROW_OR_CHECK(check, msg) CARB_CHECK((check), msg) # if CARB_COMPILER_MSC # define CARB_ALWAYS_FAIL(msg) static_assert(false, msg) # else # define CARB_ALWAYS_FAIL(msg) CARB_FATAL_UNLESS(false, msg) # endif #endif } // namespace detail //! \endcond /** * An object that refers to a contiguous sequence of objects. * * The class template span describes an object that can refer to a contiguous sequence of objects with the first element * of the sequence at position zero. A span can either have a \a static extent, in which case the number of elements in * the sequence is known at compile-time and encoded in the type, or a \a dynamic extent. * * If a span has \a dynamic extent, this implementation holds two members: a pointer to T and a size. A span with * \a static extent has only one member: a pointer to T. * * Every specialization of \c span is a \a TriviallyCopyable type. * * This implementation of \c span is a C++14-compatible implementation of the * [C++20 std::span](https://en.cppreference.com/w/cpp/container/span), as such certain constructors that involve * `ranges` or `concepts` are either not implemented or are implemented using C++14 paradigms. * * This implementation of \c span is a guaranteed @rstref{ABI- and interop-safe <abi-compatibility>} type. * * @note For function definitions below the following definitions are used: An ill-formed program will generate a * compiler error via `static_assert`. Undefined behavior is typically signaled by throwing a `std::out_of_range` * exception as this is allowed for `constexpr` functions to cause a compiler error, however, if exceptions are * disabled a \ref CARB_CHECK will occur (this also disables `constexpr` as \ref CARB_CHECK is not `constexpr`). * @tparam T Element type; must be a complete object type that is not an abstract class type * @tparam Extent The number of elements in the sequence, or \ref dynamic_extent if dynamic */ template <class T, size_t Extent = dynamic_extent> class span { // NOTE: This implementation is used for Extent != 0 && Extent != dynamic_extent, both of which have specializations public: using element_type = T; //!< The element type `T` using value_type = std::remove_cv_t<T>; //!< The value type; const/volatile is removed from `T` using size_type = std::size_t; //!< The size type `size_t` using difference_type = std::ptrdiff_t; //!< The difference type `ptrdiff_t` using pointer = T*; //!< The pointer type `T*` using const_pointer = const T*; //!< The const pointer type `const T*` using reference = T&; //!< The reference type `T&` using const_reference = const T&; //!< The const reference type `const T&` //! The iterator type \ref omni::detail::PointerIterator using iterator = omni::detail::PointerIterator<pointer, span>; //! The reverse iterator type `std::reverse_iterator<iterator>` using reverse_iterator = std::reverse_iterator<iterator>; //! The number of elements in the sequence, or \ref dynamic_extent if dynamic constexpr static std::size_t extent = Extent; #ifdef DOXYGEN_BUILD //! Default constructor //! //! Constructs an empty span whose \ref data() is `nullptr` and \ref size() is `0`. This constructor participates in //! overload resolution only if `extent == 0 || extent == dynamic_extent`. constexpr span() noexcept { } #endif //! Constructs a \ref span that is a view over the range `[first, first + count)`. //! //! Behavior is undefined if `count != extent` (for static extent) or \p first does not model `contiguous_iterator`. //! However, since `contiguous_iterator` is not available until C++20, instead this function does not participate in //! overload resolution unless `std::iterator_traits<It>::iterator_category == std::random_access_iterator_tag`. //! @param first An iterator or pointer type that models C++20 `contiguous_iterator` //! @param count The number of elements from \p first to include in the span. If `extent != dynamic_extent` then //! this must match \ref extent. template <class It CARB_NO_DOC( , std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false)> constexpr explicit span(It first, size_type count) { CARB_THROW_OR_CHECK(extent == count, "Behavior is undefined if count != extent"); m_p = detail::to_address(first); } //! Constructs a \ref span that is a view over the range `[first, last)`. //! //! Behavior is undefined if `(last - first) != extent` (for static extent) or if `[first, last)` does not represent //! a contiguous range. This function differs significantly from the C++20 definition since the concepts of //! `contiguous_iterator` and `sized_sentinel_for` are not available. Since these concepts are not available until //! C++20, instead this function does not participate in overload resolution unless //! `std::iterator_traits<It>::iterator_category == std::random_access_iterator_tag`. Also \p first and \p last must //! be a matching iterator type. //! @param first An iterator or pointer type that represents the first element in the span. //! @param last An iterator or pointer type that represents the past-the-end element in the span. template <class It CARB_NO_DOC( , std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false)> constexpr explicit span(It first, It last) { CARB_THROW_OR_CHECK((last - first) == extent, "Behavior is undefined if (last - first) != extent"); m_p = detail::to_address(first); } //! Constructs a span that is a view over an array. //! //! Behavior is undefined if `extent != dynamic_extent && N != extent`. //! @param arr The array to view template <std::size_t N> constexpr span(type_identity_t<element_type> (&arr)[N]) noexcept { static_assert(N == extent, "Undefined if N != extent"); m_p = cpp::data(arr); } //! Constructs a span that is a view over an array. //! //! Behavior is undefined if `extent != dynamic_extent && N != extent`. //! @param arr The array to view template <class U, std::size_t N CARB_NO_DOC(, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false)> constexpr span(std::array<U, N>& arr) noexcept { static_assert(N == extent, "Undefined if N != extent"); m_p = cpp::data(arr); } //! Constructs a span that is a view over an array. //! //! Behavior is undefined if `extent != dynamic_extent && N != extent`. //! @param arr The array to view template <class U, std::size_t N CARB_NO_DOC(, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false)> constexpr span(const std::array<U, N>& arr) noexcept { static_assert(N == extent, "Undefined if N != extent"); m_p = cpp::data(arr); } // template< class R > // explicit(extent != dynamic_extent) // constexpr span( R&& range ); // (Constructor not available without ranges, but approximate constructor follows) //! Constructs a span that is a view over a range. //! //! The behavior is undefined if any of the following are true: //! * `R` does not actually model `contiguous_range` and `sized_range` //! * if `R` does not model `borrowed_range` while `element_type` is non-const //! * `extent` is not `dynamic_extent` and the size of the range != `extent` //! //! @tparam R A range type. Since this implementation is for pre-C++20 and ranges are not available, this is an //! approximation of a `range`: This type must have `data()` and `size()` member functions that must be //! convertible to the \ref pointer and \ref size_type types respectively. //! @param range The range to view. Behavior is undefined if `[range.data(), range.data() + range.size())` is not a //! contiguous range or cannot be borrowed (i.e. it is a temporary that will expire leaving a danging pointer). template <class R CARB_NO_DOC( , std::enable_if_t<detail::IsConvertibleRange<cpp::remove_cvref_t<R>, pointer>::value && // These types have a separate constructor !detail::IsStdArray<cpp::remove_cvref_t<R>>::value && !detail::IsSpan<cpp::remove_cvref_t<R>>::value && !std::is_array<cpp::remove_cvref_t<R>>::value, bool> = false)> constexpr explicit span(R&& range) { CARB_THROW_OR_CHECK(range.size() == extent, "Behavior is undefined if R.size() != extent"); m_p = range.data(); } #ifndef DOXYGEN_BUILD template <class U, std::size_t N, std::enable_if_t<N == dynamic_extent && std::is_convertible<U, element_type>::value, bool> = false> constexpr explicit span(const span<U, N>& source) noexcept : m_p(source.data()) { CARB_CHECK(source.size() == extent); // specified as `noexcept` so we cannot throw } template <class U, std::size_t N, std::enable_if_t<N != dynamic_extent && std::is_convertible<U, element_type>::value, bool> = false> #else //! Converting constructor from another span. //! //! Behavior is undefined if `extent != dynamic_extent && source.size() != extent`. //! @tparam U `element_type` of \p source; must be convertible to `element_type` //! @tparam N `extent` of \p source //! @param source The span to convert from template <class U, std::size_t N> #endif constexpr span(const span<U, N>& source) noexcept : m_p(source.data()) { static_assert(N == extent, "Undefined if N != extent"); } //! Copy constructor //! @param other A span to copy from constexpr span(const span& other) noexcept = default; //! Assignment operator //! //! @param other A span to copy from //! @returns *this constexpr span& operator=(const span& other) noexcept = default; //! Returns an iterator to the first element of the span. //! //! If the span is empty, the returned iterator will be equal to \ref end(). //! @returns an \ref iterator to the first element of the span constexpr iterator begin() const noexcept { return iterator(m_p); } //! Returns an iterator to the element following the last element of the span. //! //! This element acts as a placeholder; attempting to access it results in undefined behavior. //! @returns an \ref iterator to the element following the last element of the span constexpr iterator end() const noexcept { return iterator(m_p + extent); } //! Returns a reverse iterator to the first element of the reversed span. //! //! It corresponds to the last element of the non-reversed span. If the span is empty, the returned iterator is //! equal to \ref rend(). //! @returns a \ref reverse_iterator to the first element of the reversed span constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator(end()); } //! Reverse a reverse iterator to the element following the last element of the reversed span. //! //! It corresponds to the element preceding the first element of the non-reversed span. This element acts as a //! placeholder, attempting to access it results in undefined behavior. //! @returns a \ref reverse_iterator to the element following the last element of the reversed span constexpr reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } //! Returns a reference to the first element in the span. //! //! Calling this on an empty span results in undefined behavior. //! @returns a reference to the first element constexpr reference front() const { return *m_p; } //! Returns a reference to the last element in a span. //! //! Calling this on an empty span results in undefined behavior. //! @returns a reference to the last element constexpr reference back() const { return m_p[extent - 1]; } //! Returns a reference to the element in the span at the given index. //! //! The behavior is undefined if \p index is out of range (i.e. if it is greater than or equal to \ref size() or //! the span is \ref empty()). //! @param index The index of the element to access //! @returns a reference to the element at position \p index constexpr reference operator[](size_type index) const { CARB_THROW_OR_CHECK(index < extent, "Behavior is undefined when index exceeds size()"); return m_p[index]; } //! Returns a pointer to the beginning of the sequence. //! @returns a pointer to the beginning of the sequence constexpr pointer data() const noexcept { return m_p; } //! Returns the number of elements in the span. //! @returns the number of elements in the span constexpr size_type size() const noexcept { return extent; } //! Returns the size of the sequence in bytes. //! @returns the size of the sequence in bytes constexpr size_type size_bytes() const noexcept { return sizeof(element_type) * extent; } //! Checks if the span is empty. //! @returns \c true if the span is empty (i.e. \ref size() == 0); \c false otherwise CARB_NODISCARD constexpr bool empty() const noexcept { return false; } //! Obtains a subspan consisting of the first N elements of the sequence. //! //! The program is ill-formed if `Count > extent`. The behavior is undefined if `Count > size()`. //! @tparam Count the number of elements of the subspan //! @returns a span that is a view over the first `Count` elements of `*this` template <std::size_t Count> constexpr span<element_type, Count> first() const { static_assert(Count <= extent, "Program ill-formed if Count > extent"); return span<element_type, Count>{ m_p, Count }; } //! Obtains a subspan consisting of the first N elements of the sequence. //! //! The program is ill-formed if `Count > extent`. The behavior is undefined if `Count > size()`. //! @param Count the number of elements of the subspan //! @returns a span of dynamic extent that is a view over the first `Count` elements of `*this` constexpr span<element_type, dynamic_extent> first(size_type Count) const { CARB_THROW_OR_CHECK(Count <= extent, "Program ill-formed if Count > extent"); return span<element_type, dynamic_extent>{ m_p, Count }; } //! Obtains a subspan consisting of the last N elements of the sequence. //! //! The program is ill-formed if `Count > Extent`. The behavior is undefined if `Count > size()`. //! @tparam Count the number of elements of the subspan //! @returns a span that is a view over the last `Count` elements of `*this` template <std::size_t Count> constexpr span<element_type, Count> last() const { static_assert(Count <= extent, "Program ill-formed if Count > extent"); return span<element_type, Count>{ m_p + (extent - Count), Count }; } //! Obtains a subspan consisting of the last N elements of the sequence. //! //! The program is ill-formed if `Count > extent`. The behavior is undefined if `Count > size()`. //! @param Count the number of elements of the subspan //! @returns a span of dynamic extent that is a view over the last `Count` elements of `*this` constexpr span<element_type, dynamic_extent> last(size_type Count) const { CARB_THROW_OR_CHECK(Count <= extent, "Program ill-formed if Count > extent"); return span<element_type, dynamic_extent>{ m_p + (extent - Count), Count }; } //! Obtains a subspan that is a view over Count elements of this span starting at Offset. //! //! If `Count` is \ref dynamic_extent, the number of elements in the subspan is \ref size() - `Offset` (i.e. it ends //! at the end of `*this`). //! Ill-formed if `Offset` is greater than \ref extent, or `Count` is not \ref dynamic_extent and `Count` is greater //! than \ref extent - `Offset`. //! Behavior is undefined if either `Offset` or `Count` is out of range. This happens if `Offset` is greater than //! \ref size(), or `Count` is not \ref dynamic_extent and `Count` is greater than \ref size() - `Offset`. //! The \ref extent of the returned span is determined as follows: if `Count` is not \ref dynamic_extent, `Count`; //! otherwise, if `Extent` is not \ref dynamic_extent, `Extent - Offset`; otherwise \ref dynamic_extent. //! @tparam Offset The offset within `*this` to start the subspan //! @tparam Count The length of the subspan, or \ref dynamic_extent to indicate the rest of the span. //! @returns A subspan of the given range template <std::size_t Offset, std::size_t Count = dynamic_extent> constexpr span<element_type, detail::DetermineSubspanExtent<extent, Offset, Count>::value> subspan() const { static_assert(Offset <= extent, "Ill-formed"); static_assert(Count == dynamic_extent || (Offset + Count) <= extent, "Ill-formed"); return span<element_type, detail::DetermineSubspanExtent<extent, Offset, Count>::value>{ data() + Offset, carb_min(size() - Offset, Count) }; } //! Obtains a subspan that is a view over Count elements of this span starting at Offset. //! //! If \p Count is \ref dynamic_extent, the number of elements in the subspan is \ref size() - `Offset` (i.e. it //! ends at the end of `*this`). //! Behavior is undefined if either \p Offset or \p Count is out of range. This happens if \p Offset is greater than //! \ref size(), or \p Count is not \ref dynamic_extent and \p Count is greater than \ref size() - \p Offset. //! The extent of the returned span is always \ref dynamic_extent. //! @param Offset The offset within `*this` to start the subspan //! @param Count The length of the subspan, or \ref dynamic_extent to indicate the rest of the span. //! @returns A subspan of the given range constexpr span<element_type, dynamic_extent> subspan(size_type Offset, size_type Count = dynamic_extent) const { CARB_THROW_OR_CHECK(Offset <= extent, "Program ill-formed if Offset > extent"); CARB_THROW_OR_CHECK(Count == dynamic_extent || (Offset + Count) <= extent, "Program ill-formed if Count is not dynamic_extent and is greater than Extent - Offset"); return { data() + Offset, carb_min(size() - Offset, Count) }; } private: pointer m_p; }; CARB_ASSERT_INTEROP_SAFE(span<int, 1>); // Doxygen can ignore the specializations #ifndef DOXYGEN_BUILD // Specialization for dynamic_extent template <class T> class span<T, dynamic_extent> { // NOTE: This specialization is for Extent == dynamic_extent public: using element_type = T; using value_type = std::remove_cv_t<T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using iterator = omni::detail::PointerIterator<pointer, span>; using reverse_iterator = std::reverse_iterator<iterator>; constexpr static std::size_t extent = dynamic_extent; constexpr span() noexcept : m_p(nullptr), m_size(0) { } template <class It, std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false> constexpr span(It first, size_type count) { m_p = detail::to_address(first); m_size = count; } template <class It, std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false> constexpr span(It first, It last) { m_p = detail::to_address(first); m_size = last - first; } template <std::size_t N> constexpr span(type_identity_t<element_type> (&arr)[N]) noexcept { m_p = cpp::data(arr); m_size = N; } template <class U, std::size_t N, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false> constexpr span(std::array<U, N>& arr) noexcept { m_p = cpp::data(arr); m_size = N; } template <class U, std::size_t N, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false> constexpr span(const std::array<U, N>& arr) noexcept { m_p = cpp::data(arr); m_size = N; } // template< class R > // explicit(extent != dynamic_extent) // constexpr span( R&& range ); // (Constructor not available without ranges, but approximate constructor follows) template <class R, std::enable_if_t<detail::IsConvertibleRange<cpp::remove_cvref_t<R>, pointer>::value && !detail::IsStdArray<cpp::remove_cvref_t<R>>::value && // has separate constructor !detail::IsSpan<cpp::remove_cvref_t<R>>::value && // has separate constructor !std::is_array<cpp::remove_cvref_t<R>>::value, // has separate constructor bool> = false> constexpr span(R&& range) { m_p = range.data(); m_size = range.size(); } template <class U, std::size_t N, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false> constexpr span(const span<U, N>& source) noexcept { m_p = source.data(); m_size = source.size(); } constexpr span(const span& other) noexcept = default; constexpr span& operator=(const span& other) noexcept = default; constexpr iterator begin() const noexcept { return iterator(m_p); } constexpr iterator end() const noexcept { return iterator(m_p + m_size); } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator(end()); } constexpr reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } constexpr reference front() const { CARB_THROW_OR_CHECK(!empty(), "Behavior is undefined when calling front() on an empty span"); return *m_p; } constexpr reference back() const { CARB_THROW_OR_CHECK(!empty(), "Behavior is undefined when calling back() on an empty span"); return m_p[m_size - 1]; } constexpr reference operator[](size_type index) const { CARB_THROW_OR_CHECK(index < m_size, "Behavior is undefined when index exceeds size()"); return m_p[index]; } constexpr pointer data() const noexcept { return m_p; } constexpr size_type size() const noexcept { return m_size; } constexpr size_type size_bytes() const noexcept { return sizeof(element_type) * m_size; } CARB_NODISCARD constexpr bool empty() const noexcept { return m_size == 0; } template <std::size_t Count> constexpr span<element_type, Count> first() const { CARB_THROW_OR_CHECK(Count <= m_size, "Behavior is undefined when Count > size()"); return span<element_type, Count>{ m_p, Count }; } constexpr span<element_type, dynamic_extent> first(size_type Count) const { CARB_THROW_OR_CHECK(Count <= m_size, "Behavior is undefined when Count > size()"); return span<element_type, dynamic_extent>{ m_p, Count }; } template <std::size_t Count> constexpr span<element_type, Count> last() const { CARB_THROW_OR_CHECK(Count <= m_size, "Behavior is undefined when Count > size()"); return span<element_type, Count>{ m_p + (m_size - Count), Count }; } constexpr span<element_type, dynamic_extent> last(size_type Count) const { CARB_THROW_OR_CHECK(Count <= m_size, "Behavior is undefined when Count > size()"); return span<element_type, dynamic_extent>{ m_p + (m_size - Count), Count }; } template <std::size_t Offset, std::size_t Count = dynamic_extent> constexpr span<element_type, detail::DetermineSubspanExtent<extent, Offset, Count>::value> subspan() const { CARB_THROW_OR_CHECK(Offset <= m_size, "Behavior is undefined when Offset > size()"); CARB_THROW_OR_CHECK(Count == dynamic_extent || (Offset + Count) <= m_size, "Behavior is undefined when Count != dynamic_extent and (Offset + Count) > size()"); return span<element_type, detail::DetermineSubspanExtent<extent, Offset, Count>::value>{ data() + Offset, carb_min(size() - Offset, Count) }; } constexpr span<element_type, dynamic_extent> subspan(size_type Offset, size_type Count = dynamic_extent) const { CARB_THROW_OR_CHECK(Offset <= m_size, "Behavior is undefined when Offset > size()"); CARB_THROW_OR_CHECK(Count == dynamic_extent || (Offset + Count) <= m_size, "Behavior is undefined when Count != dynamic_extent and (Offset + Count) > size()"); return { data() + Offset, carb_min(size() - Offset, Count) }; } private: pointer m_p; size_type m_size; }; // Specialization for zero template <class T> class span<T, 0> { // NOTE: This specialization is for Extent == 0 public: using element_type = T; using value_type = std::remove_cv_t<T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using iterator = omni::detail::PointerIterator<pointer, span>; using reverse_iterator = std::reverse_iterator<iterator>; constexpr static std::size_t extent = 0; constexpr span() noexcept = default; template <class It, std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false> constexpr explicit span(It first, size_type count) { CARB_UNUSED(first, count); CARB_THROW_OR_CHECK(count == 0, "Behavior is undefined if count != extent"); } template <class It, std::enable_if_t<std::is_same<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>::value, bool> = false> constexpr explicit span(It first, It last) { CARB_UNUSED(first, last); CARB_THROW_OR_CHECK(first == last, "Behavior is undefined if (last - first) != extent"); } template <std::size_t N> constexpr span(type_identity_t<element_type> (&arr)[N]) noexcept { CARB_UNUSED(arr); static_assert(N == extent, "Undefined if N != extent"); } template <class U, std::size_t N, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false> constexpr span(std::array<U, N>& arr) noexcept { CARB_UNUSED(arr); static_assert(N == extent, "Undefined if N != extent"); } template <class U, std::size_t N, std::enable_if_t<std::is_convertible<U, element_type>::value, bool> = false> constexpr span(const std::array<U, N>& arr) noexcept { CARB_UNUSED(arr); static_assert(N == extent, "Undefined if N != extent"); } // template< class R > // explicit(extent != dynamic_extent) // constexpr span( R&& range ); // (Constructor not available without ranges, but approximate constructor follows) template <class R, std::enable_if_t<detail::IsConvertibleRange<cpp::remove_cvref_t<R>, pointer>::value && !detail::IsStdArray<cpp::remove_cvref_t<R>>::value && // has separate constructor !detail::IsSpan<cpp::remove_cvref_t<R>>::value && // has separate constructor !std::is_array<cpp::remove_cvref_t<R>>::value, // has separate constructor bool> = false> constexpr explicit span(R&& range) { CARB_THROW_OR_CHECK(range.size() == extent, "Behavior is undefined if R.size() != extent"); } template <class U, std::size_t N, std::enable_if_t<N == dynamic_extent && std::is_convertible<U, element_type>::value, bool> = false> constexpr explicit span(const span<U, N>& source) noexcept { CARB_UNUSED(source); CARB_THROW_OR_CHECK(N == extent, "Behavior is undefined if N != extent"); } template <class U, std::size_t N, std::enable_if_t<N != dynamic_extent && std::is_convertible<U, element_type>::value, bool> = false> constexpr explicit span(const span<U, N>& source) noexcept { CARB_UNUSED(source); CARB_THROW_OR_CHECK(N == extent, "Behavior is undefined if N != extent"); } constexpr span(const span& other) noexcept = default; constexpr span& operator=(const span& other) noexcept = default; constexpr iterator begin() const noexcept { return end(); } constexpr iterator end() const noexcept { return iterator(nullptr); } constexpr reverse_iterator rbegin() const noexcept { return rend(); } constexpr reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } constexpr reference front() const { CARB_ALWAYS_FAIL("Behavior is undefined if front() is called on an empty span"); } constexpr reference back() const { CARB_ALWAYS_FAIL("Behavior is undefined if back() is called on an empty span"); } constexpr reference operator[](size_type index) const { CARB_UNUSED(index); CARB_ALWAYS_FAIL("Behavior is undefined if index >= size()"); } constexpr pointer data() const noexcept { return nullptr; } constexpr size_type size() const noexcept { return 0; } constexpr size_type size_bytes() const noexcept { return 0; } CARB_NODISCARD constexpr bool empty() const noexcept { return true; } template <std::size_t Count> constexpr span<element_type, Count> first() const { static_assert(Count <= extent, "Program ill-formed if Count > extent"); return span<element_type, Count>{}; } constexpr span<element_type, dynamic_extent> first(size_type Count) const { CARB_UNUSED(Count); CARB_THROW_OR_CHECK(Count == 0, "Behavior is undefined if Count > extent"); return span<element_type, dynamic_extent>{}; } template <std::size_t Count> constexpr span<element_type, Count> last() const { CARB_THROW_OR_CHECK(Count == 0, "Behavior is undefined if Count > extent"); return span<element_type, Count>{}; } constexpr span<element_type, dynamic_extent> last(size_type Count) const { CARB_UNUSED(Count); CARB_THROW_OR_CHECK(Count == 0, "Behavior is undefined if Count > extent"); return span<element_type, dynamic_extent>{}; } template <std::size_t Offset, std::size_t Count = dynamic_extent> constexpr span<element_type, detail::DetermineSubspanExtent<extent, Offset, Count>::value> subspan() const { static_assert(Offset <= extent, "Ill-formed"); static_assert(Count == dynamic_extent || (Offset + Count) <= extent, "Ill-formed"); return {}; } constexpr span<element_type, dynamic_extent> subspan(size_type Offset, size_type Count = dynamic_extent) const { CARB_UNUSED(Offset, Count); CARB_THROW_OR_CHECK(Offset <= extent, "Behavior is undefined if Offset > extent"); CARB_THROW_OR_CHECK(Count == dynamic_extent || (Offset + Count) <= extent, "Behavior is undefined if Count != dynamic_extent and (Offset + Count) > extent"); return {}; } }; CARB_ASSERT_INTEROP_SAFE(span<int, 0>); CARB_ASSERT_INTEROP_SAFE(span<int, dynamic_extent>); #endif #ifndef DOXYGEN_BUILD template <class T, std::size_t N, std::enable_if_t<N == dynamic_extent, bool> = false> span<const cpp::byte, dynamic_extent> as_bytes(span<T, N> s) noexcept { return { reinterpret_cast<const cpp::byte*>(s.data()), s.size_bytes() }; } template <class T, std::size_t N, std::enable_if_t<N != dynamic_extent, bool> = false> span<const cpp::byte, sizeof(T) * N> as_bytes(span<T, N> s) noexcept #else //! Obtains a view ot the object representation of the elements of the given span //! @tparam T the `element_type` of the span //! @tparam N the `extent` of the span //! @param s The span //! @returns A \ref span of type `span<const cpp::byte, E>` where `E` is \ref dynamic_extent if `N` is also //! \ref dynamic_extent, otherwise `E` is `sizeof(T) * N`. template <class T, std::size_t N> auto as_bytes(span<T, N> s) noexcept #endif { return span<const cpp::byte, sizeof(T) * N>{ reinterpret_cast<const cpp::byte*>(s.data()), s.size_bytes() }; } #ifndef DOXYGEN_BUILD template <class T, std::size_t N, std::enable_if_t<N == dynamic_extent, bool> = false> span<cpp::byte, dynamic_extent> as_writable_bytes(span<T, N> s) noexcept { return { reinterpret_cast<cpp::byte*>(s.data()), s.size_bytes() }; } template <class T, std::size_t N, std::enable_if_t<N != dynamic_extent, bool> = false> span<cpp::byte, sizeof(T) * N> as_writable_bytes(span<T, N> s) noexcept #else //! Obtains a writable view to the object representation of the elements of the given span //! @tparam T the `element_type` of the span //! @tparam N the `extent` of the span //! @param s The span //! @returns A \ref span of type `span<cpp::byte, E>` where `E` is \ref dynamic_extent if `N` is also //! \ref dynamic_extent, otherwise `E` is `sizeof(T) * N`. template <class T, std::size_t N> auto as_writable_bytes(span<T, N> s) noexcept #endif { return span<cpp::byte, sizeof(T) * N>{ reinterpret_cast<cpp::byte*>(s.data()), s.size_bytes() }; } #undef CARB_ALWAYS_FAIL #undef CARB_THROW_OR_CHECK } // namespace cpp } // namespace carb
37,511
C
38.653277
138
0.636507
omniverse-code/kit/include/carb/cpp/Bit.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 C++14-compatible implementation of select functionality from C++ `<bit>` library. #pragma once #include "TypeTraits.h" #include "detail/ImplDummy.h" #include "../extras/CpuInfo.h" #ifndef DOXYGEN_SHOULD_SKIP_THIS // CARB_POPCNT is 1 if the compiler is targeting a CPU with AVX instructions or GCC reports popcnt is available. It is // undefined at the bottom of the file. # if defined(__AVX__) /* MSC/GCC */ || defined(__POPCNT__) /* GCC */ # define CARB_POPCNT 1 # else # define CARB_POPCNT 0 # endif // CARB_LZCNT is 1 if the compiler is targeting a CPU with AVX2 instructions or GCC reports lzcnt is available. It is // undefined at the bottom of the file. # if defined(__AVX2__) /* MSC/GCC */ || defined(__LZCNT__) /* GCC */ # define CARB_LZCNT 1 # else # define CARB_LZCNT 0 # endif #endif #if CARB_COMPILER_MSC extern "C" { unsigned int __popcnt(unsigned int value); unsigned __int64 __popcnt64(unsigned __int64 value); unsigned char _BitScanReverse(unsigned long* _Index, unsigned long _Mask); unsigned char _BitScanReverse64(unsigned long* _Index, unsigned __int64 _Mask); unsigned char _BitScanForward(unsigned long* _Index, unsigned long _Mask); unsigned char _BitScanForward64(unsigned long* _Index, unsigned __int64 _Mask); # if CARB_LZCNT unsigned int __lzcnt(unsigned int); unsigned short __lzcnt16(unsigned short); unsigned __int64 __lzcnt64(unsigned __int64); # endif } # pragma intrinsic(__popcnt) # pragma intrinsic(__popcnt64) # pragma intrinsic(_BitScanReverse) # pragma intrinsic(_BitScanReverse64) # pragma intrinsic(_BitScanForward) # pragma intrinsic(_BitScanForward64) # if CARB_LZCNT # pragma intrinsic(__lzcnt) # pragma intrinsic(__lzcnt16) # pragma intrinsic(__lzcnt64) # endif #elif CARB_COMPILER_GNUC #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace carb { namespace cpp { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { // Naive implementation of popcnt for CPUs without built in instructions. template <class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true> constexpr int popCountImpl(T val) noexcept { int count = 0; while (val != 0) { ++count; val = val & (val - 1); } return count; } // The Helper class is specialized by type and size since many intrinsics have different names for different sizes. 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>; // popCount implementation for 1-4 bytes integers static int popCount(const T& val) { # if CARB_COMPILER_MSC # if !CARB_POPCNT // Skip the check if we know we have the instruction // Only use the intrinsic if it's supported on the CPU static extras::CpuInfo cpuInfo; if (!cpuInfo.popcntSupported()) { return popCountImpl((Unsigned)val); } else # endif { return (int)__popcnt((unsigned long)(Unsigned)val); } # else return __builtin_popcount((unsigned long)(Unsigned)val); # endif } static constexpr void propagateHighBit(T& n) { n |= (n >> 1); n |= (n >> 2); n |= (n >> 4); } static int countl_zero(T val) { # if CARB_LZCNT # if CARB_COMPILER_MSC return int(__lzcnt16((unsigned short)(Unsigned)val)) - (16 - std::numeric_limits<T>::digits); # else return int(__builtin_ia32_lzcnt_u16((unsigned short)(Unsigned)val)) - (16 - std::numeric_limits<T>::digits); # endif # else # if CARB_COMPILER_MSC unsigned long index; constexpr static int diff = std::numeric_limits<unsigned long>::digits - std::numeric_limits<T>::digits; return _BitScanReverse(&index, (unsigned long)(Unsigned)val) ? (std::numeric_limits<unsigned long>::digits - 1 - index - diff) : std::numeric_limits<T>::digits; # else // According to docs, undefined if val == 0 return val ? __builtin_clz((unsigned int)(Unsigned)val) - (32 - std::numeric_limits<T>::digits) : std::numeric_limits<T>::digits; # endif # endif } static int countr_zero(T val) { if (val == 0) { return std::numeric_limits<T>::digits; } else { # if CARB_COMPILER_MSC unsigned long result; _BitScanForward(&result, (unsigned long)(Unsigned)val); return (int)result; # else return __builtin_ctz((unsigned int)(Unsigned)val); # 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; static constexpr void propagateHighBit(T& n) { Base::propagateHighBit(n); n |= (n >> 8); } }; // 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; static constexpr void propagateHighBit(T& n) { Base::propagateHighBit(n); n |= (n >> 16); } # if CARB_LZCNT # if CARB_COMPILER_MSC static int countl_zero(T val) { static_assert(std::numeric_limits<T>::digits == 32, "Invalid assumption"); return int(__lzcnt((unsigned int)(Unsigned)val)); } # else static int countl_zero(T val) { static_assert(std::numeric_limits<T>::digits == 32, "Invalid assumption"); return int(__builtin_ia32_lzcnt_u32((unsigned int)(Unsigned)val)); } # endif # endif }; // 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; // popCount implementation for 8 byte integers static int popCount(const T& val) { static_assert(sizeof(T) == sizeof(uint64_t), "Unexpected size"); # if CARB_COMPILER_MSC # if !CARB_POPCNT // Skip the check if we know we have the instruction // Only use the intrinsic if it's supported on the CPU static extras::CpuInfo cpuInfo; if (!cpuInfo.popcntSupported()) { return popCountImpl((Unsigned)val); } else # endif { return (int)__popcnt64((Unsigned)val); } # else return __builtin_popcountll((Unsigned)val); # endif } static constexpr void propagateHighBit(T& n) { Base::propagateHighBit(n); n |= (n >> 32); } static int countl_zero(T val) { # if CARB_LZCNT # if CARB_COMPILER_MSC return int(__lzcnt64((Unsigned)val)); # else return int(__builtin_ia32_lzcnt_u64((Unsigned)val)); # endif # else # if CARB_COMPILER_MSC unsigned long index; static_assert(sizeof(val) == sizeof(unsigned __int64), "Invalid assumption"); return _BitScanReverse64(&index, val) ? std::numeric_limits<T>::digits - 1 - index : std::numeric_limits<T>::digits; # else // According to docs, undefined if val == 0 return val ? __builtin_clzll((Unsigned)val) : std::numeric_limits<T>::digits; # endif # endif } static int countr_zero(T val) { if (val == 0) { return std::numeric_limits<T>::digits; } else { # if CARB_COMPILER_MSC unsigned long result; _BitScanForward64(&result, (Unsigned)val); return (int)result; # else return __builtin_ctzll((Unsigned)val); # endif } } }; template <class U, class V> struct SizeMatches : cpp::bool_constant<sizeof(U) == sizeof(V)> { }; } // namespace detail #endif /** * Indicates the endianness of all scalar types for the current system. * * Endianness refers to byte ordering of scalar types larger than one byte. Take for example a 32-bit scalar with the * value "1". * On a little-endian system, the least-significant ("littlest") bytes are ordered first in memory. "1" would be * represented as: * @code{.txt} * 01 00 00 00 * @endcode * * On a big-endian system, the most-significant ("biggest") bytes are ordered first in memory. "1" would be represented * as: * @code{.txt} * 00 00 00 01 * @endcode */ enum class endian { #ifdef DOXYGEN_BUILD little = 0, //!< An implementation-defined value representing little-endian scalar types. big = 1, //!< An implementation-defined value representing big-endian scalar types. native = -1 //!< Will be either @ref endian::little or @ref endian::big depending on the target platform. #elif CARB_COMPILER_GNUC little = __ORDER_LITTLE_ENDIAN__, big = __ORDER_BIG_ENDIAN__, native = __BYTE_ORDER__ #else little = 0, big = 1, # if CARB_X86_64 || CARB_AARCH64 native = little # else CARB_UNSUPPORTED_PLATFORM(); # endif #endif }; /** * Re-interprets the bits @p src as type `To`. * * @note The `To` and `From` types must exactly match size and both be trivially copyable. * * See: https://en.cppreference.com/w/cpp/numeric/bit_cast * @tparam To The object type to convert to. * @tparam From The (typically inferred) object type to convert from. * @param src The source object to reinterpret. * @returns The reinterpreted object. */ template <class To, class From, std::enable_if_t<detail::SizeMatches<To, From>::value && std::is_trivially_copyable<From>::value && std::is_trivially_copyable<To>::value, bool> = false> /* constexpr */ // Cannot be constexpr without compiler support To bit_cast(const From& src) noexcept { // This union allows us to bypass `dest`'s constructor and just trivially copy into it. union { detail::NontrivialDummyType dummy{}; To dest; } u; std::memcpy(&u.dest, &src, sizeof(From)); return u.dest; } /** * Checks if a given value is an integral power of 2 * @see https://en.cppreference.com/w/cpp/numeric/has_single_bit * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns \c true if \p val is not zero and has a single bit set (integral power of two); \c false otherwise. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr bool has_single_bit(T val) noexcept { return val != T(0) && (val & (val - 1)) == T(0); } /** * Finds the smallest integral power of two not less than the given value. * @see https://en.cppreference.com/w/cpp/numeric/bit_ceil * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The smallest integral power of two that is not smaller than \p val. Undefined if the resulting value is not * representable in \c T. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr T bit_ceil(T val) noexcept { if (val <= 1) return T(1); // Yes, this could be implemented with a `nlz` instruction but cannot be constexpr without compiler support. --val; detail::Helper<T>::propagateHighBit(val); ++val; return val; } /** * Finds the largest integral power of two not greater than the given value. * @see https://en.cppreference.com/w/cpp/numeric/bit_floor * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The largest integral power of two not greater than \p val. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr T bit_floor(T val) noexcept { // Yes, this could be implemented with a `nlz` instruction but cannot be constexpr without compiler support. detail::Helper<T>::propagateHighBit(val); return val - (val >> 1); } /** * Returns the number of 1 bits in the value of x. * * @note Unlike std::popcount, this function is not constexpr. This is because the compiler intrinsics used to * implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to * use compiler intrinsics. If a constexpr implementation is required, use \ref popcount_constexpr(). * * @note (Intel/AMD CPUs) This function will check to see if the CPU supports the `popcnt` instruction (Intel Nehalem * micro-architecture, 2008; AMD Jaguar micro-architecture, 2013), and if it is not supported, will use a fallback * function that is ~85% slower than the `popcnt` instruction. If the compiler indicates that the target CPU has that * instruction, the CPU support check can be skipped, saving about 20%. This is accomplished with command-line switches: * `/arch:AVX` (or higher) for Visual Studio or `-march=sandybridge` (or several other `-march` options) for GCC. * * @param[in] val The unsigned integer value to test. * @returns The number of 1 bits in the value of \p val. */ template <class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true> int popcount(T val) noexcept { return detail::Helper<T>::popCount(val); } /** * Returns the number of 1 bits in the value of x. * * @note Unlike \ref popcount(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at * runtime it is recommended to use \ref popcount() instead of this function. * * @param[in] val The unsigned integer value to test. * @returns The number of 1 bits in the value of \p val. */ template <class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true> constexpr int popcount_constexpr(T val) noexcept { return detail::popCountImpl(val); } /** * Returns the number of consecutive 0 bits in the value of val, starting from the most significant bit ("left"). * @see https://en.cppreference.com/w/cpp/numeric/countl_zero * * @note Unlike std::countl_zero, this function is not constexpr. This is because the compiler intrinsics used to * implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to * use compiler intrinsics. If a constexpr implementation is required, use \ref countl_zero_constexpr(). * * @note (Intel/AMD CPUs) To support backwards compatibility with older CPUs, by default this is implemented with a * `bsr` instruction (i386+), that is slightly less performant (~3%) than the more modern `lzcnt` instruction. This * function implementation will switch to using `lzcnt` if the compiler indicates that instruction is supported. On * Visual Studio this is provided by passing `/arch:AVX2` command-line switch, or on GCC with `-march=haswell` (or * several other * `-march` options). The `lzcnt` instruction was * <a href="https://en.wikipedia.org/wiki/X86_Bit_manipulation_instruction_set">introduced</a> on Intel's Haswell micro- * architecture and AMD's Jaguar and Piledriver micro-architectures. * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 0 bits in the provided value, starting from the most significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> int countl_zero(T val) noexcept { return detail::Helper<T>::countl_zero(val); } /** * Returns the number of consecutive 0 bits in the value of val, starting from the most significant bit ("left"). * @see https://en.cppreference.com/w/cpp/numeric/countl_zero * * @note Unlike \ref countl_zero(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at * runtime it is recommended to use \ref countl_zero() instead of this function. * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 0 bits in the provided value, starting from the most significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr int countl_zero_constexpr(T val) noexcept { if (val == 0) return std::numeric_limits<T>::digits; unsigned zeros = 0; for (T shift = std::numeric_limits<T>::digits >> 1; shift; shift >>= 1) { T temp = val >> shift; if (temp) val = temp; else zeros |= shift; } return int(zeros); } /** * Returns the number of consecutive 0 bits in the value of val, starting from the least significant bit ("right"). * @see https://en.cppreference.com/w/cpp/numeric/countr_zero * * @note Unlike std::countr_zero, this function is not constexpr. This is because the compiler intrinsics used to * implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to * use compiler intrinsics. If a constexpr implementation is required, use \ref countr_zero_constexpr(). * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 0 bits in the provided value, starting from the least significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> int countr_zero(T val) noexcept { return detail::Helper<T>::countr_zero(val); } #pragma push_macro("max") #undef max /** * Returns the number of consecutive 0 bits in the value of val, starting from the least significant bit ("right"). * @see https://en.cppreference.com/w/cpp/numeric/countr_zero * * @note Unlike \ref countr_zero(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at * runtime it is recommended to use \ref countr_zero() instead of this function. * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 0 bits in the provided value, starting from the least significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr int countr_zero_constexpr(T val) noexcept { if (val == 0) return std::numeric_limits<T>::digits; if (val & 1) return 0; int zeros = 0; T shift = std::numeric_limits<T>::digits >> 1; T mask = std::numeric_limits<T>::max() >> shift; while (shift) { if (!(val & mask)) { val >>= shift; zeros |= shift; } shift >>= 1; mask >>= shift; } return zeros; } #pragma pop_macro("max") /** * Returns the number of consecutive 1 bits in the value of val, starting from the most significant bit ("left"). * @see https://en.cppreference.com/w/cpp/numeric/countl_one * * @note Unlike std::countl_one, this function is not constexpr. This is because the compiler intrinsics used to * implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to * use compiler intrinsics. If a constexpr implementation is required, use \ref countl_one_constexpr(). * * @note (Intel/AMD CPUs) To support backwards compatibility with older CPUs, by default this is implemented with a * `bsr` instruction (i386+), that is slightly less performant (~3%) than the more modern `lzcnt` instruction. This * function implementation will switch to using `lzcnt` if the compiler indicates that instruction is supported. On * Visual Studio this is provided by passing `/arch:AVX2` command-line switch, or on GCC with `-march=haswell` (or * several other * `-march` options). The `lzcnt` instruction was * <a href="https://en.wikipedia.org/wiki/X86_Bit_manipulation_instruction_set">introduced</a> on Intel's Haswell micro- * architecture and AMD's Jaguar and Piledriver micro-architectures. * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 1 bits in the provided value, starting from the most significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> int countl_one(T val) noexcept { return detail::Helper<T>::countl_zero(T(~val)); } /** * Returns the number of consecutive 1 bits in the value of val, starting from the most significant bit ("left"). * @see https://en.cppreference.com/w/cpp/numeric/countl_zero * * @note Unlike \ref countl_one(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at * runtime it is recommended to use \ref countl_one() instead of this function. * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 0 bits in the provided value, starting from the most significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr int countl_one_constexpr(T val) noexcept { return countl_zero_constexpr(T(~val)); } /** * Returns the number of consecutive 1 bits in the value of val, starting from the least significant bit ("right"). * @see https://en.cppreference.com/w/cpp/numeric/countr_one * * @note Unlike std::countr_one, this function is not constexpr. This is because the compiler intrinsics used to * implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to * use compiler intrinsics. If a constexpr implementation is required, use \ref countr_one_constexpr(). * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 1 bits in the provided value, starting from the least significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> int countr_one(T val) noexcept { return detail::Helper<T>::countr_zero(T(~val)); } /** * Returns the number of consecutive 1 bits in the value of val, starting from the least significant bit ("right"). * @see https://en.cppreference.com/w/cpp/numeric/countr_one * * @note Unlike \ref countr_one(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at * runtime it is recommended to use \ref countr_one() instead of this function. * * @tparam T An unsigned integral type * @param val An unsigned integral value * @returns The number of consecutive 1 bits in the provided value, starting from the least significant bit. */ template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false> constexpr int countr_one_constexpr(T val) noexcept { return countr_zero_constexpr(T(~val)); } } // namespace cpp } // namespace carb #undef CARB_LZCNT #undef CARB_POPCNT
23,782
C
35.365443
120
0.668447
omniverse-code/kit/include/carb/cpp/Numeric.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 C++14-compatible implementation of select functionality from C++ `<numeric>` library. #pragma once #include "../Defines.h" #include "Bit.h" namespace carb { namespace cpp { //! \cond DEV namespace detail { template <class Signed, std::enable_if_t<std::is_signed<Signed>::value, bool> = false> constexpr inline std::make_unsigned_t<Signed> abs(const Signed val) noexcept { using Unsigned = std::make_unsigned_t<Signed>; if (val < 0) return Unsigned(0) - Unsigned(val); return Unsigned(val); } template <class Unsigned, std::enable_if_t<std::is_unsigned<Unsigned>::value, bool> = false> constexpr inline Unsigned abs(const Unsigned val) noexcept { return val; } template <class Unsigned> constexpr inline unsigned long bitscan_forward(Unsigned mask) noexcept { // Since carb::cpp::countr_zero isn't constexpr... static_assert(std::is_unsigned<Unsigned>::value, "Must be an unsigned value"); unsigned long count = 0; if (mask != 0) { while ((mask & 1u) == 0) { mask >>= 1; ++count; } } return count; } template <class T> using NotBoolIntegral = ::carb::cpp::bool_constant<std::is_integral<T>::value && !std::is_same<std::remove_cv_t<T>, bool>::value>; } // namespace detail //! \endcond /** * Computes the greatest common divisor of two integers. * * If either `M` or `N` is not an integer type, or if either is (possibly cv-qualified) `bool`, the program is ill- * formed. If either `|m|` or `|n|` is not representable as a value of type `std::common_type_t<M, N>`, the behavior is * undefined. * @param m Integer value * @param n Integer value * @returns If both @p m and @p n are 0, returns 0; otherwise returns the greatest common divisor of `|m|` and `|n|`. */ template <class M, class N> constexpr inline std::common_type_t<M, N> gcd(M m, N n) noexcept /*strengthened*/ { static_assert(::carb::cpp::detail::NotBoolIntegral<M>::value && ::carb::cpp::detail::NotBoolIntegral<N>::value, "Requires non-bool integral"); using Common = std::common_type_t<M, N>; using Unsigned = std::make_unsigned_t<Common>; Unsigned am = ::carb::cpp::detail::abs(m); Unsigned an = ::carb::cpp::detail::abs(n); if (am == 0) return Common(an); if (an == 0) return Common(am); const auto trailingZerosM = ::carb::cpp::detail::bitscan_forward(am); const auto common2s = carb_min(trailingZerosM, ::carb::cpp::detail::bitscan_forward(an)); an >>= common2s; am >>= trailingZerosM; do { an >>= ::carb::cpp::detail::bitscan_forward(an); if (am > an) { Unsigned temp = am; am = an; an = temp; } an -= am; } while (an != 0u); return Common(am << common2s); } } // namespace cpp } // namespace carb
3,324
C
28.166666
119
0.640794
omniverse-code/kit/include/carb/cpp/Atomic.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 the wait/notify functions from C++20-standard atomics for types that are 1, 2, 4 or 8 bytes. If this // feature is not desired, or the type you're trying to atomic-wrap isn't supported, use std::atomic instead. // See the following: // https://en.cppreference.com/w/cpp/atomic/atomic/wait // https://en.cppreference.com/w/cpp/atomic/atomic/notify_one // https://en.cppreference.com/w/cpp/atomic/atomic/notify_all //! \file //! \brief C++14-compatible implementation of select functionality from C++ `<atomic>` library. #pragma once #include "../thread/Futex.h" #include "../thread/Util.h" #include <type_traits> #include <algorithm> namespace carb { namespace cpp { template <class T> class atomic; namespace detail { // C++20 adds fetch_add/fetch_sub and operator support for floating point types template <class T> class atomic_float_facade : public std::atomic<T> { using Base = std::atomic<T>; static_assert(std::is_floating_point<T>::value, ""); public: atomic_float_facade() noexcept = default; constexpr atomic_float_facade(T desired) noexcept : Base(desired) { } atomic_float_facade(const atomic_float_facade&) = delete; using Base::operator=; T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) noexcept { T temp = this->load(std::memory_order_relaxed); while (!this->compare_exchange_strong(temp, temp + arg, order, std::memory_order_relaxed)) { } return temp; } T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) volatile noexcept { T temp = this->load(std::memory_order_relaxed); while (!this->compare_exchange_strong(temp, temp + arg, order, std::memory_order_relaxed)) { } return temp; } T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) noexcept { T temp = this->load(std::memory_order_relaxed); while (!this->compare_exchange_strong(temp, temp - arg, order, std::memory_order_relaxed)) { } return temp; } T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) volatile noexcept { T temp = this->load(std::memory_order_relaxed); while (!this->compare_exchange_strong(temp, temp - arg, order, std::memory_order_relaxed)) { } return temp; } T operator+=(T arg) noexcept { return this->fetch_add(arg) + arg; } T operator+=(T arg) volatile noexcept { return this->fetch_add(arg) + arg; } T operator-=(T arg) noexcept { return this->fetch_sub(arg) - arg; } T operator-=(T arg) volatile noexcept { return this->fetch_sub(arg) - arg; } }; template <class T> class atomic_ref_base { protected: using AtomicType = ::carb::cpp::atomic<T>; AtomicType& m_ref; public: using value_type = T; static constexpr bool is_always_lock_free = AtomicType::is_always_lock_free; static constexpr std::size_t required_alignment = alignof(T); explicit atomic_ref_base(T& obj) : m_ref(reinterpret_cast<AtomicType&>(obj)) { } atomic_ref_base(const atomic_ref_base& ref) noexcept : m_ref(ref.m_ref) { } T operator=(T desired) const noexcept { m_ref.store(desired); return desired; } atomic_ref_base& operator=(const atomic_ref_base&) = delete; bool is_lock_free() const noexcept { return m_ref.is_lock_free(); } void store(T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept { m_ref.store(desired, order); } T load(std::memory_order order = std::memory_order_seq_cst) const noexcept { return m_ref.load(order); } operator T() const noexcept { return load(); } T exchange(T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept { return m_ref.exchange(desired, order); } bool compare_exchange_weak(T& expected, T desired, std::memory_order success, std::memory_order failure) const noexcept { return m_ref.compare_exchange_weak(expected, desired, success, failure); } bool compare_exchange_weak(T& expected, T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept { return m_ref.compare_exchange_weak(expected, desired, order); } bool compare_exchange_strong(T& expected, T desired, std::memory_order success, std::memory_order failure) const noexcept { return m_ref.compare_exchange_strong(expected, desired, success, failure); } bool compare_exchange_strong(T& expected, T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept { return m_ref.compare_exchange_strong(expected, desired, order); } void wait(T old, std::memory_order order = std::memory_order_seq_cst) const noexcept { m_ref.wait(old, order); } void wait(T old, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept { m_ref.wait(old, order); } template <class Rep, class Period> bool wait_for(T old, std::chrono::duration<Rep, Period> duration, std::memory_order order = std::memory_order_seq_cst) const noexcept { return m_ref.wait_for(old, duration, order); } template <class Rep, class Period> bool wait_for(T old, std::chrono::duration<Rep, Period> duration, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept { return m_ref.wait_for(old, duration, order); } template <class Clock, class Duration> bool wait_until(T old, std::chrono::time_point<Clock, Duration> time_point, std::memory_order order = std::memory_order_seq_cst) const noexcept { return m_ref.wait_until(old, time_point, order); } template <class Clock, class Duration> bool wait_until(T old, std::chrono::time_point<Clock, Duration> time_point, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept { return m_ref.wait_until(old, time_point, order); } void notify_one() const noexcept { m_ref.notify_one(); } void notify_one() const volatile noexcept { m_ref.notify_one(); } void notify_all() const noexcept { m_ref.notify_all(); } void notify_all() const volatile noexcept { m_ref.notify_all(); } }; template <class T> class atomic_ref_pointer_facade : public atomic_ref_base<T> { using Base = atomic_ref_base<T>; static_assert(std::is_pointer<T>::value, ""); public: using difference_type = std::ptrdiff_t; explicit atomic_ref_pointer_facade(T& ref) : Base(ref) { } atomic_ref_pointer_facade(const atomic_ref_pointer_facade& other) noexcept : Base(other) { } using Base::operator=; T fetch_add(std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_add(arg, order); } T fetch_sub(std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_sub(arg, order); } T operator++() const noexcept { return this->m_ref.fetch_add(1) + 1; } T operator++(int) const noexcept { return this->m_ref.fetch_add(1); } T operator--() const noexcept { return this->m_ref.fetch_sub(1) - 1; } T operator--(int) const noexcept { return this->m_ref.fetch_sub(1); } T operator+=(std::ptrdiff_t arg) const noexcept { return this->m_ref.fetch_add(arg) + arg; } T operator-=(std::ptrdiff_t arg) const noexcept { return this->m_ref.fetch_sub(arg) - arg; } }; template <class T> class atomic_ref_numeric_facade : public atomic_ref_base<T> { using Base = atomic_ref_base<T>; static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, ""); public: using difference_type = T; explicit atomic_ref_numeric_facade(T& ref) : Base(ref) { } atomic_ref_numeric_facade(const atomic_ref_numeric_facade& other) noexcept : Base(other) { } using Base::operator=; T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_add(arg, order); } T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_sub(arg, order); } T operator+=(T arg) const noexcept { return this->m_ref.fetch_add(arg) + arg; } T operator-=(T arg) const noexcept { return this->m_ref.fetch_sub(arg) - arg; } }; template <class T> class atomic_ref_integer_facade : public atomic_ref_numeric_facade<T> { using Base = atomic_ref_numeric_facade<T>; static_assert(std::is_integral<T>::value, ""); public: explicit atomic_ref_integer_facade(T& ref) : Base(ref) { } atomic_ref_integer_facade(const atomic_ref_integer_facade& other) noexcept : Base(other) { } using Base::operator=; T fetch_and(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_and(arg, order); } T fetch_or(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_or(arg, order); } T fetch_xor(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept { return this->m_ref.fetch_xor(arg, order); } T operator++() const noexcept { return this->m_ref.fetch_add(T(1)) + T(1); } T operator++(int) const noexcept { return this->m_ref.fetch_add(T(1)); } T operator--() const noexcept { return this->m_ref.fetch_sub(T(1)) - T(1); } T operator--(int) const noexcept { return this->m_ref.fetch_sub(T(1)); } T operator&=(T arg) const noexcept { return this->m_ref.fetch_and(arg) & arg; } T operator|=(T arg) const noexcept { return this->m_ref.fetch_or(arg) | arg; } T operator^=(T arg) const noexcept { return this->m_ref.fetch_xor(arg) ^ arg; } }; template <class T> using SelectAtomicRefBase = std::conditional_t< std::is_pointer<T>::value, atomic_ref_pointer_facade<T>, std::conditional_t<std::is_integral<T>::value, atomic_ref_integer_facade<T>, std::conditional_t<std::is_floating_point<T>::value, atomic_ref_numeric_facade<T>, atomic_ref_base<T>>>>; template <class T> using SelectAtomicBase = std::conditional_t<std::is_floating_point<T>::value, atomic_float_facade<T>, std::atomic<T>>; } // namespace detail template <class T> class atomic : public detail::SelectAtomicBase<T> { using Base = detail::SelectAtomicBase<T>; public: using value_type = T; atomic() noexcept = default; constexpr atomic(T desired) noexcept : Base(desired) { } static constexpr bool is_always_lock_free = sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8; using Base::operator=; using Base::operator T; CARB_PREVENT_COPY_AND_MOVE(atomic); // See https://en.cppreference.com/w/cpp/atomic/atomic/wait void wait(T old, std::memory_order order = std::memory_order_seq_cst) const noexcept { static_assert(is_always_lock_free, "Only supported for always-lock-free types"); using I = thread::detail::to_integral_t<T>; for (;;) { if (this_thread::spinTryWait([&] { return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old); })) { break; } thread::futex::wait(*this, old); } } void wait(T old, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept { static_assert(is_always_lock_free, "Only supported for always-lock-free types"); using I = thread::detail::to_integral_t<T>; for (;;) { if (this_thread::spinTryWait([&] { return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old); })) { break; } thread::futex::wait(const_cast<atomic<T>&>(*this), old); } } // wait_for and wait_until are non-standard template <class Rep, class Period> bool wait_for(T old, std::chrono::duration<Rep, Period> duration, std::memory_order order = std::memory_order_seq_cst) const noexcept { // Since futex can spuriously wake up, calculate the end time so that we can handle the spurious wakeups without // shortening our wait time potentially significantly. return wait_until(old, std::chrono::steady_clock::now() + thread::detail::clampDuration(duration), order); } template <class Rep, class Period> bool wait_for(T old, std::chrono::duration<Rep, Period> duration, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept { // Since futex can spuriously wake up, calculate the end time so that we can handle the spurious wakeups without // shortening our wait time potentially significantly. return wait_until(old, std::chrono::steady_clock::now() + thread::detail::clampDuration(duration), order); } template <class Clock, class Duration> bool wait_until(T old, std::chrono::time_point<Clock, Duration> time_point, std::memory_order order = std::memory_order_seq_cst) const noexcept { static_assert(is_always_lock_free, "Only supported for always-lock-free types"); using I = thread::detail::to_integral_t<T>; for (;;) { if (this_thread::spinTryWait([&] { return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old); })) { return true; } if (!thread::futex::wait_until(*this, old, time_point)) { return false; } } } template <class Clock, class Duration> bool wait_until(T old, std::chrono::time_point<Clock, Duration> time_point, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept { static_assert(is_always_lock_free, "Only supported for always-lock-free types"); using I = thread::detail::to_integral_t<T>; for (;;) { if (this_thread::spinTryWait([&] { return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old); })) { return true; } if (!thread::futex::wait_until(const_cast<atomic<T>&>(*this), old, time_point)) { return false; } } } // See https://en.cppreference.com/w/cpp/atomic/atomic/notify_one void notify_one() noexcept { thread::futex::notify_one(*this); } void notify_one() volatile noexcept { thread::futex::notify_one(const_cast<atomic<T>&>(*this)); } // See https://en.cppreference.com/w/cpp/atomic/atomic/notify_all void notify_all() noexcept { thread::futex::notify_all(*this); } void notify_all() volatile noexcept { thread::futex::notify_all(const_cast<atomic<T>&>(*this)); } }; template <class T> class atomic_ref : public detail::SelectAtomicRefBase<T> { using Base = detail::SelectAtomicRefBase<T>; public: explicit atomic_ref(T& ref) : Base(ref) { } atomic_ref(const atomic_ref& other) noexcept : Base(other) { } using Base::operator=; }; // Helper functions // See https://en.cppreference.com/w/cpp/atomic/atomic_wait template <class T> inline void atomic_wait(const atomic<T>* object, typename atomic<T>::value_type old) noexcept { object->wait(old); } template <class T> inline void atomic_wait_explicit(const atomic<T>* object, typename atomic<T>::value_type old, std::memory_order order) noexcept { object->wait(old, order); } // See https://en.cppreference.com/w/cpp/atomic/atomic_notify_one template <class T> inline void atomic_notify_one(atomic<T>* object) { object->notify_one(); } // See https://en.cppreference.com/w/cpp/atomic/atomic_notify_all template <class T> inline void atomic_notify_all(atomic<T>* object) { object->notify_all(); } using atomic_bool = atomic<bool>; using atomic_char = atomic<char>; using atomic_schar = atomic<signed char>; using atomic_uchar = atomic<unsigned char>; using atomic_short = atomic<short>; using atomic_ushort = atomic<unsigned short>; using atomic_int = atomic<int>; using atomic_uint = atomic<unsigned int>; using atomic_long = atomic<long>; using atomic_ulong = atomic<unsigned long>; using atomic_llong = atomic<long long>; using atomic_ullong = atomic<unsigned long long>; using atomic_char16_t = atomic<char16_t>; using atomic_char32_t = atomic<char32_t>; using atomic_wchar_t = atomic<wchar_t>; using atomic_int8_t = atomic<int8_t>; using atomic_uint8_t = atomic<uint8_t>; using atomic_int16_t = atomic<int16_t>; using atomic_uint16_t = atomic<uint16_t>; using atomic_int32_t = atomic<int32_t>; using atomic_uint32_t = atomic<uint32_t>; using atomic_int64_t = atomic<int64_t>; using atomic_uint64_t = atomic<uint64_t>; using atomic_int_least8_t = atomic<int_least8_t>; using atomic_uint_least8_t = atomic<uint_least8_t>; using atomic_int_least16_t = atomic<int_least16_t>; using atomic_uint_least16_t = atomic<uint_least16_t>; using atomic_int_least32_t = atomic<int_least32_t>; using atomic_uint_least32_t = atomic<uint_least32_t>; using atomic_int_least64_t = atomic<int_least64_t>; using atomic_uint_least64_t = atomic<uint_least64_t>; using atomic_int_fast8_t = atomic<int_fast8_t>; using atomic_uint_fast8_t = atomic<uint_fast8_t>; using atomic_int_fast16_t = atomic<int_fast16_t>; using atomic_uint_fast16_t = atomic<uint_fast16_t>; using atomic_int_fast32_t = atomic<int_fast32_t>; using atomic_uint_fast32_t = atomic<uint_fast32_t>; using atomic_int_fast64_t = atomic<int_fast64_t>; using atomic_uint_fast64_t = atomic<uint_fast64_t>; using atomic_intptr_t = atomic<intptr_t>; using atomic_uintptr_t = atomic<uintptr_t>; using atomic_size_t = atomic<size_t>; using atomic_ptrdiff_t = atomic<ptrdiff_t>; using atomic_intmax_t = atomic<intmax_t>; using atomic_uintmax_t = atomic<uintmax_t>; } // namespace cpp } // namespace carb
19,529
C
30.704545
128
0.623995
omniverse-code/kit/include/carb/cpp/detail/ImplData.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 C++14-compatible implementation of the C++ standard library `std::data` function. #pragma once #include <cstddef> #include <initializer_list> namespace carb { namespace cpp { //! Returns a pointer to the block of memory containing the elements of the range. //! @tparam T The type of the array elements //! @tparam N The size of the array //! @param array An array //! @returns array template <class T, std::size_t N> constexpr T* data(T (&array)[N]) noexcept { return array; } //! Returns a pointer to the block of memory containing the elements of the range. //! @tparam C The container type //! @param c A container //! @returns `c.data()` template <class C> constexpr auto data(C& c) -> decltype(c.data()) { return c.data(); } //! Returns a pointer to the block of memory containing the elements of the range. //! @tparam C The container type //! @param c A container //! @returns `c.data()` template <class C> constexpr auto data(const C& c) -> decltype(c.data()) { return c.data(); } //! Returns a pointer to the block of memory containing the elements of the range. //! @tparam E The type contained in the `std::initializer_list` //! @param il An `std::initializer_list` of type E //! @returns `il.begin()` template <class E> constexpr const E* data(std::initializer_list<E> il) noexcept { return il.begin(); } } // namespace cpp } // namespace carb
1,836
C
27.261538
92
0.712418
omniverse-code/kit/include/carb/cpp/detail/ImplDummy.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 details #pragma once #include <type_traits> namespace carb { namespace cpp { //! \cond DEV namespace detail { struct NontrivialDummyType { constexpr NontrivialDummyType() noexcept { } }; static_assert(!std::is_trivially_default_constructible<NontrivialDummyType>::value, "Invalid assumption"); } // namespace detail //! \endcond } // namespace cpp } // namespace carb
857
C
21.578947
106
0.752625
omniverse-code/kit/include/carb/cpp/detail/ImplInvoke.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 Implementation details for `carb::cpp::invoke` and related functions. #pragma once #include "../../Defines.h" #include "../../detail/NoexceptType.h" #include <functional> #include <type_traits> #include <utility> //! \file //! Contains common utilities used by \c invoke (which lives in the \c functional header) and the \c invoke_result type //! queries (which live in the \c type_traits header). namespace carb { namespace cpp { //! \cond DEV namespace detail { CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE() template <typename T> struct is_reference_wrapper : std::false_type { }; template <typename T> struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type { }; // The interface of invoke_impl are the `eval` and `uneval` functions, which have the correct return type and noexcept // specifiers for an expression `INVOKE(f, args...)` (this comes from the C++ concept of "Callable"). The two functions // are identical, save for the `eval` function having a body while the `uneval` function does not. This matters for // functions with declared-but-undefined return types. It is legal to ask type transformation questions about a function // `R (*)(Args...)` when `R` is undefined, but not legal to evaluate it in any way. // // Base template: T is directly invocable -- a function pointer or object with operator() template <typename T> struct invoke_impl { template <typename F, typename... TArgs> static constexpr auto eval(F&& f, TArgs&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<TArgs>(args)...))) -> decltype(std::forward<F>(f)(std::forward<TArgs>(args)...)) { return std::forward<F>(f)(std::forward<TArgs>(args)...); } template <typename F, typename... TArgs> static constexpr auto uneval(F&& f, TArgs&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<TArgs>(args)...))) -> decltype(std::forward<F>(f)(std::forward<TArgs>(args)...)); }; // Match the case where we want to invoke a member function. template <typename TObject, typename TReturn> struct invoke_impl<TReturn TObject::*> { using Self = invoke_impl; template <bool B> using bool_constant = std::integral_constant<bool, B>; #if CARB_COMPILER_GNUC == 1 && __cplusplus <= 201703L // WORKAROUND for pre-C++20: Calling a `const&` member function on an `&&` object through invoke is a C++20 // extension. MSVC supports this, but GNUC-compatible compilers do not until C++20. To work around this, we change // the object's ref qualifier from `&&` to `const&` if we are attempting to call a `const&` member function. // // Note `move(x).f()` has always been allowed if `f` is `const&` qualified, the issue is `std::move(x).*(&T::foo)()` // is not allowed (this is a C++ specification bug, corrected in C++20). Further note that we can not do this for // member data selectors, because the ref qualifier carries through since C++17. When this workaround is no longer // needed (when C++20 is minimum), the `_is_cref_mem_fn` tests on the `_access` functions can be removed. template <typename UReturn, typename UObject, typename... UArgs> static std::true_type _test_is_cref_mem_fn(UReturn (UObject::*mem_fn)(UArgs...) const&); static std::false_type _test_is_cref_mem_fn(...); template <typename TRMem> using _is_cref_mem_fn = decltype(_test_is_cref_mem_fn(std::declval<std::decay_t<TRMem>>())); template <typename T, typename = std::enable_if_t<std::is_base_of<TObject, std::decay_t<T>>::value>> static constexpr auto _access(T&& x, std::false_type) noexcept -> std::add_rvalue_reference_t<T> { return std::forward<T>(x); } template <typename T, typename = std::enable_if_t<std::is_base_of<TObject, std::decay_t<T>>::value>> static constexpr auto _access(T const& x, std::true_type) noexcept -> T const& { return x; } #else template <typename> using _is_cref_mem_fn = std::false_type; // Accessing the type should be done directly. template <typename T, bool M, typename = std::enable_if_t<std::is_base_of<TObject, std::decay_t<T>>::value>> static constexpr auto _access(T&& x, bool_constant<M>) noexcept -> std::add_rvalue_reference_t<T> { return std::forward<T>(x); } #endif // T is a reference wrapper -- access goes through the `get` function. template <typename T, bool M, typename = std::enable_if_t<is_reference_wrapper<std::decay_t<T>>::value>> static constexpr auto _access(T&& x, bool_constant<M>) noexcept(noexcept(x.get())) -> decltype(x.get()) { return x.get(); } // Matches cases where a pointer or fancy pointer is passed in. template <typename TOriginal, bool M, typename T = std::decay_t<TOriginal>, typename = std::enable_if_t<!std::is_base_of<TObject, T>::value && !is_reference_wrapper<T>::value>> static constexpr auto _access(TOriginal&& x, bool_constant<M>) noexcept(noexcept(*std::forward<TOriginal>(x))) -> decltype(*std::forward<TOriginal>(x)) { return *std::forward<TOriginal>(x); } template <typename T, typename... TArgs, typename TRMem, typename = std::enable_if_t<std::is_function<TRMem>::value>> static constexpr auto eval(TRMem TObject::*pmem, T&& x, TArgs&&... args) noexcept(noexcept( (Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*pmem)(std::forward<TArgs>(args)...))) -> decltype((Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).* pmem)(std::forward<TArgs>(args)...)) { return (Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*pmem)(std::forward<TArgs>(args)...); } template <typename T, typename... TArgs, typename TRMem, typename = std::enable_if_t<std::is_function<TRMem>::value>> static constexpr auto uneval(TRMem TObject::*pmem, T&& x, TArgs&&... args) noexcept(noexcept( (Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*pmem)(std::forward<TArgs>(args)...))) -> decltype((Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).* pmem)(std::forward<TArgs>(args)...)); template <typename T> static constexpr auto eval(TReturn TObject::*select, T&& x) noexcept(noexcept(Self::_access(std::forward<T>(x), std::false_type{}).*select)) -> decltype(Self::_access(std::forward<T>(x), std::false_type{}).*select) { return Self::_access(std::forward<T>(x), std::false_type{}).*select; } template <typename T> static constexpr auto uneval(TReturn TObject::*select, T&& x) noexcept(noexcept(Self::_access(std::forward<T>(x), std::false_type{}).*select)) -> decltype(Self::_access(std::forward<T>(x), std::false_type{}).*select); }; // Test invocation of `f(args...)` in an unevaluated context to get its return type. This is a SFINAE-safe error if the // expression `f(args...)` is invalid. template <typename F, typename... TArgs> auto invoke_uneval(F&& f, TArgs&&... args) noexcept( noexcept(invoke_impl<std::decay_t<F>>::uneval(std::forward<F>(f), std::forward<TArgs>(args)...))) -> decltype(invoke_impl<std::decay_t<F>>::uneval(std::forward<F>(f), std::forward<TArgs>(args)...)); CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE() } // namespace detail //! \endcond } // namespace cpp } // namespace carb
8,010
C
44.005618
122
0.650687
omniverse-code/kit/include/carb/cpp/detail/ImplOptional.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 Implementation details for `carb::cpp::optional<>`. #pragma once #ifndef CARB_IMPLOPTIONAL # error This file should only be included from Optional.h #endif #include <utility> #include "../TypeTraits.h" #include "ImplDummy.h" namespace carb { namespace cpp { namespace detail { // Default facade for trivial destruction of T template <class T, bool = std::is_trivially_destructible<T>::value> struct OptionalDestructor { union { NontrivialDummyType empty; CARB_VIZ typename std::remove_const_t<T> value; }; CARB_VIZ bool hasValue; constexpr OptionalDestructor() noexcept : empty{}, hasValue{ false } { } template <class... Args> constexpr explicit OptionalDestructor(in_place_t, Args&&... args) : value(std::forward<Args>(args)...), hasValue(true) { } // Cannot access anonymous union member `value` until C++17, so expose access here constexpr const T& val() const& { CARB_ASSERT(hasValue); return value; } constexpr T& val() & { CARB_ASSERT(hasValue); return value; } constexpr const T&& val() const&& { CARB_ASSERT(hasValue); return std::move(value); } constexpr T&& val() && { CARB_ASSERT(hasValue); return std::move(value); } void reset() noexcept { // No need to destruct since trivially destructible hasValue = false; } }; // Specialization for non-trivial destruction of T template <class T> struct OptionalDestructor<T, false> { union { NontrivialDummyType empty; CARB_VIZ typename std::remove_const_t<T> value; }; CARB_VIZ bool hasValue; ~OptionalDestructor() noexcept { if (hasValue) { value.~T(); } } constexpr OptionalDestructor() noexcept : empty{}, hasValue{ false } { } template <class... Args> constexpr explicit OptionalDestructor(in_place_t, Args&&... args) : value(std::forward<Args>(args)...), hasValue(true) { } OptionalDestructor(const OptionalDestructor&) = default; OptionalDestructor(OptionalDestructor&&) = default; OptionalDestructor& operator=(const OptionalDestructor&) = default; OptionalDestructor& operator=(OptionalDestructor&&) = default; // Cannot access anonymous union member `value` until C++17, so expose access here const T& val() const& { CARB_ASSERT(hasValue); return value; } T& val() & { CARB_ASSERT(hasValue); return value; } constexpr const T&& val() const&& { CARB_ASSERT(hasValue); return std::move(value); } constexpr T&& val() && { CARB_ASSERT(hasValue); return std::move(value); } void reset() noexcept { if (hasValue) { value.~T(); hasValue = false; } } }; template <class T> struct OptionalConstructor : OptionalDestructor<T> { using value_type = T; using OptionalDestructor<T>::OptionalDestructor; template <class... Args> T& construct(Args&&... args) { CARB_ASSERT(!this->hasValue); new (std::addressof(this->value)) decltype(this->value)(std::forward<Args>(args)...); this->hasValue = true; return this->value; } template <class U> void assign(U&& rhs) { if (this->hasValue) { this->value = std::forward<U>(rhs); } else { construct(std::forward<U>(rhs)); } } template <class U> void constructFrom(U&& rhs) noexcept(std::is_nothrow_constructible<T, decltype((std::forward<U>(rhs).value))>::value) { if (rhs.hasValue) { construct(std::forward<U>(rhs).value); } } template <class U> void assignFrom(U&& rhs) noexcept(std::is_nothrow_constructible<T, decltype((std::forward<U>(rhs).value))>::value&& std::is_nothrow_assignable<T, decltype((std::forward<U>(rhs).value))>::value) { if (rhs.hasValue) { assign(std::forward<U>(rhs).value); } else { this->reset(); } } }; template <class Base> struct NonTrivialCopy : Base { using Base::Base; NonTrivialCopy() = default; #if CARB_COMPILER_MSC // MSVC can evaluate the noexcept operator, but GCC errors when compiling it NonTrivialCopy(const NonTrivialCopy& from) noexcept(noexcept(Base::constructFrom(static_cast<const Base&>(from)))) #else // for GCC, use the same clause as Base::constructFrom NonTrivialCopy(const NonTrivialCopy& from) noexcept( std::is_nothrow_constructible<typename Base::value_type, decltype(from.value)>::value) #endif { Base::constructFrom(static_cast<const Base&>(from)); } }; // If T is copy-constructible and not trivially copy-constructible, select NonTrivialCopy, // otherwise use the base OptionalConstructor template <class Base, class... Types> using SelectCopy = typename std::conditional_t<conjunction<std::is_copy_constructible<Types>..., negation<conjunction<std::is_trivially_copy_constructible<Types>...>>>::value, NonTrivialCopy<Base>, Base>; template <class Base, class... Types> struct NonTrivialMove : SelectCopy<Base, Types...> { using BaseClass = SelectCopy<Base, Types...>; using BaseClass::BaseClass; NonTrivialMove() = default; NonTrivialMove(const NonTrivialMove&) = default; #if CARB_COMPILER_MSC // MSVC can evaluate the noexcept operator, but GCC errors when compiling it NonTrivialMove(NonTrivialMove&& from) noexcept(noexcept(BaseClass::constructFrom(static_cast<Base&&>(from)))) #else // for GCC, use the same clause as Base::constructFrom NonTrivialMove(NonTrivialMove&& from) noexcept( std::is_nothrow_constructible<typename Base::value_type, decltype(static_cast<Base&&>(from).value)>::value) #endif { BaseClass::constructFrom(static_cast<Base&&>(from)); } NonTrivialMove& operator=(const NonTrivialMove&) = default; NonTrivialMove& operator=(NonTrivialMove&&) = default; }; // If T is move-constructible and not trivially move-constructible, select NonTrivialMove, // otherwise use the selected Copy struct. template <class Base, class... Types> using SelectMove = typename std::conditional_t<conjunction<std::is_move_constructible<Types>..., negation<conjunction<std::is_trivially_move_constructible<Types>...>>>::value, NonTrivialMove<Base, Types...>, SelectCopy<Base, Types...>>; template <class Base, class... Types> struct NonTrivialCopyAssign : SelectMove<Base, Types...> { using BaseClass = SelectMove<Base, Types...>; using BaseClass::BaseClass; NonTrivialCopyAssign() = default; NonTrivialCopyAssign(const NonTrivialCopyAssign&) = default; NonTrivialCopyAssign(NonTrivialCopyAssign&&) = default; NonTrivialCopyAssign& operator=(const NonTrivialCopyAssign& from) noexcept( noexcept(BaseClass::assignFrom(static_cast<const Base&>(from)))) { BaseClass::assignFrom(static_cast<const Base&>(from)); return *this; } NonTrivialCopyAssign& operator=(NonTrivialCopyAssign&&) = default; }; template <class Base, class... Types> struct DeletedCopyAssign : SelectMove<Base, Types...> { using BaseClass = SelectMove<Base, Types...>; using BaseClass::BaseClass; DeletedCopyAssign() = default; DeletedCopyAssign(const DeletedCopyAssign&) = default; DeletedCopyAssign(DeletedCopyAssign&&) = default; DeletedCopyAssign& operator=(const DeletedCopyAssign&) = delete; DeletedCopyAssign& operator=(DeletedCopyAssign&&) = default; }; // For selecting the proper copy-assign class, things get a bit more complicated: // - If T is trivially destructible and trivially copy-constructible and trivially copy-assignable: // * We use the Move struct selected above // - Otherwise, if T is copy-constructible and copy-assignable: // * We select the NonTrivialCopyAssign struct // - If all else fails, the class is not copy-assignable, so select DeletedCopyAssign template <class Base, class... Types> using SelectCopyAssign = typename std::conditional_t< conjunction<std::is_trivially_destructible<Types>..., std::is_trivially_copy_constructible<Types>..., std::is_trivially_copy_assignable<Types>...>::value, SelectMove<Base, Types...>, typename std::conditional_t<conjunction<std::is_copy_constructible<Types>..., std::is_copy_assignable<Types>...>::value, NonTrivialCopyAssign<Base, Types...>, DeletedCopyAssign<Base, Types...>>>; template <class Base, class... Types> struct NonTrivialMoveAssign : SelectCopyAssign<Base, Types...> { using BaseClass = SelectCopyAssign<Base, Types...>; using BaseClass::BaseClass; NonTrivialMoveAssign() = default; NonTrivialMoveAssign(const NonTrivialMoveAssign&) = default; NonTrivialMoveAssign(NonTrivialMoveAssign&&) = default; NonTrivialMoveAssign& operator=(const NonTrivialMoveAssign&) = default; NonTrivialMoveAssign& operator=(NonTrivialMoveAssign&& from) noexcept( noexcept(BaseClass::assignFrom(static_cast<const Base&&>(from)))) { BaseClass::assignFrom(static_cast<Base&&>(from)); return *this; } }; template <class Base, class... Types> struct DeletedMoveAssign : SelectCopyAssign<Base, Types...> { using BaseClass = SelectCopyAssign<Base, Types...>; using BaseClass::BaseClass; DeletedMoveAssign() = default; DeletedMoveAssign(const DeletedMoveAssign&) = default; DeletedMoveAssign(DeletedMoveAssign&&) = default; DeletedMoveAssign& operator=(const DeletedMoveAssign&) = default; DeletedMoveAssign& operator=(DeletedMoveAssign&&) = delete; }; // Selecting the proper move-assign struct is equally complicated: // - If T is trivially destructible, trivially move-constructible and trivially move-assignable: // * We use the CopyAssign struct selected above // - If T is move-constructible and move-assignable: // * We select the NonTrivialMoveAssign struct // - If all else fails, T is not move-assignable, so select DeletedMoveAssign template <class Base, class... Types> using SelectMoveAssign = typename std::conditional_t< conjunction<std::is_trivially_destructible<Types>..., std::is_trivially_move_constructible<Types>..., std::is_trivially_move_assignable<Types>...>::value, SelectCopyAssign<Base, Types...>, typename std::conditional_t<conjunction<std::is_move_constructible<Types>..., std::is_move_assignable<Types>...>::value, NonTrivialMoveAssign<Base, Types...>, DeletedMoveAssign<Base, Types...>>>; // An alias for constructing our struct hierarchy to wrap T template <class Base, class... Types> using SelectHierarchy = SelectMoveAssign<Base, Types...>; // Helpers for determining which operators can be enabled template <class T> using EnableIfBoolConvertible = typename std::enable_if_t<std::is_convertible<T, bool>::value, int>; template <class L, class R> using EnableIfComparableWithEqual = EnableIfBoolConvertible<decltype(std::declval<const L&>() == std::declval<const R&>())>; template <class L, class R> using EnableIfComparableWithNotEqual = EnableIfBoolConvertible<decltype(std::declval<const L&>() != std::declval<const R&>())>; template <class L, class R> using EnableIfComparableWithLess = EnableIfBoolConvertible<decltype(std::declval<const L&>() < std::declval<const R&>())>; template <class L, class R> using EnableIfComparableWithGreater = EnableIfBoolConvertible<decltype(std::declval<const L&>() > std::declval<const R&>())>; template <class L, class R> using EnableIfComparableWithLessEqual = EnableIfBoolConvertible<decltype(std::declval<const L&>() <= std::declval<const R&>())>; template <class L, class R> using EnableIfComparableWithGreaterEqual = EnableIfBoolConvertible<decltype(std::declval<const L&>() >= std::declval<const R&>())>; } // namespace detail } // namespace cpp } // namespace carb
12,932
C
32.076726
124
0.658367
omniverse-code/kit/include/carb/tokens/TokensBindingsPython.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 "../Framework.h" #include "TokensUtils.h" #include <memory> #include <string> #include <vector> namespace carb { namespace tokens { namespace { inline void definePythonModule(py::module& m) { using namespace carb::tokens; m.attr("RESOLVE_FLAG_NONE") = py::int_(kResolveFlagNone); m.attr("RESOLVE_FLAG_LEAVE_TOKEN_IF_NOT_FOUND") = py::int_(kResolveFlagLeaveTokenIfNotFound); defineInterfaceClass<ITokens>(m, "ITokens", "acquire_tokens_interface") .def("set_value", wrapInterfaceFunction(&ITokens::setValue), py::call_guard<py::gil_scoped_release>()) .def("set_initial_value", &ITokens::setInitialValue, py::call_guard<py::gil_scoped_release>()) .def("remove_token", &ITokens::removeToken, py::call_guard<py::gil_scoped_release>()) .def("exists", wrapInterfaceFunction(&ITokens::exists), py::call_guard<py::gil_scoped_release>()) .def("resolve", [](ITokens* self, const std::string& str, ResolveFlags flags) -> py::str { carb::tokens::ResolveResult result; std::string resolvedString; { py::gil_scoped_release nogil; resolvedString = carb::tokens::resolveString(self, str.c_str(), flags, &result); } if (result == ResolveResult::eSuccess) return resolvedString; else return py::none(); }, py::arg("str"), py::arg("flags") = kResolveFlagNone) ; } } // namespace } // namespace tokens } // namespace carb
2,097
C
33.393442
110
0.638531
omniverse-code/kit/include/carb/tokens/TokensUtils.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 Implementation of utilities for \ref carb::tokens::ITokens. #pragma once #include "../InterfaceUtils.h" #include "../logging/Log.h" #include "ITokens.h" #include <string> #include <algorithm> namespace carb { namespace tokens { /** * Helper for resolving a token string. The resolve result (resolve code) is placed in the optional parameter. * * @param tokens tokens interface (passing a null pointer will result in an error) * @param str string for token resolution (passing a null pointer will result in an error) * @param resolveFlags flags that modify token resolution process * @param resolveResult optional parameter for receiving resulting resolve code * * @return true if the operation was successful false otherwise */ inline std::string resolveString(const ITokens* tokens, const char* str, ResolveFlags resolveFlags = kResolveFlagNone, ResolveResult* resolveResult = nullptr) { // Defaulting to an error result thus it's possible to just log an error message and return an empty string if // anything goes wrong if (resolveResult) { *resolveResult = ResolveResult::eFailure; } if (!tokens) { CARB_LOG_ERROR("Couldn't acquire ITokens interface."); return std::string(); } if (!str) { CARB_LOG_ERROR("Can't resolve a null token string."); return std::string(); } const size_t strLen = std::strlen(str); ResolveResult resResult; size_t resolvedStringSize = tokens->calculateDestinationBufferSize( str, strLen, StringEndingMode::eNoNullTerminator, resolveFlags, &resResult); if (resResult == ResolveResult::eFailure) { CARB_LOG_ERROR("Couldn't calculate required buffer size for token resolution of string: %s", str); return std::string(); } // Successful resolution to an empty string if (resolvedStringSize == 0) { if (resolveResult) { *resolveResult = ResolveResult::eSuccess; } return std::string(); } // C++11 guarantees that strings are continuous in memory std::string resolvedString; resolvedString.resize(resolvedStringSize); const ResolveResult resolveResultLocal = tokens->resolveString(str, strLen, &resolvedString.front(), resolvedString.size(), StringEndingMode::eNoNullTerminator, resolveFlags, nullptr); if (resolveResultLocal != ResolveResult::eSuccess) { CARB_LOG_ERROR("Couldn't successfully resolve provided string: %s", str); return std::string(); } if (resolveResult) { *resolveResult = ResolveResult::eSuccess; } return resolvedString; } /** * A helper function that escapes necessary symbols in the provided string so that they won't be recognized as related * to token parsing * @param str a string that requires preprocessing to evade the token resolution (a string provided by a user or some * other data that must not be a part of token resolution) * @return a string with necessary modification so it won't participate in token resolution */ inline std::string escapeString(const std::string& str) { constexpr char kSpecialChar = '$'; const size_t countSpecials = std::count(str.begin(), str.end(), kSpecialChar); if (!countSpecials) { return str; } std::string result; result.reserve(str.length() + countSpecials); for (char curChar : str) { result.push_back(curChar); if (curChar == kSpecialChar) { result.push_back(kSpecialChar); } } return result; } } // namespace tokens } // namespace carb
4,219
C
30.259259
118
0.671012
omniverse-code/kit/include/carb/tokens/ITokens.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 Implementation of `ITokens` interface #pragma once #include "../Interface.h" namespace carb { //! Namespace for `ITokens`. namespace tokens { /** * Possible result of resolving tokens. */ enum class ResolveResult { eSuccess, //!< Result indicating success. eTruncated, //!< Result that indicates success, but the output was truncated. eFailure, //!< Result that indicates failure. }; /** * Possible options for ending of the resolved string */ enum class StringEndingMode { eNullTerminator, //!< Indicates that the resolved string is NUL-terminated. eNoNullTerminator //!< Indicates that the resolved string is not NUL-terminated. }; /** * Flags for token resolution algorithm */ using ResolveFlags = uint32_t; const ResolveFlags kResolveFlagNone = 0; //!< Default token resolution process const ResolveFlags kResolveFlagLeaveTokenIfNotFound = 1; //!< If cannot resolve token in a string then leave it as is. /** * Interface for storing tokens and resolving strings containing them. Tokens are string pairs {name, value} that can be * referenced in a string as `"some text ${token_name} some other text"`, where the token name starts with a sequence * `"${"` and end with a first closing `"}"`. * * If a token with the name \<token_name\> has a defined value, then it will be substituted with its value. * If the token does not have a defined value, an empty string will be used for the replacement. This interface will use * the ISetting interface, if available, as storage and in such case tokens will be stored under the '/app/tokens' node. * * Note: The "$" symbol is considered to be special by the tokenizer and should be escaped by doubling it ("$" -> "$$") * in order to be processed as just a symbol "$" * Ex: "some text with $ sign" -> "some text with $$ sign" * * Single unescaped "$" signs are considered to be a bad practice to be used for token resolution but they are * acceptable and will be resolved into single "$" signs and no warning will be given about it. * * Ex: * "$" -> "$", * "$$" -> "$", * "$$$" -> "$$" * * It's better to use the helper function "escapeString" from the "TokensUtils.h" to produce a string * that doesn't have any parts that could participate in tokenization. As a token name start with "${" and ends with the * first encountered "}" it can contain "$" (same rules about escaping it apply) and "{" characters, however such cases * will result in a warning being output to the log. * Ex: for the string "${bar$${}" the token resolution process will consider the token name to be "bar${" * (note that "$$" is reduced into a single "$") and a warning will be outputted into the log. * * Environment variables are automatically available as tokens, if defined. These are specified with the text * `${env:<var name>}` where `<var name>` is the name of the environment variable. The `env:` prefix is a reserved name, * so any call to \ref ITokens::setValue() or \ref ITokens::setInitialValue() with a name that starts with `env:` will * be rejected. The environment variable is read when needed and not cached in any way. An undefined environment * variable behaves as an undefined token. * * @thread_safety the interface's functions are not thread safe. It is responsibility of the user to use all necessary * synchronization mechanisms if needed. All data passed into a plugin's function must be valid for the duration of the * function call. */ struct ITokens { CARB_PLUGIN_INTERFACE("carb::tokens::ITokens", 1, 0) /** * Sets a new value for the specified token, if the token didn't exist it will be created. * * Note: if the value is null then the token will be removed (see also: "removeToken" function). In this case true * is returned if the token was successfully deleted or didn't exist. * * @param name token name not enclosed in "${" and "}". Passing a null pointer results in an error * @param value new value for the token. Passing a null pointer deletes the token * * @return true if the operation was successful, false if the token name was null or an error occurred during the * operation */ bool(CARB_ABI* setValue)(const char* name, const char* value); /** * Creates a token with the given name and value if it was non-existent. Otherwise does nothing. * * @param name Name of a token. Passing a null pointer results in an error * @param value Value of a token. Passing a null pointer does nothing. */ void setInitialValue(const char* name, const char* value) const; /** * A function to delete a token. * * @param name token name not enclosed in "${" and "}". Passing a null pointer results in an error * * @return true if the operation was successful or token with such name didn't exist, false if the name is null or * an error occurred */ bool removeToken(const char* name) const; /** * Tries to resolve all tokens in the source string buffer and places the result into the destination buffer. * If the destBufLen isn't enough to contain the result then the result will be truncated. * * @param sourceBuf the source string buffer. Passing a null pointer results in an error * @param sourceBufLen the length of the source string buffer * @param destBuf the destination buffer. Passing a null pointer results in an error * @param destBufLen the size of the destination buffer * @param endingMode sets if the result will have a null-terminator (in this case passing a zero * destBufLen will result in an error) or not * @param resolveFlags flags that modify token resolution process * @param[out] resolvedSize optional parameter. If the provided buffer were enough for the operation and it * succeeded then resolvedSize <= destBufLen and equals to the number of written bytes to the buffer, if the * operation were successful but the output were truncated then resolvedSize > destBufLen and equals to the minimum * buffer size that can hold the fully resolved string, if the operation failed then the value of the resolvedSize * is undetermined * * @retval ResolveResult::eTruncated if the destination buffer was too small to contain the result (note that if the * StringEndingMode::eNullTerminator was used the result truncated string will end with a null-terminator) * @retval ResolveResult::eFailure if an error occurred. * @retval ResolveResult::eSuccess will be returned if the function successfully wrote the whole resolve result into * the \p destBuf. */ ResolveResult(CARB_ABI* resolveString)(const char* sourceBuf, size_t sourceBufLen, char* destBuf, size_t destBufLen, StringEndingMode endingMode, ResolveFlags resolveFlags, size_t* resolvedSize); /** * Calculates the minimum buffer size required to hold the result of resolving of the input string buffer. * * @param sourceBuf the source string buffer. Passing a null pointer results in an error * @param sourceBufLen the length of the source string buffer * @param endingMode sets if the result will have a null-terminator or not * @param resolveFlags flags that modify token resolution process * @param[out] resolveResult optional parameter that will contain the result of the attempted resolution to * calculate the necessary size * * @returns The calculated minimum size. In case of any error the function will return 0. */ size_t(CARB_ABI* calculateDestinationBufferSize)(const char* sourceBuf, size_t sourceBufLen, StringEndingMode endingMode, ResolveFlags resolveFlags, ResolveResult* resolveResult); /** * Check the existence of a token * * @param tokenName the name of a token that will be checked for existence. Passing a null pointer results in an * error * * @return true if the token with the specified name exists, false is returned if an error occurs or there is no * token with such name */ bool(CARB_ABI* exists)(const char* tokenName); }; inline void ITokens::setInitialValue(const char* name, const char* value) const { if (!exists(name) && value) { setValue(name, value); } } inline bool ITokens::removeToken(const char* name) const { return setValue(name, nullptr); } } // namespace tokens } // namespace carb
9,369
C
46.563452
120
0.678834
omniverse-code/kit/include/carb/tasking/ThreadPoolUtils.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 ThreadPoolWrapper definition file. #pragma once #include "../cpp/Tuple.h" #include "../logging/Log.h" #include "IThreadPool.h" #include <future> namespace carb { namespace tasking { #ifndef DOXYGEN_BUILD namespace detail { template <class ReturnType> struct ApplyWithPromise { template <class Callable, class Tuple> void operator()(std::promise<ReturnType>& promise, Callable&& f, Tuple&& t) { promise.set_value(std::forward<ReturnType>(cpp::apply(std::forward<Callable>(f), std::forward<Tuple>(t)))); } }; template <> struct ApplyWithPromise<void> { template <class Callable, class Tuple> void operator()(std::promise<void>& promise, Callable& f, Tuple&& t) { cpp::apply(std::forward<Callable>(f), std::forward<Tuple>(t)); promise.set_value(); } }; } // namespace detail #endif /** * Helper class for using IThreadPool API */ class ThreadPoolWrapper { public: /** * Constructor * * @param poolInterface The acquired IThreadPool interface. * @param workerCount (optional) The number of worker threads to create. If 0 (default) is specified, the value * returned from IThreadPool::getDefaultWorkerCount() is used. */ ThreadPoolWrapper(IThreadPool* poolInterface, size_t workerCount = 0) : m_interface(poolInterface) { if (m_interface == nullptr) { CARB_LOG_ERROR("IThreadPool interface used to create a thread pool wrapper is null."); return; } if (workerCount == 0) { workerCount = m_interface->getDefaultWorkerCount(); } m_pool = m_interface->createEx(workerCount); if (m_pool == nullptr) { CARB_LOG_ERROR("Couldn't create a new thread pool."); } } /** * Returns the number of worker threads in the thread pool. * @returns The number of worker threads. */ size_t getWorkerCount() const { if (!isValid()) { CARB_LOG_ERROR("Attempt to call the 'getWorkerCount' method of an invalid thread pool wrapper."); return 0; } return m_interface->getWorkerCount(m_pool); } /** * Enqueues a <a href="https://en.cppreference.com/w/cpp/named_req/Callable">Callable</a> to run on a worker thread. * * @param task The callable object. May be a lambda, [member] function, functor, etc. * @param args Optional <a href="https://en.cppreference.com/w/cpp/utility/functional/bind">std::bind</a>-style * arguments to pass to the callable object. * @returns A <a href="https://en.cppreference.com/w/cpp/thread/future">std::future</a> based on the return-type of * the callable object. If enqueuing failed, `valid()` on the returned future will be false. */ template <class Callable, class... Args> auto enqueueJob(Callable&& task, Args&&... args) { using ReturnType = typename cpp::invoke_result_t<Callable, Args...>; using Future = std::future<ReturnType>; using Tuple = std::tuple<std::decay_t<Args>...>; struct Data { std::promise<ReturnType> promise{}; Callable f; Tuple args; Data(Callable&& f_, Args&&... args_) : f(std::forward<Callable>(f_)), args(std::forward<Args>(args_)...) { } void callAndDelete() { detail::ApplyWithPromise<ReturnType>{}(promise, f, args); delete this; } }; if (!isValid()) { CARB_LOG_ERROR("Attempt to call the 'enqueueJob' method of an invalid thread pool wrapper."); return Future{}; } Data* pData = new (std::nothrow) Data{ std::forward<Callable>(task), std::forward<Args>(args)... }; if (!pData) { CARB_LOG_ERROR("ThreadPoolWrapper: No memory for job"); return Future{}; } Future result = pData->promise.get_future(); if (CARB_LIKELY(m_interface->enqueueJob( m_pool, [](void* userData) { static_cast<Data*>(userData)->callAndDelete(); }, pData))) { return result; } CARB_LOG_ERROR("ThreadPoolWrapper: failed to enqueue job"); delete pData; return Future{}; } /** * Returns the number of jobs currently enqueued or executing in the ThreadPool. * * enqueueJob() increments this value and the value is decremented as jobs finish. * * @note This value changes by other threads and cannot be read atomically. * * @returns The number of jobs currently executing in the ThreadPool. */ size_t getCurrentlyRunningJobCount() const { if (!isValid()) { CARB_LOG_ERROR("Attempt to call the 'getCurrentlyRunningJobCount' method of an invalid thread pool wrapper."); return 0; } return m_interface->getCurrentlyRunningJobCount(m_pool); } /** * Blocks the calling thread until all enqueued tasks have completed. */ void waitUntilFinished() const { if (!isValid()) { CARB_LOG_ERROR("Attempt to call the 'waitUntilFinished' method of an invalid thread pool wrapper."); return; } m_interface->waitUntilFinished(m_pool); } /** * Returns true if the underlying ThreadPool is valid. * * @returns `true` if the underlying ThreadPool is valid; `false` otherwise. */ bool isValid() const { return m_pool != nullptr; } /** * Destructor */ ~ThreadPoolWrapper() { if (isValid()) { m_interface->destroy(m_pool); } } CARB_PREVENT_COPY_AND_MOVE(ThreadPoolWrapper); private: // ThreadPoolWrapper private members and functions IThreadPool* m_interface = nullptr; ThreadPool* m_pool = nullptr; }; } // namespace tasking } // namespace carb
6,482
C
28.202703
122
0.607066
omniverse-code/kit/include/carb/tasking/IThreadPool.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 IThreadPool definition file. #pragma once #include "../Interface.h" namespace carb { namespace tasking { /** * Opaque handle for a thread pool. */ class ThreadPool DOXYGEN_EMPTY_CLASS; /** * Defines the function for performing a user-provided job. * * @param jobData User provided data for the job, the memory must not be released until it no longer needed by the * task. */ typedef void (*JobFn)(void* jobData); /** * Optional plugin providing helpful facilities for utilizing a pool of threads to perform basic small tasks. * * @warning It is not recommended to use IThreadPool in conjunction with ITasking; the latter is a much richer feature * set and generally preferred over IThreadPool. IThreadPool is a simple thread pool with the ability to run individual * tasks. * * @warning If multiple ThreadPool objects are used, caution must be taken to not overburden the system with too many * threads. * * @note Prefer using ThreadPoolWrapper. */ struct IThreadPool { CARB_PLUGIN_INTERFACE("carb::tasking::IThreadPool", 1, 0) /** * Creates a new thread pool where the number of worker equals to the number specified by the user. * * @param workerCount Required number of worker threads. * * @return A newly created thread pool. */ ThreadPool*(CARB_ABI* createEx)(size_t workerCount); /** * Creates a new thread pool where the number of worker equals to a value * returned by the "getDefaultWorkerCount" function. * * @return A newly created thread pool. */ ThreadPool* create() const; /** * Destroys previously created thread pool. * * @param threadPool Previously created thread pool. */ void(CARB_ABI* destroy)(ThreadPool* threadPool); /** * Returns default number of workers used for creation of a new thread pool. * * @return The default number of workers. */ size_t(CARB_ABI* getDefaultWorkerCount)(); /** * Returns the number of worker threads in the thread pool. * * @param threadPool ThreadPool previously created with create(). * @returns The number of worker threads. */ size_t(CARB_ABI* getWorkerCount)(ThreadPool* threadPool); /** * Adds a new task to be executed by the thread pool. * * @param threadPool Thread pool for execution of the job. * @param jobFunction User provided function to be executed by a worker. * @param jobData User provided data for the job, the memory must not be released until it no longer needed by the * task. * * @return Returns true if the task was successfully added into the thread pool. */ bool(CARB_ABI* enqueueJob)(ThreadPool* threadPool, JobFn jobFunction, void* jobData); /** * Returns the number of currently executed tasks in the thread pool. * * @param threadPool Thread pool to be inspected. * * @return The number of currently executed tasks in the thread pool. */ size_t(CARB_ABI* getCurrentlyRunningJobCount)(ThreadPool* threadPool); /** * Blocks execution of the current thread until the thread pool finishes all queued jobs. * * @param threadPool Thread pool to wait on. */ void(CARB_ABI* waitUntilFinished)(ThreadPool* threadPool); }; inline ThreadPool* IThreadPool::create() const { return createEx(getDefaultWorkerCount()); } } // namespace tasking } // namespace carb
3,918
C
29.858267
119
0.696274
omniverse-code/kit/include/carb/tasking/ITasking.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 carb.tasking interface definition file. #pragma once #include "../Interface.h" #include "../InterfaceUtils.h" #include "TaskingHelpers.h" namespace carb { //! Namespace for *carb.tasking.plugin* and related utilities. namespace tasking { /** * Default TaskingDesc plugin starts with. */ inline TaskingDesc getDefaultTaskingDesc() { return TaskingDesc{}; } /** * Defines a tasking plugin interface, acquired with carb::Framework::acquireInterface() when *carb.tasking.plugin* is * loaded. * * ITasking is started automatically on plugin startup. It uses default TaskingDesc, see getDefaultTaskingDesc(). * * Several @rstref{ISettings keys <tasking_settings>} exist to provide debug behavior and to override default startup * behavior (but do not override a TaskingDesc provided to ITasking::changeParameters()). * * @thread_safety Unless otherwise specified, all functions in this interface can be called from multiple threads * simultaneously. */ struct ITasking { // 0.1 - Initial version // 0.2 - Thread pinning, sleep, suspending/waking (not ABI compatible with 0.1) // 0.3 - Semaphore support, SharedMutex support // 0.4 - ConditionVariable support // 1.0 - Wait timeouts (git hash e13289c5a5) // 1.1 - changeTaskPriority() / executeMainTasks() // 1.2 - restart() -> changeParameters(); don't lose tasks when changing parameters // 1.3 - Respect task priority when resuming tasks that have slept, waited, or unsuspended (not an API change) // 1.4 - Stuck checking (not an API change) // 1.5 - internalGroupCounters() // 1.6 - createRecursiveMutex() // 2.0 - ITasking 2.0 (git hash f68ae95da7) // 2.1 - allocTaskStorage() / freeTaskStorage() / setTaskStorage() / getTaskStorage() // 2.2 - beginTracking() / endTracking() // 2.3 - internalNameTask() // 2.4 - reloadFiberEvents() CARB_PLUGIN_INTERFACE("carb::tasking::ITasking", 2, 4) /** * Changes the parameters under which the ITasking interface functions. This may stop and start threads, but will * not lose any tasks in progress or queued. * * @note This function reloads all registered @ref IFiberEvents interfaces so they will start receiving * notifications. However, if this is the only change desired it is recommended to use @ref reloadFiberEvents() * instead. * * @thread_safety It is unsafe to add any additional tasks while calling this function. The caller must ensure that * no new tasks are added until this function returns. * * @warning Calling this function from within a task context causes undefined behavior. * * @param desc The tasking plugin descriptor. */ void(CARB_ABI* changeParameters)(TaskingDesc desc); /** * Get TaskingDesc the plugin currently running with. * * @return The tasking plugin descriptor. */ const TaskingDesc&(CARB_ABI* getDesc)(); /** * Creates a Counter with target value of zero. * * @warning Prefer using CounterWrapper instead. * * @return The counter created. */ Counter*(CARB_ABI* createCounter)(); /** * Creates a counter with a specific target value. * * @warning Prefer using CounterWrapper instead. * * @param target The target value of the counter. Yielding on this counter will wait for this target. * @return The counter created. */ Counter*(CARB_ABI* createCounterWithTarget)(uint32_t target); /** * Destroys the counter. * * @param counter A counter. */ void(CARB_ABI* destroyCounter)(Counter* counter); /** * Adds a task to the internal queue. Do not call this function directly; instead, use one of the helper functions * such as addTask(), addSubTask() or addThrottledTask(). * * @param task The task to queue. * @param counter A counter to associate with this task. It will be incremented by 1. * When the task completes, it will be decremented. * @return A TaskContext that can be used to refer to this task */ //! @private TaskContext(CARB_ABI* internalAddTask)(TaskDesc task, Counter* counter); /** * Adds a group of tasks to the internal queue * * @param tasks The tasks to queue. * @param taskCount The number of tasks. * @param counter A counter to associate with the task group as a whole. * Initially it incremented by taskCount. When each task completes, it will be decremented by 1. */ void(CARB_ABI* addTasks)(TaskDesc* tasks, size_t taskCount, Counter* counter); //! @private TaskContext(CARB_ABI* internalAddDelayedTask)(uint64_t delayNs, TaskDesc desc, Counter* counter); //! @private void(CARB_ABI* internalApplyRange)(size_t range, ApplyFn fn, void* context); /** * Yields execution to another task until counter reaches its target value. * * Tasks invoking this call can resume on different thread. If the task must resume on the same thread, use * PinGuard. * * @note deprecated Use wait() instead. * * @param counter The counter to check. */ CARB_DEPRECATED("Use wait() instead") void yieldUntilCounter(RequiredObject counter); /** * Yields execution to another task until counter reaches its target value or the timeout period elapses. * * Tasks invoking this call can resume on different thread. If the task must resume on the same thread, use * PinGuard. * * @note Deprecated: Use wait_for() or wait_until() instead. * * @param counter The counter to check. * @param timeoutNs The number of nanoseconds to wait. Pass kInfinite to wait forever or 0 to try immediately * without waiting. * @return true if the counter period has completed; false if the timeout period elapses. */ CARB_DEPRECATED("Use wait_for() or wait_until() instead.") bool timedYieldUntilCounter(RequiredObject counter, uint64_t timeoutNs); //! @private bool(CARB_ABI* internalCheckCounter)(Counter* counter); //! @private uint32_t(CARB_ABI* internalGetCounterValue)(Counter* counter); //! @private uint32_t(CARB_ABI* internalGetCounterTarget)(Counter* counter); //! @private uint32_t(CARB_ABI* internalFetchAddCounter)(Counter* counter, uint32_t value); //! @private uint32_t(CARB_ABI* internalFetchSubCounter)(Counter* counter, uint32_t value); //! @private void(CARB_ABI* internalStoreCounter)(Counter* counter, uint32_t value); /** * Checks if counter is at the counter's target value * * @note Deprecated: The Counter interface is deprecated. * * @param c The counter to check. * @return `true` if the counter is at the target value; `false` otherwise. */ CARB_DEPRECATED("The Counter interface is deprecated.") bool checkCounter(Counter* c) { return internalCheckCounter(c); } /** * Retrieves the current value of the target. Note! Because of the threaded nature of counters, this * value may have changed by another thread before the function returns. * * @note Deprecated: The Counter interface is deprecated. * * @param counter The counter. * @return The current value of the counter. */ CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t getCounterValue(Counter* counter) { return internalGetCounterValue(counter); } /** * Gets the target value for the Counter * * @note Deprecated: The Counter interface is deprecated. * * @param counter The counter to check. * @return The target value of the counter. */ CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t getCounterTarget(Counter* counter) { return internalGetCounterTarget(counter); } /** * Atomically adds a value to the counter and returns the value held previously. * * The fetchAdd operation on the counter will be atomic, but this function as a whole is not atomic. * * @note Deprecated: The Counter interface is deprecated. * * @param counter The counter. * @param value The value to add to the counter. * @return The value of the counter before the addition. */ CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t fetchAddCounter(Counter* counter, uint32_t value) { return internalFetchAddCounter(counter, value); } /** * Atomically subtracts a value from the counter and returns the value held previously. * * The fetchSub operation on the counter will be atomic, but this function as a whole is not atomic. * * @note Deprecated: The Counter interface is deprecated. * * @param counter The counter. * @param value The value to subtract from the counter. * @return The value of the counter before the addition. */ CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t fetchSubCounter(Counter* counter, uint32_t value) { return internalFetchSubCounter(counter, value); } /** * Atomically replaces the current value with desired on a counter. * * The store operation on the counter will be atomic, but this function as a whole is not atomic. * * @note Deprecated: The Counter interface is deprecated. * * @param counter The counter. * @param value The value to load into to the counter. */ CARB_DEPRECATED("The Counter interface is deprecated.") void storeCounter(Counter* counter, uint32_t value) { return internalStoreCounter(counter, value); } /** * Yields execution. Task invoking this call will be put in the very end of task queue, priority is ignored. */ void(CARB_ABI* yield)(); /** * Causes the currently executing TaskContext to be "pinned" to the thread it is currently running on. * * @warning Do not call this function directly; instead use PinGuard. * * This function causes the current thread to be the only task thread that can run the current task. This is * necessary in some cases where thread specificity is required (those these situations are NOT recommended for * tasks): holding a mutex, or using thread-specific data, etc. Thread pinning is not efficient (the pinned thread * could be running a different task causing delays for the current task to be resumed, and wakeTask() must wait to * return until the pinned thread has been notified) and should therefore be avoided. * * Call unpinFromCurrentThread() to remove the pin, allowing the task to run on any thread. * * @note %All calls to pin a thread will issue a warning log message. * * @note It is assumed that the task is allowed to move to another thread during the pinning process, though this * may not always be the case. Only after pinToCurrentThread() returns will a task be pinned. Therefore, make sure * to call pinToCurrentThread() *before* any operation that requires pinning. * * @return true if the task was already pinned; false if the task was not pinned or if not called from Task Context * (i.e. getTaskContext() would return kInvalidTaskContext) */ bool(CARB_ABI* pinToCurrentThread)(); /** * Un-pins the currently executing TaskContext from the thread it is currently running on. * * @warning Do not call this function directly; instead use PinGuard. * * @return true if the task was successfully un-pinned; false if the task was not pinned or if not called from Task * Context (i.e. getTaskContext() would return kInvalidTaskContext) */ bool(CARB_ABI* unpinFromCurrentThread)(); /** * Creates a non-recursive mutex. * * @warning Prefer using MutexWrapper instead. * * @note Both createMutex() and createRecursiveMutex() return a Mutex object; it is up to the creator to ensure that * the Mutex object is used properly. A Mutex created with createMutex() will call `std::terminate()` if recursively * locked. * * @return The created non-recursive mutex. */ Mutex*(CARB_ABI* createMutex)(); /** * Destroys a mutex. * * @param The mutex to destroy. */ void(CARB_ABI* destroyMutex)(Mutex* mutex); /** * Locks a mutex * * @param mutex The mutex to lock. */ void lockMutex(Mutex* mutex); /** * Locks a mutex or waits for the timeout period to expire. * * @note Attempting to recursively lock a mutex created with createMutex() will abort. Use a mutex created with * createRecursiveMutex() to support recursive locking. * * @param mutex The mutex to lock. * @param timeoutNs The relative timeout in nanoseconds. Specify kInfinite to wait forever or 0 to try locking * without waiting. * @returns true if the calling thread/fiber now has ownership of the mutex; false if the timeout period expired. */ bool(CARB_ABI* timedLockMutex)(Mutex* mutex, uint64_t timeoutNs); /** * Unlock a mutex * * @param The mutex to unlock. */ void(CARB_ABI* unlockMutex)(Mutex* mutex); /** * Sleeps for the given number of nanoseconds. Prefer using sleep_for() or sleep_until() * * @note This function is fiber-aware. If currently executing in a fiber, the fiber will be yielded until the * requested amount of time has passed. If a thread is currently executing, then the thread will sleep. * * @param nanoseconds The amount of time to yield/sleep, in nanoseconds. */ void(CARB_ABI* sleepNs)(uint64_t nanoseconds); /** * If the calling thread is running in "task context", that is, a fiber executing a task previously queued with * addTask(), this function returns a handle that can be used with suspendTask() and wakeTask(). * * @return kInvalidTaskContext if the calling thread is not running within "task context"; otherwise, a TaskContext * handle is returned that can be used with suspendTask() and wakeTask(), as well as anywhere a RequiredObject is * used. */ TaskContext(CARB_ABI* getTaskContext)(); /** * Suspends the current task. Does not return until wakeTask() is called with the task's TaskContext (see * getTaskContext()). * * @note to avoid race-conditions between wakeTask() and suspendTask(), a wakeTask() that occurs before * suspendTask() has been called will cause suspendTask() to return true immediately without waiting. * * @return true when wakeTask() is called. If the current thread is not running in "task context" (i.e. * getTaskContext() would return kInvalidTaskContext), then this function returns false immediately. */ bool(CARB_ABI* suspendTask)(); /** * Wakes a task previously suspended with suspendTask(). * * @note to avoid race-conditions between wakeTask() and suspendTask(), a wakeTask() that occurs before * suspendTask() has been called will cause suspendTask() to return true immediately without waiting. The wakeTask() * function returns immediately and does not wait for the suspended task to resume. * * wakeTask() cannot be called on the current task context (false will be returned). Additional situations that will * log (as a warning) and return false: * - The task context given already has a pending wake * - The task has finished * - The task context given is sleeping or otherwise waiting on an event (cannot be woken) * - The given TaskContext is not valid * * @param task The TaskContext (returned by getTaskContext()) for the task suspended with suspendTask(). * @return true if the task was woken properly. false if a situation listed above occurs. */ bool(CARB_ABI* wakeTask)(TaskContext task); /** * Blocks the current thread/task until the given Task has completed. * * Similar to yieldUntilCounter() but does not require a Counter object. * * @note Deprecated: Use wait() instead. * * @param task The TaskContext to wait on * @return true if the wait was successful; false if the TaskContext has already expired or was invalid. */ CARB_DEPRECATED("Use wait() instead") bool waitForTask(TaskContext task); //! @private bool(CARB_ABI* internalTimedWait)(Object obj, uint64_t timeoutNs); /** * Checks the object specified in @p req to see if it is signaled. * * @param req The RequiredObject object to check. * @returns `true` if the object is signaled; `false` if the object is invalid or not signaled. */ bool try_wait(RequiredObject req); /** * Blocks the calling thread or task until @p req is signaled. * * @param req The RequiredObject object to check. */ void wait(RequiredObject req); /** * Blocks the calling thread or task until @p req is signaled or @p dur has elapsed. * * @param dur The duration to wait for. * @param req The RequiredObject object to check. * @returns `true` if the object is signaled; `false` if the object is invalid or not signaled, or @p dur elapses. */ template <class Rep, class Period> bool wait_for(std::chrono::duration<Rep, Period> dur, RequiredObject req); /** * Blocks the calling thread or task until @p req is signaled or the clock reaches @p when. * * @param when The time_point to wait until. * @param req The RequiredObject object to check. * @returns `true` if the object is signaled; `false` if the object is invalid or not signaled, or @p when is * reached. */ template <class Clock, class Duration> bool wait_until(std::chrono::time_point<Clock, Duration> when, RequiredObject req); /** * Creates a fiber-aware semaphore primitive. * * A semaphore is a gate that lets a certain number of tasks/threads through. This can also be used to throttle * tasks (see addThrottledTask()). When the count of a semaphore goes negative tasks/threads will wait on the * semaphore. * * @param value The starting value of the semaphore. Limited to INT_MAX. 0 means that any attempt to wait on the * semaphore will block until the semaphore is released. * @return A Semaphore object. When finished, dispose of the semaphore with destroySemaphore(). * * @warning Prefer using SemaphoreWrapper instead. * * @note Semaphore can be used for @rstref{Throttling <tasking-throttling-label>} tasks. */ Semaphore*(CARB_ABI* createSemaphore)(unsigned value); /** * Destroys a semaphore object created by createSemaphore() * * @param sema The semaphore to destroy. */ void(CARB_ABI* destroySemaphore)(Semaphore* sema); /** * Releases (or posts, or signals) a semaphore. * * If a task/thread is waiting on the semaphore when it is released, * the task/thread is un-blocked and will be resumed. If no tasks/threads are waiting on the semaphore, the next * task/thread that attempts to wait will resume immediately. * * @param sema The semaphore to release. * @param count The number of tasks/threads to release. */ void(CARB_ABI* releaseSemaphore)(Semaphore* sema, unsigned count); /** * Waits on a semaphore until it has been signaled. * * If the semaphore has already been signaled, this function returns immediately. * * @param sema The semaphore to wait on. */ void waitSemaphore(Semaphore* sema); /** * Waits on a semaphore until it has been signaled or the timeout period expires. * * If the semaphore has already been signaled, this function returns immediately. * * @param sema The semaphore to wait on. * @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever, or 0 to test * immediately without waiting. * @returns true if the semaphore count was decremented; false if the timeout period expired. */ bool(CARB_ABI* timedWaitSemaphore)(Semaphore* sema, uint64_t timeoutNs); /** * Creates a fiber-aware SharedMutex primitive. * * @warning Prefer using SharedMutexWrapper instead. * * A SharedMutex (also known as a read/write mutex) allows either multiple threads/tasks to share the primitive, or * a single thread/task to own the primitive exclusively. Threads/tasks that request ownership of the primitive, * whether shared or exclusive, will be blocked until they can be granted the access level requested. SharedMutex * gives priority to exclusive access, but will not block additional shared access requests when exclusive access * is requested. * * @return A SharedMutex object. When finished, dispose of the SharedMutex with destroySharedMutex(). */ SharedMutex*(CARB_ABI* createSharedMutex)(); /** * Requests shared access on a SharedMutex object. * * Use unlockSharedMutex() to release the shared lock. SharedMutex is not recursive. * * @param mutex The SharedMutex object. */ void lockSharedMutex(SharedMutex* mutex); /** * Requests shared access on a SharedMutex object with a timeout period. * * Use unlockSharedMutex() to release the shared lock. SharedMutex is not recursive. * * @param mutex The SharedMutex object. * @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever or 0 to test * immediately without waiting. * @returns true if the shared lock succeeded; false if timed out. */ bool(CARB_ABI* timedLockSharedMutex)(SharedMutex* mutex, uint64_t timeoutNs); /** * Requests exclusive access on a SharedMutex object. * * Use unlockSharedMutex() to release the exclusive lock. SharedMutex is not recursive. * * @param mutex The SharedMutex object. */ void lockSharedMutexExclusive(SharedMutex* mutex); /** * Requests exclusive access on a SharedMutex object with a timeout period. * * Use unlockSharedMutex() to release the exclusive lock. SharedMutex is not recursive. * * @param mutex The SharedMutex object. * @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever or 0 to test * immediately without waiting. * @returns true if the exclusive lock succeeded; false if timed out. */ bool(CARB_ABI* timedLockSharedMutexExclusive)(SharedMutex* mutex, uint64_t timeoutNs); /** * Releases a shared or an exclusive lock on a SharedMutex object. * * @param mutex The SharedMutex object. */ void(CARB_ABI* unlockSharedMutex)(SharedMutex* mutex); /** * Destroys a SharedMutex previously created with createSharedMutex(). * * @param mutex The SharedMutex object to destroy. */ void(CARB_ABI* destroySharedMutex)(SharedMutex* mutex); /** * Creates a fiber-aware ConditionVariable primitive. * * @warning Prefer using ConditionVariableWrapper instead. * * ConditionVariable is a synchronization primitive that, together with a Mutex, blocks one or more threads or tasks * until a condition becomes true. * * @return The ConditionVariable object. Destroy with destroyConditionVariable() when finished. */ ConditionVariable*(CARB_ABI* createConditionVariable)(); /** * Destroys a previously-created ConditionVariable object. * * @param cv The ConditionVariable to destroy */ void(CARB_ABI* destroyConditionVariable)(ConditionVariable* cv); /** * Waits on a ConditionVariable object until it is notified. Prefer using the helper function, * waitConditionVariablePred(). * * The given Mutex must match the Mutex passed in by all other threads/tasks waiting on the ConditionVariable, and * must be locked by the current thread/task. While waiting, the Mutex is unlocked. When the thread/task is notified * the Mutex is re-locked before returning to the caller. ConditionVariables are allowed to spuriously wake up, so * best practice is to check the variable in a loop and sleep if the variable still does not match desired. * * @param cv The ConditionVariable to wait on. * @param m The Mutex that is locked by the current thread/task. */ void waitConditionVariable(ConditionVariable* cv, Mutex* m); /** * Waits on a ConditionVariable object until it is notified or the timeout period expires. Prefer using the helper * function, timedWaitConditionVariablePred(). * * The given Mutex must match the Mutex passed in by all other threads/tasks waiting on the ConditionVariable, and * must be locked by the current thread/task. While waiting, the Mutex is unlocked. When the thread/task is notified * the Mutex is re-locked before returning to the caller. ConditionVariables are allowed to spuriously wake up, so * best practice is to check the variable in a loop and sleep if the variable still does not match desired. * * @param cv The ConditionVariable to wait on. * @param m The Mutex that is locked by the current thread/task. * @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever or 0 to test * immediately without waiting. * @returns true if the condition variable was notified; false if the timeout period expired. */ bool(CARB_ABI* timedWaitConditionVariable)(ConditionVariable* cv, Mutex* m, uint64_t timeoutNs); /** * Wakes one thread/task currently waiting on the ConditionVariable. * * @note Having the Mutex provided to waitConditionVariable() locked while calling this function is recommended * but not required. * * @param cv The condition variable to notify */ void(CARB_ABI* notifyConditionVariableOne)(ConditionVariable* cv); /** * Wakes all threads/tasks currently waiting on the ConditionVariable. * * @note Having the Mutex provided to waitConditionVariable() locked while calling this function is recommended * but not required. * * @param cv The condition variable to notify */ void(CARB_ABI* notifyConditionVariableAll)(ConditionVariable* cv); /** * Changes a tasks priority. * * @note This can be used to change a task to execute on the main thread when it next resumes when using * Priority::eMain. If called from within the context of the running task, the task immediately suspends itself * until resumed on the main thread with the next call to executeMainTasks(), at which point this function will * return. * * @param ctx The \ref TaskContext returned by \ref getTaskContext() or \ref Future::task_if(). * @param newPrio The Priority to change the task to. * @returns `true` if the priority change took effect; `false` if the TaskContext is invalid. */ bool(CARB_ABI* changeTaskPriority)(TaskContext ctx, Priority newPrio); /** * Executes all tasks that have been queued with Priority::eMain until they finish or yield. * * @note Scheduled tasks (addTaskIn() / addTaskAt()) with Priority::eMain will only be executed during the next * executeMainTasks() call after the requisite time has elapsed. */ void(CARB_ABI* executeMainTasks)(); // Intended for internal use only; only for the RequiredObject object. // NOTE: The Counter returned from this function is a one-shot counter that is only intended to be passed as a // RequiredObject. It is immediately released. //! @private enum GroupType { eAny, eAll, }; //! @private Counter*(CARB_ABI* internalGroupObjects)(GroupType type, Object const* counters, size_t count); /** * Creates a recursive mutex. * * @warning Prefer using RecursiveMutexWrapper instead. * * @note Both createMutex() and createRecursiveMutex() return a Mutex object; it is up to the creator to ensure that * the Mutex object is used properly. A Mutex created with createMutex() will call `std::terminate()` if recursively * locked. * * @return The created recursive mutex. */ Mutex*(CARB_ABI* createRecursiveMutex)(); /** * Attempts to cancel an outstanding task. * * If the task has already been started, has already been canceled or has completed, `false` is returned. * * If `true` is returned, then the task is guaranteed to never start, but every other side effect is as if the task * completed. That is, any Counter objects that were passed to addTask() will be decremented; any blocking calls to * waitForTask() will return `true`. The Future object for this task will no longer wait, but any attempt to read a * non-`void` value from it will call `std::terminate()`. If the addTask() call provided a TaskDesc::cancel member, * it will be called in the context of the calling thread and will finish before tryCancelTask() returns true. * * @param task The \ref TaskContext returned by \ref getTaskContext() or \ref Future::task_if(). * @returns `true` if the task was successfully canceled and state reset as described above. `false` if the task has * cannot be canceled because it has already started, already been canceled or has already finished. */ bool(CARB_ABI* tryCancelTask)(TaskContext task); //! @private bool(CARB_ABI* internalFutexWait)(const void* addr, const void* compare, size_t size, uint64_t timeoutNs); //! @private unsigned(CARB_ABI* internalFutexWakeup)(const void* addr, unsigned count); /** * Attempts to allocate task storage, which is similar to thread-local storage but specific to a task. * * Allocates a "key" for Task Storage. A value can be stored at this key location ("slot") that is specific to each * task. When the task finishes, @p fn is executed for any non-`nullptr` value stored in that slot. * * Values can be stored in the Task Storage slot with setTaskStorage() and getTaskStorage(). * * When Task Storage is no longer needed, use freeTaskStorage() to return the slot to the system. * * @warning The number of slots are very limited. If no slots are available, kInvalidTaskStorageKey is returned. * * @param fn (Optional) A destructor function called when a task finishes with a non-`nullptr` value in the * allocated slot. The value stored with setTaskStorage() is passed to the destructor. If a destructor is not * desired, `nullptr` can be passed. * @returns An opaque TaskStorageKey representing the slot for the requested Task Storage data. If no slots are * available, kInvalidTaskStorageKey is returned. */ TaskStorageKey(CARB_ABI* allocTaskStorage)(TaskStorageDestructorFn fn); /** * Frees a Task Storage slot. * * @note Any associated destructor function registered with allocTaskStorage() will not be called for any data * present in currently running tasks. Once freeTaskStorage() returns, the destructor function registered with * allocTaskStorage() will not be called for any data on any tasks. * * @param key The Task Storage key previously allocated with allocTaskStorage(). */ void(CARB_ABI* freeTaskStorage)(TaskStorageKey key); /** * Stores a value at a slot in Task Storage for the current task. * * The destructor function passed to allocTaskStorage() will be called with any non-`nullptr` values remaining in * Task Storage at the associated @p key when the task finishes. * * @warning This function can only be called from task context, otherwise `false` is returned. * @param key The Task Storage key previously allocated with allocTaskStorage(). * @param value A value to store at the Task Storage slot described by @p key for the current task only. * @return `true` if the value was stored; `false` otherwise. */ bool(CARB_ABI* setTaskStorage)(TaskStorageKey key, void* value); /** * Retrieves a value at a slot in Task Storage for the current task. * * The destructor function passed to allocTaskStorage() will be called with any non-`nullptr` values remaining in * Task Storage at the associated @p key when the task finishes. * * @warning This function can only be called from task context, otherwise `nullptr` is returned. * @param key The Task Storage key previously allocated with allocTaskStorage(). * @returns The value previously passed to setTaskStorage(), or `nullptr` if not running in task context or a value * was not previously passed to setTaskStorage() for the current task. */ void*(CARB_ABI* getTaskStorage)(TaskStorageKey key); // Do not call directly; use ScopedTracking instead. // Returns a special tracking object that MUST be passed to endTracking(). //! @private Object(CARB_ABI* beginTracking)(Object const* trackers, size_t numTrackers); // Do not call directly; use ScopedTracking instead. //! @private void(CARB_ABI* endTracking)(Object tracker); /** * Retrieves debug information about a specific task. * * @note This information is intended for debug only and should not affect application state or decisions in the * application. * * @warning Since carb.tasking is an inherently multi-threaded API, the values presented as task debug information * may have changed in a worker thread in the short amount of time between when they were generated and when they * were read by the application. As such, the debug information was true at a previous point in time and should not * be considered necessarily up-to-date. * * @param task The TaskContext to retrieve information about. * @param[out] out A structure to fill with debug information about @p task. The TaskDebugInfo::sizeOf field must be * pre-filled by the caller. May be `nullptr` to determine if @p task is valid. * @returns `true` if the TaskContext was valid and @p out (if non-`nullptr`) was filled with known information * about @p task. `false` if @p out specified an unknown size or @p task does not refer to a valid task. */ bool(CARB_ABI* getTaskDebugInfo)(TaskContext task, TaskDebugInfo* out); /** * Walks all current tasks and calls a callback function with debug info for each. * * @note This information is intended for debug only and should not affect application state or decisions in the * application. * * @warning Since carb.tasking is an inherently multi-threaded API, the values presented as task debug information * may have changed in a worker thread in the short amount of time between when they were generated and when they * were read by the application. As such, the debug information was true at a previous point in time and should not * be considered necessarily up-to-date. * * @param info A structure to fill with debug information about tasks encountered during the walk. The * TaskDebugInfo::sizeOf field must be pre-filled by the caller. * @param fn A function to call for each task encountered. The function is called repeatedly with a different task * each time, until all tasks have been visited or the callback function returns `false`. * @param context Application-specific context information that is passed directly to each invocation of @p fn. */ bool(CARB_ABI* walkTaskDebugInfo)(TaskDebugInfo& info, TaskDebugInfoFn fn, void* context); //! @private void(CARB_ABI* internalApplyRangeBatch)(size_t range, size_t batchHint, ApplyBatchFn fn, void* context); //! @private void(CARB_ABI* internalBindTrackers)(Object required, Object const* ptrackes, size_t numTrackers); //! @private void(CARB_ABI* internalNameTask)(TaskContext task, const char* name, bool dynamic); /** * Instructs ITasking to reload all IFiberEvents interfaces. * * The @ref IFiberEvents interface is used by @ref ITasking to notify listeners that are interested in fiber-switch * events. All @ref IFiberEvents interfaces are queried from the @ref carb::Framework by @ref ITasking only at * startup, or when @ref changeParameters() is called, or when `reloadFiberEvents()` is called. * * Unlike @ref changeParameters(), this function is safe to call from within a task, or from multiple threads * simultaneously, and tasks can be added while this function is executing. * * @note This function is a task system synchronization point, requiring all task threads to synchronize and pause * before reloading @ref IFiberEvents interfaces. Generally this happens rapidly, but if a task thread is busy, the * entire tasking system will wait for the task to finish or enter a wait state before reloading @ref IFiberEvents * interfaces. */ void(CARB_ABI* reloadFiberEvents)(); /////////////////////////////////////////////////////////////////////////// // Helper functions /** * Yields execution to another task until `counter == value`. * * Task invoking this call will resume on the same thread due to thread pinning. Thread pinning is not efficient. * See pinToCurrentThread() for details. * * @param counter The counter to check. */ void yieldUntilCounterPinThread(RequiredObject counter); /** * Checks @p pred in a loop until it returns true, and waits on a ConditionVariable if @p pred returns false. * * @param cv The ConditionVariable to wait on * @param m The Mutex associated with the ConditionVariable. Must be locked by the calling thread/task. * @param pred A function-like predicate object in the form `bool(void)`. waitConditionVariablePred() returns when * @p pred returns true. */ template <class Pred> void waitConditionVariablePred(ConditionVariable* cv, Mutex* m, Pred&& pred) { while (!pred()) { this->waitConditionVariable(cv, m); } } /** * Checks @p pred in a loop until it returns true or the timeout period expires, and waits on a ConditionVariable * if @p pred returns false. * * @param cv The ConditionVariable to wait on * @param m The Mutex associated with the ConditionVariable. Must be locked by the calling thread/task. * @param timeoutNs The relative timeout period in nanoseconds. Specify @ref kInfinite to wait forever or 0 to test * immediately without waiting. * @param pred A function-like predicate object in the form `bool(void)`. waitConditionVariablePred() returns when * @p pred returns true. * @returns `true` if the predicate returned `true`; `false` if the timeout period expired */ template <class Pred> bool timedWaitConditionVariablePred(ConditionVariable* cv, Mutex* m, uint64_t timeoutNs, Pred&& pred) { while (!pred()) if (!this->timedWaitConditionVariable(cv, m, timeoutNs)) return false; return true; } /** * Executes a task synchronously. * * @note To ensure that the task executes in task context, the function is called directly if already in task * context. If called from non-task context, @p f is executed by a call to addTask() but this function does not * return until the subtask is complete. * * @param priority The priority of the task to execute. Only used if not called in task context. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value. * @param args Arguments to pass to @p f. * @return The return value of @p f. */ template <class Callable, class... Args> auto awaitSyncTask(Priority priority, Callable&& f, Args&&... args); /** * Runs the given function-like object as a task. * * @param priority The priority of the task to execute. * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class... Args> auto addTask(Priority priority, Trackers&& trackers, Callable&& f, Args&&... args); /** * Adds a task to the internal queue. * * @note Deprecated: The other addTask() (and variant) functions accept lambdas and function-like objects, and are * designed to simplify adding tasks and add tasks succinctly. Prefer using those functions. * * @param desc The TaskDesc describing the task. * @param counter A counter to associate with this task. It will be incremented by 1. * When the task completes, it will be decremented. * @return A TaskContext that can be used to refer to this task */ CARB_DEPRECATED("Use a C++ addTask() function") TaskContext addTask(TaskDesc desc, Counter* counter) { return this->internalAddTask(desc, counter); } /** * Runs the given function-like object as a task when a Semaphore is signaled. * * @param throttler (optional) A Semaphore used to throttle the number of tasks that can run concurrently. The task * waits until the semaphore is signaled (released) before starting, and then signals the semaphore after the task * has executed. * @param priority The priority of the task to execute. * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class... Args> auto addThrottledTask(Semaphore* throttler, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args); /** * Runs the given function-like object as a task once a Counter reaches its target. * * @param requiredObject (optional) An object convertible to RequiredObject (such as a task or Future). * that will, upon completing, trigger the execution of this task. * @param priority The priority of the task to execute. * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class... Args> auto addSubTask(RequiredObject requiredObject, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args); /** * Runs the given function-like object as a task once a Counter reaches its target and when a Semaphore is signaled. * * @param requiredObject (optional) An object convertible to RequiredObject (such as a task or Future). * that will, upon completing, trigger the execution of this task. * @param throttler (optional) A semaphore used to throttle the number of tasks that can run concurrently. Once * requiredObject becomes signaled, the task waits until the semaphore is signaled (released) before starting, and * then signals the semaphore after the task has executed. * @param priority The priority of the task to execute. * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class... Args> auto addThrottledSubTask(RequiredObject requiredObject, Semaphore* throttler, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args); /** * Adds a task to occur after a specific duration has passed. * * @param dur The duration to wait for. The task is not started until this duration elapses. * @param priority The priority of the task to execute * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class Rep, class Period, class... Args> auto addTaskIn(const std::chrono::duration<Rep, Period>& dur, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args); /** * Adds a task to occur at a specific point in time * * @param when The point in time at which to begin the task * @param priority The priority of the task to execute * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class Clock, class Duration, class... Args> auto addTaskAt(const std::chrono::time_point<Clock, Duration>& when, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args); /** * Processes a range from `[0..range)` calling a functor for each index, potentially from different threads. * * @note This function does not return until @p f has been called (and returned) on every index from [0.. * @p range) * @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must * be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in * @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety. * @note Calling this function recursively will automatically scale down the parallelism in order to not overburden * the system. * @note As there is overhead to calling \p f repeatedly, it is more efficient to use \ref applyRangeBatch() with * `batchHint = 0` and a `f` that handles multiple indexes on one invocation. * * See the @rstref{additional documentation <tasking-parallel-for>} for `applyRange`. * * @param range The number of times to call @p f. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that is repeatedly called until * all indexes in `[0..range)` have been processed, potentially from different threads. It is invoked with * parameters `f(args..., index)` where `index` is within the range `[0..range)`. * @param args Arguments to pass to @p f */ template <class Callable, class... Args> void applyRange(size_t range, Callable f, Args&&... args); /** * Processes a range from `[0..range)` calling a functor for batches of indexes, potentially from different threads. * * @note This function does not return until @p f has been called (and returned) for every index from * `[0..range)` * @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must * be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in * @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety. * @note Calling this function recursively will automatically scale down the parallelism in order to not overburden * the system. * * See the @rstref{additional documentation <tasking-parallel-for>} for `applyRange`. * * @param range The number of times to call @p f. * @param batchHint A recommendation of batch size to determine the range of indexes to pass to @p f for processing. * A value of 0 uses an internal heuristic to divide work, which is recommended in most cases. This value is a hint * to the internal heuristic and therefore \p f may be invoked with a different range size. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that is repeatedly called until * all indexes in `[0..range)` have been processed, potentially from different threads. It is invoked with * parameters `f(args..., startIndex, endIndex)` where `[startIndex..endIndex)` is the range of indexes that must be * processed by that invocation of `f`. Note that `endIndex` is a past-the-end index and must not actually be * processed by that invocation of `f`. * @param args Arguments to pass to @p f */ template <class Callable, class... Args> void applyRangeBatch(size_t range, size_t batchHint, Callable f, Args&&... args); /** * Processes a range from [begin..end) calling a functor for each index, potentially from different threads. * * @note This function does not return until @p f has been called (and returned) on every index from [begin.. * @p end) * @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must * be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in * @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety. * @note Calling this function recursively will automatically scale down the parallelism in order to not overburden * the system. * * @param begin The starting value passed to @p f * @param end The ending value. Every T(1) step in [begin, end) is passed to @p f * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value. * The index value from [begin..end) is passed as the last parameter (after any passed @p args). * @param args Arguments to pass to @p f */ template <class T, class Callable, class... Args> void parallelFor(T begin, T end, Callable f, Args&&... args); /** * Processes a stepped range from [begin..end) calling a functor for each step, potentially from different threads. * * @note This function does not return until @p f has been called (and returned) on every index from [begin.. * @p end) * @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must * be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in * @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety. * @note Calling this function recursively will automatically scale down the parallelism in order to not overburden * the system. * * @param begin The starting value passed to @p f * @param end The ending value. Every @p step in [begin, end) is passed to @p f * @param step The step size to determine every value passed to @p f * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value. * The stepped value from [begin..end) is passed as the last parameter (after any passed @p args). * @param args Arguments to pass to @p f */ template <class T, class Callable, class... Args> void parallelFor(T begin, T end, T step, Callable f, Args&&... args); /** * Causes the current thread or task to sleep for the specified time. * * @note This function is fiber-aware. If currently executing in a fiber, the fiber will be yielded until the * requested amount of time has passed. If a thread is currently executing, then the thread will sleep. * * @param dur The duration to sleep for */ template <class Rep, class Period> void sleep_for(const std::chrono::duration<Rep, Period>& dur) { sleepNs(detail::convertDuration(dur)); } /** * Causes the current thread or task to sleep until the specified time. * * @note This function is fiber-aware. If currently executing in a fiber, the fiber will be yielded until the * requested amount of time has passed. If a thread is currently executing, then the thread will sleep. * * @param tp The absolute time point to sleep until */ template <class Clock, class Duration> void sleep_until(const std::chrono::time_point<Clock, Duration>& tp) { sleepNs(detail::convertAbsTime(tp)); } /** * A fiber-safe futex implementation: if @p val equals @p compare, the thread or task sleeps until woken. * * @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives. * * @param val The atomic value to check. * @param compare The value to compare against. If @p val matches this, then the calling thread or task sleeps until * futexWakeup() is called. */ template <class T> void futexWait(const std::atomic<T>& val, T compare) { bool b = internalFutexWait(&val, &compare, sizeof(T), kInfinite); CARB_ASSERT(b); CARB_UNUSED(b); } /** * A fiber-safe futex implementation: if @p val equals @p compare, the thread or task sleeps until woken or the * timeout period expires. * * @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives. * * @param val The atomic value to check. * @param compare The value to compare against. If @p val matches this, then the calling thread or task sleeps until * futexWakeup() is called. * @param dur The maximum duration to wait. * @returns `true` if @p val doesn't match @p compare or if futexWakeup() was called; `false` if the timeout period * expires. */ template <class T, class Rep, class Period> bool futexWaitFor(const std::atomic<T>& val, T compare, std::chrono::duration<Rep, Period> dur) { return internalFutexWait(&val, &compare, sizeof(T), detail::convertDuration(dur)); } /** * A fiber-safe futex implementation: if @p val equals @p compare, the thread or task sleeps until woken or the * specific time is reached. * * @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives. * * @param val The atomic value to check. * @param compare The value to compare against. If @p val matches this, then the calling thread or task sleeps until * futexWakeup() is called. * @param when The clock time to wait until. * @returns `true` if @p val doesn't match @p compare or if futexWakeup() was called; `false` if the clock time is * reached. */ template <class T, class Clock, class Duration> bool futexWaitUntil(const std::atomic<T>& val, T compare, std::chrono::time_point<Clock, Duration> when) { return internalFutexWait(&val, &compare, sizeof(T), detail::convertAbsTime(when)); } /** * Wakes threads or tasks waiting in futexWait(), futexWaitFor() or futexWaitUntil(). * * @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives. * * @param val The same `val` passed to futexWait(), futexWaitFor() or futexWaitUntil(). * @param count The number of threads or tasks to wakeup. To wake all waiters use `UINT_MAX`. * @returns The number of threads or tasks that were waiting and are now woken. */ template <class T> unsigned futexWakeup(const std::atomic<T>& val, unsigned count) { return internalFutexWakeup(&val, count); } /** * Binds any number of \ref Tracker objects to the given \ref RequiredObject. Effectively allows adding trackers to * a given object. * * Previously this was only achievable through a temporary task: * ```cpp * // Old way: a task that would bind `taskGroup` to `requiredObject` * tasking->addSubTask(requiredObject, Priority::eDefault, { taskGroup }, []{}); * // New way: direct binding: * tasking->bindTrackers(requiredObject, { taskGroup }); * ``` * The previous method wasted time in that one of the task threads would eventually have to pop the task from the * queue and run an empty function. Calling `bindTrackers()` does not waste this time. * * However, there are some "disadvantages." The `addSubTask()` method would allocate a \ref TaskContext, return a * \ref Future, and could be canceled. These features were seldom needed, hence this function. * * @param requiredObject An object convertible to RequiredObject (such as a task or Future). The given \p trackers * will be bound to this required object. * @param trackers A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. */ void bindTrackers(RequiredObject requiredObject, Trackers&& trackers); /** * Sets a name for a task for debugging purposes, similar to how threads can be named. * * This function is optimized for a literal string: passing a literal string as @p name does not copy the string but * instead retains the pointer as it is guaranteed to never change. Passing a non-literal string will result in a * copy. * * The task name is visible in the debugger as @rstref{debug information <showing-all-tasks>} for a task. * * Retrieving the task name can be accomplished through @ref getTaskDebugInfo(). * * @note It is often easier to name the task as it's created by passing a task name as a @ref Tracker object to * @ref addTask() or the other task creation functions. * * @thread_safety It is safe to set a task name from multiple threads, though inadvisable. Reading the task name via * @ref getTaskDebugInfo() while it is being changed in a different thread is not strongly ordered and may * result in an empty string being read, or random bytes as the name string, but will not result in a crash. * @tparam T A type that is convertible to `const char*`. See @p name below. * @param task The @ref TaskContext to name. If this is not a valid task, or the task has already completed or has * been cancelled, nothing happens. * @param name Either a `const char*` (dynamic string) or a `const char (&)[N]` (literal string) as the string name. * May be `nullptr` to un-set a task name. Dynamic strings will be copied before the call returns. Literal * strings will be retained by pointer value. */ template <class T, std::enable_if_t<std::is_convertible<T, const char*>::value, bool> = false> void nameTask(TaskContext task, T&& name) { internalNameTask(task, name, !detail::is_literal_string<T>::value); } }; /** * Causes the currently executing TaskContext to be "pinned" to the thread it is currently running on until PinGuard is * destroyed. * * Appropriately handles recursive pinning. This class causes the current thread to be the only task thread that can run * the current task. This is necessary in some cases where thread specificity is required (those these situations are * NOT recommended for tasks): holding a mutex, or using thread-specific data, etc. Thread pinning is not efficient (the * pinned thread could be running a different task causing delays for the current task to be resumed, and wakeTask() * must wait to return until the pinned thread has been notified) and should therefore be avoided. * * @note It is assumed that the task is allowed to move to another thread during the pinning process, though this may * not always be the case. Only after the PinGuard is constructed will a task be pinned. Therefore, make sure to * construct PinGuard *before* any operation that requires pinning. */ class PinGuard { public: /** * Constructs a PinGuard and enters the "pinned" scope. */ PinGuard() : m_wasPinned(carb::getCachedInterface<ITasking>()->pinToCurrentThread()) { } /** * Constructs a PinGuard and enters the "pinned" scope. * @note Deprecated: ITasking no longer needed. */ CARB_DEPRECATED("ITasking no longer needed.") PinGuard(ITasking*) : m_wasPinned(carb::getCachedInterface<ITasking>()->pinToCurrentThread()) { } /** * Destructs a PinGuard and leaves the "pinned" scope. */ ~PinGuard() { if (!m_wasPinned) carb::getCachedInterface<ITasking>()->unpinFromCurrentThread(); } private: bool m_wasPinned; }; } // namespace tasking } // namespace carb #include "ITasking.inl"
63,576
C
46.304315
121
0.68378
omniverse-code/kit/include/carb/tasking/TaskingTypes.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 carb.tasking type definitions #pragma once #include "../Defines.h" namespace carb { namespace tasking { /** * Used to create dependencies between tasks and to wait for a set of tasks to finish. * * @note Prefer using CounterWrapper. * * @see ITasking::createCounter(), ITasking::createCounterWithTarget(), ITasking::destroyCounter(), * ITasking::yieldUntilCounter(), ITasking::timedYieldUntilCounter(), ITasking::checkCounter(), * ITasking::getCounterValue(), ITasking::getCounterTarget(), ITasking::fetchAddCounter(), ITasking::fetchSubCounter(), * ITasking::storeCounter() */ class Counter DOXYGEN_EMPTY_CLASS; /** * A fiber-aware mutex: a synchronization primitive for mutual exclusion. Only one thread/fiber can "own" the mutex at * a time. * * @note Prefer using MutexWrapper. * * @see ITasking::createMutex(), ITasking::destroyMutex(), ITasking::lockMutex(), ITasking::timedLockMutex(), * ITasking::unlockMutex(), ITasking::createRecursiveMutex() */ class Mutex DOXYGEN_EMPTY_CLASS; /** * A fiber-aware semaphore: a synchronization primitive that limits to N threads/fibers. * * @note Prefer using SemaphoreWrapper. * * @see ITasking::createSemaphore(), ITasking::destroySemaphore(), ITasking::releaseSemaphore(), * ITasking::waitSemaphore(), ITasking::timedWaitSemaphore() */ class Semaphore DOXYGEN_EMPTY_CLASS; /** * A fiber-aware shared_mutex: a synchronization primitive that functions as a multiple-reader/single-writer lock. * * @note Prefer using SharedMutexWrapper. * * @see ITasking::createSharedMutex(), ITasking::lockSharedMutex(), ITasking::timedLockSharedMutex(), * ITasking::lockSharedMutexExclusive(), ITasking::timedLockSharedMutexExclusive(), ITasking::unlockSharedMutex(), * ITasking::destroySharedMutex() */ class SharedMutex DOXYGEN_EMPTY_CLASS; /** * A fiber-aware condition_variable: a synchronization primitive that, together with a Mutex, blocks one or more threads * or tasks until a condition becomes true. * * @note Prefer using ConditionVariableWwrapper. * * @see ITasking::createConditionVariable(), ITasking::destroyConditionVariable(), ITasking::waitConditionVariable(), * ITasking::timedWaitConditionVariable(), ITasking::notifyConditionVariableOne(), * ITasking::notifyConditionVariableAll() */ class ConditionVariable DOXYGEN_EMPTY_CLASS; struct ITasking; /** * A constant for ITasking wait functions indicating "infinite" timeout */ constexpr uint64_t kInfinite = uint64_t(-1); /** * Defines a task priority. */ enum class Priority { eLow, //!< Low priority. Tasks will be executed after higher priority tasks. eMedium, //!< Medium priority. eHigh, //!< High priority. Tasks will be executed before lower priority tasks. eMain, //!< A special priority for tasks that are only executed during ITasking::executeMainTasks() eCount, //!< The number of Priority classes // Aliases eDefault = eMedium, //!< Alias for eMedium priority. }; /** * Object type for Object. * * @note These are intended to be used only by helper classes such as RequiredObject. */ enum class ObjectType { eNone, //!< Null/no object. eCounter, //!< Object::data refers to a Counter*. eTaskContext, //!< Object::data refers to a TaskContext. ePtrTaskContext, //!< Object::data refers to a TaskContext*. eTaskGroup, //!< Object::data is a pointer to a std::atomic_size_t. @see TaskGroup eSharedState, //!< Object::data is a pointer to a detail::SharedState. Not used internally by carb.tasking. eFutex1, //!< Object::data is a pointer to a std::atomic_uint8_t. Signaled on zero. eFutex2, //!< Object::data is a pointer to a std::atomic_uint16_t. Signaled on zero. eFutex4, //!< Object::data is a pointer to a std::atomic_uint32_t. Signaled on zero. eFutex8, //!< Object::data is a pointer to a std::atomic_uint64_t. Signaled on zero. eTrackerGroup, //!< Object::data is a pointer to an internal tracking object. eTaskName, //!< Object::data is a `const char*` to be copied and used as a task name. eTaskNameLiteral, //!< Object::data is a `const char*` that can be retained because it is a literal. }; /** * The function to execute as a task. * * @param taskArg The argument passed to ITasking::addTask() variants. */ using OnTaskFn = void (*)(void* taskArg); /** * The function executed by ITasking::applyRange() * * @param index The ApplyFn is called once for every integer @p index value from 0 to the range provided to * ITasking::applyRange(). * @param taskArg The argument passed to ITasking::applyRange(). */ using ApplyFn = void (*)(size_t index, void* taskArg); /** * The function executed by ITasking::applyRangeBatch() * * @note This function differs from \ref ApplyFn in that it must handle a contiguous range of indexes determined by * `[startIndex, endIndex)`. * @warning The item at index \p endIndex is \b not to be processed by this function. In other words, the range handled * by this function is: * ```cpp * for (size_t i = startIndex; i != endIndex; ++i) * array[i]->process(); * ``` * @param startIndex The initial index that must be handled by this function call. * @param endIndex The after-the-end index representing the range of indexes that must be handled by this function call. * The item at this index is after-the-end of the assigned range and <strong>must not be processed</strong>. * @param taskArg The argument passed to ITasking::applyRangeBatch(). */ using ApplyBatchFn = void (*)(size_t startIndex, size_t endIndex, void* taskArg); /** * A destructor function for a Task Storage slot. * * This function is called when a task completes with a non-`nullptr` value in the respective Task Storage slot. * @see ITasking::allocTaskStorage() * @param arg The non-`nullptr` value stored in a task storage slot. */ using TaskStorageDestructorFn = void (*)(void* arg); /** * An opaque handle representing a Task Storage slot. */ using TaskStorageKey = size_t; /** * Represents an invalid TaskStorageKey. */ constexpr TaskStorageKey kInvalidTaskStorageKey = size_t(-1); /** * An opaque handle that is used with getTaskContext(), suspendTask() and wakeTask(). */ using TaskContext = size_t; /** * A specific value for TaskContext that indicates a non-valid TaskContext. */ constexpr TaskContext kInvalidTaskContext = 0; /** * The absolute maximum number of fibers that ITasking will create. */ constexpr uint32_t kMaxFibers = 1048575; /** * A generic @rstref{ABI-safe <abi-compatibility>} representation of multiple types. */ struct Object { ObjectType type; //!< The ObjectType of the represented type. void* data; //!< Interpreted based on the ObjectType provided. }; /** * Defines a task descriptor. */ struct TaskDesc { /// Must be set to sizeof(TaskDesc). size_t size{ sizeof(TaskDesc) }; /// The task function to execute OnTaskFn task; /// The argument passed to the task function void* taskArg; /// The priority assigned to the task Priority priority; /// If not nullptr, then the task will only start when this counter reaches its target value. Specifying the counter /// here is more efficient than having the task function yieldUntilCounter(). Object requiredObject; /// If waitSemaphore is not nullptr, then the task will wait on the semaphore before starting. This can be used to /// throttle tasks. If requiredObject is also specified, then the semaphore is not waited on until requiredObject /// has reached its target value. Specifying the semaphore here is more efficient than having the task function /// wait on the semaphore. Semaphore* waitSemaphore; /// Optional. An OnTaskFn that is executed only when ITasking::tryCancelTask() successfully cancels the task. Called /// in the context of ITasking::tryCancelTask(). Typically provided to destroy taskArg. OnTaskFn cancel; // Internal only //! @private Object const* trackers{ nullptr }; //! @private size_t numTrackers{ 0 }; /// Constructor. constexpr TaskDesc(OnTaskFn task_ = nullptr, void* taskArg_ = nullptr, Priority priority_ = Priority::eLow, Counter* requiredCounter_ = nullptr, Semaphore* waitSemaphore_ = nullptr, OnTaskFn cancel_ = nullptr) : task(task_), taskArg(taskArg_), priority(priority_), requiredObject{ ObjectType::eCounter, requiredCounter_ }, waitSemaphore(waitSemaphore_), cancel(cancel_) { } }; /** * Defines a tasking plugin descriptor. */ struct TaskingDesc { /** * The size of the fiber pool, limited to kMaxFibers. * * Every task must be assigned a fiber before it can execute. A fiber is like a thread stack, but carb.tasking can * choose when the fibers run, as opposed to threads where the OS schedules them. * * A value of 0 means to use kMaxFibers. */ uint32_t fiberCount; /** * The number of worker threads. * * A value of 0 means to use \ref carb::thread::hardware_concurrency(). */ uint32_t threadCount; /** * The optional array of affinity values for every thread. * * If set to `nullptr`, affinity is not set. Otherwise it must contain `threadCount` number of elements. Each * affinity value is a CPU index in the range [0 - `carb::thread::hardware_concurrency()`) */ uint32_t* threadAffinity; /** * The stack size per fiber. 0 indicates to use the system default. */ uint64_t stackSize; }; /** * Debug state of a task. */ enum class TaskDebugState { Pending, //!< The task has unmet pre-requisites and cannot be started yet. New, //!< The task has passed all pre-requisites and is waiting to be assigned to a task thread. Running, //!< The task is actively running on a task thread. Waiting, //!< The task has been started but is currently waiting and is not running on a task thread. Finished, //!< The task has finished or has been canceled. }; /** * Defines debug information about a task retrieved by ITasking::getTaskDebugInfo() or ITasking::walkTaskDebugInfo(). * * @note This information is intended for debug only and should not affect application state or decisions in the * application. * * @warning Since carb.tasking is an inherently multi-threaded API, the values presented as task debug information * may have changed in a worker thread in the short amount of time between when they were generated and when they were * read by the application. As such, the debug information was true at a previous point in time and should not be * considered necessarily up-to-date. */ struct TaskDebugInfo { //! Size of this struct, used for versioning. size_t sizeOf{ sizeof(TaskDebugInfo) }; //! The TaskContext handle for the task. TaskContext context{}; //! The state of the task. TaskDebugState state{}; //! The task function for this task that was submitted to ITasking::addTask() (or variant function), if known. May //! be `nullptr` if the task has finished or was canceled. OnTaskFn task{}; //! The task argument for this task that was submitted to ITasking::addTask() (or variant function), if known. May //! be `nullptr` if the task has finished or was canceled. void* taskArg{}; //! Input: the maximum number of frames that can be stored in the memory pointed to by the `creationCallstack` //! member. //! Output: the number of frames that were stored in the memory pointed to by the `creationCallstack` member. size_t numCreationFrames{ 0 }; //! The callstack that called ITasking::addTask() (or variant function). The callstack is only available if //! carb.tasking is configured to capture callstacks with setting */plugins/carb.tasking.plugin/debugTaskBacktrace*. //! //! @note If this value is desired, prior to calling ITasking::getTaskDebugInfo() set this member to a buffer that //! will be filled by the ITasking::getTaskDebugInfo() function. Set `numCreationFrames` to the number of frames //! that can be contained in the buffer. After calling ITasking::getTaskDebugInfo(), this member will contain the //! available creation callstack frames and `numCreationFrames` will be set to the number of frames that could be //! written. void** creationCallstack{ nullptr }; //! Input: the maximum number of frames that can be stored in the memory pointed to by the `waitingCallstack` //! member. //! Output: the number of frames that were stored in the memory pointed to by the `waitingCallstack` member. size_t numWaitingFrames{ 0 }; //! The callstack of the task when waiting. This is only captured if carb.tasking is configured to capture //! callstacks with setting */plugins/carb.tasking.plugin/debugTaskBacktrace* and if `state` is //! TaskDebugState::Waiting. //! //! @warning Capturing this value is somewhat unsafe as debug information is not stored in a way that will impede //! task execution whatsoever (i.e. with synchronization), therefore information is gathered from a running task //! without stopping it. As such, reading the waiting callstack may produce bad data and in extremely rare cases //! cause a crash. If the state changes while gathering info, `state` may report TaskDebugState::Waiting but //! `numWaitingFrames` may be `0` even though some data was written to the buffer pointed to by `waitingCallstack`. //! //! @note If this value is desired, prior to calling ITasking::getTaskDebugInfo() set this member to a buffer that //! will be filled by the ITasking::getTaskDebugInfo() function. Set `numWaitingFrames` to the number of frames that //! can be contained in the buffer. After calling ITasking::getTaskDebugInfo(), this member will contain the //! available waiting callstack frames and `numWaitingFrames` will be set to the number of frames that could be //! written. void** waitingCallstack{ nullptr }; //! Input: the maximum number of characters that can be stored in the memory pointed to by the `taskName` member. //! Output: the number of characters written (including the NUL terminator) to the memory pointed to by the //! `taskName` member. size_t taskNameSize{ 0 }; //! A optional buffer that will be filled with the task name if provided. //! //! @note If this value is desired, prior to calling ITasking::getTaskDebugInfo() set this member to a buffer that //! will be filled by the ITasking::getTaskDebugInfo() function. Set `taskNameSize` to the number of characters that //! can be contained in the buffer. After calling ITasking::getTaskDebugInfo(), this member will contain the //! NUL-terminated task name and `taskNameSize` will be set to the number of characters that could be written //! (including the NUL-terminator). char* taskName{ nullptr }; }; //! Callback function for ITasking::walkTaskDebugInfo(). //! @param info The TaskDebugInfo structure passed to ITasking::walkTaskDebugInfo(), filled with information about a //! task. //! @param context The `context` field passed to ITasking::walkTaskDebugInfo(). //! @return `true` if walking tasks should continue; `false` to terminate walking tasks. using TaskDebugInfoFn = bool (*)(const TaskDebugInfo& info, void* context); #ifndef DOXYGEN_BUILD namespace detail { template <class T> struct GenerateFuture; template <class T> class SharedState; } // namespace detail struct Trackers; struct RequiredObject; template <class T> class Promise; template <class T> class SharedFuture; #endif /** * A Future is a counterpart to a Promise. It is the receiving end of a one-way, one-time asynchronous communication * channel for transmitting the result of an asynchronous operation. * * Future is very similar to <a href="https://en.cppreference.com/w/cpp/thread/future">std::future</a> * * Communication starts by creating a Promise. The Promise has an associated Future that can be retrieved once via * Promise::get_future(). The Promise and the Future both reference a "shared state" that is used to communicate the * result. When the result is available, it is set through Promise::set_value() (or the promise can be broken through * Promise::setCanceled()), at which point the shared state becomes Ready and the Future will be able to retrieve the * value through Future::get() (or determine cancellation via Future::isCanceled()). * * Task functions like ITasking::addTask() return a Future where the Promise side is the return value from the callable * passed when the task is created. * * Future is inherently a "read-once" object. Once Future::get() is called, the Future becomes invalid. However, * SharedFuture can be used (created via Future::share()) to retain the value. Many threads can wait on a SharedFuture * and access the result simultaneously through SharedFuture::get(). * * There are three specializations of Future: * * Future<T>: The base specialization, used to communicate objects between tasks/threads. * * Future<T&>: Reference specialization, used to communicate references between tasks/threads. * * Future<void>: Void specialization, used to communicate stateless events between tasks/threads. * * The `void` specialization of Future is slightly different: * * Future<void> does not have Future::isCanceled(); cancellation state cannot be determined. */ template <class T = void> class Future { public: /** * Creates a future in an invalid state (valid() would return false). */ constexpr Future() noexcept = default; /** * Destructor. */ ~Future(); /** * Futures are movable. */ Future(Future&& rhs) noexcept; /** * Futures are movable. */ Future& operator=(Future&& rhs) noexcept; /** * Tests to see if this Future is valid. * * @returns true if get() and wait() are supported; false otherwise */ bool valid() const noexcept; /** * Checks to see if a value can be read from this Future * * @warning Undefined behavior to call this if valid() == `false`. * @returns true if a value can be read from this Future; false if the value is not yet ready */ bool try_wait() const; /** * Waits until a value can be read from this Future * @warning Undefined behavior to call this if valid() == `false`. */ void wait() const; /** * Waits until a value can be read from this Future, or the timeout period expires. * * @warning Undefined behavior to call this if valid() == `false`. * @param dur The relative timeout period. * @returns true if a value can be read from this Future; false if the timeout period expires before the value can * be read */ template <class Rep, class Period> bool wait_for(const std::chrono::duration<Rep, Period>& dur) const; /** * Waits until a value can be read from this Future, or the timeout period expires. * * @warning Undefined behavior to call this if valid() == `false`. * @param when The absolute timeout period. * @returns true if a value can be read from this Future; false if the timeout period expires before the value can * be read */ template <class Clock, class Duration> bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const; /** * Waits until the future value is ready and returns the value. Resets the Future to an invalid state. * * @warning This function will call `std::terminate()` if the underlying task has been canceled with * ITasking::tryCancelTask() or the Promise was broken. Use isCanceled() to determine if the value is safe to read. * * @returns The value passed to Promise::set_value(). */ T get(); /** * Returns whether the Promise has been broken (or if this Future represents a task, the task has been canceled). * * @warning Undefined behavior to call this if valid() == `false`. * @note The `void` specialization of Future does not have this function. * @returns `true` if the task has been canceled; `false` if the task is still pending or has a valid value to read. */ bool isCanceled() const; /** * Transfers the Future's shared state (if any) to a SharedFuture and leaves `*this` invalid (valid() == `false`). * @returns A SharedFuture with the same shared state as `*this`. */ SharedFuture<T> share(); /** * Returns a valid TaskContext if this Future represents a task. * * @note Futures can be returned from \ref ITasking::addTask() and related functions or from * \ref Promise::get_future(). Only Future objects returned from \ref ITasking::addTask() will return a valid * pointer from task_if(). * * @returns A pointer to a TaskContext if this Future was created from \ref ITasking::addTask() or related * functions; `nullptr` otherwise. The pointer is valid as long as the Future exists and the result from * \ref valid() is `true`. */ const TaskContext* task_if() const; /** * Convertible to RequiredObject. */ operator RequiredObject() const; /** * Syntactic sugar around ITasking::addSubTask() that automatically passes the value from get() into `Callable` and * resets the Future to an invalid state. * * @warning This resets the Future to an invalid state since the value is being consumed by the sub-task. * * @note This can be used to "chain" tasks together. * * @warning If the dependent task is canceled then the sub-task will call `std::terminate()`. When canceling the * dependent task you must first cancel the sub-task. * * @warning For non-`void` specializations, it is undefined behavior to call this if valid() == `false`. * * @param prio The priority of the task to execute. * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value. * The Callable object must take the Future's `T` type as its last parameter. * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class... Args> auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args); private: template <class U> friend struct detail::GenerateFuture; template <class U> friend class Promise; template <class U> friend class SharedFuture; CARB_PREVENT_COPY(Future); constexpr Future(detail::SharedState<T>* state) noexcept; Future(TaskContext task, detail::SharedState<T>* state) noexcept; detail::SharedState<T>* m_state{ nullptr }; }; #ifndef DOXYGEN_BUILD template <> class Future<void> { public: constexpr Future() noexcept = default; ~Future(); Future(Future&& rhs) noexcept; Future& operator=(Future&& rhs) noexcept; bool valid() const noexcept; bool try_wait() const; void wait() const; template <class Rep, class Period> bool wait_for(const std::chrono::duration<Rep, Period>& dur) const; template <class Clock, class Duration> bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const; void get(); SharedFuture<void> share(); const TaskContext* task_if() const; operator RequiredObject() const; template <class Callable, class... Args> auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args); private: template <class U> friend struct detail::GenerateFuture; template <class U> friend class Future; template <class U> friend class Promise; template <class U> friend class SharedFuture; friend struct Tracker; TaskContext* ptask(); detail::SharedState<void>* state() const noexcept; Future(TaskContext task); Future(detail::SharedState<void>* state); Object m_obj{ ObjectType::eNone, nullptr }; }; #endif /** * SharedFuture is a shareable version of Future. Instead of Future::get() invalidating the Future and returning the * value one time, multiple SharedFuture objects can reference the same shared state and allow multiple threads to * wait and access the result value simultaneously. * * SharedFuture is similar to <a href="https://en.cppreference.com/w/cpp/thread/shared_future">std::shared_future</a> * * The same specializations (and their limitations) exist as with Future. */ template <class T = void> class SharedFuture { public: /** * Default constructor. Constructs a SharedFuture where valid() == `false`. */ SharedFuture() noexcept = default; /** * Copy constructor. Holds the same state (if any) as @p other. * @param other A SharedFuture to copy state from. */ SharedFuture(const SharedFuture<T>& other) noexcept; /** * Move constructor. Moves the shared state (if any) from @p other. * * After this call, @p other will report valid() == `false`. * @param other A SharedFuture to move state from. */ SharedFuture(SharedFuture<T>&& other) noexcept; /** * Transfers the shared state (if any) from @p fut. * * After construction, @p fut will report valid() == `false`. * @param fut A Future to move state from. */ SharedFuture(Future<T>&& fut) noexcept; /** * Destructor. */ ~SharedFuture(); /** * Copy-assign operator. Holds the same state (if any) as @p other after releasing any shared state previously held. * @param other A SharedFuture to copy state from. * @returns `*this` */ SharedFuture<T>& operator=(const SharedFuture<T>& other); /** * Move-assign operator. Swaps shared states with @p other. * @param other A SharedFuture to swap states with. * @returns `*this` */ SharedFuture<T>& operator=(SharedFuture<T>&& other) noexcept; /** * Waits until the shared state is Ready and retrieves the value stored. * @warning Undefined behavior if valid() == `false`. * @returns A const reference to the stored value. */ const T& get() const; /** * Checks if the SharedFuture references a shared state. * * This is only `true` for default-constructed SharedFuture or when moved from. Unlike Future, SharedFuture does not * invalidate once the value is read with Future::get(). * @returns `true` if this SharedFuture references a shared state; `false` otherwise. */ bool valid() const noexcept; /** * Checks to see if the shared state is Ready without waiting. * * @warning Undefined behavior to call this if valid() == `false`. * @returns `true` if the shared state is Ready; `false` otherwise. */ bool try_wait() const; /** * Blocks the task or thread and waits for the shared state to become Ready. try_wait() == `true` after this call * and get() will immediately return a value. * * @warning Undefined behavior to call this if valid() == `false`. */ void wait() const; /** * Blocks the task or thread until @p dur has elapsed or the shared state becomes Ready. * * If `true` is returned, get() will return a value immediately. * @warning Undefined behavior to call this if valid() == `false`. * @param dur The duration to wait for. * @returns `true` If the shared state is Ready; `false` if the timeout period elapsed. */ template <class Rep, class Period> bool wait_for(const std::chrono::duration<Rep, Period>& dur) const; /** * Blocks the task or thread until @p when is reached or the shared state becomes Ready. * * If `true` is returned, get() will return a value immediately. * @warning Undefined behavior to call this if valid() == `false`. * @param when The clock time to wait until. * @returns `true` If the shared state is Ready; `false` if the timeout period elapsed. */ template <class Clock, class Duration> bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const; /** * Returns whether the task promising a value to this Future has been canceled. * * @warning Undefined behavior to call this if valid() == `false`. * @note The `void` specialization of SharedFuture does not have this function. * @returns `true` if the task has been canceled or promise broken; `false` if the task is still pending, promise * not yet fulfilled, or has a valid value to read. */ bool isCanceled() const; /** * Convertible to RequiredObject. */ operator RequiredObject() const; /** * Returns a valid TaskContext if this SharedFuture represents a task. * * @note Futures can be returned from addTask() and related functions or from Promise::get_future(). Only Future * objects returned from addTask() and transferred to SharedFuture will return a valid pointer from task_if(). * * @returns A pointer to a TaskContext if this SharedFuture was created from addTask() or related functions; * `nullptr` otherwise. The pointer is valid as long as the SharedFuture exists and the response from valid() would * be consistent. */ const TaskContext* task_if() const; /** * Syntactic sugar around ITasking::addSubTask() that automatically passes the value from get() into `Callable`. * Unlike Future::then(), the SharedFuture is not reset to an invalid state. * * @note This can be used to "chain" tasks together. * * @warning If the dependent task is canceled then the sub-task will call `std::terminate()`. When canceling the * dependent task you must first cancel the sub-task. * * @param prio The priority of the task to execute. * @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a * temporary object. The Tracker objects can be used to determine task completion or to provide input/output * parameters to the task system. * @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value. * The Callable object must take `const T&` as its last parameter. * @param args Arguments to pass to @p f * @return A Future based on the return type of @p f */ template <class Callable, class... Args> auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args); private: detail::SharedState<T>* m_state{ nullptr }; }; #ifndef DOXYGEN_BUILD template <class T> class SharedFuture<T&> { public: constexpr SharedFuture() noexcept = default; SharedFuture(const SharedFuture& other) noexcept; SharedFuture(SharedFuture&& other) noexcept; SharedFuture(Future<T&>&& fut) noexcept; ~SharedFuture(); SharedFuture& operator=(const SharedFuture& other); SharedFuture& operator=(SharedFuture&& other) noexcept; T& get() const; bool valid() const noexcept; bool try_wait() const; void wait() const; template <class Rep, class Period> bool wait_for(const std::chrono::duration<Rep, Period>& dur) const; template <class Clock, class Duration> bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const; bool isCanceled() const; operator RequiredObject() const; const TaskContext* task_if() const; template <class Callable, class... Args> auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args); private: detail::SharedState<T&>* m_state{ nullptr }; }; template <> class SharedFuture<void> { public: constexpr SharedFuture() noexcept = default; SharedFuture(const SharedFuture<void>& other) noexcept; SharedFuture(SharedFuture<void>&& other) noexcept; SharedFuture(Future<void>&& fut) noexcept; ~SharedFuture(); SharedFuture<void>& operator=(const SharedFuture<void>& other); SharedFuture<void>& operator=(SharedFuture<void>&& other) noexcept; void get() const; bool valid() const noexcept; bool try_wait() const; void wait() const; template <class Rep, class Period> bool wait_for(const std::chrono::duration<Rep, Period>& dur) const; template <class Clock, class Duration> bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const; operator RequiredObject() const; const TaskContext* task_if() const; template <class Callable, class... Args> auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args); private: friend struct Tracker; TaskContext* ptask(); detail::SharedState<void>* state() const; Object m_obj{ ObjectType::eNone, nullptr }; }; #endif /** * A facility to store a value that is later acquired asynchronously via a Future created via Promise::get_future(). * * The carb.tasking implementation is very similar to the C++11 <a * href="https://en.cppreference.com/w/cpp/thread/promise">std::promise</a>. * * A promise has a "shared state" that is shared with the Future that it creates through Promise::get_future(). * * A promise is a single-use object. The get_future() function may only be called once, and either set_value() or * setCanceled() may only be called once. * * A promise that is destroyed without ever having called set_value() or setCanceled() is consider a broken promise and * automatically calls setCanceled(). * * There are three specializations of Promise: * * Promise<T>: The base specialization, used to communicate objects between tasks/threads. * * Promise<T&>: Reference specialization, used to communicate references between tasks/threads. * * Promise<void>: Void specialization, used to communicate stateless events between tasks/threads. * * The `void` specialization of Promise is slightly different: * * Promise<void> does not have Promise::setCanceled(); cancellation state cannot be determined. */ template <class T = void> class Promise { CARB_PREVENT_COPY(Promise); public: /** * Default constructor. * * Initializes the shared state. */ Promise(); /** * Can be move-constructed. */ Promise(Promise&& other) noexcept; /** * Destructor. * * If the shared state has not yet received a value with set_value(), then it is canceled and made Ready similarly * to setCanceled(). */ ~Promise(); /** * Can be move-assigned. */ Promise& operator=(Promise&& other) noexcept; /** * Swaps the shared state with @p other's. * * @param other A Promise to swap shared states with. */ void swap(Promise& other) noexcept; /** * Atomically retrieves and clears the Future from this Promise that shares the same state. * * A Future::wait() call will wait until the shared state becomes Ready. * * @warning `std::terminate()` will be called if this function is called more than once. * * @returns A Future with the same shared state as this Promise. */ Future<T> get_future(); /** * Atomically stores the value in the shared state and makes the state Ready. * * @warning Only one call of set_value() or setCanceled() is allowed. Subsequent calls will result in a call to * `std::terminate()`. * * @param value The value to atomically set into the shared state. */ void set_value(const T& value); /** * Atomically stores the value in the shared state and makes the state Ready. * * @warning Only one call of set_value() or setCanceled() is allowed. Subsequent calls will result in a call to * `std::terminate()`. * * @param value The value to atomically set into the shared state. */ void set_value(T&& value); /** * Atomically sets the shared state to canceled and makes the state Ready. This is a broken promise. * * @warning Calling Future::get() will result in a call to `std::terminate()`; Future::isCanceled() will return * `true`. */ void setCanceled(); private: using State = detail::SharedState<T>; State* m_state{ nullptr }; }; #ifndef DOXYGEN_BUILD template <class T> class Promise<T&> { CARB_PREVENT_COPY(Promise); public: Promise(); Promise(Promise&& other) noexcept; ~Promise(); Promise& operator=(Promise&& other) noexcept; void swap(Promise& other) noexcept; Future<T&> get_future(); void set_value(T& value); void setCanceled(); private: using State = detail::SharedState<T&>; State* m_state{ nullptr }; }; template <> class Promise<void> { CARB_PREVENT_COPY(Promise); public: Promise(); Promise(Promise&& other) noexcept; ~Promise(); Promise& operator=(Promise&& other) noexcept; void swap(Promise& other) noexcept; Future<void> get_future(); void set_value(); private: using State = detail::SharedState<void>; State* m_state{ nullptr }; }; #endif } // namespace tasking } // namespace carb
38,072
C
35.643888
120
0.6862
omniverse-code/kit/include/carb/tasking/TaskingHelpers.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 carb.tasking helper functions #pragma once #include "TaskingTypes.h" #include "../thread/Futex.h" #include "../cpp/Functional.h" #include "../cpp/Optional.h" #include "../cpp/Variant.h" #include "../Memory.h" #include <atomic> #include <chrono> #include <iterator> #include <vector> namespace carb { namespace tasking { #ifndef DOXYGEN_BUILD namespace detail { template <class T> struct CarbDeleter { void operator()(T* p) noexcept { p->~T(); carb::deallocate(p); } }; template <class T, class U = std::remove_cv_t<T>> inline void carbDelete(T* p) noexcept { if (p) { p->~T(); carb::deallocate(const_cast<U*>(p)); } } template <class T> struct is_literal_string { constexpr static bool value = false; }; template <size_t N> struct is_literal_string<const char (&)[N]> { constexpr static bool value = true; }; Counter* const kListOfCounters{ (Counter*)(size_t)-1 }; template <class Rep, class Period> uint64_t convertDuration(const std::chrono::duration<Rep, Period>& dur) { auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(thread::detail::clampDuration(dur)).count(); return uint64_t(::carb_max(std::chrono::nanoseconds::rep(0), ns)); } template <class Clock, class Duration> uint64_t convertAbsTime(const std::chrono::time_point<Clock, Duration>& tp) { return convertDuration(tp - Clock::now()); } template <class F, class Tuple, size_t... I, class... Args> decltype(auto) applyExtraImpl(F&& f, Tuple&& t, std::index_sequence<I...>, Args&&... args) { CARB_UNUSED(t); // Can get C4100: unreferenced formal parameter on MSVC when Tuple is empty. return cpp::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))..., std::forward<Args>(args)...); } template <class F, class Tuple, class... Args> decltype(auto) applyExtra(F&& f, Tuple&& t, Args&&... args) { return applyExtraImpl(std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size<std::remove_reference_t<Tuple>>::value>{}, std::forward<Args>(args)...); } // U looks like an iterator convertible to V when dereferenced template <class U, class V> using IsForwardIter = carb::cpp::conjunction< carb::cpp::negation< typename std::is_convertible<typename std::iterator_traits<U>::iterator_category, std::random_access_iterator_tag>>, typename std::is_convertible<typename std::iterator_traits<U>::iterator_category, std::forward_iterator_tag>, std::is_convertible<decltype(*std::declval<U&>()), V>>; template <class U, class V> using IsRandomAccessIter = carb::cpp::conjunction< typename std::is_convertible<typename std::iterator_traits<U>::iterator_category, std::random_access_iterator_tag>, std::is_convertible<decltype(*std::declval<U&>()), V>>; // Must fit within a pointer, be trivially move constructible and trivially destructible. template <class Functor> using FitsWithinPointerTrivially = carb::cpp::conjunction<carb::cpp::bool_constant<sizeof(typename std::decay_t<Functor>) <= sizeof(void*)>, std::is_trivially_move_constructible<typename std::decay_t<Functor>>, std::is_trivially_destructible<typename std::decay_t<Functor>>>; template <class Functor, std::enable_if_t<FitsWithinPointerTrivially<Functor>::value, bool> = false> inline void generateTaskFunc(TaskDesc& desc, Functor&& func) { // Use SFINAE to have this version of generateTaskFunc() contribute to resolution only if Functor will fit within a // void*, so that we can use the taskArg as the instance. On my machine, this is about a tenth of the time for the // below specialization, and happens more frequently. using Func = typename std::decay_t<Functor>; union { Func f; void* v; } u{ std::forward<Functor>(func) }; desc.taskArg = u.v; desc.task = [](void* arg) { union CARB_ATTRIBUTE(visibility("hidden")) { void* v; Func f; } u{ arg }; u.f(); }; // Func is trivially destructible so we don't need a cancel func } template <class Functor, std::enable_if_t<!FitsWithinPointerTrivially<Functor>::value, bool> = false> inline void generateTaskFunc(TaskDesc& desc, Functor&& func) { // Use SFINAE to have this version of generateTaskFunc() contribute to resolution only if Functor will NOT fit // within a void*, so that the heap can be used only if necessary using Func = typename std::decay_t<Functor>; // Need to allocate desc.taskArg = new (carb::allocate(sizeof(Func))) Func(std::forward<Functor>(func)); desc.task = [](void* arg) { std::unique_ptr<Func, detail::CarbDeleter<Func>> p(static_cast<Func*>(arg)); (*p)(); }; desc.cancel = [](void* arg) { detail::carbDelete(static_cast<Func*>(arg)); }; } template <class T> class SharedState; template <> class SharedState<void> { std::atomic_size_t m_refs; public: SharedState(bool futureRetrieved) noexcept : m_refs(1 + futureRetrieved), m_futureRetrieved(futureRetrieved) { } virtual ~SharedState() = default; void addRef() noexcept { m_refs.fetch_add(1, std::memory_order_relaxed); } void release() { if (m_refs.fetch_sub(1, std::memory_order_release) == 1) { std::atomic_thread_fence(std::memory_order_acquire); detail::carbDelete(this); } } void set() { CARB_FATAL_UNLESS(m_futex.exchange(isTask() ? eTaskPending : eReady, std::memory_order_acq_rel) == eUnset, "Value already set"); } void get() { } void notify(); void markReady() { m_futex.store(eReady, std::memory_order_release); } bool ready() const { return m_futex.load(std::memory_order_relaxed) == eReady; } bool isTask() const { return m_object.type == ObjectType::eTaskContext; } enum State : uint8_t { eReady = 0, eUnset, eInProgress, eTaskPending, }; std::atomic<State> m_futex{ eUnset }; std::atomic_bool m_futureRetrieved{ false }; Object m_object{ ObjectType::eFutex1, &m_futex }; }; template <class T> class SharedState<T&> final : public SharedState<void> { public: SharedState(bool futureRetrieved) noexcept : SharedState<void>(futureRetrieved) { } bool isSet() const noexcept { return m_value != nullptr; } T& get() const { CARB_FATAL_UNLESS(m_value, "Attempting to retrieve value from broken promise"); return *m_value; } void set(T& val) { CARB_FATAL_UNLESS(m_futex.exchange(eInProgress, std::memory_order_acquire) == 1, "Value already set"); m_value = std::addressof(val); m_futex.store(this->isTask() ? eTaskPending : eReady, std::memory_order_release); } T* m_value{ nullptr }; }; template <class T> class SharedState final : public SharedState<void> { public: using Type = typename std::decay<T>::type; SharedState(bool futureRetrieved) noexcept : SharedState<void>(futureRetrieved) { } bool isSet() const noexcept { return m_type.has_value(); } const T& get_ref() const { CARB_FATAL_UNLESS(m_type, "Attempting to retrieve value from broken promise"); return m_type.value(); } T get() { CARB_FATAL_UNLESS(m_type, "Attempting to retrieve value from broken promise"); return std::move(m_type.value()); } void set(const T& value) { CARB_FATAL_UNLESS(m_futex.exchange(eInProgress, std::memory_order_acquire) == 1, "Value already set"); m_type.emplace(value); m_futex.store(this->isTask() ? eTaskPending : eReady, std::memory_order_release); } void set(T&& value) { CARB_FATAL_UNLESS(m_futex.exchange(eInProgress, std::memory_order_acquire) == 1, "Value already set"); m_type.emplace(std::move(value)); m_futex.store(this->isTask() ? eTaskPending : eReady, std::memory_order_release); } carb::cpp::optional<Type> m_type; }; } // namespace detail #endif class TaskGroup; /** * Helper class to ensure correct compliance with the requiredObject parameter of ITasking::add[Throttled]SubTask() and * wait() functions. * * The following may be converted into a RequiredObject: TaskContext, Future, Any, All, Counter*, or CounterWrapper. */ struct RequiredObject final : public Object { /** * Constructor that accepts a `std::nullptr_t`. */ constexpr RequiredObject(std::nullptr_t) : Object{ ObjectType::eNone, nullptr } { } /** * Constructor that accepts an object that can be converted to Counter*. * * @param c An object convertible to Counter*. This can be Any, All, Counter* or CounterWrapper. */ template <class T, std::enable_if_t<std::is_convertible<T, Counter*>::value, bool> = false> constexpr RequiredObject(T&& c) : Object{ ObjectType::eCounter, static_cast<Counter*>(c) } { } /** * Constructor that accepts an object that can be converted to TaskContext. * * @param tc A TaskContext or object convertible to TaskContext, such as a Future. */ template <class T, std::enable_if_t<std::is_convertible<T, TaskContext>::value, bool> = true> constexpr RequiredObject(T&& tc) : Object{ ObjectType::eTaskContext, reinterpret_cast<void*>(static_cast<TaskContext>(tc)) } { } /** * Constructor that accepts a TaskGroup&. */ constexpr RequiredObject(const TaskGroup& tg); /** * Constructor that accepts a TaskGroup*. `nullptr` may be provided. */ constexpr RequiredObject(const TaskGroup* tg); private: friend struct ITasking; template <class U> friend class Future; template <class U> friend class SharedFuture; constexpr RequiredObject(const Object& o) : Object(o) { } void get(TaskDesc& desc); }; /** * Specifies an "all" grouping of RequiredObject(s). * * @note *ALL* RequiredObject(s) given in the constructor must become signaled before the All object will be considered * signaled. * * All and Any objects can be nested as they are convertible to RequiredObject. */ struct All final { /** * Constructor that accepts an initializer_list of RequiredObject(s). * @param il The `initializer_list` of RequiredObject(s). */ All(std::initializer_list<RequiredObject> il); /** * Constructor that accepts begin and end iterators that produce RequiredObject objects. * @param begin The beginning iterator. * @param end An off-the-end iterator just beyond the end of the list. */ template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool> = false> All(InputIt begin, InputIt end); //! @private template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool> = false> All(InputIt begin, InputIt end); /** * Convertible to RequiredObject. */ operator RequiredObject() const { return RequiredObject(m_counter); } private: friend struct RequiredObject; Counter* m_counter; operator Counter*() const { return m_counter; } }; /** * Specifies an "any" grouping of RequiredObject(s). * * @note *ANY* RequiredObject given in the constructor that is or becomes signaled will cause the Any object to become * signaled. * * All and Any objects can be nested as they are convertible to RequiredObject. */ struct Any final { /** * Constructor that accepts an initializer_list of RequiredObject objects. * @param il The initializer_list of RequiredObject objects. */ Any(std::initializer_list<RequiredObject> il); /** * Constructor that accepts begin and end iterators that produce RequiredObject objects. * @param begin The beginning iterator. * @param end An off-the-end iterator just beyond the end of the list. */ template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool> = false> Any(InputIt begin, InputIt end); //! @private template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool> = false> Any(InputIt begin, InputIt end); /** * Convertible to RequiredObject. */ operator RequiredObject() const { return RequiredObject(m_counter); } private: friend struct RequiredObject; Counter* m_counter; operator Counter*() const { return m_counter; } }; /** * Helper class to provide correct types to the Trackers class. * * The following types are valid trackers: * - Anything convertible to Counter*, such as CounterWrapper. Counters are deprecated however. The Counter is * incremented before the task can possibly begin executing and decremented when the task finishes. * - Future<void>&: This can be used to atomically populate a Future<void> before the task could possibly start * executing. * - Future<void>*: Can be `nullptr`, but if not, can be used to atomically populate a Future<void> before the task * could possibly start executing. * - TaskContext&: By providing a reference to a TaskContext it will be atomically filled before the task could possibly * begin executing. * - TaskContext*: By providing a pointer to a TaskContext (that can be `nullptr`), it will be atomically filled before * the task could possibly begin executing, if valid. */ struct Tracker final : Object { /** * Constructor that accepts a `std::nullptr_t`. */ constexpr Tracker(std::nullptr_t) : Object{ ObjectType::eNone, nullptr } { } /** * Constructor that accepts a Counter* or an object convertible to Counter*, such as CounterWrapper. * * @param c The object convertible to Counter*. */ template <class T, std::enable_if_t<std::is_convertible<T, Counter*>::value, bool> = false> constexpr Tracker(T&& c) : Object{ ObjectType::eCounter, reinterpret_cast<void*>(static_cast<Counter*>(c)) } { } /** * Constructor that accepts a task name. * * @note This is not a Tracker per se; this is syntactic sugar to name a task as it is created. * @tparam T A type that is convertible to `const char*`. * @param name Either a `const char*` (dynamic string) or a `const char (&)[N]` (literal string) as the string name * for a task. * @see ITasking::nameTask() */ template <class T, std::enable_if_t<std::is_convertible<T, const char*>::value, bool> = false> constexpr Tracker(T&& name) : Object{ detail::is_literal_string<T>::value ? ObjectType::eTaskNameLiteral : ObjectType::eTaskName, const_cast<void*>(reinterpret_cast<const void*>(name)) } { } /** * Constructor that accepts a Future<void>&. The Future will be initialized before the task can begin. */ Tracker(Future<>& fut) : Object{ ObjectType::ePtrTaskContext, fut.ptask() } { } /** * Constructor that accepts a Future<void>*. The Future<void> will be initialized before the task can begin. * The Future<void> pointer can be `nullptr`. */ Tracker(Future<>* fut) : Object{ ObjectType::ePtrTaskContext, fut ? fut->ptask() : nullptr } { } /** * Constructor that accepts a SharedFuture<void>&. The SharedFuture will be initialized before the task can begin. */ Tracker(SharedFuture<>& fut) : Object{ ObjectType::ePtrTaskContext, fut.ptask() } { } /** * Constructor that accepts a SharedFuture<void>*. The SharedFuture<void> will be initialized before the task can * begin. The SharedFuture<void> pointer can be `nullptr`. */ Tracker(SharedFuture<>* fut) : Object{ ObjectType::ePtrTaskContext, fut ? fut->ptask() : nullptr } { } /** * Constructor that accepts a TaskContext&. The value will be atomically written before the task can begin. */ constexpr Tracker(TaskContext& ctx) : Object{ ObjectType::ePtrTaskContext, &ctx } { } /** * Constructor that accepts a TaskContext*. The value will be atomically written before the task can begin. * The TaskContext* can be `nullptr`. */ constexpr Tracker(TaskContext* ctx) : Object{ ObjectType::ePtrTaskContext, ctx } { } /** * Constructor that accepts a TaskGroup&. The TaskGroup will be entered immediately and left when the task finishes. * The TaskGroup must exist until the task completes. */ Tracker(TaskGroup& grp); /** * Constructor that accepts a TaskGroup*. The TaskGroup will be entered immediately and left when the task finishes. * The TaskGroup* can be `nullptr` in which case nothing happens. The TaskGroup must exist until the task completes. */ Tracker(TaskGroup* grp); private: friend struct Trackers; }; /** * Helper class to ensure correct compliance with trackers parameter of ITasking::addTask() variants */ struct Trackers final { /** * Default constructor. */ constexpr Trackers() : m_variant{} { } /** * Constructor that accepts a single Tracker. * * @param t The type passed to the Tracker constructor. */ template <class T, std::enable_if_t<std::is_constructible<Tracker, T>::value, bool> = false> constexpr Trackers(T&& t) : m_variant(Tracker(t)) { } /** * Constructor that accepts an initializer_list of Tracker objects. * * @param il The `std::initializer_list` of Tracker objects. */ constexpr Trackers(std::initializer_list<Tracker> il) { switch (il.size()) { case 0: break; case 1: m_variant.emplace<Tracker>(*il.begin()); break; default: m_variant.emplace<std::vector<Tracker>>(std::move(il)); } } /** * Constructor that accepts an initializer_list of Tracker objects and additional Tracker objects. * * @param il The `std::initializer_list` of Tracker objects. * @param p A pointer to additional Tracker objects; size specified by @p count. * @param count The number of additional Tracker objects in the list specified by @p p. */ Trackers(std::initializer_list<Tracker> il, Tracker const* p, size_t count) : m_variant(carb::cpp::in_place_index<2>) { switch (il.size() + count) { case 0: break; case 1: m_variant.emplace<Tracker>(il.size() == 0 ? *p : *il.begin()); break; default: { auto& vec = m_variant.emplace<std::vector<Tracker>>(); vec.reserve(il.size() + count); vec.insert(vec.end(), il.begin(), il.end()); vec.insert(vec.end(), p, p + count); } } } /** * Retrieves a list of Tracker objects managed by this helper object. * * @param trackers Receives a pointer to a list of Tracker objects. * @param count Receives the count of Tracker objects. */ void output(Tracker const*& trackers, size_t& count) const { static_assert(sizeof(Object) == sizeof(Tracker), ""); fill(reinterpret_cast<Object const*&>(trackers), count); } CARB_PREVENT_COPY(Trackers); /** * Trackers is move-constructible. */ Trackers(Trackers&&) = default; /** * Trackers is move-assignable. */ Trackers& operator=(Trackers&&) = default; private: friend struct ITasking; using TrackerVec = std::vector<Tracker>; using Variant = carb::cpp::variant<carb::cpp::monostate, Tracker, TrackerVec>; Variant m_variant; Counter* fill(carb::tasking::Object const*& trackers, size_t& count) const { if (m_variant.index() == 0) { trackers = nullptr; count = 0; return nullptr; } if (auto* vec = carb::cpp::get_if<TrackerVec>(&m_variant)) { trackers = vec->data(); count = vec->size(); } else { const Tracker& t = carb::cpp::get<Tracker>(m_variant); trackers = &t; count = 1; } return detail::kListOfCounters; } }; //! A macro that can be used to mark a function as async, that is, it always executes in the context of a task. //! //! Generally the body of the function has one of @ref CARB_ASSERT_ASYNC, @ref CARB_CHECK_ASYNC, or //! @ref CARB_FATAL_UNLESS_ASYNC. //! //! @code{.cpp} //! void CARB_ASYNC Context::loadTask(); //! @endcode #define CARB_ASYNC //! A macro that can be used to mark a function as possibly async, that is, it may execute in the context of a task. //! @code{.cpp} //! void CARB_MAYBE_ASYNC Context::loadTask(); //! @endcode #define CARB_MAYBE_ASYNC //! Helper macro that results in a boolean expression which is `true` if the current thread is running in task context. #define CARB_IS_ASYNC \ (::carb::getCachedInterface<carb::tasking::ITasking>()->getTaskContext() != ::carb::tasking::kInvalidTaskContext) //! A macro that is used to assert that a scope is running in task context in debug builds only. #define CARB_ASSERT_ASYNC CARB_ASSERT(CARB_IS_ASYNC) //! A macro that is used to assert that a scope is running in task context in debug and checked builds. #define CARB_CHECK_ASYNC CARB_CHECK(CARB_IS_ASYNC) //! A macro that is used to assert that a scope is running in task context. #define CARB_FATAL_UNLESS_ASYNC CARB_FATAL_UNLESS(CARB_IS_ASYNC, "Not running in task context!") } // namespace tasking } // namespace carb
22,528
C
30.597475
124
0.640137
omniverse-code/kit/include/carb/tasking/IFiberEvents.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 IFiberEvents definition file. #pragma once #include "../Framework.h" #include "../Interface.h" namespace carb { namespace tasking { /** * Defines the fiber events interface that receives fiber-related notifications. * * This is a \a reverse interface. It is not implemented by *carb.tasking.plugin*. Instead, *carb.tasking.plugin* looks * for all instances of this interface and will call the functions to inform other plugins of fiber events. This can be * used, for example, by a profiler that wants to keep track of which fiber is running on a thread. * * Once \ref IFiberEvents::notifyFiberStart() has been called, this is a signal to the receiver that a task is executing * on the current thread, and will be executing on the current thread until \ref IFiberEvents::notifyFiberStop() is * called on the same thread. Between these two calls, the thread is executing in *Task context*, that is, within a task * submitted to *carb.tasking.plugin*. As such, it is possible to query information about the task, such as the context * handle ( \ref ITasking::getTaskContext()) or access task-local storage ( \ref ITasking::getTaskStorage() / * \ref ITasking::setTaskStorage()). However, **anything that could cause a task to yield is strictly prohibited** * in these functions and will produce undefined behavior. This includes but is not limited to yielding, waiting on any * task-aware synchronization primitive (i.e. locking a \ref Mutex), sleeping in a task-aware manner, suspending a task, * etc. * * @warning *carb.tasking.plugin* queries for all IFiberEvents interfaces only during startup, during * @ref ITasking::changeParameters() and @ref ITasking::reloadFiberEvents(). If a plugin is loaded which exports * \c IFiberEvents then you **must** perform one of these methods to receive notifications about fiber events. * * @warning **DO NOT EVER** call the functions; only *carb.tasking.plugin* should be calling these functions. Receiving * one of these function calls implies that *carb.tasking.plugin* is loaded, and these function calls can be coordinated * with certain *carb.tasking.plugin* actions (reading task-specific data, for instance). * * @note Notification functions are called in the context of the thread which caused the fiber event. */ struct IFiberEvents { CARB_PLUGIN_INTERFACE("carb::tasking::IFiberEvents", 1, 0) /** * Specifies that a fiber started or resumed execution on the calling thread. * * Specifies that the calling thread is now running fiber with ID @p fiberId until notifyFiberStop() is called on * the same thread. * * @note A thread switching fibers will always call notifyFiberStop() before calling notifyFiberStart() with the new * fiber ID. * * @param fiberId A unique identifier for a fiber. */ void(CARB_ABI* notifyFiberStart)(const uint64_t fiberId); /** * Specifies that a fiber yielded execution on the calling thread. It may or may not restart again at some later * point, on the same thread or a different one. * * Specifies that the calling thread has yielded fiber with ID @p fiberId and is now running its own context. * * @param fiberId A unique identifier for a fiber. */ void(CARB_ABI* notifyFiberStop)(const uint64_t fiberId); }; } // namespace tasking } // namespace carb
3,835
C
48.179487
120
0.739505
omniverse-code/kit/include/carb/tasking/TaskingUtils.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.tasking utilities. #pragma once #include "ITasking.h" #include "../thread/Util.h" #include <atomic> #include <condition_variable> // for std::cv_status #include <functional> namespace carb { namespace tasking { class RecursiveSharedMutex; /** * This atomic spin lock conforms to C++ Named Requirements of <a * href="https://en.cppreference.com/w/cpp/named_req/Lockable">Lockable</a> which makes it compatible with * std::lock_guard. */ struct SpinMutex { public: /** * Constructs the SpinMutex. */ constexpr SpinMutex() noexcept = default; CARB_PREVENT_COPY_AND_MOVE(SpinMutex); /** * Spins until the lock is acquired. * * See § 30.4.1.2.1 in the C++11 standard. */ void lock() noexcept { this_thread::spinWaitWithBackoff([&] { return try_lock(); }); } /** * Attempts to acquire the lock, on try, returns true if the lock was acquired. */ bool try_lock() noexcept { return (!mtx.load(std::memory_order_relaxed) && !mtx.exchange(true, std::memory_order_acquire)); } /** * Unlocks, wait-free. * * See § 30.4.1.2.1 in the C++11 standard. */ void unlock() noexcept { mtx.store(false, std::memory_order_release); } private: std::atomic_bool mtx{}; }; /** * Spin lock conforming to C++ named requirements of <a * href="https://en.cppreference.com/w/cpp/named_req/SharedMutex">SharedMutex</a>. * * @warning This implementation is non-recursive. */ struct SpinSharedMutex { public: /** * Constructor. */ constexpr SpinSharedMutex() = default; CARB_PREVENT_COPY_AND_MOVE(SpinSharedMutex); /** * Spins until the shared mutex is exclusive-locked * * @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. */ void lock() { while (!try_lock()) { CARB_HARDWARE_PAUSE(); } } /** * Attempts to exclusive-lock the shared mutex immediately without spinning. * * @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * @returns true if the mutex was exclusive-locked; false if no exclusive lock could be obtained. */ bool try_lock() { int expected = 0; return counter.compare_exchange_strong(expected, -1, std::memory_order_acquire, std::memory_order_relaxed); } /** * Unlocks the mutex previously exclusive-locked by this thread/task. * * @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task. */ void unlock() { CARB_ASSERT(counter == -1); counter.store(0, std::memory_order_release); } /** * Attempts to shared-lock the shared mutex immediately without spinning. * * @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * @returns true if the mutex was shared-locked; false if no shared lock could be obtained. */ bool try_lock_shared() { auto ctr = counter.load(std::memory_order_relaxed); if (ctr >= 0) { return counter.compare_exchange_strong(ctr, ctr + 1, std::memory_order_acquire, std::memory_order_relaxed); } return false; } /** * Spins until the shared mutex is shared-locked * * @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. */ void lock_shared() { auto ctr = counter.load(std::memory_order_relaxed); for (;;) { if (ctr < 0) { CARB_HARDWARE_PAUSE(); ctr = counter.load(std::memory_order_relaxed); } else if (counter.compare_exchange_strong(ctr, ctr + 1, std::memory_order_acquire, std::memory_order_relaxed)) { return; } } } /** * Unlocks the mutex previously shared-locked by this thread/task. * * @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task. */ void unlock_shared() { int ctr = counter.fetch_sub(1, std::memory_order_release); CARB_ASSERT(ctr > 0); CARB_UNUSED(ctr); } private: // 0 - unlocked // > 0 - Shared lock count // -1 - Exclusive lock std::atomic<int> counter{ 0 }; }; /** * Wrapper for a carb::tasking::Counter */ class CounterWrapper { public: /** * Constructs a new CounterWrapper. * * @param target An optional (default:0) target value for the Counter to become signaled. */ CounterWrapper(uint32_t target = 0) : m_counter(carb::getCachedInterface<ITasking>()->createCounterWithTarget(target)) { } /** * Constructs a new CounterWrapper. * * @note Deprecated: The ITasking* parameter is no longer needed in this call. * @param tasking The acquired ITasking interface. * @param target An optional (default:0) target value for the Counter to become signaled. */ CARB_DEPRECATED("ITasking no longer needed.") CounterWrapper(ITasking* tasking, uint32_t target = 0) : m_counter(carb::getCachedInterface<ITasking>()->createCounterWithTarget(target)) { CARB_UNUSED(tasking); } /** * Destrutor * * @warning Destroying a Counter that is not signaled will assert in debug builds. */ ~CounterWrapper() { carb::getCachedInterface<ITasking>()->destroyCounter(m_counter); } /** * @returns true if the Counter is signaled; false otherwise */ CARB_DEPRECATED("The Counter interface is deprecated.") bool check() const { return try_wait(); } /** * @returns true if the Counter is signaled; false otherwise */ bool try_wait() const { return carb::getCachedInterface<ITasking>()->try_wait(m_counter); } /** * Blocks the current thread or task in a fiber-safe way until the Counter becomes signaled. */ void wait() const { carb::getCachedInterface<ITasking>()->wait(m_counter); } /** * Blocks the current thread or task in a fiber-safe way until the Counter becomes signaled or a period of time has * elapsed. * * @param dur The amount of time to wait for. * @returns true if the Counter is signaled; false if the time period elapsed. */ template <class Rep, class Period> bool wait_for(const std::chrono::duration<Rep, Period>& dur) const { return carb::getCachedInterface<ITasking>()->wait_for(dur, m_counter); } /** * Blocks the current thread or task in a fiber-safe way until the Counter becomes signaled or the clock reaches the * given time point. * * @param tp The time point to wait until. * @returns true if the Counter is signaled; false if the clock time is reached. */ template <class Clock, class Duration> bool wait_until(const std::chrono::time_point<Clock, Duration>& tp) const { return carb::getCachedInterface<ITasking>()->wait_until(tp, m_counter); } /** * Convertible to Counter*. */ operator Counter*() const { return m_counter; } /** * Returns the acquired ITasking interface that was used to construct this object. * @note Deprecated: Use carb::getCachedInterface instead. */ CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const { return carb::getCachedInterface<ITasking>(); } CARB_PREVENT_COPY_AND_MOVE(CounterWrapper); private: Counter* m_counter; }; /** * TaskGroup is a small and fast counter for tasks. * * TaskGroup blocks when tasks have "entered" the TaskGroup. It becomes signaled when all tasks have left the TaskGroup. */ class TaskGroup { public: CARB_PREVENT_COPY_AND_MOVE(TaskGroup); /** * Constructs an empty TaskGroup. */ constexpr TaskGroup() = default; /** * TaskGroup destructor. * * @warning It is an error to destroy a TaskGroup that is not empty. Doing so can result in memory corruption. */ ~TaskGroup() { CARB_CHECK(empty(), "Destroying busy TaskGroup!"); } /** * Returns (with high probability) whether the TaskGroup is empty. * * As TaskGroup atomically tracks tasks, this function may return an incorrect value as another task may have * entered or left the TaskGroup before the return value could be processed. * * @returns `true` if there is high probability that the TaskGroup is empty (signaled); `false` otherwise. */ bool empty() const { // This cannot be memory_order_relaxed because it does not synchronize with anything and would allow the // compiler to cache the value or hoist it out of a loop. Acquire semantics will require synchronization with // all other locations that release m_count. return m_count.load(std::memory_order_acquire) == 0; } /** * "Enters" the TaskGroup. * * @warning Every call to this function must be paired with leave(). It is generally better to use with(). */ void enter() { m_count.fetch_add(1, std::memory_order_acquire); // synchronizes-with all other locations releasing m_count } /** * "Leaves" the TaskGroup. * * @warning Every call to this function must be paired with an earlier enter() call. It is generally better to use * with(). */ void leave() { size_t v = m_count.fetch_sub(1, std::memory_order_release); CARB_ASSERT(v, "Mismatched enter()/leave() calls"); if (v == 1) { carb::getCachedInterface<ITasking>()->futexWakeup(m_count, UINT_MAX); } } /** * Returns `true` if the TaskGroup is empty (signaled) with high probability. * * @returns `true` if there is high probability that the TaskGroup is empty (signaled); `false` otherwise. */ bool try_wait() const { return empty(); } /** * Blocks the calling thread or task until the TaskGroup becomes empty. */ void wait() const { size_t v = m_count.load(std::memory_order_acquire); // synchronizes-with all other locations releasing m_count if (v) { ITasking* tasking = carb::getCachedInterface<ITasking>(); while (v) { tasking->futexWait(m_count, v); v = m_count.load(std::memory_order_relaxed); } } } /** * Blocks the calling thread or task until the TaskGroup becomes empty or the given duration elapses. * * @param dur The duration to wait for. * @returns `true` if the TaskGroup has become empty; `false` if the duration elapses. */ template <class Rep, class Period> bool try_wait_for(std::chrono::duration<Rep, Period> dur) { return try_wait_until(std::chrono::steady_clock::now() + dur); } /** * Blocks the calling thread or task until the TaskGroup becomes empty or the given time is reached. * * @param when The time to wait until. * @returns `true` if the TaskGroup has become empty; `false` if the given time is reached. */ template <class Clock, class Duration> bool try_wait_until(std::chrono::time_point<Clock, Duration> when) { size_t v = m_count.load(std::memory_order_acquire); // synchronizes-with all other locations releasing m_count if (v) { ITasking* tasking = carb::getCachedInterface<ITasking>(); while (v) { if (!tasking->futexWaitUntil(m_count, v, when)) { return false; } v = m_count.load(std::memory_order_relaxed); } } return true; } /** * A helper function for entering the TaskGroup during a call to `invoke()` and leaving afterwards. * * @param args Arguments to pass to `carb::cpp::invoke`. The TaskGroup is entered (via \ref enter()) before the * invoke and left (via \ref leave()) when the invoke completes. * @returns the value returned by `carb::cpp::invoke`. */ template <class... Args> auto with(Args&&... args) { enter(); CARB_SCOPE_EXIT { leave(); }; return carb::cpp::invoke(std::forward<Args>(args)...); } private: friend struct Tracker; friend struct RequiredObject; std::atomic_size_t m_count{ 0 }; }; /** * Wrapper for a carb::tasking::Mutex that conforms to C++ Named Requirements of <a * href="https://en.cppreference.com/w/cpp/named_req/Lockable">Lockable</a>. * * Non-recursive. If a recursive mutex is desired, use RecursiveMutexWrapper. */ class MutexWrapper { public: /** * Constructs a new MutexWrapper object */ MutexWrapper() : m_mutex(carb::getCachedInterface<ITasking>()->createMutex()) { } /** * Constructs a new MutexWrapper object * @note Deprecated: ITasking no longer needed. */ CARB_DEPRECATED("ITasking no longer needed.") MutexWrapper(ITasking*) : m_mutex(carb::getCachedInterface<ITasking>()->createMutex()) { } /** * Destructor * * @warning It is an error to destroy a mutex that is locked. */ ~MutexWrapper() { carb::getCachedInterface<ITasking>()->destroyMutex(m_mutex); } /** * Attempts to lock the mutex immediately. * * @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired. * * @returns true if the mutex was locked; false otherwise */ bool try_lock() { return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, 0); } /** * Locks the mutex, waiting until it becomes available. * * @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired. */ void lock() { carb::getCachedInterface<ITasking>()->lockMutex(m_mutex); } /** * Unlocks a mutex previously acquired with try_lock() or lock() * * @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task. */ void unlock() { carb::getCachedInterface<ITasking>()->unlockMutex(m_mutex); } /** * Attempts to lock a mutex within a specified duration. * * @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired. * * @param duration The duration to wait for the mutex to be available * @returns true if the mutex was locked; false if the timeout period expired */ template <class Rep, class Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertDuration(duration)); } /** * Attempts to lock a mutex waiting until a specific clock time. * * @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired. * * @param time_point The clock time to wait until. * @returns true if the mutex was locked; false if the timeout period expired */ template <class Clock, class Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time_point) { return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertAbsTime(time_point)); } /** * Convertible to Mutex*. */ operator Mutex*() const { return m_mutex; } /** * Returns the acquired ITasking interface that was used to construct this object. * @note Deprecated: Use carb::getCachedInterface instead. */ CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const { return carb::getCachedInterface<ITasking>(); } CARB_PREVENT_COPY_AND_MOVE(MutexWrapper); private: Mutex* m_mutex; }; /** * Wrapper for a recursive carb::tasking::Mutex that conforms to C++ Named Requirements of <a * href="https://en.cppreference.com/w/cpp/named_req/Lockable">Lockable</a>. */ class RecursiveMutexWrapper { public: /** * Constructs a new RecursiveMutexWrapper object */ RecursiveMutexWrapper() : m_mutex(carb::getCachedInterface<ITasking>()->createRecursiveMutex()) { } /** * Constructs a new RecursiveMutexWrapper object * @note Deprecated: ITasking no longer needed. */ CARB_DEPRECATED("ITasking no longer needed.") RecursiveMutexWrapper(ITasking*) : m_mutex(carb::getCachedInterface<ITasking>()->createRecursiveMutex()) { } /** * Destructor * * @warning It is an error to destroy a mutex that is locked. */ ~RecursiveMutexWrapper() { carb::getCachedInterface<ITasking>()->destroyMutex(m_mutex); } /** * Attempts to lock the mutex immediately. * * @returns true if the mutex was locked or already owned by this thread/task; false otherwise. If true is returned, * unlock() must be called to release the lock. */ bool try_lock() { return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, 0); } /** * Locks the mutex, waiting until it becomes available. Call unlock() to release the lock. */ void lock() { carb::getCachedInterface<ITasking>()->lockMutex(m_mutex); } /** * Unlocks a mutex previously acquired with try_lock() or lock() * * @note The unlock() function must be called for each successful lock. * @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task. */ void unlock() { carb::getCachedInterface<ITasking>()->unlockMutex(m_mutex); } /** * Attempts to lock a mutex within a specified duration. * * @param duration The duration to wait for the mutex to be available * @returns true if the mutex was locked; false if the timeout period expired. If true is returned, unlock() must be * called to release the lock. */ template <class Rep, class Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertDuration(duration)); } /** * Attempts to lock a mutex waiting until a specific clock time. * * @param time_point The clock time to wait until. * @returns true if the mutex was locked; false if the timeout period expired. If true is returned, unlock() must be * called to release the lock. */ template <class Clock, class Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time_point) { return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertAbsTime(time_point)); } /** * Convertible to Mutex*. */ operator Mutex*() const { return m_mutex; } /** * Returns the acquired ITasking interface that was used to construct this object. * @note Deprecated: Use carb::getCachedInterface instead. */ CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const { return carb::getCachedInterface<ITasking>(); } CARB_PREVENT_COPY_AND_MOVE(RecursiveMutexWrapper); private: Mutex* m_mutex; }; /** * Wrapper for a carb::tasking::Semaphore * * @note SemaphoreWrapper can be used for @rstref{Throttling <tasking-throttling-label>} tasks. */ class SemaphoreWrapper { public: /** * Constructs a new SemaphoreWrapper object * * @param value The initial value of the semaphore (i.e. how many times acquire() can be called without blocking). */ SemaphoreWrapper(unsigned value) : m_sema(carb::getCachedInterface<ITasking>()->createSemaphore(value)) { } /** * Constructs a new SemaphoreWrapper object * * @note Deprecated: ITasking no longer needed. * @param value The initial value of the semaphore (i.e. how many times acquire() can be called without blocking). */ CARB_DEPRECATED("ITasking no longer needed.") SemaphoreWrapper(ITasking*, unsigned value) : m_sema(carb::getCachedInterface<ITasking>()->createSemaphore(value)) { } /** * Destructor */ ~SemaphoreWrapper() { carb::getCachedInterface<ITasking>()->destroySemaphore(m_sema); } /** * Increases the value of the semaphore, potentially unblocking any threads waiting in acquire(). * * @param count The value to add to the Semaphore's value. That is, the number of threads to either unblock while * waiting in acquire(), or to allow to call acquire() without blocking. */ void release(unsigned count = 1) { carb::getCachedInterface<ITasking>()->releaseSemaphore(m_sema, count); } /** * Reduce the value of the Semaphore by one, potentially blocking if the count is already zero. * * @note Threads that are blocked by acquire() must be released by other threads calling release(). */ void acquire() { carb::getCachedInterface<ITasking>()->waitSemaphore(m_sema); } /** * Attempts to reduce the value of the Semaphore by one. If the Semaphore's value is zero, false is returned. * * @returns true if the count of the Semaphore was reduced by one; false if the count is already zero. */ bool try_acquire() { return carb::getCachedInterface<ITasking>()->timedWaitSemaphore(m_sema, 0); } /** * Attempts to reduce the value of the Semaphore by one, waiting until the duration expires if the value is zero. * * @returns true if the count of the Semaphore was reduced by one; false if the duration expires. */ template <class Rep, class Period> bool try_acquire_for(const std::chrono::duration<Rep, Period>& dur) { return carb::getCachedInterface<ITasking>()->timedWaitSemaphore(m_sema, detail::convertDuration(dur)); } /** * Attempts to reduce the value of the Semaphore by one, waiting until the given time point is reached if the value * is zero. * * @returns true if the count of the Semaphore was reduced by one; false if the time point is reached by the clock. */ template <class Clock, class Duration> bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& tp) { return carb::getCachedInterface<ITasking>()->timedWaitSemaphore(m_sema, detail::convertAbsTime(tp)); } /** * Convertible to Semaphore*. */ operator Semaphore*() const { return m_sema; } /** * Returns the acquired ITasking interface that was used to construct this object. * @note Deprecated: Use carb::getCachedInterface instead. */ CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const { return carb::getCachedInterface<ITasking>(); } CARB_PREVENT_COPY_AND_MOVE(SemaphoreWrapper); private: Semaphore* m_sema; }; /** * Wrapper for a carb::tasking::SharedMutex that (mostly) conforms to C++ Named Requirements of SharedMutex. */ class SharedMutexWrapper { public: /** * Constructs a new SharedMutexWrapper object */ SharedMutexWrapper() : m_mutex(carb::getCachedInterface<ITasking>()->createSharedMutex()) { } /** * Constructs a new SharedMutexWrapper object * @note Deprecated: ITasking no longer needed. */ CARB_DEPRECATED("ITasking no longer needed.") SharedMutexWrapper(ITasking*) : m_mutex(carb::getCachedInterface<ITasking>()->createSharedMutex()) { } /** * Destructor * * @note It is an error to destroy a shared mutex that is locked. */ ~SharedMutexWrapper() { carb::getCachedInterface<ITasking>()->destroySharedMutex(m_mutex); } /** * Attempts to shared-lock the shared mutex immediately. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * * @returns true if the mutex was shared-locked; false otherwise */ bool try_lock_shared() { return carb::getCachedInterface<ITasking>()->timedLockSharedMutex(m_mutex, 0); } /** * Attempts to exclusive-lock the shared mutex immediately. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * * @returns true if the mutex was shared-locked; false otherwise */ bool try_lock() { return carb::getCachedInterface<ITasking>()->timedLockSharedMutexExclusive(m_mutex, 0); } /** * Attempts to exclusive-lock the shared mutex within a specified duration. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * * @param duration The duration to wait for the mutex to be available * @returns true if the mutex was exclusive-locked; false if the timeout period expired */ template <class Rep, class Period> bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) { return carb::getCachedInterface<ITasking>()->timedLockSharedMutexExclusive( m_mutex, detail::convertDuration(duration)); } /** * Attempts to shared-lock the shared mutex within a specified duration. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * * @param duration The duration to wait for the mutex to be available * @returns true if the mutex was shared-locked; false if the timeout period expired */ template <class Rep, class Period> bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration) { return carb::getCachedInterface<ITasking>()->timedLockSharedMutex(m_mutex, detail::convertDuration(duration)); } /** * Attempts to exclusive-lock the shared mutex until a specific clock time. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * * @param time_point The clock time to wait until. * @returns true if the mutex was exclusive-locked; false if the timeout period expired */ template <class Clock, class Duration> bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time_point) { return try_lock_for(time_point - Clock::now()); } /** * Attempts to shared-lock the shared mutex until a specific clock time. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. * * @param time_point The clock time to wait until. * @returns true if the mutex was shared-locked; false if the timeout period expired */ template <class Clock, class Duration> bool try_lock_shared_until(const std::chrono::time_point<Clock, Duration>& time_point) { return try_lock_shared_for(time_point - Clock::now()); } /** * Shared-locks the shared mutex, waiting until it becomes available. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. */ void lock_shared() { carb::getCachedInterface<ITasking>()->lockSharedMutex(m_mutex); } /** * Unlocks a mutex previously shared-locked by this thread/task. * * @note It is undefined behavior to unlock a mutex that is not owned by the current thread or task. */ void unlock_shared() { carb::getCachedInterface<ITasking>()->unlockSharedMutex(m_mutex); } /** * Exclusive-locks the shared mutex, waiting until it becomes available. * * @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa. */ void lock() { carb::getCachedInterface<ITasking>()->lockSharedMutexExclusive(m_mutex); } /** * Unlocks a mutex previously exclusive-locked by this thread/task. * * @note It is undefined behavior to unlock a mutex that is not owned by the current thread or task. */ void unlock() { carb::getCachedInterface<ITasking>()->unlockSharedMutex(m_mutex); } /** * Convertible to SharedMutex*. */ operator SharedMutex*() const { return m_mutex; } /** * Returns the acquired ITasking interface that was used to construct this object. * @note Deprecated: Use carb::getCachedInterface instead. */ CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const { return carb::getCachedInterface<ITasking>(); } CARB_PREVENT_COPY_AND_MOVE(SharedMutexWrapper); private: SharedMutex* m_mutex; }; /** * Wrapper for carb::tasking::ConditionVariable */ class ConditionVariableWrapper { public: /** * Constructs a new ConditionVariableWrapper object */ ConditionVariableWrapper() : m_cv(carb::getCachedInterface<ITasking>()->createConditionVariable()) { } /** * Constructs a new ConditionVariableWrapper object * @note Deprecated: ITasking no longer needed. */ CARB_DEPRECATED("ITasking no longer needed.") ConditionVariableWrapper(ITasking*) : m_cv(carb::getCachedInterface<ITasking>()->createConditionVariable()) { } /** * Destructor * * @note It is an error to destroy a condition variable that has waiting threads. */ ~ConditionVariableWrapper() { carb::getCachedInterface<ITasking>()->destroyConditionVariable(m_cv); } /** * Waits until the condition variable is notified. * * @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked * before returning to the caller. * * @param m The mutex to unlock while waiting for the condition variable to be notified. */ void wait(Mutex* m) { carb::getCachedInterface<ITasking>()->waitConditionVariable(m_cv, m); } /** * Waits until a predicate has been satisfied and the condition variable is notified. * * @note @p m must be locked when calling this function. The mutex will be locked when calling @p pred and when this * function returns, but unlocked while waiting. * * @param m The mutex to unlock while waiting for the condition variable to be notified. * @param pred A predicate that is called repeatedly. When it returns true, the function returns. If it returns * false, @p m is unlocked and the thread/task waits until the condition variable is notified. */ template <class Pred> void wait(Mutex* m, Pred&& pred) { carb::getCachedInterface<ITasking>()->waitConditionVariablePred(m_cv, m, std::forward<Pred>(pred)); } /** * Waits until the condition variable is notified or the specified duration expires. * * @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked * before returning to the caller. * * @param m The mutex to unlock while waiting for the condition variable to be notified. * @param duration The amount of time to wait for. * @returns `std::cv_status::no_timeout` if the condition variable was notified; `std::cv_status::timeout` if the * timeout period expired. */ template <class Rep, class Period> std::cv_status wait_for(Mutex* m, const std::chrono::duration<Rep, Period>& duration) { return carb::getCachedInterface<ITasking>()->timedWaitConditionVariable( m_cv, m, detail::convertDuration(duration)) ? std::cv_status::no_timeout : std::cv_status::timeout; } /** * Waits until a predicate is satisfied and the condition variable is notified, or the specified duration expires. * * @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked * before returning to the caller. * * @param m The mutex to unlock while waiting for the condition variable to be notified. * @param duration The amount of time to wait for. * @param pred A predicate that is called repeatedly. When it returns true, the function returns. If it returns * false, @p m is unlocked and the thread/task waits until the condition variable is notified. * @returns true if the predicate was satisfied; false if a timeout occurred. */ template <class Rep, class Period, class Pred> bool wait_for(Mutex* m, const std::chrono::duration<Rep, Period>& duration, Pred&& pred) { return carb::getCachedInterface<ITasking>()->timedWaitConditionVariablePred( m_cv, m, detail::convertDuration(duration), std::forward<Pred>(pred)); } /** * Waits until the condition variable is notified or the clock reaches the given time point. * * @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked * before returning to the caller. * * @param m The mutex to unlock while waiting for the condition variable to be notified. * @param time_point The clock time to wait until. * @returns `std::cv_status::no_timeout` if the condition variable was notified; `std::cv_status::timeout` if the * timeout period expired. */ template <class Clock, class Duration> std::cv_status wait_until(Mutex* m, const std::chrono::time_point<Clock, Duration>& time_point) { return carb::getCachedInterface<ITasking>()->timedWaitConditionVariable( m_cv, m, detail::convertAbsTime(time_point)) ? std::cv_status::no_timeout : std::cv_status::timeout; } /** * Waits until a predicate is satisfied and the condition variable is notified or the clock reaches the given time * point. * * @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked * before returning to the caller. * * @param m The mutex to unlock while waiting for the condition variable to be notified. * @param time_point The clock time to wait until. * @param pred A predicate that is called repeatedly. When it returns true, the function returns. If it returns * false, @p m is unlocked and the thread/task waits until the condition variable is notified. * @returns true if the predicate was satisfied; false if a timeout occurred. */ template <class Clock, class Duration, class Pred> bool wait_until(Mutex* m, const std::chrono::time_point<Clock, Duration>& time_point, Pred&& pred) { return carb::getCachedInterface<ITasking>()->timedWaitConditionVariablePred( m_cv, m, detail::convertAbsTime(time_point), std::forward<Pred>(pred)); } /** * Notifies one waiting thread/task to wake and check the predicate (if applicable). */ void notify_one() { carb::getCachedInterface<ITasking>()->notifyConditionVariableOne(m_cv); } /** * Notifies all waiting threads/tasks to wake and check the predicate (if applicable). */ void notify_all() { carb::getCachedInterface<ITasking>()->notifyConditionVariableAll(m_cv); } /** * Convertible to ConditionVariable*. */ operator ConditionVariable*() const { return m_cv; } /** * Returns the acquired ITasking interface that was used to construct this object. * @note Deprecated: Use carb::getCachedInterface instead. */ CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const { return carb::getCachedInterface<ITasking>(); } CARB_PREVENT_COPY_AND_MOVE(ConditionVariableWrapper); private: ConditionVariable* m_cv; }; /** * When instantiated, begins tracking the passed Trackers. At destruction, tracking on the given Trackers is ended. * * This is similar to the manner in which ITasking::addTask() accepts Trackers and begins tracking them prior to the * task starting, and then leaves them when the task finishes. This class allows performing the same tracking behavior * without the overhead of a task. */ class ScopedTracking { public: /** * Default constructor. */ ScopedTracking() : m_tracker{ ObjectType::eNone, nullptr } { } /** * Constructor that accepts a Trackers object. * @param trackers The Trackers to begin tracking. */ ScopedTracking(Trackers trackers); /** * Destructor. The Trackers provided to the constructor finish tracking when `this` is destroyed. */ ~ScopedTracking(); CARB_PREVENT_COPY(ScopedTracking); /** * Allows move-construct. */ ScopedTracking(ScopedTracking&& rhs); /** * Allows move-assign. */ ScopedTracking& operator=(ScopedTracking&& rhs) noexcept; private: Object m_tracker; }; inline constexpr RequiredObject::RequiredObject(const TaskGroup& tg) : Object{ ObjectType::eTaskGroup, const_cast<std::atomic_size_t*>(&tg.m_count) } { } inline constexpr RequiredObject::RequiredObject(const TaskGroup* tg) : Object{ ObjectType::eTaskGroup, tg ? const_cast<std::atomic_size_t*>(&tg->m_count) : nullptr } { } inline All::All(std::initializer_list<RequiredObject> il) { static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption"); m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAll, il.begin(), il.size()); } template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool>> inline All::All(InputIt begin, InputIt end) { static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption"); std::vector<RequiredObject> objects; for (; begin != end; ++begin) objects.push_back(*begin); m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAll, objects.data(), objects.size()); } template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool>> inline All::All(InputIt begin, InputIt end) { static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption"); size_t const count = end - begin; RequiredObject* objects = CARB_STACK_ALLOC(RequiredObject, count); size_t index = 0; for (; begin != end; ++begin) objects[index++] = *begin; CARB_ASSERT(index == count); m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAll, objects, count); } inline Any::Any(std::initializer_list<RequiredObject> il) { static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption"); m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAny, il.begin(), il.size()); } template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool>> inline Any::Any(InputIt begin, InputIt end) { static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption"); std::vector<RequiredObject> objects; for (; begin != end; ++begin) objects.push_back(*begin); m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAny, objects.data(), objects.size()); } template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool>> inline Any::Any(InputIt begin, InputIt end) { static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption"); size_t const count = end - begin; RequiredObject* objects = CARB_STACK_ALLOC(RequiredObject, count); size_t index = 0; for (; begin != end; ++begin) objects[index++] = *begin; CARB_ASSERT(index == count); m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAny, objects, count); } inline Tracker::Tracker(TaskGroup& grp) : Object{ ObjectType::eTaskGroup, &grp.m_count } { } inline Tracker::Tracker(TaskGroup* grp) : Object{ ObjectType::eTaskGroup, grp ? &grp->m_count : nullptr } { } inline ScopedTracking::ScopedTracking(Trackers trackers) { Tracker const* ptrackers; size_t numTrackers; trackers.output(ptrackers, numTrackers); m_tracker = carb::getCachedInterface<ITasking>()->beginTracking(ptrackers, numTrackers); } inline ScopedTracking::~ScopedTracking() { Object tracker = std::exchange(m_tracker, { ObjectType::eNone, nullptr }); if (tracker.type == ObjectType::eTrackerGroup) { carb::getCachedInterface<ITasking>()->endTracking(tracker); } } inline ScopedTracking::ScopedTracking(ScopedTracking&& rhs) : m_tracker(std::exchange(rhs.m_tracker, { ObjectType::eNone, nullptr })) { } inline ScopedTracking& ScopedTracking::operator=(ScopedTracking&& rhs) noexcept { std::swap(m_tracker, rhs.m_tracker); return *this; } } // namespace tasking } // namespace carb
42,050
C
31.247699
121
0.648466
omniverse-code/kit/include/carb/memory/MemoryTrackerReplaceAllocation.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" #if CARB_PLATFORM_WINDOWS && defined CARB_MEMORY_TRACKER_ENABLED && defined CARB_MEMORY_TRACKER_MODE_REPLACE # include <vcruntime_new.h> # pragma warning(push) # pragma warning(disable : 4595) // non-member operator new or delete functions may not be declared inline /** * Replacement of the new/delete operator in C++ */ inline void* operator new(size_t size) { return malloc(size); } inline void operator delete(void* address) { free(address); } inline void* operator new[](size_t size) { return malloc(size); } inline void operator delete[](void* address) { free(address); } /* void* operator new(size_t size, const std::nothrow_t&) { return malloc(size); } void operator delete(void* address, const std::nothrow_t&) { free(address); } void* operator new[](size_t size, const std::nothrow_t&) { return malloc(size); } void operator delete[](void* address, const std::nothrow_t&) { free(address); }*/ # pragma warning(pop) #endif
1,465
C
21.90625
109
0.714676
omniverse-code/kit/include/carb/memory/Memory.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 "../Defines.h" #include "IMemoryTracker.h" #if CARB_MEMORY_WORK_AS_PLUGIN # define CARB_MEMORY_GLOBALS() CARB_MEMORY_TRACKER_GLOBALS() class MemoryInitializerScoped { public: MemoryInitializerScoped() { carb::memory::registerMemoryTrackerForClient(); } ~MemoryInitializerScoped() { carb::memory::deregisterMemoryTrackerForClient(); } }; #endif #if defined(CARB_MEMORY_TRACKER_MODE_REPLACE) inline void* mallocWithRecord(size_t size) { void* address = malloc(size); if (address) { carb::memory::IMemoryTracker* tracker = carb::memory::getMemoryTracker(); if (tracker) { // Set allocationGroup to nullptr means using default allocation group(HEAP) tracker->recordAllocation(nullptr, address, size); } } return address; } inline void freeWithRecord(void* address) { carb::memory::IMemoryTracker* tracker = carb::memory::getMemoryTracker(); if (tracker) { // Set allocationGroup to nullptr means using default allocation group(HEAP) tracker->recordFree(nullptr, address); } } # if CARB_PLATFORM_WINDOWS inline void* operator new(size_t size) throw() # else void* operator new(size_t size) throw() # endif { return mallocWithRecord(size); } # if CARB_PLATFORM_WINDOWS inline void operator delete(void* address) throw() # else void operator delete(void* address) throw() # endif { freeWithRecord(address); } # if CARB_PLATFORM_WINDOWS inline void operator delete(void* address, unsigned long) throw() # else void operator delete(void* address, unsigned long) throw() # endif { freeWithRecord(address); } # if CARB_PLATFORM_WINDOWS inline void* operator new[](size_t size) throw() # else void* operator new[](size_t size) throw() # endif { return mallocWithRecord(size); } # if CARB_PLATFORM_WINDOWS inline void operator delete[](void* address) throw() # else void operator delete[](void* address) throw() # endif { freeWithRecord(address); } # if CARB_PLATFORM_WINDOWS inline void operator delete[](void* address, unsigned long) throw() # else void operator delete[](void* address, unsigned long) throw() # endif { freeWithRecord(address); } void* operator new(size_t size, const std::nothrow_t&) { return mallocWithRecord(size); } void operator delete(void* address, const std::nothrow_t&) { freeWithRecord(address); } void* operator new[](size_t size, const std::nothrow_t&) { return mallocWithRecord(size); } void operator delete[](void* address, const std::nothrow_t&) { freeWithRecord(address); } #endif inline void* _carbMalloc(size_t size, va_list args) { carb::memory::Context* context = va_arg(args, carb::memory::Context*); carb::memory::IMemoryTracker* tracker = carb::memory::getMemoryTracker(); if (tracker && context) tracker->pushContext(*context); #if defined(CARB_MEMORY_TRACKER_MODE_REPLACE) void* address = mallocWithRecord(size); #else void* address = malloc(size); #endif if (tracker && context) tracker->popContext(); return address; } inline void* carbMalloc(size_t size, ...) { va_list args; va_start(args, size); void* address = _carbMalloc(size, args); va_end(args); return address; } inline void carbFree(void* address) { #if defined(CARB_MEMORY_TRACKER_MODE_REPLACE) freeWithRecord(address); #else free(address); #endif } inline void* operator new(size_t size, const char* file, int line, ...) { CARB_UNUSED(file); va_list args; va_start(args, line); void* address = _carbMalloc(size, args); va_end(args); return address; } inline void* operator new[](size_t size, const char* file, int line, ...) { CARB_UNUSED(file); va_list args; va_start(args, line); void* address = _carbMalloc(size, args); va_end(args); return address; } #define NV_MALLOC(size, ...) carbMalloc(size, ##__VA_ARGS__) #define NV_FREE(p) carbFree(p) #define NV_NEW(...) new (__FILE__, __LINE__, ##__VA_ARGS__) #define NV_DELETE delete #define NV_DELETE_ARRAY delete[]
4,609
C
22.88601
88
0.678672
omniverse-code/kit/include/carb/memory/PooledAllocator.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 "../container/LocklessQueue.h" #include "../thread/Mutex.h" #include <memory> // Change this to 1 to enable pooled allocator leak checking. This captures a callstack and puts everything into an // intrusive list. #define CARB_POOLEDALLOC_LEAKCHECK 0 #if CARB_POOLEDALLOC_LEAKCHECK # include "../extras/Debugging.h" # include "../container/IntrusiveList.h" #endif #if CARB_DEBUG # include "../logging/Log.h" #endif namespace carb { namespace memory { /** * PooledAllocator implements the Allocator named requirements. It is thread-safe and (mostly) lockless. The given * Allocator type must be thread-safe as well. Memory is never returned to the given Allocator until destruction. * * @param T The type created by this PooledAllocator * @param Allocator The allocator to use for underlying memory allocation. Must be able to allocate many instances * contiguously. */ template <class T, class Allocator = std::allocator<T>> class PooledAllocator { public: using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using void_pointer = void*; using const_void_pointer = const void*; using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; template <class U> struct rebind { using other = PooledAllocator<U>; }; PooledAllocator() : m_emo(ValueInitFirst{}), m_debugName(CARB_PRETTY_FUNCTION) { } ~PooledAllocator() { #if CARB_DEBUG // Leak checking size_type freeCount = 0; m_emo.second.forEach([&freeCount](MemBlock*) { ++freeCount; }); size_t const totalCount = m_bucketCount ? (size_t(1) << (m_bucketCount + kBucketShift)) - (size_t(1) << kBucketShift) : 0; size_t const leaks = totalCount - freeCount; if (leaks != 0) { CARB_LOG_ERROR("%s: leaked %zu items", m_debugName, leaks); } #endif #if CARB_POOLEDALLOC_LEAKCHECK m_list.clear(); #endif // Deallocate everything m_emo.second.popAll(); for (size_type i = 0; i != m_bucketCount; ++i) { m_emo.first().deallocate(m_buckets[i], size_t(1) << (i + kBucketShift)); } } pointer allocate(size_type n = 1) { CARB_CHECK(n <= 1); // cannot allocate more than 1 item simultaneously MemBlock* p = m_emo.second.pop(); p = p ? p : _expand(); #if CARB_POOLEDALLOC_LEAKCHECK size_t frames = extras::debugBacktrace(0, p->entry.callstack, CARB_COUNTOF(p->entry.callstack)); memset(p->entry.callstack + frames, 0, sizeof(void*) * (CARB_COUNTOF(p->entry.callstack) - frames)); new (&p->entry.link) decltype(p->entry.link){}; std::lock_guard<carb::thread::mutex> g(m_listMutex); m_list.push_back(p->entry); #endif return reinterpret_cast<pointer>(p); } pointer allocate(size_type n, const_void_pointer p) { pointer mem = p ? pointer(p) : allocate(n); return mem; } void deallocate(pointer p, size_type n = 1) { CARB_CHECK(n <= 1); // cannot free more than 1 item simultaneously MemBlock* mb = reinterpret_cast<MemBlock*>(p); #if CARB_POOLEDALLOC_LEAKCHECK { std::lock_guard<carb::thread::mutex> g(m_listMutex); m_list.remove(mb->entry); } #endif m_emo.second.push(mb); } size_type max_size() const { return 1; } private: constexpr static size_type kBucketShift = 10; // First bucket contains 1<<10 items constexpr static size_type kAlignment = ::carb_max(alignof(T), alignof(carb::container::LocklessQueueLink<void*>)); struct alignas(kAlignment) PoolEntry { T obj; #if CARB_POOLEDALLOC_LEAKCHECK void* callstack[32]; carb::container::IntrusiveListLink<PoolEntry> link; #endif }; struct NontrivialDummyType { constexpr NontrivialDummyType() noexcept { // Avoid zero-initialization when value initialized } }; struct alignas(kAlignment) MemBlock { union { NontrivialDummyType dummy{}; PoolEntry entry; carb::container::LocklessQueueLink<MemBlock> m_link; }; ~MemBlock() { } }; #if CARB_POOLEDALLOC_LEAKCHECK carb::thread::mutex m_listMutex; carb::container::IntrusiveList<PoolEntry, &PoolEntry::link> m_list; #endif // std::allocator<>::rebind<> has been deprecated in C++17 on mac. CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wdeprecated-declarations") using BaseAllocator = typename Allocator::template rebind<MemBlock>::other; CARB_IGNOREWARNING_GNUC_POP MemBlock* _expand() { std::lock_guard<Lock> g(m_mutex); // If we get the lock, first check to see if another thread populated the buckets first if (MemBlock* mb = m_emo.second.pop()) { return mb; } size_t const bucket = m_bucketCount; size_t const allocationCount = size_t(1) << (bucket + kBucketShift); // Allocate from base. The underlying allocator may throw MemBlock* mem = m_emo.first().allocate(allocationCount); CARB_FATAL_UNLESS(mem, "PooledAllocator underlying allocation failed: Out of memory"); // If any further exceptions are thrown, deallocate `mem`. CARB_SCOPE_EXCEPT { m_emo.first().deallocate(mem, allocationCount); }; // Resize the number of buckets. This can throw if make_unique() fails. auto newBuckets = std::make_unique<MemBlock*[]>(m_bucketCount + 1); if (m_bucketCount++ > 0) memcpy(newBuckets.get(), m_buckets.get(), sizeof(MemBlock*) * (m_bucketCount - 1)); m_buckets = std::move(newBuckets); // Populate the new bucket // Add entries (after the first) to the free list m_emo.second.push(mem + 1, mem + allocationCount); m_buckets[bucket] = mem; // Return the first entry that we reserved for the caller return mem; } using LocklessQueue = carb::container::LocklessQueue<MemBlock, &MemBlock::m_link>; EmptyMemberPair<BaseAllocator, LocklessQueue> m_emo; using Lock = carb::thread::mutex; Lock m_mutex; std::unique_ptr<MemBlock* []> m_buckets {}; size_t m_bucketCount{ 0 }; const char* const m_debugName; }; } // namespace memory } // namespace carb
6,979
C
29.347826
119
0.634188
omniverse-code/kit/include/carb/memory/IMemoryTracker.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 "MemoryTrackerDefines.h" #include "MemoryTrackerReplaceAllocation.h" #include "MemoryTrackerTypes.h" #if CARB_MEMORY_WORK_AS_PLUGIN # include "../Framework.h" #endif #include "../Types.h" namespace carb { namespace memory { /** * Defines a toolkit Memory Tracker, used to monitor/track memory usage/leak. */ struct IMemoryTracker { CARB_PLUGIN_INTERFACE("carb::memory::IMemoryTracker", 1, 0) /** * Setting this number either in the debugger, or in code will result in causing * the memory allocator to break when this allocation is encountered. */ intptr_t* breakOnAlloc; /** * Specify that the debugger signal should be triggered nth allocation within a context. * @param context The context to modify. * @param nAlloc Signal the debugger on the nth allocation within context. -1 disables * this feature. * This feature only respects the top of the Context stack. */ void(CARB_ABI* contextBreakOnAlloc)(const Context& context, intptr_t nAlloc); /** * Makes the context active on the context stack for this thread. * * @param context The context to become active */ void(CARB_ABI* pushContext)(const Context& context); /** * Pops the context on the top of the stack off for this thread. */ void(CARB_ABI* popContext)(); /** * Creates an allocation group. * * @param name The name of the memory address group. * @return The address group object. */ AllocationGroup*(CARB_ABI* createAllocationGroup)(const char* name); /** * Destroys an allocation group. * * @param allocationGroup The address group to destroy */ void(CARB_ABI* destroyAllocationGroup)(AllocationGroup* allocationGroup); /** * Records an allocation on behalf of a region. * * The context recorded is on the top of the context stack. Additionally, the backtrace * associated with this allocation is recorded from this call site. * * @param allocationGroup The allocationGroup to record the allocation into * @param address The address that the allocation exists at * @param size The size of the allocation. */ void(CARB_ABI* recordAllocation)(AllocationGroup* allocationGroup, const void* const address, size_t size); /** * Records an allocation on behalf of a region. * * Additionally, the backtrace associated with this allocation is recorded from this call * site. * * @param allocationGroup The allocationGroup to record the allocation into * @param context The context that the allocation is associated with. * @param address The address that the allocation exists at * @param size The size of the allocation. */ void(CARB_ABI* recordAllocationWithContext)(AllocationGroup* allocationGroup, const Context& context, const void* const address, size_t size); /** * Records that an allocation that was previously recorded was released. * * @param allocationGroup The allocation group that the allocation was associated with. * @param address The address the allocation was associated with. */ void(CARB_ABI* recordFree)(AllocationGroup* allocationGroup, const void* const address); /** * Creates a bookmark of the current state of the memory system. * * This is somewhat of a heavy-weight operation and should only be used at certain times * such as level load. * * @return A snapshot of the current state of the memory system. */ Bookmark*(CARB_ABI* createBookmark)(); /** * Destroys a memory bookmark. * * @param bookmark The bookmark to destroy. */ void(CARB_ABI* destroyBookmark)(Bookmark* bookmark); /** * Get a basic summary of the current state of the memory system, that is of a low enough overhead that we could put * on a ImGui page that updates ever frame. * * @return The Summary struct of current state. */ Summary(CARB_ABI* getSummary)(); /** * Generates a memory report. * * @param reportFlags The flags about the report. * @param report The generated report, it is up to the user to release the report with releaseReport. * @return nullptr if the report couldn't be generated, otherwise the report object. */ Report*(CARB_ABI* createReport)(ReportFlags reportFlags); /** * Generates a memory report, starting at a bookmark to now. * * @param reportFlags The flags about the report. * @param bookmark Any allocations before bookmark will be ignored in the report. * @param report The generated report, it is up to the user to release the report with * releaseReport. * @return nullptr if the report couldn't be generated, otherwise the report object. */ Report*(CARB_ABI* createReportFromBookmark)(ReportFlags reportFlags, Bookmark* bookmark); /** * Frees underlying data for the report. * * @param report The report to free. */ void(CARB_ABI* destroyReport)(Report* report); /** * Returns a pointer to the report data. The returned pointer can not be stored for persistence usage, and it will * be freed along with the report. * * @param report The report data to inspect. * @return The raw report data. */ const char*(CARB_ABI* reportGetData)(Report* report); /** * Returns the number of leaks stored in a memory report. * * @param report The report to return the number of leaks for. * @return The number of leaks associated with the report. */ size_t(CARB_ABI* getReportMemoryLeakCount)(const Report* report); /** * When exiting, memory tracker will create a memory leak report. * The report file name could be (from high priority to low): * - In command line arguments (top priority) as format: --memory.report.path * - Parameter in this function * - The default: * ${WorkingDir}/memoryleak.json * @param fileName The file name (including full path) to save memory leak report when exiting */ void(CARB_ABI* setReportFileName)(const char* fileName); }; } // namespace memory } // namespace carb #if CARB_MEMORY_WORK_AS_PLUGIN CARB_WEAKLINK carb::memory::IMemoryTracker* g_carbMemoryTracker; # define CARB_MEMORY_TRACKER_GLOBALS() #endif namespace carb { namespace memory { #if CARB_MEMORY_WORK_AS_PLUGIN inline void registerMemoryTrackerForClient() { Framework* framework = getFramework(); g_carbMemoryTracker = framework->acquireInterface<memory::IMemoryTracker>(); } inline void deregisterMemoryTrackerForClient() { g_carbMemoryTracker = nullptr; } /** * Get the toolkit Memory Tracker * @return the memory tracker toolkit */ inline IMemoryTracker* getMemoryTracker() { return g_carbMemoryTracker; } #else /** * Get the toolkit Memory Tracker * @return the memory tracker toolkit */ CARB_EXPORT memory::IMemoryTracker* getMemoryTracker(); #endif /** * RAII Context helper * * This class uses RAII to automatically set a context as active and then release it. * * @code * { * ScopedContext(SoundContext); * // Allocate some sound resources * } * @endcode */ class ScopedContext { public: ScopedContext(const Context& context) { CARB_UNUSED(context); #if CARB_MEMORY_TRACKER_ENABLED IMemoryTracker* tracker = getMemoryTracker(); CARB_ASSERT(tracker); if (tracker) tracker->pushContext(context); #endif } ~ScopedContext() { #if CARB_MEMORY_TRACKER_ENABLED IMemoryTracker* tracker = getMemoryTracker(); CARB_ASSERT(tracker); if (tracker) tracker->popContext(); #endif } }; } // namespace memory } // namespace carb
8,453
C
31.022727
120
0.671951
omniverse-code/kit/include/carb/memory/MemoryTrackerTypes.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. // // ver: 0.1 // #pragma once #include <cstddef> #include <cstdint> namespace carb { namespace memory { /** * A context is a thin wrapper of a string pointer, as such it is up to the programmer * to ensure that the pointer is valid at the invocation. * * To minimize the possibility of error any API receiving the context should copy the * string rather than reference its pointer. */ class Context { public: explicit Context(const char* contextName) : m_contextName(contextName) { } const char* getContextName() const { return m_contextName; } private: const char* m_contextName; }; /** * An address space is a type of memory that the user wishes to track. Normal * allocation goes into the Global address space. This is used to track manual heaps, as * well as resources that behave like memory but are not directly tied to the memory * systems provided by the global heap. This can also be used to track an object who has * unique id for the life-time of the object. Example: OpenGL Texture Ids * * Examples include GPU resources and Object Pools. */ struct AllocationGroup; #define DEFAULT_ALLOCATION_GROUP_NAME "" /** * A bookmark is a point in time in the memory tracker, it allows the user to * create a view of the memory between a bookmark and now. */ struct Bookmark; struct ReportFlag { enum { eReportLeaks = 0x1, ///< Report any memory leaks as well. eSummary = 0x2, ///< Just a summary. eFull = eReportLeaks | eSummary, }; }; typedef uint32_t ReportFlags; /** * This structure wraps up the data of the report. */ class Report; /** * A Summary is a really simple report. */ struct Summary { size_t allocationGroupCount; size_t allocationCount; size_t allocationBytes; size_t freeCount; size_t freeBytes; }; enum class MemoryType { eMalloc, eCalloc, eRealloc, eAlignedAlloc, eStrdup, eNew, eNewArray, eExternal, eMemalign, // Linux only eValloc, // Linux only ePosixMemalign, // Linux only eHeapAlloc, eHeapRealloc, }; } // namespace memory } // namespace carb
2,588
C
22.324324
88
0.703632
omniverse-code/kit/include/carb/memory/MemoryTrackerDefines.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 "../Defines.h" // In plugin mode, memory tracker is required to be loaded/unloaded as other plugins // In this mode, always track memory allocation/free after loaded #define CARB_MEMORY_WORK_AS_PLUGIN 1 // JMK 2021-09-13: disabling carb.memory as it can lead to shutdown issues. The hooks are not added or removed in a // thread-safe way, which means that other threads can be in a trampoline or hook function when they are removed. This // leads to potential crashes at shutdown. #ifndef CARB_MEMORY_TRACKER_ENABLED // # define CARB_MEMORY_TRACKER_ENABLED (CARB_DEBUG) # define CARB_MEMORY_TRACKER_ENABLED 0 #endif // Option on work mode for Windows // Set to 1: Hook windows heap API (only for Windows) // Set to 0: Replace malloc/free, new/delete // Linux always use replace mode #define CARB_MEMORY_HOOK 1 #if CARB_PLATFORM_LINUX && CARB_MEMORY_TRACKER_ENABLED # define CARB_MEMORY_TRACKER_MODE_REPLACE #elif CARB_PLATFORM_WINDOWS && CARB_MEMORY_TRACKER_ENABLED # if CARB_MEMORY_HOOK # define CARB_MEMORY_TRACKER_MODE_HOOK # else # define CARB_MEMORY_TRACKER_MODE_REPLACE # endif #endif // Option to add addition header before allocated memory // See MemoryBlockHeader for header structure #define CARB_MEMORY_ADD_HEADER 0 #if !CARB_MEMORY_ADD_HEADER // If header not added, will verify the 6 of 8 bytes before allocated memory // --------------------------------- // | Y | Y | Y | Y | N | N | Y | Y | Allocated memory // --------------------------------- // Y means to verify, N means to ignore // These 8 bytes should be part of heap chunk header // During test, the 6 bytes will not changed before free while other 2 bytes may changed. // Need investigate more for reason. # define CARB_MEMORY_VERIFY_HEAP_CHUNK_HEADER 1 #else # define CARB_MEMORY_VERIFY_HEAP_CHUNK_HEADER 0 #endif
2,295
C
38.586206
118
0.725926
omniverse-code/kit/include/carb/memory/ArenaAllocator.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 Allocator that initially uses a memory arena first (typically on the stack) and then falls back to the heap. #pragma once #include "../Defines.h" #include <memory> namespace carb { namespace memory { /** * An allocator that initially allocates from a memory arena (typically on the stack) and falls back to another * allocator when that is exhausted. * * ArenaAllocator conforms to the C++ Named Requirement of <a * href="https://en.cppreference.com/w/cpp/named_req/Allocator">Allocator</a>. * @tparam T The type allocated by this allocator. * @tparam FallbackAllocator The Allocator that is used when the arena is exhausted. */ template <class T, class FallbackAllocator = std::allocator<T>> class ArenaAllocator { public: //! \c T* using pointer = typename std::allocator_traits<FallbackAllocator>::pointer; //! `T const*` using const_pointer = typename std::allocator_traits<FallbackAllocator>::const_pointer; //! \c void* using void_pointer = typename std::allocator_traits<FallbackAllocator>::void_pointer; //! `void const*` using const_void_pointer = typename std::allocator_traits<FallbackAllocator>::const_void_pointer; //! \c T using value_type = typename std::allocator_traits<FallbackAllocator>::value_type; //! \c std::size_t using size_type = typename std::allocator_traits<FallbackAllocator>::size_type; //! \c std::ptrdiff_t using difference_type = typename std::allocator_traits<FallbackAllocator>::difference_type; //! Rebinds ArenaAllocator to a different type \c U template <class U> struct rebind { //! The rebound ArenaAllocator using other = ArenaAllocator<U, typename FallbackAllocator::template rebind<U>::other>; }; /** * Default constructor. Only uses \c FallbackAllocator as no arena is given. */ ArenaAllocator() : m_members(ValueInitFirst{}, nullptr), m_current(nullptr), m_end(nullptr) { } /** * Constructs \c ArenaAllocator with a specific \c FallbackAllocator. Only uses \c FallbackAllocator as no arena is * given. * * @param fallback A \c FallbackAllocator instance to copy. */ explicit ArenaAllocator(const FallbackAllocator& fallback) : m_members(InitBoth{}, fallback, nullptr), m_current(nullptr), m_end(nullptr) { } /** * Constructs \c ArenaAllocator with an arena and optionally a specific \c FallbackAllocator. * * @warning It is the caller's responsibility to ensure that the given memory arena outlives \c *this and any other * \ref ArenaAllocator which it may be moved to. * * @param begin A pointer to the beginning of the arena. * @param end A pointer immediately past the end of the arena. * @param fallback A \c FallbackAllocator instance to copy. */ ArenaAllocator(void* begin, void* end, const FallbackAllocator& fallback = FallbackAllocator()) : m_members(InitBoth{}, fallback, static_cast<uint8_t*>(begin)), m_current(alignForward(m_members.second)), m_end(static_cast<uint8_t*>(end)) { } /** * Move constructor: constructs \c ArenaAllocator by moving from a different \c ArenaAllocator. * * @param other The \c ArenaAllocator to copy from. */ ArenaAllocator(ArenaAllocator&& other) : m_members(InitBoth{}, std::move(other.m_members.first()), other.m_members.second), m_current(other.m_current), m_end(other.m_end) { // Prevent `other` from allocating memory from the arena. By adding 1 we put it past the end which prevents // other->deallocate() from reclaiming the last allocation. other.m_current = other.m_end + 1; } /** * Copy constructor: constructs \c ArenaAllocator from a copy of a given \c ArenaAllocator. * * @note Even though \p other is passed via const-reference, the arena is transferred from \p other to `*this`. * Further allocations from \p other will defer to the FallbackAllocator. * * @param other The \c ArenaAllocator to copy from. */ ArenaAllocator(const ArenaAllocator& other) : m_members(InitBoth{}, other.m_members.first(), other.m_members.second), m_current(other.m_current), m_end(other.m_end) { // Prevent `other` from allocating memory from the arena. By adding 1 we put it past the end which prevents // other->deallocate() from reclaiming the last allocation. other.m_current = other.m_end + 1; } /** * Copy constructor: constructs \c ArenaAllocator for type \c T from a copy of a given \c ArenaAllocator for type * \c U. * * @note This does not copy the arena; that is retained by the original allocator. * * @param other The \c ArenaAllocator to copy from. */ template <class U, class UFallbackAllocator> ArenaAllocator(const ArenaAllocator<U, UFallbackAllocator>& other) : m_members(InitBoth{}, other.m_members.first(), other.m_members.second), m_current(other.m_end + 1), m_end(other.m_end) { // m_current is explicitly assigned to `other.m_end + 1` to prevent further allocations from the arena from // *this and to prevent this->deallocate() from reclaiming the last allocation. } /** * Allocates (but does not construct) memory for one or more instances of \c value_type. * * @param n The number of contiguous \c value_type instances to allocate. If the request cannot be serviced by the * arena, the \c FallbackAllocator is used. * @returns An uninitialized memory region that will fit \p n contiguous instances of \c value_type. * @throws Memory Any exception that would be thrown by \c FallbackAllocator. */ pointer allocate(size_type n = 1) { if ((m_current + (sizeof(value_type) * n)) <= end()) { pointer p = reinterpret_cast<pointer>(m_current); m_current += (sizeof(value_type) * n); return p; } return m_members.first().allocate(n); } /** * Deallocates (but does not destruct) memory for one or more instances of \c value_type. * * @note If the memory came from the arena, the memory will not be available for reuse unless the memory is the * most recent allocation from the arena. * @param in The pointer previously returned from \ref allocate(). * @param n The same \c n value that was passed to \ref allocate() that produced \p in. */ void deallocate(pointer in, size_type n = 1) { uint8_t* p = reinterpret_cast<uint8_t*>(in); if (p >= begin() && p < end()) { if ((p + (sizeof(value_type) * n)) == m_current) m_current -= (sizeof(value_type) * n); } else m_members.first().deallocate(in, n); } private: uint8_t* begin() const noexcept { return m_members.second; } uint8_t* end() const noexcept { return m_end; } static uint8_t* alignForward(void* p) { uint8_t* out = reinterpret_cast<uint8_t*>(p); constexpr static size_t align = alignof(value_type); size_t aligned = (size_t(out) + (align - 1)) & -(ptrdiff_t)align; return out + (aligned - size_t(out)); } template <class U, class UFallbackAllocator> friend class ArenaAllocator; mutable EmptyMemberPair<FallbackAllocator, uint8_t* /*begin*/> m_members; mutable uint8_t* m_current; mutable uint8_t* m_end; }; //! Equality operator //! @param lhs An allocator to compare //! @param rhs An allocator to compare //! @returns \c true if \p lhs and \p rhs can deallocate each other's allocations. template <class T, class U, class Allocator1, class Allocator2> bool operator==(const ArenaAllocator<T, Allocator1>& lhs, const ArenaAllocator<U, Allocator2>& rhs) { return (void*)lhs.m_members.second == (void*)rhs.m_members.second && lhs.m_members.first() == rhs.m_members.first(); } //! Inequality operator //! @param lhs An allocator to compare //! @param rhs An allocator to compare //! @returns the inverse of the equality operator. template <class T, class U, class Allocator1, class Allocator2> bool operator!=(const ArenaAllocator<T, Allocator1>& lhs, const ArenaAllocator<U, Allocator2>& rhs) { return !(lhs == rhs); } } // namespace memory } // namespace carb
8,915
C
37.597402
120
0.661245
omniverse-code/kit/include/carb/memory/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 Helper utilities for memory #pragma once #include "../Defines.h" #if CARB_PLATFORM_LINUX # include <unistd.h> #endif namespace carb { namespace memory { // Turn off optimization for testReadable() for Visual Studio, otherwise the read will be elided and it will always // return true. CARB_OPTIMIZE_OFF_MSC() /** * Tests if a memory word (size_t) can be read from an address without crashing. * * @note This is not a particularly efficient function and should not be depended on for performance. * * @param mem The address to attempt to read * @returns `true` if a value could be read successfully, `false` if attempting to read the value would cause an access * violation or SIGSEGV. */ CARB_ATTRIBUTE(no_sanitize_address) inline bool testReadable(const void* mem) { #if CARB_PLATFORM_WINDOWS // Use SEH to catch a read failure. This is very fast unless an exception occurs as no setup work is needed on // x86_64. __try { size_t s = *reinterpret_cast<const size_t*>(mem); CARB_UNUSED(s); return true; } __except (1) { return false; } #elif CARB_POSIX // The pipes trick: use the kernel to validate that the memory can be read. write() will return -1 with errno=EFAULT // if the memory is not readable. int pipes[2]; CARB_FATAL_UNLESS(pipe(pipes) == 0, "Failed to create pipes"); int ret = CARB_RETRY_EINTR(write(pipes[1], mem, sizeof(size_t))); CARB_FATAL_UNLESS( ret == sizeof(size_t) || errno == EFAULT, "Unexpected result from write(): {%d/%s}", errno, strerror(errno)); close(pipes[0]); close(pipes[1]); return ret == sizeof(size_t); #else CARB_UNSUPPORTED_PLATFORM(); #endif } CARB_OPTIMIZE_ON_MSC() /** * Copies memory as via memmove, but returns false if a read access violation occurs while reading. * * @rst * .. warning:: This function is designed for protection, not performance, and may be very slow to execute. * @endrst * @thread_safety This function is safe to call concurrently. However, this function makes no guarantees about the * consistency of data copied when the data is modified while copied, only the attempting to read invalid memory * will not result in an access violation. * * As with `memmove()`, the memory areas may overlap: copying takes place as though the bytes in @p source are first * copied into a temporary array that does not overlap @p source or @p dest, and the bytes are then copied from the * temporary array to @p dest. * * @param dest The destination buffer that will receive the copied bytes. * @param source The source buffer to copy bytes from. * @param len The number of bytes of @p source to copy to @p dest. * @returns `true` if the memory was successfully copied. If `false` is returned, @p dest is in a valid but undefined * state. */ CARB_ATTRIBUTE(no_sanitize_address) inline bool protectedMemmove(void* dest, const void* source, size_t len) { if (!source) return false; #if CARB_PLATFORM_WINDOWS // Use SEH to catch a read failure. This is very fast unless an exception occurs as no setup work is needed on // x86_64. __try { memmove(dest, source, len); return true; } __except (1) { return false; } #elif CARB_POSIX // Create a pipe and read the data through the pipe. The kernel will sanitize the reads. int pipes[2]; if (pipe(pipes) != 0) return false; while (len != 0) { ssize_t s = ::carb_min((ssize_t)len, (ssize_t)4096); if (CARB_RETRY_EINTR(write(pipes[1], source, s)) != s || CARB_RETRY_EINTR(read(pipes[0], dest, s)) != s) break; len -= size_t(s); dest = static_cast<uint8_t*>(dest) + s; source = static_cast<const uint8_t*>(source) + s; } close(pipes[0]); close(pipes[1]); return len == 0; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Copies memory as via strncpy, but returns false if an access violation occurs while reading. * * @rst * .. warning:: This function is designed for safety, not performance, and may be very slow to execute. * .. warning:: The `source` and `dest` buffers may not overlap. * @endrst * @thread_safety This function is safe to call concurrently. However, this function makes no guarantees about the * consistency of data copied when the data is modified while copied, only the attempting to read invalid memory * will not result in an access violation. * @param dest The destination buffer that will receive the memory. Must be at least @p n bytes in size. * @param source The source buffer. Up to @p n bytes will be copied. * @param n The maximum number of characters of @p source to copy to @p dest. If no `NUL` character was encountered in * the first `n - 1` characters of `source`, then `dest[n - 1]` will be a `NUL` character. This is a departure * from `strncpy()` but similar to `strncpy_s()`. * @returns `true` if the memory was successfully copied; `false` otherwise. If `false` is returned, `dest` is in a * valid but undefined state. */ CARB_ATTRIBUTE(no_sanitize_address) inline bool protectedStrncpy(char* dest, const char* source, size_t n) { if (!source) return false; #if CARB_PLATFORM_WINDOWS // Use SEH to catch a read failure. This is very fast unless an exception occurs as no setup work is needed on // x86_64. __try { size_t len = strnlen(source, n - 1); memcpy(dest, source, len); dest[len] = '\0'; return true; } __except (1) { return false; } #elif CARB_POSIX if (n == 0) return false; // Create a pipe and read the data through the pipe. The kernel will sanitize the reads. struct Pipes { bool valid; int fds[2]; Pipes() { valid = pipe(fds) == 0; } ~Pipes() { if (valid) { close(fds[0]); close(fds[1]); } } int operator[](int p) const noexcept { return fds[p]; } } pipes; if (!pipes.valid) return false; constexpr static size_t kBytes = sizeof(size_t); constexpr static size_t kMask = kBytes - 1; // Unaligned reads while (n != 0 && (size_t(source) & kMask) != 0) { if (CARB_RETRY_EINTR(write(pipes[1], source, 1)) != 1 || CARB_RETRY_EINTR(read(pipes[0], dest, 1)) != 1) return false; if (*dest == '\0') return true; ++source, ++dest, --n; } // Aligned reads while (n >= kBytes) { CARB_ASSERT((size_t(source) & kMask) == 0); union { size_t value; char chars[kBytes]; } u; if (CARB_RETRY_EINTR(write(pipes[1], source, kBytes)) != kBytes || CARB_RETRY_EINTR(read(pipes[0], &u.value, kBytes)) != kBytes) return false; // Use the strlen bit trick to check if any bytes that make up a word are definitely not zero if (CARB_UNLIKELY(((u.value - 0x0101010101010101) & 0x8080808080808080))) { // One of the bytes could be zero for (int i = 0; i != sizeof(size_t); ++i) { dest[i] = u.chars[i]; if (!dest[i]) return true; } } else { memcpy(dest, u.chars, kBytes); } source += kBytes; dest += kBytes; n -= kBytes; } // Trailing reads while (n != 0) { if (CARB_RETRY_EINTR(write(pipes[1], source, 1)) != 1 || CARB_RETRY_EINTR(read(pipes[0], dest, 1)) != 1) return false; if (*dest == '\0') return true; ++source, ++dest, --n; } // Truncate *(dest - 1) = '\0'; return true; #else CARB_UNSUPPORTED_PLATFORM(); #endif } } // namespace memory } // namespace carb
8,469
C
31.083333
120
0.614358
omniverse-code/kit/include/carb/windowing/IGLContext.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 "../Interface.h" #include "../Types.h" namespace carb { namespace windowing { struct GLContext; /** * Defines a GL context interface for off-screen rendering. */ struct IGLContext { CARB_PLUGIN_INTERFACE("carb::windowing::IGLContext", 1, 0) /** * Creates a context for OpenGL. * * @param width The width of the off-screen surface for the context. * @param height The height of the off-screen surface for the context. * @return The GL context created. */ GLContext*(CARB_ABI* createContextOpenGL)(int width, int height); /** * Creates a context for OpenGL(ES). * * @param width The width of the off-screen surface for the context. * @param height The height of the off-screen surface for the context. * @return The GL context created. */ GLContext*(CARB_ABI* createContextOpenGLES)(int width, int height); /** * Destroys a GL context. * * @param ctx The GL context to be destroyed. */ void(CARB_ABI* destroyContext)(GLContext* ctx); /** * Makes the GL context current. * * After calling this you can make any GL function calls. * * @param ctx The GL context to be made current. */ void(CARB_ABI* makeContextCurrent)(GLContext* ctx); /** * Try and resolve an OpenGL or OpenGL(es) procedure address from name. * * @param procName The name of procedure to load. * @return The address of procedure. */ void*(CARB_ABI* getProcAddress)(const char* procName); }; } // namespace windowing } // namespace carb
2,052
C
27.123287
77
0.674951
omniverse-code/kit/include/carb/windowing/WindowingBindingsPython.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 "../BindingsPythonUtils.h" #include "../BindingsPythonTypes.h" #include "IGLContext.h" #include "IWindowing.h" #include <memory> #include <string> #include <vector> namespace carb { namespace windowing { struct Cursor { }; struct GLContext { }; struct Monitor { }; struct ImagePy { int32_t width; int32_t height; py::bytes pixels; ImagePy(int32_t _width, int32_t _height, py::bytes& _pixels) : width(_width), height(_height), pixels(_pixels) { } }; inline void definePythonModule(py::module& m) { using namespace carb; using namespace carb::windowing; m.doc() = "pybind11 carb.windowing bindings"; py::class_<Window>(m, "Window"); py::class_<Cursor>(m, "Cursor"); py::class_<GLContext>(m, "GLContext"); py::class_<Monitor>(m, "Monitor"); py::class_<ImagePy>(m, "Image") .def(py::init<int32_t, int32_t, py::bytes&>(), py::arg("width"), py::arg("height"), py::arg("pixels")); m.attr("WINDOW_HINT_NONE") = py::int_(kWindowHintNone); m.attr("WINDOW_HINT_NO_RESIZE") = py::int_(kWindowHintNoResize); m.attr("WINDOW_HINT_NO_DECORATION") = py::int_(kWindowHintNoDecoration); m.attr("WINDOW_HINT_NO_AUTO_ICONIFY") = py::int_(kWindowHintNoAutoIconify); m.attr("WINDOW_HINT_NO_FOCUS_ON_SHOW") = py::int_(kWindowHintNoFocusOnShow); m.attr("WINDOW_HINT_SCALE_TO_MONITOR") = py::int_(kWindowHintScaleToMonitor); m.attr("WINDOW_HINT_FLOATING") = py::int_(kWindowHintFloating); m.attr("WINDOW_HINT_MAXIMIZED") = py::int_(kWindowHintMaximized); py::enum_<CursorStandardShape>(m, "CursorStandardShape") .value("ARROW", CursorStandardShape::eArrow) .value("IBEAM", CursorStandardShape::eIBeam) .value("CROSSHAIR", CursorStandardShape::eCrosshair) .value("HAND", CursorStandardShape::eHand) .value("HORIZONTAL_RESIZE", CursorStandardShape::eHorizontalResize) .value("VERTICAL_RESIZE", CursorStandardShape::eVerticalResize); py::enum_<CursorMode>(m, "CursorMode") .value("NORMAL", CursorMode::eNormal) .value("HIDDEN", CursorMode::eHidden) .value("DISABLED", CursorMode::eDisabled); py::enum_<InputMode>(m, "InputMode") .value("STICKY_KEYS", InputMode::eStickyKeys) .value("STICKY_MOUSE_BUTTONS", InputMode::eStickyMouseButtons) .value("LOCK_KEY_MODS", InputMode::eLockKeyMods) .value("RAW_MOUSE_MOTION", InputMode::eRawMouseMotion); defineInterfaceClass<IWindowing>(m, "IWindowing", "acquire_windowing_interface") .def("create_window", [](const IWindowing* iface, int width, int height, const char* title, bool fullscreen, int hints) { WindowDesc desc = {}; desc.width = width; desc.height = height; desc.title = title; desc.fullscreen = fullscreen; desc.hints = hints; return iface->createWindow(desc); }, py::arg("width"), py::arg("height"), py::arg("title"), py::arg("fullscreen"), py::arg("hints") = kWindowHintNone, py::return_value_policy::reference) .def("destroy_window", wrapInterfaceFunction(&IWindowing::destroyWindow)) .def("show_window", wrapInterfaceFunction(&IWindowing::showWindow)) .def("hide_window", wrapInterfaceFunction(&IWindowing::hideWindow)) .def("get_window_width", wrapInterfaceFunction(&IWindowing::getWindowWidth)) .def("get_window_height", wrapInterfaceFunction(&IWindowing::getWindowHeight)) .def("get_window_position", wrapInterfaceFunction(&IWindowing::getWindowPosition)) .def("set_window_position", wrapInterfaceFunction(&IWindowing::setWindowPosition)) .def("set_window_title", wrapInterfaceFunction(&IWindowing::setWindowTitle)) .def("set_window_opacity", wrapInterfaceFunction(&IWindowing::setWindowOpacity)) .def("get_window_opacity", wrapInterfaceFunction(&IWindowing::getWindowOpacity)) .def("set_window_fullscreen", wrapInterfaceFunction(&IWindowing::setWindowFullscreen)) .def("is_window_fullscreen", wrapInterfaceFunction(&IWindowing::isWindowFullscreen)) .def("resize_window", wrapInterfaceFunction(&IWindowing::resizeWindow)) .def("focus_window", wrapInterfaceFunction(&IWindowing::focusWindow)) .def("is_window_focused", wrapInterfaceFunction(&IWindowing::isWindowFocused)) .def("maximize_window", wrapInterfaceFunction(&IWindowing::maximizeWindow)) .def("minimize_window", wrapInterfaceFunction(&IWindowing::minimizeWindow)) .def("restore_window", wrapInterfaceFunction(&IWindowing::restoreWindow)) .def("is_window_maximized", wrapInterfaceFunction(&IWindowing::isWindowMaximized)) .def("is_window_minimized", wrapInterfaceFunction(&IWindowing::isWindowMinimized)) .def("should_window_close", wrapInterfaceFunction(&IWindowing::shouldWindowClose)) .def("set_window_should_close", wrapInterfaceFunction(&IWindowing::setWindowShouldClose)) .def("get_window_user_pointer", wrapInterfaceFunction(&IWindowing::getWindowUserPointer)) .def("set_window_user_pointer", wrapInterfaceFunction(&IWindowing::setWindowUserPointer)) .def("set_window_content_scale", wrapInterfaceFunction(&IWindowing::getWindowContentScale)) .def("get_native_display", wrapInterfaceFunction(&IWindowing::getNativeDisplay)) .def("get_native_window", wrapInterfaceFunction(&IWindowing::getNativeWindow), py::return_value_policy::reference) .def("set_input_mode", wrapInterfaceFunction(&IWindowing::setInputMode)) .def("get_input_mode", wrapInterfaceFunction(&IWindowing::getInputMode)) .def("update_input_devices", wrapInterfaceFunction(&IWindowing::updateInputDevices)) .def("poll_events", wrapInterfaceFunction(&IWindowing::pollEvents)) .def("wait_events", wrapInterfaceFunction(&IWindowing::waitEvents)) .def("get_keyboard", wrapInterfaceFunction(&IWindowing::getKeyboard), py::return_value_policy::reference) .def("get_mouse", wrapInterfaceFunction(&IWindowing::getMouse), py::return_value_policy::reference) .def("create_cursor_standard", wrapInterfaceFunction(&IWindowing::createCursorStandard), py::return_value_policy::reference) .def("create_cursor", [](IWindowing* windowing, ImagePy& imagePy, int32_t xhot, int32_t yhot) { py::buffer_info info(py::buffer(imagePy.pixels).request()); uint8_t* data = reinterpret_cast<uint8_t*>(info.ptr); Image image{ imagePy.width, imagePy.height, data }; return windowing->createCursor(image, xhot, yhot); }, py::return_value_policy::reference) .def("destroy_cursor", wrapInterfaceFunction(&IWindowing::destroyCursor)) .def("set_cursor", wrapInterfaceFunction(&IWindowing::setCursor)) .def("set_cursor_mode", wrapInterfaceFunction(&IWindowing::setCursorMode)) .def("get_cursor_mode", wrapInterfaceFunction(&IWindowing::getCursorMode)) .def("set_cursor_position", wrapInterfaceFunction(&IWindowing::setCursorPosition)) .def("get_cursor_position", wrapInterfaceFunction(&IWindowing::getCursorPosition)) .def("set_clipboard", wrapInterfaceFunction(&IWindowing::setClipboard)) .def("get_clipboard", wrapInterfaceFunction(&IWindowing::getClipboard)) .def("get_monitors", [](IWindowing* iface) { size_t monitorCount; const Monitor** monitors = iface->getMonitors(&monitorCount); py::tuple tuple(monitorCount); for (size_t i = 0; i < monitorCount; ++i) { tuple[i] = monitors[i]; } return tuple; }) .def("get_monitor_position", wrapInterfaceFunction(&IWindowing::getMonitorPosition)) .def("get_monitor_work_area", [](IWindowing* iface, Monitor* monitor) { Int2 pos, size; iface->getMonitorWorkArea(monitor, &pos, &size); py::tuple tuple(2); tuple[0] = pos; tuple[1] = size; return tuple; }) .def("set_window_icon", [](IWindowing* windowing, Window* window, ImagePy& imagePy) { py::buffer_info info(py::buffer(imagePy.pixels).request()); uint8_t* data = reinterpret_cast<uint8_t*>(info.ptr); Image image{ imagePy.width, imagePy.height, data }; windowing->setWindowIcon(window, image); }); defineInterfaceClass<IGLContext>(m, "IGLContext", "acquire_gl_context_interface") .def("create_context_opengl", [](const IGLContext* iface, int width, int height) { return iface->createContextOpenGL(width, height); }, py::arg("width"), py::arg("height"), py::return_value_policy::reference) .def("create_context_opengles", [](const IGLContext* iface, int width, int height) { return iface->createContextOpenGLES(width, height); }, py::arg("width"), py::arg("height"), py::return_value_policy::reference) .def("destroy_context", wrapInterfaceFunction(&IGLContext::destroyContext)) .def("make_context_current", wrapInterfaceFunction(&IGLContext::makeContextCurrent)); } } // namespace windowing } // namespace carb
9,947
C
50.27835
122
0.660903
omniverse-code/kit/include/carb/windowing/IWindowing.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" namespace carb { namespace input { struct Keyboard; struct Mouse; struct Gamepad; } // namespace input namespace windowing { struct Window; struct Cursor; struct Monitor; enum class MonitorChangeEvent : uint32_t { eUnknown, eConnected, eDisconnected }; typedef void (*OnWindowMoveFn)(Window* window, int x, int y, void* userData); typedef void (*OnWindowResizeFn)(Window* window, int width, int height, void* userData); typedef void (*OnWindowDropFn)(Window* window, const char** paths, int count, void* userData); typedef void (*OnWindowCloseFn)(Window* window, void* userData); typedef void (*OnWindowContentScaleFn)(Window* window, float scaleX, float scaleY, void* userData); typedef void (*OnWindowFocusFn)(Window* window, bool isFocused, void* userData); typedef void (*OnWindowMaximizeFn)(Window* window, bool isMaximized, void* userData); typedef void (*OnWindowMinimizeFn)(Window* window, bool isMinimized, void* userData); typedef void (*OnMonitorChangeFn)(const Monitor* monitor, MonitorChangeEvent evt); typedef uint32_t WindowHints; constexpr WindowHints kWindowHintNone = 0; constexpr WindowHints kWindowHintNoResize = 1 << 0; constexpr WindowHints kWindowHintNoDecoration = 1 << 1; constexpr WindowHints kWindowHintNoAutoIconify = 1 << 2; constexpr WindowHints kWindowHintNoFocusOnShow = 1 << 3; constexpr WindowHints kWindowHintScaleToMonitor = 1 << 4; constexpr WindowHints kWindowHintFloating = 1 << 5; constexpr WindowHints kWindowHintMaximized = 1 << 6; /** * Descriptor for how a window is to be created. */ struct WindowDesc { int width; ///! The initial window width. int height; ///! The initial window height. const char* title; ///! The initial title of the window. bool fullscreen; ///! Should the window be initialized in fullscreen mode. WindowHints hints; ///! Initial window hints / attributes. }; /** * Defines cursor standard shapes. */ enum class CursorStandardShape : uint32_t { eArrow, ///! The regular arrow cursor shape. eIBeam, ///! The text input I-beam cursor shape. eCrosshair, ///! The crosshair shape. eHand, ///! The hand shape eHorizontalResize, ///! The horizontal resize arrow shape. eVerticalResize ///! The vertical resize arrow shape. }; enum class CursorMode : uint32_t { eNormal, ///! Cursor visible and behaving normally. eHidden, ///! Cursor invisible when over the content area of window but does not restrict the cursor from leaving. eDisabled, ///! Hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful /// for implementing for example 3D camera controls. }; enum class InputMode : uint32_t { eStickyKeys, ///! Config sticky key. eStickyMouseButtons, ///! Config sticky mouse button. eLockKeyMods, ///! Config lock key modifier bits. eRawMouseMotion ///! Config raw mouse motion. }; struct VideoMode { int width; ///! The width, in screen coordinates, of the video mode. int height; ///! The height, in screen coordinates, of the video mode. int redBits; ///! The bit depth of the red channel of the video mode. int greenBits; ///! The bit depth of the green channel of the video mode. int blueBits; ///! The bit depth of the blue channel of the video mode. int refreshRate; ///! The refresh rate, in Hz, of the video mode. }; /** * This describes a single 2D image. See the documentation for each related function what the expected pixel format is. */ struct Image { int32_t width; ///! The width, in pixels, of this image. int32_t height; ///! The height, in pixels, of this image. uint8_t* pixels; ///! The pixel data of this image, arranged left-to-right, top-to-bottom. }; /** * Defines a windowing interface. */ struct IWindowing { CARB_PLUGIN_INTERFACE("carb::windowing::IWindowing", 1, 4) /** * Creates a window. * * @param desc The descriptor for the window. * @return The window created. */ Window*(CARB_ABI* createWindow)(const WindowDesc& desc); /** * Destroys a window. * * @param window The window to be destroyed. */ void(CARB_ABI* destroyWindow)(Window* window); /** * Shows a window making it visible. * * @param window The window to use. */ void(CARB_ABI* showWindow)(Window* window); /** * Hides a window making it hidden. * * @param window The window to use. */ void(CARB_ABI* hideWindow)(Window* window); /** * Gets the current window width. * * @param window The window to use. * @return The current window width. */ uint32_t(CARB_ABI* getWindowWidth)(Window* window); /** * Gets the current window height. * * @param window The window to use. * @return The current window height. */ uint32_t(CARB_ABI* getWindowHeight)(Window* window); /** * Gets the current window position. * * @param window The window to use. * @return The current window position. */ Int2(CARB_ABI* getWindowPosition)(Window* window); /** * Sets the current window position. * * @param window The window to use. * @param position The position to set the window to. */ void(CARB_ABI* setWindowPosition)(Window* window, const Int2& position); /** * Sets the window title. * * @param window The window to use. * @param title The window title to be set (as a utf8 string) */ void(CARB_ABI* setWindowTitle)(Window* window, const char* title); /** * Sets the window opacity. * * @param window The window to use. * @param opacity The window opacity. 1.0f is fully opaque. 0.0 is fully transparent. */ void(CARB_ABI* setWindowOpacity)(Window* window, float opacity); /** * Gets the window opacity. * * @param window The window to use. * @return The window opacity. 1.0f is fully opaque. 0.0 is fully transparent. */ float(CARB_ABI* getWindowOpacity)(Window* window); /** * Sets the window into fullscreen or windowed mode. * * @param window The window to use. * @param fullscreen true to be set to fullscreen, false to be set to windowed. */ void(CARB_ABI* setWindowFullscreen)(Window* window, bool fullscreen); /** * Determines if the window is in fullscreen mode. * * @param window The window to use. * @return true if the window is in fullscreen mode, false if in windowed mode. */ bool(CARB_ABI* isWindowFullscreen)(Window* window); /** * Sets the function for handling resize events. * * @param window The window to use. * @param onWindowResize The function callback to handle resize events on the window. */ void(CARB_ABI* setWindowResizeFn)(Window* window, OnWindowResizeFn onWindowResize, void* userData); /** * Resizes the window. * * @param window The window to resize. * @param width The width to resize to. * @param height The height to resize to. */ void(CARB_ABI* resizeWindow)(Window* window, int width, int height); /** * Set the window in focus. * * @param window The window to use. */ void(CARB_ABI* focusWindow)(Window* window); /** * Sets the function for handling window focus events. * * @param window The window to use. * @param onWindowFocusFn The function callback to handle focus events on the window. */ void(CARB_ABI* setWindowFocusFn)(Window* window, OnWindowFocusFn onWindowFocusFn, void* userData); /** * Determines if the window is in focus. * * @param window The window to use. * @return true if the window is in focus, false if it is not. */ bool(CARB_ABI* isWindowFocused)(Window* window); /** * Sets the function for handling window minimize events. * * @param window The window to use. * @param onWindowMinimizeFn The function callback to handle minimize events on the window. */ void(CARB_ABI* setWindowMinimizeFn)(Window* window, OnWindowMinimizeFn onWindowMinimizeFn, void* userData); /** * Determines if the window is minimized. * * @param window The window to use. * @return true if the window is minimized, false if it is not. */ bool(CARB_ABI* isWindowMinimized)(Window* window); /** * Sets the function for handling drag-n-drop events. * * @param window The window to use. * @param onWindowDrop The function callback to handle drop events on the window. */ void(CARB_ABI* setWindowDropFn)(Window* window, OnWindowDropFn onWindowDrop, void* userData); /** * Sets the function for handling window close events. * * @param window The window to use. * @param onWindowClose The function callback to handle window close events. */ void(CARB_ABI* setWindowCloseFn)(Window* window, OnWindowCloseFn onWindowClose, void* userData); /** * Determines if the user has attempted to closer the window. * * @param window The window to use. * @return true if the user has attempted to closer the window, false if still open. */ bool(CARB_ABI* shouldWindowClose)(Window* window); /** * Hints to the window that it should close. * * @param window The window to use. * @param value true to request the window to close, false to request it not to close. */ void(CARB_ABI* setWindowShouldClose)(Window* window, bool value); /** * This function returns the current value of the user-defined pointer of the specified window. * The initial value is nullptr. * * @param window The window to use. * @return the current value of the user-defined pointer of the specified window. */ void*(CARB_ABI* getWindowUserPointer)(Window* window); /** * This function sets the user-defined pointer of the specified window. * The current value is retained until the window is destroyed. The initial value is nullptr. * * @param window The window to use. * @param pointer The new pointer value. */ void(CARB_ABI* setWindowUserPointer)(Window* window, void* pointer); /** * Sets the function for handling content scale events. * * @param window The window to use. * @param onWindowContentScale The function callback to handle content scale events on the window. */ void(CARB_ABI* setWindowContentScaleFn)(Window* window, OnWindowContentScaleFn onWindowContentScale, void* userData); /** * Retrieves the content scale for the specified monitor. * * @param window The window to use. * @return The content scale of the window. */ Float2(CARB_ABI* getWindowContentScale)(Window* window); /** * Gets the native display handle. * * windows = nullptr * linux = ::Display* * * @param window The window to use. * @return The native display handle. */ void*(CARB_ABI* getNativeDisplay)(Window* window); /** * Gets the native window handle. * * windows = ::HWND * linux = ::Window * * @param window The window to use. * @return The native window handle. */ void*(CARB_ABI* getNativeWindow)(Window* window); /** * Sets an input mode option for the specified window. * * @param window The window to set input mode. * @param mode The mode to set. * @param enabled The new value @ref mode should be changed to. */ void(CARB_ABI* setInputMode)(Window* window, InputMode mode, bool enabled); /** * Gets the value of a input mode option for the specified window. * * @param window The window to get input mode value. * @param mode The input mode to get value from. * @return The input mode value associated with the window. */ bool(CARB_ABI* getInputMode)(Window* window, InputMode mode); /** * Updates input device states. */ void(CARB_ABI* updateInputDevices)(); /** * Polls and processes only those events that have already been received and then returns immediately. */ void(CARB_ABI* pollEvents)(); /** * Puts the calling thread to sleep until at least one event has been received. */ void(CARB_ABI* waitEvents)(); /** * Gets the logical keyboard associated with the window. * * @param window The window to use. * @return The keyboard. */ input::Keyboard*(CARB_ABI* getKeyboard)(Window* window); /** * Gets the logical mouse associated with the window. * * @param window The window to use. * @return The mouse. */ input::Mouse*(CARB_ABI* getMouse)(Window* window); /** * Creates a cursor with a standard shape, that can be set for a window with @ref setCursor. * * Use @ref destroyCursor to destroy cursors. * * @param shape The standard shape of cursor to be created. * @return A new cursor ready to use or nullptr if an error occurred. */ Cursor*(CARB_ABI* createCursorStandard)(CursorStandardShape shape); /** * Destroys a cursor previously created with @ref createCursorStandard. * If the specified cursor is current for any window, that window will be reverted to the default cursor. * * @param cursor the cursor object to destroy. */ void(CARB_ABI* destroyCursor)(Cursor* cursor); /** * Sets the cursor image to be used when the cursor is over the content area of the specified window. * * @param window The window to set the cursor for. * @param cursor The cursor to set, or nullptr to switch back to the default arrow cursor. */ void(CARB_ABI* setCursor)(Window* window, Cursor* cursor); /** * Sets cursor mode option for the specified window. * * @param window The window to set cursor mode. * @param mode The mouse mode to set to. */ void(CARB_ABI* setCursorMode)(Window* window, CursorMode mode); /** * Gets cursor mode option for the specified window. * * @param window The window to get cursor mode. * @return The mouse mode associated with the window. */ CursorMode(CARB_ABI* getCursorMode)(Window* window); /** * Sets cursor position relative to the window. * * @param window The window to set input mode. * @param position The x/y coordinates relative to the window. */ void(CARB_ABI* setCursorPosition)(Window* window, const Int2& position); /** * Gets cursor position relative to the window. * * @param window The window to set input mode. * @return The x/y coordinates relative to the window. */ Int2(CARB_ABI* getCursorPosition)(Window* window); /** * The set clipboard function, which expects a Window and text. * * @param window The window that contains a glfwWindow * @param text The text to set to the clipboard */ void(CARB_ABI* setClipboard)(Window* window, const char* text); /** * Gets the clipboard text. * * @param window The window that contains a glfwWindow * @return The text from the clipboard */ const char*(CARB_ABI* getClipboard)(Window* window); /** * Sets the monitors callback function for configuration changes * * The onMonitorChange function callback will occur when monitors are changed. * Current changes that can occur are connected/disconnected. * * @param onMonitorChange The callback function when monitors change. */ void(CARB_ABI* setMonitorsChangeFn)(OnMonitorChangeFn onMonitorChange); /** * Gets the primary monitor. * * A Monitor object represents a currently connected monitor and is represented as a pointer * to the opaque native monitor. Monitor objects cannot be created or destroyed by the application * and retain their addresses until the monitors they represent are disconnected. * * @return The primary monitor. */ const Monitor*(CARB_ABI* getMonitorPrimary)(); /** * Gets the enumerated monitors. * * This represents a currently connected monitors and is represented as a pointer * to the opaque native monitor. Monitors cannot be created or destroyed * and retain their addresses until the monitors are disconnected. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitorCount The returned number of monitors enumerated. * @return The enumerated monitors. */ const Monitor**(CARB_ABI* getMonitors)(size_t* monitorCount); /** * Gets the human read-able monitor name. * * The name pointer returned is only valid for the life of the Monitor. * When the Monitor is disconnected, the name pointer becomes invalid. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitor The monitor to use. * @return The human read-able monitor name. Pointer returned is owned by monitor. */ const char*(CARB_ABI* getMonitorName)(const Monitor* monitor); /** * Gets a monitors physical size in millimeters. * * The size returned is only valid for the life of the Monitor. * When the Monitor is disconnected, the size becomes invalid. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitor The monitor to use. * @param size The monitor physical size returned. */ Int2(CARB_ABI* getMonitorPhysicalSize)(const Monitor* monitor); /** * Gets a monitors current video mode. * * The pointer returned is only valid for the life of the Monitor. * When the Monitor is disconnected, the pointer becomes invalid. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitor The monitor to use. * @return The video mode. */ const VideoMode*(CARB_ABI* getMonitorVideoMode)(const Monitor* monitor); /** * Gets a monitors virtual position. * * The position returned is only valid for the life of the Monitor. * When the Monitor is disconnected, the position becomes invalid. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitor The monitor to use. * @param position The monitor virtual position returned. */ Int2(CARB_ABI* getMonitorPosition)(const Monitor* monitor); /** * Gets a monitors content scale. * * The content scale is the ratio between the current DPI and the platform's default DPI. * This is especially important for text and any UI elements. If the pixel dimensions of * your UI scaled by this look appropriate on your machine then it should appear at a * reasonable size on other machines regardless of their DPI and scaling settings. * This relies on the system DPI and scaling settings being somewhat correct. * * The content scale returned is only valid for the life of the Monitor. * When the Monitor is disconnected, the content scale becomes invalid. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitor The monitor to use. * @return The monitor content scale (dpi). */ Float2(CARB_ABI* getMonitorContentScale)(const Monitor* monitor); /** * Gets a monitors work area. * * The area of a monitor not occupied by global task bars or * menu bars is the work area * * The work area returned is only valid for the life of the Monitor. * When the Monitor is disconnected, the work area becomes invalid. * * Use @ref setMonitorsChangeFn to know when a monitor is disconnected. * * @param monitor The monitor to use. * @param position The returned position. * @param size The returned size. */ void(CARB_ABI* getMonitorWorkArea)(const Monitor* monitor, Int2* positionOut, Int2* sizeOut); /** * Sets the function for handling move events. Must be called on a main thread. * * @param window The window to use (shouldn't be nullptr). * @param onWindowMove The function callback to handle move events on the window (can be nullptr). * @param userData User-specified pointer to the data. Lifetime and value can be anything. */ void(CARB_ABI* setWindowMoveFn)(Window* window, OnWindowMoveFn onWindowMove, void* userData); /** * Determines if the window is floating (or always-on-top). * * @param window The window to use. * @return true if the window is floating. */ bool(CARB_ABI* isWindowFloating)(Window* window); /** * Sets the window into floating (always-on-top) or regular mode. * * @param window The window to use. * @param fullscreen true to be set to floating (always-on-top), false to be set to regular. */ void(CARB_ABI* setWindowFloating)(Window* window, bool isFloating); /** * Creates a new custom cursor image that can be set for a window with @ref setCursor. The cursor can be destroyed * with @ref destroyCursor. * * The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with the red channel * first. They are arranged canonically as packed sequential rows, starting from the top-left corner. * * The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor image. Like all other * coordinate systems in GLFW, the X-axis points to the right and the Y-axis points down. * * @param image The desired cursor image. * @param xhot The desired x-coordinate, in pixels, of the cursor hotspot. * @param yhot The desired y-coordinate, in pixels, of the cursor hotspot. * @return created cursor, or nullptr if error occurred. */ Cursor*(CARB_ABI* createCursor)(const Image& image, int32_t xhot, int32_t yhot); /** * Maximize the window. * * @param window The window to use. */ void(CARB_ABI* maximizeWindow)(Window* window); /** * Minimize the window. * * @param window The window to use. */ void(CARB_ABI* minimizeWindow)(Window* window); /** * Restore the window. * * @param window The window to use. */ void(CARB_ABI* restoreWindow)(Window* window); /** * Sets the function for handling window maximize events. * * @param window The window to use. * @param onWindowMaximizeFn The function callback to handle maximize events on the window. */ void(CARB_ABI* setWindowMaximizeFn)(Window* window, OnWindowMaximizeFn onWindowMaximizeFn, void* userData); /** * Determines if the window is maximized. * * @param window The window to use. * @return true if the window is maximized, false if it is not. */ bool(CARB_ABI* isWindowMaximized)(Window* window); /** * This function sets the icon of the specified window. * * This function will do nothing when pass a invalid image, i.e. image.width==0 or * image.height ==0 or image.pixels == nullptr * * The image.pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight * bits per channel with the red channel first. They are arranged canonically * as packed sequential rows, starting from the top-left corner. * * The desired image sizes varies depending on platform and system settings. * The selected images will be rescaled as needed. Good sizes include 16x16, * 32x32 and 48x48. * * @param window The window to use. * @param image The desired icon image. */ void(CARB_ABI* setWindowIcon)(Window* window, const Image& image); }; } // namespace windowing } // namespace carb
24,565
C
33.166898
121
0.663953
omniverse-code/kit/include/carb/dictionary/DictionaryUtils.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 Utility helper functions for common dictionary operations. #pragma once #include "../Framework.h" #include "../InterfaceUtils.h" #include "../datasource/IDataSource.h" #include "../extras/CmdLineParser.h" #include "../filesystem/IFileSystem.h" #include "../logging/Log.h" #include "IDictionary.h" #include "ISerializer.h" #include <algorithm> #include <string> namespace carb { /** Namespace for @ref carb::dictionary::IDictionary related interfaces and helpers. */ namespace dictionary { /** helper function to retrieve the IDictionary interface. * * @returns The cached @ref carb::dictionary::IDictionary interface. This will be cached * until the plugin is unloaded. */ inline IDictionary* getCachedDictionaryInterface() { return getCachedInterface<IDictionary>(); } /** Prototype for a callback function used to walk items in a dictionary. * * @tparam ElementData An arbitrary data type used as both a parameter and the return * value of the callback. The callback itself is assumed to know * how to interpret and use this value. * @param[in] srcItem The current item being visited. This will never be `nullptr`. * @param[in] elementData An arbitrary data object passed into the callback by the caller of * walkDictionary(). The callback is assumed that it knows how to * interpret and use this value. * @param[in] userData An opaque data object passed by the caller of walkDictionary(). * The callback is assumed that it knows how to interpret and use * this object. * @returns An \a ElementData object or value to pass back to the dictionary walker. When * the callback returns from passing in a new dictionary value (ie: a child of the * original dictionary), this value is stored and passed on to following callbacks. */ template <typename ElementData> using OnItemFn = ElementData (*)(const Item* srcItem, ElementData elementData, void* userData); /** Prototype for a callback function used to walk children in a dictionary. * * @tparam ItemPtrType The data type of the dictionary item in the dictionary being walked. * This should be either `Item` or `const Item`. * @param[in] dict The @ref IDictionary interface being used to access the items in the * dictionary during the walk. This must not be `nullptr`. * @param[in] item The dictionary item to retrieve one of the child items from. This * must not be `nullptr`. This is assumed to be an item of type * @ref ItemType::eDictionary. * @param[in] idx The zero based index of the child item of @p item to retrieve. This * is expected to be within the range of the number of children in the * given dictionary item. * @returns The child item at the requested index in the given dictionary item @p item. Returns * `nullptr` if the given index is out of range of the number of children in the given * dictionary item. * * @remarks This callback provides a way to control the order in which the items in a dictionary * are walked. An basic implementation is provided below. */ template <typename ItemPtrType> inline ItemPtrType* getChildByIndex(IDictionary* dict, ItemPtrType* item, size_t idx); /** Specialization for the getChildByIndex() callback that implements a simple retrieval of the * requested child item using @ref IDictionary::getItemChildByIndex(). * * @sa getChildByIndex(IDictionary*,ItemPtrType*,size_t). */ template <> inline const Item* getChildByIndex(IDictionary* dict, const Item* item, size_t idx) { return dict->getItemChildByIndex(item, idx); } /** Mode names for the ways to walk the requested dictionary. */ enum class WalkerMode { /** When walking the dictionary, include the root item itself. */ eIncludeRoot, /** When walking the dictionary, skip the root item and start with the enumeration with * the immediate children of the root item. */ eSkipRoot }; /** Walk a dictionary item to enumerate all of its values. * * @tparam ElementData The data type for the per-item element data that is maintained * during the walk. This can be used for example to track which * level of the dictionary a given item is at by using an `int` * type here. * @tparam OnItemFnType The type for the @p onItemFn callback function. * @tparam ItemPtrType The type used for the item type in the @p GetChildByIndexFuncType * callback. This must either be `const Item` or `Item`. This * defaults to `const Item`. If a non-const type is used here * it is possible that items' values could be modified during the * walk. Using a non-const value is discouraged however since it * can lead to unsafe use or undefined behavior. * @tparam GetChildByIndexFuncType The type for the @p getChildByIndexFunc callback function. * @param[in] dict The @ref IDictionary interface to use to access the items * in the dictionary. This must not be `nullptr`. This must * be the same interface that was originally used to create * the dictionary @p root being walked. * @param[in] walkerMode The mode to walk the given dictionary in. * @param[in] root The root dictionary to walk. This must not be `nullptr`. * @param[in] rootElementData The user specified element data value that is to be associated * with the @p root element. This value can be changed during * the walk by the @p onItemFn callback function. * @param[in] onItemFn The callback function that is performed for each value in the * given dictionary. The user specified element data value can * be modified on each non-leaf item. This modified element data * value is then passed to all further children of the given * item. The element data value returned for leaf items is * discarded. This must not be `nullptr`. * @param[in] userData Opaque user data object that is passed to each @p onItemFn * callback. The caller is responsible for knowing how to * interpret and access this value. * @param[in] getChildByIndexFunc Callback function to enumerate the children of a given * item in the dictionary being walked. This must not be * `nullptr`. This can be used to either control the order * in which the child items are enumerated (ie: sort them * before returning), or to return them as non-const objects * so that the item's value can be changed during enumeration. * Attempting to insert or remove items by using a non-const * child enumerator is unsafe and will generally result in * undefined behavior. * @returns No return value. * * @remarks This walks a dictionary and enumerates all of its values of all types. This * includes even @ref ItemType::eDictionary items. Non-leaf items in the walk will * be passed to the @p onItemFn callback before walking through its children. * The @p getChildByIndexFunc callback function can be used to control the order in * which the children of each level of the dictionary are enumerated. The default * implementation simply enumerates the items in the order they are stored in (which * is generally arbitrary). The dictionary's full tree is walked in a depth first * manner so sibling items are not guaranteed to be enumerated consecutively. * * @thread_safety This function is thread safe as long as nothing else is concurrently modifying * the dictionary being walked. It is the caller's responsibility to ensure that * neither the dictionary nor any of its children will be modified until the walk * is complete. */ template <typename ElementData, typename OnItemFnType, typename ItemPtrType = const Item, typename GetChildByIndexFuncType CARB_NO_DOC(= decltype(getChildByIndex<ItemPtrType>))> inline void walkDictionary(IDictionary* dict, WalkerMode walkerMode, ItemPtrType* root, ElementData rootElementData, OnItemFnType onItemFn, void* userData, GetChildByIndexFuncType getChildByIndexFunc = getChildByIndex<ItemPtrType>) { if (!root) { return; } struct ValueToParse { ItemPtrType* srcItem; ElementData elementData; }; std::vector<ValueToParse> valuesToParse; valuesToParse.reserve(100); if (walkerMode == WalkerMode::eSkipRoot) { size_t numChildren = dict->getItemChildCount(root); for (size_t chIdx = 0; chIdx < numChildren; ++chIdx) { valuesToParse.push_back({ getChildByIndexFunc(dict, root, numChildren - chIdx - 1), rootElementData }); } } else { valuesToParse.push_back({ root, rootElementData }); } while (valuesToParse.size()) { const ValueToParse valueToParse = valuesToParse.back(); ItemPtrType* curItem = valueToParse.srcItem; ItemType curItemType = dict->getItemType(curItem); valuesToParse.pop_back(); if (curItemType == ItemType::eDictionary) { size_t numChildren = dict->getItemChildCount(curItem); ElementData elementData = onItemFn(curItem, valueToParse.elementData, userData); for (size_t chIdx = 0; chIdx < numChildren; ++chIdx) { valuesToParse.push_back({ getChildByIndexFunc(dict, curItem, numChildren - chIdx - 1), elementData }); } } else { onItemFn(curItem, valueToParse.elementData, userData); } } } /** Attempts to retrieve the name of an item from a given path in a dictionary. * * @param[in] dict The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p baseItem. * @param[in] baseItem The base item to retrieve the item name relative to. This is expected * to contain the child path @p path. This may not be `nullptr`. * @param[in] path The item path relative to @p baseItem that indicates where to find the * item whose name should be retrieved. This may be `nullptr` to retrieve * the name of @p baseItem itself. * @returns A string containing the name of the item at the given path relative to @p baseItem * if it exists. Returns an empty string if no item could be found at the requested * path or a string buffer could not be allocated for its name. * * @thread_safety This call is thread safe. */ inline std::string getStringFromItemName(const IDictionary* dict, const Item* baseItem, const char* path = nullptr) { const Item* item = dict->getItem(baseItem, path); if (!item) { return std::string(); } const char* itemNameBuf = dict->createStringBufferFromItemName(item); std::string returnString = itemNameBuf; dict->destroyStringBuffer(itemNameBuf); return returnString; } /** Attempts to retrieve the value of an item from a given path in a dictionary. * * @param[in] dict The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p baseItem. * @param[in] baseItem The base item to retrieve the item value relative to. This is expected * to contain the child path @p path. This may not be `nullptr`. * @param[in] path The item path relative to @p baseItem that indicates where to find the * item whose value should be retrieved. This may be `nullptr` to retrieve * the value of @p baseItem itself. * @returns A string containing the value of the item at the given path relative to @p baseItem * if it exists. If the requested item was not of type @ref ItemType::eString, the * value will be converted to a string as best it can. Returns an empty string if no * item could be found at the requested path or a string buffer could not be allocated * for its name. * * @thread_safety This call is thread safe. */ inline std::string getStringFromItemValue(const IDictionary* dict, const Item* baseItem, const char* path = nullptr) { const Item* item = dict->getItem(baseItem, path); if (!item) { return std::string(); } const char* stringBuf = dict->createStringBufferFromItemValue(item); std::string returnString = stringBuf; dict->destroyStringBuffer(stringBuf); return returnString; } /** Attempts to retrieve an array of string values from a given dictionary path. * * @param[in] dict The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p baseItem. * @param[in] baseItem The base item to retrieve the item values relative to. This is expected * to contain the child path @p path. This may not be `nullptr`. * @param[in] path The item path relative to @p baseItem that indicates where to find the * item whose value should be retrieved. This may be `nullptr` to retrieve * the values of @p baseItem itself. The value at this path is expected to * be an array of strings. * @returns A vector of string values for the array at the path @p path relative to @p baseItem. * If the given path is not an array item, a vector containing a single value will be * returned. If @p path points to an item that is an array of something other than * strings, a vector of empty strings will be returned instead. * * @thread_safety This call in itself is thread safe, however the retrieved array may contain * unexpected or incorrect values if another thread is modifying the same item * in the dictionary simultaneously. */ inline std::vector<std::string> getStringArray(const IDictionary* dict, const Item* baseItem, const char* path) { const Item* itemAtKey = dict->getItem(baseItem, path); std::vector<std::string> stringArray(dict->getArrayLength(itemAtKey)); for (size_t i = 0; i < stringArray.size(); i++) { stringArray[i] = dict->getStringBufferAt(itemAtKey, i); } return stringArray; } /** Attempts to retrieve an array of string values from a given dictionary path. * * @param[in] dict The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p baseItem. * @param[in] item The base item to retrieve the item values relative to. This is expected * to contain the child path @p path. This may not be `nullptr`. * @returns A vector of string values for the array at the path @p path relative to @p baseItem. * If the given path is not an array item, a vector containing a single value will be * returned. If @p path points to an item that is an array of something other than * strings, a vector of empty strings will be returned instead. * * @thread_safety This call in itself is thread safe, however the retrieved array may contain * unexpected or incorrect values if another thread is modifying the same item * in the dictionary simultaneously. */ inline std::vector<std::string> getStringArray(const IDictionary* dict, const Item* item) { return getStringArray(dict, item, nullptr); } /** Sets an array of values at a given path relative to a dictionary item. * * @param[in] dict The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p baseItem. * @param[in] baseItem The base item to act as the root of where to set the values relative * to. This is expected to contain the child path @p path. This may not * be `nullptr`. * @param[in] path The path to the item to set the array of strings in. This path must * either already exist as an array of strings or be an empty item in the * dictionary. This may be `nullptr` to set the string array into the * item @p baseItem itself. * @param[in] stringArray The array of strings to set in the dictionary. This may contain a * different number of items than the existing array. If the number of * items differs, this new array of values will replace the existing * item at @p path entirely. If the count is the same as the previous * item, values will simply be replaced. * @returns No return value. * * @thread_safety This call itself is thread safe as long as no other call is trying to * concurrently modify the same item in the dictionary. Results are undefined * if another thread is modifying the same item in the dictionary. Similarly, * undefined behavior may result if another thread is concurrently trying to * retrieve the items from this same dictionary. */ inline void setStringArray(IDictionary* dict, Item* baseItem, const char* path, const std::vector<std::string>& stringArray) { Item* itemAtKey = dict->getItemMutable(baseItem, path); if (dict->getItemType(itemAtKey) != dictionary::ItemType::eCount) { dict->destroyItem(itemAtKey); } for (size_t i = 0, stringCount = stringArray.size(); i < stringCount; ++i) { dict->setStringAt(itemAtKey, i, stringArray[i].c_str()); } } /** Sets an array of values at a given path relative to a dictionary item. * * @param[in] dict The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p baseItem. * @param[in] item The base item to act as the root of where to set the values relative * to. This is expected to contain the child path @p path. This may not * be `nullptr`. * @param[in] stringArray The array of strings to set in the dictionary. This may contain a * different number of items than the existing array. If the number of * items differs, this new array of values will replace the existing * item at @p path entirely. If the count is the same as the previous * item, values will simply be replaced. * @returns No return value. * * @thread_safety This call itself is thread safe as long as no other call is trying to * concurrently modify the same item in the dictionary. Results are undefined * if another thread is modifying the same item in the dictionary. Similarly, * undefined behavior may result if another thread is concurrently trying to * retrieve the items from this same dictionary. */ inline void setStringArray(IDictionary* dict, Item* item, const std::vector<std::string>& stringArray) { setStringArray(dict, item, nullptr, stringArray); } /** Attempts to set a value in a dictionary with an attempt to detect the value type. * * @param[in] id The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p dict. * @param[in] dict The base item to act as the root of where to set the value relative * to. This may not be `nullptr`. * @param[in] path The path to the item to set the value in. This path does not need to * exist yet in the dictionary. This may be `nullptr` to create the new * value in the @p dict item itself. * @param[in] value The new value to set expressed as a string. An attempt will be made to * detect the type of the data from the contents of the string. If there * are surrounding quotation marks, it will be treated as a string. If the * value is a case insensitive variant on `FALSE` or `TRUE`, it will be * treated as a boolean value. If the value fully converts to an integer or * floating point value, it will be treated as those types. Otherwise the * value is stored unmodified as a string. * @returns No return value. * * @thread_safety This call is thread safe. */ inline void setDictionaryElementAutoType(IDictionary* id, Item* dict, const std::string& path, const std::string& value) { if (!path.empty()) { // We should validate that provided path is a proper path but for now we just use it // // Simple rules to support basic values: // if the value starts and with quotes (" or ') then it's the string inside the quotes // else if we can parse the value as a bool, int or float then we read it // according to the type. Otherwise we consider it to be a string. // Special case, if the string is empty, write an empty string early if (value.empty()) { constexpr const char* kEmptyString = ""; id->makeStringAtPath(dict, path.c_str(), kEmptyString); return; } if (value.size() > 1 && ((value.front() == '"' && value.back() == '"') || (value.front() == '\'' && value.back() == '\''))) { // string value - chop off quotes id->makeStringAtPath(dict, path.c_str(), value.substr(1, value.size() - 2).c_str()); return; } // Convert the value to upper case to simplify checks std::string uppercaseValue = value; std::transform(value.begin(), value.end(), uppercaseValue.begin(), [](const char c) { return static_cast<char>(::toupper(c)); }); // let's see if it's a boolean if (uppercaseValue == "TRUE") { id->makeBoolAtPath(dict, path.c_str(), true); return; } if (uppercaseValue == "FALSE") { id->makeBoolAtPath(dict, path.c_str(), false); return; } // let's see if it's an integer size_t valueLen = value.length(); char* endptr; // Use a radix of 0 to allow for decimal, octal, and hexadecimal values to all be parsed. const long long int valueAsInt = strtoll(value.c_str(), &endptr, 0); if (endptr - value.c_str() == (ptrdiff_t)valueLen) { id->makeInt64AtPath(dict, path.c_str(), valueAsInt); return; } // let's see if it's a float const double valueAsFloat = strtod(value.c_str(), &endptr); if (endptr - value.c_str() == (ptrdiff_t)valueLen) { id->makeFloat64AtPath(dict, path.c_str(), valueAsFloat); return; } // consider the value to be a string even if it's empty id->makeStringAtPath(dict, path.c_str(), value.c_str()); } } /** Sets a series of values in a dictionary based on keys and values in a map object. * * @param[in] id The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p dict. * @param[in] dict The base item to act as the root of where to set the values relative * to. This may not be `nullptr`. * @param[in] mapping A map containing item paths (as the map keys) and their values to be * set in the dictionary. * @returns No return value. * * @remarks This takes a map of path and value pairs and sets those values into the given * dictionary @p dict. Each entry in the map identifies a potential new value to * create in the dictionary. The paths to each of the new values do not have to * already exist in the dictionary. The new items will be created as needed. If * a given path already exists in the dictionary, its value is replaced with the * one from the map. All values will attempt to auto-detect their type based on * the content of the string value. See setDictionaryElementAutoType() for more * info on how the types are detected. * * @note If the map contains entries for an array and the array also exists in the dictionary, * the resulting dictionary could have more or fewer elements in the array entries if the * map either contained fewer items than the previous array's size or contained a * non-consecutive set of numbered elements in the array. If the array already exists in * the dictionary, it will not be destroyed or removed before adding the new values. * * @thread_safety This itself operation is thread safe, but a race condition may still exist * if multiple threads are trying to set the values for the same set of items * simultaneously. The operation will succeed, but the value that gets set in * each item in the end is undefined. */ inline void setDictionaryFromStringMapping(IDictionary* id, Item* dict, const std::map<std::string, std::string>& mapping) { for (const auto& kv : mapping) { setDictionaryElementAutoType(id, dict, kv.first, kv.second); } } /** Parses a set of command line arguments for dictionary items arguments and sets them. * * @param[in] id The @ref IDictionary interface to use to access the items in the * dictionary. This must not be `nullptr`. This must be the same * interface that was originally used to create the dictionary * @p dict. * @param[in] dict The base item to act as the root of where to set the values relative * to. This may not be `nullptr`. * @param[in] argv The Unix style argument array for the command line to the process. This * must not be `nullptr`. The first entry in this array is expected to be * the process's name. Only the arguments starting with @p prefix will be * parsed here. * @param[in] argc The Unix style argument count for the total number of items in @p argv * to parse. * @param[in] prefix A string indicating the prefix of arguments that should be parsed by this * operation. This may not be `nullptr`. Arguments that do not start with * this prefix will simply be ignored. * @returns No return value. * * @remarks This parses command line arguments to find ones that should be added to a settings * dictionary. Only arguments beginning with the given prefix will be added. The * type of each individual item added to the dictionary will be automatically detected * based on the same criteria used for setDictionaryElementAutoType(). * * @thread_safety This operation itself is thread safe, but a race condition may still exist * if multiple threads are trying to set the values for the same set of items * simultaneously. The operation will succeed, but the value that gets set in * each item in the end is undefined. */ inline void setDictionaryFromCmdLine(IDictionary* id, Item* dict, char** argv, int argc, const char* prefix = "--/") { carb::extras::CmdLineParser cmdLineParser(prefix); cmdLineParser.parse(argv, argc); const std::map<std::string, std::string>& opts = cmdLineParser.getOptions(); setDictionaryFromStringMapping(id, dict, opts); } /** Parses a string representation of an array and sets it relative to a dictionary path. * * @param[in] dictionaryInterface The @ref IDictionary interface to use to access the items in * the dictionary. This must not be `nullptr`. This must be the * same interface that was originally used to create the * dictionary @p targetDictionary. * @param[in] targetDictionary The base item to act as the root of where to set the values * relative to. This may not be `nullptr`. * @param[in] elementPath The path to the item to set the values in. This path does not * need to exist yet in the dictionary. This may be an empty * string to create the new values in the @p dict item itself. * Any item at this path will be completely overwritten by this * operation. * @param[in] elementValue The string containing the values to parse for the new array * value. These are expected to be expressed in the format * "[<value1>, <value2>, <value3>, ...]" (ie: all values enclosed * in a single set of square brackets with each individual value * separated by commas). Individual value strings may not * contain a comma (even if escaped or surrounded by quotation * marks) otherwise they will be seen as separate values and * likely not set appropriately in the dictionary. This must * not be an empty string and must contain at least the square * brackets at either end of the string. * @returns No return value. * * @remarks This parses an array of values from a string into a dictionary array item. The array * string is expected to have the format "[<value1>, <value2>, <value3>, ...]". Quoted * values are not respected if they contain internal commas (the comma is still seen as * a value separator in this case). Each value parsed from the array will be set in the * dictionary item with its data type detected from its content. This detection is done * in the same manner as in setDictionaryElementAutoType(). * * @thread_safety This call itself is thread safe. However, if another thread is simultaneously * attempting to modify, retrieve, or delete items or values in the same branch of * the dictionary, the results may be undefined. */ inline void setDictionaryArrayElementFromStringValue(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() == ']'); // Force delete item if it exists before creating a new array dictionary::Item* arrayItem = dictionaryInterface->getItemMutable(targetDictionary, elementPath.c_str()); if (arrayItem) { dictionaryInterface->destroyItem(arrayItem); } // Creating a new dictionary element at the required path arrayItem = dictionaryInterface->makeDictionaryAtPath(targetDictionary, elementPath.c_str()); // Setting necessary flag to make it a proper empty array // This will result in correct item replacement in case of dictionary merging dictionaryInterface->setItemFlag(arrayItem, dictionary::ItemFlag::eUnitSubtree, true); // Skip initial and the last square brackets and consider all elements separated by commas one by one // For each value create corresponding new path including index // Ex. "/some/path=[10,20]" will be processed as "/some/path/0=10" and "/some/path/1=20" const std::string commonElementPath = elementPath + '/'; size_t curElementIndex = 0; // Helper adds provided value into the dictionary and increases index for the next addition auto dictElementAddHelper = [&](std::string value) { carb::extras::trimStringInplace(value); // Processing only non empty strings, empty string values should be stated as "": [ "a", "", "b" ] if (value.empty()) { CARB_LOG_WARN( "Encountered and skipped an empty value for dictionary array element '%s' while parsing value '%s'", elementPath.c_str(), elementValue.c_str()); return; } carb::dictionary::setDictionaryElementAutoType( dictionaryInterface, targetDictionary, commonElementPath + std::to_string(curElementIndex), value); ++curElementIndex; }; std::string::size_type curValueStartPos = 1; // Add comma-separated values (except for the last one) for (std::string::size_type curCommaPos = elementValue.find(',', curValueStartPos); curCommaPos != std::string::npos; curCommaPos = elementValue.find(',', curValueStartPos)) { dictElementAddHelper(elementValue.substr(curValueStartPos, curCommaPos - curValueStartPos)); curValueStartPos = curCommaPos + 1; } // Now only the last value is left for addition std::string lastValue = elementValue.substr(curValueStartPos, elementValue.size() - curValueStartPos - 1); carb::extras::trimStringInplace(lastValue); // Do nothing if it's just a trailing comma: [ 1, 2, 3, ] if (!lastValue.empty()) { carb::dictionary::setDictionaryElementAutoType( dictionaryInterface, targetDictionary, commonElementPath + std::to_string(curElementIndex), lastValue); } } /** Attempts to read the contents of a file into a dictionary. * * @param[in] serializer The @ref ISerializer interface to use to parse the data in the file. * This serializer must be able to parse the assumed format of the named * file (ie: JSON or TOML). This must not be `nullptr`. Note that this * interface will internally depend on only a single implementation of * the @ref IDictionary interface having been loaded. If multiple * implementations are available, this operation will be likely to * result in undefined behavior. * @param[in] filename The name of the file to parse in the format assumed by the serializer * interface @p serializer. This must not be `nullptr`. * @returns A new dictionary item containing the information parsed from the file @p filename if * it is successfully opened, read, and parsed. When no longer needed, this must be * passed to @ref IDictionary::destroyItem() to destroy it. Returns `nullptr` if the * file does not exit, could not be opened, or a parsing error occurred. * * @remarks This attempts to parse a dictionary data from a file. The format that the file's * data is parsed from will be implied by the specific implementation of the @ref * ISerializer interface that is passed in. The data found in the file will be parsed * into a full dictionary hierarchy if it is parsed correctly. If the file contains * a syntax error, the specific result (ie: full failure vs partial success) is * determined by the specific behavior of the @ref ISerializer interface. * * @thread_safety This operation is thread safe. */ inline Item* createDictionaryFromFile(ISerializer* serializer, const char* filename) { carb::filesystem::IFileSystem* fs = carb::getCachedInterface<carb::filesystem::IFileSystem>(); auto file = fs->openFileToRead(filename); if (!file) return nullptr; const size_t fileSize = fs->getFileSize(file); const size_t contentLen = fileSize + 1; std::unique_ptr<char[]> heap; char* content; if (contentLen <= 4096) { content = CARB_STACK_ALLOC(char, contentLen); } else { heap.reset(new char[contentLen]); content = heap.get(); } const size_t readBytes = fs->readFileChunk(file, content, contentLen); fs->closeFile(file); if (readBytes != fileSize) { CARB_LOG_ERROR("Only read %zu bytes of a total of %zu bytes from file '%s'", readBytes, fileSize, filename); } // NUL terminate content[readBytes] = '\0'; return serializer->createDictionaryFromStringBuffer(content, readBytes, fDeserializerOptionInSitu); } /** Writes the contents of a dictionary to a file. * * @param[in] serializer The @ref ISerializer interface to use to format the dictionary * data before writing it to file. This may not be `nullptr`. * @param[in] dictionary The dictionary root item to format and write to file. This * not be `nullptr`. This must have been created by the same * @ref IDictionary interface that @p serializer uses internally. * @param[in] filename The name of the file to write the formatted dictionary data * to. This file will be unconditionally overwritten. It is the * caller's responsibility to ensure any previous file at this * location can be safely overwritten. This must not be * `nullptr`. * @param[in] serializerOptions Option flags passed to the @p serializer interface when * formatting the dictionary data. * @returns No return value. * * @remarks This formats the contents of a dictionary to a string and writes it to a file. The * file will be formatted according to the serializer interface that is used. The * extra flag options passed to the serializer in @p serializerOptions control the * specifics of the formatting. The formatted data will be written to the file as * long as it can be opened successfully for writing. * * @thread_safety This operation itself is thread safe. However, if another thread is attempting * to modify the dictionary @p dictionary at the same time, a race condition may * exist and undefined behavior could occur. It won't crash but the written data * may be unexpected. */ inline void saveFileFromDictionary(ISerializer* serializer, const dictionary::Item* dictionary, const char* filename, SerializerOptions serializerOptions) { const char* serializedString = serializer->createStringBufferFromDictionary(dictionary, serializerOptions); filesystem::IFileSystem* fs = getFramework()->acquireInterface<filesystem::IFileSystem>(); filesystem::File* sFile = fs->openFileToWrite(filename); if (sFile == nullptr) { CARB_LOG_ERROR("failed to open file '%s' - unable to save the dictionary", filename); return; } fs->writeFileChunk(sFile, serializedString, strlen(serializedString)); fs->closeFile(sFile); serializer->destroyStringBuffer(serializedString); } /** Writes a dictionary to a string. * * @param[in] c The dictionary to be serialized. This must not be `nullptr`. * This dictionary must have been created by the same dictionary * interface that the serializer will use. The serializer that is * used controls how the string is formatted. * @param[in] serializerName The name of the serializer plugin to use. This must be the name * of the serializer plugin to be potentially loaded and used. For * example, "carb.dictionary.serializer-json.plugin" to serialize to * use the JSON serializer. The serializer plugin must already be * known to the framework. This may be `nullptr` to pick the first * or best serializer plugin instead. If the serializer plugin with * this name cannot be found or the @ref ISerializer interface * cannot be acquired from it, the first loaded serializer interface * will be acquired and used instead. * @returns A string containing the human readable contents of the dictionary @p c. If the * dictionary failed to be written, an empty string will be returned but the operation * will still be considered successful. The dictionary will always be formatted using * the @ref fSerializerOptionMakePretty flag so that it is as human-readable as * possible. * * @thread_safety This operation itself is thread safe. However, if the dictionary @p c is * being modified concurrently by another thread, the output contents may be * unexpected. */ inline std::string dumpToString(const dictionary::Item* c, const char* serializerName = nullptr) { std::string serializedDictionary; Framework* framework = carb::getFramework(); dictionary::ISerializer* configSerializer = nullptr; // First, try to acquire interface with provided plugin name, if any if (serializerName) { configSerializer = framework->tryAcquireInterface<dictionary::ISerializer>(serializerName); } // If not available, or plugin name is not provided, try to acquire any serializer interface if (!configSerializer) { configSerializer = framework->tryAcquireInterface<dictionary::ISerializer>(); } const char* configString = configSerializer->createStringBufferFromDictionary(c, dictionary::fSerializerOptionMakePretty); if (configString != nullptr) { serializedDictionary = configString; configSerializer->destroyStringBuffer(configString); } return serializedDictionary; }; /** Retrieves the full path to dictionary item from its top-most ancestor. * * @param[in] dict The @ref IDictionary interface to use to retrieve the full path to the * requested dictionary item. This must not be `nullptr`. * @param[in] item The dictionary item to retrieve the full path to. This may not be `nullptr`. * This item must have been created by the same @ref IDictionary interface passed * in as @p dict. * @returns A string containing the full path to the dictionary item @p item. This path will be * relative to its top-most ancestor. On failure, an empty string is returned. * * @thread_safety This operation itself is thread safe. However, if the item or its chain of * ancestors is being modified concurrently, undefined behavior may result. */ inline std::string getItemFullPath(dictionary::IDictionary* dict, const carb::dictionary::Item* item) { if (!item) { return std::string(); } std::vector<const char*> pathElementsNames; while (item) { pathElementsNames.push_back(dict->getItemName(item)); item = dict->getItemParent(item); } size_t totalSize = 0; for (const auto& elementName : pathElementsNames) { totalSize += 1; // the '/' separator if (elementName) { totalSize += std::strlen(elementName); } } std::string result; result.reserve(totalSize); for (size_t idx = 0, elementCount = pathElementsNames.size(); idx < elementCount; ++idx) { const char* elementName = pathElementsNames[elementCount - idx - 1]; result += '/'; if (elementName) { result += elementName; } } return result; } /** Helper function to convert a data type to a corresponding dictionary item type. * * @tparam Type The primitive data type to convert to a dictionary item type. This operation * is undefined for types other than the handful of primitive types it is * explicitly specialized for. If a another data type is used here, a link * link error will occur. * @returns The dictionary item type corresponding to the templated primitive data type. * * @thread_safety This operation is thread safe. */ template <typename Type> inline ItemType toItemType(); /** Specialization for an `int32_t` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<int32_t>() { return ItemType::eInt; } /** Specialization for an `int64_t` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<int64_t>() { return ItemType::eInt; } /** Specialization for an `float` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<float>() { return ItemType::eFloat; } /** Specialization for an `double` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<double>() { return ItemType::eFloat; } /** Specialization for an `bool` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<bool>() { return ItemType::eBool; } /** Specialization for an `char*` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<char*>() { return ItemType::eString; } /** Specialization for an `const char*` item value. * @copydoc toItemType(). */ template <> inline ItemType toItemType<const char*>() { return ItemType::eString; } /** Unsubscribes all items in a dictionary tree from change notifications. * * @param[in] dict The @ref IDictionary interface to use when walking the dictionary. This must * not be `nullptr`. This must be the same @ref IDictionary interface that was * used to create the dictionary item @p item. * @param[in] item The dictionary item to unsubscribe all nodes from change notifications. This * must not be `nullptr`. Each item in this dictionary's tree will have all of * its tree and node change subscriptions removed. * @returns No return value. * * @remarks This removes all change notification subscriptions for an entire tree in a * dictionary. This should only be used as a last cleanup effort to prevent potential * shutdown crashes since it will even remove subscriptions that the caller didn't * necessarily setup. * * @thread_safety This operation is thread safe. */ inline void unsubscribeTreeFromAllEvents(IDictionary* dict, Item* item) { auto unsubscribeItem = [](Item* srcItem, uint32_t elementData, void* userData) -> uint32_t { IDictionary* dict = (IDictionary*)userData; dict->unsubscribeItemFromNodeChangeEvents(srcItem); dict->unsubscribeItemFromTreeChangeEvents(srcItem); return elementData; }; const auto getChildByIndexMutable = [](IDictionary* dict, Item* item, size_t index) { return dict->getItemChildByIndexMutable(item, index); }; walkDictionary(dict, WalkerMode::eIncludeRoot, item, 0, unsubscribeItem, dict, getChildByIndexMutable); } /** Helper function for IDictionary::update() that ensures arrays are properly overwritten. * * @param[in] dstItem The destination dictionary item for the merge operation. This * may be `nullptr` if the destination item doesn't already exist * in the tree (ie: a new item is being merged into the tree). * @param[in] dstItemType The data type of the item @p dstItem. If @p dstItem is * `nullptr`, this will be @ref ItemType::eCount. * @param[in] srcItem The source dictionary item for the merge operation. This will * never be `nullptr`. This will be the new value or node that * is being merged into the dictionary tree. * @param[in] srcItemType The data type of the item @p srcItem. * @param[in] dictionaryInterface The @ref IDictionary interface to use when merging the new * item into the dictionary tree. This is expected to be passed * into the @a userData parameter for IDictionary::update(). * @returns an @ref UpdateAction value indicating how the merge operation should proceed. * * @remarks This is intended to be used as the @ref OnUpdateItemFn callback function for the * @ref IDictionary::update() function when the handling of merging array items is * potentially needed. When this is used, the @ref IDictionary interface object must * be passed into the @a userData parameter of IDictionary::update(). * * @thread_safety This operation is thread safe. However, this call isn't expected to be used * directly, but rather through the IDictionary::update() function. The overall * thread safety of that operation should be noted instead. */ inline UpdateAction overwriteOriginalWithArrayHandling( const Item* dstItem, ItemType dstItemType, const Item* srcItem, ItemType srcItemType, void* dictionaryInterface) { CARB_UNUSED(dstItemType, srcItemType); if (dstItem && dictionaryInterface) { carb::dictionary::IDictionary* dictInt = static_cast<carb::dictionary::IDictionary*>(dictionaryInterface); if (dictInt->getItemFlag(srcItem, carb::dictionary::ItemFlag::eUnitSubtree)) { return carb::dictionary::UpdateAction::eReplaceSubtree; } } return carb::dictionary::UpdateAction::eOverwrite; } } // namespace dictionary } // namespace carb
53,296
C
49.904489
124
0.627402
omniverse-code/kit/include/carb/dictionary/DictionaryBindingsPython.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 "../cpp/Optional.h" #include "DictionaryUtils.h" #include "IDictionary.h" #include "ISerializer.h" #include <memory> #include <vector> namespace carb { namespace dictionary { struct Item { }; } // namespace dictionary } // namespace carb namespace carb { namespace dictionary { template <typename T> inline py::tuple toTuple(const std::vector<T>& v) { py::tuple tuple(v.size()); for (size_t i = 0; i < v.size(); i++) tuple[i] = v[i]; return tuple; } // Prerequisites: dictionary lock must be held followed by GIL inline py::object getPyObjectLocked(dictionary::ScopedRead& lock, const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path = "") { CARB_ASSERT(baseItem); const Item* item = path && *path != '\0' ? idictionary->getItem(baseItem, path) : baseItem; ItemType itemType = idictionary->getItemType(item); switch (itemType) { case ItemType::eInt: { return py::int_(idictionary->getAsInt64(item)); } case ItemType::eFloat: { return py::float_(idictionary->getAsFloat64(item)); } case ItemType::eBool: { return py::bool_(idictionary->getAsBool(item)); } case ItemType::eString: { return py::str(getStringFromItemValue(idictionary, item)); } case ItemType::eDictionary: { size_t const arrayLength = idictionary->getArrayLength(item); if (arrayLength > 0) { py::tuple v(arrayLength); bool needsList = false; for (size_t idx = 0; idx != arrayLength; ++idx) { v[idx] = getPyObjectLocked(lock, idictionary, idictionary->getItemChildByIndex(item, idx)); if (py::isinstance<py::dict>(v[idx])) { // The old code would return a list of dictionaries, but a tuple of everything else. *shrug* needsList = true; } } if (needsList) { return py::list(std::move(v)); } return v; } else { size_t childCount = idictionary->getItemChildCount(item); py::dict v; for (size_t idx = 0; idx < childCount; ++idx) { const dictionary::Item* childItem = idictionary->getItemChildByIndex(item, idx); if (childItem) { v[idictionary->getItemName(childItem)] = getPyObjectLocked(lock, idictionary, childItem); } } return v; } } default: return py::none(); } } inline py::object getPyObject(const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path = "") { if (!baseItem) { return py::none(); } // We need both the dictionary lock and the GIL, but we should take the GIL last, so release the GIL temporarily, // grab the dictionary lock and then re-lock the GIL by resetting the optional<>. cpp::optional<py::gil_scoped_release> nogil{ cpp::in_place }; dictionary::ScopedRead readLock(*idictionary, baseItem); nogil.reset(); return getPyObjectLocked(readLock, idictionary, baseItem, path); } inline void setPyObject(dictionary::IDictionary* idictionary, Item* baseItem, const char* path, const py::handle& value) { auto createDict = [](dictionary::IDictionary* idictionary, Item* baseItem, const char* path, const py::handle& 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(); setPyObject(idictionary, baseItem, subPath.c_str(), kv.second); } }; if (py::isinstance<py::bool_>(value)) { auto val = value.cast<bool>(); py::gil_scoped_release nogil; idictionary->makeBoolAtPath(baseItem, path, val); } else if (py::isinstance<py::int_>(value)) { auto val = value.cast<int64_t>(); py::gil_scoped_release nogil; idictionary->makeInt64AtPath(baseItem, path, val); } else if (py::isinstance<py::float_>(value)) { auto val = value.cast<double>(); py::gil_scoped_release nogil; idictionary->makeFloat64AtPath(baseItem, path, val); } else if (py::isinstance<py::str>(value)) { auto val = value.cast<std::string>(); py::gil_scoped_release nogil; idictionary->makeStringAtPath(baseItem, path, val.c_str()); } else if (py::isinstance<py::tuple>(value) || py::isinstance<py::list>(value)) { Item* item; py::sequence valueSeq = value.cast<py::sequence>(); { py::gil_scoped_release nogil; item = idictionary->makeDictionaryAtPath(baseItem, path); idictionary->deleteChildren(item); } 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; idictionary->setBoolAt(item, idx, val); } else if (py::isinstance<py::int_>(valueSeqElement)) { auto val = valueSeqElement.cast<int64_t>(); py::gil_scoped_release nogil; idictionary->setInt64At(item, idx, val); } else if (py::isinstance<py::float_>(valueSeqElement)) { auto val = valueSeqElement.cast<double>(); py::gil_scoped_release nogil; idictionary->setFloat64At(item, idx, val); } else if (py::isinstance<py::str>(valueSeqElement)) { auto val = valueSeqElement.cast<std::string>(); py::gil_scoped_release nogil; idictionary->setStringAt(item, idx, val.c_str()); } else if (py::isinstance<py::dict>(valueSeqElement)) { std::string basePath = path ? path : ""; std::string elemPath = basePath + "/" + std::to_string(idx); createDict(idictionary, baseItem, elemPath.c_str(), valueSeqElement); } else { CARB_LOG_WARN("Unknown type in sequence being written to item"); } } } else if (py::isinstance<py::dict>(value)) { createDict(idictionary, baseItem, path, value); } } inline carb::dictionary::IDictionary* getDictionary() { return getCachedInterfaceForBindings<carb::dictionary::IDictionary>(); } inline void definePythonModule(py::module& m) { using namespace carb; using namespace carb::dictionary; m.doc() = "pybind11 carb.dictionary bindings"; py::enum_<ItemType>(m, "ItemType") .value("BOOL", ItemType::eBool) .value("INT", ItemType::eInt) .value("FLOAT", ItemType::eFloat) .value("STRING", ItemType::eString) .value("DICTIONARY", ItemType::eDictionary) .value("COUNT", ItemType::eCount); py::enum_<UpdateAction>(m, "UpdateAction").value("OVERWRITE", UpdateAction::eOverwrite).value("KEEP", UpdateAction::eKeep); py::class_<Item>(m, "Item") .def("__getitem__", [](const Item& self, const char* path) { return getPyObject(getDictionary(), &self, path); }) .def("__setitem__", [](Item& self, const char* path, py::object value) { setPyObject(getDictionary(), &self, path, value); }) .def("__len__", [](Item& self) { return getDictionary()->getItemChildCount(&self); }, py::call_guard<py::gil_scoped_release>()) .def("get", [](const Item& self, const char* path, py::object defaultValue) { py::object v = getPyObject(getDictionary(), &self, path); return v.is_none() ? defaultValue : v; }) .def("get_key_at", [](const Item& self, size_t index) -> py::object { cpp::optional<std::string> name; { py::gil_scoped_release nogil; dictionary::ScopedRead readlock(*getDictionary(), &self); auto child = getDictionary()->getItemChildByIndex(&self, index); if (child) name.emplace(getDictionary()->getItemName(child)); } if (name) return py::str(name.value()); return py::none(); }) .def("__contains__", [](const Item& self, py::object value) -> bool { auto name = value.cast<std::string>(); py::gil_scoped_release nogil; dictionary::ScopedRead readlock(*getDictionary(), &self); ItemType type = getDictionary()->getItemType(&self); if (type != ItemType::eDictionary) return false; return getDictionary()->getItem(&self, name.c_str()) != nullptr; }) .def("get_keys", [](const Item& self) { IDictionary* idictionary = getDictionary(); dictionary::ScopedRead readlock(*idictionary, &self); std::vector<std::string> keys(idictionary->getItemChildCount(&self)); for (size_t i = 0; i < keys.size(); i++) { const Item* child = idictionary->getItemChildByIndex(&self, i); if (child) keys[i] = idictionary->getItemName(child); } return keys; }, py::call_guard<py::gil_scoped_release>()) .def("clear", [](Item& self) { getDictionary()->deleteChildren(&self); }, py::call_guard<py::gil_scoped_release>()) .def("get_dict", [](Item& self) { return getPyObject(getDictionary(), &self, nullptr); }) .def("__str__", [](Item& self) { return py::str(getPyObject(getDictionary(), &self, nullptr)); }) .def("__repr__", [](Item& self) { return py::str("carb.dictionary.Item({0})").format(getPyObject(getDictionary(), &self, nullptr)); }); using UpdateFunctionWrapper = ScriptCallbackRegistryPython<void*, dictionary::UpdateAction, const dictionary::Item*, dictionary::ItemType, const dictionary::Item*, dictionary::ItemType>; defineInterfaceClass<IDictionary>(m, "IDictionary", "acquire_dictionary_interface") .def("get_dict_copy", getPyObject, R"( Creates python object from the supplied dictionary at path (supplied item is unchanged). Item is calculated via the path relative to the base item. Args: base_item: The base item. path: Path, relative to the base item - to the item Returns: Python object with copies of the item data.)", py::arg("base_item"), py::arg("path") = "") .def("get_item", wrapInterfaceFunction(&IDictionary::getItem), py::arg("base_item"), py::arg("path") = "", py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_item_mutable", wrapInterfaceFunction(&IDictionary::getItemMutable), py::arg("base_item"), py::arg("path") = "", py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_item_child_count", wrapInterfaceFunction(&IDictionary::getItemChildCount), py::call_guard<py::gil_scoped_release>()) .def("get_item_child_by_index", wrapInterfaceFunction(&IDictionary::getItemChildByIndex), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_item_child_by_index_mutable", wrapInterfaceFunction(&IDictionary::getItemChildByIndexMutable), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_item_parent", wrapInterfaceFunction(&IDictionary::getItemParent), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_item_parent_mutable", wrapInterfaceFunction(&IDictionary::getItemParentMutable), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("get_item_type", wrapInterfaceFunction(&IDictionary::getItemType), py::call_guard<py::gil_scoped_release>()) .def("get_item_name", [](const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path) { return getStringFromItemName(idictionary, baseItem, path); }, py::arg("base_item"), py::arg("path") = "", py::call_guard<py::gil_scoped_release>()) .def("create_item", [](const dictionary::IDictionary* idictionary, const py::object& item, const char* path, dictionary::ItemType itemType) { Item* p = item.is_none() ? nullptr : item.cast<Item*>(); py::gil_scoped_release nogil; return idictionary->createItem(p, path, itemType); }, py::return_value_policy::reference) .def("is_accessible_as", wrapInterfaceFunction(&IDictionary::isAccessibleAs), py::call_guard<py::gil_scoped_release>()) .def("is_accessible_as_array_of", wrapInterfaceFunction(&IDictionary::isAccessibleAsArrayOf), py::call_guard<py::gil_scoped_release>()) .def("get_array_length", wrapInterfaceFunction(&IDictionary::getArrayLength), py::call_guard<py::gil_scoped_release>()) .def("get_preferred_array_type", wrapInterfaceFunction(&IDictionary::getPreferredArrayType), py::call_guard<py::gil_scoped_release>()) .def("get_as_int", wrapInterfaceFunction(&IDictionary::getAsInt64), py::call_guard<py::gil_scoped_release>()) .def("set_int", wrapInterfaceFunction(&IDictionary::setInt64), py::call_guard<py::gil_scoped_release>()) .def("get_as_float", wrapInterfaceFunction(&IDictionary::getAsFloat64), py::call_guard<py::gil_scoped_release>()) .def("set_float", wrapInterfaceFunction(&IDictionary::setFloat64), py::call_guard<py::gil_scoped_release>()) .def("get_as_bool", wrapInterfaceFunction(&IDictionary::getAsBool), py::call_guard<py::gil_scoped_release>()) .def("set_bool", wrapInterfaceFunction(&IDictionary::setBool), py::call_guard<py::gil_scoped_release>()) .def("get_as_string", [](const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path) { return getStringFromItemValue(idictionary, baseItem, path); }, py::arg("base_item"), py::arg("path") = "", py::call_guard<py::gil_scoped_release>()) .def("set_string", [](dictionary::IDictionary* idictionary, Item* item, const std::string& str) { idictionary->setString(item, str.c_str()); }, py::call_guard<py::gil_scoped_release>()) .def("get", &getPyObject, py::arg("base_item"), py::arg("path") = "") .def("set", &setPyObject, py::arg("item"), py::arg("path") = "", py::arg("value")) .def("set_int_array", [](const dictionary::IDictionary* idictionary, Item* item, const std::vector<int64_t>& v) { idictionary->setInt64Array(item, v.data(), v.size()); }, py::call_guard<py::gil_scoped_release>()) .def("set_float_array", [](const dictionary::IDictionary* idictionary, Item* item, const std::vector<double>& v) { idictionary->setFloat64Array(item, v.data(), v.size()); }, py::call_guard<py::gil_scoped_release>()) .def("set_bool_array", [](const dictionary::IDictionary* idictionary, Item* item, const std::vector<bool>& v) { if (v.size() == 0) return; bool* pbool = CARB_STACK_ALLOC(bool, v.size()); for (size_t i = 0; i != v.size(); ++i) pbool[i] = v[i]; idictionary->setBoolArray(item, pbool, v.size()); }, py::call_guard<py::gil_scoped_release>()) .def("set_string_array", [](const dictionary::IDictionary* idictionary, Item* item, const std::vector<std::string>& v) { if (v.size() == 0) return; const char** pstr = CARB_STACK_ALLOC(const char*, v.size()); for (size_t i = 0; i != v.size(); ++i) pstr[i] = v[i].c_str(); idictionary->setStringArray(item, pstr, v.size()); }, py::call_guard<py::gil_scoped_release>()) .def("destroy_item", wrapInterfaceFunction(&IDictionary::destroyItem), py::call_guard<py::gil_scoped_release>()) .def("update", [](dictionary::IDictionary* idictionary, dictionary::Item* dstItem, const char* dstPath, const dictionary::Item* srcItem, const char* srcPath, 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) { idictionary->update(dstItem, dstPath, srcItem, srcPath, dictionary::overwriteOriginal, nullptr); } else if (updatePolicyEnum == dictionary::UpdateAction::eKeep) { idictionary->update(dstItem, dstPath, srcItem, srcPath, 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; idictionary->update( dstItem, dstPath, srcItem, srcPath, UpdateFunctionWrapper::call, (void*)&updateFn); } }) .def("readLock", wrapInterfaceFunction(&IDictionary::readLock), py::call_guard<py::gil_scoped_release>()) .def("writeLock", wrapInterfaceFunction(&IDictionary::writeLock), py::call_guard<py::gil_scoped_release>()) .def("unlock", wrapInterfaceFunction(&IDictionary::unlock), py::call_guard<py::gil_scoped_release>()); carb::defineInterfaceClass<ISerializer>(m, "ISerializer", "acquire_serializer_interface") .def("create_dictionary_from_file", &createDictionaryFromFile, py::arg("path"), py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("create_dictionary_from_string_buffer", [](ISerializer* self, std::string val) { return self->createDictionaryFromStringBuffer( val.data(), val.size(), carb::dictionary::fDeserializerOptionInSitu); }, py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()) .def("create_string_buffer_from_dictionary", [](ISerializer* self, const carb::dictionary::Item* dictionary, SerializerOptions serializerOptions) { const char* buf = self->createStringBufferFromDictionary(dictionary, serializerOptions); std::string ret = buf; // Copy self->destroyStringBuffer(buf); return ret; }, py::arg("item"), py::arg("ser_options") = 0, py::call_guard<py::gil_scoped_release>()) .def("save_file_from_dictionary", &saveFileFromDictionary, py::arg("dict"), py::arg("path"), py::arg("options") = 0, py::call_guard<py::gil_scoped_release>()); m.def("get_toml_serializer", []() { static ISerializer* s_serializer = carb::getFramework()->acquireInterface<ISerializer>("carb.dictionary.serializer-toml.plugin"); return s_serializer; }, py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()); m.def("get_json_serializer", []() { static ISerializer* s_serializer = carb::getFramework()->acquireInterface<ISerializer>("carb.dictionary.serializer-json.plugin"); return s_serializer; }, py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>()); } } // namespace dictionary } // namespace carb
22,161
C
45.170833
127
0.561076