forked from thecaptury/RemoteCaptury
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoteCaptury.cpp
2634 lines (2246 loc) · 77.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 <ctime>
#include <time.h>
#include <string.h>
#include <inttypes.h>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
#ifdef WIN32
#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>
#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
typedef uint32_t uint;
#if defined WIN32 || defined _WIN32 && !defined __CYGWIN__
static inline void atomicStore(int64_t* ptr, int64_t value) { InterlockedExchange64(ptr, value); }
static inline void atomicLoad(int64_t* srcPtr, int64_t* dstPtr) { *dstPtr = InterlockedOr64(srcPtr, 0); }
#else
#if ((__GNUC__ * 100 + __GNUC_MINOR__ * 10) > 464)
#define atomicStore(dstPtr, value) __atomic_store(dstPtr, &(value), __ATOMIC_RELAXED)
#define atomicLoad(srcPtr, dstPtr) __atomic_load(srcPtr, dstPtr, __ATOMIC_RELAXED)
#else
#define atomicStore(where, what) *(where) = (what);
#define atomicLoad(srcPtr, dstPtr) *(dstPtr) = *(srcPtr);
#endif
#endif
#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__))
#ifdef WIN32
static HANDLE thread;
static CRITICAL_SECTION mutex;
static CRITICAL_SECTION partialActorMutex;
#define socklen_t int
#else
#define SOCKET int
#define closesocket close
static pthread_t thread;
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 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static std::string currentDay;
static std::string currentSession;
static std::string currentShot;
static int numCameras = -1;
static std::vector<CapturyCamera> cameras;
static std::vector<CapturyActor> actors GUARDED_BY(mutex); // current actors
static std::vector<CapturyActor> partialActors GUARDED_BY(partialActorMutex); // actors that have been received in part
static std::vector<CapturyActor> newActors GUARDED_BY(mutex); // actors that have just been received
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
// actor id -> pointer to actor
static std::map<int, CapturyActor*> actorsById GUARDED_BY(mutex);
const char* CapturyActorStatusString[] = {"scaling", "tracking", "stopped", "deleted"};
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_DELETED), flags(0)
{
currentPose.numTransforms = 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::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;
static bool getLocalPoses = false;
static CapturyNewPoseCallback newPoseCallback = NULL;
static CapturyActorChangedCallback actorChangedCallback = NULL;
static CapturyARTagCallback arTagCallback = NULL;
static CapturyImageCallback imageCallback = NULL;
static bool isThreadRunning = false;
static SOCKET sock = -1;
static volatile int stopStreamThread = 0; // stop streaming 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 int64_t timeOffset = 0; // time offset between clock on Captury Live server and local machine
static int backgroundQuality = -1;
static CapturyBackgroundFinishedCallback backgroundFinishedCallback = NULL;
static void* backgroundFinishedCallbackUserData = NULL;
#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();
}
#endif
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 capturyError:
return "<error>";
}
return "<unknown message type>";
}
#ifdef WIN32
// 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:
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
}
// waits for at most 30ms before it fails
// returns false if the expected packet is not received
static bool receive(SOCKET sok, CapturyPacketTypes expect)
{
int numRetries = 3;
int packetsMissing = 1;
char buf[9000];
CapturyRequestPacket* p = (CapturyRequestPacket*) &buf[0];
for (int n = 0; n < numRetries; ++n) {
fd_set reader;
FD_ZERO(&reader);
FD_SET(sok, &reader);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 10000; // 10ms should be enough
int ret = select((int)(sok+1), &reader, NULL, NULL, &tv);
if (ret == -1) { // error
printf("error waiting for socket waiting for packet type %s\n", Captury_getHumanReadableMessageType(expect));
return 0;
}
if (ret == 0) {
printf("timeout waiting for packet type %s\n", Captury_getHumanReadableMessageType(expect));
continue;
}
{
struct sockaddr_in thisEnd;
socklen_t len = sizeof(thisEnd);
getsockname(sok, (sockaddr*) &thisEnd, &len);
// #ifdef WIN32
// printf("Stream receiving on %d.%d.%d.%d:%d\n", thisEnd.sin_addr.S_un.S_un_b.s_b1, thisEnd.sin_addr.S_un.S_un_b.s_b2, thisEnd.sin_addr.S_un.S_un_b.s_b3, thisEnd.sin_addr.S_un.S_un_b.s_b4, ntohs(thisEnd.sin_port));
// #else
// char buf[100];
// printf("stream receiving on %s:%d\n", inet_ntop(AF_INET, &thisEnd.sin_addr, buf, 100), ntohs(thisEnd.sin_port));
// #endif
}
// first peek to find out which packet type this is
int size = recv(sok, buf, sizeof(buf), 0);
if (size == 0) { // the other end shut down the socket...
printf("socket shut down by other end\n");
return 0;
}
if (size == -1) { // error
printf("socket error\n");
return 0;
}
// printf("received packet size %d type %d (expected %d)\n", size, p->type, expect);
switch (p->type) {
case capturyActors: {
CapturyActorsPacket* cap = (CapturyActorsPacket*)&buf[0];
printf("expecting %d actor packets\n", cap->numActors);
if (expect == capturyActors) {
if (cap->numActors != 0) {
packetsMissing = cap->numActors;
expect = capturyActor2;
}
}
numRetries += packetsMissing;
break; }
case capturyCameras: {
CapturyCamerasPacket* ccp = (CapturyCamerasPacket*)&buf[0];
numCameras = ccp->numCameras;
if (expect == capturyCameras) {
packetsMissing = numCameras;
expect = capturyCamera;
}
numRetries += packetsMissing;
break; }
case capturyActor:
case capturyActor2:
case capturyActor3: {
CapturyActor actor;
CapturyActorPacket* cap = (CapturyActorPacket*)&buf[0];
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 = buf + 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;
}
/*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;
}
//printf("received actor %d (%d/%d), missing %d\n", actor.id, numTransmittedJoints, actor.numJoints, packetsMissing);
p->type = capturyActor;
if (numTransmittedJoints == actor.numJoints) {
//printf("received fulll actor %d\n", actor.id);
lockMutex(&mutex);
newActors.push_back(actor);
unlockMutex(&mutex);
} else {
lockMutex(&partialActorMutex);
partialActors.push_back(actor);
unlockMutex(&partialActorMutex);
}
break; }
case capturyActorContinued:
case capturyActorContinued2:
case capturyActorContinued3: {
int version = (p->type == capturyActor) ? 1 : (p->type == capturyActor2) ? 2 : 3;
CapturyActorContinuedPacket* cacp = (CapturyActorContinuedPacket*)&buf[0];
lockMutex(&partialActorMutex);
for (int i = 0; i < (int) partialActors.size(); ++i) {
if (partialActors[i].id != cacp->id)
continue;
CapturyActor& actor = partialActors[i];
int j = cacp->startJoint;
switch (version) {
case 1: {
CapturyJointPacket* end = (CapturyJointPacket*)&buf[size];
for (int k = 0; j < actor.numJoints && &cacp->joints[k] < end; ++j, ++k) {
strncpy(actor.joints[j].name, cacp->joints[k].name, sizeof(actor.joints[j].name)-1);
actor.joints[j].parent = cacp->joints[k].parent;
for (int x = 0; x < 3; ++x) {
actor.joints[j].offset[x] = cacp->joints[k].offset[x];
actor.joints[j].orientation[x] = cacp->joints[k].orientation[x];
actor.joints[j].scale[x] = 1.0f;
}
}
break; }
case 2: {
char* at = (char*)cacp->joints;
char* end = (char*)&buf[size];
for ( ; j < actor.numJoints && at < end; ++j) {
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: {
char* at = (char*)cacp->joints;
char* end = (char*)&buf[size];
for ( ; j < actor.numJoints && at < end; ++j) {
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; }
}
if (j == actor.numJoints) {
// printf("received fulll actor %d\n", actor.id);
lockMutex(&mutex);
newActors.push_back(actor);
unlockMutex(&mutex);
partialActors.erase(partialActors.begin() + i);
} else {
// expect is already set correctly
numRetries += 1;
packetsMissing += 1;
}
// printf("received actor cont %d (%d/%d), missing %d\n", actor.id, j, actor.numJoints, packetsMissing);
break;
}
unlockMutex(&partialActorMutex);
break; }
case capturyCamera: {
CapturyCamera camera;
CapturyCameraPacket* ccp = (CapturyCameraPacket*)&buf[0];
strncpy(camera.name, ccp->name, sizeof(camera.name));
camera.id = ccp->id;
for (int x = 0; x < 3; ++x) {
camera.position[x] = ccp->position[x];
camera.orientation[x] = ccp->orientation[x];
}
camera.sensorSize[0] = ccp->sensorSize[0];
camera.sensorSize[1] = ccp->sensorSize[1];
camera.focalLength = ccp->focalLength;
camera.lensCenter[0] = ccp->lensCenter[0];
camera.lensCenter[1] = ccp->lensCenter[1];
strncpy(camera.distortionModel, "none", sizeof(camera.distortionModel));
memset(&camera.distortion[0], 0, sizeof(camera.distortion));
// TODO compute extrinsic and intrinsic matrix
lockMutex(&mutex);
cameras.push_back(camera);
unlockMutex(&mutex);
break; }
case capturyPose:
case capturyPose2:
printf("received pose on control socket\n");
break;
case capturyDaySessionShot: {
CapturyDaySessionShotPacket* dss = (CapturyDaySessionShotPacket*)&buf[0];
currentDay = dss->day;
currentSession = dss->session;
currentShot = dss->shot;
break; }
case capturyTime: {
CapturyTimePacket* tp = (CapturyTimePacket*)&buf[0];
int64_t zero = 0;
atomicStore(&timeOffset, zero);
uint64_t pongTime = getTime();
// we assume that the network transfer time is symmetric
// so the timestamp given in the packet was captured at (pingTime + pongTime) / 2
uint64_t t = (pongTime - pingTime) / 2 + pingTime;
int64_t delta = tp->timestamp - t;
atomicStore(&timeOffset, delta);
printf("local: %" PRIu64 " remote: %" PRIu64 " => offset %" PRId64 ", roundtrip %" PRId64 "\n", t, tp->timestamp, tp->timestamp - t, pongTime - pingTime);
break; }
case capturyCustom: {
CapturyCustomPacket* ccp = (CapturyCustomPacket*)&buf[0];
ccp->name[15] = 0;
std::map<std::string, CapturyCustomPacketCallback>::iterator it = callbacks.find(ccp->name);
if (it == callbacks.end()) // no callback for this string
break;
it->second(ccp->size - sizeof(CapturyCustomPacketCallback), ccp->data);
break; }
case capturyImageHeader: {
CapturyImageHeaderPacket* tp = (CapturyImageHeaderPacket*)&buf[0];
// update the image structures
lockMutex(&mutex);
if (actorData.count(tp->actor) > 0) {
free(actorData[tp->actor].currentTextures.data);
actorData[tp->actor].currentTextures.data = NULL;
}
actorData[tp->actor].currentTextures.camera = -1;
actorData[tp->actor].currentTextures.width = tp->width;
actorData[tp->actor].currentTextures.height = tp->height;
actorData[tp->actor].currentTextures.timestamp = 0;
// printf("got image header %dx%d for actor %x\n", currentTextures[tp->actor].width, currentTextures[tp->actor].height, tp->actor);
actorData[tp->actor].currentTextures.data = (unsigned char*)malloc(tp->width*tp->height*3);
actorData[tp->actor].receivedPackets = std::vector<int>( ((tp->width*tp->height*3 + tp->dataPacketSize-16-1) / (tp->dataPacketSize-16)), 0);
unlockMutex(&mutex);
// and request the data to go with it
if (sock == -1 || streamSocketPort == 0)
break;
CapturyGetImageDataPacket packet;
packet.type = capturyGetImageData;
packet.size = sizeof(packet);
packet.actor = tp->actor;
packet.port = streamSocketPort;
// printf("requesting image to port %d\n", ntohs(packet.port));
if (send(sock, (const char*)&packet, packet.size, 0) != packet.size)
break;
break; }
case capturyMarkerTransform: {
CapturyMarkerTransformPacket* cmt = (CapturyMarkerTransformPacket*)&buf[0];
ActorAndJoint aj(cmt->actor, cmt->joint);
MarkerTransform& mt = markerTransforms[aj];
mt.timestamp = cmt->timestamp;
mt.trafo.translation[0] = cmt->translation[0];
mt.trafo.translation[1] = cmt->translation[1];
mt.trafo.translation[2] = cmt->translation[2];
mt.trafo.rotation[0] = cmt->rotation[0];
mt.trafo.rotation[1] = cmt->rotation[1];
mt.trafo.rotation[2] = cmt->rotation[2];
break; }
case capturyScalingProgress: {
CapturyScalingProgressPacket* spp = (CapturyScalingProgressPacket*)&buf[0];
lockMutex(&mutex);
actorData[spp->actor].scalingProgress = spp->progress;
unlockMutex(&mutex);
break; }
case capturyBackgroundQuality: {
CapturyBackgroundQualityPacket* bqp = (CapturyBackgroundQualityPacket*)&buf[0];
backgroundQuality = bqp->quality;
break; }
case capturyStatus: {
CapturyStatusPacket* sp = (CapturyStatusPacket*)&buf[0];
lastStatusMessage = sp->message; // FIXME this is unsafe. assumes that message is 0 terminated.
break; }
case capturyStreamAck:
case capturySetShotAck:
case capturyStartRecordingAck:
case capturyStopRecordingAck:
case capturyCustomAck:
break; // all good
}
if (p->type == expect) {
--packetsMissing;
if (packetsMissing == 0)
break;
}
}
return (packetsMissing == 0);
}
static bool sendPacket(CapturyRequestPacket* packet, CapturyPacketTypes expectedReplyType)
{
bool received = false;
for (int i = 0; i < 3; ++i) {
if (send(sock, (const char*)packet, packet->size, 0) != packet->size)
continue;
if (expectedReplyType == capturyError)
break;
if (receive(sock, expectedReplyType)) {
received = true;
break;
}
}
return received;
}
static void receivedPose(CapturyPose* pose, int actorId, ActorData* aData, uint64_t timestamp) REQUIRES(mutex)
{
if (getLocalPoses)
Captury_convertPoseToLocal(pose, actorId);
pose->timestamp = timestamp;
uint64_t now = getTime();
aData->lastPoseTimestamp = now;
int64_t to;
atomicLoad(&timeOffset, &to);
mostRecentPoseReceivedTime = now + to;
mostRecentPoseReceivedTimestamp = timestamp;
if (aData->status != ACTOR_SCALING && aData->status != ACTOR_TRACKING) {
aData->status = ACTOR_TRACKING;
if (actorChangedCallback) {
unlockMutex(&mutex);
actorChangedCallback(actorId, ACTOR_TRACKING);
lockMutex(&mutex);
}
}
if (newPoseCallback != NULL) {
if (actorsById[actorId]) {
CapturyActor* actor = actorsById[actorId];
unlockMutex(&mutex);
newPoseCallback(actor, pose, aData->trackingQuality);
lockMutex(&mutex);
} else {
bool added = false;
while (!newActors.empty()) {
CapturyActor& actor = newActors.back();
if (actorsById.count(actor.id) == 0 || actorsById[actor.id] == nullptr) {
actors.push_back(actor);
added = true;
}
newActors.pop_back();
}
if (added) {
actorsById.clear();
for (CapturyActor& actor : actors)
actorsById[actor.id] = &actor;
}
if (actorsById.count(actorId) == 0 || actorsById[actorId] == nullptr) {
CapturyRequestPacket packet;
packet.type = capturyActors2;
packet.size = sizeof(packet);
sendPacket(&packet, capturyActors);
} else {
CapturyActor* actor = actorsById[actorId];
unlockMutex(&mutex);
newPoseCallback(actor, pose, aData->trackingQuality);
lockMutex(&mutex);
}
}
}
// mark actors as stopped if no data was received for a while
now -= 500000; // half a second ago
for (std::map<int, ActorData>::iterator it = actorData.begin(); it != actorData.end(); ++it) {
if (it->second.lastPoseTimestamp > now) // still current
continue;
if (it->second.status == ACTOR_SCALING || it->second.status == ACTOR_TRACKING) {
if (actorChangedCallback) {
unlockMutex(&mutex);
actorChangedCallback(it->first, ACTOR_STOPPED);
lockMutex(&mutex);
}
it->second.status = ACTOR_STOPPED;
}
}
}
#ifdef WIN32
static DWORD WINAPI streamLoop(void* arg)
#else
static void* streamLoop(void* arg)
#endif
{
isThreadRunning = true;
CapturyStreamPacket* packet = (CapturyStreamPacket*)arg;
SOCKET streamSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (streamSock == -1) {
printf("failed to create stream socket\n");
delete packet;
return 0;
}
if (bind(streamSock, (sockaddr*) &localStreamAddress, sizeof(localStreamAddress)) != 0) {
closesocket(streamSock);
printf("failed to bind stream socket\n");
delete packet;
return 0;
}
if (connect(streamSock, (sockaddr*) &remoteAddress, sizeof(remoteAddress)) != 0) {
closesocket(streamSock);
printf("failed to connect stream socket\n");
delete packet;
return 0;
}
// set read timeout
struct timeval tv;
tv.tv_sec = 0; /* 100 milliseconds Timeout */
tv.tv_usec = 100000;
setsockopt(streamSock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
{
struct sockaddr_in thisEnd;
socklen_t len = sizeof(thisEnd);
getsockname(streamSock, (sockaddr*) &thisEnd, &len);
streamSocketPort = thisEnd.sin_port;
#ifdef WIN32
printf("Stream receiving on %d.%d.%d.%d:%d\n", thisEnd.sin_addr.S_un.S_un_b.s_b1, thisEnd.sin_addr.S_un.S_un_b.s_b2, thisEnd.sin_addr.S_un.S_un_b.s_b3, thisEnd.sin_addr.S_un.S_un_b.s_b4, ntohs(thisEnd.sin_port));
#else
char buf[100];
printf("stream receiving on %s:%d\n", inet_ntop(AF_INET, &thisEnd.sin_addr, buf, 100), ntohs(thisEnd.sin_port));
#endif
}
// printf("stream packet has size %d\n", packet->size);
// resend request 3 times
bool received = false;
for (int i = 0; i < 3; ++i) {
if (send(streamSock, (const char*)packet, packet->size, 0) != packet->size)
continue;
if (receive(streamSock, capturyStreamAck)) {
received = true;
break;
}
}
if (!received) {
lastErrorMessage = "Failed to start streaming";
delete packet;
return 0;
}
time_t lastHeartbeat = time(NULL);
do {
fd_set reader;
FD_ZERO(&reader);
FD_SET(streamSock, &reader);
// keep the streaming alive
time_t t = time(NULL);
if (t > lastHeartbeat + 1) {
send(streamSock, (const char*)packet, packet->size, 0);
lastHeartbeat = time(nullptr);
}
tv.tv_sec = 0;
tv.tv_usec = 500000; // 0.5s = 2Hz
int ret = select((int)(streamSock+1), &reader, NULL, NULL, &tv);
if (ret == -1) { // error
lastErrorMessage = "Error waiting for stream socket";
return 0;
}
if (ret == 0) {
lastErrorMessage = "Stream timed out";
continue;
}
int64_t to;
atomicLoad(&timeOffset, &to);
dataAvailableTime = getTime() + to;
char buf[10000];
CapturyPosePacket* cpp = (CapturyPosePacket*)&buf[0];
// first peek to find out which packet type this is
int size = recv(streamSock, buf, sizeof(buf), 0);
// printf("received stream packet size %d (%d %d)\n", (int) size, cpp->type, cpp->size);
if (size == 0) { // the other end shut down the socket...
lastErrorMessage = "Stream socket closed unexpectedly";
continue;
}
if (size == -1) { // error
char buff[200];
#ifdef WIN32
sprintf(buff, "Stream socket error: %d", WSAGetLastError());
#else
sprintf(buff, "Stream socket error: %s", strerror(errno));
#endif
lastErrorMessage = buff;