-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathalink_drone.c
1833 lines (1543 loc) · 62.4 KB
/
alink_drone.c
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 <stdio.h> // For printf, perror
#include <stdlib.h> // For malloc, free, atoi
#include <string.h> // For strtok, strdup
#include <unistd.h> // For usleep
#include <pthread.h> // For pthread functions
#include <sys/socket.h> // For socket functions
#include <netinet/in.h> // For sockaddr_in
#include <arpa/inet.h> // For inet_pton
#include <stdbool.h> // For bool, true, false
#include <sys/time.h> // For timeval, settimeofday
#include <sys/wait.h> // For waitpid
#include <time.h> // For timespec, clock_gettime
#include <math.h>
#include <ctype.h>
#include <limits.h>
#define MAX_COMMAND_SIZE 256
#define BUFFER_SIZE 1024
#define DEFAULT_PORT 9999
#define DEFAULT_IP "10.5.0.10"
#define CONFIG_FILE "/etc/alink.conf"
#define PROFILE_FILE "/etc/txprofiles.conf"
#define MAX_PROFILES 20
#define DEFAULT_PACE_EXEC_MS 50
#define min(a, b) ((a) < (b) ? (a) : (b))
// Profile struct
typedef struct {
int rangeMin;
int rangeMax;
char setGI[10];
int setMCS;
int setFecK;
int setFecN;
int setBitrate;
float setGop;
int wfbPower;
char ROIqp[20];
int bandwidth;
int setQpDelta;
} Profile;
Profile profiles[MAX_PROFILES];
// osd2udp struct
typedef struct {
int udp_out_sock;
char udp_out_ip[INET_ADDRSTRLEN];
int udp_out_port;
} osd_udp_config_t;
// OSD strings
char global_profile_osd[48] = "initializing...";
char global_profile_fec_osd[16] = "0/0";
char global_regular_osd[64] = "&L%d0&F%d&B &C tx&Wc";
char global_gs_stats_osd[64] = "waiting for gs.";
char global_extra_stats_osd[256] = "initializing...";
char global_score_related_osd[64] = "initializing...";
int osd_level = 4;
int x_res = 1920;
int y_res = 1080;
int global_fps = 120;
int total_pixels = 2073600;
int set_osd_font_size = 20;
int set_osd_colour = 7;
float multiply_font_size_by = 0.5;
int num_antennas = 0;
int num_antennas_drone = 0;
int noise_pnlty = 0;
int fec_change = 0;
int prev_fec_change = 0;
int prevWfbPower = -1;
float prevSetGop = -1.0;
int prevBandwidth = -20;
char prevSetGI[10] = "-1";
int prevSetMCS = -1;
char prevROIqp[20] = "-1";
int prevSetFecK = -1;
int prevSetFecN = -1;
int prevSetBitrate = -1;
int prevDivideFpsBy = -1;
int prevFPS = -1;
int prevQpDelta = -100;
int old_bitrate = -1;
int old_fec_k = -1;
int old_fec_n = -1;
int tx_factor = 50; // Default tx power factor 50 (most cards)
int ldpc_tx = 1;
int stbc = 1;
long pace_exec = DEFAULT_PACE_EXEC_MS * 1000L;
int currentProfile = -1;
int previousProfile = -2;
long prevTimeStamp = 0;
bool allow_set_power = 1;
float rssi_weight = 0.5;
float snr_weight = 0.5;
int hold_fallback_mode_s = 2;
int hold_modes_down_s = 2;
int min_between_changes_ms = 100;
int request_keyframe_interval_ms = 50;
bool allow_request_keyframe = 1;
bool allow_rq_kf_by_tx_d = 1;
int check_xtx_period_ms = 500;
int hysteresis_percent = 15;
int hysteresis_percent_down = 5;
int baseline_value = 100;
float smoothing_factor = 0.5;
float smoothing_factor_down = 0.8;
float smoothed_combined_value = 1500;
bool limitFPS = 1;
bool get_card_info_from_yaml = false;
bool allow_dynamic_fec = 1;
bool fec_k_adjust = 0;
int fallback_ms = 1000;
bool idr_every_change = false;
bool roi_focus_mode = false;
char fpsCommandTemplate[150], powerCommandTemplate[100], qpDeltaCommandTemplate[150], mcsCommandTemplate[100], bitrateCommandTemplate[150], gopCommandTemplate[100], fecCommandTemplate[100], roiCommandTemplate[150], idrCommandTemplate[100];
bool verbose_mode = false;
bool selection_busy = false;
bool initialized_by_first_message = false;
int message_count = 0; // Global variable for message count
bool paused = false; // Global variable for pause state
bool time_synced = false; // Global flag to indicate if time has been synced
int last_value_sent = 100;
struct timespec last_exec_time;
struct timespec last_keyframe_request_time; // Last keyframe request command
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; // Mutex for message count
pthread_mutex_t pause_mutex = PTHREAD_MUTEX_INITIALIZER; // Mutex for pause state
#define MAX_CODES 5 // Maximum number of unique keyframe requests to track
#define CODE_LENGTH 8 // Max length of each unique code
#define EXPIRY_TIME_MS 1000 // Code expiry time in milliseconds
int total_keyframe_requests = 0;
int total_keyframe_requests_xtx = 0;
long global_total_tx_dropped = 0;
volatile int weak_antenna_detected = 0;
// monitor drone antenna rssi
void *parse_rssi_thread(void *arg) {
const char *FIFO_PATH = "/tmp/wfb_rx.log";
const int MAX_LINE = 512;
const int NUM_ANTENNAS = 4; //max
const int HISTORY_SIZE = 20;
const int RSSI_THRESHOLD = 20; // to trigger flag
FILE *fp = fopen(FIFO_PATH, "r");
if (!fp) {
perror("Failed to open FIFO, not tracking local wfb_rx tunnel stats\nIf you want to track these, add the logic to your wifibroadcast script");
pthread_exit(NULL);
}
int rssi_history[NUM_ANTENNAS][HISTORY_SIZE];
int rssi_index[NUM_ANTENNAS];
int rssi_avg[NUM_ANTENNAS];
int rssi_count[NUM_ANTENNAS];
// Initialize arrays
for (int i = 0; i < NUM_ANTENNAS; i++) {
rssi_index[i] = 0;
rssi_avg[i] = 0;
rssi_count[i] = 0;
for (int j = 0; j < HISTORY_SIZE; j++) {
rssi_history[i][j] = 0;
}
}
char line[MAX_LINE];
while (fgets(line, sizeof(line), fp)) {
if (strstr(line, "RX_ANT")) {
char freq_mcs_band[64], colon_values[128];
int antenna, timestamp;
if (sscanf(line, "%d RX_ANT %63s %d %127[^\n]", ×tamp, freq_mcs_band, &antenna, colon_values) == 4) {
if (antenna < 0 || antenna >= NUM_ANTENNAS) continue; // Ignore invalid antennas
if (antenna >= num_antennas_drone) {
num_antennas_drone = antenna + 1; // Update global
}
char *token;
int token_count = 0, rssi = 0;
token = strtok(colon_values, ":");
while (token) {
if (++token_count == 3) { // RSSI is the third field
rssi = atoi(token);
break;
}
token = strtok(NULL, ":");
}
// Store RSSI in history buffer
rssi_history[antenna][rssi_index[antenna] % HISTORY_SIZE] = rssi;
rssi_index[antenna]++;
rssi_count[antenna]++;
// Compute moving average
int sum = 0, count = rssi_count[antenna] < HISTORY_SIZE ? rssi_count[antenna] : HISTORY_SIZE;
for (int i = 0; i < count; i++) {
sum += rssi_history[antenna][i];
}
rssi_avg[antenna] = sum / count;
// Detect weak antenna
int min_rssi = INT_MAX, max_rssi = INT_MIN;
for (int i = 0; i < NUM_ANTENNAS; i++) {
if (rssi_count[i] > 0) {
if (rssi_avg[i] < min_rssi) min_rssi = rssi_avg[i];
if (rssi_avg[i] > max_rssi) max_rssi = rssi_avg[i];
}
}
if (max_rssi - min_rssi >= RSSI_THRESHOLD) {
weak_antenna_detected = 1;
} else {
weak_antenna_detected = 0;
}
}
}
}
fclose(fp);
pthread_exit(NULL);
}
void error_to_osd(const char *message) {
const char *prefix = "&L50&F30 ";
char full_message[128];
snprintf(full_message, sizeof(full_message), "%s%s", prefix, message);
FILE *file = fopen("/tmp/MSPOSD.msg", "w");
if (file == NULL) {
perror("Error opening /tmp/MSPOSD.msg");
return;
}
if (fwrite(full_message, sizeof(char), strlen(full_message), file) != strlen(full_message)) {
perror("Error writing to /tmp/MSPOSD.msg");
}
fclose(file);
}
// Struct to store each keyframe request code and its timestamp
typedef struct {
char code[CODE_LENGTH];
struct timespec timestamp;
} KeyframeRequest;
// Static array of keyframe requests
static KeyframeRequest keyframe_request_codes[MAX_CODES];
static int num_keyframe_requests = 0; // Track the number of stored keyframe requests
long get_monotonic_time() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec;
}
int get_resolution() {
char resolution[32];
// Execute system command to get resolution
FILE *fp = popen("cli --get .video0.size", "r");
if (fp == NULL) {
printf("Failed to run get resolution command\n");
return 1;
}
if (fgets(resolution, sizeof(resolution) - 1, fp) == NULL) {
printf("fgets failed\n");
}
pclose(fp);
// Parse the resolution in the format <x_res>x<y_res>
if (sscanf(resolution, "%dx%d", &x_res, &y_res) != 2) {
printf("Failed to parse resolution\n");
return 1;
}
printf("Video Size: %dx%d\n", x_res, y_res);
return 0;
}
void load_config(const char* filename) {
FILE *file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Error: Could not open configuration file: %s\n", filename);
perror("");
error_to_osd("Adaptive-Link: Check/update /etc/alink.conf");
exit(EXIT_FAILURE);
}
char line[BUFFER_SIZE];
while (fgets(line, sizeof(line), file)) {
// Ignore comments (lines starting with '#')
if (line[0] == '#')
continue;
char *key = strtok(line, "=");
char *value = strtok(NULL, "\n");
if (key && value) {
if (strcmp(key, "allow_set_power") == 0) {
allow_set_power = atoi(value);
} else if (strcmp(key, "rssi_weight") == 0) {
rssi_weight = atof(value);
} else if (strcmp(key, "snr_weight") == 0) {
snr_weight = atof(value);
} else if (strcmp(key, "hold_fallback_mode_s") == 0) {
hold_fallback_mode_s = atoi(value);
} else if (strcmp(key, "hold_modes_down_s") == 0) {
hold_modes_down_s = atoi(value);
} else if (strcmp(key, "min_between_changes_ms") == 0) {
min_between_changes_ms = atoi(value);
} else if (strcmp(key, "request_keyframe_interval_ms") == 0) {
request_keyframe_interval_ms = atoi(value);
} else if (strcmp(key, "fallback_ms") == 0) {
fallback_ms = atoi(value);
} else if (strcmp(key, "idr_every_change") == 0) {
idr_every_change = atoi(value);
} else if (strcmp(key, "allow_request_keyframe") == 0) {
allow_request_keyframe = atoi(value);
} else if (strcmp(key, "get_card_info_from_yaml") == 0) {
get_card_info_from_yaml = atoi(value);
} else if (strcmp(key, "allow_dynamic_fec") == 0) {
allow_dynamic_fec = atoi(value);
} else if (strcmp(key, "fec_k_adjust") == 0) {
fec_k_adjust = atoi(value);
} else if (strcmp(key, "allow_rq_kf_by_tx_d") == 0) {
allow_rq_kf_by_tx_d = atoi(value);
} else if (strcmp(key, "hysteresis_percent") == 0) {
hysteresis_percent = atoi(value);
} else if (strcmp(key, "hysteresis_percent_down") == 0) {
hysteresis_percent_down = atoi(value);
} else if (strcmp(key, "exp_smoothing_factor") == 0) {
smoothing_factor = atof(value);
} else if (strcmp(key, "exp_smoothing_factor_down") == 0) {
smoothing_factor_down = atof(value);
} else if (strcmp(key, "roi_focus_mode") == 0) {
roi_focus_mode = atoi(value);
} else if (strcmp(key, "allow_spike_fix_fps") == 0) {
limitFPS = atoi(value);
} else if (strcmp(key, "osd_level") == 0) {
osd_level = atoi(value);
} else if (strcmp(key, "multiply_font_size_by") == 0) {
multiply_font_size_by = atof(value);
} else if (strcmp(key, "check_xtx_period_ms") == 0) {
check_xtx_period_ms = atoi(value);
}
// New keys for command templates:
else if (strcmp(key, "powerCommandTemplate") == 0) {
strncpy(powerCommandTemplate, value, sizeof(powerCommandTemplate));
} else if (strcmp(key, "fpsCommandTemplate") == 0) {
strncpy(fpsCommandTemplate, value, sizeof(fpsCommandTemplate));
} else if (strcmp(key, "qpDeltaCommandTemplate") == 0) {
strncpy(qpDeltaCommandTemplate, value, sizeof(qpDeltaCommandTemplate));
} else if (strcmp(key, "mcsCommandTemplate") == 0) {
strncpy(mcsCommandTemplate, value, sizeof(mcsCommandTemplate));
} else if (strcmp(key, "bitrateCommandTemplate") == 0) {
strncpy(bitrateCommandTemplate, value, sizeof(bitrateCommandTemplate));
} else if (strcmp(key, "gopCommandTemplate") == 0) {
strncpy(gopCommandTemplate, value, sizeof(gopCommandTemplate));
} else if (strcmp(key, "fecCommandTemplate") == 0) {
strncpy(fecCommandTemplate, value, sizeof(fecCommandTemplate));
} else if (strcmp(key, "roiCommandTemplate") == 0) {
strncpy(roiCommandTemplate, value, sizeof(roiCommandTemplate));
} else if (strcmp(key, "idrCommandTemplate") == 0) {
strncpy(idrCommandTemplate, value, sizeof(idrCommandTemplate));
} else if (strcmp(key, "customOSD") == 0) {
strncpy(global_regular_osd, value, sizeof(global_regular_osd));
} else {
fprintf(stderr, "Warning: Unrecognized configuration key: %s\n", key);
error_to_osd("Adaptive-Link: Check/update /etc/alink.conf");
exit(EXIT_FAILURE);
}
} else if (strlen(line) > 1 && line[0] != '\n') { // ignore empty lines
fprintf(stderr, "Error: Invalid configuration format: %s\n", line);
error_to_osd("Adaptive-Link: Check/update /etc/alink.conf");
exit(EXIT_FAILURE);
}
}
fclose(file);
}
void trim_whitespace(char *str) {
char *end;
// Trim leading spaces
while (isspace((unsigned char)*str)) str++;
if (*str == 0) return; // Empty string
// Trim trailing spaces
end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end)) end--;
// Null-terminate the trimmed string
*(end + 1) = '\0';
}
void normalize_whitespace(char *str) {
char *src = str, *dst = str;
int in_space = 0;
while (*src) {
if (isspace((unsigned char)*src)) {
if (!in_space) {
*dst++ = ' '; // Replace any whitespace sequence with a single space
in_space = 1;
}
} else {
*dst++ = *src;
in_space = 0;
}
src++;
}
*dst = '\0'; // Null-terminate the cleaned string
}
void load_profiles(const char* filename) {
FILE *file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Problem loading %s: ", filename);
error_to_osd("Adaptive-Link: Check /etc/txprofiles.conf");
perror("");
exit(1);
}
char line[256];
int i = 0;
while (fgets(line, sizeof(line), file) && i < MAX_PROFILES) {
// Remove comments
char *comment = strchr(line, '#');
if (comment) *comment = '\0';
// Trim and normalize spaces
trim_whitespace(line);
normalize_whitespace(line);
// Skip empty lines
if (*line == '\0') continue;
// Parse the cleaned line
if (sscanf(line, "%d - %d %15s %d %d %d %d %f %d %15s %d %d",
&profiles[i].rangeMin, &profiles[i].rangeMax, profiles[i].setGI,
&profiles[i].setMCS, &profiles[i].setFecK, &profiles[i].setFecN,
&profiles[i].setBitrate, &profiles[i].setGop, &profiles[i].wfbPower,
profiles[i].ROIqp, &profiles[i].bandwidth, &profiles[i].setQpDelta) == 12) {
i++;
} else {
fprintf(stderr, "Malformed line ignored: %s\n", line);
}
}
fclose(file);
}
int check_module_loaded(const char *module_name) {
FILE *fp = fopen("/proc/modules", "r");
if (!fp) {
perror("Failed to open /proc/modules");
return 0;
}
char line[256];
while (fgets(line, sizeof(line), fp)) {
if (strncmp(line, module_name, strlen(module_name)) == 0) {
fclose(fp);
return 1; // Found the module
}
}
fclose(fp);
return 0; // Not found
}
void load_from_vtx_info_yaml() {
char command1[] = "yaml-cli -i /etc/wfb.yaml -g .broadcast.ldpc";
char command2[] = "yaml-cli -i /etc/wfb.yaml -g .broadcast.stbc";
char buffer[128]; // Buffer to store command output
FILE *pipe;
// Retrieve ldpc_tx value
pipe = popen(command1, "r");
if (pipe == NULL) {
fprintf(stderr, "Failed to run yaml reader for ldpc_tx\n");
return;
}
if (fgets(buffer, sizeof(buffer), pipe) != NULL) {
ldpc_tx = atoi(buffer);
}
pclose(pipe);
// Retrieve stbc value
pipe = popen(command2, "r");
if (pipe == NULL) {
fprintf(stderr, "Failed to run yaml reader for stbc\n");
return;
}
if (fgets(buffer, sizeof(buffer), pipe) != NULL) {
stbc = atoi(buffer);
}
pclose(pipe);
}
void determine_tx_power_equation() {
if (check_module_loaded("88XXau")) {
tx_factor = -100;
printf("Found 88XXau card\n");
} else {
tx_factor = 50;
printf("Did not find 88XXau\n");
}
}
// Function to read fps from majestic.yaml
int get_video_fps() {
char command[] = "cli --get .video0.fps";
char buffer[128]; // Buffer to store command output
FILE *pipe;
int fps = 0;
// Open a pipe to execute the command
pipe = popen(command, "r");
if (pipe == NULL) {
fprintf(stderr, "Failed to run cli --get .video0.fps\n");
return -1; // Return an error code
}
// Read the output from the command
if (fgets(buffer, sizeof(buffer), pipe) != NULL) {
// Convert the output string to an integer
fps = atoi(buffer);
}
// Close the pipe
pclose(pipe);
return fps;
}
// Function to setup roi in majestic.yaml based on resolution
int setup_roi() {
FILE *fp; // Declare the FILE pointer before using it
// Round x_res and y_res to nearest multiples of 32
int rounded_x_res = floor(x_res / 32) * 32;
int rounded_y_res = floor(y_res / 32) * 32;
// ROI calculation with additional condition
int roi_height, start_roi_y;
if (rounded_y_res != y_res) {
roi_height = rounded_y_res - 32;
start_roi_y = 32;
} else {
roi_height = rounded_y_res;
start_roi_y = y_res - rounded_y_res;
}
// Make rois 32 lower for clear stats, make total roi 32 less
roi_height = roi_height - 32;
start_roi_y = start_roi_y + 32;
// Calculate edge_roi_width and next_roi_width as multiples of 32
int edge_roi_width = floor(rounded_x_res / 8 / 32) * 32;
int next_roi_width = (floor(rounded_x_res / 8 / 32) * 32) + 32;
int coord0 = 0;
int coord1 = edge_roi_width;
int coord2 = x_res - edge_roi_width - next_roi_width;
int coord3 = x_res - edge_roi_width;
// Format ROI definition as a string
char roi_define[256];
snprintf(roi_define, sizeof(roi_define), "%dx%dx%dx%d,%dx%dx%dx%d,%dx%dx%dx%d,%dx%dx%dx%d",
coord0, start_roi_y, edge_roi_width, roi_height,
coord1, start_roi_y, next_roi_width, roi_height,
coord2, start_roi_y, next_roi_width, roi_height,
coord3, start_roi_y, edge_roi_width, roi_height);
// Prepare the command to set ROI
char command[512];
snprintf(command, sizeof(command), "cli --set .fpv.roiRect %s", roi_define);
// Check if .fpv.enabled is set
char enabled_status[16];
fp = popen("cli --get .fpv.enabled", "r");
if (fp == NULL) {
printf("Failed to run command\n");
return 1;
}
if (fgets(enabled_status, sizeof(enabled_status) - 1, fp) == NULL) {
printf("fgets failed\n");
}
// Trim newline character
enabled_status[strcspn(enabled_status, "\n")] = 0;
// Check if enabled_status is "true" or "false"
if (strcmp(enabled_status, "true") != 0 && strcmp(enabled_status, "false") != 0) {
if (system("cli --set .fpv.enabled true") != 0) { printf("problem with reading fpv.enabled status\n"); }
}
// Run the command to set ROI
if (system(command) != 0) { printf("set ROI command failed\n"); }
// Check if .fpv.roiQp is set correctly
char roi_qp_status[32];
fp = popen("cli --get .fpv.roiQp", "r");
if (fp == NULL) {
printf("Failed to run command\n");
return 1;
}
if (fgets(roi_qp_status, sizeof(roi_qp_status) - 1, fp) == NULL) { printf("fgets failed\n"); }
pclose(fp);
// Trim newline character
roi_qp_status[strcspn(roi_qp_status, "\n")] = 0;
// Check for four integers separated by commas
int num_count = 0;
char *token = strtok(roi_qp_status, ",");
while (token != NULL) {
num_count++;
token = strtok(NULL, ",");
}
if (num_count != 4) {
if (system("cli --set .fpv.roiQp 0,0,0,0") != 0) { printf("Command failed\n"); }
}
return 0;
}
void read_wfb_tx_cmd_output(int *k, int *n, int *stbc, int *ldpc, int *short_gi, int *actual_bandwidth, int *mcs_index, int *vht_mode, int *vht_nss) {
char buffer[256];
FILE *fp;
// Run first command
fp = popen("wfb_tx_cmd 8000 get_fec", "r");
if (fp == NULL) {
perror("Failed to run wfb_tx_cmd command");
return;
}
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
if (sscanf(buffer, "k=%d", k) == 1) continue;
if (sscanf(buffer, "n=%d", n) == 1) continue;
}
pclose(fp);
// Run second command
fp = popen("wfb_tx_cmd 8000 get_radio", "r");
if (fp == NULL) {
perror("Failed to run wfb_tx_cmd command");
return;
}
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
if (sscanf(buffer, "stbc=%d", stbc) == 1) continue;
if (sscanf(buffer, "ldpc=%d", ldpc) == 1) continue;
if (sscanf(buffer, "short_gi=%d", short_gi) == 1) continue;
if (sscanf(buffer, "bandwidth=%d", actual_bandwidth) == 1) continue;
if (sscanf(buffer, "mcs_index=%d", mcs_index) == 1) continue;
if (sscanf(buffer, "vht_mode=%d", vht_mode) == 1) continue;
if (sscanf(buffer, "vht_nss=%d", vht_nss) == 1) continue;
}
pclose(fp);
}
// Get the profile based on input value
Profile* get_profile(int input_value) {
for (int i = 0; i < MAX_PROFILES; i++) {
if (input_value >= profiles[i].rangeMin && input_value <= profiles[i].rangeMax) {
return &profiles[i];
}
}
return NULL;
}
// Execute system command without adding quotes
void execute_command_no_quotes(const char* command) {
if (verbose_mode) {
puts(command);
}
if (system(command) != 0) { printf("Command failed: %s\n", command); }
usleep(pace_exec);
}
// Execute command, add quotes first
void execute_command(const char* command) {
// Create a new command with quotes
char quotedCommand[BUFFER_SIZE]; // Define a buffer for the quoted command
snprintf(quotedCommand, sizeof(quotedCommand), "\"%s\"", command); // Add quotes around the command
if (verbose_mode) {
puts(quotedCommand);
}
if (system(quotedCommand) != 0) { printf("Command failed: %s\n", quotedCommand); }
if (verbose_mode) {
printf("Waiting %ldms\n", pace_exec / 1000);
}
usleep(pace_exec);
}
// Replaces the first occurrence of a placeholder (e.g. "{name}") in 'str' with 'value'
void replace_placeholder(char *str, const char *placeholder, const char *value) {
char buffer[MAX_COMMAND_SIZE];
char *pos = strstr(str, placeholder);
if (!pos)
return; // placeholder not found
size_t prefix_len = pos - str;
buffer[0] = '\0';
strncat(buffer, str, prefix_len);
strncat(buffer, value, sizeof(buffer) - strlen(buffer) - 1);
strncat(buffer, pos + strlen(placeholder), sizeof(buffer) - strlen(buffer) - 1);
strncpy(str, buffer, MAX_COMMAND_SIZE);
str[MAX_COMMAND_SIZE-1] = '\0';
}
// Formats a command by replacing named placeholders with the provided values.
// 'count' is the number of keys/values, and keys/values are provided in parallel arrays.
void format_command(char *dest, size_t dest_size, const char *template,
int count, const char **keys, const char **values) {
char temp[MAX_COMMAND_SIZE];
strncpy(temp, template, sizeof(temp));
temp[sizeof(temp)-1] = '\0';
char placeholder[64];
for (int i = 0; i < count; i++) {
snprintf(placeholder, sizeof(placeholder), "{%s}", keys[i]);
replace_placeholder(temp, placeholder, values[i]);
}
strncpy(dest, temp, dest_size);
dest[dest_size-1] = '\0';
}
void manage_fec_and_bitrate(int new_fec_k, int new_fec_n, int new_bitrate) {
char fecCommand[MAX_COMMAND_SIZE];
char bitrateCommand[MAX_COMMAND_SIZE];
// Adjust fec and bitrate based on fec_change (if applicable)
if (allow_dynamic_fec && fec_change > 0 && fec_change <= 5) {
float denominators[] = { 1, 1.11111, 1.25, 1.42, 1.66667, 2.0 };
float denominator = denominators[fec_change];
new_bitrate = (int)(new_bitrate / denominator);
// divide k or multiply n depending on fec_k_adjust option
(fec_k_adjust) ? (new_fec_k /= denominator) : (new_fec_n *= denominator);
}
// Update the global FEC OSD regardless of order.
snprintf(global_profile_fec_osd, sizeof(global_profile_fec_osd), "%d/%d", new_fec_k, new_fec_n);
// If increasing bitrate, change FEC first; otherwise, bitrate first.
if (new_bitrate > old_bitrate) {
// Format fecCommand
const char *fecKeys[] = { "fecK", "fecN" };
char strFecK[10], strFecN[10];
snprintf(strFecK, sizeof(strFecK), "%d", new_fec_k);
snprintf(strFecN, sizeof(strFecN), "%d", new_fec_n);
const char *fecValues[] = { strFecK, strFecN };
format_command(fecCommand, sizeof(fecCommand), fecCommandTemplate, 2, fecKeys, fecValues);
execute_command(fecCommand);
old_fec_k = new_fec_k;
old_fec_n = new_fec_n;
// Format bitrateCommand
const char *brKeys[] = { "bitrate" };
char strBitrate[12];
snprintf(strBitrate, sizeof(strBitrate), "%d", new_bitrate);
const char *brValues[] = { strBitrate };
format_command(bitrateCommand, sizeof(bitrateCommand), bitrateCommandTemplate, 1, brKeys, brValues);
execute_command(bitrateCommand);
old_bitrate = new_bitrate;
} else {
// Format bitrateCommand first
const char *brKeys[] = { "bitrate" };
char strBitrate[12];
snprintf(strBitrate, sizeof(strBitrate), "%d", new_bitrate);
const char *brValues[] = { strBitrate };
format_command(bitrateCommand, sizeof(bitrateCommand), bitrateCommandTemplate, 1, brKeys, brValues);
execute_command(bitrateCommand);
old_bitrate = new_bitrate;
// Then format fecCommand
const char *fecKeys[] = { "fecK", "fecN" };
char strFecK[10], strFecN[10];
snprintf(strFecK, sizeof(strFecK), "%d", new_fec_k);
snprintf(strFecN, sizeof(strFecN), "%d", new_fec_n);
const char *fecValues[] = { strFecK, strFecN };
format_command(fecCommand, sizeof(fecCommand), fecCommandTemplate, 2, fecKeys, fecValues);
execute_command(fecCommand);
old_fec_k = new_fec_k;
old_fec_n = new_fec_n;
}
}
void apply_profile(Profile* profile) {
char powerCommand[MAX_COMMAND_SIZE];
char fpsCommand[MAX_COMMAND_SIZE];
char qpDeltaCommand[MAX_COMMAND_SIZE];
char mcsCommand[MAX_COMMAND_SIZE];
char gopCommand[MAX_COMMAND_SIZE];
char roiCommand[MAX_COMMAND_SIZE];
const char *idrCommand = idrCommandTemplate; // No formatting needed
// Calculate seconds since last change
long currentTime = get_monotonic_time();
long timeElapsed = currentTime - prevTimeStamp; // Time since the last change
// Load current profile variables into local variables
int currentWfbPower = profile->wfbPower;
float currentSetGop = profile->setGop;
char currentSetGI[10];
strcpy(currentSetGI, profile->setGI);
int currentSetMCS = profile->setMCS;
int currentSetFecK = profile->setFecK;
int currentSetFecN = profile->setFecN;
int currentSetBitrate = profile->setBitrate;
char currentROIqp[20];
strcpy(currentROIqp, profile->ROIqp);
int currentBandwidth = profile->bandwidth;
int currentQpDelta = profile->setQpDelta;
int currentDivideFpsBy = 1;
int currentFPS = global_fps;
// Determine FPS limit
if (limitFPS && currentSetBitrate < 4000 && global_fps > 30 && total_pixels > 1300000) {
currentFPS = 30;
currentDivideFpsBy = round((double)global_fps / 30);
} else if (limitFPS && currentSetBitrate < 8000 && total_pixels > 1300000 && global_fps > 60) {
currentFPS = 60;
currentDivideFpsBy = round((double)global_fps / 60);
}
// --- qpDeltaCommand ---
{
const char *keys[] = { "qpDelta" };
char strQpDelta[10];
snprintf(strQpDelta, sizeof(strQpDelta), "%d", currentQpDelta);
const char *values[] = { strQpDelta };
format_command(qpDeltaCommand, sizeof(qpDeltaCommand), qpDeltaCommandTemplate, 1, keys, values);
}
// --- fpsCommand ---
{
const char *keys[] = { "fps" };
char strFPS[10];
snprintf(strFPS, sizeof(strFPS), "%d", currentFPS);
const char *values[] = { strFPS };
format_command(fpsCommand, sizeof(fpsCommand), fpsCommandTemplate, 1, keys, values);
}
// --- powerCommand ---
{
const char *keys[] = { "power" };
char strPower[10];
snprintf(strPower, sizeof(strPower), "%d", currentWfbPower * tx_factor);
const char *values[] = { strPower };
format_command(powerCommand, sizeof(powerCommand), powerCommandTemplate, 1, keys, values);
}
// --- gopCommand ---
{
const char *keys[] = { "gop" };
char strGop[10];
snprintf(strGop, sizeof(strGop), "%.1f", currentSetGop);
const char *values[] = { strGop };
format_command(gopCommand, sizeof(gopCommand), gopCommandTemplate, 1, keys, values);
}
// --- mcsCommand ---
{
const char *keys[] = { "bandwidth", "gi", "stbc", "ldpc", "mcs" };
char strBandwidth[10], strGI[10], strStbc[10], strLdpc[10], strMcs[10];
snprintf(strBandwidth, sizeof(strBandwidth), "%d", currentBandwidth);
snprintf(strGI, sizeof(strGI), "%s", currentSetGI);
snprintf(strStbc, sizeof(strStbc), "%d", stbc);
snprintf(strLdpc, sizeof(strLdpc), "%d", ldpc_tx);
snprintf(strMcs, sizeof(strMcs), "%d", currentSetMCS);
const char *values[] = { strBandwidth, strGI, strStbc, strLdpc, strMcs };
format_command(mcsCommand, sizeof(mcsCommand), mcsCommandTemplate, 5, keys, values);
}
// --- roiCommand ---
{
const char *keys[] = { "roiQp" };
const char *values[] = { currentROIqp };
format_command(roiCommand, sizeof(roiCommand), roiCommandTemplate, 1, keys, values);
}
// --- Execution Logic ---
if (currentProfile > previousProfile) {
if (currentQpDelta != prevQpDelta) {
execute_command(qpDeltaCommand);
prevQpDelta = currentQpDelta;
}
if (currentFPS != prevFPS) {
execute_command(fpsCommand);
prevFPS = currentFPS;
}
if (allow_set_power && currentWfbPower != prevWfbPower) {
execute_command(powerCommand);
prevWfbPower = currentWfbPower;
}
if (currentSetGop != prevSetGop) {
execute_command(gopCommand);
prevSetGop = currentSetGop;
}
if (strcmp(currentSetGI, prevSetGI) != 0 ||
currentSetMCS != prevSetMCS ||
currentBandwidth != prevBandwidth) {
execute_command(mcsCommand);
prevBandwidth = currentBandwidth;
strcpy(prevSetGI, currentSetGI);
prevSetMCS = currentSetMCS;
}
if (currentSetFecK != prevSetFecK || currentSetFecN != prevSetFecN || currentSetBitrate != prevSetBitrate) {
manage_fec_and_bitrate(currentSetFecK, currentSetFecN, currentSetBitrate);
prevSetBitrate = currentSetBitrate;
prevSetFecK = currentSetFecK;
prevSetFecN = currentSetFecN;
}
if (roi_focus_mode && strcmp(currentROIqp, prevROIqp) != 0) {
execute_command(roiCommand);
strcpy(prevROIqp, currentROIqp);
}
if (idr_every_change) {
execute_command(idrCommand);
}
} else {
if (currentQpDelta != prevQpDelta) {
execute_command(qpDeltaCommand);
prevQpDelta = currentQpDelta;
}
if (currentFPS != prevFPS) {
execute_command(fpsCommand);
prevFPS = currentFPS;
}
if (currentSetFecK != prevSetFecK || currentSetFecN != prevSetFecN || currentSetBitrate != prevSetBitrate) {
manage_fec_and_bitrate(currentSetFecK, currentSetFecN, currentSetBitrate);
prevSetBitrate = currentSetBitrate;
prevSetFecK = currentSetFecK;
prevSetFecN = currentSetFecN;
}
if (currentSetGop != prevSetGop) {
execute_command(gopCommand);
prevSetGop = currentSetGop;
}
if (strcmp(currentSetGI, prevSetGI) != 0 ||
currentSetMCS != prevSetMCS ||
currentBandwidth != prevBandwidth) {
execute_command(mcsCommand);
prevBandwidth = currentBandwidth;
strcpy(prevSetGI, currentSetGI);
prevSetMCS = currentSetMCS;