MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
mxl::lib Namespace Reference

Namespaces

namespace  detail
namespace  fabrics
namespace  this_thread

Classes

class  ContinuousFlowData
class  ContinuousFlowReader
class  ContinuousFlowWriter
class  Deferred
 Helper class that is created by a call to. More...
class  DiscreteFlowData
class  DiscreteFlowReader
class  DiscreteFlowWriter
struct  DomainWatcherRecord
 Entry stored in the unordered_maps. More...
struct  Duration
struct  Event
 Fixed part of an event slot; its payload follows immediately in the mapping. More...
class  EventFlowData
 Own the common flow mapping, single event ring mapping and ring view. More...
class  EventFlowReader
 Backend contract for reading complete event entries or fragments in queue order. Each reader has one owning thread; concurrent consumers must use independent readers. More...
class  EventFlowWriter
 Backend contract for a single event producer with private write staging. Callers guarantee one writer per flow across all instances and processes, and serialize the complete open/edit/commit-or-cancel transaction. More...
struct  EventHeader
 768-byte slot header with layout fields, sequence and metadata on separate 128-byte boundaries. The fixed padding is part of the shared-memory ABI and must not depend on compiler CPU tuning. More...
class  EventRingBuffer
 Non-owning single-producer event ring view safe for concurrent snapshot readers. More...
struct  EventRingHeader
 Immutable 4 KiB geometry header at the start of the single event ring file. More...
struct  Flow
class  FlowData
class  FlowIoFactory
class  FlowManager
class  FlowOptionsParser
class  FlowParser
class  FlowReader
class  FlowReaderFactory
struct  FlowState
class  FlowSynchronizationGroup
class  FlowWriter
class  FlowWriterFactory
struct  Grain
struct  GrainHeader
class  Instance
struct  JsonLimits
 Limits applied by parseJson(). More...
class  PosixContinuousFlowReader
class  PosixContinuousFlowWriter
class  PosixDiscreteFlowReader
class  PosixDiscreteFlowWriter
class  PosixEventFlowReader
 POSIX event consumer with a single-thread cursor and an owned payload snapshot. More...
class  PosixEventFlowWriter
 POSIX single-producer writer with private staging and monotonic timestamps. The caller guarantees one writer per flow and serializes transactions; readers may run concurrently. More...
struct  PosixFlowIoFactory
class  SharedMemoryBase
struct  SharedMemoryInstance
struct  SharedMemorySegment
struct  Timepoint

Enumerations

enum class  AccessMode { READ_ONLY , READ_WRITE , CREATE_READ_WRITE }
enum class  Clock {
  Monotonic , Realtime , TAI , ProcessCPUTime ,
  ThreadCPUTime
}
enum class  LockMode { Exclusive , Shared , None }

Functions

void addFlow (FlowWriter *writer, uuids::uuid id)
constexpr Duration asDuration (std::timespec const &duration) noexcept
constexpr Timepoint asTimepoint (std::timespec const &timepoint) noexcept
constexpr std::timespec asTimeSpec (Duration duration) noexcept
constexpr std::timespec asTimeSpec (Timepoint timepoint) noexcept
std::size_t count (uuids::uuid id) const noexcept
 Returns the number of writers registered for flow id 'id'.
Timepoint currentTime (Clock clock) noexcept
Timepoint currentTimeUTC () noexcept
template<typename F>
constexpr Deferred< F > defer (F &&f) noexcept
 DomainWatcher (std::filesystem::path const &in_domain)
template<typename To, typename From>
std::unique_ptr< To > dynamic_pointer_cast (std::unique_ptr< From > &&source) noexcept
constexpr Duration fromMicroSeconds (double duration) noexcept
constexpr Duration fromMilliSeconds (double duration) noexcept
constexpr Duration fromSeconds (double duration) noexcept
std::uint32_t get10BitAlphaLineLength (std::size_t width)
std::uint32_t getV210LineLength (std::size_t width)
 if (lockMode !=LockMode::None &&mode !=AccessMode::READ_ONLY)
 if (struct stat statBuf;::fstat(_fd, &statBuf) !=-1)
