labstreaminglayer / liblsl-Matlab

Matlab bindings for liblsl

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unmonotonic timestamps returned by pull_chunk()

SeanZhang99 opened this issue · comments

MATLAB version: R2023b
liblsl version: 114 (returned by 'LSLVersion()' )

Situation: when I tried to use liblsl to create inlet to receive EEG data from OpenBCI GUI, I found that the timestamps are not monotonic returned by pull_chunk(). However, it is monotonic if I combine a loop and the pull_sample().

The pull_sample code is as:

function [data,ts,t] = stream_lsl(varargin)
    if nargin == 0
        inlet = init_lsl("TimeSeriesRaw");
    else
        inlet = varargin{1};
    end
    disp("Start recording...")
    bufferSize = 10 * 125;
    % 30 seconds, 125 Hz fs.
    data = zeros(bufferSize,16);
    ts = zeros(bufferSize,1);
    tic;
    t = toc;
    inlet.open_stream;
    while t<10 || any(data==0,"all")
        [datatmp,tstmp] = inlet.pull_sample();
        if any(datatmp~=0)
            data = [data(size(datatmp,1)+1:end,:);datatmp];
            ts = [ts(size(tstmp,1)+1:end);tstmp];
        else
            disp("No LSL data received")
        end
        t = toc;
    end
    inlet.close_stream;
end

while the pull_chunk() code replaces the while loop with

    [data,ts] = inlet.pull_chunk();
    pause(10);
    [data,ts] = inlet.pull_chunk();
    inlet.close_stream;

(The init_lsl function is as:

function inlet = init_lsl(varargin)
    inlet = NaN;
    try
        if nargin == 0
            name = 'TimeSeriesRaw';
        else
            name = char(varargin{1});
        end
        lib = lsl_loadlib();
        result = {};
        while isempty(result)
            result = lsl_resolve_byprop(lib,'name',name);
        end
        inlet = lsl_inlet(result{1});
        [vec,~] = inlet.pull_sample();
        assert(all(~isempty(vec)));
    catch ME
        warning(ME);
    end
end

)

After received the data, I calculate the difference of adjacent timestamps, and plot it:

a = diff(ts);
plot(a)
all(a>0)

And MATLAB gives the following answer:
ans = False
image

Sometimes more negatives between adjacent timestamps can occur.
In this case, should I believe that the EEG data returned by pull_chunk() is well sorted, or shall I manually sort the timestamp first, and then use the correct index to sort the EEG data again?

Raw timestamps from pull_chunk are not monotonic and this is by design. You need to use either online or offline methods for achieving this. See post_processing flags when creating an inlet. https://github.com/labstreaminglayer/liblsl-Matlab/blob/master/lsl_inlet.m#L129-L146

This is not a matlab issue, but applies to any LSL stream.