@aivin-labs/cli 1.0.51 → 1.0.57
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 +2214 -2211
- 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 +1454 -1418
- package/bin/lib/remote/codingAgents.mjs +594 -293
- package/bin/lib/remote/constants.mjs +1 -1
- package/bin/lib/remote/desktop/castAuth.mjs +259 -249
- package/bin/lib/remote/desktop/castConsent.mjs +154 -90
- package/bin/lib/remote/desktop/castInput.mjs +3 -0
- package/bin/lib/remote/desktop/castTrust.mjs +184 -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 +250 -12
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
- package/bin/lib/remote/desktop/strings.mjs +138 -132
- package/bin/lib/remote/desktop/traySource.mjs +1438 -1385
- package/bin/lib/remote/gui/index.mjs +567 -485
- package/bin/lib/remote/gui/windowsHostSource.mjs +630 -33
- package/bin/lib/remote/humanInput.mjs +7 -0
- package/bin/lib/remote/localConfirm.mjs +2 -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
|
|
|
@@ -594,13 +604,14 @@ namespace AivinDesktopCast {
|
|
|
594
604
|
Native.CURSORINFO pci;
|
|
595
605
|
pci.cbSize = Marshal.SizeOf(typeof(Native.CURSORINFO));
|
|
596
606
|
if (Native.GetCursorInfo(out pci) && (pci.flags & Native.CURSOR_SHOWING) != 0) {
|
|
597
|
-
|
|
607
|
+
IntPtr shape = SystemCursorHider.ShapeOf(pci.hCursor);
|
|
608
|
+
var hot = CursorTracker.Hotspot(shape);
|
|
598
609
|
int cursorX = pci.ptScreenPos.x - hot.X - r.Left;
|
|
599
610
|
int cursorY = pci.ptScreenPos.y - hot.Y - r.Top;
|
|
600
611
|
if (cursorX >= -32 && cursorX < r.Width && cursorY >= -32 && cursorY < r.Height) {
|
|
601
612
|
IntPtr hdc = g.GetHdc();
|
|
602
613
|
try {
|
|
603
|
-
Native.DrawIcon(hdc, cursorX, cursorY,
|
|
614
|
+
Native.DrawIcon(hdc, cursorX, cursorY, shape);
|
|
604
615
|
} finally {
|
|
605
616
|
g.ReleaseHdc(hdc);
|
|
606
617
|
}
|
|
@@ -738,6 +749,143 @@ namespace AivinDesktopCast {
|
|
|
738
749
|
}
|
|
739
750
|
}
|
|
740
751
|
|
|
752
|
+
/**
|
|
753
|
+
* 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ê ở
|
|
754
|
+
* đó 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
|
|
755
|
+
* 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.
|
|
756
|
+
*/
|
|
757
|
+
public static class LocalPointerGuard {
|
|
758
|
+
public const int TOLERANCE_PX = 4;
|
|
759
|
+
public const int HOLD_MS = 1500;
|
|
760
|
+
static readonly object gate = new object();
|
|
761
|
+
static readonly System.Diagnostics.Stopwatch clock = System.Diagnostics.Stopwatch.StartNew();
|
|
762
|
+
static bool placed;
|
|
763
|
+
static int lastX, lastY;
|
|
764
|
+
static long localUntil = -1;
|
|
765
|
+
|
|
766
|
+
/** Đồng hồ chung của luồng đọc lệnh và luồng canh con trỏ ẩn. */
|
|
767
|
+
public static long Now() { return clock.ElapsedMilliseconds; }
|
|
768
|
+
|
|
769
|
+
public static void Reset() { lock (gate) { placed = false; localUntil = -1; } }
|
|
770
|
+
|
|
771
|
+
/** 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). */
|
|
772
|
+
public static void Placed(int x, int y) { lock (gate) { placed = true; lastX = x; lastY = y; } }
|
|
773
|
+
|
|
774
|
+
/** Đú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). */
|
|
775
|
+
public static bool LocalActive(int x, int y, long nowMs) {
|
|
776
|
+
lock (gate) {
|
|
777
|
+
if (placed && (Math.Abs(x - lastX) > TOLERANCE_PX || Math.Abs(y - lastY) > TOLERANCE_PX)) localUntil = nowMs + HOLD_MS;
|
|
778
|
+
lastX = x;
|
|
779
|
+
lastY = y;
|
|
780
|
+
return localUntil >= 0 && nowMs < localUntil;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* Ẩ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,
|
|
787
|
+
* 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
|
|
788
|
+
* 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
|
|
789
|
+
* 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ả
|
|
790
|
+
* 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
|
|
791
|
+
* (không thuộc bộ chuẩn) không ẩn được.
|
|
792
|
+
*/
|
|
793
|
+
public static class SystemCursorHider {
|
|
794
|
+
public const int IDLE_SHOW_MS = 3000;
|
|
795
|
+
const int POLL_MS = 50;
|
|
796
|
+
const uint SPI_SETCURSORS = 0x0057;
|
|
797
|
+
static readonly uint[] Ids = { 32512, 32513, 32514, 32515, 32516, 32642, 32643, 32644, 32645, 32646, 32648, 32649, 32650, 32651, 32671, 32672 };
|
|
798
|
+
static readonly object gate = new object();
|
|
799
|
+
static readonly Dictionary<IntPtr, IntPtr> originals = new Dictionary<IntPtr, IntPtr>();
|
|
800
|
+
static volatile bool hidden;
|
|
801
|
+
static long lastRemoteMs;
|
|
802
|
+
static Thread watcher;
|
|
803
|
+
|
|
804
|
+
public static bool Hidden { get { return hidden; } }
|
|
805
|
+
|
|
806
|
+
public static void Init() {
|
|
807
|
+
Restore();
|
|
808
|
+
AppDomain.CurrentDomain.ProcessExit += delegate { Show(); };
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** Người xem vừa thao tác chuột (đã qua LocalPointerGuard): ẩn con trỏ trên máy nếu chưa ẩn. */
|
|
812
|
+
public static void RemoteInput() {
|
|
813
|
+
lock (gate) {
|
|
814
|
+
lastRemoteMs = LocalPointerGuard.Now();
|
|
815
|
+
if (hidden) return;
|
|
816
|
+
for (int i = 0; i < Ids.Length; i++) {
|
|
817
|
+
IntPtr sys = Native.LoadCursor(IntPtr.Zero, new IntPtr((int)Ids[i]));
|
|
818
|
+
if (sys == IntPtr.Zero) continue;
|
|
819
|
+
if (!originals.ContainsKey(sys)) {
|
|
820
|
+
IntPtr copy = Native.CopyIcon(sys);
|
|
821
|
+
if (copy != IntPtr.Zero) originals[sys] = copy;
|
|
822
|
+
}
|
|
823
|
+
IntPtr blank = Blank();
|
|
824
|
+
if (blank != IntPtr.Zero && !Native.SetSystemCursor(blank, Ids[i])) Native.DestroyCursor(blank);
|
|
825
|
+
}
|
|
826
|
+
hidden = true;
|
|
827
|
+
Notify(true);
|
|
828
|
+
if (watcher == null) {
|
|
829
|
+
watcher = new Thread(Watch);
|
|
830
|
+
watcher.IsBackground = true;
|
|
831
|
+
watcher.Start();
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
public static void Show() {
|
|
837
|
+
lock (gate) {
|
|
838
|
+
if (!hidden) return;
|
|
839
|
+
hidden = false;
|
|
840
|
+
Restore();
|
|
841
|
+
Notify(false);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/** 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. */
|
|
846
|
+
public static IntPtr ShapeOf(IntPtr handle) {
|
|
847
|
+
IntPtr copy;
|
|
848
|
+
lock (gate) {
|
|
849
|
+
if (hidden && originals.TryGetValue(handle, out copy)) return copy;
|
|
850
|
+
}
|
|
851
|
+
return handle;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
static void Restore() {
|
|
855
|
+
try { Native.SystemParametersInfo(SPI_SETCURSORS, 0, IntPtr.Zero, 0); } catch { }
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
static IntPtr Blank() {
|
|
859
|
+
var and = new byte[32 * 32 / 8];
|
|
860
|
+
for (int i = 0; i < and.Length; i++) and[i] = 0xFF;
|
|
861
|
+
return Native.CreateCursor(IntPtr.Zero, 0, 0, 32, 32, and, new byte[32 * 32 / 8]);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
static void Watch() {
|
|
865
|
+
while (true) {
|
|
866
|
+
Thread.Sleep(POLL_MS);
|
|
867
|
+
if (!hidden) continue;
|
|
868
|
+
try {
|
|
869
|
+
Native.POINT p;
|
|
870
|
+
bool local = Native.GetCursorPos(out p) && LocalPointerGuard.LocalActive(p.x, p.y, LocalPointerGuard.Now());
|
|
871
|
+
long idle;
|
|
872
|
+
lock (gate) idle = LocalPointerGuard.Now() - lastRemoteMs;
|
|
873
|
+
if (local || idle > IDLE_SHOW_MS) Show();
|
|
874
|
+
} catch {
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
static void Notify(bool value) {
|
|
880
|
+
try {
|
|
881
|
+
var msg = Out.Msg("cursor_hidden");
|
|
882
|
+
msg["hidden"] = value;
|
|
883
|
+
Out.Send(msg);
|
|
884
|
+
} catch {
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
741
889
|
public static class CastHost {
|
|
742
890
|
const long JPEG_SMALL_CHANGE_INTERVAL_MS = 200;
|
|
743
891
|
const double JPEG_BIG_CHANGE_DIFF = 4.5;
|
|
@@ -757,11 +905,25 @@ namespace AivinDesktopCast {
|
|
|
757
905
|
static volatile int targetMaxFps = 15;
|
|
758
906
|
static volatile int targetMaxWidth = 1366;
|
|
759
907
|
static volatile int targetQuality = 65;
|
|
908
|
+
// Ả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.
|
|
909
|
+
// 0 = không có; gửi xong một lần thì về 0.
|
|
910
|
+
static volatile int leadInWidth = 0;
|
|
911
|
+
static volatile int leadInQuality = 80;
|
|
912
|
+
// 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
|
|
913
|
+
// 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).
|
|
914
|
+
static readonly AutoResetEvent inputWake = new AutoResetEvent(false);
|
|
915
|
+
const int INPUT_WAKE_MIN_GAP_MS = 16;
|
|
916
|
+
// Đ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
|
|
917
|
+
// 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ễ.
|
|
918
|
+
static int inputEchoSeq = 0;
|
|
919
|
+
static long inputEchoAtMs = 0;
|
|
920
|
+
static readonly System.Diagnostics.Stopwatch echoClock = System.Diagnostics.Stopwatch.StartNew();
|
|
760
921
|
static bool lastSecureDesktop = false;
|
|
761
922
|
static long lastScreensMs = -SCREENS_REFRESH_MS;
|
|
762
923
|
|
|
763
924
|
public static void Run(string argsJson) {
|
|
764
925
|
Native.UsePerMonitorDpi();
|
|
926
|
+
SystemCursorHider.Init();
|
|
765
927
|
Native.timeBeginPeriod(1);
|
|
766
928
|
var a = Out.Parse(argsJson);
|
|
767
929
|
long inputTag;
|
|
@@ -859,6 +1021,7 @@ namespace AivinDesktopCast {
|
|
|
859
1021
|
lastJpegThumb = CastScreen.Thumb(source.Frame);
|
|
860
1022
|
}
|
|
861
1023
|
long sendStartMs = clock.ElapsedMilliseconds;
|
|
1024
|
+
frameEchoSeq = sendChange ? Interlocked.Exchange(ref inputEchoSeq, 0) : 0;
|
|
862
1025
|
SendFrame(source.Frame, cursorInFrame, withJpeg, nowMs, hostStats);
|
|
863
1026
|
hostStats.AddLoad(clock.ElapsedMilliseconds - sendStartMs);
|
|
864
1027
|
}
|
|
@@ -869,8 +1032,12 @@ namespace AivinDesktopCast {
|
|
|
869
1032
|
}
|
|
870
1033
|
|
|
871
1034
|
long sleepMs = targetFrameInterval - (clock.ElapsedMilliseconds - frameStartMs);
|
|
872
|
-
if (sleepMs > 0)
|
|
873
|
-
|
|
1035
|
+
if (sleepMs > 0) {
|
|
1036
|
+
if (inputWake.WaitOne((int)sleepMs)) {
|
|
1037
|
+
long gapMs = INPUT_WAKE_MIN_GAP_MS - (clock.ElapsedMilliseconds - lastSendMs);
|
|
1038
|
+
if (gapMs > 0) Thread.Sleep((int)gapMs);
|
|
1039
|
+
}
|
|
1040
|
+
} else if (!source.UsingDxgi) Thread.Sleep(1);
|
|
874
1041
|
}
|
|
875
1042
|
source.Dispose();
|
|
876
1043
|
StopInput();
|
|
@@ -880,11 +1047,14 @@ namespace AivinDesktopCast {
|
|
|
880
1047
|
Out.Send(stoppedMsg);
|
|
881
1048
|
}
|
|
882
1049
|
|
|
1050
|
+
static int frameEchoSeq = 0;
|
|
1051
|
+
|
|
883
1052
|
static void SendFrame(Bitmap frame, bool cursorInFrame, bool jpegMode, long nowMs, HostStats hostStats) {
|
|
884
1053
|
Bitmap encodeBmp = frame;
|
|
885
1054
|
if (cursorInFrame) {
|
|
886
1055
|
encodeBmp = CastScreen.WithCursor(frame, currentBounds);
|
|
887
1056
|
}
|
|
1057
|
+
if (leadInWidth > 0) SendLeadIn(encodeBmp, nowMs);
|
|
888
1058
|
if (encodeBmp.Width > targetMaxWidth) {
|
|
889
1059
|
encodeBmp = CastScreen.Scale(encodeBmp, targetMaxWidth);
|
|
890
1060
|
}
|
|
@@ -911,10 +1081,34 @@ namespace AivinDesktopCast {
|
|
|
911
1081
|
}
|
|
912
1082
|
frameMsg["ts"] = nowMs;
|
|
913
1083
|
frameMsg["stats"] = hostStats.Snapshot(nowMs);
|
|
1084
|
+
if (frameEchoSeq > 0) {
|
|
1085
|
+
frameMsg["iseq"] = frameEchoSeq;
|
|
1086
|
+
frameMsg["iseq_ms"] = echoClock.ElapsedMilliseconds - Interlocked.Read(ref inputEchoAtMs);
|
|
1087
|
+
frameEchoSeq = 0;
|
|
1088
|
+
}
|
|
914
1089
|
if (lastSecureDesktop) frameMsg["secureDesktop"] = true;
|
|
915
1090
|
Out.Send(frameMsg);
|
|
916
1091
|
}
|
|
917
1092
|
|
|
1093
|
+
/** Ả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. */
|
|
1094
|
+
static void SendLeadIn(Bitmap src, long nowMs) {
|
|
1095
|
+
int lw = leadInWidth;
|
|
1096
|
+
leadInWidth = 0;
|
|
1097
|
+
Bitmap leadBmp = src.Width > lw ? CastScreen.Scale(src, lw) : src;
|
|
1098
|
+
var leadMsg = Out.Msg("frame");
|
|
1099
|
+
leadMsg["image"] = Convert.ToBase64String(CastScreen.Jpeg(leadBmp, leadInQuality));
|
|
1100
|
+
leadMsg["width"] = leadBmp.Width;
|
|
1101
|
+
leadMsg["height"] = leadBmp.Height;
|
|
1102
|
+
leadMsg["screenWidth"] = currentBounds.Width;
|
|
1103
|
+
leadMsg["screenHeight"] = currentBounds.Height;
|
|
1104
|
+
leadMsg["screenX"] = currentBounds.X;
|
|
1105
|
+
leadMsg["screenY"] = currentBounds.Y;
|
|
1106
|
+
leadMsg["monitor"] = currentMonitor;
|
|
1107
|
+
leadMsg["ts"] = nowMs;
|
|
1108
|
+
leadMsg["lead_in"] = true;
|
|
1109
|
+
Out.Send(leadMsg);
|
|
1110
|
+
}
|
|
1111
|
+
|
|
918
1112
|
/**
|
|
919
1113
|
* Đọ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
1114
|
* 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 +1150,21 @@ namespace AivinDesktopCast {
|
|
|
956
1150
|
cmd = inputQueue.Dequeue();
|
|
957
1151
|
}
|
|
958
1152
|
string op = cmd.ContainsKey("op") ? Convert.ToString(cmd["op"]) : "";
|
|
959
|
-
if (op == "input")
|
|
1153
|
+
if (op == "input") {
|
|
1154
|
+
HandleInput(cmd);
|
|
1155
|
+
string act = cmd.ContainsKey("action") ? Convert.ToString(cmd["action"]) : "";
|
|
1156
|
+
if (cmd.ContainsKey("iseq")) {
|
|
1157
|
+
try {
|
|
1158
|
+
int seq = Convert.ToInt32(cmd["iseq"]);
|
|
1159
|
+
if (seq > 0) {
|
|
1160
|
+
Interlocked.Exchange(ref inputEchoAtMs, echoClock.ElapsedMilliseconds);
|
|
1161
|
+
Interlocked.Exchange(ref inputEchoSeq, seq);
|
|
1162
|
+
}
|
|
1163
|
+
} catch { }
|
|
1164
|
+
}
|
|
1165
|
+
// 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.
|
|
1166
|
+
if (act != "move" && act != "clipboard") inputWake.Set();
|
|
1167
|
+
}
|
|
960
1168
|
else if (op == "config") HandleConfig(cmd);
|
|
961
1169
|
else if (op == "refresh") refreshRequested = true;
|
|
962
1170
|
}
|
|
@@ -965,6 +1173,7 @@ namespace AivinDesktopCast {
|
|
|
965
1173
|
} finally {
|
|
966
1174
|
// 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
1175
|
ReleaseHeldInput();
|
|
1176
|
+
SystemCursorHider.Show();
|
|
968
1177
|
}
|
|
969
1178
|
}
|
|
970
1179
|
|
|
@@ -986,6 +1195,15 @@ namespace AivinDesktopCast {
|
|
|
986
1195
|
targetMaxWidth = w;
|
|
987
1196
|
}
|
|
988
1197
|
}
|
|
1198
|
+
if (cmd.ContainsKey("lead_in_width")) {
|
|
1199
|
+
int lw = Convert.ToInt32(cmd["lead_in_width"]);
|
|
1200
|
+
int lq = cmd.ContainsKey("lead_in_quality") ? Convert.ToInt32(cmd["lead_in_quality"]) : 80;
|
|
1201
|
+
if (lw >= 640 && lw <= 2560 && lq >= 10 && lq <= 95) {
|
|
1202
|
+
leadInQuality = lq;
|
|
1203
|
+
leadInWidth = lw;
|
|
1204
|
+
refreshRequested = true;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
989
1207
|
if (cmd.ContainsKey("jpeg") && cmd["jpeg"] is bool) {
|
|
990
1208
|
jpegEnabled = (bool)cmd["jpeg"];
|
|
991
1209
|
refreshRequested = true;
|
|
@@ -1127,6 +1345,19 @@ namespace AivinDesktopCast {
|
|
|
1127
1345
|
// 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
1346
|
static readonly List<int> heldButtons = new List<int>();
|
|
1129
1347
|
static readonly List<byte> heldModifiers = new List<byte>();
|
|
1348
|
+
// 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.
|
|
1349
|
+
static readonly HashSet<string> PointerActions = new HashSet<string> { "move", "click", "dblclick", "rightclick", "mousedown", "scroll" };
|
|
1350
|
+
|
|
1351
|
+
static void PlaceCursor(int x, int y) {
|
|
1352
|
+
Native.SetCursorPos(x, y);
|
|
1353
|
+
Native.POINT p;
|
|
1354
|
+
if (Native.GetCursorPos(out p)) LocalPointerGuard.Placed(p.x, p.y);
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
static bool LocalPointerActive() {
|
|
1358
|
+
Native.POINT p;
|
|
1359
|
+
return Native.GetCursorPos(out p) && LocalPointerGuard.LocalActive(p.x, p.y, LocalPointerGuard.Now());
|
|
1360
|
+
}
|
|
1130
1361
|
|
|
1131
1362
|
static void MouseButton(int button, bool down) {
|
|
1132
1363
|
uint flag = button == 2 ? (down ? Native.MOUSEEVENTF_RIGHTDOWN : Native.MOUSEEVENTF_RIGHTUP)
|
|
@@ -1169,11 +1400,16 @@ namespace AivinDesktopCast {
|
|
|
1169
1400
|
targetY += (int)Math.Round((ry / currentImageHeight) * currentBounds.Height);
|
|
1170
1401
|
}
|
|
1171
1402
|
|
|
1403
|
+
bool pointer = PointerActions.Contains(action);
|
|
1404
|
+
bool localPointer = (pointer || action.Equals("mouseup")) && LocalPointerActive();
|
|
1405
|
+
if (pointer && localPointer) return;
|
|
1406
|
+
if (pointer) SystemCursorHider.RemoteInput();
|
|
1407
|
+
|
|
1172
1408
|
if (action == "move") {
|
|
1173
|
-
|
|
1409
|
+
PlaceCursor(targetX, targetY);
|
|
1174
1410
|
} else if (action == "click") {
|
|
1175
1411
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
1176
|
-
|
|
1412
|
+
PlaceCursor(targetX, targetY);
|
|
1177
1413
|
Thread.Sleep(10);
|
|
1178
1414
|
PressModifiers(mods);
|
|
1179
1415
|
try {
|
|
@@ -1195,7 +1431,7 @@ namespace AivinDesktopCast {
|
|
|
1195
1431
|
}
|
|
1196
1432
|
if (button == 0) ProbeInputFocus();
|
|
1197
1433
|
} else if (action == "dblclick") {
|
|
1198
|
-
|
|
1434
|
+
PlaceCursor(targetX, targetY);
|
|
1199
1435
|
Thread.Sleep(10);
|
|
1200
1436
|
PressModifiers(mods);
|
|
1201
1437
|
try {
|
|
@@ -1208,7 +1444,7 @@ namespace AivinDesktopCast {
|
|
|
1208
1444
|
ReleaseModifiers(mods);
|
|
1209
1445
|
}
|
|
1210
1446
|
} else if (action == "rightclick") {
|
|
1211
|
-
|
|
1447
|
+
PlaceCursor(targetX, targetY);
|
|
1212
1448
|
Thread.Sleep(10);
|
|
1213
1449
|
PressModifiers(mods);
|
|
1214
1450
|
try {
|
|
@@ -1220,7 +1456,7 @@ namespace AivinDesktopCast {
|
|
|
1220
1456
|
}
|
|
1221
1457
|
} else if (action == "mousedown") {
|
|
1222
1458
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
1223
|
-
|
|
1459
|
+
PlaceCursor(targetX, targetY);
|
|
1224
1460
|
var newMods = new List<byte>();
|
|
1225
1461
|
for (int i = 0; i < mods.Count; i++) {
|
|
1226
1462
|
if (!heldModifiers.Contains(mods[i])) newMods.Add(mods[i]);
|
|
@@ -1232,7 +1468,9 @@ namespace AivinDesktopCast {
|
|
|
1232
1468
|
} else if (action == "mouseup") {
|
|
1233
1469
|
int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
|
|
1234
1470
|
// 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
|
-
|
|
1471
|
+
// 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ữ.
|
|
1472
|
+
if (localPointer && !heldButtons.Contains(button)) return;
|
|
1473
|
+
if (!localPointer && (cmd.ContainsKey("rx") || cmd.ContainsKey("x"))) PlaceCursor(targetX, targetY);
|
|
1236
1474
|
MouseButton(button, false);
|
|
1237
1475
|
heldButtons.Remove(button);
|
|
1238
1476
|
if (heldButtons.Count == 0) ReleaseHeldModifiers();
|
|
@@ -1240,7 +1478,7 @@ namespace AivinDesktopCast {
|
|
|
1240
1478
|
} else if (action == "scroll") {
|
|
1241
1479
|
int deltaY = cmd.ContainsKey("deltaY") ? Convert.ToInt32(cmd["deltaY"]) : 0;
|
|
1242
1480
|
int deltaX = cmd.ContainsKey("deltaX") ? Convert.ToInt32(cmd["deltaX"]) : 0;
|
|
1243
|
-
|
|
1481
|
+
PlaceCursor(targetX, targetY);
|
|
1244
1482
|
PressModifiers(mods);
|
|
1245
1483
|
try {
|
|
1246
1484
|
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 */ }
|