-
Notifications
You must be signed in to change notification settings - Fork 2
/
RemoteCaptury.cpp
3310 lines (2832 loc) · 96.6 KB
/
RemoteCaptury.cpp
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
#if 1
#include "RemoteCaptury.h"
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <memory>
#include <list>
#include <ctime>
#include <time.h>
#include <string.h>
#include <inttypes.h>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
// #define MAXIMUM(a, b) ((a) > (b) ? (a) : (b))
#ifdef WIN32
#undef max
#undef min
#pragma warning(disable : 4200)
#pragma warning(disable : 4996)
#define _CRT_SECURE_NO_WARNINGS
#define _WIN32_WINNT_WINTHRESHOLD 0
#define _APISET_RTLSUPPORT_VER 0
#define _APISET_INTERLOCKED_VER 0
#define _APISET_SECURITYBASE_VER 0
#define NTDDI_WIN7SP1 0
#define snprintf _snprintf
#include <winsock2.h>
#include <sysinfoapi.h>
#pragma comment(lib, "ws2_32.lib")
#ifndef PRIu64
#define PRIu64 "I64u"
#endif
#ifndef PRId64
#define PRId64 "I64d"
#endif
#ifndef SYSTEM_INFO
#include <chrono>
#endif
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <errno.h>
#endif
#include <stdarg.h>
typedef uint32_t uint;
#if defined(__clang__) && (!defined(SWIG))
#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
#else
#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
#endif
#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#define REQUIRES(...) THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
#define ACQUIRE(...) THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
#define RELEASE(...) THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
// #pragma clang optimize off
// #pragma GCC optimize("O0")
#ifdef WIN32
static HANDLE streamThread;
static HANDLE receiveThread;
static HANDLE syncThread;
static CRITICAL_SECTION mutex;
static CRITICAL_SECTION partialActorMutex;
static CRITICAL_SECTION syncMutex;
static CRITICAL_SECTION logMutex;
static bool mutexesInited = false;
#define socklen_t int
#define sleepMicroSeconds(us) Sleep(us / 1000)
static inline int sockerror() { return WSAGetLastError(); }
static inline const char* sockstrerror(int err) { static char msg[200]; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), msg, sizeof(msg), nullptr); return msg; }
static inline const char* sockstrerror() { static char msg[200]; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), msg, sizeof(msg), nullptr); return msg; }
static inline int setSocketTimeout(SOCKET sock, int timeout_ms)
{
DWORD timeout = timeout_ms; // timeout in ms
return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
}
static bool wsaInited = false;
#else
#define SOCKET int
#define closesocket close
static pthread_t streamThread;
static pthread_t receiveThread;
static pthread_t syncThread;
struct CAPABILITY("mutex") MutexStruct {
pthread_mutex_t m;
MutexStruct() { pthread_mutex_init(&m, nullptr); }
void lock() ACQUIRE() { pthread_mutex_lock(&m); }
void unlock() RELEASE() { pthread_mutex_unlock(&m); }
};
static MutexStruct mutex;
static MutexStruct partialActorMutex;
static MutexStruct syncMutex;
static MutexStruct logMutex;
// static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define sleepMicroSeconds(us) usleep(us)
static inline int sockerror() { return errno; }
static inline const char* sockstrerror(int err) { return strerror(err); }
static inline const char* sockstrerror() { return strerror(errno); }
static inline int setSocketTimeout(SOCKET sock, int timeout_ms)
{
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;// seconds timeout
tv.tv_usec = (timeout_ms % 1000) * 1000;
return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
}
#endif
static bool syncLoopIsRunning = false;
static int streamWhat = CAPTURY_STREAM_NOTHING;
static int32_t streamCamera;
static std::vector<uint16_t> streamAngles;
static std::string currentDay;
static std::string currentSession;
static std::string currentShot;
typedef std::shared_ptr<CapturyActor> CapturyActor_p;
// actor id -> pointer to actor
static std::unordered_map<int, CapturyActor_p> actorsById GUARDED_BY(mutex);
static std::unordered_map<const CapturyActor*, CapturyActor_p> returnedActors GUARDED_BY(mutex);
static std::unordered_map<int, CapturyActor_p> partialActors GUARDED_BY(partialActorMutex); // actors that have been received in part
static std::vector<CapturyActor> actorPointers GUARDED_BY(mutex); // used by Captury_getActors()
static std::vector<CapturyActor_p> actorSharedPointers GUARDED_BY(mutex); // used by Captury_getActors()
static std::unordered_map<int, std::vector<CapturyAngleData>> currentAngles;
static int numCameras = -1;
static std::vector<CapturyCamera> cameras;
static CapturyLatencyPacket currentLatency;
static uint64_t receivedPoseTime; // time pose packet was received
static uint64_t receivedPoseTimestamp; // timestamp of pose that corresponds to the receivedPoseTime
static uint64_t dataAvailableTime;
static uint64_t dataReceivedTime;
static uint64_t mostRecentPoseReceivedTime; // time pose was received
static uint64_t mostRecentPoseReceivedTimestamp; // timestamp of that pose
static int framerateNumerator = -1.0f;
static int framerateDenominator = -1.0f;
const char* CapturyActorStatusString[] = {"scaling", "tracking", "stopped", "deleted", "unknown"};
struct ActorData {
// actor id -> scaling progress (0 to 100)
int scalingProgress;
// actor id -> tracking quality (0 to 100)
int trackingQuality;
// actor id -> pose
CapturyPose currentPose;
struct InProgress {
float* pose;
int bytesDone;
uint64_t timestamp;
};
InProgress inProgress[4];
// actor id -> timestamp
uint64_t lastPoseTimestamp;
// actor id -> texture
CapturyImage currentTextures;
std::vector<int> receivedPackets;
CapturyActorStatus status;
int flags;
ActorData() : scalingProgress(0), trackingQuality(100), lastPoseTimestamp(0), status(ACTOR_STOPPED), flags(0)
{
currentPose.timestamp = 0;
currentPose.numTransforms = 0;
currentPose.numBlendShapes = 0;
currentPose.flags = 0;
currentTextures.width = 0;
currentTextures.height = 0;
currentTextures.data = NULL;
for (int i = 0; i < 4; ++i) {
inProgress[i].pose = NULL;
inProgress[i].timestamp = 0;
}
}
};
static std::unordered_map<int, ActorData> actorData GUARDED_BY(mutex);
static std::map<int32_t, CapturyImage> currentImages;
static std::map<int32_t, std::vector<int>> currentImagesReceivedPackets;
static std::map<int32_t, CapturyImage> currentImagesDone;
// custom type name -> callback
static std::map<std::string, CapturyCustomPacketCallback> callbacks;
static uint64_t arTagsTime;
static std::vector<CapturyARTag> arTags;
// helper structs
struct ActorAndJoint {
int actorId;
int jointIndex;
bool operator<(const ActorAndJoint& aj) const
{
if (actorId < aj.actorId)
return true;
if (actorId > aj.actorId)
return false;
return (jointIndex < aj.jointIndex);
}
ActorAndJoint() : actorId(0), jointIndex(-1) {}
ActorAndJoint(int actor, int joint) : actorId(actor), jointIndex(joint) {}
};
struct MarkerTransform {
CapturyTransform trafo;
uint64_t timestamp;
};
// actor id + joint index -> marker transformation + timestamp
static std::map<ActorAndJoint, MarkerTransform> markerTransforms;
// error message
static std::string lastErrorMessage;
static std::string lastStatusMessage = "disconnected";
static bool getLocalPoses = false;
static CapturyNewPoseCallback newPoseCallback = NULL;
static void* newPoseArg = NULL;
static CapturyNewAnglesCallback newAnglesCallback = NULL;
static void* newAnglesArg = NULL;
static CapturyActorChangedCallback actorChangedCallback = NULL;
static void* actorChangedArg = NULL;
static CapturyARTagCallback arTagCallback = NULL;
static void* arTagArg = NULL;
static CapturyImageCallback imageCallback = NULL;
static void* imageArg = NULL;
static volatile bool handshakeFinished = false;
static volatile bool isStreamThreadRunning = false;
static SOCKET sock = -1;
static volatile int stopStreamThread = 0; // stop streaming thread
static volatile int stopReceiving = 0; // stop receiving thread
static sockaddr_in localAddress; // local address
static sockaddr_in localStreamAddress; // local address for streaming socket
static sockaddr_in remoteAddress; // address of server
static uint16_t streamSocketPort = 0;
static uint64_t pingTime;
static int32_t nextTimeId = 213;
static int backgroundQuality = -1;
static CapturyBackgroundFinishedCallback backgroundFinishedCallback = NULL;
static void* backgroundFinishedCallbackUserData = NULL;
static int64_t startRecordingTime = 0;
static bool doPrintf = true;
static bool doRemoteLogging = false;
static std::list<std::string> logs;
#ifndef WIN32
static void log(const char *format, ...) __attribute__((format(printf,1,2)));
#endif
struct Sync {
double offset;
double factor;
Sync(double o, double f) : offset(o), factor(f) {}
uint64_t getRemoteTime(uint64_t localT) { return uint64_t((localT) * factor + offset); }
};
struct SyncSample {
int64_t localT;
int64_t remoteT;
uint32_t pingPongT;
SyncSample(uint64_t l, uint64_t r, uint32_t pp) : localT(l), remoteT(r), pingPongT(pp) {}
};
std::vector<SyncSample> syncSamples;
#ifdef WIN32
static inline void lockMutex(CRITICAL_SECTION* critsec)
{
EnterCriticalSection(critsec);
}
static inline void unlockMutex(CRITICAL_SECTION* critsec)
{
LeaveCriticalSection(critsec);
}
#else
static inline void lockMutex(MutexStruct* mtx) ACQUIRE(mtx)
{
mtx->lock();
}
static inline void unlockMutex(MutexStruct* mtx) RELEASE(mtx)
{
mtx->unlock();
}
// #define unlockMutex(mtx) printf("unlocked %p at %d\n", mtx, __LINE__); (mtx)->unlock()
// #define lockMutex(mtx) printf(" locked %p at %d\n", mtx, __LINE__); (mtx)->lock()
#endif
static void actualLog(int logLevel, const char* format, va_list args)
{
#ifdef WIN32
if (!mutexesInited) {
InitializeCriticalSection(&mutex);
InitializeCriticalSection(&partialActorMutex);
InitializeCriticalSection(&syncMutex);
InitializeCriticalSection(&logMutex);
mutexesInited = true;
}
#endif
char buffer[509];
vsnprintf(buffer + 9, 500, format, args);
if (doPrintf)
printf("%s", buffer + 9);
lockMutex(&logMutex);
logs.emplace_back(buffer + 9);
if (logs.size() > 100000)
logs.pop_front();
unlockMutex(&logMutex);
if (doRemoteLogging && sock != -1) {
CapturyLogPacket* lp = (CapturyLogPacket*)buffer;
lp->type = capturyMessage;
lp->size = 9 + strlen(buffer + 9) + 1;
lp->logLevel = logLevel;
send(sock, (const char*)lp, lp->size, 0);
}
}
static void log(const char* format, ...)
{
va_list args;
va_start(args, format);
actualLog(CAPTURY_LOG_INFO, format, args);
va_end(args);
}
void Captury_log(int logLevel, const char* format, ...)
{
va_list args;
va_start(args, format);
actualLog(logLevel, format, args);
va_end(args);
}
void Captury_enablePrintf(int on)
{
doPrintf = (on != 0);
}
void Captury_enableRemoteLogging(int on)
{
doRemoteLogging = (on != 0);
}
const char* Captury_getNextLogMessage()
{
lockMutex(&logMutex);
if (logs.empty()) {
unlockMutex(&logMutex);
return nullptr;
}
const char* str = strdup(logs.front().c_str());
logs.pop_front();
unlockMutex(&logMutex);
return str;
}
const char* Captury_getHumanReadableMessageType(CapturyPacketTypes type)
{
switch (type) {
case capturyActors:
return "<actors>";
case capturyActor:
return "<actor>";
case capturyCameras:
return "<cameras>";
case capturyCamera:
return "<camera>";
case capturyStream:
return "<stream>";
case capturyStreamAck:
return "<stream ack>";
case capturyPose:
return "<pose>";
case capturyDaySessionShot:
return "<day/session/shot>";
case capturySetShot:
return "<set shot>";
case capturySetShotAck:
return "<set shot ack>";
case capturyStartRecording:
return "<start recording>";
case capturyStartRecordingAck:
return "<start recording ack>";
case capturyStopRecording:
return "<stop recording>";
case capturyStopRecordingAck:
return "<stop recording ack>";
case capturyConstraint:
return "<constraint>";
case capturyConstraintAck:
return "<constraint ack>";
case capturyGetTime:
return "<get time>";
case capturyTime:
return "<time>";
case capturyCustom:
return "<custom>";
case capturyCustomAck:
return "<custom ack>";
case capturyGetImage:
return "<get image>";
case capturyImageHeader:
return "<texture header>";
case capturyImageData:
return "<texture data>";
case capturyGetImageData:
return "<get image data>";
case capturyActorContinued:
return "<actor continued>";
case capturyGetMarkerTransform:
return "<get marker transform>";
case capturyMarkerTransform:
return "<marker transform>";
case capturyGetScalingProgress:
return "<get scaling progress>";
case capturyScalingProgress:
return "<scaling progress>";
case capturySnapActor:
return "<snap actor>";
case capturySnapActorAck:
return "<snap actor ack>";
case capturyStopTracking:
return "<stop tracking>";
case capturyStopTrackingAck:
return "<stop tracking ack>";
case capturyDeleteActor:
return "<delete actor>";
case capturyDeleteActorAck:
return "<delete actor ack>";
case capturyActorModeChanged:
return "<actor mode changed>";
case capturyARTag:
return "<ar tag>";
case capturyGetBackgroundQuality:
return "<get background quality>";
case capturyBackgroundQuality:
return "<background quality>";
case capturyCaptureBackground:
return "<capture background>";
case capturyCaptureBackgroundAck:
return "<capture background ack>";
case capturyBackgroundFinished:
return "<capture background finished>";
case capturySetActorName:
return "<set actor name>";
case capturySetActorNameAck:
return "<set actor name ack>";
case capturyStreamedImageHeader:
return "<streamed image header>";
case capturyStreamedImageData:
return "<streamed image data>";
case capturyGetStreamedImageData:
return "<get streamed image data>";
case capturyRescaleActor:
return "<rescale actor>";
case capturyRecolorActor:
return "<recolor actor>";
case capturyUpdateActorColors:
return "<update actor colors>";
case capturyRescaleActorAck:
return "<rescale actor ack>";
case capturyRecolorActorAck:
return "<recolor actor ack>";
case capturyStartTracking:
return "<start tracking>";
case capturyStartTrackingAck:
return "<start tracking ack>";
case capturyPoseCont:
return "<pose continued>";
case capturyPose2:
return "<pose2>";
case capturyGetStatus:
return "<get status>";
case capturyStatus:
return "<status>";
case capturyActor2:
return "<actor2>";
case capturyActorContinued2:
return "<actor2 continued>";
case capturyLatency:
return "<latency measurements>";
case capturyActors2:
return "<actors2>";
case capturyActor3:
return "<actor3>";
case capturyActorContinued3:
return "<actor3 continued>";
case capturyCompressedPose:
return "<compressed pose>";
case capturyCompressedPose2:
return "<compressed pose2>";
case capturyCompressedPoseCont:
return "<compressed pose continued>";
case capturyGetTime2:
return "<get time2>";
case capturyTime2:
return "<time2>";
case capturyAngles:
return "<angles>";
case capturyStartRecording2:
return "<start recording 2>";
case capturyStartRecordingAck2:
return "<start recording ack 2>";
case capturyHello:
return "<hello>";
case capturyActorBlendShapes:
return "<actor blend shapes>";
case capturyMessage:
return "<message>";
case capturyEnableRemoteLogging:
return "<enable remote logging>";
case capturyDisableRemoteLogging:
return "<enable remote logging>";
case capturyError:
return "<error>";
case capturyGetFramerate:
return "<get framerate>";
case capturyFramerate:
return "<framerate>";
}
return "<unknown message type>";
}
#ifdef SYSTEM_INFO
// thanks https://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/
// A UNIX timestamp contains the number of seconds from Jan 1, 1970, while the FILETIME documentation says:
// Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
//
// Between Jan 1, 1601 and Jan 1, 1970 there are 11644473600 seconds, so we will just subtract that value:
static uint64_t convertFileTimeToTimestamp(FILETIME& ft)
{
// takes the last modified date
LARGE_INTEGER date, adjust;
date.HighPart = ft.dwHighDateTime;
date.LowPart = ft.dwLowDateTime;
// 100-nanoseconds = milliseconds * 10000
adjust.QuadPart = 11644473600000 * 10000;
// removes the diff between 1970 and 1601
date.QuadPart -= adjust.QuadPart;
// converts back from 100-nanoseconds to microseconds
return date.QuadPart / 10;
}
#endif
//
// returns current time in us
//
static uint64_t getTime()
{
#ifdef WIN32
#ifdef SYSTEM_INFO
FILETIME ft;
GetSystemTimePreciseAsFileTime(&ft);
return convertFileTimeToTimestamp(ft);
#else
std::chrono::time_point<std::chrono::system_clock> tp = std::chrono::system_clock::now();
std::chrono::duration<double, std::micro> duration = tp.time_since_epoch();
return (uint64_t)duration.count();
#endif
#else
timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return (uint64_t)t.tv_sec * 1000000 + t.tv_nsec / 1000;
#endif
}
//
// the approach this function takes may not be obvious.
//
// generally the goal is to estimate remote time r as a function of the local time l.
// we assume that r = l * f + o
// i.e. there is an offset between the clocks and a linear drift
//
// given some measurement samples the goal is to compute the two parameters f and o
//
// the naive approach of estimating the parameters directly with a linear system fails
// because of numerical instability. that's why we first subtract mean/median and then
// solve the following:
// note that the median(r-l) is necessary because the remote time measurement is noisy
// local time measurement is relatively smooth. so using the mean is sufficient.
//
// b = r - l - median(r-l)
// a = l - mean(l)
// a * f = b
// f = a \ b <=>
// f = dot(a, b) / dot(a, a) <- least squares solution
// (l - mean(l)) * f = b <=>
// (l - mean(l)) * f = r - l - median(r-l) <=>
// (l - mean(l)) * f + l + median(r-l) = r <=>
// (l - mean(l)) * f + l + median(r-l) = r <=>
// l * (f + 1) + median(r-l) - mean(l) * f = r
// \_____/ \_______________________/
// factor offset
//
// note that for extra efficiency all operations except for the division in the
// least squares solution and the multiplication in the last line can be performed as
// integer operations.
//
// if there are only a few samples we cannot estimate the slope f accurately. so we
// just estimate an offset (the median of the time differences between remote and local)
//
void computeSync(Sync& s)
{
double meanLocalT = 0;
double medianOffset = 0.0;
int64_t offsets[50];
int num = (int)syncSamples.size();
for (int i = 0; i < num; ++i) {
SyncSample& ss = syncSamples[i];
offsets[i] = ss.remoteT - ss.localT; // alternatively use median here
meanLocalT += ss.localT;
}
std::sort(&offsets[0], &offsets[num]);
medianOffset = (num % 2 == 0) ? (offsets[num/2] + offsets[num/2+1]) * 0.5 : offsets[num/2];
if (num < 10 || (syncSamples.back().localT - syncSamples.front().localT) < 1000000) { // not enough samples
s.offset = medianOffset;
s.factor = 1.0;
log("sync based on %d samples: offset %g\n", num, s.offset);
} else {
s.offset = medianOffset;
s.factor = 0.0;
meanLocalT /= num;
int64_t sumAsqr = 0;
int64_t sumAB = 0;
for (SyncSample& ss : syncSamples) {
int64_t a = ss.localT - meanLocalT;
sumAsqr += a*a;
int64_t b = ss.remoteT - ss.localT - medianOffset;
sumAB += a*b;
}
s.factor = sumAB / (double)sumAsqr;
s.offset -= meanLocalT * s.factor;
s.factor += 1.0;
log("sync based on %d samples: offset %15f, factor %.15f (mlt %15f, moff %15f)\n", num, s.offset, s.factor, meanLocalT, medianOffset);
}
}
static Sync oldSync GUARDED_BY(syncMutex) = Sync(0.0, 1.0);
static Sync currentSync GUARDED_BY(syncMutex) = Sync(0.0, 1.0);
static uint64_t transitionStartLocalT GUARDED_BY(syncMutex) = 0;
static uint64_t transitionEndLocalT GUARDED_BY(syncMutex) = 0;
static void updateSync(uint64_t localT)
{
constexpr uint64_t defaultTransitionTime = 100000; // 0.1 second
Sync tempSync(0.0, 1.0);
computeSync(tempSync);
lockMutex(&syncMutex);
transitionStartLocalT = localT;
// transitionFactor = std::abs(transitionStartRemoteT - remoteT) / defaultTransitionTime;
// TODO limit skew speed
transitionEndLocalT = transitionStartLocalT + defaultTransitionTime;
double transitionStartRemoteT = (double)currentSync.getRemoteTime(localT);
oldSync = currentSync;
currentSync = tempSync;
double delta = transitionStartRemoteT - currentSync.getRemoteTime(localT);
double factor = currentSync.factor;
unlockMutex(&syncMutex);
log("sync: old - new estimate %g (factor %g)\n", delta, factor);
}
static uint64_t getRemoteTime(uint64_t localT)
{
lockMutex(&syncMutex);
if (localT >= transitionEndLocalT) {
uint64_t t = currentSync.getRemoteTime(localT);
unlockMutex(&syncMutex);
return t;
}
uint64_t oldEstimate = oldSync.getRemoteTime(localT);
uint64_t newEstimate = currentSync.getRemoteTime(localT);
double at = double(localT - transitionStartLocalT) / (transitionEndLocalT - transitionStartLocalT);
unlockMutex(&syncMutex);
// log("sync: local %" PRIu64 " old %" PRIu64 " new %" PRIu64 " -> %" PRIu64 "\n", localT, oldEstimate, newEstimate, (uint64_t)(oldEstimate * (1.0 - at) + newEstimate * at));
return (uint64_t)(oldEstimate * (1.0 - at) + newEstimate * at);
}
extern "C" uint64_t Captury_getTime()
{
return getRemoteTime(getTime());
}
static SOCKET openTcpSocket()
{
log("opening TCP socket\n");
SOCKET sok = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sok == -1)
return -1;
if (localAddress.sin_port != 0 && bind(sok, (sockaddr*) &localAddress, sizeof(localAddress)) != 0) {
closesocket(sok);
return -1;
}
if (connect(sok, (sockaddr*) &remoteAddress, sizeof(remoteAddress)) != 0) {
closesocket(sok);
return -1;
}
// set read timeout
setSocketTimeout(sok, 500);
#ifndef WIN32
char buf[100];
log("connected to %s:%d\n", inet_ntop(AF_INET, &remoteAddress.sin_addr, buf, 100), ntohs(remoteAddress.sin_port));
#endif
return sok;
}
static bool isSocketErrorFatal(int err)
{
#ifdef WIN32
return (err == WSAENOTSOCK || err == WSAESHUTDOWN || err == WSAECONNABORTED || err == WSAECONNRESET || err == WSAENETDOWN || err == WSAENETUNREACH || err == WSAENETRESET || err == WSAEBADF);
#else
return (err == EPIPE || err == ECONNRESET || err == ENETRESET || err == EBADF);
#endif
}
static bool isSocketErrorTryAgain(int err)
{
#ifdef WIN32
return (err == WSAEINTR || err == WSAETIMEDOUT || err == WSAEWOULDBLOCK || err == WSAEINPROGRESS || err == 0);
#else
return (err == EAGAIN || err == EBUSY || err == EINTR);
#endif
}
// waits for at most 500ms before it fails
// returns false if the expected packet is not received
static bool receive(SOCKET& sok)
{
static std::vector<char> buffer(9000);
CapturyRequestPacket* p = (CapturyRequestPacket*)buffer.data();
{
fd_set reader;
FD_ZERO(&reader);
FD_SET(sok, &reader);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 500000; // 500ms should be enough
int ret = select((int)(sok+1), &reader, NULL, NULL, &tv);
if (ret == -1) { // error
int err = sockerror();
if (isSocketErrorFatal(err)) {
// connection closed by peer or network down
closesocket(sok);
sok = -1;
}
log("error waiting for socket: %s\n", sockstrerror(err));
return false;
}
if (ret == 0) { // timeout
return true;
}
{
struct sockaddr_in thisEnd;
socklen_t len = sizeof(thisEnd);
getsockname(sok, (sockaddr*) &thisEnd, &len);
}
// first peek to find out which packet type this is
int size = recv(sok, buffer.data(), sizeof(CapturyRequestPacket), 0);
if (size == 0) { // the other end shut down the socket...
log("socket shut down by other end %s\n", sockstrerror());
closesocket(sok);
sok = -1;
return false;
}
if (size == -1) { // error
int err = sockerror();
log("socket error %s\n", sockstrerror(err));
if (isSocketErrorFatal(err)) {
closesocket(sok);
sok = -1;
}
return false;
}
if (p->size > (int)sizeof(CapturyRequestPacket)) {
if (p->size > 10000000) {
log("invalid packet size: %d. closing connection.", p->size);
closesocket(sok);
sok = -1;
return false;
}
int at = sizeof(CapturyRequestPacket);
if (p->size > (int)buffer.size()) {
buffer.resize(p->size);
p = (CapturyRequestPacket*)buffer.data();
}
int toGet = p->size - at;
while (toGet > 0) {
size = recv(sok, &buffer[at], toGet, 0);
if (size == 0) { // the other end shut down the socket...
log("socket shut down by other end: %s\n", sockstrerror());
closesocket(sok);
sok = -1;
return false;
}
if (size == -1) { // error
int err = sockerror();
log("socket error: %s\n", sockstrerror(err));
if (isSocketErrorFatal(err)) {
closesocket(sok);
sok = -1;
}
return false;
}
at += size;
toGet = std::min<int>(p->size, buffer.size()) - at;
}
size = std::min<int>(p->size, buffer.size());
}
// log("received packet size %d type %d (expected %d)\n", size, p->type, expect);
switch (p->type) {
case capturyHello:
handshakeFinished = true;
break;
case capturyActors: {
CapturyActorsPacket* cap = (CapturyActorsPacket*)p;
log("expecting %d actor packets\n", cap->numActors);
// if (expect == capturyActors) {
// if (cap->numActors != 0) {
// packetsMissing = cap->numActors;
// expect = capturyActor;
// }
// }
// numRetries += packetsMissing;
break; }
case capturyCameras: {
CapturyCamerasPacket* ccp = (CapturyCamerasPacket*)p;
numCameras = ccp->numCameras;
// if (expect == capturyCameras) {
// packetsMissing = numCameras;
// expect = capturyCamera;
// }
// numRetries += packetsMissing;
break; }
case capturyActor:
case capturyActor2:
case capturyActor3: {
CapturyActor_p actor(new CapturyActor);
CapturyActorPacket* cap = (CapturyActorPacket*)p;
strncpy(actor->name, cap->name, sizeof(actor->name));
actor->id = cap->id;
actor->numJoints = cap->numJoints;
actor->joints = new CapturyJoint[actor->numJoints];
char* at = (char*)cap->joints;
char* end = &buffer[size];
int version = (p->type == capturyActor) ? 1 : (p->type == capturyActor2) ? 2 : 3;
int numTransmittedJoints = 0;
for (int j = 0; at < end; ++j) {
switch (version) {
case 1: {
CapturyJointPacket* jp = (CapturyJointPacket*)at;
actor->joints[j].parent = jp->parent;
for (int x = 0; x < 3; ++x) {
actor->joints[j].offset[x] = jp->offset[x];
actor->joints[j].orientation[x] = jp->orientation[x];
actor->joints[j].scale[x] = 1.0f;
}
strncpy(actor->joints[j].name, jp->name, sizeof(actor->joints[j].name));
at += sizeof(CapturyJointPacket);
break; }
case 2: {
CapturyJointPacket2* jp = (CapturyJointPacket2*)at;
actor->joints[j].parent = jp->parent;
for (int x = 0; x < 3; ++x) {
actor->joints[j].offset[x] = jp->offset[x];
actor->joints[j].orientation[x] = jp->orientation[x];
actor->joints[j].scale[x] = 1.0f;
}
strncpy(actor->joints[j].name, jp->name, sizeof(actor->joints[j].name)-1);
at += sizeof(CapturyJointPacket2) + strlen(jp->name) + 1;
break; }
case 3: {
CapturyJointPacket3* jp = (CapturyJointPacket3*)at;
actor->joints[j].parent = jp->parent;
for (int x = 0; x < 3; ++x) {
actor->joints[j].offset[x] = jp->offset[x];
actor->joints[j].orientation[x] = jp->orientation[x];
actor->joints[j].scale[x] = jp->scale[x];
}
strncpy(actor->joints[j].name, jp->name, sizeof(actor->joints[j].name)-1);
at += sizeof(CapturyJointPacket3) + strlen(jp->name) + 1;
break; }
}
numTransmittedJoints = j + 1;
}
actor->numBlendShapes = 0;
/*int numTransmittedJoints = std::min<int>((cap->size - sizeof(CapturyActorPacket)) / sizeof(CapturyJointPacket), actor->numJoints);
for (int j = 0; j < numTransmittedJoints; ++j) {
strcpy(actor->joints[j].name, cap->joints[j].name);
actor->joints[j].parent = cap->joints[j].parent;
for (int x = 0; x < 3; ++x) {
actor->joints[j].offset[x] = cap->joints[j].offset[x];
actor->joints[j].orientation[x] = cap->joints[j].orientation[x];
}
}*/
for (int j = numTransmittedJoints; j < actor->numJoints; ++j) { // initialize to default values
strncpy(actor->joints[j].name, "uninitialized", sizeof(actor->joints[j].name));
actor->joints[j].parent = 0;
for (int x = 0; x < 3; ++x) {
actor->joints[j].offset[x] = 0;
actor->joints[j].orientation[x] = 0;
}
}
if (numTransmittedJoints < actor->numJoints) {
// expect = (version == 1) ? capturyActorContinued : (version == 2) ? capturyActorContinued2 : capturyActorContinued3;
// numRetries += 1;
}
log("received actor %x (%d/%d)\n", actor->id, numTransmittedJoints, actor->numJoints);
p->type = capturyActor;
if (numTransmittedJoints == actor->numJoints) {
//log("received fulll actor %d\n", actor->id);
lockMutex(&mutex);
actorsById[actor->id] = actor;
unlockMutex(&mutex);
if (actorChangedCallback)
actorChangedCallback(actor->id, actorData[actor->id].status, actorChangedArg);
} else {
lockMutex(&partialActorMutex);
partialActors[actor->id] = actor;
unlockMutex(&partialActorMutex);
}
break; }
case capturyActorContinued:
case capturyActorContinued2:
case capturyActorContinued3: {
int version = (p->type == capturyActor) ? 1 : (p->type == capturyActor2) ? 2 : 3;