constexpr Timepoint indexToTimestamp (mxlRational const &editRate, std::uint64_t index) noexcept
constexpr double inMicroSeconds (Duration duration) noexcept
constexpr double inMilliSeconds (Duration duration) noexcept
constexpr double inNanoSeconds (Duration duration) noexcept
constexpr double inSeconds (Duration duration) noexcept
template<std::integral T>
T jsonStringToInteger (picojson::value const &value, std::string_view name)
template<std::integral T>
T jsonToInteger (picojson::value const &value, std::string_view name)
std::filesystem::path makeChannelDataFilePath (std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeChannelDataFilePath (std::filesystem::path const &flowDirectory)
std::filesystem::path makeDomainOptionsFilePath (std::filesystem::path const &domain)
std::filesystem::path makeEventDataFilePath (std::filesystem::path const &flowDirectory)
 Locate an event ring file within its flow directory.
std::filesystem::path makeFlowAccessFilePath (std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeFlowAccessFilePath (std::filesystem::path const &flowDirectory)
std::filesystem::path makeFlowDataFilePath (std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeFlowDataFilePath (std::filesystem::path const &flowDirectory)
std::filesystem::path makeFlowDescriptorFilePath (std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeFlowDescriptorFilePath (std::filesystem::path const &flowDirectory)
std::filesystem::path makeFlowDirectoryName (std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeGrainDataFilePath (std::filesystem::path const &domain, std::string const &uuid, unsigned int index)
std::filesystem::path makeGrainDataFilePath (std::filesystem::path const &grainDirectory, unsigned int index)
std::filesystem::path makeGrainDirectoryName (std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeGrainDirectoryName (std::filesystem::path const &flowDirectory)
std::filesystem::path makelowAccessFilePath (std::filesystem::path const &domain, std::string const &uuid)
constexpr bool operator!= (Duration lhs, Duration rhs) noexcept
constexpr bool operator!= (Timepoint lhs, Timepoint rhs) noexcept
constexpr Duration operator* (Duration lhs, int rhs) noexcept
constexpr Duration operator* (int lhs, Duration rhs) noexcept
constexpr Duration operator+ (Duration lhs, Duration rhs) noexcept
constexpr Timepoint operator+ (Timepoint lhs, Duration rhs) noexcept
constexpr Duration operator- (Duration lhs, Duration rhs) noexcept
constexpr Timepoint operator- (Timepoint lhs, Duration rhs) noexcept
constexpr Duration operator- (Timepoint lhs, Timepoint rhs) noexcept
constexpr Duration operator/ (Duration lhs, int rhs) noexcept
constexpr bool operator< (Duration lhs, Duration rhs) noexcept
constexpr bool operator< (Timepoint lhs, Timepoint rhs) noexcept
std::ostream & operator<< (std::ostream &os, Grain const &obj)
constexpr bool operator<= (Duration lhs, Duration rhs) noexcept
constexpr bool operator<= (Timepoint lhs, Timepoint rhs) noexcept
constexpr bool operator== (Duration lhs, Duration rhs) noexcept
constexpr bool operator== (Timepoint lhs, Timepoint rhs) noexcept
constexpr bool operator> (Duration lhs, Duration rhs) noexcept
constexpr bool operator> (Timepoint lhs, Timepoint rhs) noexcept
constexpr bool operator>= (Duration lhs, Duration rhs) noexcept
constexpr bool operator>= (Timepoint lhs, Timepoint rhs) noexcept
std::string parseJson (picojson::value &out, std::string_view text, JsonLimits const &limits={})
void processEvents ()
void removeFlow (FlowWriter *writer, uuids::uuid id)
std::size_t size () const noexcept
 Returns the total number of writers that are registered in the DomainWatcher.
void stop ()
template<std::integral T>
T stringToInteger (std::string_view text, std::string_view name)
constexpr void swap (Duration &lhs, Duration &rhs) noexcept
template<typename T>
constexpr void swap (SharedMemoryInstance< T > &lhs, SharedMemoryInstance< T > &rhs) noexcept
constexpr void swap (SharedMemorySegment &lhs, SharedMemorySegment &rhs) noexcept
constexpr void swap (Timepoint &lhs, Timepoint &rhs) noexcept
constexpr std::uint64_t timestampToIndex (mxlRational const &editRate, Timepoint timestamp) noexcept
FlowReader * to_FlowReader (mxlFlowReader reader) noexcept
 Utility function to convert from a C mxlFlowReader handle to a C++ FlowReader instance.
FlowSynchronizationGroup * to_FlowSynchronizationGroup (mxlFlowSynchronizationGroup group) noexcept
 Utility function to convert from a C mxlFlowSynchronizationGroup handle to a C++ FlowSynchronizationGroup instance.
FlowWriter * to_FlowWriter (mxlFlowWriter writer) noexcept
 Utility function to convert from a C mxlFlowWriter handle to a C++ FlowWriter instance.
Instance * to_Instance (mxlInstance instance) noexcept
 Utility function to convert from a C mxlInstance handle to a C++ Instance class.
template<typename T>
bool waitUntilChanged (T const *in_addr, T in_expected, Duration in_timeout)
template<typename T>
bool waitUntilChanged (T const *in_addr, T in_expected, Timepoint in_deadline)
template bool waitUntilChanged< std::int32_t > (std::int32_t const *in_addr, std::int32_t in_expected, Duration in_timeout)
template bool waitUntilChanged< std::int32_t > (std::int32_t const *in_addr, std::int32_t in_expected, Timepoint in_deadline)
template bool waitUntilChanged< std::uint32_t > (std::uint32_t const *in_addr, std::uint32_t in_expected, Duration in_timeout)
template bool waitUntilChanged< std::uint32_t > (std::uint32_t const *in_addr, std::uint32_t in_expected, Timepoint in_deadline)
template<typename T>
void wakeAll (T const *in_addr)
template void wakeAll< std::int32_t > (std::int32_t const *in_addr)
template void wakeAll< std::uint32_t > (std::uint32_t const *in_addr)
template<typename T>
void wakeOne (T const *in_addr)
template void wakeOne< std::int32_t > (std::int32_t const *in_addr)
template void wakeOne< std::uint32_t > (std::uint32_t const *in_addr)
 ~DomainWatcher ()

Variables

std::filesystem::path _domain
 The monitored domain.
std::mutex _mutex
 Prodect maps.
std::atomic< bool > _running
 Controls the event processing thread.
std::unordered_multimap< int, DomainWatcherRecord > _watches
 Map of watch descriptors to file records. Multiple records could use the same watchfd.
std::thread _watchThread
 Event processing thread.
constexpr auto const CHANNEL_DATA_FILE_NAME = "channels"
constexpr auto const DOMAIN_OPTIONS_FILE_NAME = "options.json"
 else
constexpr auto EVENT_DATA_FILE_NAME = "events"
 Filename of the single shared-memory event ring within a flow directory.
constexpr auto EVENT_HEADER_VERSION = std::uint32_t{1}
 Version stored in the public mxlEventInfo metadata of every published entry.
constexpr auto const FLOW_ACCESS_FILE_NAME = "access"
constexpr auto const FLOW_DATA_FILE_NAME = "data"
constexpr auto FLOW_DATA_VERSION = 1U
 The version of the flow data structs in shared memory that we expect and support.
constexpr auto const FLOW_DESCRIPTOR_FILE_NAME = "flow_def.json"
constexpr auto const FLOW_DIRECTORY_NAME_SUFFIX = ".mxl-flow"
constexpr auto const GRAIN_DATA_FILE_NAME_STEM = "data"
constexpr auto const GRAIN_DIRECTORY_NAME = "grains"
constexpr auto GRAIN_HEADER_VERSION = 1U
 The version of the grain header structs in shared memory that we expect an support.
constexpr auto const MXL_GRAIN_PAYLOAD_OFFSET = std::size_t{8192}

Enumeration Type Documentation

◆ AccessMode

enum class mxl::lib::AccessMode
strong
Enumerator
READ_ONLY 
READ_WRITE 
CREATE_READ_WRITE 

Definition at line 22 of file SharedMemory.hpp.

◆ Clock

enum class mxl::lib::Clock
strong

An enumeration identifying one of the available clocks in the system.

Enumerator
Monotonic 
Realtime 
TAI 
ProcessCPUTime 
ThreadCPUTime 

Definition at line 14 of file Timing.hpp.

◆ LockMode

enum class mxl::lib::LockMode
strong
Enumerator
Exclusive 
Shared 
None 

Definition at line 15 of file SharedMemory.hpp.

Function Documentation

◆ addFlow()

void mxl::lib::DomainWatcher::addFlow ( FlowWriter * writer,
uuids::uuid id )

Add a new FlowWriter reference to the DomainWatcher.

Parameters
writerThe FlowWriter reference
idId of the flow the FlowWriter is writing to.

Definition at line 210 of file DomainWatcher.cpp.

211 {
212 auto record = DomainWatcherRecord{
213 .id = id,
214 .fileName = makeFlowAccessFilePath(makeFlowDirectoryName(_domain, uuids::to_string(id))),
215 .fw = writer,
216 .flowData = {},
217 };
218 {
219 auto lock = std::scoped_lock{_mutex};
220 auto existingWd = -1;
221
222 // Check if this flow is already being watched
223 for (auto const& [wd, rec] : _watches)
224 {
225 if (rec.id == record.id)
226 {
227 existingWd = wd;
228 record.flowData = rec.flowData;
229 break;
230 }
231 }
232
233 if (existingWd == -1)
234 {
235 MXL_DEBUG("Record for {} not found, creating one.", uuids::to_string(record.id));
236
237#ifdef __APPLE__
238 existingWd = ::open(record.fileName.c_str(), O_EVTONLY | O_CLOEXEC);
239 if (existingWd != -1)
240 {
241 auto change = KEvent{};
242 EV_SET(&change,
243 existingWd,
244 EVFILT_VNODE,
245 EV_ADD | EV_CLEAR,
246 VNODE_EVENTS,
247 0,
248 std::bit_cast<void*>(static_cast<std::uintptr_t>(existingWd)));
249 if (::kevent(_kq, &change, 1, nullptr, 0, nullptr) == -1)
250 {
251 auto const error = errno;
252 ::close(existingWd);
253 errno = error;
254 existingWd = -1;
255 }
256 }
257#elif defined __linux__
258 // if not found, add the watch and add it to the maps
259 existingWd = ::inotify_add_watch(_inotifyFd, record.fileName.c_str(), IN_ACCESS | IN_ATTRIB);
260#endif
261 if (existingWd == -1)
262 {
263 auto const error = errno;
264 MXL_ERROR("Failed to add watch for file '{}': {}", record.fileName, std::strerror(error));
265 throw std::system_error{error, std::generic_category(), "Failed to add watch for file: " + record.fileName};
266 }
267 else
268 {
269 MXL_DEBUG("Added watch {} for file: {}", existingWd, record.fileName);
270 }
271 }
272
273 record.flowData = std::make_shared<SharedMemoryInstance<Flow>>(
274 makeFlowDataFilePath(_domain, uuids::to_string(record.id)).c_str(), AccessMode::READ_WRITE, 0U, LockMode::None);
275 _watches.emplace(existingWd, std::move(record));
276 }
277 }
#define MXL_ERROR(...)
Definition Logging.hpp:67
#define MXL_DEBUG(...)
Definition Logging.hpp:34
std::filesystem::path _domain
The monitored domain.
std::unordered_multimap< int, DomainWatcherRecord > _watches
Map of watch descriptors to file records. Multiple records could use the same watchfd.
std::filesystem::path makeFlowAccessFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:29
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:17
std::mutex _mutex
Prodect maps.
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
Definition PathUtils.cpp:11
Entry stored in the unordered_maps.
mxlFlowWriter writer

◆ asDuration()

Duration mxl::lib::asDuration ( std::timespec const & duration)
nodiscardconstexprnoexcept

Return the equivalent of a timespec instance as a duration.

Returns
The equivalent of a timespec instance as a duration.

Definition at line 385 of file Timing.hpp.

386 {
387 return Duration{(duration.tv_sec * 1'000'000'000LL) + duration.tv_nsec};
388 }

◆ asTimepoint()

Timepoint mxl::lib::asTimepoint ( std::timespec const & timepoint)
nodiscardconstexprnoexcept

Return the equivalent of a timespec instance relative to whichever reference frame the system uses as a time point.

Returns
The equivalent of a timespec instance as a time point.

Definition at line 236 of file Timing.hpp.

237 {
238 return Timepoint{(timepoint.tv_sec * 1'000'000'000LL) + timepoint.tv_nsec};
239 }

◆ asTimeSpec() [1/2]

std::timespec mxl::lib::asTimeSpec ( Duration duration)
nodiscardconstexprnoexcept

Return the equivalent of a duration as a timespec instance.

Returns
The equivalent of a duration as a timespec instance.

Definition at line 390 of file Timing.hpp.

391 {
392 return std::timespec{static_cast<std::time_t>(duration.value / 1'000'000'000LL), duration.value % 1'000'000'000LL};
393 }
value_type value
Definition Timing.hpp:250

◆ asTimeSpec() [2/2]

std::timespec mxl::lib::asTimeSpec ( Timepoint timepoint)
nodiscardconstexprnoexcept

Return the equivalent of a time point as a timespec instance relative to whichever reference frame the system uses.

Returns
The equivalent of a time point as a timespec instance.

Definition at line 241 of file Timing.hpp.

242 {
243 return std::timespec{static_cast<std::time_t>(timepoint.value / 1'000'000'000LL), timepoint.value % 1'000'000'000LL};
244 }
value_type value
Definition Timing.hpp:178

◆ count()

std::size_t mxl::lib::count ( uuids::uuid id) const
nodiscardnoexcept

Returns the number of writers registered for flow id 'id'.

◆ currentTime()

MXL_EXPORT Timepoint mxl::lib::currentTime ( Clock clock)
nodiscardnoexcept

Return the current time.

Returns
The current time as a Timepoint.

Definition at line 11 of file Timing.cpp.

12 {
13 auto result = Timepoint{};
14
15 std::timespec ts;
16 if (::clock_gettime(detail::clockToId(clock), &ts) == 0)
17 {
18 result = asTimepoint(ts) + detail::getClockOffset(clock);
19 }
20 return result;
21 }
constexpr clockid_t clockToId(Clock clock) noexcept
constexpr Duration getClockOffset(Clock clock) noexcept
constexpr Timepoint asTimepoint(std::timespec const &timepoint) noexcept
Definition Timing.hpp:236

◆ currentTimeUTC()

Timepoint mxl::lib::currentTimeUTC ( )
nodiscardnoexcept

Return the current time in UTC.

Returns
The current time as a Timepoint in UTC.

Definition at line 23 of file Timing.cpp.

24 {
25 auto result = Timepoint{};
26
27 std::timespec ts;
28 if (::timespec_get(&ts, TIME_UTC) != 0)
29 {
30 result = asTimepoint(ts);
31 }
32 return result;
33 }

◆ defer()

template<typename F>
Deferred< F > mxl::lib::defer ( F && f)
nodiscardconstexprnoexcept

Definition at line 48 of file Deferred.hpp.

49 {
50 return Deferred{std::forward<F>(f)};
51 }
Helper class that is created by a call to.
Definition Deferred.hpp:16

◆ DomainWatcher()

mxl::lib::DomainWatcher::DomainWatcher ( std::filesystem::path const & in_domain)
explicit

Monitors flows on disk for changes.

A flow writer is looking for changes to the {mxl_domain}/{flow_id}.mxl-flow/access file. This file is 'touched' by readers when they read a grain, which will trigger a 'FlowInfo.lastRead` update.

class MXL_EXPORT DomainWatcher */ { public: using ptr = std::shared_ptr<DomainWatcher>; ///< Shared ownership of the domain watcher.

/** Constructor that initializes inotify and epoll/kqueue, and starts the event processing thread.

Parameters
in_domainThe mxl domain path to monitor.
in_callbackFunction to be called when a monitored file's attributes change.

Definition at line 53 of file DomainWatcher.cpp.

54 : _domain{in_domain}
55 , _running{true}
56 {
57 // Validate that the domain path is a directory
58 if (!std::filesystem::is_directory(in_domain))
59 {
60 throw std::filesystem::filesystem_error("Domain path is not a directory", in_domain, std::make_error_code(std::errc::not_a_directory));
61 }
62#ifdef __APPLE__
63 /* Open a kernel queue. */
64 _kq = kqueue();
65 if (_kq < 0)
66 {
67 auto const error = errno;
68 throw std::system_error(error, std::generic_category(), "Failed to create a kqueue");
69 }
70
71#elif defined __linux__
72 _inotifyFd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
73 if (_inotifyFd == -1)
74 {
75 auto const error = errno;
76 MXL_ERROR("inotify_init1 failed: {}", std::strerror(error));
77 throw std::system_error(error, std::generic_category(), "inotify_init1 failed");
78 }
79
80 // Create epoll instance (close-on-exec), so child processes do not inherit it.
81 // This is necessary to avoid file descriptor leaks in child processes.
82 _epollFd = epoll_create1(EPOLL_CLOEXEC);
83 if (_epollFd == -1)
84 {
85 auto const error = errno;
86 MXL_ERROR("epoll_create1 failed (errno {}: {})", error, std::strerror(error));
87 // Clean up inotify FD before throwing
88 ::close(_inotifyFd);
89 throw std::system_error(error, std::generic_category(), "epoll_create1 failed");
90 }
91
92 // Add inotify file descriptor to epoll
93 epoll_event event{};
94 event.events = EPOLLIN;
95 event.data.fd = _inotifyFd;
96 if (epoll_ctl(_epollFd, EPOLL_CTL_ADD, _inotifyFd, &event) == -1)
97 {
98 auto const error = errno;
99 MXL_ERROR("epoll_ctl ADD(inotify) failed: {}", std::strerror(error));
100 ::close(_inotifyFd);
101 ::close(_epollFd);
102 throw std::system_error(error, std::generic_category(), "epoll_ctl ADD inotify failed");
103 }
104
105 _eventFd = ::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
106 if (_eventFd < 0)
107 {
108 auto const error = errno;
109 ::close(_inotifyFd);
110 ::close(_epollFd);
111 throw std::system_error{error, std::generic_category(), "failed to create evenfd"};
112 }
113
114 auto efdEvent = ::epoll_event{};
115 efdEvent.events = EPOLLIN;
116 efdEvent.data.fd = _eventFd;
117 if (::epoll_ctl(_epollFd, EPOLL_CTL_ADD, _eventFd, &efdEvent) == -1)
118 {
119 auto const error = errno;
120 ::close(_inotifyFd);
121 ::close(_epollFd);
122 ::close(_eventFd);
123 throw std::system_error(error, std::generic_category(), "epoll_ctl ADD eventfd failed");
124 }
125#endif
126
127 // Start event processing thread
128 try
129 {
130 _watchThread = std::thread(&DomainWatcher::processEvents, this);
131 }
132 catch (std::exception const& e)
133 {
134 MXL_ERROR("Failed to start watcher thread: {}", e.what());
135#ifdef __APPLE__
136 ::close(_kq);
137#elif defined __linux__
138 ::close(_inotifyFd);
139 ::close(_epollFd);
140 ::close(_eventFd);
141#endif
142 throw;
143 }
144 catch (...)
145 {
146 MXL_ERROR("Failed to start watcher thread: unknown exception");
147#ifdef __APPLE__
148 ::close(_kq);
149#elif defined __linux__
150 ::close(_inotifyFd);
151 ::close(_epollFd);
152 ::close(_eventFd);
153#endif
154 throw;
155 }
156 }
std::atomic< bool > _running
Controls the event processing thread.
std::thread _watchThread
Event processing thread.

◆ dynamic_pointer_cast()

template<typename To, typename From>
std::unique_ptr< To > mxl::lib::dynamic_pointer_cast ( std::unique_ptr< From > && source)
noexcept

Definition at line 10 of file DynamicPointerCast.hpp.

11 {
12 auto const p = dynamic_cast<To*>(source.get());
13 if (p != nullptr)
14 {
15 source.release();
16 }
17 return std::unique_ptr<To>{p};
18 }

◆ fromMicroSeconds()

Duration mxl::lib::fromMicroSeconds ( double duration)
nodiscardconstexprnoexcept

Return a duration representing the specified number of microseconds.

Returns
A duration representing the specified number of milcroliseconds.

Definition at line 380 of file Timing.hpp.

381 {
382 return Duration{static_cast<Duration::value_type>(duration * 1'000.0)};
383 }
std::int64_t value_type
Definition Timing.hpp:248

◆ fromMilliSeconds()

Duration mxl::lib::fromMilliSeconds ( double duration)
nodiscardconstexprnoexcept

Return a duration representing the specified number of milliseconds.

Returns
A duration representing the specified number of milliseconds.

Definition at line 375 of file Timing.hpp.

376 {
377 return Duration{static_cast<Duration::value_type>(duration * 1'000'000.0)};
378 }

◆ fromSeconds()

Duration mxl::lib::fromSeconds ( double duration)
nodiscardconstexprnoexcept

Return a duration representing the specified number of seconds.

Returns
A duration representing the specified number of seconds.

Definition at line 370 of file Timing.hpp.

371 {
372 return Duration{static_cast<Duration::value_type>(duration * 1'000'000'000.0)};
373 }

◆ get10BitAlphaLineLength()

MXL_EXPORT std::uint32_t mxl::lib::get10BitAlphaLineLength ( std::size_t width)

Length in bytes of a line in the 10-bit alpha video format (3x10-bit samples per 32 bit word).

Parameters
widthThe width of the video frame in pixels.
Returns
The line length in bytes for the 10-bit Alpha format, including padding.

Definition at line 14 of file MediaUtils.cpp.

15{
16 return static_cast<std::uint32_t>((width + 2) / 3 * 4);
17}

◆ getV210LineLength()

MXL_EXPORT std::uint32_t mxl::lib::getV210LineLength ( std::size_t width)

Length in bytes of a line in the V210 video format.

Parameters
widthThe width of the video frame in pixels.
Returns
The line length in bytes for the V210 format, including padding.

Definition at line 8 of file MediaUtils.cpp.

9{
10 return static_cast<std::uint32_t>((width + 47) / 48 * 128);
11}

◆ if() [1/2]

mxl::lib::if ( lockMode ! = LockMode::None && mode != AccessMode::READ_ONLY)

Definition at line 56 of file SharedMemory.cpp.

57 {
58 auto lockFlags = LOCK_NB;
59
60 if (lockMode == LockMode::Exclusive)
61 {
62 lockFlags |= LOCK_EX;
63 _lockType = LockType::Exclusive;
64 }
65 else
66 {
67 lockFlags |= LOCK_SH;
68 _lockType = LockType::Shared;
69 }
70
71 if (::flock(_fd, lockFlags) == -1)
72 {
73 throw std::system_error{errno, std::system_category(), fmt::format("Failed to lock shared memory segment.")};
74 }
75 }

◆ if() [2/2]

mxl::lib::if ( struct stat statBuf;::fstat(_fd, &statBuf) ! = -1)

Definition at line 81 of file SharedMemory.cpp.

82 {
83 if (static_cast<std::size_t>(statBuf.st_size) >= payloadSize)
84 {
85 auto const shared_data_buffer = ::mmap(
86 nullptr, statBuf.st_size, PROT_READ | ((mode != AccessMode::READ_ONLY) ? PROT_WRITE : 0), MAP_FILE | MAP_SHARED, _fd, 0);
87 if (shared_data_buffer != MAP_FAILED)
88 {
89 _data = shared_data_buffer;
90 _mappedSize = statBuf.st_size;
91 }
92 else
93 {
94 throw std::system_error(errno, std::generic_category(), "Could not map shared memory segment.");
95 }
96 }
97 else
98 {
99 throw std::system_error(ENOMEM, std::generic_category(), "Shared memory segment does not meet the minimum size requirements.");
100 }
101 }

◆ indexToTimestamp()

Timepoint mxl::lib::indexToTimestamp ( mxlRational const & editRate,
std::uint64_t index )
constexprnoexcept

Definition at line 25 of file IndexConversion.hpp.

26 {
27 // Validate the edit rate
28 if ((editRate.denominator != 0) && (editRate.numerator != 0))
29 {
30 return Timepoint{static_cast<std::int64_t>(
31 (index * __int128_t{editRate.denominator} * 1'000'000'000 + __int128_t{editRate.numerator} / 2) / __int128_t{editRate.numerator})};
32 }
33 return {};
34 }
uint64_t index

◆ inMicroSeconds()

double mxl::lib::inMicroSeconds ( Duration duration)
nodiscardconstexprnoexcept

Return the equivalent of a duration in microseconds.

Returns
The equivalent of a duration in microseconds.

Definition at line 360 of file Timing.hpp.

361 {
362 return static_cast<double>(duration.value) / 1'000.0;
363 }

◆ inMilliSeconds()

double mxl::lib::inMilliSeconds ( Duration duration)
nodiscardconstexprnoexcept

Return the equivalent of a duration in milliseconds.

Returns
The equivalent of a duration in milliseconds.

Definition at line 355 of file Timing.hpp.

356 {
357 return static_cast<double>(duration.value) / 1'000'000.0;
358 }

◆ inNanoSeconds()

double mxl::lib::inNanoSeconds ( Duration duration)
nodiscardconstexprnoexcept

Return the equivalent of a duration in nanoseconds.

Returns
The equivalent of a duration in nanoseconds.

Definition at line 365 of file Timing.hpp.

366 {
367 return static_cast<double>(duration.value);
368 }

◆ inSeconds()

double mxl::lib::inSeconds ( Duration duration)
nodiscardconstexprnoexcept

Return the equivalent of a duration in seconds.

Returns
The equivalent of a duration in seconds.

Definition at line 350 of file Timing.hpp.

351 {
352 return static_cast<double>(duration.value) / 1'000'000'000.0;
353 }

◆ jsonStringToInteger()

template<std::integral T>
T mxl::lib::jsonStringToInteger ( picojson::value const & value,
std::string_view name )
inline

Convert a JSON string holding a decimal number to the integer type T.

Use this for values such as memory addresses and keys, which are stored as strings because a JSON number is a double and cannot hold every 64-bit integer exactly.

Parameters
valueThe JSON value.
nameThe field name, used in the error message.
Returns
The value as T.
Exceptions
std::invalid_argumentIf the value is not a string, or not a decimal number in the range of T.
See also
stringToInteger()

Definition at line 270 of file JsonUtils.hpp.

271 {
272 if (!value.is<std::string>())
273 {
274 throw std::invalid_argument{fmt::format("'{}' must be a string.", name)};
275 }
276 return stringToInteger<T>(value.get<std::string>(), name);
277 }
T stringToInteger(std::string_view text, std::string_view name)

◆ jsonToInteger()

template<std::integral T>
T mxl::lib::jsonToInteger ( picojson::value const & value,
std::string_view name )
inline

Convert a JSON number to the integer type T.

Converting a double that is outside the range of an integer type is undefined behavior in C++, so the value is checked before the conversion.

Parameters
valueThe JSON value.
nameThe field name, used in the error message.
Returns
The value as T.
Exceptions
std::invalid_argumentIf the value is not a number, not a whole number, or outside the range of T.

Definition at line 236 of file JsonUtils.hpp.

237 {
238 if (!value.is<double>())
239 {
240 throw std::invalid_argument{fmt::format("'{}' must be a number.", name)};
241 }
242
243 auto const number = value.get<double>();
244
245 // 2^digits is the first value past the range of T. It is exact as a double, while numeric_limits<T>::max() may
246 // round up to it.
247 auto const upper = std::ldexp(1.0, std::numeric_limits<T>::digits);
248 auto const lower = std::numeric_limits<T>::is_signed ? -upper : 0.0;
249 if ((std::trunc(number) != number) || (number < lower) || (number >= upper))
250 {
251 throw std::invalid_argument{fmt::format(
252 "'{}' must be a whole number between {} and {}, got {}.", name, std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), number)};
253 }
254 return static_cast<T>(number);
255 }

◆ makeChannelDataFilePath() [1/2]

std::filesystem::path mxl::lib::makeChannelDataFilePath ( std::filesystem::path const & domain,
std::string const & uuid )
inline

Definition at line 83 of file PathUtils.hpp.

84 {
86 }
std::filesystem::path makeChannelDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:47

◆ makeChannelDataFilePath() [2/2]

MXL_EXPORT std::filesystem::path mxl::lib::makeChannelDataFilePath ( std::filesystem::path const & flowDirectory)

Definition at line 47 of file PathUtils.cpp.

48 {
49 return flowDirectory / CHANNEL_DATA_FILE_NAME;
50 }
constexpr auto const CHANNEL_DATA_FILE_NAME
Definition PathUtils.hpp:20

◆ makeDomainOptionsFilePath()

MXL_EXPORT std::filesystem::path mxl::lib::makeDomainOptionsFilePath ( std::filesystem::path const & domain)

Definition at line 59 of file PathUtils.cpp.

60 {
61 return domain / (DOMAIN_OPTIONS_FILE_NAME);
62 }
constexpr auto const DOMAIN_OPTIONS_FILE_NAME
Definition PathUtils.hpp:23

◆ makeEventDataFilePath()

MXL_EXPORT std::filesystem::path mxl::lib::makeEventDataFilePath ( std::filesystem::path const & flowDirectory)

Locate an event ring file within its flow directory.

Parameters
flowDirectoryFully resolved flow directory, including its flow ID component.
Returns
Path to the events file; no filesystem access is performed.

Definition at line 53 of file PathUtils.cpp.

54 {
55 return flowDirectory / EVENT_DATA_FILE_NAME;
56 }
constexpr auto EVENT_DATA_FILE_NAME
Filename of the single shared-memory event ring within a flow directory.
Definition PathUtils.hpp:22

◆ makeFlowAccessFilePath() [1/2]

std::filesystem::path mxl::lib::makeFlowAccessFilePath ( std::filesystem::path const & domain,
std::string const & uuid )
inline

Definition at line 68 of file PathUtils.hpp.

69 {
71 }

◆ makeFlowAccessFilePath() [2/2]

MXL_EXPORT std::filesystem::path mxl::lib::makeFlowAccessFilePath ( std::filesystem::path const & flowDirectory)

Definition at line 29 of file PathUtils.cpp.

30 {
31 return flowDirectory / FLOW_ACCESS_FILE_NAME;
32 }
constexpr auto const FLOW_ACCESS_FILE_NAME
Definition PathUtils.hpp:17

◆ makeFlowDataFilePath() [1/2]

std::filesystem::path mxl::lib::makeFlowDataFilePath ( std::filesystem::path const & domain,
std::string const & uuid )
inline

Definition at line 58 of file PathUtils.hpp.

59 {
60 return makeFlowDataFilePath(makeFlowDirectoryName(domain, uuid));
61 }

◆ makeFlowDataFilePath() [2/2]

MXL_EXPORT std::filesystem::path mxl::lib::makeFlowDataFilePath ( std::filesystem::path const & flowDirectory)

Definition at line 17 of file PathUtils.cpp.

18 {
19 return flowDirectory / FLOW_DATA_FILE_NAME;
20 }
constexpr auto const FLOW_DATA_FILE_NAME
Definition PathUtils.hpp:16

◆ makeFlowDescriptorFilePath() [1/2]

std::filesystem::path mxl::lib::makeFlowDescriptorFilePath ( std::filesystem::path const & domain,
std::string const & uuid )
inline

Definition at line 63 of file PathUtils.hpp.

64 {
66 }
std::filesystem::path makeFlowDescriptorFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:23

◆ makeFlowDescriptorFilePath() [2/2]

MXL_EXPORT std::filesystem::path mxl::lib::makeFlowDescriptorFilePath ( std::filesystem::path const & flowDirectory)

Definition at line 23 of file PathUtils.cpp.

24 {
25 return flowDirectory / FLOW_DESCRIPTOR_FILE_NAME;
26 }
constexpr auto const FLOW_DESCRIPTOR_FILE_NAME
Definition PathUtils.hpp:15

◆ makeFlowDirectoryName()

MXL_EXPORT std::filesystem::path mxl::lib::makeFlowDirectoryName ( std::filesystem::path const & domain,
std::string const & uuid )

Definition at line 11 of file PathUtils.cpp.

12 {
13 return domain / (uuid + FLOW_DIRECTORY_NAME_SUFFIX);
14 }
constexpr auto const FLOW_DIRECTORY_NAME_SUFFIX
Definition PathUtils.hpp:14

◆ makeGrainDataFilePath() [1/2]

std::filesystem::path mxl::lib::makeGrainDataFilePath ( std::filesystem::path const & domain,
std::string const & uuid,
unsigned int index )
inline

Definition at line 78 of file PathUtils.hpp.

79 {
81 }
std::filesystem::path makeGrainDirectoryName(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:35
std::filesystem::path makeGrainDataFilePath(std::filesystem::path const &grainDirectory, unsigned int index)
Definition PathUtils.cpp:41

◆ makeGrainDataFilePath() [2/2]

MXL_EXPORT std::filesystem::path mxl::lib::makeGrainDataFilePath ( std::filesystem::path const & grainDirectory,
unsigned int index )

Definition at line 41 of file PathUtils.cpp.

42 {
43 return grainDirectory / fmt::format("{}.{}", GRAIN_DATA_FILE_NAME_STEM, index);
44 }
constexpr auto const GRAIN_DATA_FILE_NAME_STEM
Definition PathUtils.hpp:19

◆ makeGrainDirectoryName() [1/2]

std::filesystem::path mxl::lib::makeGrainDirectoryName ( std::filesystem::path const & domain,
std::string const & uuid )
inline

Definition at line 73 of file PathUtils.hpp.

74 {
76 }

◆ makeGrainDirectoryName() [2/2]

MXL_EXPORT std::filesystem::path mxl::lib::makeGrainDirectoryName ( std::filesystem::path const & flowDirectory)

Definition at line 35 of file PathUtils.cpp.

36 {
37 return flowDirectory / GRAIN_DIRECTORY_NAME;
38 }
constexpr auto const GRAIN_DIRECTORY_NAME
Definition PathUtils.hpp:18

◆ makelowAccessFilePath()

std::filesystem::path mxl::lib::makelowAccessFilePath ( std::filesystem::path const & domain,
std::string const & uuid )

◆ operator!=() [1/2]

bool mxl::lib::operator!= ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 276 of file Timing.hpp.

277 {
278 return (lhs.value != rhs.value);
279 }

◆ operator!=() [2/2]

bool mxl::lib::operator!= ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 204 of file Timing.hpp.

205 {
206 return (lhs.value != rhs.value);
207 }

◆ operator*() [1/2]

Duration mxl::lib::operator* ( Duration lhs,
int rhs )
nodiscardconstexprnoexcept

Definition at line 316 of file Timing.hpp.

317 {
318 return Duration{lhs.value * rhs};
319 }

◆ operator*() [2/2]

Duration mxl::lib::operator* ( int lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 311 of file Timing.hpp.

312 {
313 return Duration{lhs * rhs.value};
314 }

◆ operator+() [1/2]

Duration mxl::lib::operator+ ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 301 of file Timing.hpp.

302 {
303 return Duration{lhs.value + rhs.value};
304 }

◆ operator+() [2/2]

Timepoint mxl::lib::operator+ ( Timepoint lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 337 of file Timing.hpp.

338 {
339 auto const sum = lhs.value + rhs.value;
340 return Timepoint{(sum >= 0) ? sum : 0LL};
341 }

◆ operator-() [1/3]

Duration mxl::lib::operator- ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 306 of file Timing.hpp.

307 {
308 return Duration{lhs.value - rhs.value};
309 }

◆ operator-() [2/3]

Timepoint mxl::lib::operator- ( Timepoint lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 331 of file Timing.hpp.

332 {
333 auto const diff = lhs.value - rhs.value;
334 return Timepoint{(diff >= 0) ? diff : 0LL};
335 }

◆ operator-() [3/3]

Duration mxl::lib::operator- ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 326 of file Timing.hpp.

327 {
328 return Duration{lhs.value - rhs.value};
329 }

◆ operator/()

Duration mxl::lib::operator/ ( Duration lhs,
int rhs )
nodiscardconstexprnoexcept

Definition at line 321 of file Timing.hpp.

322 {
323 return Duration{lhs.value / rhs};
324 }

◆ operator<() [1/2]

bool mxl::lib::operator< ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 291 of file Timing.hpp.

292 {
293 return (lhs.value < rhs.value);
294 }

◆ operator<() [2/2]

bool mxl::lib::operator< ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 209 of file Timing.hpp.

210 {
211 return (lhs.value < rhs.value);
212 }

◆ operator<<()

std::ostream & mxl::lib::operator<< ( std::ostream & os,
Grain const & obj )

◆ operator<=() [1/2]

bool mxl::lib::operator<= ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 281 of file Timing.hpp.

282 {
283 return (lhs.value <= rhs.value);
284 }

◆ operator<=() [2/2]

bool mxl::lib::operator<= ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 219 of file Timing.hpp.

220 {
221 return (lhs.value <= rhs.value);
222 }

◆ operator==() [1/2]

bool mxl::lib::operator== ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 271 of file Timing.hpp.

272 {
273 return (lhs.value == rhs.value);
274 }

◆ operator==() [2/2]

bool mxl::lib::operator== ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 199 of file Timing.hpp.

200 {
201 return (lhs.value == rhs.value);
202 }

◆ operator>() [1/2]

bool mxl::lib::operator> ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 296 of file Timing.hpp.

297 {
298 return (lhs.value > rhs.value);
299 }

◆ operator>() [2/2]

bool mxl::lib::operator> ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 214 of file Timing.hpp.

215 {
216 return (lhs.value > rhs.value);
217 }

◆ operator>=() [1/2]

bool mxl::lib::operator>= ( Duration lhs,
Duration rhs )
nodiscardconstexprnoexcept

Definition at line 286 of file Timing.hpp.

287 {
288 return (lhs.value >= rhs.value);
289 }

◆ operator>=() [2/2]

bool mxl::lib::operator>= ( Timepoint lhs,
Timepoint rhs )
nodiscardconstexprnoexcept

Definition at line 224 of file Timing.hpp.

225 {
226 return (lhs.value >= rhs.value);
227 }

◆ parseJson()

std::string mxl::lib::parseJson ( picojson::value & out,
std::string_view text,
JsonLimits const & limits = {} )
inline

Parse a JSON document with the limits in limits.

Unlike picojson::parse(value&, std::string const&), this rejects any content after the first value other than whitespace, and rejects objects with duplicate keys.

Parameters
outReceives the parsed value. Its content is unspecified on error.
textThe JSON document.
limitsThe limits to apply.
Returns
An empty string on success, otherwise a description of the error.

Definition at line 193 of file JsonUtils.hpp.

193 {})
194 {
195 if (text.size() > limits.maxInputSize)
196 {
197 return fmt::format("JSON input has {} bytes, the limit is {}.", text.size(), limits.maxInputSize);
198 }
199
200 auto limitError = std::string{};
201 auto syntaxError = std::string{};
202 auto ctx = detail::LimitedJsonParseContext{&out, limits, limitError, 0U};
203 auto const end = picojson::_parse(ctx, text.begin(), text.end(), &syntaxError);
204 if (!limitError.empty())
205 {
206 return limitError;
207 }
208 if (!syntaxError.empty())
209 {
210 return syntaxError;
211 }
212
213 auto const isWhitespace = [](char c) noexcept
214 {
215 return (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r');
216 };
217 if (!std::all_of(end, text.end(), isWhitespace))
218 {
219 return "Unexpected content after the JSON value.";
220 }
221 return {};
222 }

◆ processEvents()

void mxl::lib::DomainWatcher::processEvents ( )
private

Event loop that waits for inotify file change events and processes them. (invokes the callback)

Definition at line 322 of file DomainWatcher.cpp.

323 {
324#ifdef __APPLE__
325
326 while (_running)
327 {
328 auto timeout = timespec{.tv_sec = 0, .tv_nsec = 250000000}; // 250 milliseconds
329
330 setWatch();
331
332 auto const eventCount = kevent(_kq,
333 _eventsToMonitor.data(),
334 static_cast<int>(_eventsToMonitor.size()),
335 _eventData.data(),
336 static_cast<int>(_eventData.size()),
337 &timeout);
338 if (eventCount < 0)
339 {
340 auto const error = errno;
341 MXL_ERROR("kevent error {}", std::strerror(error));
342 break;
343 }
344 else if (eventCount)
345 {
346 processPendingEvents(eventCount);
347 }
348 }
349
350#elif defined __linux__
351 epoll_event events[1];
352 alignas(alignof(struct inotify_event)) char buffer[4096] = {};
353
354 while (_running)
355 {
356 int nfds = ::epoll_wait(_epollFd, events, 1, 250);
357 if (nfds == -1)
358 {
359 auto const error = errno;
360 if (error == EINTR)
361 {
362 continue; // interrupted by signal, retry loop
363 }
364 MXL_ERROR("epoll_wait failed: {}", std::strerror(error));
365 break; // exit thread on critical epoll error
366 }
367 if (nfds == 0)
368 {
369 continue; // no events, continue looping
370 }
371
372 for (auto ev = events; ev != events + nfds; ++ev)
373 {
374 if (ev->data.fd == _eventFd)
375 {
376 auto value = ::eventfd_t{};
377 if (::read(_eventFd, &value, sizeof(::eventfd_t)) < 0)
378 {
379 MXL_WARN("Failed to read event file descriptor: {}", ::strerror(errno));
380 continue;
381 }
382
383 if (value > 0)
384 {
385 MXL_DEBUG("Domain watcher thread exit requested");
386 }
387 }
388 else
389 {
390 // We have an inotify event ready
391 auto length = ::read(_inotifyFd, buffer, sizeof buffer);
392 if (length == -1)
393 {
394 auto const error = errno;
395 if ((error == EINTR) || (error == EAGAIN))
396 {
397 continue; // spurious interrupt or non-blocking empty read, retry
398 }
399 MXL_ERROR("Error reading inotify events: {}", std::strerror(error));
400 break; // break on critical read error
401 }
402 if (length == 0)
403 {
404 continue; // nothing to read (should not happen if nfds > 0)
405 }
406
407 processEventBuffer(reinterpret_cast<::inotify_event const*>(buffer), length / sizeof(::inotify_event));
408 }
409 }
410 }
411#endif
412 }
#define MXL_WARN(...)
Definition Logging.hpp:56
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.

◆ removeFlow()

void mxl::lib::DomainWatcher::removeFlow ( FlowWriter * writer,
uuids::uuid id )

Remove a FlowWriter reference from the DomainWatcher. If no more FlowWriter references for a given flow id are present in the DomainWatcher it stops watching the flow.

Parameters
writerThe flow writer reference to remove.
idId of the flow the FlowWriter is writing to.

Definition at line 279 of file DomainWatcher.cpp.

280 {
281 auto record = DomainWatcherRecord{
282 .id = id,
283 .fileName = makeFlowAccessFilePath(makeFlowDirectoryName(_domain, uuids::to_string(id))),
284 .fw = writer,
285 .flowData = {},
286 };
287 {
288 auto lock = std::scoped_lock{_mutex};
289
290 // Remove the record for this writer
291 auto it = std::ranges::find_if(_watches, [record](auto const& item) noexcept { return item.second == record; });
292 if (it == _watches.end())
293 {
294 return;
295 }
296
297 auto const wd = it->first;
298 _watches.erase(it);
299
300 // Remove the watch if there are no more writers interested in notification for this flow.
301 if (!_watches.contains(wd))
302 {
303#ifdef __APPLE__
304 if (::close(wd) == -1)
305 {
306 MXL_ERROR("Error closing file descriptor {} for '{}'", wd, record.fileName);
307 }
308#elif defined __linux__
309 if (::inotify_rm_watch(_inotifyFd, wd) == -1)
310 {
311 auto const error = errno;
312 if ((error != EINVAL) || std::filesystem::exists(record.fileName))
313 {
314 MXL_WARN("Failed to remove inotify watch (wd={}) for '{}': {}", wd, record.fileName, std::strerror(error));
315 }
316 }
317#endif
318 }
319 }
320 }

◆ size()

std::size_t mxl::lib::size ( ) const
nodiscardnoexcept

Returns the total number of writers that are registered in the DomainWatcher.

◆ stop()

void mxl::lib::stop ( )

Stops the running thread

Definition at line 93 of file DomainWatcher.hpp.

94 {
95 _running = false;
96 if (_watchThread.joinable())
97 {
98#if defined __linux__
99 auto value = ::eventfd_t{1};
100 if (::write(_eventFd, &value, sizeof(::eventfd_t)) < 0)
101 {
102 auto const error = errno;
103 MXL_ERROR("Failed to signal DomainWatcher stop request: {}", ::strerror(error));
104 }
105#elif defined __APPLE__
106 struct kevent kev{};
107 EV_SET(&kev, USER_IDENT, EVFILT_USER, 0, NOTE_TRIGGER, 0, nullptr);
108 if (::kevent(_kq, &kev, 1, nullptr, 0, nullptr) < 0)
109 {
110 auto const error = errno;
111 MXL_WARN("Failed so signal DomainWatcher stop request: {}", std::strerror(error));
112 }
113#endif
114
115 _watchThread.join();
116 }
117 }

◆ stringToInteger()

template<std::integral T>
T mxl::lib::stringToInteger ( std::string_view text,
std::string_view name )

Convert a decimal string to the integer type T.

Parameters
textThe string to convert.
nameThe field name, used in the error message.
Returns
The value as T.
Exceptions
std::invalid_argumentIf the string is not a decimal number in the range of T.

Definition at line 24 of file StringUtils.hpp.

25 {
26 auto value = T{};
27 auto const* const first = text.data();
28 auto const* const last = text.data() + text.size();
29 auto const [end, error] = std::from_chars(first, last, value);
30 if (error == std::errc::result_out_of_range)
31 {
32 throw std::invalid_argument{
33 fmt::format("'{}' must be between {} and {}, got '{}'.", name, std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), text)};
34 }
35 if ((error != std::errc{}) || (end != last))
36 {
37 throw std::invalid_argument{fmt::format("'{}' must be a decimal integer, got '{}'.", name, text)};
38 }
39 return value;
40 }

◆ swap() [1/4]

void mxl::lib::swap ( Duration & lhs,
Duration & rhs )
constexprnoexcept

Definition at line 343 of file Timing.hpp.

344 {
345 auto const temp = lhs.value;
346 lhs.value = rhs.value;
347 rhs.value = temp;
348 }

◆ swap() [2/4]

template<typename T>
void mxl::lib::swap ( SharedMemoryInstance< T > & lhs,
SharedMemoryInstance< T > & rhs )
constexprnoexcept

ADL compatible shwap function for SharedMemorySegment.

Definition at line 373 of file SharedMemory.hpp.

374 {
375 lhs.swap(rhs);
376 }
constexpr void swap(SharedMemoryInstance &other) noexcept

◆ swap() [3/4]

void mxl::lib::swap ( SharedMemorySegment & lhs,
SharedMemorySegment & rhs )
constexprnoexcept

ADL compatible shwap function for SharedMemorySegment.

Definition at line 316 of file SharedMemory.hpp.

317 {
318 lhs.swap(rhs);
319 }
constexpr void swap(SharedMemorySegment &other) noexcept

◆ swap() [4/4]

void mxl::lib::swap ( Timepoint & lhs,
Timepoint & rhs )
constexprnoexcept

Definition at line 229 of file Timing.hpp.

230 {
231 auto const temp = lhs.value;
232 lhs.value = rhs.value;
233 rhs.value = temp;
234 }

◆ timestampToIndex()

std::uint64_t mxl::lib::timestampToIndex ( mxlRational const & editRate,
Timepoint timestamp )
constexprnoexcept

Definition at line 12 of file IndexConversion.hpp.

13 {
14 if ((editRate.denominator != 0) && (editRate.numerator != 0))
15 {
16 return static_cast<std::uint64_t>((timestamp.value * __int128_t{editRate.numerator} + 500'000'000 * __int128_t{editRate.denominator}) /
17 (1'000'000'000 * __int128_t{editRate.denominator}));
18 }
19 else
20 {
22 }
23 }
#define MXL_UNDEFINED_INDEX
Definition rational.h:17
auto const timestamp
Definition test_time.cpp:61

◆ to_FlowReader()

FlowReader * mxl::lib::to_FlowReader ( mxlFlowReader reader)
inlinenoexcept

Utility function to convert from a C mxlFlowReader handle to a C++ FlowReader instance.

Definition at line 252 of file Instance.hpp.

253 {
254 return reinterpret_cast<FlowReader*>(reader);
255 }
mxlFlowReader reader

◆ to_FlowSynchronizationGroup()

FlowSynchronizationGroup * mxl::lib::to_FlowSynchronizationGroup ( mxlFlowSynchronizationGroup group)
inlinenoexcept

Utility function to convert from a C mxlFlowSynchronizationGroup handle to a C++ FlowSynchronizationGroup instance.

Definition at line 262 of file Instance.hpp.

263 {
264 return reinterpret_cast<FlowSynchronizationGroup*>(group);
265 }

◆ to_FlowWriter()

FlowWriter * mxl::lib::to_FlowWriter ( mxlFlowWriter writer)
inlinenoexcept

Utility function to convert from a C mxlFlowWriter handle to a C++ FlowWriter instance.

Definition at line 257 of file Instance.hpp.

258 {
259 return reinterpret_cast<FlowWriter*>(writer);
260 }

◆ to_Instance()

Instance * mxl::lib::to_Instance ( mxlInstance instance)
inlinenoexcept

Utility function to convert from a C mxlInstance handle to a C++ Instance class.

Definition at line 247 of file Instance.hpp.

248 {
249 return reinterpret_cast<Instance*>(instance);
250 }

◆ waitUntilChanged() [1/2]

template<typename T>
bool mxl::lib::waitUntilChanged ( T const * in_addr,
T in_expected,
Duration in_timeout )

Wait until *in_addr changes or timeout expires.

Parameters
in_addrThe memory address to monitor. Must refer to a 32 bit value.
in_expectedThe initial value expected at in_addr
in_timeoutHow long to wait.
Returns
true if value changed, false if timeout expired

Definition at line 114 of file Sync.cpp.

115 {
116 static_assert(valid_specialization_v<T>, "Only 32 bit types with natural alignment are supported.");
117
118 return waitUntilChanged(in_addr, in_expected, currentTime(Clock::Realtime) + in_timeout);
119 }
bool waitUntilChanged(T const *in_addr, T in_expected, Timepoint in_deadline)
Definition Sync.cpp:68
auto const currentTime
Definition test_time.cpp:58

◆ waitUntilChanged() [2/2]

template<typename T>
bool mxl::lib::waitUntilChanged ( T const * in_addr,
T in_expected,
Timepoint in_deadline )

Wait until *in_addr changes or timeout expires.

Parameters
in_addrThe memory address to monitor. Must refer to a 32 bit value.
in_expectedThe initial value expected at in_addr
in_deadlineUntil when to wait. Timepoint is expected to come from Clock::Realtime.
Returns
true if value changed, false if timeout expired

Definition at line 68 of file Sync.cpp.

69 {
70 static_assert(valid_specialization_v<T>, "Only 32 bit types with natural alignment are supported.");
71
72#if _LIBCPP_VERSION
73 // libc++ limitation due to: https://github.com/llvm/llvm-project/issues/118378
74 auto syncObject = std::atomic_ref{*const_cast<T*>(in_addr)};
75#else
76 auto syncObject = std::atomic_ref{*in_addr};
77#endif
78 while (syncObject.load(std::memory_order_acquire) == in_expected)
79 {
80 auto const now = currentTime(Clock::Realtime);
81 if (now >= in_deadline)
82 {
83 MXL_DEBUG("Deadline already reached");
84 return false;
85 }
86
87 // ATTENTION: Do not check for != 0, as positive values are success indicators
88 // in the macOS implementation of this function.
89 // NOTE: Unfortunately syncObject.address() is only available from C++26 onwards
90 if (auto const ret = do_wait(in_addr, in_expected, in_deadline - now); ret == -1)
91 {
92 switch (errno)
93 {
94 case EAGAIN:
95 // On linux EAGAIN indicates that the kernel detected *in_addr to
96 // not be equal to in_expected.
97 continue;
98
99 case EINTR:
100 // Interrupted. try again.
101 continue;
102
103 case ETIMEDOUT: MXL_TRACE("ETIMEDOUT. returning false"); break;
104
105 default: break;
106 }
107 return false;
108 }
109 }
110 return true;
111 }
#define MXL_TRACE(...)
Definition Logging.hpp:23
auto const now

◆ waitUntilChanged< std::int32_t >() [1/2]

template bool mxl::lib::waitUntilChanged< std::int32_t > ( std::int32_t const * in_addr,
std::int32_t in_expected,
Duration in_timeout )

◆ waitUntilChanged< std::int32_t >() [2/2]

template bool mxl::lib::waitUntilChanged< std::int32_t > ( std::int32_t const * in_addr,
std::int32_t in_expected,
Timepoint in_deadline )

◆ waitUntilChanged< std::uint32_t >() [1/2]

template bool mxl::lib::waitUntilChanged< std::uint32_t > ( std::uint32_t const * in_addr,
std::uint32_t in_expected,
Duration in_timeout )

◆ waitUntilChanged< std::uint32_t >() [2/2]

template bool mxl::lib::waitUntilChanged< std::uint32_t > ( std::uint32_t const * in_addr,
std::uint32_t in_expected,
Timepoint in_deadline )

◆ wakeAll()

template<typename T>
void mxl::lib::wakeAll ( T const * in_addr)

Wake all waiters waiting on in_addr

Parameters
in_addrThe memory address to signal. Must refer to a 32 bit value.

Definition at line 131 of file Sync.cpp.

132 {
133 static_assert(valid_specialization_v<T>, "Only 32 bit types with natural alignment are supported.");
134
135 MXL_TRACE("Wake all waiting on = {}, val : {}", static_cast<void const*>(in_addr), *in_addr);
136 do_wake_all(in_addr);
137 }

◆ wakeAll< std::int32_t >()

template void mxl::lib::wakeAll< std::int32_t > ( std::int32_t const * in_addr)

◆ wakeAll< std::uint32_t >()

template void mxl::lib::wakeAll< std::uint32_t > ( std::uint32_t const * in_addr)

◆ wakeOne()

template<typename T>
void mxl::lib::wakeOne ( T const * in_addr)

Wake a single waiter waiting on in_addr

Parameters
in_addrThe memory address to signal. Must refer to a 32 bit value.

Definition at line 122 of file Sync.cpp.

123 {
124 static_assert(valid_specialization_v<T>, "Only 32 bit types with natural alignment are supported.");
125
126 MXL_TRACE("Wake one waiting on = {}, val : {}", static_cast<void const*>(in_addr), *in_addr);
127 do_wake_one(in_addr);
128 }

◆ wakeOne< std::int32_t >()

template void mxl::lib::wakeOne< std::int32_t > ( std::int32_t const * in_addr)

◆ wakeOne< std::uint32_t >()

template void mxl::lib::wakeOne< std::uint32_t > ( std::uint32_t const * in_addr)

◆ ~DomainWatcher()

mxl::lib::DomainWatcher::~DomainWatcher ( )

Destructor that stops the event loop, removes all watches, and closes file descriptors.

Definition at line 158 of file DomainWatcher.cpp.

159 {
160 stop();
161
162#ifdef __APPLE__
163 ::close(_kq);
164#elif defined __linux__
165 // Linux: remove all inotify watches and close FDs
166 for (auto const& [wd, rec] : _watches)
167 {
168 if (inotify_rm_watch(_inotifyFd, wd) == -1)
169 {
170 auto const error = errno;
171 MXL_ERROR("Error removing inotify watch (wd={}): {}", wd, std::strerror(error));
172 }
173 }
174 if (::close(_inotifyFd) == -1)
175 {
176 auto const error = errno;
177 MXL_ERROR("Error closing inotify FD: {}", std::strerror(error));
178 }
179 if (::close(_eventFd) == -1)
180 {
181 auto const error = errno;
182 MXL_ERROR("Error closing epoll FD: {}", std::strerror(error));
183 }
184 if (::close(_epollFd) == -1)
185 {
186 auto const error = errno;
187 MXL_ERROR("Error closing epoll FD: {}", std::strerror(error));
188 }
189#endif
190 }

Variable Documentation

◆ _domain

std::filesystem::path mxl::lib::_domain
private

The monitored domain.

Definition at line 142 of file DomainWatcher.hpp.

◆ _mutex

std::mutex mxl::lib::_mutex
mutableprivate

Prodect maps.

Definition at line 160 of file DomainWatcher.hpp.

◆ _running

std::atomic<bool> mxl::lib::_running
private

Controls the event processing thread.

Definition at line 162 of file DomainWatcher.hpp.

◆ _watches

std::unordered_multimap<int, DomainWatcherRecord> mxl::lib::_watches
private

Map of watch descriptors to file records. Multiple records could use the same watchfd.

Definition at line 158 of file DomainWatcher.hpp.

◆ _watchThread

std::thread mxl::lib::_watchThread
private

Event processing thread.

Definition at line 164 of file DomainWatcher.hpp.

◆ CHANNEL_DATA_FILE_NAME

auto const mxl::lib::CHANNEL_DATA_FILE_NAME = "channels"
inlineconstexpr

Definition at line 20 of file PathUtils.hpp.

◆ DOMAIN_OPTIONS_FILE_NAME

auto const mxl::lib::DOMAIN_OPTIONS_FILE_NAME = "options.json"
inlineconstexpr

Definition at line 23 of file PathUtils.hpp.

◆ else

mxl::lib::else
Initial value:
{
if ((_fd = ::open(path, (mode == AccessMode::READ_ONLY) ? OMODE_RO : OMODE_RW)) == -1)
{
throw std::system_error(errno, std::generic_category(), "Could not open shared memory segment.");
}

Definition at line 47 of file SharedMemory.cpp.

48 {
49 if ((_fd = ::open(path, (mode == AccessMode::READ_ONLY) ? OMODE_RO : OMODE_RW)) == -1)
50 {
51 throw std::system_error(errno, std::generic_category(), "Could not open shared memory segment.");
52 }

◆ EVENT_DATA_FILE_NAME

auto mxl::lib::EVENT_DATA_FILE_NAME = "events"
inlineconstexpr

Filename of the single shared-memory event ring within a flow directory.

Definition at line 22 of file PathUtils.hpp.

◆ EVENT_HEADER_VERSION

auto mxl::lib::EVENT_HEADER_VERSION = std::uint32_t{1}
inlineconstexpr

Version stored in the public mxlEventInfo metadata of every published entry.

Definition at line 61 of file Flow.hpp.

61{1};

◆ FLOW_ACCESS_FILE_NAME

auto const mxl::lib::FLOW_ACCESS_FILE_NAME = "access"
inlineconstexpr

Definition at line 17 of file PathUtils.hpp.

◆ FLOW_DATA_FILE_NAME

auto const mxl::lib::FLOW_DATA_FILE_NAME = "data"
inlineconstexpr

Definition at line 16 of file PathUtils.hpp.

◆ FLOW_DATA_VERSION

auto mxl::lib::FLOW_DATA_VERSION = 1U
inlineconstexpr

The version of the flow data structs in shared memory that we expect and support.

Definition at line 21 of file Flow.hpp.

◆ FLOW_DESCRIPTOR_FILE_NAME

auto const mxl::lib::FLOW_DESCRIPTOR_FILE_NAME = "flow_def.json"
inlineconstexpr

Definition at line 15 of file PathUtils.hpp.

◆ FLOW_DIRECTORY_NAME_SUFFIX

auto const mxl::lib::FLOW_DIRECTORY_NAME_SUFFIX = ".mxl-flow"
inlineconstexpr

Definition at line 14 of file PathUtils.hpp.

◆ GRAIN_DATA_FILE_NAME_STEM

auto const mxl::lib::GRAIN_DATA_FILE_NAME_STEM = "data"
inlineconstexpr

Definition at line 19 of file PathUtils.hpp.

◆ GRAIN_DIRECTORY_NAME

auto const mxl::lib::GRAIN_DIRECTORY_NAME = "grains"
inlineconstexpr

Definition at line 18 of file PathUtils.hpp.

◆ GRAIN_HEADER_VERSION

auto mxl::lib::GRAIN_HEADER_VERSION = 1U
inlineconstexpr

The version of the grain header structs in shared memory that we expect an support.

Definition at line 24 of file Flow.hpp.

◆ MXL_GRAIN_PAYLOAD_OFFSET

auto const mxl::lib::MXL_GRAIN_PAYLOAD_OFFSET = std::size_t{8192}
inlineconstexpr

The first 8KiB of a grain are reserved for the mxlGrainInfo structure, including user data. Ample padding is provided between the header and the payload. Payload is page aligned AND AVX512 (64 bytes) aligned.

Definition at line 38 of file Flow.hpp.

38{8192};