-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsample_buffer.simba
More file actions
117 lines (100 loc) · 2.47 KB
/
sample_buffer.simba
File metadata and controls
117 lines (100 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
type
TSample = record
Time: UInt64;
Data: Pointer;
end;
TSampleArray = array of TSample;
procedure TSampleArray.Free();
var
i: Integer;
begin
for i := Self.Low to Self.High do
begin
if Self[i].Data = nil then
Continue;
FreeMem(Self[i].Data);
Self[i].Data := nil;
Self[i].Time := 0;
end;
end;
type
TSampleBuffer = record
Data: array of TSample;
Index: Integer;
SampleDataSize: Integer;
end;
procedure TSampleBuffer.Init(capacity, sampleDataSize: Integer);
begin
SetLength(Self.Data, capacity);
Self.SampleDataSize := sampleDataSize;
Self.Index := 0;
end;
procedure TSampleBuffer.Add(p: Pointer);
var
newPtr: Pointer;
begin
if Self.Data[Self.Index].Data <> nil then
FreeMem(Self.Data[Self.Index].Data);
newPtr := AllocMem(Self.SampleDataSize);
Move(p^, newPtr^, Self.SampleDataSize);
Self.Data[Self.Index].Time := Time();
Self.Data[Self.Index].Data := newPtr;
Inc(Self.Index);
if Self.Index > High(Self.Data) then
Self.Index := 0;
end;
procedure TSampleBuffer.FreeExpired(olderThan: UInt64);
var
i: Integer;
now: UInt64;
begin
now := Time();
for i := 0 to High(Self.Data) do
if (Self.Data[i].Data <> nil) and (now - Self.Data[i].Time > olderThan) then
begin
FreeMem(Self.Data[i].Data);
Self.Data[i].Data := nil;
Self.Data[i] := [];
end;
end;
procedure TSampleBuffer.Free();
var
i: Integer;
begin
for i := 0 to High(Self.Data) do
if Self.Data[i].Data <> nil then
begin
FreeMem(Self.Data[i].Data);
Self.Data[i].Time := 0;
Self.Data[i].Data := nil;
end;
SetLength(Self.Data, 0);
Self.Index := 0;
end;
function TSampleBuffer.GetSample(index: Integer): TSample;
begin
Result := Self.Data[index];
end;
function TSampleBuffer.GetSamples(ageMin, ageMax: Integer): TSampleArray;
var
i, count, index, capacity: Integer;
currentTime: UInt64;
begin
capacity := Length(Self.Data);
SetLength(Result, capacity);
currentTime := Time();
for i := 0 to capacity - 1 do
begin
index := (Self.Index - 1 - i + capacity) mod capacity; // walk backward from newest
if Self.Data[index].Data = nil then
Continue;
if InRange(currentTime - Self.Data[index].Time, ageMin, ageMax) then
begin
Result[count].Time := Self.Data[index].Time;
Result[count].Data := GetMem(Self.SampleDataSize);
Move(Self.Data[index].Data^, Result[count].Data^, Self.SampleDataSize);
Inc(count);
end;
end;
SetLength(Result, count);
end;