-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathgstrtpreceiver.cpp
More file actions
1479 lines (1264 loc) · 49.5 KB
/
Copy pathgstrtpreceiver.cpp
File metadata and controls
1479 lines (1264 loc) · 49.5 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
//
// Created by https://github.com/Consti10 on 09.04.24.
// https://github.com/OpenHD/FPVue_RK3566/tree/openhd
//
#include "gstrtpreceiver.h"
#include "latency_probe.hpp"
#include "gst/gstparse.h"
#include "gst/gstpipeline.h"
#include "gst/net/gstnetaddressmeta.h"
#include "gst/app/gstappsink.h"
#include "gst/app/gstappsrc.h"
#include "spdlog/spdlog.h"
#include <gio/gio.h>
#include <cstring>
#include <algorithm>
#include <stdexcept>
#include <cassert>
#include <sstream>
#include <iostream>
#include <memory>
#include <utility>
#include <functional>
#include <fstream>
#include <atomic>
#include <mutex>
#include <thread>
#include <random>
#include <chrono>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/un.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#if defined(__linux__)
#include <sys/random.h>
#endif
namespace pipeline {
static std::string gst_create_rtp_caps(const VideoCodec& videoCodec){
std::stringstream ss;
if(videoCodec==VideoCodec::H264){
ss<<"caps=\"application/x-rtp, media=(string)video, encoding-name=(string)H264, payload=(int)96\"";
}else if(videoCodec==VideoCodec::H265){
ss<<"caps=\"application/x-rtp, media=(string)video, encoding-name=(string)H265, clock-rate=(int)90000\"";
}
return ss.str();
}
static std::string create_rtp_depacketize_for_codec(const VideoCodec& codec){
if(codec==VideoCodec::H264)return "rtph264depay ! ";
if(codec==VideoCodec::H265)return "rtph265depay ! ";
assert(false);
return "";
}
static std::string create_parse_for_codec(const VideoCodec& codec){
// config-interval=-1 = makes 100% sure each keyframe has SPS and PPS
if(codec==VideoCodec::H264)return "h264parse config-interval=-1 ! ";
if(codec==VideoCodec::H265)return "h265parse config-interval=-1 ! ";
assert(false);
return "";
}
static std::string create_out_caps(const VideoCodec& codec){
if(codec==VideoCodec::H264){
std::stringstream ss;
ss<<"video/x-h264";
ss<<", stream-format=\"byte-stream\",alignment=nal";
//ss<<", alignment=\"nal\"";
ss<<" ! ";
return ss.str();
}else if(codec==VideoCodec::H265){
std::stringstream ss;
ss<<"video/x-h265";
ss<<", stream-format=\"byte-stream\"";
//ss<<", alignment=\"nal\"";
ss<<" ! ";
return ss.str();
}
assert(false);
}
}
static VideoCodec detect_mp4_codec(const char* file_path) {
auto scan = [](const uint8_t* buf, size_t n) -> VideoCodec {
for (size_t i = 0; i + 3 < n; i++) {
if (buf[i]=='a' && buf[i+1]=='v' && buf[i+2]=='c' && buf[i+3]=='1')
return VideoCodec::H264;
if (buf[i]=='h' && buf[i+1]=='v' && buf[i+2]=='c' && buf[i+3]=='1')
return VideoCodec::H265;
if (buf[i]=='h' && buf[i+1]=='e' && buf[i+2]=='v' && buf[i+3]=='1')
return VideoCodec::H265;
}
return VideoCodec::UNKNOWN;
};
FILE* f = fopen(file_path, "rb");
if (!f) return VideoCodec::UNKNOWN;
uint8_t buf[16384];
size_t n = fread(buf, 1, sizeof(buf), f);
VideoCodec result = scan(buf, n);
if (result == VideoCodec::UNKNOWN) {
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
long tail_offset = (fsize > (long)sizeof(buf)) ? fsize - (long)sizeof(buf) : 0;
fseek(f, tail_offset, SEEK_SET);
n = fread(buf, 1, sizeof(buf), f);
result = scan(buf, n);
}
fclose(f);
return result;
}
namespace {
static constexpr int kIdrUdpPort = 11223;
static constexpr int kIdrBurstCount = 3;
static constexpr int kIdrBurstSpacingMs = 100;
static constexpr int kIdrRepeatCount = 3;
static constexpr int kIdrRepeatSpacingMs = 100;
static constexpr int kIdrRecordRepeatCount = 3;
static constexpr int kIdrRecordRepeatSpacingMs = 150;
static constexpr uint64_t kStreamDownMs = 1200;
static constexpr uint64_t kStreamTickMs = 200;
static constexpr uint64_t kIntegrityCooldownMs = 350;
static constexpr uint64_t kRtpGapCooldownMs = 500;
static constexpr uint64_t kDecodeStallMs = 700;
static constexpr uint64_t kDecodeStallCooldownMs = 700;
static constexpr uint64_t kDecodeStallPktWindowMs = 500;
static constexpr uint64_t kRtpSeqResetMs = 1000;
static std::mutex g_idr_sock_mutex;
static int g_idr_sock = -1;
static std::atomic<bool> g_idr_sock_ready{false};
static std::mutex g_restream_mutex;
static GstElement* g_restream_valve = nullptr;
static GstElement* g_restream_sink = nullptr;
static std::atomic<bool> g_restream_enabled{false};
static std::string g_restream_target_ip;
static std::string g_restream_manual_ip; // user's active selection; empty = auto-discover
static std::string g_restream_pinned_ip; // always shown in dropdown, set from config
static std::mutex g_last_hop_mutex;
static std::string g_last_hop_ip;
static std::atomic<uint64_t> g_last_pkt_ms{0};
static std::atomic<bool> g_stream_up{false};
static std::atomic<bool> g_pending_rec_idr{false};
static std::atomic<uint64_t> g_last_integrity_idr_ms{0};
static std::atomic<uint64_t> g_last_rtp_gap_idr_ms{0};
static std::atomic<uint64_t> g_last_decode_stall_idr_ms{0};
static std::atomic<uint64_t> g_last_decoded_ms{0};
static std::atomic<uint64_t> g_last_rtp_seq_ms{0};
static std::atomic<uint16_t> g_last_rtp_seq{0};
static std::atomic<bool> g_last_rtp_seq_valid{false};
static std::atomic<bool> g_idr_enabled{true};
static std::atomic<bool> g_stream_idr_pending{false};
static std::atomic<bool> g_record_idr_pending{false};
static uint64_t now_ms() {
const auto now = std::chrono::steady_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(now).count();
}
static void request_idr_bursts(const char* reason, int request_count, bool allow_pending);
static void maybe_update_restream_target(bool force);
static bool contains_ip(const std::vector<std::string>& ips, const std::string& ip) {
return !ip.empty() && std::find(ips.begin(), ips.end(), ip) != ips.end();
}
static bool is_stream_idr_reason(const char* reason) {
return reason && !strcmp(reason, "stream-up");
}
static bool is_record_idr_reason(const char* reason) {
return reason && !strncmp(reason, "record-start", strlen("record-start"));
}
static bool ensure_idr_socket() {
if (g_idr_sock_ready.load(std::memory_order_acquire)) {
return true;
}
std::lock_guard<std::mutex> lock(g_idr_sock_mutex);
if (g_idr_sock_ready.load(std::memory_order_relaxed)) {
return true;
}
g_idr_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (g_idr_sock < 0) {
spdlog::warn("[IDR] socket(AF_INET,SOCK_DGRAM) failed: {}", strerror(errno));
return false;
}
g_idr_sock_ready.store(true, std::memory_order_release);
spdlog::info("[IDR] UDP socket ready");
return true;
}
static void set_restream_valve_locked(bool enabled) {
if (!g_restream_valve) {
return;
}
g_object_set(G_OBJECT(g_restream_valve), "drop", enabled ? FALSE : TRUE, NULL);
}
static void update_restream_valve(bool enabled) {
std::lock_guard<std::mutex> lock(g_restream_mutex);
// Only force-close when disabling. Opening is handled by maybe_update_restream_target
// once a valid target IP is confirmed, to avoid briefly streaming to 127.0.0.1.
if (!enabled) {
set_restream_valve_locked(false);
}
}
static void clear_restream_valve() {
std::lock_guard<std::mutex> lock(g_restream_mutex);
if (!g_restream_valve) {
if (!g_restream_sink) {
return;
}
}
if (g_restream_valve) {
gst_object_unref(g_restream_valve);
g_restream_valve = nullptr;
}
if (g_restream_sink) {
gst_object_unref(g_restream_sink);
g_restream_sink = nullptr;
}
g_restream_target_ip.clear();
}
static void bind_restream_valve(GstElement* pipeline) {
clear_restream_valve();
if (!pipeline || !GST_IS_BIN(pipeline)) {
return;
}
GstElement* valve = gst_bin_get_by_name(GST_BIN(pipeline), "restream_valve");
if (!valve) {
return;
}
GstElement* sink = gst_bin_get_by_name(GST_BIN(pipeline), "restream_sink");
if (!sink) {
gst_object_unref(valve);
return;
}
{
std::lock_guard<std::mutex> lock(g_restream_mutex);
g_restream_valve = valve;
g_restream_sink = sink;
g_restream_target_ip.clear();
set_restream_valve_locked(false);
}
maybe_update_restream_target(true);
}
static std::string create_restream_branch() {
std::stringstream ss;
ss << " rtp_tee. ! valve name=restream_valve drop=true"
" ! queue leaky=downstream max-size-buffers=0 max-size-bytes=0 max-size-time=1000000000 silent=true"
" ! udpsink name=restream_sink host=0.0.0.0 port=5600 sync=false async=false qos=false";
return ss.str();
}
static std::vector<std::string> scan_hotspot_clients() {
std::ifstream arp_file("/proc/net/arp");
if (!arp_file.is_open()) return {};
std::string line;
std::getline(arp_file, line); // skip header
std::vector<std::string> result;
while (std::getline(arp_file, line)) {
std::istringstream iss(line);
std::string ip, hw_type, flags, hw_address, mask, device;
if (!(iss >> ip >> hw_type >> flags >> hw_address >> mask >> device)) continue;
if (device != "wlan0" && device != "usb0") continue;
if (flags == "0x0" || hw_address == "00:00:00:00:00:00") continue;
result.push_back(ip);
}
return result;
}
static std::string find_first_hotspot_client_ip() {
const auto clients = scan_hotspot_clients();
if (contains_ip(clients, g_restream_target_ip)) {
return g_restream_target_ip;
}
return clients.empty() ? "" : clients.front();
}
static void maybe_update_restream_target(bool force) {
static uint64_t last_probe_ms = 0;
const uint64_t now = now_ms();
if (!force && (now - last_probe_ms) < 1000) {
return;
}
last_probe_ms = now;
bool new_target = false;
{
std::lock_guard<std::mutex> lock(g_restream_mutex);
if (!g_restream_valve || !g_restream_sink) {
return;
}
if (!g_restream_enabled.load(std::memory_order_relaxed)) {
set_restream_valve_locked(false);
return;
}
// If the user picked a specific IP use it, otherwise auto-discover.
const std::string next_ip = !g_restream_manual_ip.empty()
? g_restream_manual_ip
: find_first_hotspot_client_ip();
if (next_ip.empty()) {
if (!g_restream_target_ip.empty()) {
spdlog::info("[RESTREAM] No target client found; stopping unicast restream");
g_restream_target_ip.clear();
}
set_restream_valve_locked(false);
return;
}
if (next_ip != g_restream_target_ip) {
g_restream_target_ip = next_ip;
g_object_set(G_OBJECT(g_restream_sink), "host", g_restream_target_ip.c_str(), NULL);
spdlog::info("[RESTREAM] Streaming to {}:{}",
g_restream_target_ip,
5600);
new_target = true;
}
set_restream_valve_locked(true);
}
if (new_target) {
request_idr_bursts("restream-start", kIdrRepeatCount, false);
}
}
static uint32_t secure_random_u32() {
uint32_t out = 0;
#if defined(__linux__)
ssize_t n = getrandom(&out, sizeof(out), 0);
if (n == sizeof(out)) {
return out;
}
#endif
static std::random_device rd;
out = (static_cast<uint32_t>(rd()) << 16) ^ static_cast<uint32_t>(rd());
return out;
}
static void make_idr_token3(char out[4]) {
static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const uint32_t r0 = secure_random_u32();
const uint32_t r1 = secure_random_u32();
const uint32_t r2 = secure_random_u32();
out[0] = alphabet[r0 % 26];
out[1] = alphabet[r1 % 26];
out[2] = alphabet[r2 % 26];
out[3] = '\0';
}
static bool extract_sender_ip_from_buffer(GstBuffer* buf, std::string& out_ip) {
out_ip.clear();
if (!buf) {
return false;
}
GstNetAddressMeta* meta = (GstNetAddressMeta*)gst_buffer_get_meta(buf, GST_NET_ADDRESS_META_API_TYPE);
if (!meta || !meta->addr) {
return false;
}
if (!G_IS_INET_SOCKET_ADDRESS(meta->addr)) {
return false;
}
GInetSocketAddress* isa = G_INET_SOCKET_ADDRESS(meta->addr);
GInetAddress* ia = g_inet_socket_address_get_address(isa);
if (!ia) {
return false;
}
gchar* s = g_inet_address_to_string(ia);
if (!s) {
return false;
}
out_ip = s;
g_free(s);
return !out_ip.empty();
}
static void maybe_update_last_hop_from_buffer(GstBuffer* buf) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
std::string ip;
if (!extract_sender_ip_from_buffer(buf, ip)) {
return;
}
std::lock_guard<std::mutex> lock(g_last_hop_mutex);
if (ip != g_last_hop_ip) {
g_last_hop_ip = ip;
spdlog::info("[NET] Last-hop sender: {}", g_last_hop_ip);
}
}
static std::string get_last_hop_ip_copy() {
std::lock_guard<std::mutex> lock(g_last_hop_mutex);
return g_last_hop_ip;
}
static bool extract_rtp_sequence(GstBuffer* buf, uint16_t* out_seq) {
if (!buf || !out_seq) {
return false;
}
GstMapInfo map;
if (!gst_buffer_map(buf, &map, GST_MAP_READ)) {
return false;
}
bool ok = false;
if (map.size >= 4) {
const uint8_t* data = map.data;
*out_seq = static_cast<uint16_t>((data[2] << 8) | data[3]);
ok = true;
}
gst_buffer_unmap(buf, &map);
return ok;
}
static void maybe_request_idr_for_rtp_gap(uint16_t gap_count) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
if (!g_stream_up.load(std::memory_order_relaxed)) {
return;
}
const uint64_t now = now_ms();
const uint64_t last = g_last_rtp_gap_idr_ms.load(std::memory_order_relaxed);
if (last && (now - last) < kRtpGapCooldownMs) {
return;
}
g_last_rtp_gap_idr_ms.store(now, std::memory_order_relaxed);
spdlog::info("[IDR] RTP gap detected (missing {} packet(s)) -> request IDR", gap_count);
request_idr_bursts("rtp-gap", 1, false);
}
static void maybe_track_rtp_sequence(GstBuffer* buf) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
uint16_t seq = 0;
if (!extract_rtp_sequence(buf, &seq)) {
return;
}
const uint64_t now = now_ms();
if (!g_last_rtp_seq_valid.load(std::memory_order_relaxed)) {
g_last_rtp_seq.store(seq, std::memory_order_relaxed);
g_last_rtp_seq_ms.store(now, std::memory_order_relaxed);
g_last_rtp_seq_valid.store(true, std::memory_order_relaxed);
return;
}
const uint16_t last = g_last_rtp_seq.load(std::memory_order_relaxed);
const uint16_t diff = static_cast<uint16_t>(seq - last);
if (diff == 0) {
return;
}
if (diff >= 30000) {
const uint64_t last_ms = g_last_rtp_seq_ms.load(std::memory_order_relaxed);
if (last_ms == 0 || (now - last_ms) > kRtpSeqResetMs) {
g_last_rtp_seq.store(seq, std::memory_order_relaxed);
g_last_rtp_seq_ms.store(now, std::memory_order_relaxed);
}
return;
}
if (diff > 1) {
maybe_request_idr_for_rtp_gap(static_cast<uint16_t>(diff - 1));
}
g_last_rtp_seq.store(seq, std::memory_order_relaxed);
g_last_rtp_seq_ms.store(now, std::memory_order_relaxed);
}
static void for_each_nal(const uint8_t* data, size_t size,
const std::function<void(const uint8_t*, size_t)>& cb) {
auto find_start = [&](size_t from, size_t& start_len) -> size_t {
for (size_t i = from; i + 3 < size; i++) {
if (data[i] == 0x00 && data[i + 1] == 0x00) {
if (data[i + 2] == 0x01) {
start_len = 3;
return i;
}
if (i + 3 < size && data[i + 2] == 0x00 && data[i + 3] == 0x01) {
start_len = 4;
return i;
}
}
}
start_len = 0;
return size;
};
size_t pos = 0;
while (pos < size) {
size_t start_len = 0;
size_t start = find_start(pos, start_len);
if (start == size) {
break;
}
size_t nal_start = start + start_len;
size_t next_len = 0;
size_t next = find_start(nal_start, next_len);
size_t nal_end = (next == size) ? size : next;
if (nal_end > nal_start) {
cb(data + nal_start, nal_end - nal_start);
}
pos = nal_end;
}
}
static bool has_idr_frame(const uint8_t* data, size_t size, VideoCodec codec) {
bool found = false;
if (!data || size == 0) {
return false;
}
for_each_nal(data, size, [&](const uint8_t* nal, size_t nal_size) {
if (found || !nal || nal_size == 0) {
return;
}
if (codec == VideoCodec::H265) {
uint8_t nal_type = (nal[0] >> 1) & 0x3f;
if (nal_type >= 16 && nal_type <= 21) {
found = true;
}
} else if (codec == VideoCodec::H264) {
uint8_t nal_type = nal[0] & 0x1f;
if (nal_type == 5) {
found = true;
}
}
});
return found;
}
static void maybe_mark_idr_received(const uint8_t* data, size_t size, VideoCodec codec) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
if (!g_stream_idr_pending.load(std::memory_order_relaxed) &&
!g_record_idr_pending.load(std::memory_order_relaxed)) {
return;
}
if (!has_idr_frame(data, size, codec)) {
return;
}
if (g_stream_idr_pending.exchange(false, std::memory_order_relaxed)) {
spdlog::info("[IDR] Stream refresh confirmed (IDR received)");
}
if (g_record_idr_pending.exchange(false, std::memory_order_relaxed)) {
g_pending_rec_idr.store(false, std::memory_order_relaxed);
spdlog::info("[IDR] Record refresh confirmed (IDR received)");
}
}
static void send_idr_token_to_ip(const char* ip, const char token3[4]) {
if (!ip || !ip[0]) {
return;
}
sockaddr_in dst{};
dst.sin_family = AF_INET;
dst.sin_port = htons(static_cast<uint16_t>(kIdrUdpPort));
if (inet_pton(AF_INET, ip, &dst.sin_addr) != 1) {
spdlog::warn("[IDR] inet_pton failed for ip={}", ip);
return;
}
char payload[16];
snprintf(payload, sizeof(payload), "%s\n", token3);
int rc = sendto(g_idr_sock, payload, static_cast<int>(strlen(payload)), 0,
reinterpret_cast<sockaddr*>(&dst), static_cast<int>(sizeof(dst)));
if (rc < 0) {
spdlog::warn("[IDR] sendto({}:{}) failed: {}", ip, kIdrUdpPort, strerror(errno));
}
}
static void send_idr_burst(const std::string& ip) {
for (int i = 0; i < kIdrBurstCount; ++i) {
char tok[4];
make_idr_token3(tok);
send_idr_token_to_ip(ip.c_str(), tok);
if (i + 1 < kIdrBurstCount) {
std::this_thread::sleep_for(std::chrono::milliseconds(kIdrBurstSpacingMs));
}
}
}
static void request_idr_bursts(const char* reason, int request_count, bool allow_pending) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
const bool track_stream = is_stream_idr_reason(reason);
const bool track_record = is_record_idr_reason(reason);
if (track_stream) {
g_stream_idr_pending.store(true, std::memory_order_relaxed);
}
if (track_record) {
g_record_idr_pending.store(true, std::memory_order_relaxed);
}
const std::string ip = get_last_hop_ip_copy();
if (ip.empty()) {
spdlog::warn("[IDR] Cannot request IDR (last-hop unknown) reason={}", reason ? reason : "(null)");
if (allow_pending) {
g_pending_rec_idr.store(true, std::memory_order_relaxed);
}
return;
}
if (!ensure_idr_socket()) {
return;
}
g_pending_rec_idr.store(false, std::memory_order_relaxed);
const std::string reason_str = reason ? reason : "";
if (track_record) {
std::thread([ip, reason_str, request_count]() {
const char* reason_c = reason_str.empty() ? "no-reason" : reason_str.c_str();
for (int r = 0; r < request_count; ++r) {
if (!g_record_idr_pending.load(std::memory_order_relaxed)) {
spdlog::info("[IDR] Record refresh confirmed; skipping remaining bursts");
break;
}
spdlog::info("[IDR] Request 1 burst(s) to {}:{} ({} {}/{})",
ip, kIdrUdpPort, reason_c, r + 1, request_count);
send_idr_burst(ip);
if (r + 1 < request_count) {
std::this_thread::sleep_for(
std::chrono::milliseconds(kIdrRecordRepeatSpacingMs));
}
}
}).detach();
return;
}
std::thread([ip, reason_str, request_count]() {
const char* reason_c = reason_str.empty() ? "no-reason" : reason_str.c_str();
const bool track_stream = is_stream_idr_reason(reason_c);
spdlog::info("[IDR] Request {} burst(s) to {}:{} ({})", request_count, ip, kIdrUdpPort, reason_c);
for (int r = 0; r < request_count; ++r) {
if (track_stream && !g_stream_idr_pending.load(std::memory_order_relaxed)) {
spdlog::info("[IDR] Stream refresh confirmed; skipping remaining bursts");
break;
}
send_idr_burst(ip);
if (r + 1 < request_count) {
std::this_thread::sleep_for(std::chrono::milliseconds(kIdrRepeatSpacingMs));
}
}
}).detach();
}
static void on_incoming_stream_buffer(GstBuffer* buf, const char* tag) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
g_last_pkt_ms.store(now_ms(), std::memory_order_relaxed);
maybe_update_last_hop_from_buffer(buf);
if (!g_stream_up.exchange(true)) {
spdlog::info("[NET] Stream UP ({})", tag ? tag : "unknown");
request_idr_bursts("stream-up", kIdrRepeatCount, false);
}
if (g_pending_rec_idr.load(std::memory_order_relaxed)) {
if (!g_record_idr_pending.load(std::memory_order_relaxed)) {
g_pending_rec_idr.store(false, std::memory_order_relaxed);
} else {
const std::string ip = get_last_hop_ip_copy();
if (!ip.empty()) {
g_pending_rec_idr.store(false, std::memory_order_relaxed);
request_idr_bursts("record-start(pending)", kIdrRecordRepeatCount, false);
}
}
}
}
static void maybe_request_decode_stall(uint64_t now) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
if (!g_stream_up.load(std::memory_order_relaxed)) {
return;
}
const uint64_t last_pkt = g_last_pkt_ms.load(std::memory_order_relaxed);
const uint64_t last_decoded = g_last_decoded_ms.load(std::memory_order_relaxed);
if (last_decoded == 0) {
return;
}
if (last_pkt && (now - last_pkt) > kDecodeStallPktWindowMs) {
return;
}
if (last_pkt > last_decoded && (now - last_decoded) > kDecodeStallMs) {
const uint64_t last_idr = g_last_decode_stall_idr_ms.load(std::memory_order_relaxed);
if (!last_idr || (now - last_idr) > kDecodeStallCooldownMs) {
g_last_decode_stall_idr_ms.store(now, std::memory_order_relaxed);
spdlog::info("[IDR] Decode stall (no frames for {} ms) -> request IDR", now - last_decoded);
request_idr_bursts("decode-stall", 1, false);
}
}
}
static void tick_stream_presence() {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
static uint64_t last_tick = 0;
const uint64_t now = now_ms();
if (now - last_tick < kStreamTickMs) {
return;
}
last_tick = now;
if (!g_stream_up.load(std::memory_order_relaxed)) {
return;
}
const uint64_t last = g_last_pkt_ms.load(std::memory_order_relaxed);
if (last && now > last && (now - last) > kStreamDownMs) {
if (g_stream_up.exchange(false)) {
spdlog::info("[NET] Stream DOWN (no packets for {} ms)", now - last);
g_last_rtp_seq_valid.store(false, std::memory_order_relaxed);
g_last_rtp_seq_ms.store(0, std::memory_order_relaxed);
}
}
maybe_request_decode_stall(now);
}
static void reset_stream_tracking() {
g_stream_up.store(false, std::memory_order_relaxed);
g_last_pkt_ms.store(0, std::memory_order_relaxed);
g_last_decoded_ms.store(0, std::memory_order_relaxed);
g_last_rtp_seq_valid.store(false, std::memory_order_relaxed);
g_last_rtp_seq_ms.store(0, std::memory_order_relaxed);
g_stream_idr_pending.store(false, std::memory_order_relaxed);
std::lock_guard<std::mutex> lock(g_last_hop_mutex);
g_last_hop_ip.clear();
}
static GstPadProbeReturn udp_last_hop_probe(GstPad*, GstPadProbeInfo* info, gpointer) {
if (!(GST_PAD_PROBE_INFO_TYPE(info) & GST_PAD_PROBE_TYPE_BUFFER))
return GST_PAD_PROBE_OK;
GstBuffer* buf = GST_PAD_PROBE_INFO_BUFFER(info);
if (!buf) return GST_PAD_PROBE_OK;
// Latency-probe hook runs first and is cheap when active==false.
if (latency_probe::active.load(std::memory_order_acquire)) {
GstMapInfo map;
if (gst_buffer_map(buf, &map, GST_MAP_READ)) {
latency_probe::on_rtp_buffer(map.data, map.size,
latency_probe::now_us());
gst_buffer_unmap(buf, &map);
}
}
// Existing IDR-tracking path.
if (g_idr_enabled.load(std::memory_order_relaxed)) {
on_incoming_stream_buffer(buf, "udpsrc");
maybe_track_rtp_sequence(buf);
}
return GST_PAD_PROBE_OK;
}
static void attach_last_hop_probes(GstElement* pipeline) {
if (!g_idr_enabled.load(std::memory_order_relaxed) &&
!latency_probe::active.load(std::memory_order_acquire)) {
return;
}
if (!pipeline || !GST_IS_BIN(pipeline)) {
return;
}
GstIterator* it = gst_bin_iterate_recurse(GST_BIN(pipeline));
if (!it) {
return;
}
GValue v = G_VALUE_INIT;
while (gst_iterator_next(it, &v) == GST_ITERATOR_OK) {
GstElement* e = GST_ELEMENT(g_value_get_object(&v));
GstElementFactory* f = e ? gst_element_get_factory(e) : nullptr;
const gchar* fname = f ? gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(f)) : nullptr;
if (fname && (!strcmp(fname, "udpsrc") || !strcmp(fname, "ts-udpsrc"))) {
if (g_object_class_find_property(G_OBJECT_GET_CLASS(e), "retrieve-sender-address")) {
g_object_set(G_OBJECT(e), "retrieve-sender-address", TRUE, NULL);
}
GstPad* src_pad = gst_element_get_static_pad(e, "src");
if (src_pad) {
gst_pad_add_probe(src_pad, GST_PAD_PROBE_TYPE_BUFFER, udp_last_hop_probe, nullptr, nullptr);
gst_object_unref(src_pad);
spdlog::info("[NET] last-hop probe attached to {}", fname);
}
}
g_value_unset(&v);
}
gst_iterator_free(it);
}
static void maybe_request_idr_rate_limited(const char* reason, const char* context) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
if (!g_stream_up.load(std::memory_order_relaxed)) {
return;
}
const uint64_t now = now_ms();
const uint64_t last = g_last_integrity_idr_ms.load(std::memory_order_relaxed);
if (last && (now - last) < kIntegrityCooldownMs) {
return;
}
g_last_integrity_idr_ms.store(now, std::memory_order_relaxed);
if (context && context[0]) {
spdlog::info("[IDR] {} -> request IDR", context);
} else {
spdlog::info("[IDR] Decoder issue -> request IDR");
}
request_idr_bursts(reason ? reason : "decoder-issue", 1, false);
}
}
static void initGstreamerOrThrow() {
GError* error = nullptr;
if (!gst_init_check(nullptr, nullptr, &error)) {
g_error_free(error);
throw std::runtime_error("GStreamer initialization failed");
}
}
GstRtpReceiver::GstRtpReceiver(int udp_port, const VideoCodec& codec)
{
m_port=udp_port;
m_video_codec=codec;
initGstreamerOrThrow();
}
GstRtpReceiver::GstRtpReceiver(const char *s, const VideoCodec& codec) {
unix_socket = strdup(s);
m_video_codec = codec;
initGstreamerOrThrow();
spdlog::debug("Creating receiver socket on {}", unix_socket);
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock < 0) {
throw std::runtime_error(std::string("socket() failed: ") + strerror(errno));
}
struct sockaddr_un addr = {0};
addr.sun_family = AF_UNIX;
// Abstract socket: Start sun_path with a null byte, then copy the rest.
// The "@" in logs is a placeholder for the null byte.
addr.sun_path[0] = '\0'; // First byte is null
strncpy(addr.sun_path + 1, unix_socket, sizeof(addr.sun_path) - 2); // Leave room for null
addr.sun_path[sizeof(addr.sun_path) - 1] = '\0'; // Ensure null-terminated
// Length = sizeof(sun_family) + 1 (null byte) + strlen(path)
socklen_t addr_len = sizeof(addr.sun_family) + 1 + strlen(unix_socket);
if (bind(sock, (struct sockaddr*)&addr, addr_len) < 0) {
close(sock);
throw std::runtime_error(std::string("bind() failed: ") + strerror(errno));
}
spdlog::debug("Bound successfully to abstract socket: @{}", unix_socket);
}
GstRtpReceiver::~GstRtpReceiver(){
if (sock >= 0) {
close(sock);
}
}
static std::shared_ptr<std::vector<uint8_t>> gst_copy_buffer(GstBuffer* buffer){
assert(buffer);
const auto buff_size = gst_buffer_get_size(buffer);
auto ret = std::make_shared<std::vector<uint8_t>>(buff_size);
GstMapInfo map;
gst_buffer_map(buffer, &map, GST_MAP_READ);
assert(map.size == buff_size);
std::memcpy(ret->data(), map.data, buff_size);
gst_buffer_unmap(buffer, &map);
return ret;
}
static void loop_pull_appsink_samples(bool& keep_looping,GstElement *app_sink_element,
const GstRtpReceiver::NEW_FRAME_CALLBACK out_cb){
assert(app_sink_element);
assert(out_cb);
const uint64_t timeout_ns=std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(100)).count();
while (keep_looping){
//GstSample* sample = nullptr;
GstSample* sample= gst_app_sink_try_pull_sample(GST_APP_SINK(app_sink_element),timeout_ns);
if (sample) {
//gst_debug_sample(sample);
GstBuffer* buffer = gst_sample_get_buffer(sample);
if (buffer) {
on_incoming_stream_buffer(buffer, "appsink");
auto buff_copy=gst_copy_buffer(buffer);
out_cb(buff_copy);
}
gst_sample_unref(sample);
}
maybe_update_restream_target(false);
tick_stream_presence();
}
}
std::string GstRtpReceiver::construct_gstreamer_pipeline()
{
std::stringstream ss;
if (! unix_socket)
ss<<"udpsrc port="<<m_port<<" "<<pipeline::gst_create_rtp_caps(m_video_codec)<<" ! tee name=rtp_tee ";
else
ss<<"appsrc name=appsrc "<<pipeline::gst_create_rtp_caps(m_video_codec)<<" ! tee name=rtp_tee ";
ss<<"rtp_tee. ! ";
ss<<pipeline::create_rtp_depacketize_for_codec(m_video_codec);
ss<<pipeline::create_parse_for_codec(m_video_codec);
ss<<pipeline::create_out_caps(m_video_codec);
ss<<"appsink drop=true name=out_appsink";
ss<<create_restream_branch();
return ss.str();
}
void GstRtpReceiver::loop_pull_samples()
{
assert(m_app_sink_element);
auto cb=[this](std::shared_ptr<std::vector<uint8_t>> sample){
this->on_new_sample(sample);
};
loop_pull_appsink_samples(m_pull_samples_run,m_app_sink_element,cb);
}
void GstRtpReceiver::on_new_sample(std::shared_ptr<std::vector<uint8_t> > sample)
{
if (sample && !sample->empty()) {
maybe_mark_idr_received(sample->data(), sample->size(), m_video_codec);
}
if(m_cb){
//debug_sample(sample);
m_cb(sample);
}else{
}
}