-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathgstrtpreceiver.cpp
More file actions
2526 lines (2215 loc) · 99.4 KB
/
Copy pathgstrtpreceiver.cpp
File metadata and controls
2526 lines (2215 loc) · 99.4 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 "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, const std::string& name = ""){
const std::string n = name.empty() ? "" : (" name=" + name);
if(codec==VideoCodec::H264)return "rtph264depay" + n + " ! ";
if(codec==VideoCodec::H265)return "rtph265depay" + n + " ! ";
assert(false);
return "";
}
// Bare RTP caps fields for use as an in-pipeline capsfilter on the video
// branch when the source caps are left generic (audio muxed in). Unlike
// gst_create_rtp_caps() this omits the udpsrc-style caps="..." wrapper and
// does not pin a payload type, so the actual video PT is accepted as-is.
static std::string gst_rtp_video_caps_fields(const VideoCodec& videoCodec){
std::stringstream ss;
ss<<"application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)";
ss<<((videoCodec==VideoCodec::H264) ? "H264" : "H265");
return ss.str();
}
// Opus audio playback branch, fed from the shared rtp_tee.
//
// The leading leaky queue decouples the branch from the tee so a stalled or
// slow ALSA sink can never back-pressure upstream and stall the video branch.
//
// Caps are asserted with capssetter, NOT a capsfilter: the tee broadcasts one
// caps to all its branches, so a capsfilter demanding audio caps here would
// force the tee to negotiate video-caps ∩ audio-caps = empty and the whole
// pipeline (video included) would fail with not-negotiated. capssetter has an
// ANY sink template, so it imposes nothing on the tee while still handing the
// Opus RTP caps to rtpopusdepay downstream. A pad probe (attached after
// parsing) drops the non-audio-PT packets that still arrive here.
// Map the user's output selection to an alsasink "device". Empty or "default"
// -> system default (no device property). A bare ALSA card id (e.g. the
// "rockchiphdmi"/"HEADSET" ids from /proc/asound/cards, as the OSD menu
// provides) -> plughw:CARD=<id> so format/rate conversion is handled. A value
// that already looks like a full ALSA device string (contains ':') is used
// verbatim, so power users can still pass e.g. plughw:CARD=x,DEV=1 via CLI.
static std::string resolve_alsa_device(const std::string& sel){
if(sel.empty() || sel == "default") return "";
if(sel.find(':') != std::string::npos) return sel;
return "plughw:CARD=" + sel + ",DEV=0";
}
static std::string create_audio_branch(int audio_pt, const std::string& device){
std::stringstream ss;
ss<<" rtp_tee. ! queue name=audio_in_queue leaky=downstream max-size-buffers=128"
" max-size-bytes=0 max-size-time=0 silent=true"
" ! capssetter replace=true caps=\"application/x-rtp, media=(string)audio,"
" clock-rate=(int)48000, encoding-name=(string)OPUS, payload=(int)"<<audio_pt<<"\""
" ! rtpopusdepay name=audio_depay ! opusdec ! audioconvert ! audioresample"
// Software volume (named so it can be set live) — works regardless of
// whether the sink card exposes a hardware mixer, e.g. HDMI has none.
" ! volume name=audio_volume"
// Keep live latency low. The dominant delay is alsasink's ring buffer,
// which defaults to 200 ms; pin it (and the pre-sink queue) to ~50 ms.
// buffer-time/latency-time are in microseconds. Lower = less delay but
// more prone to dropouts on a loaded system — raise buffer-time (e.g.
// 100000) if you hear crackle/underruns.
" ! queue leaky=downstream max-size-buffers=0 max-size-bytes=0 max-size-time=50000000 silent=true"
// provide-clock=false is critical: audio sinks are GStreamer's default
// pipeline-clock provider, so without this alsasink hijacks the clock
// and the (sync=true) video appsink paces the display to the *audio*
// clock. When audio is sparse/absent that clock stalls -> video frames
// are held (repeats) and back-pressure drops RTP packets (scrambled
// frames). Keeping the system clock makes video timing independent of
// audio, exactly as in the audio-off pipeline.
" ! alsasink name=audio_sink sync=false async=false provide-clock=false buffer-time=50000 latency-time=10000";
const std::string dev = resolve_alsa_device(device);
if(!dev.empty()){
ss<<" device=\""<<dev<<"\"";
}
return ss.str();
}
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\", alignment=au";
ss<<" ! ";
return ss.str();
}
assert(false);
return "";
}
}
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;
}
// Defined below; classifies a single RTP packet as H264/H265/UNKNOWN.
static VideoCodec classify_rtp_packet(const uint8_t* pkt, size_t len);
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;
// Number of consecutive RTP packets that must classify as the *other* codec
// before a mid-stream switch is accepted. Frequent active-codec packets reset
// the run, so a stray misclassified packet cannot trigger a rebuild.
static constexpr int kCodecSwitchConfirm = 12;
// Mid-stream codec-switch detection. g_active_codec is the codec the running
// pipeline was built for; g_codec_switch_cb performs the rebuild and is set
// by the receiver. The cb is invoked at most once until the rebuild clears
// g_codec_switch_pending.
static std::atomic<bool> g_codec_auto{false};
static std::atomic<int> g_active_codec{static_cast<int>(VideoCodec::UNKNOWN)};
static std::atomic<int> g_codec_switch_run{0};
static std::atomic<bool> g_codec_switch_pending{false};
static std::mutex g_codec_switch_mutex;
static std::function<void(VideoCodec)> g_codec_switch_cb;
// RTP payload type carrying muxed Opus audio, or -1 when audio is disabled.
// Used to keep audio packets out of the video-only stream trackers (IDR
// sequence-gap detection and mid-stream codec-switch detection).
static std::atomic<int> g_audio_pt{-1};
// Wall-clock ms of the last observed audio (Opus) packet; 0 = never seen.
// Lets the DVR decide whether a recording should carry an audio track.
static std::atomic<uint64_t> g_last_audio_pkt_ms{0};
static bool is_audio_pt(uint8_t pt) {
const int a = g_audio_pt.load(std::memory_order_relaxed);
return a >= 0 && pt == static_cast<uint8_t>(a);
}
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();
}
// True if Opus is flowing right now (a packet seen very recently). Recording
// an empty audio track — which happens when --audio is on but the air sends
// no audio — produces an unplayable mp4, so the DVR only adds an audio track
// when this is true. Kept short so a recording started shortly after audio
// stops doesn't get an empty track either.
static bool audio_recently_seen() {
const uint64_t last = g_last_audio_pkt_ms.load(std::memory_order_relaxed);
return last != 0 && (now_ms() - last) < 1500;
}
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;
}
// Muxed audio has its own SSRC/sequence space; feeding it into the video
// gap detector would trip spurious IDR requests, so skip audio packets.
if (g_audio_pt.load(std::memory_order_relaxed) >= 0) {
GstMapInfo map;
if (gst_buffer_map(buf, &map, GST_MAP_READ)) {
const bool audio = map.size >= 2 && is_audio_pt(map.data[1] & 0x7f);
gst_buffer_unmap(buf, &map);
if (audio) {
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 note_pipeline_codec(VideoCodec codec) {
g_active_codec.store(static_cast<int>(codec), std::memory_order_relaxed);
g_codec_switch_run.store(0, std::memory_order_relaxed);
g_codec_switch_pending.store(false, std::memory_order_relaxed);
}
static void set_codec_switch_callback(std::function<void(VideoCodec)> cb) {
std::lock_guard<std::mutex> lock(g_codec_switch_mutex);
g_codec_switch_cb = std::move(cb);
}
// Inspect a raw RTP packet and, if the stream has switched to the other
// codec for a sustained run, hand off a rebuild to the registered callback.
// Called from RTP-ingress threads; must not block or rebuild inline.
static void maybe_detect_codec_switch(const uint8_t* rtp, size_t len) {
if (!g_codec_auto.load(std::memory_order_relaxed)) {
return; // codec pinned by the user; never override it
}
const int active = g_active_codec.load(std::memory_order_relaxed);
if (active == static_cast<int>(VideoCodec::UNKNOWN)) {
return; // no pipeline built yet, nothing to compare against
}
if (g_codec_switch_pending.load(std::memory_order_relaxed)) {
return; // a switch is already being applied
}
if (len >= 2 && is_audio_pt(rtp[1] & 0x7f)) {
return; // muxed audio packet: not a video codec signal
}
const VideoCodec c = classify_rtp_packet(rtp, len);
if (c == VideoCodec::UNKNOWN) {
return; // ambiguous packet: neither confirm nor reset
}
if (static_cast<int>(c) == active) {
g_codec_switch_run.store(0, std::memory_order_relaxed);
return;
}
if (g_codec_switch_run.fetch_add(1, std::memory_order_relaxed) + 1 < kCodecSwitchConfirm) {
return;
}
// Confirmed switch; ensure we only fire once until the rebuild completes.
if (g_codec_switch_pending.exchange(true, std::memory_order_relaxed)) {
return;
}
g_codec_switch_run.store(0, std::memory_order_relaxed);
spdlog::info("[CODEC] Mid-stream switch detected: {} -> {}",
active == static_cast<int>(VideoCodec::H265) ? "H.265" : "H.264",
c == VideoCodec::H265 ? "H.265" : "H.264");
std::function<void(VideoCodec)> cb;
{
std::lock_guard<std::mutex> lock(g_codec_switch_mutex);
cb = g_codec_switch_cb;
}
if (cb) {
cb(c);
} else {
g_codec_switch_pending.store(false, 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 (!g_idr_enabled.load(std::memory_order_relaxed)) {
return GST_PAD_PROBE_OK;
}
if (GST_PAD_PROBE_INFO_TYPE(info) & GST_PAD_PROBE_TYPE_BUFFER) {
GstBuffer* buf = GST_PAD_PROBE_INFO_BUFFER(info);
if (buf) {
on_incoming_stream_buffer(buf, "udpsrc");
maybe_track_rtp_sequence(buf);
GstMapInfo map;
if (gst_buffer_map(buf, &map, GST_MAP_READ)) {
maybe_detect_codec_switch(map.data, map.size);
gst_buffer_unmap(buf, &map);
}
}
}
return GST_PAD_PROBE_OK;
}
static void attach_last_hop_probes(GstElement* pipeline) {
if (!g_idr_enabled.load(std::memory_order_relaxed)) {
return;
}
if (!pipeline || !GST_IS_BIN(pipeline)) {
return;
}
GstIterator* it = gst_bin_iterate_recurse(GST_BIN(pipeline));
if (!it) {
return;
}