labrecorder 1.0.0rc0__cp311-cp311-macosx_26_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of labrecorder might be problematic. Click here for more details.

@@ -0,0 +1,1720 @@
1
+ #ifndef LSL_CPP_H
2
+ #define LSL_CPP_H
3
+
4
+ /**
5
+ * @file lsl_cpp.h
6
+ *
7
+ * C++ API for the lab streaming layer.
8
+ *
9
+ * The lab streaming layer provides a set of functions to make instrument data accessible
10
+ * in real time within a lab network. From there, streams can be picked up by recording programs,
11
+ * viewing programs or custom experiment applications that access data streams in real time.
12
+ *
13
+ * The API covers two areas:
14
+ * - The "push API" allows to create stream outlets and to push data (regular or irregular
15
+ * measurement time series, event data, coded audio/video frames, etc.) into them.
16
+ * - The "pull API" allows to create stream inlets and read time-synched experiment data from them
17
+ * (for recording, viewing or experiment control).
18
+ *
19
+ * To use this library you need to link to the shared library (lsl) that comes with
20
+ * this header. Under Visual Studio the library is linked in automatically.
21
+ */
22
+
23
+ #include <memory>
24
+ #include <stdexcept>
25
+ #include <string>
26
+ #include <vector>
27
+
28
+ extern "C" {
29
+ #include "lsl_c.h"
30
+ }
31
+
32
+ namespace lsl {
33
+ /// Assert that no error happened; throw appropriate exception otherwise
34
+ int32_t check_error(int32_t ec);
35
+
36
+ /// Constant to indicate that a stream has variable sampling rate.
37
+ const double IRREGULAR_RATE = 0.0;
38
+
39
+ /**
40
+ * Constant to indicate that a sample has the next successive time stamp.
41
+ *
42
+ * This is an optional optimization to transmit less data per sample.
43
+ * The stamp is then deduced from the preceding one according to the stream's sampling rate
44
+ * (in the case of an irregular rate, the same time stamp as before will is assumed).
45
+ */
46
+ const double DEDUCED_TIMESTAMP = -1.0;
47
+
48
+ /**
49
+ * A very large time duration (> 1 year) for timeout values.
50
+ *
51
+ * Note that significantly larger numbers can cause the timeout to be invalid on some operating
52
+ * systems (e.g., 32-bit UNIX).
53
+ */
54
+ const double FOREVER = 32000000.0;
55
+
56
+ /// Data format of a channel (each transmitted sample holds an array of channels).
57
+ enum channel_format_t {
58
+ /** For up to 24-bit precision measurements in the appropriate physical unit (e.g., microvolts).
59
+ Integers from -16777216 to 16777216 are represented accurately.*/
60
+ cf_float32 = 1,
61
+ /// For universal numeric data as long as permitted by network & disk budget.
62
+ /// The largest representable integer is 53-bit.
63
+ cf_double64 = 2,
64
+ /// For variable-length ASCII strings or data blobs, such as video frames, complex event
65
+ /// descriptions, etc.
66
+ cf_string = 3,
67
+ /// For high-rate digitized formats that require 32-bit precision.
68
+ /// Depends critically on meta-data to represent meaningful units.
69
+ /// Useful for application event codes or other coded data.
70
+ cf_int32 = 4,
71
+ /// For very high rate signals (40Khz+) or consumer-grade audio (for professional audio float is
72
+ /// recommended).
73
+ cf_int16 = 5,
74
+ /// For binary signals or other coded data. Not recommended for encoding string data.
75
+ cf_int8 = 6,
76
+ /// For now only for future compatibility. Support for this type is not yet exposed in all
77
+ /// languages. Also, some builds of liblsl will not be able to send or receive data of this
78
+ /// type.
79
+ cf_int64 = 7,
80
+ /// Can not be transmitted.
81
+ cf_undefined = 0
82
+ };
83
+
84
+ /// Post-processing options for stream inlets.
85
+ enum processing_options_t {
86
+ /// No automatic post-processing; return the ground-truth time stamps for manual post-processing
87
+ /// (this is the default behavior of the inlet).
88
+ post_none = 0,
89
+ /// Perform automatic clock synchronization; equivalent to manually adding the time_correction()
90
+ /// value to the received time stamps.
91
+ post_clocksync = 1,
92
+ /// Remove jitter from time stamps. This will apply a smoothing algorithm to the received time
93
+ /// stamps; the smoothing needs to see a minimum number of samples (30-120 seconds worst-case)
94
+ /// until the remaining jitter is consistently below 1ms.
95
+ post_dejitter = 2,
96
+ /// Force the time-stamps to be monotonically ascending (only makes sense if timestamps are
97
+ /// dejittered).
98
+ post_monotonize = 4,
99
+ /// Post-processing is thread-safe (same inlet can be read from by multiple threads); uses
100
+ /// somewhat more CPU.
101
+ post_threadsafe = 8,
102
+ /// The combination of all possible post-processing options.
103
+ post_ALL = 1 | 2 | 4 | 8
104
+ };
105
+
106
+ /**
107
+ * Protocol version.
108
+ *
109
+ * The major version is `protocol_version() / 100`;
110
+ * The minor version is `protocol_version() % 100`;
111
+ * Clients with different minor versions are protocol-compatible with each other
112
+ * while clients with different major versions will refuse to work together.
113
+ */
114
+ inline int32_t protocol_version() { return lsl_protocol_version(); }
115
+
116
+ /// @copydoc ::lsl_library_version()
117
+ inline int32_t library_version() { return lsl_library_version(); }
118
+
119
+ /**
120
+ * Get a string containing library information.
121
+ *
122
+ * The format of the string shouldn't be used for anything important except giving a a debugging
123
+ * person a good idea which exact library version is used. */
124
+ inline const char *library_info() { return lsl_library_info(); }
125
+
126
+ /**
127
+ * Obtain a local system time stamp in seconds.
128
+ *
129
+ * The resolution is better than a millisecond.
130
+ * This reading can be used to assign time stamps to samples as they are being acquired.
131
+ * If the "age" of a sample is known at a particular time (e.g., from USB transmission
132
+ * delays), it can be used as an offset to local_clock() to obtain a better estimate of
133
+ * when a sample was actually captured. See stream_outlet::push_sample() for a use case.
134
+ */
135
+ inline double local_clock() { return lsl_local_clock(); }
136
+
137
+
138
+ /// @section Stream Declaration
139
+
140
+ class xml_element;
141
+
142
+ /**
143
+ * The stream_info object stores the declaration of a data stream.
144
+ *
145
+ * Represents the following information:
146
+ * a) stream data format (number of channels, channel format)
147
+ * b) core information (stream name, content type, sampling rate)
148
+ * c) optional meta-data about the stream content (channel labels, measurement units, etc.)
149
+ *
150
+ * Whenever a program wants to provide a new stream on the lab network it will typically first
151
+ * create a stream_info to describe its properties and then construct a stream_outlet with it to
152
+ * create the stream on the network. Recipients who discover the outlet can query the stream_info;
153
+ * it is also written to disk when recording the stream (playing a similar role as a file header).
154
+ */
155
+ class stream_info {
156
+ public:
157
+ /**
158
+ * Construct a new stream_info object.
159
+ *
160
+ * Core stream information is specified here. Any remaining meta-data can be added later.
161
+ * @param name Name of the stream. Describes the device (or product series) that this stream
162
+ * makes available (for use by programs, experimenters or data analysts). Cannot be empty.
163
+ * @param type Content type of the stream. Please see https://github.com/sccn/xdf/wiki/Meta-Data
164
+ * (or web search for: XDF meta-data) for pre-defined content-type names, but you can also make
165
+ * up your own. The content type is the preferred way to find streams (as opposed to searching
166
+ * by name).
167
+ * @param channel_count Number of channels per sample. This stays constant for the lifetime of
168
+ * the stream.
169
+ * @param nominal_srate The sampling rate (in Hz) as advertised by the data source, if regular
170
+ * (otherwise set to IRREGULAR_RATE).
171
+ * @param channel_format Format/type of each channel. If your channels have different formats,
172
+ * consider supplying multiple streams or use the largest type that can hold them all (such as
173
+ * cf_double64).
174
+ * @param source_id Unique identifier of the device or source of the data, if available (such as
175
+ * the serial number). This is critical for system robustness since it allows recipients to
176
+ * recover from failure even after the serving app, device or computer crashes (just by finding
177
+ * a stream with the same source id on the network again). Therefore, it is highly recommended
178
+ * to always try to provide whatever information can uniquely identify the data source itself.
179
+ */
180
+ stream_info(const std::string &name, const std::string &type, int32_t channel_count = 1,
181
+ double nominal_srate = IRREGULAR_RATE, channel_format_t channel_format = cf_float32,
182
+ const std::string &source_id = std::string())
183
+ : obj(lsl_create_streaminfo((name.c_str()), (type.c_str()), channel_count, nominal_srate,
184
+ (lsl_channel_format_t)channel_format, (source_id.c_str())), &lsl_destroy_streaminfo) {
185
+ if (obj == nullptr) throw std::invalid_argument(lsl_last_error());
186
+ }
187
+
188
+ /// Default contructor.
189
+ stream_info(): stream_info("untitled", "", 0, 0, cf_undefined, ""){}
190
+
191
+ /// Copy constructor. Only increments the reference count! @see clone()
192
+ stream_info(const stream_info &) noexcept = default;
193
+ stream_info(lsl_streaminfo handle) : obj(handle, &lsl_destroy_streaminfo) {}
194
+
195
+ /// Clones a streaminfo object.
196
+ stream_info clone() { return stream_info(lsl_copy_streaminfo(obj.get())); }
197
+
198
+
199
+ // ========================
200
+ // === Core Information ===
201
+ // ========================
202
+ // (these fields are assigned at construction)
203
+
204
+ /**
205
+ * Name of the stream.
206
+ *
207
+ * This is a human-readable name. For streams offered by device modules, it refers to the type
208
+ * of device or product series that is generating the data of the stream. If the source is an
209
+ * application, the name may be a more generic or specific identifier. Multiple streams with the
210
+ * same name can coexist, though potentially at the cost of ambiguity (for the recording app or
211
+ * experimenter).
212
+ */
213
+ std::string name() const { return lsl_get_name(obj.get()); }
214
+
215
+ /**
216
+ * Content type of the stream.
217
+ *
218
+ * The content type is a short string such as "EEG", "Gaze" which describes the content carried
219
+ * by the channel (if known). If a stream contains mixed content this value need not be assigned
220
+ * but may instead be stored in the description of channel types. To be useful to applications
221
+ * and automated processing systems using the recommended content types is preferred. Content
222
+ * types usually follow those pre-defined in https://github.com/sccn/xdf/wiki/Meta-Data (or web
223
+ * search for: XDF meta-data).
224
+ */
225
+ std::string type() const { return lsl_get_type(obj.get()); }
226
+
227
+ /**
228
+ * Number of channels of the stream.
229
+ *
230
+ * A stream has at least one channel; the channel count stays constant for all samples.
231
+ */
232
+ int32_t channel_count() const { return lsl_get_channel_count(obj.get()); }
233
+
234
+ /**
235
+ * Sampling rate of the stream, according to the source (in Hz).
236
+ *
237
+ * If a stream is irregularly sampled, this should be set to IRREGULAR_RATE.
238
+ *
239
+ * Note that no data will be lost even if this sampling rate is incorrect or if a device has
240
+ * temporary hiccups, since all samples will be recorded anyway (except for those dropped by the
241
+ * device itself). However, when the recording is imported into an application, a good importer
242
+ * may correct such errors more accurately if the advertised sampling rate was close to the
243
+ * specs of the device.
244
+ */
245
+ double nominal_srate() const { return lsl_get_nominal_srate(obj.get()); }
246
+
247
+ /**
248
+ * Channel format of the stream.
249
+ *
250
+ * All channels in a stream have the same format. However, a device might offer multiple
251
+ * time-synched streams each with its own format.
252
+ */
253
+ channel_format_t channel_format() const {
254
+ return static_cast<channel_format_t>(lsl_get_channel_format(obj.get()));
255
+ }
256
+
257
+ /**
258
+ * Unique identifier of the stream's source, if available.
259
+ *
260
+ * The unique source (or device) identifier is an optional piece of information that, if
261
+ * available, allows that endpoints (such as the recording program) can re-acquire a stream
262
+ * automatically once it is back online.
263
+ */
264
+ std::string source_id() const { return lsl_get_source_id(obj.get()); }
265
+
266
+
267
+ // ======================================
268
+ // === Additional Hosting Information ===
269
+ // ======================================
270
+ // (these fields are implicitly assigned once bound to an outlet/inlet)
271
+
272
+ /// Protocol version used to deliver the stream.
273
+ int32_t version() const { return lsl_get_version(obj.get()); }
274
+
275
+ /**
276
+ * Creation time stamp of the stream.
277
+ *
278
+ * This is the time stamp when the stream was first created
279
+ * (as determined via #lsl::local_clock() on the providing machine).
280
+ */
281
+ double created_at() const { return lsl_get_created_at(obj.get()); }
282
+
283
+ /**
284
+ * Unique ID of the stream outlet instance (once assigned).
285
+ *
286
+ * This is a unique identifier of the stream outlet, and is guaranteed to be different
287
+ * across multiple instantiations of the same outlet (e.g., after a re-start).
288
+ */
289
+ std::string uid() const { return lsl_get_uid(obj.get()); }
290
+
291
+ /**
292
+ * Session ID for the given stream.
293
+ *
294
+ * The session id is an optional human-assigned identifier of the recording session.
295
+ * While it is rarely used, it can be used to prevent concurrent recording activitites
296
+ * on the same sub-network (e.g., in multiple experiment areas) from seeing each other's streams
297
+ * (assigned via a configuration file by the experimenter, see Network Connectivity in the LSL
298
+ * wiki).
299
+ */
300
+ std::string session_id() const { return lsl_get_session_id(obj.get()); }
301
+
302
+ /// Hostname of the providing machine.
303
+ std::string hostname() const { return lsl_get_hostname(obj.get()); }
304
+
305
+
306
+ // ========================
307
+ // === Data Description ===
308
+ // ========================
309
+
310
+ /**
311
+ * Extended description of the stream.
312
+ *
313
+ * It is highly recommended that at least the channel labels are described here.
314
+ * See code examples on the LSL wiki. Other information, such as amplifier settings,
315
+ * measurement units if deviating from defaults, setup information, subject information, etc.,
316
+ * can be specified here, as well. Meta-data recommendations follow the XDF file format project
317
+ * (github.com/sccn/xdf/wiki/Meta-Data or web search for: XDF meta-data).
318
+ *
319
+ * Important: if you use a stream content type for which meta-data recommendations exist, please
320
+ * try to lay out your meta-data in agreement with these recommendations for compatibility with
321
+ * other applications.
322
+ */
323
+ xml_element desc();
324
+
325
+ /// lsl_stream_info_matches_query
326
+ bool matches_query(const char *query) const {
327
+ return lsl_stream_info_matches_query(obj.get(), query) != 0;
328
+ }
329
+
330
+
331
+ // ===============================
332
+ // === Miscellaneous Functions ===
333
+ // ===============================
334
+
335
+ /** Retrieve the entire streaminfo in XML format.
336
+ * This yields an XML document (in string form) whose top-level element is `<info>`. The info
337
+ * element contains one element for each field of the streaminfo class, including:
338
+ *
339
+ * - the core elements `<name>`, `<type>`, `<channel_count>`, `<nominal_srate>`,
340
+ * `<channel_format>`, `<source_id>`
341
+ * - the misc elements `<version>`, `<created_at>`, `<uid>`, `<session_id>`,
342
+ * `<v4address>`, `<v4data_port>`, `<v4service_port>`, `<v6address>`, `<v6data_port>`,
343
+ * `<v6service_port>`
344
+ * - the extended description element `<desc>` with user-defined sub-elements.
345
+ */
346
+ std::string as_xml() const {
347
+ char *tmp = lsl_get_xml(obj.get());
348
+ std::string result(tmp);
349
+ lsl_destroy_string(tmp);
350
+ return result;
351
+ }
352
+
353
+ /// Number of bytes occupied by a channel (0 for string-typed channels).
354
+ int32_t channel_bytes() const { return lsl_get_channel_bytes(obj.get()); }
355
+
356
+ /// Number of bytes occupied by a sample (0 for string-typed channels).
357
+ int32_t sample_bytes() const { return lsl_get_sample_bytes(obj.get()); }
358
+
359
+ /// Get the implementation handle.
360
+ std::shared_ptr<lsl_streaminfo_struct_> handle() const { return obj; }
361
+
362
+ /// Assignment operator.
363
+ stream_info &operator=(const stream_info &rhs) {
364
+ if (this != &rhs) obj = stream_info(rhs).handle();
365
+ return *this;
366
+ }
367
+
368
+ stream_info(stream_info &&rhs) noexcept = default;
369
+
370
+ stream_info &operator=(stream_info &&rhs) noexcept = default;
371
+
372
+ /// Utility function to create a stream_info from an XML representation
373
+ static stream_info from_xml(const std::string &xml) {
374
+ return stream_info(lsl_streaminfo_from_xml(xml.c_str()));
375
+ }
376
+
377
+ private:
378
+ std::shared_ptr<lsl_streaminfo_struct_> obj;
379
+ };
380
+
381
+
382
+ // =======================
383
+ // ==== Stream Outlet ====
384
+ // =======================
385
+
386
+ /** A stream outlet.
387
+ * Outlets are used to make streaming data (and the meta-data) available on the lab network.
388
+ */
389
+ class stream_outlet {
390
+ public:
391
+ /** Establish a new stream outlet. This makes the stream discoverable.
392
+ * @param info The stream information to use for creating this stream. Stays constant over the
393
+ * lifetime of the outlet.
394
+ * @param chunk_size Optionally the desired chunk granularity (in samples) for transmission. If
395
+ * unspecified, each push operation yields one chunk. Inlets can override this setting.
396
+ * @param max_buffered Optionally the maximum amount of data to buffer (in seconds if there is a
397
+ * nominal sampling rate, otherwise x100 in samples). The default is 6 minutes of data.
398
+ */
399
+ stream_outlet(const stream_info &info, int32_t chunk_size = 0, int32_t max_buffered = 360,
400
+ lsl_transport_options_t flags = transp_default)
401
+ : channel_count(info.channel_count()), sample_rate(info.nominal_srate()),
402
+ obj(lsl_create_outlet_ex(info.handle().get(), chunk_size, max_buffered, flags),
403
+ &lsl_destroy_outlet) {}
404
+
405
+ // ========================================
406
+ // === Pushing a sample into the outlet ===
407
+ // ========================================
408
+
409
+ /** Push a C array of values as a sample into the outlet.
410
+ * Each entry in the array corresponds to one channel.
411
+ * The function handles type checking & conversion.
412
+ * @param data An array of values to push (one per channel).
413
+ * @param timestamp Optionally the capture time of the sample, in agreement with
414
+ * lsl::local_clock(); if omitted, the current time is used.
415
+ * @param pushthrough Whether to push the sample through to the receivers instead of
416
+ * buffering it with subsequent samples.
417
+ * Note that the chunk_size, if specified at outlet construction, takes precedence over the
418
+ * pushthrough flag.
419
+ */
420
+ template <class T, int32_t N>
421
+ void push_sample(const T data[N], double timestamp = 0.0, bool pushthrough = true) {
422
+ check_numchan(N);
423
+ push_sample(&data[0], timestamp, pushthrough);
424
+ }
425
+
426
+ /** Push a std vector of values as a sample into the outlet.
427
+ * Each entry in the vector corresponds to one channel. The function handles type checking &
428
+ * conversion.
429
+ * @param data A vector of values to push (one for each channel).
430
+ * @param timestamp Optionally the capture time of the sample, in agreement with local_clock();
431
+ * if omitted, the current time is used.
432
+ * @param pushthrough Whether to push the sample through to the receivers instead of buffering
433
+ * it with subsequent samples. Note that the chunk_size, if specified at outlet construction,
434
+ * takes precedence over the pushthrough flag.
435
+ */
436
+ template<typename T>
437
+ void push_sample(
438
+ const std::vector<T> &data, double timestamp = 0.0, bool pushthrough = true) {
439
+ check_numchan(data.size());
440
+ push_sample(data.data(), timestamp, pushthrough);
441
+ }
442
+
443
+ /** Push a pointer to some values as a sample into the outlet.
444
+ * This is a lower-level function for cases where data is available in some buffer.
445
+ * Handles type checking & conversion.
446
+ * @param data A pointer to values to push. The number of values pointed to must not be less
447
+ * than the number of channels in the sample.
448
+ * @param timestamp Optionally the capture time of the sample, in agreement with local_clock();
449
+ * if omitted, the current time is used.
450
+ * @param pushthrough Whether to push the sample through to the receivers instead of buffering
451
+ * it with subsequent samples. Note that the chunk_size, if specified at outlet construction,
452
+ * takes precedence over the pushthrough flag.
453
+ */
454
+ void push_sample(const float *data, double timestamp = 0.0, bool pushthrough = true) {
455
+ lsl_push_sample_ftp(obj.get(), (data), timestamp, pushthrough);
456
+ }
457
+ void push_sample(const double *data, double timestamp = 0.0, bool pushthrough = true) {
458
+ lsl_push_sample_dtp(obj.get(), (data), timestamp, pushthrough);
459
+ }
460
+ void push_sample(const int64_t *data, double timestamp = 0.0, bool pushthrough = true) {
461
+ lsl_push_sample_ltp(obj.get(), (data), timestamp, pushthrough);
462
+ }
463
+ void push_sample(const int32_t *data, double timestamp = 0.0, bool pushthrough = true) {
464
+ lsl_push_sample_itp(obj.get(), (data), timestamp, pushthrough);
465
+ }
466
+ void push_sample(const int16_t *data, double timestamp = 0.0, bool pushthrough = true) {
467
+ lsl_push_sample_stp(obj.get(), (data), timestamp, pushthrough);
468
+ }
469
+ void push_sample(const char *data, double timestamp = 0.0, bool pushthrough = true) {
470
+ lsl_push_sample_ctp(obj.get(), (data), timestamp, pushthrough);
471
+ }
472
+ void push_sample(const std::string *data, double timestamp = 0.0, bool pushthrough = true) {
473
+ std::vector<uint32_t> lengths(channel_count);
474
+ std::vector<const char *> pointers(channel_count);
475
+ for (int32_t k = 0; k < channel_count; k++) {
476
+ pointers[k] = data[k].c_str();
477
+ lengths[k] = (uint32_t)data[k].size();
478
+ }
479
+ lsl_push_sample_buftp(obj.get(), pointers.data(), lengths.data(), timestamp, pushthrough);
480
+ }
481
+
482
+ /** Push a packed C struct (of numeric data) as one sample into the outlet (search for
483
+ * [`#``pragma pack`](https://stackoverflow.com/a/3318475/73299) for information on packing
484
+ * structs appropriately).<br>
485
+ * Overall size checking but no type checking or conversion are done.<br>
486
+ * Can not be used forvariable-size / string-formatted data.
487
+ * @param sample The sample struct to push.
488
+ * @param timestamp Optionally the capture time of the sample, in agreement with
489
+ * local_clock(); if omitted, the current time is used.
490
+ * @param pushthrough Whether to push the sample through to the receivers instead of
491
+ * buffering it with subsequent samples. Note that the chunk_size, if specified at outlet
492
+ * construction, takes precedence over the pushthrough flag.
493
+ */
494
+ template <class T>
495
+ void push_numeric_struct(const T &sample, double timestamp = 0.0, bool pushthrough = true) {
496
+ if (info().sample_bytes() != sizeof(T))
497
+ throw std::runtime_error(
498
+ "Provided object size does not match the stream's sample size.");
499
+ push_numeric_raw((void *)&sample, timestamp, pushthrough);
500
+ }
501
+
502
+ /** Push a pointer to raw numeric data as one sample into the outlet.
503
+ * This is the lowest-level function; performs no checking whatsoever. Cannot be used for
504
+ * variable-size / string-formatted channels.
505
+ * @param sample A pointer to the raw sample data to push.
506
+ * @param timestamp Optionally the capture time of the sample, in agreement with local_clock();
507
+ * if omitted, the current time is used.
508
+ * @param pushthrough Whether to push the sample through to the receivers instead of buffering
509
+ * it with subsequent samples. Note that the chunk_size, if specified at outlet construction,
510
+ * takes precedence over the pushthrough flag.
511
+ */
512
+ void push_numeric_raw(const void *sample, double timestamp = 0.0, bool pushthrough = true) {
513
+ lsl_push_sample_vtp(obj.get(), (sample), timestamp, pushthrough);
514
+ }
515
+
516
+
517
+ // ===================================================
518
+ // === Pushing an chunk of samples into the outlet ===
519
+ // ===================================================
520
+
521
+ /** Push a chunk of samples (batched into an STL vector) into the outlet.
522
+ * @param samples A vector of samples in some supported format (each sample can be a data
523
+ * pointer, data array, or std vector of data).
524
+ * @param timestamp Optionally the capture time of the most recent sample, in agreement with
525
+ * local_clock(); if omitted, the current time is used. The time stamps of other samples are
526
+ * automatically derived according to the sampling rate of the stream.
527
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
528
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
529
+ * precedence over the pushthrough flag.
530
+ */
531
+ template <class T>
532
+ void push_chunk(
533
+ const std::vector<T> &samples, double timestamp = 0.0, bool pushthrough = true) {
534
+ if (!samples.empty()) {
535
+ if (timestamp == 0.0) timestamp = local_clock();
536
+ if (sample_rate != IRREGULAR_RATE)
537
+ timestamp = timestamp - (samples.size() - 1) / sample_rate;
538
+ push_sample(samples[0], timestamp, pushthrough && samples.size() == 1);
539
+ for (std::size_t k = 1; k < samples.size(); k++)
540
+ push_sample(samples[k], DEDUCED_TIMESTAMP, pushthrough && k == samples.size() - 1);
541
+ }
542
+ }
543
+
544
+ /** Push a chunk of samples (batched into an STL vector) into the outlet.
545
+ * Allows to specify a separate time stamp for each sample (for irregular-rate streams).
546
+ * @param samples A vector of samples in some supported format (each sample can be a data
547
+ * pointer, data array, or std vector of data).
548
+ * @param timestamps A vector of capture times for each sample, in agreement with local_clock().
549
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
550
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
551
+ * precedence over the pushthrough flag.
552
+ */
553
+ template <class T>
554
+ void push_chunk(const std::vector<T> &samples, const std::vector<double> &timestamps,
555
+ bool pushthrough = true) {
556
+ for (unsigned k = 0; k < samples.size() - 1; k++)
557
+ push_sample(samples[k], timestamps[k], false);
558
+ if (!samples.empty()) push_sample(samples.back(), timestamps.back(), pushthrough);
559
+ }
560
+
561
+ /** Push a chunk of numeric data as C-style structs (batched into an STL vector) into the
562
+ * outlet. This performs some size checking but no type checking. Can not be used for
563
+ * variable-size / string-formatted data.
564
+ * @param samples A vector of samples, as C structs.
565
+ * @param timestamp Optionally the capture time of the sample, in agreement with local_clock();
566
+ * if omitted, the current time is used.
567
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
568
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
569
+ * precedence over the pushthrough flag.
570
+ */
571
+ template <class T>
572
+ void push_chunk_numeric_structs(
573
+ const std::vector<T> &samples, double timestamp = 0.0, bool pushthrough = true) {
574
+ if (!samples.empty()) {
575
+ if (timestamp == 0.0) timestamp = local_clock();
576
+ if (sample_rate != IRREGULAR_RATE)
577
+ timestamp = timestamp - (samples.size() - 1) / sample_rate;
578
+ push_numeric_struct(samples[0], timestamp, pushthrough && samples.size() == 1);
579
+ for (std::size_t k = 1; k < samples.size(); k++)
580
+ push_numeric_struct(
581
+ samples[k], DEDUCED_TIMESTAMP, pushthrough && k == samples.size() - 1);
582
+ }
583
+ }
584
+
585
+ /** Push a chunk of numeric data from C-style structs (batched into an STL vector), into the
586
+ * outlet. This performs some size checking but no type checking. Can not be used for
587
+ * variable-size / string-formatted data.
588
+ * @param samples A vector of samples, as C structs.
589
+ * @param timestamps A vector of capture times for each sample, in agreement with local_clock().
590
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
591
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
592
+ * precedence over the pushthrough flag.
593
+ */
594
+ template <class T>
595
+ void push_chunk_numeric_structs(const std::vector<T> &samples,
596
+ const std::vector<double> &timestamps, bool pushthrough = true) {
597
+ for (unsigned k = 0; k < samples.size() - 1; k++)
598
+ push_numeric_struct(samples[k], timestamps[k], false);
599
+ if (!samples.empty()) push_numeric_struct(samples.back(), timestamps.back(), pushthrough);
600
+ }
601
+
602
+ /** Push a chunk of multiplexed data into the outlet.
603
+ * @name Push functions
604
+ * @param buffer A buffer of channel values holding the data for zero or more successive samples
605
+ * to send.
606
+ * @param timestamp Optionally the capture time of the most recent sample, in agreement with
607
+ * local_clock(); if omitted, the current time is used. The time stamps of other samples are
608
+ * automatically derived according to the sampling rate of the stream.
609
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
610
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
611
+ * precedence over the pushthrough flag.
612
+ */
613
+ template<typename T>
614
+ void push_chunk_multiplexed(
615
+ const std::vector<T> &buffer, double timestamp = 0.0, bool pushthrough = true) {
616
+ if (!buffer.empty())
617
+ push_chunk_multiplexed(
618
+ buffer.data(), static_cast<unsigned long>(buffer.size()), timestamp, pushthrough);
619
+ }
620
+
621
+ /** Push a chunk of multiplexed data into the outlet. One timestamp per sample is provided.
622
+ * Allows to specify a separate time stamp for each sample (for irregular-rate streams).
623
+ * @param buffer A buffer of channel values holding the data for zero or more successive samples
624
+ * to send.
625
+ * @param timestamps A buffer of timestamp values holding time stamps for each sample in the
626
+ * data buffer.
627
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
628
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
629
+ * precedence over the pushthrough flag.
630
+ */
631
+ template<typename T>
632
+ void push_chunk_multiplexed(const std::vector<T> &buffer,
633
+ const std::vector<double> &timestamps, bool pushthrough = true) {
634
+ if (!buffer.empty() && !timestamps.empty())
635
+ push_chunk_multiplexed(
636
+ buffer.data(), static_cast<unsigned long>(buffer.size()), timestamps.data(), pushthrough);
637
+ }
638
+
639
+ /** Push a chunk of multiplexed samples into the outlet. Single timestamp provided.
640
+ * @warning The provided buffer size is measured in channel values (e.g., floats), not samples.
641
+ * @param buffer A buffer of channel values holding the data for zero or more successive samples
642
+ * to send.
643
+ * @param buffer_elements The number of channel values (of type T) in the buffer. Must be a
644
+ * multiple of the channel count.
645
+ * @param timestamp Optionally the capture time of the most recent sample, in agreement with
646
+ * local_clock(); if omitted, the current time is used. The time stamps of other samples are
647
+ * automatically derived based on the sampling rate of the stream.
648
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
649
+ * with subsequent samples. Note that the stream_outlet() constructur parameter @p chunk_size,
650
+ * if specified at outlet construction, takes precedence over the pushthrough flag.
651
+ */
652
+ void push_chunk_multiplexed(const float *buffer, std::size_t buffer_elements,
653
+ double timestamp = 0.0, bool pushthrough = true) {
654
+ lsl_push_chunk_ftp(obj.get(), buffer, static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
655
+ }
656
+ void push_chunk_multiplexed(const double *buffer, std::size_t buffer_elements,
657
+ double timestamp = 0.0, bool pushthrough = true) {
658
+ lsl_push_chunk_dtp(obj.get(), buffer, static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
659
+ }
660
+ void push_chunk_multiplexed(const int64_t *buffer, std::size_t buffer_elements,
661
+ double timestamp = 0.0, bool pushthrough = true) {
662
+ lsl_push_chunk_ltp(obj.get(), buffer, static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
663
+ }
664
+ void push_chunk_multiplexed(const int32_t *buffer, std::size_t buffer_elements,
665
+ double timestamp = 0.0, bool pushthrough = true) {
666
+ lsl_push_chunk_itp(obj.get(), buffer, static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
667
+ }
668
+ void push_chunk_multiplexed(const int16_t *buffer, std::size_t buffer_elements,
669
+ double timestamp = 0.0, bool pushthrough = true) {
670
+ lsl_push_chunk_stp(obj.get(), buffer, static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
671
+ }
672
+ void push_chunk_multiplexed(const char *buffer, std::size_t buffer_elements,
673
+ double timestamp = 0.0, bool pushthrough = true) {
674
+ lsl_push_chunk_ctp(obj.get(), buffer, static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
675
+ }
676
+ void push_chunk_multiplexed(const std::string *buffer, std::size_t buffer_elements,
677
+ double timestamp = 0.0, bool pushthrough = true) {
678
+ if (buffer_elements) {
679
+ std::vector<uint32_t> lengths(buffer_elements);
680
+ std::vector<const char *> pointers(buffer_elements);
681
+ for (std::size_t k = 0; k < buffer_elements; k++) {
682
+ pointers[k] = buffer[k].c_str();
683
+ lengths[k] = (uint32_t)buffer[k].size();
684
+ }
685
+ lsl_push_chunk_buftp(obj.get(), pointers.data(), lengths.data(),
686
+ static_cast<unsigned long>(buffer_elements), timestamp, pushthrough);
687
+ }
688
+ }
689
+
690
+ /** Push a chunk of multiplexed samples into the outlet. One timestamp per sample is provided.
691
+ * @warning Note that the provided buffer size is measured in channel values (e.g., floats)
692
+ * rather than in samples.
693
+ * @param data_buffer A buffer of channel values holding the data for zero or more successive
694
+ * samples to send.
695
+ * @param timestamp_buffer A buffer of timestamp values holding time stamps for each sample in
696
+ * the data buffer.
697
+ * @param data_buffer_elements The number of data values (of type T) in the data buffer. Must be
698
+ * a multiple of the channel count.
699
+ * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it
700
+ * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes
701
+ * precedence over the pushthrough flag.
702
+ */
703
+ void push_chunk_multiplexed(const float *data_buffer, const double *timestamp_buffer,
704
+ std::size_t data_buffer_elements, bool pushthrough = true) {
705
+ lsl_push_chunk_ftnp(obj.get(), data_buffer, static_cast<unsigned long>(data_buffer_elements),
706
+ (timestamp_buffer), pushthrough);
707
+ }
708
+ void push_chunk_multiplexed(const double *data_buffer, const double *timestamp_buffer,
709
+ std::size_t data_buffer_elements, bool pushthrough = true) {
710
+ lsl_push_chunk_dtnp(obj.get(), data_buffer, static_cast<unsigned long>(data_buffer_elements),
711
+ (timestamp_buffer), pushthrough);
712
+ }
713
+ void push_chunk_multiplexed(const int64_t *data_buffer, const double *timestamp_buffer,
714
+ std::size_t data_buffer_elements, bool pushthrough = true) {
715
+ lsl_push_chunk_ltnp(obj.get(), data_buffer, static_cast<unsigned long>(data_buffer_elements),
716
+ (timestamp_buffer), pushthrough);
717
+ }
718
+ void push_chunk_multiplexed(const int32_t *data_buffer, const double *timestamp_buffer,
719
+ std::size_t data_buffer_elements, bool pushthrough = true) {
720
+ lsl_push_chunk_itnp(obj.get(), data_buffer, static_cast<unsigned long>(data_buffer_elements),
721
+ (timestamp_buffer), pushthrough);
722
+ }
723
+ void push_chunk_multiplexed(const int16_t *data_buffer, const double *timestamp_buffer,
724
+ std::size_t data_buffer_elements, bool pushthrough = true) {
725
+ lsl_push_chunk_stnp(obj.get(), data_buffer, static_cast<unsigned long>(data_buffer_elements),
726
+ (timestamp_buffer), pushthrough);
727
+ }
728
+ void push_chunk_multiplexed(const char *data_buffer, const double *timestamp_buffer,
729
+ std::size_t data_buffer_elements, bool pushthrough = true) {
730
+ lsl_push_chunk_ctnp(obj.get(), data_buffer, static_cast<unsigned long>(data_buffer_elements),
731
+ (timestamp_buffer), pushthrough);
732
+ }
733
+
734
+ void push_chunk_multiplexed(const std::string *data_buffer, const double *timestamp_buffer,
735
+ std::size_t data_buffer_elements, bool pushthrough = true) {
736
+ if (data_buffer_elements) {
737
+ std::vector<uint32_t> lengths(data_buffer_elements);
738
+ std::vector<const char *> pointers(data_buffer_elements);
739
+ for (std::size_t k = 0; k < data_buffer_elements; k++) {
740
+ pointers[k] = data_buffer[k].c_str();
741
+ lengths[k] = (uint32_t)data_buffer[k].size();
742
+ }
743
+ lsl_push_chunk_buftnp(obj.get(), pointers.data(), lengths.data(),
744
+ static_cast<unsigned long>(data_buffer_elements), timestamp_buffer, pushthrough);
745
+ }
746
+ }
747
+
748
+
749
+ // ===============================
750
+ // === Miscellaneous Functions ===
751
+ // ===============================
752
+
753
+ /** Check whether consumers are currently registered.
754
+ * While it does not hurt, there is technically no reason to push samples if there is no
755
+ * consumer.
756
+ */
757
+ bool have_consumers() { return lsl_have_consumers(obj.get()) != 0; }
758
+
759
+ /** Wait until some consumer shows up (without wasting resources).
760
+ * @return True if the wait was successful, false if the timeout expired.
761
+ */
762
+ bool wait_for_consumers(double timeout) { return lsl_wait_for_consumers(obj.get(), timeout) != 0; }
763
+
764
+ /** Retrieve the stream info provided by this outlet.
765
+ * This is what was used to create the stream (and also has the Additional Network Information
766
+ * fields assigned).
767
+ */
768
+ stream_info info() const { return stream_info(lsl_get_info(obj.get())); }
769
+
770
+ /// Return a shared pointer to pass to C-API functions that aren't wrapped yet
771
+ ///
772
+ /// Example: @code lsl_push_chunk_buft(outlet.handle().get(), data, …); @endcode
773
+ std::shared_ptr<lsl_outlet_struct_> handle() { return obj; }
774
+
775
+ /** Destructor.
776
+ * The stream will no longer be discoverable after destruction and all paired inlets will stop
777
+ * delivering data.
778
+ */
779
+ ~stream_outlet() = default;
780
+
781
+ /// stream_outlet move constructor
782
+ stream_outlet(stream_outlet &&res) noexcept = default;
783
+
784
+ stream_outlet &operator=(stream_outlet &&rhs) noexcept = default;
785
+
786
+
787
+ private:
788
+ // The outlet is a non-copyable object.
789
+ stream_outlet(const stream_outlet &rhs);
790
+ stream_outlet &operator=(const stream_outlet &rhs);
791
+
792
+ /// Check whether a given data length matches the number of channels; throw if not
793
+ void check_numchan(std::size_t N) const {
794
+ if (N != static_cast<std::size_t>(channel_count))
795
+ throw std::runtime_error("Provided element count (" + std::to_string(N) +
796
+ ") does not match the stream's channel count (" +
797
+ std::to_string(channel_count) + '.');
798
+ }
799
+
800
+ int32_t channel_count;
801
+ double sample_rate;
802
+ std::shared_ptr<lsl_outlet_struct_> obj;
803
+ };
804
+
805
+
806
+ // ===========================
807
+ // ==== Resolve Functions ====
808
+ // ===========================
809
+
810
+ /** Resolve all streams on the network.
811
+ * This function returns all currently available streams from any outlet on the network.
812
+ * The network is usually the subnet specified at the local router, but may also include
813
+ * a multicast group of machines (given that the network supports it), or list of hostnames.
814
+ * These details may optionally be customized by the experimenter in a configuration file
815
+ * (see Network Connectivity in the LSL wiki).
816
+ * This is the default mechanism used by the browsing programs and the recording program.
817
+ * @param wait_time The waiting time for the operation, in seconds, to search for streams.
818
+ * If this is too short (<0.5s) only a subset (or none) of the outlets that are present on the
819
+ * network may be returned.
820
+ * @return A vector of stream info objects (excluding their desc field), any of which can
821
+ * subsequently be used to open an inlet. The full info can be retrieve from the inlet.
822
+ */
823
+ inline std::vector<stream_info> resolve_streams(double wait_time = 1.0) {
824
+ lsl_streaminfo buffer[1024];
825
+ int nres = check_error(lsl_resolve_all(buffer, sizeof(buffer) / sizeof(lsl_streaminfo), wait_time));
826
+ return std::vector<stream_info>(&buffer[0], &buffer[nres]);
827
+ }
828
+
829
+ /** Resolve all streams with a specific value for a given property.
830
+ * If the goal is to resolve a specific stream, this method is preferred over resolving all streams
831
+ * and then selecting the desired one.
832
+ * @param prop The stream_info property that should have a specific value (e.g., "name", "type",
833
+ * "source_id", or "desc/manufaturer").
834
+ * @param value The string value that the property should have (e.g., "EEG" as the type property).
835
+ * @param minimum Return at least this number of streams.
836
+ * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout).
837
+ * If the timeout expires, less than the desired number of streams (possibly none)
838
+ * will be returned.
839
+ * @return A vector of matching stream info objects (excluding their meta-data), any of
840
+ * which can subsequently be used to open an inlet.
841
+ */
842
+ inline std::vector<stream_info> resolve_stream(const std::string &prop, const std::string &value,
843
+ int32_t minimum = 1, double timeout = FOREVER) {
844
+ lsl_streaminfo buffer[1024];
845
+ int nres = check_error(
846
+ lsl_resolve_byprop(buffer, sizeof(buffer) / sizeof(lsl_streaminfo), prop.c_str(), value.c_str(), minimum, timeout));
847
+ return std::vector<stream_info>(&buffer[0], &buffer[nres]);
848
+ }
849
+
850
+ /** Resolve all streams that match a given predicate.
851
+ *
852
+ * Advanced query that allows to impose more conditions on the retrieved streams; the given
853
+ * string is an [XPath 1.0](http://en.wikipedia.org/w/index.php?title=XPath_1.0) predicate for
854
+ * the `<info>` node (omitting the surrounding []'s)
855
+ * @param pred The predicate string, e.g. `name='BioSemi'` or
856
+ * `type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32`
857
+ * @param minimum Return at least this number of streams.
858
+ * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout).
859
+ * If the timeout expires, less than the desired number of streams (possibly
860
+ * none) will be returned.
861
+ * @return A vector of matching stream info objects (excluding their meta-data), any of
862
+ * which can subsequently be used to open an inlet.
863
+ */
864
+ inline std::vector<stream_info> resolve_stream(
865
+ const std::string &pred, int32_t minimum = 1, double timeout = FOREVER) {
866
+ lsl_streaminfo buffer[1024];
867
+ int nres =
868
+ check_error(lsl_resolve_bypred(buffer, sizeof(buffer) / sizeof(lsl_streaminfo), pred.c_str(), minimum, timeout));
869
+ return std::vector<stream_info>(&buffer[0], &buffer[nres]);
870
+ }
871
+
872
+
873
+ // ======================
874
+ // ==== Stream Inlet ====
875
+ // ======================
876
+
877
+ /** A stream inlet.
878
+ * Inlets are used to receive streaming data (and meta-data) from the lab network.
879
+ */
880
+ class stream_inlet {
881
+ public:
882
+ /**
883
+ * Construct a new stream inlet from a resolved stream info.
884
+ * @param info A resolved stream info object (as coming from one of the resolver functions).
885
+ * Note: The stream_inlet may also be constructed with a fully-specified stream_info, if the
886
+ * desired channel format and count is already known up-front, but this is strongly discouraged
887
+ * and should only ever be done if there is no time to resolve the stream up-front (e.g., due
888
+ * to limitations in the client program).
889
+ * @param max_buflen Optionally the maximum amount of data to buffer (in seconds if there is a
890
+ * nominal sampling rate, otherwise x100 in samples). Recording applications want to use a
891
+ * fairly large buffer size here, while real-time applications would only buffer as much as
892
+ * they need to perform their next calculation.
893
+ * @param max_chunklen Optionally the maximum size, in samples, at which chunks are transmitted
894
+ * (the default corresponds to the chunk sizes used by the sender).
895
+ * Recording applications can use a generous size here (leaving it to the network how to pack
896
+ * things), while real-time applications may want a finer (perhaps 1-sample) granularity.
897
+ * If left unspecified (=0), the sender determines the chunk granularity.
898
+ * @param recover Try to silently recover lost streams that are recoverable (=those that that
899
+ * have a source_id set).
900
+ * In all other cases (recover is false or the stream is not recoverable) functions may throw a
901
+ * lsl::lost_error if the stream's source is lost (e.g., due to an app or computer crash).
902
+ */
903
+ stream_inlet(const stream_info &info, int32_t max_buflen = 360, int32_t max_chunklen = 0,
904
+ bool recover = true, lsl_transport_options_t flags = transp_default)
905
+ : channel_count(info.channel_count()),
906
+ obj(lsl_create_inlet_ex(info.handle().get(), max_buflen, max_chunklen, recover, flags),
907
+ &lsl_destroy_inlet) {}
908
+
909
+ /// Return a shared pointer to pass to C-API functions that aren't wrapped yet
910
+ ///
911
+ /// Example: @code lsl_pull_sample_buf(inlet.handle().get(), buf, …); @endcode
912
+ std::shared_ptr<lsl_inlet_struct_> handle() { return obj; }
913
+
914
+ /// Move constructor for stream_inlet
915
+ stream_inlet(stream_inlet &&rhs) noexcept = default;
916
+ stream_inlet &operator=(stream_inlet &&rhs) noexcept= default;
917
+
918
+
919
+ /** Retrieve the complete information of the given stream, including the extended description.
920
+ * Can be invoked at any time of the stream's lifetime.
921
+ * @param timeout Timeout of the operation (default: no timeout).
922
+ * @throws timeout_error (if the timeout expires), or lost_error (if the stream source has been
923
+ * lost).
924
+ */
925
+ stream_info info(double timeout = FOREVER) {
926
+ int32_t ec = 0;
927
+ lsl_streaminfo res = lsl_get_fullinfo(obj.get(), timeout, &ec);
928
+ check_error(ec);
929
+ return stream_info(res);
930
+ }
931
+
932
+ /** Subscribe to the data stream.
933
+ * All samples pushed in at the other end from this moment onwards will be queued and
934
+ * eventually be delivered in response to pull_sample() or pull_chunk() calls.
935
+ * Pulling a sample without some preceding open_stream() is permitted (the stream will then be
936
+ * opened implicitly).
937
+ * @param timeout Optional timeout of the operation (default: no timeout).
938
+ * @throws timeout_error (if the timeout expires), or lost_error (if the stream source has been
939
+ * lost).
940
+ */
941
+ void open_stream(double timeout = FOREVER) {
942
+ int32_t ec = 0;
943
+ lsl_open_stream(obj.get(), timeout, &ec);
944
+ check_error(ec);
945
+ }
946
+
947
+ /** Drop the current data stream.
948
+ *
949
+ * All samples that are still buffered or in flight will be dropped and transmission
950
+ * and buffering of data for this inlet will be stopped. If an application stops being
951
+ * interested in data from a source (temporarily or not) but keeps the outlet alive,
952
+ * it should call close_stream() to not waste unnecessary system and network
953
+ * resources.
954
+ */
955
+ void close_stream() { lsl_close_stream(obj.get()); }
956
+
957
+ /** Retrieve an estimated time correction offset for the given stream.
958
+ *
959
+ * The first call to this function takes several milliseconds until a reliable first estimate
960
+ * is obtained. Subsequent calls are instantaneous (and rely on periodic background updates).
961
+ * On a well-behaved network, the precision of these estimates should be below 1 ms
962
+ * (empirically it is within +/-0.2 ms).
963
+ *
964
+ * To get a measure of whether the network is well-behaved, use the extended version
965
+ * time_correction(double*,double*,double) and check uncertainty (i.e. the round-trip-time).
966
+ *
967
+ * 0.2 ms is typical of wired networks. 2 ms is typical of wireless networks.
968
+ * The number can be much higher on poor networks.
969
+ *
970
+ * @param timeout Timeout to acquire the first time-correction estimate (default: no timeout).
971
+ * @return The time correction estimate. This is the number that needs to be added to a time
972
+ * stamp that was remotely generated via lsl_local_clock() to map it into the local clock
973
+ * domain of this machine.
974
+ * @throws #lsl::timeout_error (if the timeout expires), or #lsl::lost_error (if the stream
975
+ * source has been lost).
976
+ */
977
+
978
+ double time_correction(double timeout = FOREVER) {
979
+ int32_t ec = 0;
980
+ double res = lsl_time_correction(obj.get(), timeout, &ec);
981
+ check_error(ec);
982
+ return res;
983
+ }
984
+ /** @copydoc time_correction(double)
985
+ * @param remote_time The current time of the remote computer that was used to generate this
986
+ * time_correction. If desired, the client can fit time_correction vs remote_time to improve
987
+ * the real-time time_correction further.
988
+ * @param uncertainty The maximum uncertainty of the given time correction.
989
+ */
990
+ double time_correction(double *remote_time, double *uncertainty, double timeout = FOREVER) {
991
+ int32_t ec = 0;
992
+ double res = lsl_time_correction_ex(obj.get(), remote_time, uncertainty, timeout, &ec);
993
+ check_error(ec);
994
+ return res;
995
+ }
996
+
997
+ /** Set post-processing flags to use.
998
+ *
999
+ * By default, the inlet performs NO post-processing and returns the ground-truth time
1000
+ * stamps, which can then be manually synchronized using .time_correction(), and then
1001
+ * smoothed/dejittered if desired.<br>
1002
+ * This function allows automating these two and possibly more operations.<br>
1003
+ * @warning When you enable this, you will no longer receive or be able to recover the original
1004
+ * time stamps.
1005
+ * @param flags An integer that is the result of bitwise OR'ing one or more options from
1006
+ * processing_options_t together (e.g., `post_clocksync|post_dejitter`); the default is to
1007
+ * enable all options.
1008
+ */
1009
+ void set_postprocessing(uint32_t flags = post_ALL) {
1010
+ check_error(lsl_set_postprocessing(obj.get(), flags));
1011
+ }
1012
+
1013
+ // =======================================
1014
+ // === Pulling a sample from the inlet ===
1015
+ // =======================================
1016
+
1017
+ /** Pull a sample from the inlet and read it into an array of values.
1018
+ * Handles type checking & conversion.
1019
+ * @param sample An array to hold the resulting values.
1020
+ * @param timeout The timeout for this operation, if any. Use 0.0 to make the function
1021
+ * non-blocking.
1022
+ * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was
1023
+ * available. To remap this time stamp to the local clock, add the value returned by
1024
+ * .time_correction() to it.
1025
+ * @throws lost_error (if the stream source has been lost).
1026
+ */
1027
+ template <class T, int N> double pull_sample(T sample[N], double timeout = FOREVER) {
1028
+ return pull_sample(&sample[0], N, timeout);
1029
+ }
1030
+
1031
+ /** Pull a sample from the inlet and read it into a std vector of values.
1032
+ * Handles type checking & conversion and allocates the necessary memory in the vector if
1033
+ * necessary.
1034
+ * @param sample An STL vector to hold the resulting values.
1035
+ * @param timeout The timeout for this operation, if any. Use 0.0 to make the function
1036
+ * non-blocking.
1037
+ * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was
1038
+ * available. To remap this time stamp to the local clock, add the value returned by
1039
+ * .time_correction() to it.
1040
+ * @throws lost_error (if the stream source has been lost).
1041
+ */
1042
+ double pull_sample(std::vector<float> &sample, double timeout = FOREVER) {
1043
+ sample.resize(channel_count);
1044
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1045
+ }
1046
+ double pull_sample(std::vector<double> &sample, double timeout = FOREVER) {
1047
+ sample.resize(channel_count);
1048
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1049
+ }
1050
+ double pull_sample(std::vector<int64_t> &sample, double timeout = FOREVER) {
1051
+ sample.resize(channel_count);
1052
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1053
+ }
1054
+ double pull_sample(std::vector<int32_t> &sample, double timeout = FOREVER) {
1055
+ sample.resize(channel_count);
1056
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1057
+ }
1058
+ double pull_sample(std::vector<int16_t> &sample, double timeout = FOREVER) {
1059
+ sample.resize(channel_count);
1060
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1061
+ }
1062
+ double pull_sample(std::vector<char> &sample, double timeout = FOREVER) {
1063
+ sample.resize(channel_count);
1064
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1065
+ }
1066
+ double pull_sample(std::vector<std::string> &sample, double timeout = FOREVER) {
1067
+ sample.resize(channel_count);
1068
+ return pull_sample(&sample[0], (int32_t)sample.size(), timeout);
1069
+ }
1070
+
1071
+ /** Pull a sample from the inlet and read it into a pointer to values.
1072
+ * Handles type checking & conversion.
1073
+ * @param buffer A pointer to hold the resulting values.
1074
+ * @param buffer_elements The number of samples allocated in the buffer. Note: it is the
1075
+ * responsibility of the user to allocate enough memory.
1076
+ * @param timeout The timeout for this operation, if any. Use 0.0 to make the function
1077
+ * non-blocking.
1078
+ * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was
1079
+ * available. To remap this time stamp to the local clock, add the value returned by
1080
+ * .time_correction() to it.
1081
+ * @throws lost_error (if the stream source has been lost).
1082
+ */
1083
+ double pull_sample(float *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1084
+ int32_t ec = 0;
1085
+ double res = lsl_pull_sample_f(obj.get(), buffer, buffer_elements, timeout, &ec);
1086
+ check_error(ec);
1087
+ return res;
1088
+ }
1089
+ double pull_sample(double *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1090
+ int32_t ec = 0;
1091
+ double res = lsl_pull_sample_d(obj.get(), buffer, buffer_elements, timeout, &ec);
1092
+ check_error(ec);
1093
+ return res;
1094
+ }
1095
+ double pull_sample(int64_t *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1096
+ int32_t ec = 0;
1097
+ double res = lsl_pull_sample_l(obj.get(), buffer, buffer_elements, timeout, &ec);
1098
+ check_error(ec);
1099
+ return res;
1100
+ }
1101
+ double pull_sample(int32_t *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1102
+ int32_t ec = 0;
1103
+ double res = lsl_pull_sample_i(obj.get(), buffer, buffer_elements, timeout, &ec);
1104
+ check_error(ec);
1105
+ return res;
1106
+ }
1107
+ double pull_sample(int16_t *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1108
+ int32_t ec = 0;
1109
+ double res = lsl_pull_sample_s(obj.get(), buffer, buffer_elements, timeout, &ec);
1110
+ check_error(ec);
1111
+ return res;
1112
+ }
1113
+ double pull_sample(char *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1114
+ int32_t ec = 0;
1115
+ double res = lsl_pull_sample_c(obj.get(), buffer, buffer_elements, timeout, &ec);
1116
+ check_error(ec);
1117
+ return res;
1118
+ }
1119
+ double pull_sample(std::string *buffer, int32_t buffer_elements, double timeout = FOREVER) {
1120
+ int32_t ec = 0;
1121
+ if (buffer_elements) {
1122
+ std::vector<char *> result_strings(buffer_elements);
1123
+ std::vector<uint32_t> result_lengths(buffer_elements);
1124
+ double res = lsl_pull_sample_buf(
1125
+ obj.get(), result_strings.data(), result_lengths.data(), buffer_elements, timeout, &ec);
1126
+ check_error(ec);
1127
+ for (int32_t k = 0; k < buffer_elements; k++) {
1128
+ buffer[k].assign(result_strings[k], result_lengths[k]);
1129
+ lsl_destroy_string(result_strings[k]);
1130
+ }
1131
+ return res;
1132
+ } else
1133
+ throw std::runtime_error(
1134
+ "Provided element count does not match the stream's channel count.");
1135
+ }
1136
+
1137
+ /**
1138
+ * Pull a sample from the inlet and read it into a custom C-style struct.
1139
+ *
1140
+ * Overall size checking but no type checking or conversion are done.
1141
+ * Do not use for variable-size/string-formatted streams.
1142
+ * @param sample The raw sample object to hold the data (packed C-style struct).
1143
+ * Search for [`#``pragma pack`](https://stackoverflow.com/a/3318475/73299) for information
1144
+ * on how to pack structs correctly.
1145
+ * @param timeout The timeout for this operation, if any. Use 0.0 to make the function
1146
+ * non-blocking.
1147
+ * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was
1148
+ * available. To remap this time stamp to the local clock, add the value returned by
1149
+ * .time_correction() to it.
1150
+ * @throws lost_error (if the stream source has been lost).
1151
+ */
1152
+ template <class T> double pull_numeric_struct(T &sample, double timeout = FOREVER) {
1153
+ return pull_numeric_raw((void *)&sample, sizeof(T), timeout);
1154
+ }
1155
+
1156
+ /**
1157
+ * Pull a sample from the inlet and read it into a pointer to raw data.
1158
+ *
1159
+ * No type checking or conversions are done (not recommended!).<br>
1160
+ * Do not use for variable-size/string-formatted streams.
1161
+ * @param sample A pointer to hold the resulting raw sample data.
1162
+ * @param buffer_bytes The number of bytes allocated in the buffer.<br>
1163
+ * Note: it is the responsibility of the user to allocate enough memory.
1164
+ * @param timeout The timeout for this operation, if any. Use 0.0 to make the function
1165
+ * non-blocking.
1166
+ * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was
1167
+ * available. To remap this time stamp to the local clock, add the value returned by
1168
+ * .time_correction() to it.
1169
+ * @throws lost_error (if the stream source has been lost).
1170
+ */
1171
+ double pull_numeric_raw(void *sample, int32_t buffer_bytes, double timeout = FOREVER) {
1172
+ int32_t ec = 0;
1173
+ double res = lsl_pull_sample_v(obj.get(), sample, buffer_bytes, timeout, &ec);
1174
+ check_error(ec);
1175
+ return res;
1176
+ }
1177
+
1178
+
1179
+ // =================================================
1180
+ // === Pulling a chunk of samples from the inlet ===
1181
+ // =================================================
1182
+
1183
+ /**
1184
+ * Pull a chunk of samples from the inlet.
1185
+ *
1186
+ * This is the most complete version, returning both the data and a timestamp for each sample.
1187
+ * @param chunk A vector of vectors to hold the samples.
1188
+ * @param timestamps A vector to hold the time stamps.
1189
+ * @return True if some data was obtained.
1190
+ * @throws lost_error (if the stream source has been lost).
1191
+ */
1192
+ template <class T>
1193
+ bool pull_chunk(std::vector<std::vector<T>> &chunk, std::vector<double> &timestamps) {
1194
+ std::vector<T> sample;
1195
+ chunk.clear();
1196
+ timestamps.clear();
1197
+ while (double ts = pull_sample(sample, 0.0)) {
1198
+ chunk.push_back(sample);
1199
+ timestamps.push_back(ts);
1200
+ }
1201
+ return !chunk.empty();
1202
+ }
1203
+
1204
+ /**
1205
+ * Pull a chunk of samples from the inlet.
1206
+ *
1207
+ * This version returns only the most recent sample's time stamp.
1208
+ * @param chunk A vector of vectors to hold the samples.
1209
+ * @return The time when the most recent sample was captured
1210
+ * on the remote machine, or 0.0 if no new sample was available.
1211
+ * @throws lost_error (if the stream source has been lost)
1212
+ */
1213
+ template <class T> double pull_chunk(std::vector<std::vector<T>> &chunk) {
1214
+ double timestamp = 0.0;
1215
+ std::vector<T> sample;
1216
+ chunk.clear();
1217
+ while (double ts = pull_sample(sample, 0.0)) {
1218
+ chunk.push_back(sample);
1219
+ timestamp = ts;
1220
+ }
1221
+ return timestamp;
1222
+ }
1223
+
1224
+ /**
1225
+ * Pull a chunk of samples from the inlet.
1226
+ *
1227
+ * This function does not return time stamps for the samples. Invoked as: mychunk =
1228
+ * pull_chunk<float>();
1229
+ * @return A vector of vectors containing the obtained samples; may be empty.
1230
+ * @throws lost_error (if the stream source has been lost)
1231
+ */
1232
+ template <class T> std::vector<std::vector<T>> pull_chunk() {
1233
+ std::vector<std::vector<T>> result;
1234
+ std::vector<T> sample;
1235
+ while (pull_sample(sample, 0.0)) result.push_back(sample);
1236
+ return result;
1237
+ }
1238
+
1239
+ /**
1240
+ * Pull a chunk of data from the inlet into a pre-allocated buffer.
1241
+ *
1242
+ * This is a high-performance function that performs no memory allocations
1243
+ * (useful for very high data rates or on low-powered devices).
1244
+ * @warning The provided buffer size is measured in channel values (e.g., floats), not samples.
1245
+ * @param data_buffer A pointer to a buffer of data values where the results shall be stored.
1246
+ * @param timestamp_buffer A pointer to a buffer of timestamp values where time stamps shall be
1247
+ * stored. If this is NULL, no time stamps will be returned.
1248
+ * @param data_buffer_elements The size of the data buffer, in channel data elements (of type
1249
+ * T). Must be a multiple of the stream's channel count.
1250
+ * @param timestamp_buffer_elements The size of the timestamp buffer. If a timestamp buffer is
1251
+ * provided then this must correspond to the same number of samples as data_buffer_elements.
1252
+ * @param timeout The timeout for this operation, if any. When the timeout expires, the function
1253
+ * may return before the entire buffer is filled. The default value of 0.0 will retrieve only
1254
+ * data available for immediate pickup.
1255
+ * @return data_elements_written Number of channel data elements written to the data buffer.
1256
+ * @throws lost_error (if the stream source has been lost).
1257
+ */
1258
+ std::size_t pull_chunk_multiplexed(float *data_buffer, double *timestamp_buffer,
1259
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1260
+ double timeout = 0.0) {
1261
+ int32_t ec = 0;
1262
+ std::size_t res = lsl_pull_chunk_f(obj.get(), data_buffer, timestamp_buffer,
1263
+ (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout,
1264
+ &ec);
1265
+ check_error(ec);
1266
+ return res;
1267
+ }
1268
+ std::size_t pull_chunk_multiplexed(double *data_buffer, double *timestamp_buffer,
1269
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1270
+ double timeout = 0.0) {
1271
+ int32_t ec = 0;
1272
+ std::size_t res = lsl_pull_chunk_d(obj.get(), data_buffer, timestamp_buffer,
1273
+ (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout,
1274
+ &ec);
1275
+ check_error(ec);
1276
+ return res;
1277
+ }
1278
+ std::size_t pull_chunk_multiplexed(int64_t *data_buffer, double *timestamp_buffer,
1279
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1280
+ double timeout = 0.0) {
1281
+ int32_t ec = 0;
1282
+ std::size_t res = lsl_pull_chunk_l(obj.get(), data_buffer, timestamp_buffer,
1283
+ (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout,
1284
+ &ec);
1285
+ check_error(ec);
1286
+ return res;
1287
+ }
1288
+ std::size_t pull_chunk_multiplexed(int32_t *data_buffer, double *timestamp_buffer,
1289
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1290
+ double timeout = 0.0) {
1291
+ int32_t ec = 0;
1292
+ std::size_t res = lsl_pull_chunk_i(obj.get(), data_buffer, timestamp_buffer,
1293
+ (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout,
1294
+ &ec);
1295
+ check_error(ec);
1296
+ return res;
1297
+ }
1298
+ std::size_t pull_chunk_multiplexed(int16_t *data_buffer, double *timestamp_buffer,
1299
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1300
+ double timeout = 0.0) {
1301
+ int32_t ec = 0;
1302
+ std::size_t res = lsl_pull_chunk_s(obj.get(), data_buffer, timestamp_buffer,
1303
+ (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout,
1304
+ &ec);
1305
+ check_error(ec);
1306
+ return res;
1307
+ }
1308
+ std::size_t pull_chunk_multiplexed(char *data_buffer, double *timestamp_buffer,
1309
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1310
+ double timeout = 0.0) {
1311
+ int32_t ec = 0;
1312
+ std::size_t res = lsl_pull_chunk_c(obj.get(), data_buffer, timestamp_buffer,
1313
+ static_cast<unsigned long>(data_buffer_elements), static_cast<unsigned long>(timestamp_buffer_elements), timeout,
1314
+ &ec);
1315
+ check_error(ec);
1316
+ return res;
1317
+ }
1318
+ std::size_t pull_chunk_multiplexed(std::string *data_buffer, double *timestamp_buffer,
1319
+ std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements,
1320
+ double timeout = 0.0) {
1321
+ int32_t ec = 0;
1322
+ if (data_buffer_elements) {
1323
+ std::vector<char *> result_strings(data_buffer_elements);
1324
+ std::vector<uint32_t> result_lengths(data_buffer_elements);
1325
+ std::size_t num = lsl_pull_chunk_buf(obj.get(), result_strings.data(), result_lengths.data(),
1326
+ timestamp_buffer, static_cast<unsigned long>(data_buffer_elements),
1327
+ static_cast<unsigned long>(timestamp_buffer_elements), timeout, &ec);
1328
+ check_error(ec);
1329
+ for (std::size_t k = 0; k < num; k++) {
1330
+ data_buffer[k].assign(result_strings[k], result_lengths[k]);
1331
+ lsl_destroy_string(result_strings[k]);
1332
+ }
1333
+ return num;
1334
+ };
1335
+ return 0;
1336
+ }
1337
+
1338
+ /**
1339
+ * Pull a multiplexed chunk of samples and optionally the sample timestamps from the inlet.
1340
+ *
1341
+ * @param chunk A vector to hold the multiplexed (Sample 1 Channel 1,
1342
+ * S1C2, S2C1, S2C2, S3C1, S3C2, ...) samples
1343
+ * @param timestamps A vector to hold the timestamps or nullptr
1344
+ * @param timeout Time to wait for the first sample. The default value of 0.0 will not wait
1345
+ * for data to arrive, pulling only samples already received.
1346
+ * @param append (True:) Append data or (false:) clear them first
1347
+ * @return True if some data was obtained.
1348
+ * @throws lost_error (if the stream source has been lost).
1349
+ */
1350
+ template <typename T>
1351
+ bool pull_chunk_multiplexed(std::vector<T> &chunk, std::vector<double> *timestamps = nullptr,
1352
+ double timeout = 0.0, bool append = false) {
1353
+ if (!append) {
1354
+ chunk.clear();
1355
+ if (timestamps) timestamps->clear();
1356
+ }
1357
+ std::vector<T> sample;
1358
+ double ts;
1359
+ if ((ts = pull_sample(sample, timeout)) == 0.0) return false;
1360
+ chunk.insert(chunk.end(), sample.begin(), sample.end());
1361
+ if (timestamps) timestamps->push_back(ts);
1362
+ const auto target = samples_available();
1363
+ chunk.reserve(chunk.size() + target * this->channel_count);
1364
+ if (timestamps) timestamps->reserve(timestamps->size() + target);
1365
+ while ((ts = pull_sample(sample, 0.0)) != 0.0) {
1366
+ #if LSL_CPP11
1367
+ chunk.insert(chunk.end(), std::make_move_iterator(sample.begin()),
1368
+ std::make_move_iterator(sample.end()));
1369
+ #else
1370
+ chunk.insert(chunk.end(), sample.begin(), sample.end());
1371
+ #endif
1372
+ if (timestamps) timestamps->push_back(ts);
1373
+ }
1374
+ return true;
1375
+ }
1376
+
1377
+ /**
1378
+ * Pull a chunk of samples from the inlet.
1379
+ *
1380
+ * This is the most complete version, returning both the data and a timestamp for each sample.
1381
+ * @param chunk A vector of C-style structs to hold the samples.
1382
+ * @param timestamps A vector to hold the time stamps.
1383
+ * @return True if some data was obtained.
1384
+ * @throws lost_error (if the stream source has been lost)
1385
+ */
1386
+ template <class T>
1387
+ bool pull_chunk_numeric_structs(std::vector<T> &chunk, std::vector<double> &timestamps) {
1388
+ T sample;
1389
+ chunk.clear();
1390
+ timestamps.clear();
1391
+ while (double ts = pull_numeric_struct(sample, 0.0)) {
1392
+ chunk.push_back(sample);
1393
+ timestamps.push_back(ts);
1394
+ }
1395
+ return !chunk.empty();
1396
+ }
1397
+
1398
+ /**
1399
+ * Pull a chunk of samples from the inlet.
1400
+ *
1401
+ * This version returns only the most recent sample's time stamp.
1402
+ * @param chunk A vector of C-style structs to hold the samples.
1403
+ * @return The time when the most recent sample was captured
1404
+ * on the remote machine, or 0.0 if no new sample was available.
1405
+ * @throws lost_error (if the stream source has been lost)
1406
+ */
1407
+ template <class T> double pull_chunk_numeric_structs(std::vector<T> &chunk) {
1408
+ double timestamp = 0.0;
1409
+ T sample;
1410
+ chunk.clear();
1411
+ while (double ts = pull_numeric_struct(sample, 0.0)) {
1412
+ chunk.push_back(sample);
1413
+ timestamp = ts;
1414
+ }
1415
+ return timestamp;
1416
+ }
1417
+
1418
+ /**
1419
+ * Pull a chunk of samples from the inlet.
1420
+ *
1421
+ * This function does not return time stamps. Invoked as: mychunk = pull_chunk<mystruct>();
1422
+ * @return A vector of C-style structs containing the obtained samples; may be empty.
1423
+ * @throws lost_error (if the stream source has been lost)
1424
+ */
1425
+ template <class T> std::vector<T> pull_chunk_numeric_structs() {
1426
+ std::vector<T> result;
1427
+ T sample;
1428
+ while (pull_numeric_struct(sample, 0.0)) result.push_back(sample);
1429
+ return result;
1430
+ }
1431
+
1432
+ /**
1433
+ * Query whether samples are currently available for immediate pickup.
1434
+ *
1435
+ * Note that it is not a good idea to use samples_available() to determine whether
1436
+ * a pull_*() call would block: to be sure, set the pull timeout to 0.0 or an acceptably
1437
+ * low value. If the underlying implementation supports it, the value will be the number of
1438
+ * samples available (otherwise it will be 1 or 0).
1439
+ */
1440
+ std::size_t samples_available() { return lsl_samples_available(obj.get()); }
1441
+
1442
+ /// Drop all queued not-yet pulled samples, return the nr of dropped samples
1443
+ uint32_t flush() noexcept { return lsl_inlet_flush(obj.get()); }
1444
+
1445
+ /**
1446
+ * Query whether the clock was potentially reset since the last call to was_clock_reset().
1447
+ *
1448
+ * This is a rarely-used function that is only useful to applications that combine multiple
1449
+ * time_correction values to estimate precise clock drift; it allows to tolerate cases where the
1450
+ * source machine was hot-swapped or restarted in between two measurements.
1451
+ */
1452
+ bool was_clock_reset() { return lsl_was_clock_reset(obj.get()) != 0; }
1453
+
1454
+ /**
1455
+ * Override the half-time (forget factor) of the time-stamp smoothing.
1456
+ *
1457
+ * The default is 90 seconds unless a different value is set in the config file.
1458
+ * Using a longer window will yield lower jitter in the time stamps, but longer
1459
+ * windows will have trouble tracking changes in the clock rate (usually due to
1460
+ * temperature changes); the default is able to track changes up to 10
1461
+ * degrees C per minute sufficiently well.
1462
+ */
1463
+ void smoothing_halftime(float value) { check_error(lsl_smoothing_halftime(obj.get(), value)); }
1464
+
1465
+ int get_channel_count() const { return channel_count; }
1466
+
1467
+ private:
1468
+ // The inlet is a non-copyable object.
1469
+ stream_inlet(const stream_inlet &rhs);
1470
+ stream_inlet &operator=(const stream_inlet &rhs);
1471
+
1472
+ int32_t channel_count;
1473
+ std::shared_ptr<lsl_inlet_struct_> obj;
1474
+ };
1475
+
1476
+
1477
+ // =====================
1478
+ // ==== XML Element ====
1479
+ // =====================
1480
+
1481
+ /**
1482
+ * A lightweight XML element tree; models the .desc() field of stream_info.
1483
+ *
1484
+ * Has a name and can have multiple named children or have text content as value; attributes are
1485
+ * omitted. Insider note: The interface is modeled after a subset of pugixml's node type and is
1486
+ * compatible with it. See also
1487
+ * https://pugixml.org/docs/manual.html#access for additional documentation.
1488
+ */
1489
+ class xml_element {
1490
+ public:
1491
+ /// Constructor.
1492
+ xml_element(lsl_xml_ptr obj = 0) : obj(obj) {}
1493
+
1494
+
1495
+ // === Tree Navigation ===
1496
+
1497
+ /// Get the first child of the element.
1498
+ xml_element first_child() const { return lsl_first_child(obj); }
1499
+
1500
+ /// Get the last child of the element.
1501
+ xml_element last_child() const { return lsl_last_child(obj); }
1502
+
1503
+ /// Get the next sibling in the children list of the parent node.
1504
+ xml_element next_sibling() const { return lsl_next_sibling(obj); }
1505
+
1506
+ /// Get the previous sibling in the children list of the parent node.
1507
+ xml_element previous_sibling() const { return lsl_previous_sibling(obj); }
1508
+
1509
+ /// Get the parent node.
1510
+ xml_element parent() const { return lsl_parent(obj); }
1511
+
1512
+
1513
+ // === Tree Navigation by Name ===
1514
+
1515
+ /// Get a child with a specified name.
1516
+ xml_element child(const std::string &name) const { return lsl_child(obj, (name.c_str())); }
1517
+
1518
+ /// Get the next sibling with the specified name.
1519
+ xml_element next_sibling(const std::string &name) const {
1520
+ return lsl_next_sibling_n(obj, (name.c_str()));
1521
+ }
1522
+
1523
+ /// Get the previous sibling with the specified name.
1524
+ xml_element previous_sibling(const std::string &name) const {
1525
+ return lsl_previous_sibling_n(obj, (name.c_str()));
1526
+ }
1527
+
1528
+
1529
+ // === Content Queries ===
1530
+
1531
+ /// Whether this node is empty.
1532
+ bool empty() const { return lsl_empty(obj) != 0; }
1533
+
1534
+ /// Is this a text body (instead of an XML element)? True both for plain char data and CData.
1535
+ bool is_text() const { return lsl_is_text(obj) != 0; }
1536
+
1537
+ /// Name of the element.
1538
+ const char *name() const { return lsl_name(obj); }
1539
+
1540
+ /// Value of the element.
1541
+ const char *value() const { return lsl_value(obj); }
1542
+
1543
+ /// Get child value (value of the first child that is text).
1544
+ const char *child_value() const { return lsl_child_value(obj); }
1545
+
1546
+ /// Get child value of a child with a specified name.
1547
+ const char *child_value(const std::string &name) const {
1548
+ return lsl_child_value_n(obj, (name.c_str()));
1549
+ }
1550
+
1551
+
1552
+ // === Modification ===
1553
+
1554
+ /// Append a child node with a given name, which has a (nameless) plain-text child with the
1555
+ /// given text value.
1556
+ xml_element append_child_value(const std::string &name, const std::string &value) {
1557
+ return lsl_append_child_value(obj, (name.c_str()), (value.c_str()));
1558
+ }
1559
+
1560
+ /// Prepend a child node with a given name, which has a (nameless) plain-text child with the
1561
+ /// given text value.
1562
+ xml_element prepend_child_value(const std::string &name, const std::string &value) {
1563
+ return lsl_prepend_child_value(obj, (name.c_str()), (value.c_str()));
1564
+ }
1565
+
1566
+ /// Set the text value of the (nameless) plain-text child of a named child node.
1567
+ bool set_child_value(const std::string &name, const std::string &value) {
1568
+ return lsl_set_child_value(obj, (name.c_str()), (value.c_str())) != 0;
1569
+ }
1570
+
1571
+ /**
1572
+ * Set the element's name.
1573
+ * @return False if the node is empty (or if out of memory).
1574
+ */
1575
+ bool set_name(const std::string &rhs) { return lsl_set_name(obj, rhs.c_str()) != 0; }
1576
+
1577
+ /**
1578
+ * Set the element's value.
1579
+ * @return False if the node is empty (or if out of memory).
1580
+ */
1581
+ bool set_value(const std::string &rhs) { return lsl_set_value(obj, rhs.c_str()) != 0; }
1582
+
1583
+ /// Append a child element with the specified name.
1584
+ xml_element append_child(const std::string &name) {
1585
+ return lsl_append_child(obj, name.c_str());
1586
+ }
1587
+
1588
+ /// Prepend a child element with the specified name.
1589
+ xml_element prepend_child(const std::string &name) {
1590
+ return lsl_prepend_child(obj, (name.c_str()));
1591
+ }
1592
+
1593
+ /// Append a copy of the specified element as a child.
1594
+ xml_element append_copy(const xml_element &e) { return lsl_append_copy(obj, e.obj); }
1595
+
1596
+ /// Prepend a child element with the specified name.
1597
+ xml_element prepend_copy(const xml_element &e) { return lsl_prepend_copy(obj, e.obj); }
1598
+
1599
+ /// Remove a child element with the specified name.
1600
+ void remove_child(const std::string &name) { lsl_remove_child_n(obj, (name.c_str())); }
1601
+
1602
+ /// Remove a specified child element.
1603
+ void remove_child(const xml_element &e) { lsl_remove_child(obj, e.obj); }
1604
+
1605
+ private:
1606
+ lsl_xml_ptr obj;
1607
+ };
1608
+
1609
+ inline xml_element stream_info::desc() { return lsl_get_desc(obj.get()); }
1610
+
1611
+
1612
+ // =============================
1613
+ // ==== Continuous Resolver ====
1614
+ // =============================
1615
+
1616
+ /**
1617
+ * A convenience class that resolves streams continuously in the background throughout
1618
+ * its lifetime and which can be queried at any time for the set of streams that are currently
1619
+ * visible on the network.
1620
+ */
1621
+ class continuous_resolver {
1622
+ public:
1623
+ /**
1624
+ * Construct a new continuous_resolver that resolves all streams on the network.
1625
+ *
1626
+ * This is analogous to the functionality offered by the free function resolve_streams().
1627
+ * @param forget_after When a stream is no longer visible on the network (e.g., because it was
1628
+ * shut down), this is the time in seconds after which it is no longer reported by the resolver.
1629
+ */
1630
+ continuous_resolver(double forget_after = 5.0)
1631
+ : obj(lsl_create_continuous_resolver(forget_after), &lsl_destroy_continuous_resolver) {}
1632
+
1633
+ /**
1634
+ * Construct a new continuous_resolver that resolves all streams with a specific value for a
1635
+ * given property.
1636
+ *
1637
+ * This is analogous to the functionality provided by the free function resolve_stream(prop,value).
1638
+ * @param prop The stream_info property that should have a specific value (e.g., "name", "type",
1639
+ * "source_id", or "desc/manufaturer").
1640
+ * @param value The string value that the property should have (e.g., "EEG" as the type
1641
+ * property).
1642
+ * @param forget_after When a stream is no longer visible on the network (e.g., because it was
1643
+ * shut down), this is the time in seconds after which it is no longer reported by the resolver.
1644
+ */
1645
+ continuous_resolver(
1646
+ const std::string &prop, const std::string &value, double forget_after = 5.0)
1647
+ : obj(lsl_create_continuous_resolver_byprop((prop.c_str()), (value.c_str()), forget_after),
1648
+ &lsl_destroy_continuous_resolver) {}
1649
+
1650
+ /**
1651
+ * Construct a new continuous_resolver that resolves all streams that match a given XPath 1.0
1652
+ * predicate.
1653
+ *
1654
+ * This is analogous to the functionality provided by the free function resolve_stream(pred).
1655
+ * @param pred The predicate string, e.g.
1656
+ * `name='BioSemi'` or
1657
+ * `type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32`
1658
+ * @param forget_after When a stream is no longer visible on the network (e.g., because it was
1659
+ * shut down), this is the time in seconds after which it is no longer reported by the resolver.
1660
+ */
1661
+ continuous_resolver(const std::string &pred, double forget_after = 5.0)
1662
+ : obj(lsl_create_continuous_resolver_bypred((pred.c_str()), forget_after), &lsl_destroy_continuous_resolver) {}
1663
+
1664
+ /**
1665
+ * Obtain the set of currently present streams on the network (i.e. resolve result).
1666
+ * @return A vector of matching stream info objects (excluding their meta-data), any of
1667
+ * which can subsequently be used to open an inlet.
1668
+ */
1669
+ std::vector<stream_info> results() {
1670
+ lsl_streaminfo buffer[1024];
1671
+ return std::vector<stream_info>(
1672
+ buffer, buffer + check_error(lsl_resolver_results(obj.get(), buffer, sizeof(buffer))));
1673
+ }
1674
+
1675
+ /// Move constructor for stream_inlet
1676
+ continuous_resolver(continuous_resolver &&rhs) noexcept = default;
1677
+ continuous_resolver &operator=(continuous_resolver &&rhs) noexcept = default;
1678
+
1679
+ private:
1680
+ std::unique_ptr<lsl_continuous_resolver_, void(*)(lsl_continuous_resolver_*)> obj;
1681
+ };
1682
+
1683
+
1684
+ // ===============================
1685
+ // ==== Exception Definitions ====
1686
+ // ===============================
1687
+
1688
+ /// Exception class that indicates that a stream inlet's source has been irrecoverably lost.
1689
+ class lost_error : public std::runtime_error {
1690
+ public:
1691
+ explicit lost_error(const std::string &msg) : std::runtime_error(msg) {}
1692
+ };
1693
+
1694
+
1695
+ /// Exception class that indicates that an operation failed due to a timeout.
1696
+ class timeout_error : public std::runtime_error {
1697
+ public:
1698
+ explicit timeout_error(const std::string &msg) : std::runtime_error(msg) {}
1699
+ };
1700
+
1701
+ /// Check error codes returned from the C interface and translate into appropriate exceptions.
1702
+ inline int32_t check_error(int32_t ec) {
1703
+ if (ec < 0) {
1704
+ switch (ec) {
1705
+ case lsl_timeout_error: throw timeout_error("The operation has timed out.");
1706
+ case lsl_lost_error:
1707
+ throw lost_error(
1708
+ "The stream has been lost; to continue reading, you need to re-resolve it.");
1709
+ case lsl_argument_error:
1710
+ throw std::invalid_argument("An argument was incorrectly specified.");
1711
+ case lsl_internal_error: throw std::runtime_error("An internal error has occurred.");
1712
+ default: throw std::runtime_error("An unknown error has occurred.");
1713
+ }
1714
+ }
1715
+ return ec;
1716
+ }
1717
+
1718
+ } // namespace lsl
1719
+
1720
+ #endif // LSL_CPP_H