-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAppRuntime.cpp
More file actions
2152 lines (1912 loc) · 88.3 KB
/
AppRuntime.cpp
File metadata and controls
2152 lines (1912 loc) · 88.3 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
#include "AppRuntime.hpp"
#include "AxVencH264Encoder.hpp"
#include "AppTopics.hpp"
#include "AxVoDisplay.hpp"
#include "LaserRangefinder.hpp"
#include "ax_stereo_depth_api.h"
#define SAMPLE_LOG_TAG "RUNTIME"
#include "sample_log.h"
#include <foxglove/mcap.hpp>
#include <sys/select.h>
#include <termios.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <csignal>
#include <cstddef>
#include <cstring>
#include <ctime>
#include <deque>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
using stereo_depth::axera_pipeline::AxVoDisplay;
namespace stereo_depth::app {
namespace {
enum class KeyboardInputAction {
None,
ToggleRecord,
SingleFrameDump,
PrevImportedFrame,
NextImportedFrame,
};
constexpr uint64_t kMinReadyFramesBeforeCaptureActions = 15;
constexpr uint64_t kMaxMcapFileSizeBytes = 512ULL * 1024ULL * 1024ULL;
constexpr int kKeyboardEscapeReadTimeoutUs = 2000;
constexpr size_t kMaxKeyboardEscapeSequenceLength = 16;
bool readByteWithTimeout(int fd, char& ch, int timeoutUs) {
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(fd, &readSet);
timeval timeout;
timeout.tv_sec = timeoutUs / 1000000;
timeout.tv_usec = timeoutUs % 1000000;
const int ready = ::select(fd + 1, &readSet, nullptr, nullptr, &timeout);
if (ready <= 0) {
return false;
}
return ::read(fd, &ch, 1) == 1;
}
std::string readKeyboardEscapeSequence(int fd) {
std::string sequence;
sequence.reserve(kMaxKeyboardEscapeSequenceLength);
while (sequence.size() < kMaxKeyboardEscapeSequenceLength) {
char ch = 0;
if (!readByteWithTimeout(fd, ch, kKeyboardEscapeReadTimeoutUs)) {
break;
}
sequence.push_back(ch);
if (std::isalpha(static_cast<unsigned char>(ch)) || ch == '~') {
break;
}
}
return sequence;
}
KeyboardInputAction parseKeyboardEscapeSequence(const std::string& sequence) {
if (sequence.size() < 2) {
return KeyboardInputAction::None;
}
if (sequence[0] != '[') {
return KeyboardInputAction::None;
}
const char finalChar = sequence.back();
if (finalChar == 'D') {
return KeyboardInputAction::PrevImportedFrame;
}
if (finalChar == 'C') {
return KeyboardInputAction::NextImportedFrame;
}
return KeyboardInputAction::None;
}
KeyboardInputAction readKeyboardInputAction() {
char ch = 0;
const ssize_t n = ::read(STDIN_FILENO, &ch, 1);
if (n <= 0) {
return KeyboardInputAction::None;
}
if (ch == 'r' || ch == 'R') {
return KeyboardInputAction::ToggleRecord;
}
if (ch == 'd' || ch == 'D') {
return KeyboardInputAction::SingleFrameDump;
}
if (ch != '\x1b') {
return KeyboardInputAction::None;
}
return parseKeyboardEscapeSequence(readKeyboardEscapeSequence(STDIN_FILENO));
}
struct FramePacket {
uint64_t frameTimestampNs = 0;
uint64_t captureSteadyNs = 0;
LaserDistanceSample laserDistance;
stereo_depth::InputFrameFormat format = stereo_depth::InputFrameFormat::Yuyv;
AX_VIDEO_FRAME_T externalFrame = {};
std::shared_ptr<void> externalFrameOwner;
std::vector<std::byte> data;
};
struct StereoOutputOwner {
AX_STEREO_OUTPUT_T stereoOutput = {};
stereo_depth::PipelineOutput* data() { return AX_STEREO_OutputGetData(&stereoOutput); }
const stereo_depth::PipelineOutput* data() const {
return const_cast<StereoOutputOwner*>(this)->data();
}
~StereoOutputOwner() {
if (stereoOutput.pPrivateData) {
AX_STEREO_ReleaseOutput(&stereoOutput);
}
}
StereoOutputOwner() = default;
StereoOutputOwner(const StereoOutputOwner&) = delete;
StereoOutputOwner& operator=(const StereoOutputOwner&) = delete;
StereoOutputOwner(StereoOutputOwner&& o) noexcept : stereoOutput(o.stereoOutput) {
o.stereoOutput = {};
}
StereoOutputOwner& operator=(StereoOutputOwner&& o) noexcept {
if (this != &o) {
if (stereoOutput.pPrivateData) AX_STEREO_ReleaseOutput(&stereoOutput);
stereoOutput = o.stereoOutput;
o.stereoOutput = {};
}
return *this;
}
};
struct OutputPacket {
uint64_t captureSteadyNs = 0;
LaserDistanceSample laserDistance;
std::shared_ptr<StereoOutputOwner> output;
};
struct VoPacket {
std::shared_ptr<StereoOutputOwner> output;
};
struct ProcessStagePacket {
AX_STEREO_FRAME_CTX context = nullptr;
uint64_t captureSteadyNs = 0;
LaserDistanceSample laserDistance;
uint64_t preWaitInUs = 0;
uint64_t inferWaitInUs = 0;
uint64_t preprocessUs = 0;
uint64_t inferUs = 0;
size_t inQDepth = 0;
};
struct DumpTask {
std::shared_ptr<StereoOutputOwner> output;
LaserDistanceSample laserDistance;
TopicFlags dataFlags;
bool singleFrame = false;
bool recordH264 = false;
};
enum class H264RecordState {
Disabled,
Active,
Failed,
};
struct PerfAccum {
uint64_t frames = 0;
uint64_t samples = 0;
uint64_t dropped = 0;
uint64_t waitInUs = 0;
uint64_t workUs = 0;
uint64_t preWaitInUs = 0;
uint64_t inferWaitInUs = 0;
uint64_t postWaitInUs = 0;
uint64_t preUs = 0;
uint64_t inferUs = 0;
uint64_t postUs = 0;
uint64_t e2eUs = 0;
size_t qIn = 0;
size_t qOut = 0;
};
constexpr size_t kFrameQueueCapacity = 4;
constexpr size_t kOutputQueueCapacity = 4;
constexpr size_t kPreInferQueueCapacity = 1;
constexpr size_t kInferPostQueueCapacity = 4;
constexpr size_t kVoQueueCapacity = 2;
constexpr size_t kRecordQueueCapacity = 8;
constexpr int kDashboardInnerWidth = 51;
constexpr auto kImageFileInputFrameInterval = std::chrono::milliseconds(200);
enum class RuntimeLogKind {
Notice,
Record,
Dump,
};
constexpr const char* kAnsiReset = "\033[0m";
constexpr const char* kRuntimeNoticeColor = "\033[1;36m";
constexpr const char* kRuntimeRecordColor = "\033[1;35m";
constexpr const char* kRuntimeDumpColor = "\033[1;34m";
const char* runtimeLogColor(RuntimeLogKind kind) {
switch (kind) {
case RuntimeLogKind::Record:
return kRuntimeRecordColor;
case RuntimeLogKind::Dump:
return kRuntimeDumpColor;
case RuntimeLogKind::Notice:
default:
return kRuntimeNoticeColor;
}
}
std::string formatRuntimeLogLine(RuntimeLogKind kind, const std::string& msg) {
const char* kindStr = "NOTICE";
switch (kind) {
case RuntimeLogKind::Record:
kindStr = "RECORD";
break;
case RuntimeLogKind::Dump:
kindStr = "DUMP";
break;
case RuntimeLogKind::Notice:
default:
break;
}
std::ostringstream oss;
oss << runtimeLogColor(kind) << kindStr << ":[" << std::left << std::setw(SAMPLE_LOG_TAG_WIDTH)
<< SAMPLE_LOG_TAG << "] " << msg << kAnsiReset;
return oss.str();
}
uint64_t nowSteadyNs() {
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
}
std::string formatWallClockNs(uint64_t timeNs) {
const auto timePoint =
std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>(
std::chrono::nanoseconds(timeNs));
const auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(timePoint);
const auto subsecNs =
std::chrono::duration_cast<std::chrono::nanoseconds>(timePoint - seconds).count();
const std::time_t timeValue = std::chrono::system_clock::to_time_t(seconds);
std::tm localTm = {};
localtime_r(&timeValue, &localTm);
std::ostringstream oss;
oss << std::put_time(&localTm, "%Y-%m-%d %H:%M:%S") << '.' << std::setw(9) << std::setfill('0')
<< subsecNs;
return oss.str();
}
std::string formatDurationNs(uint64_t durationNs) {
std::ostringstream oss;
oss << std::fixed << std::setprecision(3) << (static_cast<double>(durationNs) / 1000000000.0)
<< "s";
return oss.str();
}
std::string formatByteSize(uintmax_t sizeBytes) {
static constexpr const char* kUnits[] = {"B", "KiB", "MiB", "GiB", "TiB"};
double size = static_cast<double>(sizeBytes);
size_t unitIndex = 0;
while (size >= 1024.0 && unitIndex < (sizeof(kUnits) / sizeof(kUnits[0])) - 1) {
size /= 1024.0;
++unitIndex;
}
std::ostringstream oss;
oss << std::fixed << std::setprecision(unitIndex == 0 ? 0 : 2) << size << kUnits[unitIndex];
return oss.str();
}
std::string sanitizePathComponent(const std::string& value) {
std::string sanitized;
sanitized.reserve(std::min<size_t>(value.size(), 64));
for (unsigned char ch : value) {
if (std::isalnum(ch) || ch == '-' || ch == '_') {
sanitized.push_back(static_cast<char>(ch));
} else {
sanitized.push_back('_');
}
if (sanitized.size() >= 64) {
break;
}
}
while (!sanitized.empty() && sanitized.back() == '_') {
sanitized.pop_back();
}
if (sanitized.empty()) {
sanitized = "unknown";
}
return sanitized;
}
uint64_t buildTimestampedOutputPath(const std::string& prefix, const std::string& fileTag,
const std::string& serialNumber, const std::string& extension,
std::string& path) {
const uint64_t nowNs =
static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
std::ostringstream oss;
oss << prefix;
if (!fileTag.empty()) {
oss << '_' << fileTag;
}
if (!serialNumber.empty()) {
const std::string safeSerial = sanitizePathComponent(serialNumber);
if (!safeSerial.empty()) {
oss << "_sn" << safeSerial;
}
}
oss << '_' << nowNs << extension;
path = oss.str();
return nowNs;
}
void buildSegmentedOutputPath(const std::string& prefix, const std::string& fileTag,
const std::string& serialNumber, uint64_t timestampNs,
uint32_t segmentIndex, const std::string& extension,
std::string& path) {
std::ostringstream oss;
oss << prefix;
if (!fileTag.empty()) {
oss << '_' << fileTag;
}
if (!serialNumber.empty()) {
const std::string safeSerial = sanitizePathComponent(serialNumber);
if (!safeSerial.empty()) {
oss << "_sn" << safeSerial;
}
}
oss << '_' << timestampNs;
if (segmentIndex > 0) {
oss << "_part" << std::setw(2) << std::setfill('0') << (segmentIndex + 1);
}
oss << extension;
path = oss.str();
}
uintmax_t getFileSizeBytes(const std::string& path) {
if (path.empty()) {
return 0;
}
std::error_code fileErr;
const uintmax_t fileSizeBytes = std::filesystem::file_size(path, fileErr);
return fileErr ? 0 : fileSizeBytes;
}
struct RoiRegionAverage {
const char* name = "";
uint32_t centerX = 0;
uint32_t centerY = 0;
uint32_t validSampleCount = 0;
double zAvgMeters = 0.0;
uint32_t confidenceSampleCount = 0;
double confidenceAvg = 0.0;
bool valid = false;
bool confidenceValid = false;
};
std::array<RoiRegionAverage, 9> computeRoiRegionAverages(const stereo_depth::PipelineOutput& output,
float focalLengthPixels,
float baselineMeters) {
std::array<RoiRegionAverage, 9> regions = {{
{"ROI-LT"},
{"ROI-MT"},
{"ROI-RT"},
{"ROI-LM"},
{"ROI-CT"},
{"ROI-RM"},
{"ROI-LD"},
{"ROI-MD"},
{"ROI-RD"},
}};
constexpr uint32_t kWindowRadius = 5;
constexpr uint32_t kDisparityScale = 16;
const size_t expectedBytes = static_cast<size_t>(AX_STEREO_DEWARP_IMAGE_WIDTH) *
static_cast<size_t>(AX_STEREO_DEWARP_IMAGE_HEIGHT) *
sizeof(uint16_t);
if (output.depthData.size() < expectedBytes) {
return regions;
}
const auto* disparityFixed = reinterpret_cast<const uint16_t*>(output.depthData.data());
const size_t expectedConfidenceBytes = static_cast<size_t>(AX_STEREO_DEWARP_IMAGE_WIDTH) *
static_cast<size_t>(AX_STEREO_DEWARP_IMAGE_HEIGHT) *
sizeof(float);
const auto* confidenceValues =
output.confidenceData.size() >= expectedConfidenceBytes
? reinterpret_cast<const float*>(output.confidenceData.data())
: nullptr;
const double zScale =
static_cast<double>(focalLengthPixels) * static_cast<double>(baselineMeters);
static constexpr const uint32_t kRoiOrder[9][2] = {
{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2},
};
static constexpr uint32_t kRoiX[3] = {180, 320, 460};
static constexpr uint32_t kRoiY[3] = {96, 192, 288};
for (size_t i = 0; i < regions.size(); ++i) {
const uint32_t gridX = kRoiOrder[i][0];
const uint32_t gridY = kRoiOrder[i][1];
RoiRegionAverage& region = regions[i];
region.centerX = kRoiX[gridX];
region.centerY = kRoiY[gridY];
const uint32_t xBegin =
region.centerX > kWindowRadius ? (region.centerX - kWindowRadius) : 0;
const uint32_t xEnd =
std::min<uint32_t>(AX_STEREO_DEWARP_IMAGE_WIDTH - 1, region.centerX + kWindowRadius);
const uint32_t yBegin =
region.centerY > kWindowRadius ? (region.centerY - kWindowRadius) : 0;
const uint32_t yEnd =
std::min<uint32_t>(AX_STEREO_DEWARP_IMAGE_HEIGHT - 1, region.centerY + kWindowRadius);
double sumZ = 0.0;
double confidenceSum = 0.0;
uint32_t validCount = 0;
uint32_t confidenceCount = 0;
for (uint32_t y = yBegin; y <= yEnd; ++y) {
const size_t rowBase = static_cast<size_t>(y) * AX_STEREO_DEWARP_IMAGE_WIDTH;
for (uint32_t x = xBegin; x <= xEnd; ++x) {
if (confidenceValues != nullptr) {
const float confidenceValue = confidenceValues[rowBase + x];
if (std::isfinite(confidenceValue)) {
confidenceSum += static_cast<double>(confidenceValue);
++confidenceCount;
}
}
const uint16_t disparityValue = disparityFixed[rowBase + x];
if (disparityValue == 0) {
continue;
}
const double disparity =
static_cast<double>(disparityValue) / static_cast<double>(kDisparityScale);
if (disparity <= 0.0) {
continue;
}
sumZ += zScale / disparity;
++validCount;
}
}
region.validSampleCount = validCount;
region.valid = validCount > 0;
if (region.valid) {
region.zAvgMeters = sumZ / static_cast<double>(validCount);
}
region.confidenceSampleCount = confidenceCount;
region.confidenceValid = confidenceCount > 0;
if (region.confidenceValid) {
region.confidenceAvg = confidenceSum / static_cast<double>(confidenceCount);
}
}
return regions;
}
std::vector<std::byte> makeRoiRegionAveragesJson(const stereo_depth::PipelineOutput& output,
float focalLengthPixels, float baselineMeters,
const LaserDistanceSample& laserDistance) {
const auto regions = computeRoiRegionAverages(output, focalLengthPixels, baselineMeters);
std::ostringstream oss;
oss << '{';
oss << "\"frame_timestamp_ns\":" << output.frameTimestampNs << ',';
oss << "\"items\":[";
oss << '{';
oss << "\"name\":\"laser_distance_mm\",";
oss << "\"z_avg_mm\":";
if (laserDistance.valid()) {
oss << laserDistance.distanceMm;
} else {
oss << "null";
}
oss << '}';
for (size_t i = 0; i < regions.size(); ++i) {
const RoiRegionAverage& region = regions[i];
oss << ',';
oss << '{';
oss << "\"name\":\"" << region.name << '[' << region.centerX << ',' << region.centerY
<< "]\",";
oss << "\"z_avg_mm\":";
if (region.valid) {
oss << std::fixed << std::setprecision(3) << (region.zAvgMeters * 1000.0);
} else {
oss << "null";
}
oss << ",\"confidence_avg\":";
if (region.confidenceValid) {
oss << std::fixed << std::setprecision(6) << region.confidenceAvg;
} else {
oss << "null";
}
oss << '}';
}
oss << "]}";
const std::string json = oss.str();
std::vector<std::byte> payload(json.size());
std::memcpy(payload.data(), json.data(), json.size());
return payload;
}
std::string formatDashboardRow(const std::string& stage, double fps, double waitInMs, double workMs,
uint64_t dropped) {
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << "| " << std::left << std::setw(5) << stage << " | "
<< std::right << std::setw(8) << fps << " | " << std::setw(10) << waitInMs << " | "
<< std::setw(9) << workMs << " | " << std::setw(7) << dropped << " |";
return oss.str();
}
std::string formatMetricLine(const std::string& text) {
std::ostringstream oss;
oss << "| " << std::left << std::setw(kDashboardInnerWidth) << text << " |";
return oss.str();
}
std::optional<uint64_t> readProcessRssKb() {
std::ifstream statusFile("/proc/self/status");
if (!statusFile.is_open()) {
return std::nullopt;
}
std::string line;
while (std::getline(statusFile, line)) {
if (line.rfind("VmRSS:", 0) != 0) {
continue;
}
std::istringstream iss(line.substr(std::strlen("VmRSS:")));
uint64_t rssKb = 0;
if (iss >> rssKb) {
return rssKb;
}
break;
}
return std::nullopt;
}
void notifyAll(std::condition_variable& frameQueueNotEmptyCv,
std::condition_variable& frameQueueNotFullCv,
std::condition_variable& preInferQueueNotEmptyCv,
std::condition_variable& preInferQueueNotFullCv,
std::condition_variable& inferPostQueueNotEmptyCv,
std::condition_variable& inferPostQueueNotFullCv,
std::condition_variable& outputQueueNotEmptyCv,
std::condition_variable& outputQueueNotFullCv,
std::condition_variable& voQueueNotEmptyCv) {
frameQueueNotEmptyCv.notify_all();
frameQueueNotFullCv.notify_all();
preInferQueueNotEmptyCv.notify_all();
preInferQueueNotFullCv.notify_all();
inferPostQueueNotEmptyCv.notify_all();
inferPostQueueNotFullCv.notify_all();
outputQueueNotEmptyCv.notify_all();
outputQueueNotFullCv.notify_all();
voQueueNotEmptyCv.notify_all();
}
} // namespace
StereoDepthAppRuntime::StereoDepthAppRuntime(const RuntimeOptions& options,
AX_STEREO_HANDLE hPipeline,
stereo_depth::FrameInputSource& inputSource,
FoxgloveWrapper& foxglove)
: m_options(options),
m_hPipeline(hPipeline),
m_inputSource(inputSource),
m_foxglove(foxglove) {}
int StereoDepthAppRuntime::run(std::atomic<bool>& running) {
StereoDepthTopics topics;
if (!topics.registerFoxgloveChannels(m_foxglove)) {
return 1;
}
const auto& inputInfo = m_inputSource.info();
topics.publishDeviceInfoToFoxglove(m_foxglove, inputInfo);
const bool perfTrace = m_options.perfTrace;
const bool perfTraceTty = perfTrace && (::isatty(STDOUT_FILENO) != 0);
std::ostringstream keyboardHelp;
keyboardHelp
<< "Keyboard: 'r' toggles MCAP recording with H.264, first 'd' starts continuous H.264 "
"recording and every 'd' saves a single-frame MCAP snapshot with raw YUYV";
if (m_inputSource.supportsImportedFrameSelection()) {
const auto selection = m_inputSource.importedFrameSelection();
keyboardHelp << ", Left/Right selects previous/next imported "
<< m_inputSource.importedFrameSourceName() << " frame (default 1/"
<< selection.count << ')';
}
ALOGN("%s", keyboardHelp.str().c_str());
std::mutex perfLogMutex;
std::mutex dumpLogMutex;
std::deque<std::string> dumpLogs;
std::mutex foxglovePublishMutex;
std::unique_ptr<AxVoDisplay> voDisplay;
if (m_options.enableVo) {
voDisplay = std::make_unique<AxVoDisplay>();
if (!voDisplay->start()) {
ALOGE("failed to initialize VO HDMI output");
return 1;
}
}
AxVoDisplay* const voDisplayPtr = voDisplay.get();
const bool voEnabled = (voDisplayPtr != nullptr);
auto appendRuntimeLog = [&](RuntimeLogKind kind, const std::string& msg) {
const std::string formattedMsg = formatRuntimeLogLine(kind, msg);
std::lock_guard<std::mutex> lock(dumpLogMutex);
dumpLogs.push_back(formattedMsg);
if (!perfTrace) {
std::cout << formattedMsg << std::endl;
}
};
auto appendRecordLog = [&](const std::string& msg) {
appendRuntimeLog(RuntimeLogKind::Record, msg);
};
auto appendSingleDumpLog = [&](const std::string& msg) {
appendRuntimeLog(RuntimeLogKind::Dump, msg);
};
std::mutex perfAccumMutex;
PerfAccum capPerf;
PerfAccum procPerf;
PerfAccum pubPerf;
PerfAccum voPerf;
PerfAccum dumpPerf;
std::atomic<uint64_t> droppedFrameQueue{0};
std::atomic<uint64_t> droppedPreInferQueue{0};
std::atomic<uint64_t> droppedInferPostQueue{0};
std::atomic<uint64_t> droppedOutputQueue{0};
std::atomic<uint64_t> droppedVoQueue{0};
std::atomic<uint64_t> droppedDumpQueue{0};
std::atomic<size_t> maxFrameQueueDepth{0};
std::atomic<size_t> maxPreInferQueueDepth{0};
std::atomic<size_t> maxInferPostQueueDepth{0};
std::atomic<size_t> maxOutputQueueDepth{0};
std::atomic<size_t> maxVoQueueDepth{0};
std::atomic<size_t> maxDumpQueueDepth{0};
auto updateMaxDepth = [](std::atomic<size_t>& target, size_t value) {
size_t current = target.load(std::memory_order_relaxed);
while (current < value &&
!target.compare_exchange_weak(current, value, std::memory_order_relaxed,
std::memory_order_relaxed)) {
}
};
std::atomic<bool> perfMonitorStop{false};
std::thread perfMonitorThread;
if (perfTrace) {
perfMonitorThread = std::thread([&]() {
auto lastReportTime = std::chrono::steady_clock::now();
bool firstRender = true;
bool cursorHidden = false;
size_t renderedDumpCount = 0;
size_t renderedDashboardLineCount = 0;
const std::string staticTitleLine = "[perf] StereoDepth Dashboard (window=1s)";
while (!perfMonitorStop.load()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
if (perfMonitorStop.load()) {
break;
}
const auto now = std::chrono::steady_clock::now();
const auto elapsedMs =
std::chrono::duration_cast<std::chrono::milliseconds>(now - lastReportTime)
.count();
if (elapsedMs <= 0) {
continue;
}
PerfAccum capSnapshot;
PerfAccum procSnapshot;
PerfAccum pubSnapshot;
PerfAccum voSnapshot;
PerfAccum dumpSnapshot;
{
std::lock_guard<std::mutex> lock(perfAccumMutex);
capSnapshot = capPerf;
procSnapshot = procPerf;
pubSnapshot = pubPerf;
voSnapshot = voPerf;
dumpSnapshot = dumpPerf;
capPerf = PerfAccum{};
procPerf = PerfAccum{};
pubPerf = PerfAccum{};
voPerf = PerfAccum{};
dumpPerf = PerfAccum{};
}
auto toFps = [&](uint64_t frames) {
return static_cast<double>(frames) * 1000.0 / static_cast<double>(elapsedMs);
};
auto toAvgMs = [](uint64_t totalUs, uint64_t frames) {
return frames > 0
? static_cast<double>(totalUs) / 1000.0 / static_cast<double>(frames)
: 0.0;
};
const double procPreWaitInMs =
toAvgMs(procSnapshot.preWaitInUs, procSnapshot.frames);
const double procInferWaitInMs =
toAvgMs(procSnapshot.inferWaitInUs, procSnapshot.frames);
const double procPostWaitInMs =
toAvgMs(procSnapshot.postWaitInUs, procSnapshot.frames);
const double procPreMs = toAvgMs(procSnapshot.preUs, procSnapshot.frames);
const double procInferMs = toAvgMs(procSnapshot.inferUs, procSnapshot.frames);
const double procPostMs = toAvgMs(procSnapshot.postUs, procSnapshot.frames);
const double pubE2eMs = toAvgMs(pubSnapshot.e2eUs, pubSnapshot.frames);
const uint64_t frameDrop = droppedFrameQueue.exchange(0);
const uint64_t preInferDrop = droppedPreInferQueue.exchange(0);
const uint64_t inferPostDrop = droppedInferPostQueue.exchange(0);
const uint64_t outputDrop = droppedOutputQueue.exchange(0);
const uint64_t voDrop = droppedVoQueue.exchange(0);
const uint64_t dumpDrop = droppedDumpQueue.exchange(0);
const size_t frameDepthMax = maxFrameQueueDepth.exchange(0);
const size_t preInferDepthMax = maxPreInferQueueDepth.exchange(0);
const size_t inferPostDepthMax = maxInferPostQueueDepth.exchange(0);
const size_t outputDepthMax = maxOutputQueueDepth.exchange(0);
const size_t voDepthMax = maxVoQueueDepth.exchange(0);
const size_t dumpDepthMax = maxDumpQueueDepth.exchange(0);
const FoxgloveWrapper::SubscriberStats subStats = m_foxglove.getSubscriberStats();
std::ostringstream titleStream;
titleStream << "subs_total=" << subStats.total
<< " rgb=" << m_foxglove.getSubscriberCount(topics.rgbTopic())
<< " depth=" << m_foxglove.getSubscriberCount(topics.depthTopic())
<< " gridavg=" << m_foxglove.getSubscriberCount(topics.gridAvgTopic())
<< " cloud=" << m_foxglove.getSubscriberCount(topics.cloudTopic())
<< " grid=" << m_foxglove.getSubscriberCount(topics.gridTopic());
const std::string dynamicTitleLine = titleStream.str();
const std::string splitLine =
"+-------+----------+------------+-----------+---------+";
const std::string headerLine =
"| stage | fps | wait_in_ms | work_ms | dropped |";
const std::string capLine =
formatDashboardRow("cap", toFps(capSnapshot.frames),
toAvgMs(capSnapshot.waitInUs, capSnapshot.frames),
toAvgMs(capSnapshot.workUs, capSnapshot.frames), frameDrop);
const std::string preLine = formatDashboardRow(
"pre", toFps(procSnapshot.frames), procPreWaitInMs, procPreMs, preInferDrop);
const std::string inferLine =
formatDashboardRow("infer", toFps(procSnapshot.frames), procInferWaitInMs,
procInferMs, inferPostDrop);
const std::string postLine = formatDashboardRow(
"post", toFps(procSnapshot.frames), procPostWaitInMs, procPostMs, outputDrop);
const std::string pubLine = formatDashboardRow(
"pub", toFps(pubSnapshot.frames),
toAvgMs(pubSnapshot.waitInUs, pubSnapshot.samples),
toAvgMs(pubSnapshot.workUs, pubSnapshot.samples), pubSnapshot.dropped);
const std::string voLine =
formatDashboardRow("vo", toFps(voSnapshot.frames),
toAvgMs(voSnapshot.waitInUs, voSnapshot.samples),
toAvgMs(voSnapshot.workUs, voSnapshot.samples), voDrop);
const std::string dumpLine =
formatDashboardRow("dump", toFps(dumpSnapshot.frames),
toAvgMs(dumpSnapshot.waitInUs, dumpSnapshot.samples),
toAvgMs(dumpSnapshot.workUs, dumpSnapshot.frames), dumpDrop);
std::ostringstream latencyLineStream;
latencyLineStream << std::fixed << std::setprecision(2) << "e2e_ms=" << pubE2eMs;
const std::optional<uint64_t> rssKb = readProcessRssKb();
if (rssKb.has_value()) {
latencyLineStream << " rss_mb=" << (static_cast<double>(*rssKb) / 1024.0);
} else {
latencyLineStream << " rss_mb=n/a";
}
const std::string latencyLine = formatMetricLine(latencyLineStream.str());
std::ostringstream depthLineStream;
depthLineStream << "qmax frame=" << frameDepthMax
<< " preinfer=" << preInferDepthMax
<< " inferpost=" << inferPostDepthMax
<< " output=" << outputDepthMax << " vo=" << voDepthMax
<< " dump=" << dumpDepthMax;
const std::string depthLine = formatMetricLine(depthLineStream.str());
std::vector<std::string> dumpLogSnapshot;
{
std::lock_guard<std::mutex> dumpLock(dumpLogMutex);
dumpLogSnapshot.assign(dumpLogs.begin(), dumpLogs.end());
}
std::vector<std::string> dashboardLines;
dashboardLines.push_back(staticTitleLine);
dashboardLines.push_back(dynamicTitleLine);
dashboardLines.push_back(splitLine);
dashboardLines.push_back(headerLine);
dashboardLines.push_back(splitLine);
dashboardLines.push_back(capLine);
dashboardLines.push_back(preLine);
dashboardLines.push_back(inferLine);
dashboardLines.push_back(postLine);
dashboardLines.push_back(pubLine);
dashboardLines.push_back(voLine);
dashboardLines.push_back(dumpLine);
dashboardLines.push_back(latencyLine);
dashboardLines.push_back(depthLine);
dashboardLines.push_back(splitLine);
std::lock_guard<std::mutex> lock(perfLogMutex);
if (perfTraceTty) {
if (!cursorHidden) {
std::cout << "\033[?25l";
cursorHidden = true;
}
if (!firstRender && renderedDashboardLineCount > 0) {
std::cout << "\033[" << renderedDashboardLineCount << "F";
for (size_t i = 0; i < renderedDashboardLineCount; ++i) {
std::cout << "\r\033[2K";
if (i + 1 < renderedDashboardLineCount) {
std::cout << "\n";
}
}
if (renderedDashboardLineCount > 1) {
std::cout << "\033[" << (renderedDashboardLineCount - 1) << "F";
}
std::cout << "\r";
}
if (dumpLogSnapshot.size() > renderedDumpCount) {
for (size_t i = renderedDumpCount; i < dumpLogSnapshot.size(); ++i) {
std::cout << "\r\033[2K" << dumpLogSnapshot[i] << "\n";
}
renderedDumpCount = dumpLogSnapshot.size();
}
for (const auto& line : dashboardLines) {
std::cout << "\r\033[2K" << line << "\n";
}
renderedDashboardLineCount = dashboardLines.size();
std::cout << std::flush;
} else {
if (dumpLogSnapshot.size() > renderedDumpCount) {
for (size_t i = renderedDumpCount; i < dumpLogSnapshot.size(); ++i) {
std::cout << dumpLogSnapshot[i] << std::endl;
}
renderedDumpCount = dumpLogSnapshot.size();
}
for (const auto& line : dashboardLines) {
std::cout << line << std::endl;
}
}
firstRender = false;
lastReportTime = now;
}
std::lock_guard<std::mutex> lock(perfLogMutex);
if (perfTraceTty && cursorHidden) {
std::cout << "\033[?25h" << std::flush;
}
});
}
std::atomic<bool> recording{false};
std::atomic<bool> singleFrameDumpRequested{false};
std::atomic<uint64_t> processedOutputFrameCount{0};
std::atomic<bool> inputThreadStop{false};
std::thread inputThread;
struct termios originalStdinTermios {};
bool stdinRawModeEnabled = false;
const bool stdinIsTty = (::isatty(STDIN_FILENO) != 0);
if (stdinIsTty) {
if (::tcgetattr(STDIN_FILENO, &originalStdinTermios) == 0) {
struct termios raw = originalStdinTermios;
raw.c_lflag &= static_cast<tcflag_t>(~(ICANON | ECHO));
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 0;
if (::tcsetattr(STDIN_FILENO, TCSANOW, &raw) == 0) {
stdinRawModeEnabled = true;
inputThread = std::thread([&]() {
while (running && !inputThreadStop.load()) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 200000;
const int rv =
::select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, &timeout);
if (rv <= 0 || !FD_ISSET(STDIN_FILENO, &readfds)) {
continue;
}
const KeyboardInputAction action = readKeyboardInputAction();
if (action == KeyboardInputAction::None) {
continue;
}
if (action == KeyboardInputAction::ToggleRecord) {
const bool prev = recording.load(std::memory_order_acquire);
if (!prev && processedOutputFrameCount.load(std::memory_order_acquire) <
kMinReadyFramesBeforeCaptureActions) {
std::ostringstream oss;
oss << "recording start ignored: pipeline is still warming up ("
<< processedOutputFrameCount.load(std::memory_order_acquire)
<< '/' << kMinReadyFramesBeforeCaptureActions
<< " ready frames)";
appendRecordLog(oss.str());
continue;
}
recording.store(!prev, std::memory_order_release);
} else if (action == KeyboardInputAction::SingleFrameDump) {
if (processedOutputFrameCount.load(std::memory_order_acquire) <
kMinReadyFramesBeforeCaptureActions) {
std::ostringstream oss;
oss << "single-frame dump ignored: pipeline is still warming up "
"("
<< processedOutputFrameCount.load(std::memory_order_acquire)
<< '/' << kMinReadyFramesBeforeCaptureActions
<< " ready frames)";
appendSingleDumpLog(oss.str());
continue;
}
singleFrameDumpRequested.store(true, std::memory_order_release);
} else if (action == KeyboardInputAction::PrevImportedFrame ||
action == KeyboardInputAction::NextImportedFrame) {
if (!m_inputSource.supportsImportedFrameSelection()) {
continue;
}
FrameInputSource::ImportedFrameSelection selection;
const bool switched = m_inputSource.stepImportedFrame(
action == KeyboardInputAction::NextImportedFrame ? 1 : -1,
selection);
std::ostringstream oss;