-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathInputEventTrace.cs
More file actions
1638 lines (1440 loc) · 71 KB
/
InputEventTrace.cs
File metadata and controls
1638 lines (1440 loc) · 71 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.InputSystem.Utilities;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.InputSystem.Layouts;
using Unity.Profiling;
namespace UnityEngine.InputSystem.LowLevel
{
/// <summary>
/// InputEventTrace lets you record input events for later processing. It also has features for writing traces
/// to disk, for loading them from disk, and for playing back previously recorded traces.
/// </summary>
/// <remarks>
/// InputEventTrace lets you record input events into a buffer for either a specific device, or for all events
/// received by the input system. This is useful for testing purposes or for replaying recorded input.
///
/// Note that event traces <em>must</em> be disposed of (by calling <see cref="Dispose"/>) after use or they
/// will leak memory on the unmanaged (C++) memory heap.
///
/// Event traces are serializable such that they can survive domain reloads in the editor.
/// </remarks>
[Serializable]
public sealed unsafe class InputEventTrace : IDisposable, IEnumerable<InputEventPtr>
{
private const int kDefaultBufferSize = 1024 * 1024;
private static readonly ProfilerMarker k_InputEvenTraceMarker = new ProfilerMarker("InputEventTrace");
/// <summary>
/// If <see name="recordFrameMarkers"/> is enabled, an <see cref="InputEvent"/> with this <see cref="FourCC"/>
/// code in its <see cref="InputEvent.type"/> is recorded whenever the input system starts a new update, i.e.
/// whenever <see cref="InputSystem.onBeforeUpdate"/> is triggered. This is useful for replaying events in such
/// a way that they are correctly spaced out over frames.
/// </summary>
public static FourCC FrameMarkerEvent => new FourCC('F', 'R', 'M', 'E');
/// <summary>
/// Set device to record events for. Set to <see cref="InputDevice.InvalidDeviceId"/> by default
/// in which case events from all devices are recorded.
/// </summary>
public int deviceId
{
get => m_DeviceId;
set => m_DeviceId = value;
}
/// <summary>
/// Whether the trace is currently recording input.
/// </summary>
/// <value>True if the trace is currently recording events.</value>
/// <seealso cref="Enable"/>
/// <seealso cref="Disable"/>
public bool enabled => m_Enabled;
/// <summary>
/// If true, input update boundaries will be recorded as events. By default, this is off.
/// </summary>
/// <value>Whether frame boundaries should be recorded in the trace.</value>
/// <remarks>
/// When recording with this off, all events are written one after the other for as long
/// as the recording is active. This means that when a recording runs over multiple frames,
/// it is no longer possible for the trace to tell which events happened in distinct frames.
///
/// By turning this feature on, frame marker events (i.e. <see cref="InputEvent"/> instances
/// with <see cref="InputEvent.type"/> set to <see cref="FrameMarkerEvent"/>) will be written
/// to the trace every time an input update occurs. When playing such a trace back via <see
/// cref="ReplayController.PlayAllFramesOneByOne"/>, events will get spaced out over frames corresponding
/// to how they were spaced out when input was initially recorded.
///
/// Note that having this feature enabled will fill up traces much quicker. Instead of being
/// filled up only when there is input, TODO
/// </remarks>
/// <seealso cref="ReplayController.PlayAllFramesOneByOne"/>
/// <seealso cref="FrameMarkerEvent"/>
public bool recordFrameMarkers
{
get => m_RecordFrameMarkers;
set
{
if (m_RecordFrameMarkers == value)
return;
m_RecordFrameMarkers = value;
if (m_Enabled)
{
if (value)
InputSystem.onBeforeUpdate += OnBeforeUpdate;
else
InputSystem.onBeforeUpdate -= OnBeforeUpdate;
}
}
}
/// <summary>
/// Total number of events currently in the trace.
/// </summary>
/// <value>Number of events recorded in the trace.</value>
public long eventCount => m_EventCount;
/// <summary>
/// The amount of memory consumed by all events combined that are currently
/// stored in the trace.
/// </summary>
/// <value>Total size of event data currently in trace.</value>
public long totalEventSizeInBytes => m_EventSizeInBytes;
/// <summary>
/// Total size of memory buffer (in bytes) currently allocated.
/// </summary>
/// <value>Size of memory currently allocated.</value>
/// <remarks>
/// The buffer is allocated on the unmanaged heap.
/// </remarks>
public long allocatedSizeInBytes => m_EventBuffer != default ? m_EventBufferSize : 0;
/// <summary>
/// Largest size (in bytes) that the memory buffer is allowed to grow to. By default, this is
/// the same as <see cref="allocatedSizeInBytes"/> meaning that the buffer is not allowed to grow but will
/// rather wrap around when full.
/// </summary>
/// <value>Largest size the memory buffer is allowed to grow to.</value>
public long maxSizeInBytes => m_MaxEventBufferSize;
/// <summary>
/// Information about all devices for which events have been recorded in the trace.
/// </summary>
/// <value>Record of devices recorded in the trace.</value>
public ReadOnlyArray<DeviceInfo> deviceInfos => m_DeviceInfos;
/// <summary>
/// Optional delegate to decide whether an input should be stored in a trace. Null by default.
/// </summary>
/// <value>Delegate to accept or reject individual events.</value>
/// <remarks>
/// When this is set, the callback will be invoked on every event that would otherwise be stored
/// directly in the trace. If the callback returns <c>true</c>, the trace will continue to record
/// the event. If the callback returns <c>false</c>, the event will be ignored and not recorded.
///
/// The callback should generally mutate the event. If you do so, note that this will impact
/// event processing in general, not just recording of the event in the trace.
/// </remarks>
public Func<InputEventPtr, InputDevice, bool> onFilterEvent
{
get => m_OnFilterEvent;
set => m_OnFilterEvent = value;
}
/// <summary>
/// Event that is triggered every time an event has been recorded in the trace.
/// </summary>
public event Action<InputEventPtr> onEvent
{
add => m_EventListeners.AddCallback(value);
remove => m_EventListeners.RemoveCallback(value);
}
public InputEventTrace(InputDevice device, long bufferSizeInBytes = kDefaultBufferSize, bool growBuffer = false,
long maxBufferSizeInBytes = -1, long growIncrementSizeInBytes = -1)
: this(bufferSizeInBytes, growBuffer, maxBufferSizeInBytes, growIncrementSizeInBytes)
{
if (device == null)
throw new ArgumentNullException(nameof(device));
m_DeviceId = device.deviceId;
}
/// <summary>
/// Create a disabled event trace that does not perform any allocation yet. An event trace only starts consuming resources
/// the first time it is enabled.
/// </summary>
/// <param name="bufferSizeInBytes">Size of buffer that will be allocated on first event captured by trace. Defaults to 1MB.</param>
/// <param name="growBuffer">If true, the event buffer will be grown automatically when it reaches capacity, up to a maximum
/// size of <paramref name="maxBufferSizeInBytes"/>. This is off by default.</param>
/// <param name="maxBufferSizeInBytes">If <paramref name="growBuffer"/> is true, this is the maximum size that the buffer should
/// be grown to. If the maximum size is reached, old events are being overwritten.</param>
public InputEventTrace(long bufferSizeInBytes = kDefaultBufferSize, bool growBuffer = false, long maxBufferSizeInBytes = -1, long growIncrementSizeInBytes = -1)
{
m_EventBufferSize = (uint)bufferSizeInBytes;
if (growBuffer)
{
if (maxBufferSizeInBytes < 0)
m_MaxEventBufferSize = 256 * kDefaultBufferSize;
else
m_MaxEventBufferSize = maxBufferSizeInBytes;
if (growIncrementSizeInBytes < 0)
m_GrowIncrementSize = kDefaultBufferSize;
else
m_GrowIncrementSize = growIncrementSizeInBytes;
}
else
{
m_MaxEventBufferSize = m_EventBufferSize;
}
}
/// <summary>
/// Write the contents of the event trace to a file.
/// </summary>
/// <param name="filePath">Path of the file to write.</param>
/// <exception cref="ArgumentNullException"><paramref name="filePath"/> is <c>null</c> or empty.</exception>
/// <exception cref="FileNotFoundException"><paramref name="filePath"/> is invalid.</exception>
/// <exception cref="DirectoryNotFoundException">A directory in <paramref name="filePath"/> is invalid.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="filePath"/> cannot be accessed.</exception>
/// <seealso cref="ReadFrom(string)"/>
public void WriteTo(string filePath)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
using (var stream = File.OpenWrite(filePath))
WriteTo(stream);
}
/// <summary>
/// Write the contents of the event trace to the given stream.
/// </summary>
/// <param name="stream">Stream to write the data to. Must support seeking (i.e. <c>Stream.canSeek</c> must be true).</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> does not support seeking.</exception>
/// <exception cref="IOException">An error occurred trying to write to <paramref name="stream"/>.</exception>
public void WriteTo(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanSeek)
throw new ArgumentException("Stream does not support seeking", nameof(stream));
var writer = new BinaryWriter(stream);
var flags = default(FileFlags);
if (InputSystem.settings.updateMode == InputSettings.UpdateMode.ProcessEventsInFixedUpdate)
flags |= FileFlags.FixedUpdate;
// Write header.
writer.Write(kFileFormat);
writer.Write(kFileVersion);
writer.Write((int)flags);
writer.Write((int)Application.platform);
writer.Write((ulong)m_EventCount);
writer.Write((ulong)m_EventSizeInBytes);
// Write events.
foreach (var eventPtr in this)
{
////TODO: find way to directly write a byte* buffer to the stream instead of copying to a temp byte[]
var sizeInBytes = eventPtr.sizeInBytes;
var buffer = new byte[sizeInBytes];
fixed(byte* bufferPtr = buffer)
{
UnsafeUtility.MemCpy(bufferPtr, eventPtr.data, sizeInBytes);
writer.Write(buffer);
}
}
// Write devices.
writer.Flush();
var positionOfDeviceList = stream.Position;
var deviceCount = m_DeviceInfos.LengthSafe();
writer.Write(deviceCount);
for (var i = 0; i < deviceCount; ++i)
{
ref var device = ref m_DeviceInfos[i];
writer.Write(device.deviceId);
writer.Write(device.layout);
writer.Write(device.stateFormat);
writer.Write(device.stateSizeInBytes);
writer.Write(device.m_FullLayoutJson ?? string.Empty);
writer.Write(device.m_UsagesJson ?? string.Empty);
}
// Write offset of device list.
writer.Flush();
var offsetOfDeviceList = stream.Position - positionOfDeviceList;
writer.Write(offsetOfDeviceList);
}
/// <summary>
/// Read the contents of an input event trace stored in the given file.
/// </summary>
/// <param name="filePath">Path to a file.</param>
/// <exception cref="ArgumentNullException"><paramref name="filePath"/> is <c>null</c> or empty.</exception>
/// <exception cref="FileNotFoundException"><paramref name="filePath"/> is invalid.</exception>
/// <exception cref="DirectoryNotFoundException">A directory in <paramref name="filePath"/> is invalid.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="filePath"/> cannot be accessed.</exception>
/// <remarks>
/// This method replaces the contents of the trace with those read from the given file.
/// </remarks>
/// <seealso cref="WriteTo(string)"/>
public void ReadFrom(string filePath)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
using (var stream = File.OpenRead(filePath))
ReadFrom(stream);
}
/// <summary>
/// Read the contents of an input event trace from the given stream.
/// </summary>
/// <param name="stream">A stream of binary data containing a recorded event trace as written out with <see cref="WriteTo(Stream)"/>.
/// Must support reading.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> does not support reading.</exception>
/// <exception cref="IOException">An error occurred trying to read from <paramref name="stream"/>.</exception>
/// <remarks>
/// This method replaces the contents of the event trace with those read from the stream. It does not append
/// to the existing trace.
/// </remarks>
/// <seealso cref="WriteTo(Stream)"/>
public void ReadFrom(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException("Stream does not support reading", nameof(stream));
var reader = new BinaryReader(stream);
// Read header.
if (reader.ReadInt32() != kFileFormat)
throw new IOException($"Stream does not appear to be an InputEventTrace (no '{kFileFormat}' code)");
int fileVersion = reader.ReadInt32();
if (fileVersion > kFileVersion)
throw new IOException($"Stream is an InputEventTrace but a newer version (expected version {kFileVersion} or below)");
reader.ReadInt32(); // Flags; ignored for now.
reader.ReadInt32(); // Platform; for now we're not doing anything with it.
var eventCount = reader.ReadUInt64();
var totalEventSizeInBytes = reader.ReadUInt64();
var oldBuffer = m_EventBuffer;
if (eventCount > 0 && totalEventSizeInBytes > 0)
{
// Allocate buffer, if need be.
byte* buffer;
if (m_EventBuffer != null && m_EventBufferSize >= (long)totalEventSizeInBytes)
{
// Existing buffer is large enough.
buffer = m_EventBuffer;
}
else
{
buffer = (byte*)UnsafeUtility.Malloc((long)totalEventSizeInBytes, InputEvent.kAlignment, Allocator.Persistent);
m_EventBufferSize = (long)totalEventSizeInBytes;
}
try
{
// Read events.
var tailPtr = buffer;
var endPtr = tailPtr + totalEventSizeInBytes;
var totalEventSize = 0L;
for (var i = 0ul; i < eventCount; ++i)
{
var eventType = reader.ReadInt32();
var eventSizeInBytes = (uint)reader.ReadUInt16();
var eventDeviceId = (uint)reader.ReadUInt16();
if (eventSizeInBytes > endPtr - tailPtr)
break;
*(int*)tailPtr = eventType;
tailPtr += 4;
*(ushort*)tailPtr = (ushort)eventSizeInBytes;
tailPtr += 2;
*(ushort*)tailPtr = (ushort)eventDeviceId;
tailPtr += 2;
////TODO: find way to directly read from stream into a byte* pointer
var remainingSize = (int)eventSizeInBytes - sizeof(int) - sizeof(short) - sizeof(short);
var tempBuffer = reader.ReadBytes(remainingSize);
fixed(byte* tempBufferPtr = tempBuffer)
UnsafeUtility.MemCpy(tailPtr, tempBufferPtr, remainingSize);
tailPtr += remainingSize.AlignToMultipleOf(InputEvent.kAlignment);
totalEventSize += eventSizeInBytes.AlignToMultipleOf(InputEvent.kAlignment);
if (tailPtr >= endPtr)
break;
}
// Read device infos.
var deviceCount = reader.ReadInt32();
var deviceInfos = new DeviceInfo[deviceCount];
for (var i = 0; i < deviceCount; ++i)
{
deviceInfos[i] = new DeviceInfo
{
deviceId = reader.ReadInt32(),
layout = reader.ReadString(),
stateFormat = reader.ReadInt32(),
stateSizeInBytes = reader.ReadInt32(),
m_FullLayoutJson = reader.ReadString(),
m_UsagesJson = fileVersion >= 2 ? reader.ReadString() : null // Usages were added in version 2
};
}
// Install buffer.
m_EventBuffer = buffer;
m_EventBufferHead = m_EventBuffer;
m_EventBufferTail = endPtr;
m_EventCount = (long)eventCount;
m_EventSizeInBytes = totalEventSize;
m_DeviceInfos = deviceInfos;
}
catch
{
if (buffer != oldBuffer)
UnsafeUtility.Free(buffer, Allocator.Persistent);
throw;
}
}
else
{
m_EventBuffer = default;
m_EventBufferHead = default;
m_EventBufferTail = default;
}
// Release old buffer, if we've switched to a new one.
if (m_EventBuffer != oldBuffer && oldBuffer != null)
UnsafeUtility.Free(oldBuffer, Allocator.Persistent);
++m_ChangeCounter;
}
/// <summary>
/// Load an input event trace from the given file.
/// </summary>
/// <param name="filePath">Path to a file.</param>
/// <exception cref="ArgumentNullException"><paramref name="filePath"/> is <c>null</c> or empty.</exception>
/// <exception cref="FileNotFoundException"><paramref name="filePath"/> is invalid.</exception>
/// <exception cref="DirectoryNotFoundException">A directory in <paramref name="filePath"/> is invalid.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="filePath"/> cannot be accessed.</exception>
/// <seealso cref="WriteTo(string)"/>
/// <seealso cref="ReadFrom(string)"/>
public static InputEventTrace LoadFrom(string filePath)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
using (var stream = File.OpenRead(filePath))
return LoadFrom(stream);
}
/// <summary>
/// Load an event trace from a previously captured event stream.
/// </summary>
/// <param name="stream">A stream as written by <see cref="WriteTo(Stream)"/>. Must support reading.</param>
/// <returns>The loaded event trace.</returns>
/// <exception cref="ArgumentException"><paramref name="stream"/> is not readable.</exception>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is <c>null</c>.</exception>
/// <exception cref="IOException">The stream cannot be loaded (e.g. wrong format; details in the exception).</exception>
/// <seealso cref="WriteTo(Stream)"/>
public static InputEventTrace LoadFrom(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException("Stream must be readable", nameof(stream));
var trace = new InputEventTrace();
trace.ReadFrom(stream);
return trace;
}
/// <summary>
/// Start a replay of the events in the trace.
/// </summary>
/// <returns>An object that controls playback.</returns>
/// <remarks>
/// Calling this method implicitly turns off recording, if currently enabled (i.e. it calls <see cref="Disable"/>),
/// as replaying an event trace cannot be done while it is also concurrently modified.
/// </remarks>
public ReplayController Replay()
{
Disable();
return new ReplayController(this);
}
/// <summary>
/// Resize the current event memory buffer to the specified size.
/// </summary>
/// <param name="newBufferSize">Size to allocate for the buffer.</param>
/// <param name="newMaxBufferSize">Optional parameter to specifying the mark up to which the buffer is allowed to grow. By default,
/// this is negative which indicates the buffer should not grow. In this case, <see cref="maxSizeInBytes"/> will be set
/// to <paramref name="newBufferSize"/>. If this parameter is a non-negative number, it must be greater than or equal to
/// <paramref name="newBufferSize"/> and will become the new value for <see cref="maxSizeInBytes"/>.</param>
/// <returns>True if the new buffer was successfully allocated.</returns>
/// <exception cref="ArgumentException"><paramref name="newBufferSize"/> is negative.</exception>
public bool Resize(long newBufferSize, long newMaxBufferSize = -1)
{
if (newBufferSize <= 0)
throw new ArgumentException("Size must be positive", nameof(newBufferSize));
if (m_EventBufferSize == newBufferSize)
return true;
if (newMaxBufferSize < newBufferSize)
newMaxBufferSize = newBufferSize;
// Allocate.
var newEventBuffer = (byte*)UnsafeUtility.Malloc(newBufferSize, InputEvent.kAlignment, Allocator.Persistent);
if (newEventBuffer == default)
return false;
// If we have existing contents, migrate them.
if (m_EventCount > 0)
{
// If we're shrinking the buffer or have a buffer that has already wrapped around,
// migrate events one by one.
if (newBufferSize < m_EventBufferSize || m_HasWrapped)
{
var fromPtr = new InputEventPtr((InputEvent*)m_EventBufferHead);
var toPtr = (InputEvent*)newEventBuffer;
var newEventCount = 0;
var newEventSizeInBytes = 0;
var remainingEventBytes = m_EventSizeInBytes;
for (var i = 0; i < m_EventCount; ++i)
{
var eventSizeInBytes = fromPtr.sizeInBytes;
var alignedEventSizeInBytes = eventSizeInBytes.AlignToMultipleOf(InputEvent.kAlignment);
// We only start copying once we know that the remaining events we have fit in the new buffer.
// This way we get the newest events and not the oldest ones.
if (remainingEventBytes <= newBufferSize)
{
UnsafeUtility.MemCpy(toPtr, fromPtr.ToPointer(), eventSizeInBytes);
toPtr = InputEvent.GetNextInMemory(toPtr);
newEventSizeInBytes += (int)alignedEventSizeInBytes;
++newEventCount;
}
remainingEventBytes -= alignedEventSizeInBytes;
if (!GetNextEvent(ref fromPtr))
break;
}
m_HasWrapped = false;
m_EventCount = newEventCount;
m_EventSizeInBytes = newEventSizeInBytes;
}
else
{
// Simple case of just having to copy everything between head and tail.
UnsafeUtility.MemCpy(newEventBuffer,
m_EventBufferHead,
m_EventSizeInBytes);
}
}
if (m_EventBuffer != null)
UnsafeUtility.Free(m_EventBuffer, Allocator.Persistent);
m_EventBufferSize = newBufferSize;
m_EventBuffer = newEventBuffer;
m_EventBufferHead = newEventBuffer;
m_EventBufferTail = m_EventBuffer + m_EventSizeInBytes;
m_MaxEventBufferSize = newMaxBufferSize;
++m_ChangeCounter;
return true;
}
/// <summary>
/// Reset the trace. Clears all recorded events.
/// </summary>
public void Clear()
{
m_EventBufferHead = m_EventBufferTail = default;
m_EventCount = 0;
m_EventSizeInBytes = 0;
++m_ChangeCounter;
m_DeviceInfos = null;
}
/// <summary>
/// Start recording events.
/// </summary>
/// <seealso cref="Disable"/>
public void Enable()
{
if (m_Enabled)
return;
if (m_EventBuffer == default)
Allocate();
InputSystem.onEvent += OnInputEvent;
if (m_RecordFrameMarkers)
InputSystem.onBeforeUpdate += OnBeforeUpdate;
m_Enabled = true;
}
/// <summary>
/// Stop recording events.
/// </summary>
/// <seealso cref="Enable"/>
public void Disable()
{
if (!m_Enabled)
return;
InputSystem.onEvent -= OnInputEvent;
InputSystem.onBeforeUpdate -= OnBeforeUpdate;
m_Enabled = false;
}
/// <summary>
/// Based on the given event pointer, return a pointer to the next event in the trace.
/// </summary>
/// <param name="current">A pointer to an event in the trace or a <c>default(InputEventTrace)</c>. In the former case,
/// the pointer will be updated to the next event, if there is one. In the latter case, the pointer will be updated
/// to the first event in the trace, if there is one.</param>
/// <returns>True if <c>current</c> has been set to the next event, false otherwise.</returns>
/// <remarks>
/// Event storage in memory may be circular if the event buffer is fixed in size or has reached maximum
/// size and new events start overwriting old events. This method will automatically start with the first
/// event when the given <paramref name="current"/> event is null. Any subsequent call with then loop over
/// the remaining events until no more events are available.
///
/// Note that it is VERY IMPORTANT that the buffer is not modified while iterating over events this way.
/// If this is not ensured, invalid memory accesses may result.
///
/// <example>
/// <code>
/// // Loop over all events in the InputEventTrace in the `trace` variable.
/// var current = default(InputEventPtr);
/// while (trace.GetNextEvent(ref current))
/// {
/// Debug.Log(current);
/// }
/// </code>
/// </example>
/// </remarks>
public bool GetNextEvent(ref InputEventPtr current)
{
if (m_EventBuffer == default)
return false;
// If head is null, tail is too and it means there's nothing in the
// buffer yet.
if (m_EventBufferHead == default)
return false;
// If current is null, start iterating at head.
if (!current.valid)
{
current = new InputEventPtr((InputEvent*)m_EventBufferHead);
return true;
}
// Otherwise feel our way forward.
var nextEvent = (byte*)current.Next().data;
var endOfBuffer = m_EventBuffer + m_EventBufferSize;
// If we've run into our tail, there's no more events.
if (nextEvent == m_EventBufferTail)
return false;
// If we've reached blank space at the end of the buffer, wrap
// around to the beginning. In this scenario there must be an event
// at the beginning of the buffer; tail won't position itself at
// m_EventBuffer.
if (endOfBuffer - nextEvent < InputEvent.kBaseEventSize ||
((InputEvent*)nextEvent)->sizeInBytes == 0)
{
nextEvent = m_EventBuffer;
if (nextEvent == current.ToPointer())
return false; // There's only a single event in the buffer.
}
// We're good. There's still space between us and our tail.
current = new InputEventPtr((InputEvent*)nextEvent);
return true;
}
public IEnumerator<InputEventPtr> GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Stop recording, if necessary, and clear the trace such that it released unmanaged
/// memory which might be allocated.
/// </summary>
/// <remarks>
/// For any trace that has recorded events, calling this method is crucial in order to not
/// leak memory on the unmanaged (C++) memory heap.
/// </remarks>
public void Dispose()
{
Disable();
Release();
}
// We want to make sure that it's not possible to iterate with an enumerable over
// a trace that is being changed so we bump this counter every time we modify the
// buffer and check in the enumerator that the counts match.
[NonSerialized] private int m_ChangeCounter;
[NonSerialized] private bool m_Enabled;
[NonSerialized] private Func<InputEventPtr, InputDevice, bool> m_OnFilterEvent;
[SerializeField] private int m_DeviceId = InputDevice.InvalidDeviceId;
[NonSerialized] private CallbackArray<Action<InputEventPtr>> m_EventListeners;
// Buffer for storing event trace. Allocated in native so that we can survive a
// domain reload without losing event traces.
// NOTE: Ideally this would simply use InputEventBuffer but we can't serialize that one because
// of the NativeArray it has inside. Also, due to the wrap-around nature, storage of
// events in the buffer may not be linear.
[SerializeField] private long m_EventBufferSize;
[SerializeField] private long m_MaxEventBufferSize;
[SerializeField] private long m_GrowIncrementSize;
[SerializeField] private long m_EventCount;
[SerializeField] private long m_EventSizeInBytes;
// These are ulongs for the sake of Unity serialization which can't handle pointers or IntPtrs.
[SerializeField] private ulong m_EventBufferStorage;
[SerializeField] private ulong m_EventBufferHeadStorage;
[SerializeField] private ulong m_EventBufferTailStorage;
[SerializeField] private bool m_HasWrapped;
[SerializeField] private bool m_RecordFrameMarkers;
[SerializeField] private DeviceInfo[] m_DeviceInfos;
private byte* m_EventBuffer
{
get => (byte*)m_EventBufferStorage;
set => m_EventBufferStorage = (ulong)value;
}
private byte* m_EventBufferHead
{
get => (byte*)m_EventBufferHeadStorage;
set => m_EventBufferHeadStorage = (ulong)value;
}
private byte* m_EventBufferTail
{
get => (byte*)m_EventBufferTailStorage;
set => m_EventBufferTailStorage = (ulong)value;
}
private void Allocate()
{
m_EventBuffer = (byte*)UnsafeUtility.Malloc(m_EventBufferSize, InputEvent.kAlignment, Allocator.Persistent);
}
private void Release()
{
Clear();
if (m_EventBuffer != default)
{
UnsafeUtility.Free(m_EventBuffer, Allocator.Persistent);
m_EventBuffer = default;
}
}
private void OnBeforeUpdate()
{
////TODO: make this work correctly with the different update types
if (m_RecordFrameMarkers)
{
// Record frame marker event.
// NOTE: ATM these events don't get valid event IDs. Might be this is even useful but is more a side-effect
// of there not being a method to obtain an ID except by actually queuing an event.
var frameMarkerEvent = new InputEvent
{
type = FrameMarkerEvent,
internalTime = InputRuntime.s_Instance.currentTime,
sizeInBytes = (uint)UnsafeUtility.SizeOf<InputEvent>()
};
OnInputEvent(new InputEventPtr((InputEvent*)UnsafeUtility.AddressOf(ref frameMarkerEvent)), null);
}
}
private void OnInputEvent(InputEventPtr inputEvent, InputDevice device)
{
// Ignore events that are already marked as handled.
if (inputEvent.handled)
return;
// Ignore if the event isn't for our device (except if it's a frame marker).
if (m_DeviceId != InputDevice.InvalidDeviceId && inputEvent.deviceId != m_DeviceId && inputEvent.type != FrameMarkerEvent)
return;
// Give callback a chance to filter event.
if (m_OnFilterEvent != null && !m_OnFilterEvent(inputEvent, device))
return;
// This shouldn't happen but ignore the event if we're not tracing.
if (m_EventBuffer == default)
return;
var bytesNeeded = inputEvent.sizeInBytes.AlignToMultipleOf(InputEvent.kAlignment);
// Make sure we can fit the event at all.
if (bytesNeeded > m_MaxEventBufferSize)
return;
k_InputEvenTraceMarker.Begin();
if (m_EventBufferTail == default)
{
// First event in buffer.
m_EventBufferHead = m_EventBuffer;
m_EventBufferTail = m_EventBuffer;
}
var newTail = m_EventBufferTail + bytesNeeded;
var newTailOvertakesHead = newTail > m_EventBufferHead && m_EventBufferHead != m_EventBuffer;
// If tail goes out of bounds, enlarge the buffer or wrap around to the beginning.
var newTailGoesPastEndOfBuffer = newTail > m_EventBuffer + m_EventBufferSize;
if (newTailGoesPastEndOfBuffer)
{
// If we haven't reached the max size yet, grow the buffer.
if (m_EventBufferSize < m_MaxEventBufferSize && !m_HasWrapped)
{
var increment = Math.Max(m_GrowIncrementSize, bytesNeeded.AlignToMultipleOf(InputEvent.kAlignment));
var newBufferSize = m_EventBufferSize + increment;
if (newBufferSize > m_MaxEventBufferSize)
newBufferSize = m_MaxEventBufferSize;
if (newBufferSize < bytesNeeded)
{
k_InputEvenTraceMarker.End();
return;
}
Resize(newBufferSize);
newTail = m_EventBufferTail + bytesNeeded;
}
// See if we fit.
var spaceLeft = m_EventBufferSize - (m_EventBufferTail - m_EventBuffer);
if (spaceLeft < bytesNeeded)
{
// No, so wrap around.
m_HasWrapped = true;
// Make sure head isn't trying to advance into gap we may be leaving at the end of the
// buffer by wiping the space if it could fit an event.
if (spaceLeft >= InputEvent.kBaseEventSize)
UnsafeUtility.MemClear(m_EventBufferTail, InputEvent.kBaseEventSize);
m_EventBufferTail = m_EventBuffer;
newTail = m_EventBuffer + bytesNeeded;
// If the tail overtook both the head and the end of the buffer,
// we need to make sure the head is wrapped around as well.
if (newTailOvertakesHead)
m_EventBufferHead = m_EventBuffer;
// Recheck whether we're overtaking head.
newTailOvertakesHead = newTail > m_EventBufferHead;
}
}
// If the new tail runs into head, bump head as many times as we need to
// make room for the event. Head may itself wrap around here.
if (newTailOvertakesHead)
{
var newHead = m_EventBufferHead;
var endOfBufferMinusOneEvent =
m_EventBuffer + m_EventBufferSize - InputEvent.kBaseEventSize;
while (newHead < newTail)
{
var numBytes = ((InputEvent*)newHead)->sizeInBytes;
newHead += numBytes;
--m_EventCount;
m_EventSizeInBytes -= numBytes;
if (newHead > endOfBufferMinusOneEvent || ((InputEvent*)newHead)->sizeInBytes == 0)
{
newHead = m_EventBuffer;
break;
}
}
m_EventBufferHead = newHead;
}
var buffer = m_EventBufferTail;
m_EventBufferTail = newTail;
// Copy data to buffer.
UnsafeUtility.MemCpy(buffer, inputEvent.data, inputEvent.sizeInBytes);
++m_ChangeCounter;
++m_EventCount;
m_EventSizeInBytes += bytesNeeded;
// Make sure we have a record for the device.
if (device != null)
{
var haveRecord = false;
if (m_DeviceInfos != null)
for (var i = 0; i < m_DeviceInfos.Length; ++i)
if (m_DeviceInfos[i].deviceId == device.deviceId)
{
haveRecord = true;
break;
}
if (!haveRecord)
ArrayHelpers.Append(ref m_DeviceInfos, new DeviceInfo
{
m_DeviceId = device.deviceId,
m_Layout = device.layout,
m_StateFormat = device.stateBlock.format,
m_StateSizeInBytes = (int)device.stateBlock.alignedSizeInBytes,
// If it's a generated layout, store the full layout JSON in the device info. We do this so that
// when saving traces for this kind of input, we can recreate the device.
m_FullLayoutJson = InputControlLayout.s_Layouts.IsGeneratedLayout(device.m_Layout)
? InputSystem.LoadLayout(device.layout).ToJson()
: null,
// if the device has usages, store them as JSON in the device info
// This way, when replaying the trace, we can recreate the device with the correct usages. For example XR devices
m_UsagesJson = device.usages.Count > 0
? JsonUtility.ToJson(new DeviceInfo.UsagesJsonWrapper(device.usages))
: null
});
}
// Notify listeners.
if (m_EventListeners.length > 0)
DelegateHelpers.InvokeCallbacksSafe(ref m_EventListeners, new InputEventPtr((InputEvent*)buffer),
"InputEventTrace.onEvent");
k_InputEvenTraceMarker.End();
}
private class Enumerator : IEnumerator<InputEventPtr>
{
private InputEventTrace m_Trace;
private int m_ChangeCounter;
internal InputEventPtr m_Current;
public Enumerator(InputEventTrace trace)
{
m_Trace = trace;
m_ChangeCounter = trace.m_ChangeCounter;
}
public void Dispose()
{
m_Trace = null;
m_Current = new InputEventPtr();
}
public bool MoveNext()
{
if (m_Trace == null)
throw new ObjectDisposedException(ToString());
if (m_Trace.m_ChangeCounter != m_ChangeCounter)
throw new InvalidOperationException("Trace has been modified while enumerating!");
return m_Trace.GetNextEvent(ref m_Current);
}
public void Reset()
{
m_Current = default;
m_ChangeCounter = m_Trace.m_ChangeCounter;
}
public InputEventPtr Current => m_Current;
object IEnumerator.Current => Current;
}
private static FourCC kFileFormat => new FourCC('I', 'E', 'V', 'T');
private static int kFileVersion = 2;
[Flags]
private enum FileFlags
{
FixedUpdate = 1 << 0, // Events were recorded with system being in fixed-update mode.
}
/// <summary>
/// Controls replaying of events recorded in an <see cref="InputEventTrace"/>.