@aivin-labs/cli 1.0.51 → 1.0.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.mjs +2215 -2211
- package/bin/lib/auth.mjs +119 -88
- package/bin/lib/context.mjs +58 -5
- package/bin/lib/loginHandoff.mjs +87 -0
- package/bin/lib/openFile.mjs +29 -4
- package/bin/lib/remote/agentContract.mjs +370 -0
- package/bin/lib/remote/agentEvidence.mjs +409 -0
- package/bin/lib/remote/autoStart.mjs +640 -623
- package/bin/lib/remote/client.mjs +55 -17
- package/bin/lib/remote/codingAgents.mjs +594 -293
- package/bin/lib/remote/constants.mjs +1 -1
- package/bin/lib/remote/credentials.mjs +131 -125
- package/bin/lib/remote/desktop/castAuth.mjs +44 -19
- package/bin/lib/remote/desktop/castConsent.mjs +79 -14
- package/bin/lib/remote/desktop/castInput.mjs +3 -0
- package/bin/lib/remote/desktop/castTrust.mjs +221 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
- package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
- package/bin/lib/remote/desktop/strings.mjs +26 -0
- package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
- package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
- package/bin/lib/remote/dpapiHelper.mjs +91 -0
- package/bin/lib/remote/gui/index.mjs +422 -68
- package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
- package/bin/lib/remote/humanInput.mjs +7 -0
- package/bin/lib/remote/localConfirm.mjs +2 -2
- package/bin/lib/remote/tokenStore.mjs +19 -2
- package/bin/lib/remote/toolHandlers.mjs +861 -859
- package/docs/CLI.md +1606 -1602
- package/package.json +1 -1
|
@@ -489,7 +489,7 @@ namespace AivinDesktopCast {
|
|
|
489
489
|
var msg = Out.Msg("cursor_shape");
|
|
490
490
|
msg["id"] = id;
|
|
491
491
|
int hotX, hotY;
|
|
492
|
-
msg["png"] = RenderShape(handle, out hotX, out hotY);
|
|
492
|
+
msg["png"] = RenderShape(SystemCursorHider.ShapeOf(handle), out hotX, out hotY);
|
|
493
493
|
msg["hotX"] = hotX;
|
|
494
494
|
msg["hotY"] = hotY;
|
|
495
495
|
Out.Send(msg);
|
|
@@ -38,6 +38,13 @@ namespace AivinDesktopCast {
|
|
|
38
38
|
[DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
|
|
39
39
|
[DllImport("shcore.dll")] public static extern int SetProcessDpiAwareness(int value);
|
|
40
40
|
[DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
|
|
41
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT lpPoint);
|
|
42
|
+
[DllImport("user32.dll")] public static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
|
|
43
|
+
[DllImport("user32.dll")] public static extern IntPtr CopyIcon(IntPtr hIcon);
|
|
44
|
+
[DllImport("user32.dll")] public static extern IntPtr CreateCursor(IntPtr hInst, int xHotSpot, int yHotSpot, int nWidth, int nHeight, byte[] pvANDPlane, byte[] pvXORPlane);
|
|
45
|
+
[DllImport("user32.dll")] public static extern bool DestroyCursor(IntPtr hCursor);
|
|
46
|
+
[DllImport("user32.dll")] public static extern bool SetSystemCursor(IntPtr hcur, uint id);
|
|
47
|
+
[DllImport("user32.dll")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);
|
|
41
48
|
[DllImport("user32.dll", EntryPoint = "mouse_event")] static extern void mouse_event_native(uint dwFlags, int dx, int dy, int dwData, UIntPtr dwExtraInfo);
|
|
42
49
|
[DllImport("user32.dll", EntryPoint = "keybd_event")] static extern void keybd_event_native(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
|
|
43
50
|
|
|
@@ -341,6 +348,9 @@ namespace AivinDesktopCast {
|
|
|
341
348
|
Thread.Sleep(60);
|
|
342
349
|
} finally {
|
|
343
350
|
Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
|
|
351
|
+
// Con trỏ do chính phiên kéo tới đích thả: không tính là người ở máy vừa dùng chuột.
|
|
352
|
+
Native.POINT p;
|
|
353
|
+
if (Native.GetCursorPos(out p)) LocalPointerGuard.Placed(p.x, p.y);
|
|
344
354
|
}
|
|
345
355
|
}
|
|
346
356
|
|
|
@@ -468,7 +478,6 @@ namespace AivinDesktopCast {
|
|
|
468
478
|
static byte[] scaleRaw;
|
|
469
479
|
static byte[] scaleOut;
|
|
470
480
|
static byte[] i420Out;
|
|
471
|
-
static Bitmap cursorBuffer;
|
|
472
481
|
static Bitmap scaleBuffer;
|
|
473
482
|
static Bitmap thumbBmp;
|
|
474
483
|
static byte[] thumbRaw;
|
|
@@ -581,34 +590,71 @@ namespace AivinDesktopCast {
|
|
|
581
590
|
}
|
|
582
591
|
}
|
|
583
592
|
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
593
|
+
const int CURSOR_PATCH = 128;
|
|
594
|
+
static Bitmap cursorPatch;
|
|
595
|
+
static byte[] cursorSaved;
|
|
596
|
+
static Rectangle cursorSavedRect = Rectangle.Empty;
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Vẽ con trỏ thật của Windows thẳng lên khung, chỉ đụng vùng CURSOR_PATCH quanh con trỏ; RestoreCursorPatch trả vùng đó về như cũ sau khi
|
|
600
|
+
* khung đã gửi (khung còn dùng để so thay đổi và lần sau chỉ con trỏ đổi thì không chụp lại). Trước đây chép nguyên khung sang bản sao rồi vẽ:
|
|
601
|
+
* đo 13/11/2026 tốn 19,4 ms mỗi khung 1920×1080, là khâu đắt nhất của bộ quay. Trả về false khi không vẽ gì.
|
|
602
|
+
*/
|
|
603
|
+
public static bool DrawCursorInPlace(Bitmap frame, Rectangle r) {
|
|
604
|
+
cursorSavedRect = Rectangle.Empty;
|
|
605
|
+
try {
|
|
606
|
+
Native.CURSORINFO pci;
|
|
607
|
+
pci.cbSize = Marshal.SizeOf(typeof(Native.CURSORINFO));
|
|
608
|
+
if (!Native.GetCursorInfo(out pci) || (pci.flags & Native.CURSOR_SHOWING) == 0) return false;
|
|
609
|
+
IntPtr shape = SystemCursorHider.ShapeOf(pci.hCursor);
|
|
610
|
+
var hot = CursorTracker.Hotspot(shape);
|
|
611
|
+
int cursorX = pci.ptScreenPos.x - hot.X - r.Left;
|
|
612
|
+
int cursorY = pci.ptScreenPos.y - hot.Y - r.Top;
|
|
613
|
+
var area = Rectangle.Intersect(new Rectangle(cursorX, cursorY, CURSOR_PATCH, CURSOR_PATCH), new Rectangle(0, 0, frame.Width, frame.Height));
|
|
614
|
+
if (area.Width <= 0 || area.Height <= 0) return false;
|
|
615
|
+
if (cursorPatch == null) cursorPatch = new Bitmap(CURSOR_PATCH, CURSOR_PATCH, PixelFormat.Format32bppRgb);
|
|
616
|
+
int rowBytes = area.Width * 4;
|
|
617
|
+
if (cursorSaved == null) cursorSaved = new byte[CURSOR_PATCH * CURSOR_PATCH * 4];
|
|
618
|
+
CopyRegion(frame, area, cursorSaved, true);
|
|
619
|
+
CopyRegion(cursorPatch, new Rectangle(0, 0, area.Width, area.Height), cursorSaved, false);
|
|
620
|
+
using (var g = Graphics.FromImage(cursorPatch)) {
|
|
621
|
+
IntPtr hdc = g.GetHdc();
|
|
622
|
+
try {
|
|
623
|
+
Native.DrawIcon(hdc, cursorX - area.X, cursorY - area.Y, shape);
|
|
624
|
+
} finally {
|
|
625
|
+
g.ReleaseHdc(hdc);
|
|
608
626
|
}
|
|
609
|
-
}
|
|
627
|
+
}
|
|
628
|
+
var drawn = new byte[area.Height * rowBytes];
|
|
629
|
+
CopyRegion(cursorPatch, new Rectangle(0, 0, area.Width, area.Height), drawn, true);
|
|
630
|
+
CopyRegion(frame, area, drawn, false);
|
|
631
|
+
cursorSavedRect = area;
|
|
632
|
+
return true;
|
|
633
|
+
} catch {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** Trả vùng dưới con trỏ về ảnh màn hình thật (xem DrawCursorInPlace). */
|
|
639
|
+
public static void RestoreCursorPatch(Bitmap frame) {
|
|
640
|
+
if (cursorSavedRect.IsEmpty) return;
|
|
641
|
+
try { CopyRegion(frame, cursorSavedRect, cursorSaved, false); } catch { }
|
|
642
|
+
cursorSavedRect = Rectangle.Empty;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** Chép từng hàng giữa một vùng của bitmap 32bpp và mảng liền (hàng nối tiếp, mỗi hàng area.Width * 4 byte). */
|
|
646
|
+
static void CopyRegion(Bitmap bmp, Rectangle area, byte[] buffer, bool toBuffer) {
|
|
647
|
+
var data = bmp.LockBits(area, toBuffer ? ImageLockMode.ReadOnly : ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
|
|
648
|
+
try {
|
|
649
|
+
int rowBytes = area.Width * 4;
|
|
650
|
+
for (int y = 0; y < area.Height; y++) {
|
|
651
|
+
var row = new IntPtr(data.Scan0.ToInt64() + (long)y * data.Stride);
|
|
652
|
+
if (toBuffer) Marshal.Copy(row, buffer, y * rowBytes, rowBytes);
|
|
653
|
+
else Marshal.Copy(buffer, y * rowBytes, row, rowBytes);
|
|
654
|
+
}
|
|
655
|
+
} finally {
|
|
656
|
+
bmp.UnlockBits(data);
|
|
610
657
|
}
|
|
611
|
-
return cursorBuffer;
|
|
612
658
|
}
|
|
613
659
|
|
|
614
660
|
/** Song tuyến tính chia theo hàng trên nhiều nhân: GDI+ DrawImage chỉ chạy một nhân, đo 14 ms mỗi khung từ 1080p xuống 1280, là khâu đắt nhất của bộ quay. */
|
|
@@ -738,6 +784,143 @@ namespace AivinDesktopCast {
|
|
|
738
784
|
}
|
|
739
785
|
}
|
|
740
786
|
|
|
787
|
+
/**
|
|
788
|
+
* Người ngồi trước máy được ưu tiên chuột (12/11/2026: chủ máy không di được chuột vì một thiết bị khác đang mở xem màn hình, mỗi lần rê ở
|
|
789
|
+
* đó là con trỏ bị kéo về). Phiên ghi lại vị trí con trỏ sau mỗi lần tự đặt; con trỏ đã rời chỗ đó thì người ở máy vừa dùng chuột, thao tác
|
|
790
|
+
* chuột từ xa bị bỏ trong HOLD_MS kể từ lần dời gần nhất. Nhả nút vẫn chạy để không kẹt nút.
|
|
791
|
+
*/
|
|
792
|
+
public static class LocalPointerGuard {
|
|
793
|
+
public const int TOLERANCE_PX = 4;
|
|
794
|
+
public const int HOLD_MS = 1500;
|
|
795
|
+
static readonly object gate = new object();
|
|
796
|
+
static readonly System.Diagnostics.Stopwatch clock = System.Diagnostics.Stopwatch.StartNew();
|
|
797
|
+
static bool placed;
|
|
798
|
+
static int lastX, lastY;
|
|
799
|
+
static long localUntil = -1;
|
|
800
|
+
|
|
801
|
+
/** Đồng hồ chung của luồng đọc lệnh và luồng canh con trỏ ẩn. */
|
|
802
|
+
public static long Now() { return clock.ElapsedMilliseconds; }
|
|
803
|
+
|
|
804
|
+
public static void Reset() { lock (gate) { placed = false; localUntil = -1; } }
|
|
805
|
+
|
|
806
|
+
/** Gọi ngay sau khi phiên tự đặt con trỏ, với vị trí đọc lại (Windows có thể kẹp vào mép màn hình). */
|
|
807
|
+
public static void Placed(int x, int y) { lock (gate) { placed = true; lastX = x; lastY = y; } }
|
|
808
|
+
|
|
809
|
+
/** Đúng khi người ở máy vừa dùng chuột (x, y: vị trí hiện tại; nowMs: đồng hồ tăng dần). */
|
|
810
|
+
public static bool LocalActive(int x, int y, long nowMs) {
|
|
811
|
+
lock (gate) {
|
|
812
|
+
if (placed && (Math.Abs(x - lastX) > TOLERANCE_PX || Math.Abs(y - lastY) > TOLERANCE_PX)) localUntil = nowMs + HOLD_MS;
|
|
813
|
+
lastX = x;
|
|
814
|
+
lastY = y;
|
|
815
|
+
return localUntil >= 0 && nowMs < localUntil;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Ẩn con trỏ trên màn hình máy trong lúc người xem từ xa đang điều khiển chuột (12/11/2026: chủ máy thấy con trỏ nhảy theo người xem,
|
|
822
|
+
* khó chịu). Windows không có lệnh ẩn con trỏ toàn máy: thay các con trỏ chuẩn bằng con trỏ trong suốt (SetSystemCursor), trả lại bằng
|
|
823
|
+
* SPI_SETCURSORS (nạp lại bộ con trỏ người dùng đang chọn). Hiện lại khi người ở máy động vào chuột, khi người xem thôi thao tác chuột
|
|
824
|
+
* IDLE_SHOW_MS, khi phiên dừng hay tiến trình thoát; đầu mỗi phiên cũng trả lại một lần phòng phiên trước chết giữa chừng (CLI cũng tự trả
|
|
825
|
+
* khi tiến trình này chết). Người xem vẫn thấy hình con trỏ thật nhờ bản sao chụp trước khi ẩn (ShapeOf). Con trỏ riêng của ứng dụng
|
|
826
|
+
* (không thuộc bộ chuẩn) không ẩn được.
|
|
827
|
+
*/
|
|
828
|
+
public static class SystemCursorHider {
|
|
829
|
+
public const int IDLE_SHOW_MS = 3000;
|
|
830
|
+
const int POLL_MS = 50;
|
|
831
|
+
const uint SPI_SETCURSORS = 0x0057;
|
|
832
|
+
static readonly uint[] Ids = { 32512, 32513, 32514, 32515, 32516, 32642, 32643, 32644, 32645, 32646, 32648, 32649, 32650, 32651, 32671, 32672 };
|
|
833
|
+
static readonly object gate = new object();
|
|
834
|
+
static readonly Dictionary<IntPtr, IntPtr> originals = new Dictionary<IntPtr, IntPtr>();
|
|
835
|
+
static volatile bool hidden;
|
|
836
|
+
static long lastRemoteMs;
|
|
837
|
+
static Thread watcher;
|
|
838
|
+
|
|
839
|
+
public static bool Hidden { get { return hidden; } }
|
|
840
|
+
|
|
841
|
+
public static void Init() {
|
|
842
|
+
Restore();
|
|
843
|
+
AppDomain.CurrentDomain.ProcessExit += delegate { Show(); };
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** Người xem vừa thao tác chuột (đã qua LocalPointerGuard): ẩn con trỏ trên máy nếu chưa ẩn. */
|
|
847
|
+
public static void RemoteInput() {
|
|
848
|
+
lock (gate) {
|
|
849
|
+
lastRemoteMs = LocalPointerGuard.Now();
|
|
850
|
+
if (hidden) return;
|
|
851
|
+
for (int i = 0; i < Ids.Length; i++) {
|
|
852
|
+
IntPtr sys = Native.LoadCursor(IntPtr.Zero, new IntPtr((int)Ids[i]));
|
|
853
|
+
if (sys == IntPtr.Zero) continue;
|
|
854
|
+
if (!originals.ContainsKey(sys)) {
|
|
855
|
+
IntPtr copy = Native.CopyIcon(sys);
|
|
856
|
+
if (copy != IntPtr.Zero) originals[sys] = copy;
|
|
857
|
+
}
|
|
858
|
+
IntPtr blank = Blank();
|
|
859
|
+
if (blank != IntPtr.Zero && !Native.SetSystemCursor(blank, Ids[i])) Native.DestroyCursor(blank);
|
|
860
|
+
}
|
|
861
|
+
hidden = true;
|
|
862
|
+
Notify(true);
|
|
863
|
+
if (watcher == null) {
|
|
864
|
+
watcher = new Thread(Watch);
|
|
865
|
+
watcher.IsBackground = true;
|
|
866
|
+
watcher.Start();
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
public static void Show() {
|
|
872
|
+
lock (gate) {
|
|
873
|
+
if (!hidden) return;
|
|
874
|
+
hidden = false;
|
|
875
|
+
Restore();
|
|
876
|
+
Notify(false);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** Hình thật của con trỏ để gửi / vẽ cho người xem trong lúc con trỏ trên máy đang bị ẩn. */
|
|
881
|
+
public static IntPtr ShapeOf(IntPtr handle) {
|
|
882
|
+
IntPtr copy;
|
|
883
|
+
lock (gate) {
|
|
884
|
+
if (hidden && originals.TryGetValue(handle, out copy)) return copy;
|
|
885
|
+
}
|
|
886
|
+
return handle;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
static void Restore() {
|
|
890
|
+
try { Native.SystemParametersInfo(SPI_SETCURSORS, 0, IntPtr.Zero, 0); } catch { }
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
static IntPtr Blank() {
|
|
894
|
+
var and = new byte[32 * 32 / 8];
|
|
895
|
+
for (int i = 0; i < and.Length; i++) and[i] = 0xFF;
|
|
896
|
+
return Native.CreateCursor(IntPtr.Zero, 0, 0, 32, 32, and, new byte[32 * 32 / 8]);
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
static void Watch() {
|
|
900
|
+
while (true) {
|
|
901
|
+
Thread.Sleep(POLL_MS);
|
|
902
|
+
if (!hidden) continue;
|
|
903
|
+
try {
|
|
904
|
+
Native.POINT p;
|
|
905
|
+
bool local = Native.GetCursorPos(out p) && LocalPointerGuard.LocalActive(p.x, p.y, LocalPointerGuard.Now());
|
|
906
|
+
long idle;
|
|
907
|
+
lock (gate) idle = LocalPointerGuard.Now() - lastRemoteMs;
|
|
908
|
+
if (local || idle > IDLE_SHOW_MS) Show();
|
|
909
|
+
} catch {
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
static void Notify(bool value) {
|
|
915
|
+
try {
|
|
916
|
+
var msg = Out.Msg("cursor_hidden");
|
|
917
|
+
msg["hidden"] = value;
|
|
918
|
+
Out.Send(msg);
|
|
919
|
+
} catch {
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
741
924
|
public static class CastHost {
|
|
742
925
|
const long JPEG_SMALL_CHANGE_INTERVAL_MS = 200;
|
|
743
926
|
const double JPEG_BIG_CHANGE_DIFF = 4.5;
|
|
@@ -757,11 +940,29 @@ namespace AivinDesktopCast {
|
|
|
757
940
|
static volatile int targetMaxFps = 15;
|
|
758
941
|
static volatile int targetMaxWidth = 1366;
|
|
759
942
|
static volatile int targetQuality = 65;
|
|
943
|
+
// Ảnh mở màn (12/11/2026): một ảnh JPEG nét lúc mở phiên trên mạng đã biết là tốt, người xem giữ trên khung tới khi video đủ nét.
|
|
944
|
+
// 0 = không có; gửi xong một lần thì về 0.
|
|
945
|
+
static volatile int leadInWidth = 0;
|
|
946
|
+
static volatile int leadInQuality = 80;
|
|
947
|
+
// Thao tác vừa thực thi (bấm, phím, cuộn...) đánh thức vòng quay đang ngủ giữa hai khung: chụp ngay phản hồi của máy thay vì chờ hết
|
|
948
|
+
// nhịp khung (66 ms ở 15 khung/giây, 125 ms ở 8). Hai lần gửi vẫn cách nhau ít nhất INPUT_WAKE_MIN_GAP_MS (12/11/2026).
|
|
949
|
+
static readonly AutoResetEvent inputWake = new AutoResetEvent(false);
|
|
950
|
+
const int INPUT_WAKE_MIN_GAP_MS = 16;
|
|
951
|
+
// Đo bấm -> thấy hình đổi (12/11/2026): số thao tác (iseq) người xem gửi kèm, vừa thực thi xong thì ghi lại; khung đầu tiên có thay đổi
|
|
952
|
+
// sau đó mang iseq + iseq_ms (từ lúc thực thi tới lúc gửi khung: ứng dụng phản hồi + chụp) để người xem tính độ trễ.
|
|
953
|
+
static int inputEchoSeq = 0;
|
|
954
|
+
static long inputEchoAtMs = 0;
|
|
955
|
+
static readonly System.Diagnostics.Stopwatch echoClock = System.Diagnostics.Stopwatch.StartNew();
|
|
760
956
|
static bool lastSecureDesktop = false;
|
|
761
957
|
static long lastScreensMs = -SCREENS_REFRESH_MS;
|
|
762
958
|
|
|
763
959
|
public static void Run(string argsJson) {
|
|
764
960
|
Native.UsePerMonitorDpi();
|
|
961
|
+
// Máy bận (đo 13/11/2026: CPU 50–95 %) thì luồng quay mức thường bị giành CPU, khung tới chậm từng đợt; trên mức thường vẫn nhường ứng dụng
|
|
962
|
+
// người dùng đang dùng (không lên High / Realtime).
|
|
963
|
+
try { System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.AboveNormal; } catch { }
|
|
964
|
+
try { Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; } catch { }
|
|
965
|
+
SystemCursorHider.Init();
|
|
765
966
|
Native.timeBeginPeriod(1);
|
|
766
967
|
var a = Out.Parse(argsJson);
|
|
767
968
|
long inputTag;
|
|
@@ -859,6 +1060,7 @@ namespace AivinDesktopCast {
|
|
|
859
1060
|
lastJpegThumb = CastScreen.Thumb(source.Frame);
|
|
860
1061
|
}
|
|
861
1062
|
long sendStartMs = clock.ElapsedMilliseconds;
|
|
1063
|
+
frameEchoSeq = sendChange ? Interlocked.Exchange(ref inputEchoSeq, 0) : 0;
|
|
862
1064
|
SendFrame(source.Frame, cursorInFrame, withJpeg, nowMs, hostStats);
|
|
863
1065
|
hostStats.AddLoad(clock.ElapsedMilliseconds - sendStartMs);
|
|
864
1066
|
}
|
|
@@ -869,8 +1071,12 @@ namespace AivinDesktopCast {
|
|
|
869
1071
|
}
|
|
870
1072
|
|
|
871
1073
|
long sleepMs = targetFrameInterval - (clock.ElapsedMilliseconds - frameStartMs);
|
|
872
|
-
if (sleepMs > 0)
|
|
873
|
-
|
|
1074
|
+
if (sleepMs > 0) {
|
|
1075
|
+
if (inputWake.WaitOne((int)sleepMs)) {
|
|
1076
|
+
long gapMs = INPUT_WAKE_MIN_GAP_MS - (clock.ElapsedMilliseconds - lastSendMs);
|
|
1077
|
+
if (gapMs > 0) Thread.Sleep((int)gapMs);
|
|
1078
|
+
}
|
|
1079
|
+
} else if (!source.UsingDxgi) Thread.Sleep(1);
|
|
874
1080
|
}
|
|
875
1081
|
source.Dispose();
|
|
876
1082
|
StopInput();
|
|
@@ -880,11 +1086,21 @@ namespace AivinDesktopCast {
|
|
|
880
1086
|
Out.Send(stoppedMsg);
|
|
881
1087
|
}
|
|
882
1088
|
|
|
1089
|
+
static int frameEchoSeq = 0;
|
|
1090
|
+
|
|
883
1091
|
static void SendFrame(Bitmap frame, bool cursorInFrame, bool jpegMode, long nowMs, HostStats hostStats) {
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
1092
|
+
// Con trỏ vẽ thẳng lên khung rồi trả lại vùng đó ngay sau khi gửi (CastScreen.DrawCursorInPlace).
|
|
1093
|
+
bool drawn = cursorInFrame && CastScreen.DrawCursorInPlace(frame, currentBounds);
|
|
1094
|
+
try {
|
|
1095
|
+
SendFrameCore(frame, jpegMode, nowMs, hostStats);
|
|
1096
|
+
} finally {
|
|
1097
|
+
if (drawn) CastScreen.RestoreCursorPatch(frame);
|
|
887
1098
|
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
static void SendFrameCore(Bitmap frame, bool jpegMode, long nowMs, HostStats hostStats) {
|
|
1102
|
+
Bitmap encodeBmp = frame;
|
|
1103
|
+
if (leadInWidth > 0) SendLeadIn(encodeBmp, nowMs);
|
|
888
1104
|
if (encodeBmp.Width > targetMaxWidth) {
|
|
889
1105
|
encodeBmp = CastScreen.Scale(encodeBmp, targetMaxWidth);
|
|
890
1106
|
}
|
|
@@ -911,10 +1127,34 @@ namespace AivinDesktopCast {
|
|
|
911
1127
|
}
|
|
912
1128
|
frameMsg["ts"] = nowMs;
|
|
913
1129
|
frameMsg["stats"] = hostStats.Snapshot(nowMs);
|
|
1130
|
+
if (frameEchoSeq > 0) {
|
|
1131
|
+
frameMsg["iseq"] = frameEchoSeq;
|
|
1132
|
+
frameMsg["iseq_ms"] = echoClock.ElapsedMilliseconds - Interlocked.Read(ref inputEchoAtMs);
|
|
1133
|
+
frameEchoSeq = 0;
|
|
1134
|
+
}
|
|
914
1135
|
if (lastSecureDesktop) frameMsg["secureDesktop"] = true;
|
|
915
1136
|
Out.Send(frameMsg);
|
|
916
1137
|
}
|
|
917
1138
|
|
|
1139
|
+
/** Ảnh mở màn: ảnh đầy đủ ở độ rộng xin (không quá màn hình thật), chất lượng cao, gửi một lần, đánh dấu lead_in để người xem giữ lại. */
|
|
1140
|
+
static void SendLeadIn(Bitmap src, long nowMs) {
|
|
1141
|
+
int lw = leadInWidth;
|
|
1142
|
+
leadInWidth = 0;
|
|
1143
|
+
Bitmap leadBmp = src.Width > lw ? CastScreen.Scale(src, lw) : src;
|
|
1144
|
+
var leadMsg = Out.Msg("frame");
|
|
1145
|
+
leadMsg["image"] = Convert.ToBase64String(CastScreen.Jpeg(leadBmp, leadInQuality));
|
|
1146
|
+
leadMsg["width"] = leadBmp.Width;
|
|
1147
|
+
leadMsg["height"] = leadBmp.Height;
|
|
1148
|
+
leadMsg["screenWidth"] = currentBounds.Width;
|
|
1149
|
+
leadMsg["screenHeight"] = currentBounds.Height;
|
|
1150
|
+
leadMsg["screenX"] = currentBounds.X;
|
|
1151
|
+
leadMsg["screenY"] = currentBounds.Y;
|
|
1152
|
+
leadMsg["monitor"] = currentMonitor;
|
|
1153
|
+
leadMsg["ts"] = nowMs;
|
|
1154
|
+
leadMsg["lead_in"] = true;
|
|
1155
|
+
Out.Send(leadMsg);
|
|
1156
|
+
}
|
|
1157
|
+
|
|
918
1158
|
/**
|
|
919
1159
|
* Đọc lệnh từ stdin trên một luồng, thực thi trên luồng khác (ExecuteInputLoop). Trước đây đọc + thực thi chung một luồng: lệnh "stop"
|
|
920
1160
|
* nằm sau các thao tác còn xếp hàng (một lần kéo thả, gõ dài…) nên chúng vẫn chạy hết sau khi chủ máy bấm ngắt. Nay đọc thấy "stop" (hoặc
|
|
@@ -956,7 +1196,21 @@ namespace AivinDesktopCast {
|
|
|
956
1196
|
cmd = inputQueue.Dequeue();
|
|
957
1197
|
}
|
|
958
1198
|
string op = cmd.ContainsKey("op") ? Convert.ToString(cmd["op"]) : "";
|
|
959
|
-
if (op == "input")
|
|
1199
|
+
if (op == "input") {
|
|
1200
|
+
HandleInput(cmd);
|
|
1201
|
+
string act = cmd.ContainsKey("action") ? Convert.ToString(cmd["action"]) : "";
|
|
1202
|
+
if (cmd.ContainsKey("iseq")) {
|
|
1203
|
+
try {
|
|
1204
|
+
int seq = Convert.ToInt32(cmd["iseq"]);
|
|
1205
|
+
if (seq > 0) {
|
|
1206
|
+
Interlocked.Exchange(ref inputEchoAtMs, echoClock.ElapsedMilliseconds);
|
|
1207
|
+
Interlocked.Exchange(ref inputEchoSeq, seq);
|
|
1208
|
+
}
|
|
1209
|
+
} catch { }
|
|
1210
|
+
}
|
|
1211
|
+
// Di chuột: con trỏ người xem tự vẽ, không cần khung ngay; đồng bộ clipboard không đổi màn hình.
|
|
1212
|
+
if (act != "move" && act != "clipboard") inputWake.Set();
|
|
1213
|
+
}
|
|
960
1214
|
else if (op == "config") HandleConfig(cmd);
|
|
961
1215
|
else if (op == "refresh") refreshRequested = true;
|
|
962
1216
|
}
|
|
@@ -965,6 +1219,7 @@ namespace AivinDesktopCast {
|
|
|
965
1219
|
} finally {
|
|
966
1220
|
// Dừng phiên hoặc daemon chết (stdin đóng) lúc người xem đang kéo: không để nút chuột / phím bổ trợ kẹt xuống trên máy.
|
|
967
1221
|
ReleaseHeldInput();
|
|
1222
|
+
SystemCursorHider.Show();
|
|
968
1223
|
}
|
|
969
1224
|
}
|
|
970
1225
|
|
|
@@ -986,6 +1241,15 @@ namespace AivinDesktopCast {
|
|
|
986
1241
|
targetMaxWidth = w;
|
|
987
1242
|
}
|
|
988
1243
|
}
|
|
1244
|
+
if (cmd.ContainsKey("lead_in_width")) {
|
|
1245
|
+
int lw = Convert.ToInt32(cmd["lead_in_width"]);
|
|
1246
|
+
int lq = cmd.ContainsKey("lead_in_quality") ? Convert.ToInt32(cmd["lead_in_quality"]) : 80;
|
|
1247
|
+
if (lw >= 640 && lw <= 2560 && lq >= 10 && lq <= 95) {
|
|
1248
|
+
leadInQuality = lq;
|
|
1249
|
+
leadInWidth = lw;
|
|
1250
|
+
refreshRequested = true;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
989
1253
|
if (cmd.ContainsKey("jpeg") && cmd["jpeg"] is bool) {
|
|
990
1254
|
jpegEnabled = (bool)cmd["jpeg"];
|
|
991
1255
|
refreshRequested = true;
|
|
@@ -1127,6 +1391,19 @@ namespace AivinDesktopCast {
|
|
|
1127
1391
|
// Nút + phím bổ trợ đang giữ qua mousedown (chỉ luồng đọc lệnh đụng tới). Gói mouseup không đủ để biết cần nhả gì: người xem có thể thả Ctrl trước khi thả chuột.
|
|
1128
1392
|
static readonly List<int> heldButtons = new List<int>();
|
|
1129
1393
|
static readonly List<byte> heldModifiers = new List<byte>();
|
|
1394
|
+
// Thao tác chuột từ xa bị bỏ khi người ở máy đang dùng chuột (LocalPointerGuard). Nhả nút xử lý riêng.
|
|
1395
|
+
static readonly HashSet<string> PointerActions = new HashSet<string> { "move", "click", "dblclick", "rightclick", "mousedown", "scroll" };
|
|
1396
|
+
|
|
1397
|
+
static void PlaceCursor(int x, int y) {
|
|
1398
|
+
Native.SetCursorPos(x, y);
|
|
1399
|
+
Native.POINT p;
|
|
1400
|
+
if (Native.GetCursorPos(out p)) LocalPointerGuard.Placed(p.x, p.y);
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
static bool LocalPointerActive() {
|
|
1404
|
+
Native.POINT p;
|
|
1405
|
+
return Native.GetCursorPos(out p) && LocalPointerGuard.LocalActive(p.x, p.y, LocalPointerGuard.Now());
|
|
1406
|
+
}
|
|
1130
1407
|
|
|
1131
1408
|
static void MouseButton(int button, bool down) {
|
|
1132
1409
|
uint flag = button == 2 ? (down ? Native.MOUSEEVENTF_RIGHTDOWN : Native.MOUSEEVENTF_RIGHTUP)
|
|
@@ -1169,11 +1446,16 @@ namespace AivinDesktopCast {
|
|
|
1169
1446
|
targetY += (int)Math.Round((ry / currentImageHeight) * currentBounds.Height);
|
|
1170
1447
|
}
|
|
1171
1448
|
|
|
1449
|
+
bool pointer = PointerActions.Contains(action);
|
|
1450
|
+
bool localPointer = (pointer || action.Equals("mouseup")) && LocalPointerActive();
|
|
1451
|
+
if (pointer && localPointer) return;
|
|
1452
|
+
if (pointer) SystemCursorHider.RemoteInput();
|
|
1453
|
+
|
|
1172
1454
|
if (action == "move") {
|
|
1173
|
-
|
|
1455
|
+
PlaceCursor(targetX, targetY);
|
|
1174
1456
|
} else if (action == "click") {
|
|
1175
1457
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
1176
|
-
|
|
1458
|
+
PlaceCursor(targetX, targetY);
|
|
1177
1459
|
Thread.Sleep(10);
|
|
1178
1460
|
PressModifiers(mods);
|
|
1179
1461
|
try {
|
|
@@ -1195,7 +1477,7 @@ namespace AivinDesktopCast {
|
|
|
1195
1477
|
}
|
|
1196
1478
|
if (button == 0) ProbeInputFocus();
|
|
1197
1479
|
} else if (action == "dblclick") {
|
|
1198
|
-
|
|
1480
|
+
PlaceCursor(targetX, targetY);
|
|
1199
1481
|
Thread.Sleep(10);
|
|
1200
1482
|
PressModifiers(mods);
|
|
1201
1483
|
try {
|
|
@@ -1208,7 +1490,7 @@ namespace AivinDesktopCast {
|
|
|
1208
1490
|
ReleaseModifiers(mods);
|
|
1209
1491
|
}
|
|
1210
1492
|
} else if (action == "rightclick") {
|
|
1211
|
-
|
|
1493
|
+
PlaceCursor(targetX, targetY);
|
|
1212
1494
|
Thread.Sleep(10);
|
|
1213
1495
|
PressModifiers(mods);
|
|
1214
1496
|
try {
|
|
@@ -1220,7 +1502,7 @@ namespace AivinDesktopCast {
|
|
|
1220
1502
|
}
|
|
1221
1503
|
} else if (action == "mousedown") {
|
|
1222
1504
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
1223
|
-
|
|
1505
|
+
PlaceCursor(targetX, targetY);
|
|
1224
1506
|
var newMods = new List<byte>();
|
|
1225
1507
|
for (int i = 0; i < mods.Count; i++) {
|
|
1226
1508
|
if (!heldModifiers.Contains(mods[i])) newMods.Add(mods[i]);
|
|
@@ -1232,7 +1514,9 @@ namespace AivinDesktopCast {
|
|
|
1232
1514
|
} else if (action == "mouseup") {
|
|
1233
1515
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
1234
1516
|
// Gói không toạ độ = chỉ nhả tại chỗ (AI đang bấm trên máy): không kéo con trỏ đi.
|
|
1235
|
-
|
|
1517
|
+
// Người ở máy đang dùng chuột mà phiên không giữ nút này (lần bấm từ xa đã bị bỏ): không thả nút người đó có thể đang giữ.
|
|
1518
|
+
if (localPointer && !heldButtons.Contains(button)) return;
|
|
1519
|
+
if (!localPointer && (cmd.ContainsKey("rx") || cmd.ContainsKey("x"))) PlaceCursor(targetX, targetY);
|
|
1236
1520
|
MouseButton(button, false);
|
|
1237
1521
|
heldButtons.Remove(button);
|
|
1238
1522
|
if (heldButtons.Count == 0) ReleaseHeldModifiers();
|
|
@@ -1240,7 +1524,7 @@ namespace AivinDesktopCast {
|
|
|
1240
1524
|
} else if (action == "scroll") {
|
|
1241
1525
|
int deltaY = cmd.ContainsKey("deltaY") ? Convert.ToInt32(cmd["deltaY"]) : 0;
|
|
1242
1526
|
int deltaX = cmd.ContainsKey("deltaX") ? Convert.ToInt32(cmd["deltaX"]) : 0;
|
|
1243
|
-
|
|
1527
|
+
PlaceCursor(targetX, targetY);
|
|
1244
1528
|
PressModifiers(mods);
|
|
1245
1529
|
try {
|
|
1246
1530
|
if (deltaY != 0) {
|
|
@@ -19,11 +19,54 @@ const MAX_POINTER_MESSAGE_BYTES = 512;
|
|
|
19
19
|
const MAX_CURSOR_SHAPES = 64;
|
|
20
20
|
/** Thử nối lại khi peer hỏng hẳn (`failed`): dựng peer mới, cùng người xem; hết lượt thì ở lại JPEG. Peer nối được thì đặt lại. */
|
|
21
21
|
const RECONNECT_DELAYS_MS = [1000, 3000, 8000];
|
|
22
|
+
/**
|
|
23
|
+
* Báo người xem ước lượng băng thông của bộ gửi (`availableOutgoingBitrate`, kbps) theo nhịp này. FE dựa vào đó để lúc mở phiên nhảy thẳng
|
|
24
|
+
* lên bậc nét mạng chịu được thay vì chờ QP: vài giây đầu QP còn ~105 cả trên mạng tốt, còn ước lượng lên trần sau ~2 s (đo trong máy
|
|
25
|
+
* 11/11/2026); đường yếu thì ước lượng ở thấp, FE không nhảy.
|
|
26
|
+
*/
|
|
27
|
+
const BWE_REPORT_MS = 1000;
|
|
28
|
+
|
|
29
|
+
/** Ước lượng băng thông bộ gửi của cặp đường đang dùng (kbps), không có thì `null`. */
|
|
30
|
+
export function outgoingBitrateKbps(report) {
|
|
31
|
+
const stats = [];
|
|
32
|
+
report?.forEach?.((s) => stats.push(s));
|
|
33
|
+
const selected = stats.find(s => s.type === 'transport' && s.selectedCandidatePairId)?.selectedCandidatePairId;
|
|
34
|
+
const pair = stats.find(s => s.type === 'candidate-pair' && s.id === selected && Number.isFinite(s.availableOutgoingBitrate))
|
|
35
|
+
|| stats.find(s => s.type === 'candidate-pair' && s.nominated && Number.isFinite(s.availableOutgoingBitrate));
|
|
36
|
+
return pair && pair.availableOutgoingBitrate > 0 ? Math.round(pair.availableOutgoingBitrate / 1000) : null;
|
|
37
|
+
}
|
|
22
38
|
|
|
23
39
|
/**
|
|
24
40
|
* Ghi băng thông video vào SDP answer (bên gửi đọc từ đây): mặc định libwebrtc trần ~2,5 Mbps, cuộn trang chữ 1440x810 chỉ còn ~7,5 khung/giây
|
|
25
41
|
* (đo 03/11/2026). `{ start_kbps, min_kbps, max_kbps }` do BE gửi (`config/device_agent.json`); thiếu thì giữ nguyên SDP.
|
|
26
42
|
*/
|
|
43
|
+
/**
|
|
44
|
+
* Xếp codec hình trong offer theo `codecs` máy chủ gửi (vd `['AV1', 'VP8']`): người xem chọn codec đầu tiên trong danh sách mà nó giải mã được,
|
|
45
|
+
* không được thì rơi về codec sau (Safari đời cũ không có AV1 → VP8). Đo 12/11/2026 (Chromium, đường giới hạn): AV1 cần khoảng nửa băng
|
|
46
|
+
* thông VP8 ở cùng số khung/giây, đường 1 Mbps nét ở giây 3 thay vì 14; VP9 ở chế độ màn hình bị libwebrtc giới hạn 5 khung/giây nên không dùng.
|
|
47
|
+
* Codec không có trong offer thì bỏ qua; danh sách rỗng thì giữ nguyên.
|
|
48
|
+
*/
|
|
49
|
+
export function preferVideoCodecs(sdp, codecs) {
|
|
50
|
+
if (!sdp || !Array.isArray(codecs) || !codecs.length) return sdp;
|
|
51
|
+
const eol = sdp.includes('\r\n') ? '\r\n' : '\n';
|
|
52
|
+
const lines = sdp.split(/\r?\n/);
|
|
53
|
+
const wanted = [];
|
|
54
|
+
for (const name of codecs) {
|
|
55
|
+
if (typeof name !== 'string' || !/^[A-Za-z0-9]+$/.test(name)) continue;
|
|
56
|
+
for (const line of lines) {
|
|
57
|
+
const m = /^a=rtpmap:(\d+) ([^/]+)\//.exec(line);
|
|
58
|
+
if (m && m[2].toUpperCase() === name.toUpperCase() && !wanted.includes(m[1])) wanted.push(m[1]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (!wanted.length) return sdp;
|
|
62
|
+
return lines.map((line) => {
|
|
63
|
+
if (!line.startsWith('m=video ')) return line;
|
|
64
|
+
const parts = line.split(' ');
|
|
65
|
+
const rest = parts.slice(3);
|
|
66
|
+
return [...parts.slice(0, 3), ...wanted.filter((pt) => rest.includes(pt)), ...rest.filter((pt) => !wanted.includes(pt))].join(' ');
|
|
67
|
+
}).join(eol);
|
|
68
|
+
}
|
|
69
|
+
|
|
27
70
|
export function withVideoBitrate(sdp, bitrate) {
|
|
28
71
|
const params = [['x-google-start-bitrate', bitrate?.start_kbps], ['x-google-min-bitrate', bitrate?.min_kbps], ['x-google-max-bitrate', bitrate?.max_kbps]]
|
|
29
72
|
.filter(([, v]) => Number.isFinite(v) && v > 0)
|
|
@@ -96,12 +139,12 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
96
139
|
if (peer.retryTimer || peer.attempt >= RECONNECT_DELAYS_MS.length) return;
|
|
97
140
|
peer.retryTimer = setTimeout(() => {
|
|
98
141
|
if (peers.get(peer.viewerId) !== peer) return;
|
|
99
|
-
start({ sessionId: peer.sessionId, viewerId: peer.viewerId, iceServers: peer.iceServers, videoBitrate: peer.videoBitrate, audio: peer.audioEnabled, attempt: peer.attempt + 1 }).catch(() => false);
|
|
142
|
+
start({ sessionId: peer.sessionId, viewerId: peer.viewerId, iceServers: peer.iceServers, videoBitrate: peer.videoBitrate, videoCodecs: peer.videoCodecs, audio: peer.audioEnabled, attempt: peer.attempt + 1 }).catch(() => false);
|
|
100
143
|
}, RECONNECT_DELAYS_MS[peer.attempt]);
|
|
101
144
|
peer.retryTimer.unref?.();
|
|
102
145
|
}
|
|
103
146
|
|
|
104
|
-
async function start({ sessionId, viewerId, iceServers = [], videoBitrate = null, audio = true, attempt = 0 }) {
|
|
147
|
+
async function start({ sessionId, viewerId, iceServers = [], videoBitrate = null, videoCodecs = null, audio = true, attempt = 0 }) {
|
|
105
148
|
close(viewerId);
|
|
106
149
|
const wrtc = await load();
|
|
107
150
|
const RTCPeerConnection = wrtc?.RTCPeerConnection || wrtc?.default?.RTCPeerConnection;
|
|
@@ -125,7 +168,7 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
125
168
|
pc, channel, inputChannel, fileChannel, pointerChannel, pointerSeq: 0,
|
|
126
169
|
track, video: !!track,
|
|
127
170
|
audioTrack, audio: !!audioTrack, audioEnabled: audio !== false,
|
|
128
|
-
sessionId, viewerId, iceServers, videoBitrate, attempt, retryTimer: null, open: false, dropped: 0,
|
|
171
|
+
sessionId, viewerId, iceServers, videoBitrate, videoCodecs, attempt, retryTimer: null, bweTimer: null, open: false, dropped: 0,
|
|
129
172
|
};
|
|
130
173
|
fileChannel.binaryType = 'arraybuffer';
|
|
131
174
|
fileChannel.onmessage = ({ data }) => {
|
|
@@ -179,9 +222,19 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
179
222
|
};
|
|
180
223
|
peers.set(viewerId, peer);
|
|
181
224
|
channel.binaryType = 'arraybuffer';
|
|
225
|
+
const reportBwe = async () => {
|
|
226
|
+
if (!peer.open || inputChannel.readyState !== 'open') return;
|
|
227
|
+
const kbps = outgoingBitrateKbps(await pc.getStats().catch(() => null));
|
|
228
|
+
if (kbps === null || peers.get(viewerId) !== peer || inputChannel.readyState !== 'open') return;
|
|
229
|
+
try { inputChannel.send(JSON.stringify({ t: 'bwe', kbps })); } catch { /* kênh vừa đóng */ }
|
|
230
|
+
};
|
|
182
231
|
const markConnected = () => {
|
|
183
232
|
peer.open = true;
|
|
184
233
|
peer.attempt = 0;
|
|
234
|
+
if (peer.video && !peer.bweTimer) {
|
|
235
|
+
peer.bweTimer = setInterval(() => { void reportBwe(); }, BWE_REPORT_MS);
|
|
236
|
+
peer.bweTimer.unref?.();
|
|
237
|
+
}
|
|
185
238
|
emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'connected', transport: 'webrtc', video: peer.video, audio: peer.audio });
|
|
186
239
|
onPeerReady(viewerId);
|
|
187
240
|
};
|
|
@@ -208,7 +261,8 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
208
261
|
markConnected();
|
|
209
262
|
}
|
|
210
263
|
};
|
|
211
|
-
|
|
264
|
+
const offer = await pc.createOffer();
|
|
265
|
+
await pc.setLocalDescription({ type: 'offer', sdp: preferVideoCodecs(offer.sdp, videoCodecs) });
|
|
212
266
|
emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'offer', sdp: pc.localDescription?.sdp, ice_servers: iceServers });
|
|
213
267
|
return true;
|
|
214
268
|
}
|
|
@@ -364,6 +418,7 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
|
|
|
364
418
|
if (!peer) return;
|
|
365
419
|
peers.delete(String(viewerId));
|
|
366
420
|
clearTimeout(peer.retryTimer);
|
|
421
|
+
clearInterval(peer.bweTimer);
|
|
367
422
|
try { peer.channel.close(); } catch { /* already closed */ }
|
|
368
423
|
try { peer.inputChannel?.close(); } catch { /* already closed */ }
|
|
369
424
|
try { peer.fileChannel?.close(); } catch { /* already closed */ }
|