forked from OpenIPC/adaptive-link
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalink_drone.c
More file actions
2481 lines (2073 loc) · 81.1 KB
/
alink_drone.c
File metadata and controls
2481 lines (2073 loc) · 81.1 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <sys/un.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];
Profile* selectedProfile = NULL;
// 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;
char camera_bin[64] = "";
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;
bool use_0_to_10_txpower = 0;
int power_level_0_to_10 = 0;
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;
bool allow_xtx_reduce_bitrate = 1;
float xtx_reduce_bitrate_factor = 0.5;
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;
bool spike_fix_dynamic_fec = 1;
int limit_max_score_to = 2000;
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;
bool paused = false;
bool time_synced = false;
int last_value_sent = 100;
struct timespec last_exec_time;
struct timespec last_keyframe_request_time;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t pause_mutex = PTHREAD_MUTEX_INITIALIZER;
#define MAX_CODES 5 // Maximum unique idr rq to track
#define CODE_LENGTH 8
#define EXPIRY_TIME_MS 1000
int total_keyframe_requests = 0;
int total_keyframe_requests_xtx = 0;
long global_total_tx_dropped = 0;
bool bitrate_reduced = false;
volatile int weak_antenna_detected = 0;
// ─── Shared protocol definitions ───
// for comms from air_man
enum {
CMD_SET_POWER = 1,
CMD_GET_STATUS = 2,
CMD_ANTENNA_STATS = 3,
CMD_GET = 4,
CMD_SET = 5,
// … add more as you need
CMD_STATUS_REPLY = 0x8000 // OR’d into cmd for replies
};
struct __attribute__((packed)) alink_msg_hdr {
uint16_t cmd; // one of CMD_*
uint16_t len; // length of payload in bytes
};
// ────────────────────────────────────
#define ALINK_CMD_SOCKET_PATH "/tmp/alink_cmd.sock"
pthread_mutex_t alink_tx_power_mutex = PTHREAD_MUTEX_INITIALIZER;
#define WFB_YAML "/etc/wfb.yaml"
#define WIFI_ADAPTERS_YAML "/etc/wlan_adapters.yaml"
#define MAX_OUTPUT 512
#define MAX_CMD 1024
#define RAW_BUF 2048
#define MCS_COUNT 8
#define POWER_LEVELS 11
// global table
int tx_power_table[MCS_COUNT][POWER_LEVELS];
// strip trailing newline
static void strip_newline(char *s) {
size_t l = strlen(s);
if (l > 0 && s[l-1] == '\n') s[l-1] = '\0';
}
void load_tx_power_table(void) {
char adapter[MAX_OUTPUT];
char cmd[MAX_CMD];
char raw[RAW_BUF];
char tmp[MAX_OUTPUT];
FILE *fp;
// 1) get adapter name
snprintf(cmd, sizeof(cmd),
"yaml-cli -i %s -g .wireless.wlan_adapter",
WFB_YAML);
fp = popen(cmd, "r");
if (!fp || !fgets(adapter, sizeof(adapter), fp)) {
fprintf(stderr, "Error: Could not detect WiFi adapter.\n");
if (fp) pclose(fp);
return;
}
pclose(fp);
strip_newline(adapter);
printf("\n\nUsing wlan adapter: %s\n\n", adapter);
// 2) for each MCS, fetch & parse
for (int mcs = 0; mcs < MCS_COUNT; ++mcs) {
// zero out in case of partial parse
memset(tx_power_table[mcs], 0,
sizeof tx_power_table[mcs]);
// build command (remove brackets only)
snprintf(cmd, sizeof(cmd),
"yaml-cli -i %s -g \".profiles.%s.tx_power.mcs%d\" | sed 's/[][]//g'",
WIFI_ADAPTERS_YAML, adapter, mcs);
fp = popen(cmd, "r");
if (!fp) {
fprintf(stderr, "Failed to run yaml-cli for MCS%d\n", mcs);
continue;
}
// accumulate all lines into raw[]
raw[0] = '\0';
while (fgets(tmp, sizeof(tmp), fp)) {
strip_newline(tmp);
strncat(raw, tmp, sizeof(raw) - strlen(raw) - 1);
}
pclose(fp);
// strip any stray quotes
for (char *p = raw; *p; ++p) {
if (*p == '"') *p = ' ';
}
// tokenize on commas or whitespace, remember last value
int idx = 0;
int last_value = 0;
char *tok = strtok(raw, ", \t");
while (tok && idx < POWER_LEVELS) {
while (*tok == ' ') tok++; // skip leading spaces
last_value = atoi(tok);
tx_power_table[mcs][idx++] = last_value;
tok = strtok(NULL, ", \t");
}
// pad remaining slots with last_value
for (; idx < POWER_LEVELS; idx++) {
tx_power_table[mcs][idx] = last_value;
}
}
}
void print_tx_power_table(void) {
printf("TX Power Table (MCS x Power Index):\n");
// 1) 8-space indent to match "MCS0 : "
printf(" ");
// 2) Print headers in a 5-wide field + space (total 6 chars each)
for (int i = 0; i < POWER_LEVELS; i++) {
char hdr[5];
snprintf(hdr, sizeof(hdr), "P%02d", i);
printf("%5s ", hdr);
}
printf("\n");
// 3) Print each row the same way: prefix + 5-wide numbers + space
for (int m = 0; m < MCS_COUNT; m++) {
printf("MCS%-3d: ", m);
for (int p = 0; p < POWER_LEVELS; p++) {
printf("%5d ", tx_power_table[m][p]);
}
printf("\n");
}
}
// Shared RSSI (drone antenna) Queue (thread-safe)
#define MAX_RSSI_QUEUE 64
#define MAX_RSSI_LINE 256
char rssi_line_queue[MAX_RSSI_QUEUE][MAX_RSSI_LINE];
int rssi_q_head = 0;
int rssi_q_tail = 0;
pthread_mutex_t rssi_q_lock = PTHREAD_MUTEX_INITIALIZER;
int enqueue_rssi_line(const char *line) {
pthread_mutex_lock(&rssi_q_lock);
int next_tail = (rssi_q_tail + 1) % MAX_RSSI_QUEUE;
if (next_tail == rssi_q_head) {
pthread_mutex_unlock(&rssi_q_lock);
return -1; // Queue full
}
strncpy(rssi_line_queue[rssi_q_tail], line, MAX_RSSI_LINE - 1);
rssi_line_queue[rssi_q_tail][MAX_RSSI_LINE - 1] = '\0';
rssi_q_tail = next_tail;
pthread_mutex_unlock(&rssi_q_lock);
return 0;
}
int dequeue_rssi_line(char *line_out) {
pthread_mutex_lock(&rssi_q_lock);
if (rssi_q_head == rssi_q_tail) {
pthread_mutex_unlock(&rssi_q_lock);
return 0; // Queue empty
}
strncpy(line_out, rssi_line_queue[rssi_q_head], MAX_RSSI_LINE);
rssi_q_head = (rssi_q_head + 1) % MAX_RSSI_QUEUE;
pthread_mutex_unlock(&rssi_q_lock);
return 1;
}
// monitor drone antenna rssi
void *parse_rssi_thread(void *arg) {
(void)arg; // Unused
const int MAX_LINE = 512;
const int NUM_ANTENNAS = 4;
const int HISTORY_SIZE = 20;
const int RSSI_THRESHOLD = 20;
int rssi_history[NUM_ANTENNAS][HISTORY_SIZE];
int rssi_index[NUM_ANTENNAS];
int rssi_avg[NUM_ANTENNAS];
int rssi_count[NUM_ANTENNAS];
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 (1) {
if (!dequeue_rssi_line(line)) {
usleep(10000); // Sleep 10ms if no data
continue;
}
if (verbose_mode && strstr(line, "RX_ANT")) {
printf("RX_ANT received: %s\n", line);
}
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;
if (antenna >= num_antennas_drone) {
num_antennas_drone = antenna + 1;
}
// Parse the 3rd colon-separated value (RSSI)
char *token;
int token_count = 0, rssi = 0;
token = strtok(colon_values, ":");
while (token) {
if (++token_count == 3) {
rssi = atoi(token);
break;
}
token = strtok(NULL, ":");
}
// Store RSSI in history
rssi_history[antenna][rssi_index[antenna] % HISTORY_SIZE] = rssi;
rssi_index[antenna]++;
rssi_count[antenna]++;
// Calculate 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];
}
}
weak_antenna_detected = (max_rssi - min_rssi >= RSSI_THRESHOLD) ? 1 : 0;
}
}
}
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);
}
void adjust_font_size() {
total_pixels = x_res * y_res;
set_osd_font_size = (x_res < 1280) ? ((int)(20 * multiply_font_size_by)) :
(x_res < 1700) ? ((int)(25 * multiply_font_size_by)) :
(x_res < 2000) ? ((int)(35 * multiply_font_size_by)) :
(x_res < 2560) ? ((int)(45 * multiply_font_size_by)) :
((int)(50 * multiply_font_size_by));
}
// 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_camera_bin() {
char sensor_config[256];
// Run the system command to get the sensor config file path
FILE *fp = popen("cli -g .isp.sensorConfig", "r");
if (fp == NULL) {
printf("Failed to run sensorConfig command\n");
return 1;
}
if (fgets(sensor_config, sizeof(sensor_config) - 1, fp) == NULL) {
printf("fgets failed\n");
pclose(fp);
return 1;
}
pclose(fp);
// Remove trailing newline, if any
sensor_config[strcspn(sensor_config, "\n")] = '\0';
// Extract just the filename from the path
const char *filename = strrchr(sensor_config, '/');
if (filename) {
// Skip the '/' character
strncpy(camera_bin, filename + 1, sizeof(camera_bin) - 1);
} else {
// No '/' found, copy the whole string
strncpy(camera_bin, sensor_config, sizeof(camera_bin) - 1);
}
// Ensure null-termination
camera_bin[sizeof(camera_bin) - 1] = '\0';
printf("Camera Bin: %s\n", camera_bin);
return 0;
}
int get_resolution() {
char resolution[32];
// Execute system command to get resolution
FILE *fp = popen("cli -g .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;
}
// Get resolution but default to 1080p if failed
void get_resolution_with_default() {
if (get_resolution() != 0) {
printf("Failed to get resolution. Assuming 1920x1080\n");
x_res = 1920;
y_res = 1080;
}
}
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, "use_0_to_10_txpower") == 0) {
use_0_to_10_txpower = atoi(value);
} else if (strcmp(key, "power_level_0_to_10") == 0) {
power_level_0_to_10 = 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, "spike_fix_dynamic_fec") == 0) {
spike_fix_dynamic_fec = 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, "allow_xtx_reduce_bitrate") == 0) {
allow_xtx_reduce_bitrate = atoi(value);
} else if (strcmp(key, "xtx_reduce_bitrate_factor") == 0) {
xtx_reduce_bitrate_factor = atof(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 -g .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 -g .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 -s .fpv.roiRect %s", roi_define);
// Check if .fpv.enabled is set
char enabled_status[16];
fp = popen("cli -g .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 -s .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 -g .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 -s .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);