@aivin-labs/cli 1.0.42 → 1.0.46

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.
@@ -598,5 +598,367 @@ namespace AivinDesktopCast {
598
598
  }
599
599
  }
600
600
  }
601
+
602
+ [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorCom {}
603
+
604
+ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
605
+ interface IMMDeviceEnumerator {
606
+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out IntPtr devices);
607
+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
608
+ }
609
+
610
+ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
611
+ interface IMMDevice {
612
+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object iface);
613
+ [PreserveSig] int OpenPropertyStore(int access, out IntPtr props);
614
+ [PreserveSig] int GetId(out IntPtr id);
615
+ }
616
+
617
+ [ComImport, Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
618
+ interface IAudioClient {
619
+ [PreserveSig] int Initialize(int shareMode, uint streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr sessionGuid);
620
+ [PreserveSig] int GetBufferSize(out uint frames);
621
+ [PreserveSig] int GetStreamLatency(out long latency);
622
+ [PreserveSig] int GetCurrentPadding(out uint padding);
623
+ [PreserveSig] int IsFormatSupported(int shareMode, IntPtr format, out IntPtr closest);
624
+ [PreserveSig] int GetMixFormat(out IntPtr format);
625
+ [PreserveSig] int GetDevicePeriod(out long defaultPeriod, out long minPeriod);
626
+ [PreserveSig] int Start();
627
+ [PreserveSig] int Stop();
628
+ [PreserveSig] int Reset();
629
+ [PreserveSig] int SetEventHandle(IntPtr handle);
630
+ [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service);
631
+ }
632
+
633
+ [ComImport, Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
634
+ interface IAudioCaptureClient {
635
+ [PreserveSig] int GetBuffer(out IntPtr data, out uint frames, out uint flags, out ulong devicePosition, out ulong qpcPosition);
636
+ [PreserveSig] int ReleaseBuffer(uint frames);
637
+ [PreserveSig] int GetNextPacketSize(out uint frames);
638
+ }
639
+
640
+ /**
641
+ * Thu âm thanh hệ thống (WASAPI Loopback trên loa mặc định eConsole) ở luồng nền riêng, đổi trực tiếp về PCM 16-bit 48 kHz qua
642
+ * AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, cắt từng khúc 10 ms (480 khung) đẩy qua RawPipe sang tiến trình WebRTC.
643
+ * Tự đóng khi chưa có người xem cần tiếng; tự mở lại khi người dùng đổi thiết bị phát mặc định (cắm tai nghe / loa Bluetooth).
644
+ */
645
+ public static class LoopbackAudio {
646
+ const int SAMPLE_RATE = 48000;
647
+ const int CHUNK_FRAMES = SAMPLE_RATE / 100;
648
+ const uint FLAGS_LOOPBACK_AUTOCONVERT = 0x88020000u;
649
+ const uint BUFFER_SILENT = 2;
650
+ const long RETRY_MS = 2000;
651
+ const long DEVICE_CHECK_MS = 2000;
652
+
653
+ public static volatile bool Enabled = false;
654
+
655
+ public static void SetEnabled(bool value) {
656
+ Enabled = value;
657
+ }
658
+
659
+ public static void Start() {
660
+ var t = new Thread(Loop);
661
+ t.IsBackground = true;
662
+ t.SetApartmentState(ApartmentState.MTA);
663
+ t.Start();
664
+ }
665
+
666
+ static void Loop() {
667
+ IAudioClient client = null;
668
+ IAudioCaptureClient capture = null;
669
+ string activeId = null;
670
+ int channels = 2;
671
+ byte[] chunk = new byte[CHUNK_FRAMES * 4];
672
+ int chunkFilled = 0;
673
+ byte[] scratch = new byte[0];
674
+ var clock = System.Diagnostics.Stopwatch.StartNew();
675
+ long retryAt = 0;
676
+ long nextCheckAt = 0;
677
+
678
+ try {
679
+ while (CastHost.Running) {
680
+ if (!Enabled || !RawPipe.Connected) {
681
+ if (client != null) {
682
+ CloseClient(ref client, ref capture);
683
+ activeId = null;
684
+ chunkFilled = 0;
685
+ }
686
+ Thread.Sleep(40);
687
+ continue;
688
+ }
689
+
690
+ long now = clock.ElapsedMilliseconds;
691
+ if (client == null) {
692
+ if (now < retryAt) {
693
+ Thread.Sleep(40);
694
+ continue;
695
+ }
696
+ if (!OpenClient(out client, out capture, out activeId, out channels)) {
697
+ retryAt = now + RETRY_MS;
698
+ Thread.Sleep(40);
699
+ continue;
700
+ }
701
+ int wantBytes = CHUNK_FRAMES * channels * 2;
702
+ if (chunk.Length != wantBytes) chunk = new byte[wantBytes];
703
+ chunkFilled = 0;
704
+ nextCheckAt = now + DEVICE_CHECK_MS;
705
+ }
706
+
707
+ if (now >= nextCheckAt) {
708
+ nextCheckAt = now + DEVICE_CHECK_MS;
709
+ string currentId = DefaultEndpointId();
710
+ if (currentId != null && currentId != activeId) {
711
+ CloseClient(ref client, ref capture);
712
+ activeId = null;
713
+ chunkFilled = 0;
714
+ continue;
715
+ }
716
+ }
717
+
718
+ bool gotAny = false;
719
+ bool broken = false;
720
+ int bytesPerFrame = channels * 2;
721
+ int chunkBytes = chunk.Length;
722
+ uint packet;
723
+ while (Enabled && RawPipe.Connected) {
724
+ int hr = capture.GetNextPacketSize(out packet);
725
+ if (hr < 0) { broken = true; break; }
726
+ if (packet == 0) break;
727
+ IntPtr data;
728
+ uint frames;
729
+ uint flags;
730
+ ulong pos, qpc;
731
+ hr = capture.GetBuffer(out data, out frames, out flags, out pos, out qpc);
732
+ if (hr < 0) { broken = true; break; }
733
+ gotAny = true;
734
+ int bytes = (int)frames * bytesPerFrame;
735
+ bool silent = (flags & BUFFER_SILENT) != 0;
736
+ try {
737
+ if (!silent && bytes > 0) {
738
+ if (scratch.Length < bytes) scratch = new byte[bytes];
739
+ Marshal.Copy(data, scratch, 0, bytes);
740
+ }
741
+ } finally {
742
+ capture.ReleaseBuffer(frames);
743
+ }
744
+ int offset = 0;
745
+ while (offset < bytes) {
746
+ int take = Math.Min(chunkBytes - chunkFilled, bytes - offset);
747
+ if (silent) Array.Clear(chunk, chunkFilled, take);
748
+ else Buffer.BlockCopy(scratch, offset, chunk, chunkFilled, take);
749
+ chunkFilled += take;
750
+ offset += take;
751
+ if (chunkFilled == chunkBytes) {
752
+ RawPipe.WriteAudio(SAMPLE_RATE, channels, chunk);
753
+ chunkFilled = 0;
754
+ }
755
+ }
756
+ }
757
+
758
+ if (broken) {
759
+ CloseClient(ref client, ref capture);
760
+ activeId = null;
761
+ chunkFilled = 0;
762
+ retryAt = now + 1000;
763
+ continue;
764
+ }
765
+ if (!gotAny) Thread.Sleep(5);
766
+ }
767
+ } finally {
768
+ CloseClient(ref client, ref capture);
769
+ }
770
+ }
771
+
772
+ static string DefaultEndpointId() {
773
+ try {
774
+ var en = (IMMDeviceEnumerator)new MMDeviceEnumeratorCom();
775
+ IMMDevice dev;
776
+ if (en.GetDefaultAudioEndpoint(0, 0, out dev) != 0 && en.GetDefaultAudioEndpoint(0, 1, out dev) != 0) return null;
777
+ try {
778
+ IntPtr p;
779
+ if (dev.GetId(out p) != 0 || p == IntPtr.Zero) return null;
780
+ try {
781
+ return Marshal.PtrToStringUni(p);
782
+ } finally {
783
+ Native.CoTaskMemFree(p);
784
+ }
785
+ } finally {
786
+ try { Marshal.ReleaseComObject(dev); } catch { }
787
+ }
788
+ } catch {
789
+ return null;
790
+ }
791
+ }
792
+
793
+ static bool OpenClient(out IAudioClient client, out IAudioCaptureClient capture, out string deviceId, out int channels) {
794
+ client = null;
795
+ capture = null;
796
+ deviceId = null;
797
+ channels = 2;
798
+ IMMDevice dev = null;
799
+ IntPtr fmt = IntPtr.Zero;
800
+ try {
801
+ var en = (IMMDeviceEnumerator)new MMDeviceEnumeratorCom();
802
+ if (en.GetDefaultAudioEndpoint(0, 0, out dev) != 0 && en.GetDefaultAudioEndpoint(0, 1, out dev) != 0) return false;
803
+ IntPtr idPtr;
804
+ if (dev.GetId(out idPtr) == 0 && idPtr != IntPtr.Zero) {
805
+ try { deviceId = Marshal.PtrToStringUni(idPtr); } finally { Native.CoTaskMemFree(idPtr); }
806
+ }
807
+ Guid iid = typeof(IAudioClient).GUID;
808
+ object o;
809
+ if (dev.Activate(ref iid, 0x17, IntPtr.Zero, out o) != 0 || o == null) return false;
810
+ var c = (IAudioClient)o;
811
+ fmt = Marshal.AllocHGlobal(18);
812
+ if (!InitFormat(c, fmt, 2)) {
813
+ if (!InitFormat(c, fmt, 1)) {
814
+ try { Marshal.ReleaseComObject(c); } catch { }
815
+ return false;
816
+ }
817
+ channels = 1;
818
+ }
819
+ Guid capIid = typeof(IAudioCaptureClient).GUID;
820
+ object c2;
821
+ if (c.GetService(ref capIid, out c2) != 0 || c2 == null) {
822
+ try { Marshal.ReleaseComObject(c); } catch { }
823
+ return false;
824
+ }
825
+ if (c.Start() != 0) {
826
+ try { Marshal.ReleaseComObject(c2); } catch { }
827
+ try { Marshal.ReleaseComObject(c); } catch { }
828
+ return false;
829
+ }
830
+ client = c;
831
+ capture = (IAudioCaptureClient)c2;
832
+ return true;
833
+ } catch {
834
+ return false;
835
+ } finally {
836
+ if (fmt != IntPtr.Zero) Marshal.FreeHGlobal(fmt);
837
+ if (dev != null) { try { Marshal.ReleaseComObject(dev); } catch { } }
838
+ }
839
+ }
840
+
841
+ static bool InitFormat(IAudioClient c, IntPtr fmt, short ch) {
842
+ short align = (short)(ch * 2);
843
+ Marshal.WriteInt16(fmt, 0, 1);
844
+ Marshal.WriteInt16(fmt, 2, ch);
845
+ Marshal.WriteInt32(fmt, 4, SAMPLE_RATE);
846
+ Marshal.WriteInt32(fmt, 8, SAMPLE_RATE * align);
847
+ Marshal.WriteInt16(fmt, 12, align);
848
+ Marshal.WriteInt16(fmt, 14, 16);
849
+ Marshal.WriteInt16(fmt, 16, 0);
850
+ return c.Initialize(0, FLAGS_LOOPBACK_AUTOCONVERT, 500000, 0, fmt, IntPtr.Zero) == 0;
851
+ }
852
+
853
+ static void CloseClient(ref IAudioClient client, ref IAudioCaptureClient capture) {
854
+ if (client != null) {
855
+ try { client.Stop(); } catch { }
856
+ try { Marshal.ReleaseComObject(client); } catch { }
857
+ client = null;
858
+ }
859
+ if ( capture != null) {
860
+ try { Marshal.ReleaseComObject(capture); } catch { }
861
+ capture = null;
862
+ }
863
+ }
864
+ }
865
+
866
+ /** Đồng bộ bộ nhớ tạm (Clipboard văn bản Unicode) hai chiều giữa máy từ xa và trình duyệt điều khiển. */
867
+ public static class ClipboardSync {
868
+ const uint CF_UNICODETEXT = 13;
869
+ const uint GMEM_MOVEABLE = 0x0002;
870
+ const int MAX_CHARS = 65536;
871
+ static readonly object syncGate = new object();
872
+ static uint lastSeq = 0;
873
+ static string lastText = "";
874
+
875
+ public static void Init() {
876
+ try { lastSeq = Native.GetClipboardSequenceNumber(); } catch { }
877
+ }
878
+
879
+ public static void Poll() {
880
+ uint seq;
881
+ try { seq = Native.GetClipboardSequenceNumber(); } catch { return; }
882
+ if (seq == 0 || seq == lastSeq) return;
883
+ string text = null;
884
+ lock (syncGate) {
885
+ if (seq == lastSeq) return;
886
+ lastSeq = seq;
887
+ text = ReadTextUnsafe();
888
+ if (string.IsNullOrEmpty(text) || text == lastText) return;
889
+ lastText = text;
890
+ }
891
+ var msg = Out.Msg("clipboard");
892
+ msg["text"] = text;
893
+ Out.Send(msg);
894
+ }
895
+
896
+ static string ReadTextUnsafe() {
897
+ for (int attempt = 0; attempt < 3; attempt++) {
898
+ if (Native.OpenClipboard(IntPtr.Zero)) {
899
+ try {
900
+ if (!Native.IsClipboardFormatAvailable(CF_UNICODETEXT)) return null;
901
+ IntPtr hData = Native.GetClipboardData(CF_UNICODETEXT);
902
+ if (hData == IntPtr.Zero) return null;
903
+ IntPtr ptr = Native.GlobalLock(hData);
904
+ if (ptr == IntPtr.Zero) return null;
905
+ try {
906
+ string s = Marshal.PtrToStringUni(ptr);
907
+ if (s != null && s.Length > MAX_CHARS) s = s.Substring(0, MAX_CHARS);
908
+ return s;
909
+ } finally {
910
+ Native.GlobalUnlock(hData);
911
+ }
912
+ } catch {
913
+ return null;
914
+ } finally {
915
+ Native.CloseClipboard();
916
+ }
917
+ }
918
+ Thread.Sleep(5);
919
+ }
920
+ return null;
921
+ }
922
+
923
+ public static bool SetText(string text) {
924
+ if (string.IsNullOrEmpty(text)) return false;
925
+ if (text.Length > MAX_CHARS) text = text.Substring(0, MAX_CHARS);
926
+ lock (syncGate) {
927
+ for (int attempt = 0; attempt < 5; attempt++) {
928
+ if (Native.OpenClipboard(IntPtr.Zero)) {
929
+ IntPtr hGlobal = IntPtr.Zero;
930
+ try {
931
+ Native.EmptyClipboard();
932
+ int bytes = (text.Length + 1) * 2;
933
+ hGlobal = Native.GlobalAlloc(GMEM_MOVEABLE, (UIntPtr)(ulong)bytes);
934
+ if (hGlobal == IntPtr.Zero) return false;
935
+ IntPtr target = Native.GlobalLock(hGlobal);
936
+ if (target == IntPtr.Zero) return false;
937
+ try {
938
+ Marshal.Copy(text.ToCharArray(), 0, target, text.Length);
939
+ Marshal.WriteInt16(target, text.Length * 2, 0);
940
+ } finally {
941
+ Native.GlobalUnlock(hGlobal);
942
+ }
943
+ if (Native.SetClipboardData(CF_UNICODETEXT, hGlobal) != IntPtr.Zero) {
944
+ hGlobal = IntPtr.Zero;
945
+ lastText = text;
946
+ lastSeq = Native.GetClipboardSequenceNumber();
947
+ return true;
948
+ }
949
+ return false;
950
+ } catch {
951
+ return false;
952
+ } finally {
953
+ if (hGlobal != IntPtr.Zero) Native.GlobalFree(hGlobal);
954
+ Native.CloseClipboard();
955
+ }
956
+ }
957
+ Thread.Sleep(5);
958
+ }
959
+ }
960
+ return false;
961
+ }
962
+ }
601
963
  }
602
964
  `;