Repository navigation
Expand file tree
/
Copy pathphonemic.py
More file actions
executable file
·457 lines (407 loc) · 18.9 KB
/
Copy pathphonemic.py
File metadata and controls
executable file
·457 lines (407 loc) · 18.9 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
#!/usr/bin/env python3
"""PhoneMic - telefonu bilgisayar mikrofonu olarak kullan (WO Mic benzeri, yerel ağ).
https://github.com/Ast1Kaan/phonemic (MIT Lisansı)
Sadece Python standart kütüphanesi + pactl/openssl/qrencode kullanır.
Telefon sesi -> WebSocket (HTTPS) -> FIFO -> PipeWire "PhoneMic" sanal mikrofonu.
"""
import argparse
import asyncio
import base64
import fcntl
import hashlib
import json
import hmac
import os
import signal
import socket
import secrets
import ssl
import struct
import subprocess
import sys
import termios
import time
import webbrowser
RATE = 48000
BYTES_PER_SEC = RATE * 2 # s16le mono
SOURCE_NAME = "PhoneMic"
DATA_DIR = os.path.expanduser("~/.local/share/phonemic")
FIFO = os.path.join(os.environ.get("XDG_RUNTIME_DIR", "/tmp"), "phonemic.fifo")
WS_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
F_SETPIPE_SZ = 1031
# ---------------------------------------------------------------- yardımcılar
VIRTUAL_IFACES = ("lo", "docker", "br-", "veth", "virbr", "vmnet", "vboxnet", "tun", "tap",
"wg", "tailscale", "zt", "byedpi", "podman", "cni", "flannel")
def lan_ips():
"""Telefonun erişebileceği yerel ağ IP'leri, en olası olan önce."""
out = subprocess.run(["ip", "-4", "-o", "addr"], capture_output=True, text=True).stdout
ips = []
for line in out.splitlines():
parts = line.split()
iface, cidr = parts[1], parts[3]
ip, prefix = cidr.split("/")
if iface.startswith(VIRTUAL_IFACES) or prefix == "32":
continue
ips.append(ip)
def rank(ip):
a, b = map(int, ip.split(".")[:2])
if a == 192 and b == 168:
return 0
if a == 10:
return 1
if a == 172 and 16 <= b <= 31:
return 2
return 3
return sorted(ips, key=rank)
def ensure_cert(ip):
os.makedirs(DATA_DIR, exist_ok=True)
cert = os.path.join(DATA_DIR, f"cert-{ip}.pem")
key = os.path.join(DATA_DIR, f"key-{ip}.pem")
if not (os.path.exists(cert) and os.path.exists(key)):
subprocess.run([
"openssl", "req", "-x509", "-nodes", "-days", "3650",
"-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
"-subj", "/CN=PhoneMic",
"-addext", f"subjectAltName=IP:{ip},IP:127.0.0.1",
"-keyout", key, "-out", cert,
], check=True, capture_output=True)
return cert, key
def unload_old_modules():
out = subprocess.run(["pactl", "list", "short", "modules"], capture_output=True, text=True).stdout
for line in out.splitlines():
if "module-pipe-source" in line and f"source_name={SOURCE_NAME}" in line:
subprocess.run(["pactl", "unload-module", line.split()[0]], capture_output=True)
def load_source():
unload_old_modules()
if os.path.exists(FIFO):
os.unlink(FIFO)
r = subprocess.run([
"pactl", "load-module", "module-pipe-source",
f"source_name={SOURCE_NAME}", f"file={FIFO}",
"format=s16le", f"rate={RATE}", "channels=1",
"source_properties=device.description=PhoneMic",
], capture_output=True, text=True)
if r.returncode != 0:
sys.exit(f"Sanal mikrofon oluşturulamadı: {r.stderr.strip()}")
return r.stdout.strip()
def qr_svg(url):
return subprocess.run(["qrencode", "-t", "SVG", "-m", "2", "-s", "8", "-o", "-", url],
capture_output=True, check=True).stdout
def qr_terminal(url):
return subprocess.run(["qrencode", "-t", "ANSIUTF8", "-m", "2", url],
capture_output=True, text=True).stdout
# ---------------------------------------------------------------- ses çıkışı
class Sink:
"""FIFO'ya engellemeden yazar; gecikme sınırı aşılırsa paketi atar."""
def __init__(self, max_latency_ms):
self.fd = os.open(FIFO, os.O_RDWR | os.O_NONBLOCK)
try:
fcntl.fcntl(self.fd, F_SETPIPE_SZ, 65536)
except OSError:
pass
self.max_bytes = BYTES_PER_SEC * max_latency_ms // 1000
self.dropped = 0
self.buf = bytearray(4)
def queued(self):
fcntl.ioctl(self.fd, termios.FIONREAD, self.buf)
return struct.unpack("i", self.buf)[0]
def write(self, data):
q = self.queued()
if q + len(data) > self.max_bytes:
# En eski sesi at, gecikme birikmesin (çift bayt = örnek hizası korunur)
try:
os.read(self.fd, (q - self.max_bytes // 2) & ~1)
except BlockingIOError:
pass
self.dropped += 1
try:
os.write(self.fd, data)
except BlockingIOError:
self.dropped += 1
# ---------------------------------------------------------------- sunucu
class App:
def __init__(self, args, ip):
self.args = args
self.ip = ip
# Her açılışta yeni anahtar: sadece QR'ı taratan telefon ses gönderebilir
self.token = secrets.token_urlsafe(9)
self.url = f"https://{ip}:{args.port}/#{self.token}"
self.sink = Sink(args.latency)
self.client = None # (peer, writer)
self.since = 0
self.bytes = 0
self.qr = qr_svg(self.url)
# --- HTTP ayrıştırma
async def read_request(self, reader):
line = await reader.readline()
if not line:
return None
try:
method, path, _ = line.decode().split(" ", 2)
except ValueError:
return None
headers = {}
while True:
h = await reader.readline()
if h in (b"\r\n", b"\n", b""):
break
k, _, v = h.decode().partition(":")
headers[k.strip().lower()] = v.strip()
path, _, query = path.partition("?")
return method, path, headers, query
@staticmethod
def respond(writer, body, ctype="text/html; charset=utf-8", status="200 OK"):
if isinstance(body, str):
body = body.encode()
writer.write(
f"HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {len(body)}\r\n"
f"Cache-Control: no-store\r\nConnection: close\r\n\r\n".encode() + body)
# --- bilgisayar tarafı (sadece localhost, HTTP)
async def handle_local(self, reader, writer):
try:
req = await self.read_request(reader)
if not req:
return
_, path, _, _ = req
if path == "/":
self.respond(writer, PC_PAGE.replace("{{URL}}", self.url))
elif path == "/qr.svg":
self.respond(writer, self.qr, "image/svg+xml")
elif path == "/quit":
self.respond(writer, "ok", "text/plain")
asyncio.get_running_loop().call_later(0.2, self.stop.set)
elif path == "/status":
self.respond(writer, json.dumps(self.status()), "application/json")
else:
self.respond(writer, "yok", status="404 Not Found")
await writer.drain()
except (ConnectionError, asyncio.IncompleteReadError):
pass
finally:
writer.close()
def status(self):
return {
"connected": self.client is not None,
"peer": self.client[0] if self.client else None,
"seconds": int(time.time() - self.since) if self.client else 0,
"bytes": self.bytes,
"dropped": self.sink.dropped,
"queued_ms": self.sink.queued() * 1000 // BYTES_PER_SEC,
}
# --- telefon tarafı (HTTPS + WebSocket)
async def handle_phone(self, reader, writer):
try:
req = await self.read_request(reader)
if not req:
return
_, path, headers, query = req
if path == "/ws" and headers.get("upgrade", "").lower() == "websocket":
if not hmac.compare_digest(query.encode(), f"k={self.token}".encode()):
self.respond(writer, "anahtar geçersiz, QR kodu tekrar tarat", status="403 Forbidden")
await writer.drain()
return
await self.websocket(reader, writer, headers)
return
if path == "/":
self.respond(writer, PHONE_PAGE)
else:
self.respond(writer, "yok", status="404 Not Found")
await writer.drain()
except (ConnectionError, asyncio.IncompleteReadError, ssl.SSLError):
pass
finally:
writer.close()
async def websocket(self, reader, writer, headers):
key = headers.get("sec-websocket-key", "").encode()
accept = base64.b64encode(hashlib.sha1(key + WS_GUID).digest()).decode()
writer.write(
"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Accept: {accept}\r\n\r\n".encode())
await writer.drain()
# Aynı anda tek telefon: yenisi eskisini düşürür
if self.client:
self.client[1].close()
peer = writer.get_extra_info("peername")[0]
me = (peer, writer)
self.client, self.since = me, time.time()
print(f"[+] Telefon bağlandı: {peer}", flush=True)
frag = bytearray()
try:
while True:
h = await reader.readexactly(2)
fin, op = h[0] & 0x80, h[0] & 0x0F
ln = h[1] & 0x7F
if ln == 126:
ln = struct.unpack("!H", await reader.readexactly(2))[0]
elif ln == 127:
ln = struct.unpack("!Q", await reader.readexactly(8))[0]
if ln > 1 << 20:
break
mask = await reader.readexactly(4) if h[1] & 0x80 else None
data = await reader.readexactly(ln)
if mask and ln:
m = (mask * (ln // 4 + 1))[:ln]
data = (int.from_bytes(data, "little") ^ int.from_bytes(m, "little")).to_bytes(ln, "little")
if op == 0x8: # kapat
writer.write(b"\x88\x00")
break
if op == 0x9: # ping -> pong
writer.write(bytes([0x8A, len(data)]) + data[:125])
continue
if op in (0x0, 0x2):
frag += data
if fin:
self.bytes += len(frag)
self.sink.write(bytes(frag))
frag.clear()
finally:
if self.client is me:
self.client = None
print(f"[-] Telefon ayrıldı: {peer}", flush=True)
async def main():
ap = argparse.ArgumentParser(description="Telefonu yerel ağ üzerinden mikrofon olarak kullan")
ap.add_argument("--port", type=int, default=1760,
help="telefonun bağlanacağı HTTPS portu (ufw KDE Connect aralığı 1714-1764 zaten açık)")
ap.add_argument("--local-port", type=int, default=8480, help="QR sayfası (localhost) portu")
ap.add_argument("--ip", help="QR'da kullanılacak IP (varsayılan: otomatik)")
ap.add_argument("--latency", type=int, default=150, help="maks. tampon gecikmesi (ms)")
ap.add_argument("--no-browser", action="store_true", help="QR sayfasını otomatik açma")
args = ap.parse_args()
local_url = f"http://127.0.0.1:{args.local_port}/"
try: # zaten çalışıyorsa sadece QR sayfasını aç
socket.create_connection(("127.0.0.1", args.local_port), timeout=0.5).close()
print(f"PhoneMic zaten çalışıyor: {local_url}")
if not args.no_browser:
webbrowser.open(local_url)
return
except OSError:
pass
ips = lan_ips()
ip = args.ip or (ips[0] if ips else "127.0.0.1")
cert, key = ensure_cert(ip)
module_id = load_source()
app = App(args, ip)
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain(cert, key)
phone_srv = await asyncio.start_server(app.handle_phone, "0.0.0.0", args.port, ssl=ctx)
local_srv = await asyncio.start_server(app.handle_local, "127.0.0.1", args.local_port)
print(qr_terminal(app.url))
print(f"Telefonda aç : {app.url}")
print(f"QR sayfası : {local_url}")
print(f"Sanal mikrofon: '{SOURCE_NAME}' (OBS > Ses Girişi Yakalama) | Çıkış: Ctrl+C\n", flush=True)
if not args.no_browser:
webbrowser.open(local_url)
stop = app.stop = asyncio.Event()
loop = asyncio.get_running_loop()
for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
loop.add_signal_handler(s, stop.set)
try:
await stop.wait()
finally:
phone_srv.close()
local_srv.close()
subprocess.run(["pactl", "unload-module", module_id], capture_output=True)
print("Kapatıldı, sanal mikrofon kaldırıldı.")
# ---------------------------------------------------------------- sayfalar
PC_PAGE = r"""<!doctype html><html lang="tr"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>PhoneMic</title>
<style>
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#111;color:#eee;font:15px system-ui,sans-serif}
.c{text-align:center;padding:24px}
img{width:280px;height:280px;background:#fff;border-radius:12px;padding:8px}
code{background:#222;padding:4px 8px;border-radius:6px}
#st{margin-top:18px;font-size:18px}.on{color:#4ade80}.off{color:#f87171}
small{color:#888;display:block;margin-top:10px;line-height:1.6}
</style></head><body><div class="c">
<h2>PhoneMic</h2>
<img src="/qr.svg" alt="QR">
<p>Telefonla tarat veya aç: <code>{{URL}}</code></p>
<div id="st" class="off">Telefon bekleniyor…</div>
<small id="info"></small>
<small>Sertifika uyarısı çıkarsa: <b>Gelişmiş → Yine de devam et</b><br>
OBS: Kaynak ekle → <b>Ses Girişi Yakalama</b> → Cihaz: <b>PhoneMic</b></small>
<p><button onclick="fetch('/quit').then(()=>document.body.innerHTML='<h3 style=text-align:center>PhoneMic kapatıldı</h3>')"
style="margin-top:14px;padding:8px 18px;border:0;border-radius:8px;background:#333;color:#eee;cursor:pointer">Kapat</button></p>
</div><script>
async function tick(){try{const s=await (await fetch('/status')).json();
const st=document.getElementById('st');
if(s.connected){st.className='on';st.textContent='● Bağlı: '+s.peer+' ('+s.seconds+' sn)';}
else{st.className='off';st.textContent='Telefon bekleniyor…';}
document.getElementById('info').textContent='Alınan: '+(s.bytes/1048576).toFixed(1)+' MB · Tampon: '+s.queued_ms+' ms · Atılan paket: '+s.dropped;
}catch(e){document.getElementById('st').textContent='Sunucu kapalı';}}
tick();setInterval(tick,1000);
</script></body></html>"""
PHONE_PAGE = r"""<!doctype html><html lang="tr"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>PhoneMic</title>
<style>
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#111;color:#eee;font:16px system-ui,sans-serif}
.c{text-align:center;padding:24px;width:100%;max-width:360px;box-sizing:border-box}
button{width:220px;height:220px;border-radius:50%;border:0;font-size:22px;font-weight:600;color:#fff;background:#2563eb}
button.live{background:#dc2626}
#meter{height:10px;background:#222;border-radius:5px;margin:24px 0 8px;overflow:hidden}
#bar{height:100%;width:0;background:#4ade80;transition:width .08s}
label{display:block;margin-top:14px;color:#aaa;font-size:14px}
input[type=range]{width:100%}
#st{margin-top:14px;color:#aaa;min-height:1.4em}
</style></head><body><div class="c">
<button id="b">Mikrofon Ol</button>
<div id="meter"><div id="bar"></div></div>
<label>Kazanç: <span id="gv">1.0</span>x<input id="g" type="range" min="0" max="4" step="0.1" value="1"></label>
<label><input id="ns" type="checkbox"> Gürültü engelleme</label>
<div id="st">Başlatmak için dokun. Ekran açık kalmalı.</div>
</div><script>
const WORKLET=`class P extends AudioWorkletProcessor{
constructor(){super();this.r=sampleRate/48000;this.p=0;this.l=0;this.o=new Int16Array(480);this.n=0;this.pk=0;}
push(v){v=v<-1?-1:v>1?1:v;const a=v<0?-v:v;if(a>this.pk)this.pk=a;
this.o[this.n++]=v*32767;if(this.n===480){this.port.postMessage({b:this.o.buffer,pk:this.pk},[this.o.buffer]);
this.o=new Int16Array(480);this.n=0;this.pk=0;}}
process(i){const c=i[0]&&i[0][0];if(!c)return true;
if(this.r===1){for(let k=0;k<c.length;k++)this.push(c[k]);return true;}
let p=this.p;const L=c.length;
while(p<L-1){const k=Math.floor(p),f=p-k,a=k<0?this.l:c[k];this.push(a+(c[k+1]-a)*f);p+=this.r;}
this.p=p-L;this.l=c[L-1];return true;}}
registerProcessor('p',P);`;
let ctx,stream,ws,gain,wl,live=false;
const b=document.getElementById('b'),st=document.getElementById('st'),bar=document.getElementById('bar');
const g=document.getElementById('g'),gv=document.getElementById('gv'),ns=document.getElementById('ns');
g.oninput=()=>{gv.textContent=(+g.value).toFixed(1);if(gain)gain.gain.value=+g.value;};
ns.onchange=()=>{if(live){stop();start();}};
b.onclick=()=>live?stop():start();
async function start(){
try{
if(!navigator.mediaDevices)throw new Error('HTTPS gerekli (sertifikayı kabul et)');
if(!location.hash)throw new Error('Bağlantı anahtarı yok. Bilgisayardaki QR kodu tarat.');
stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:false,
autoGainControl:false,noiseSuppression:ns.checked}});
ctx=new AudioContext({sampleRate:48000,latencyHint:'interactive'});
await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET],{type:'text/javascript'})));
const src=ctx.createMediaStreamSource(stream);gain=ctx.createGain();gain.gain.value=+g.value;
const node=new AudioWorkletNode(ctx,'p');src.connect(gain).connect(node);
connect(node);
try{wl=await navigator.wakeLock.request('screen');}catch(e){}
live=true;b.textContent='Durdur';b.classList.add('live');
}catch(e){st.textContent='Hata: '+e.message;stop();}
}
function connect(node){
ws=new WebSocket('wss://'+location.host+'/ws?k='+encodeURIComponent(location.hash.slice(1)));ws.binaryType='arraybuffer';
ws.onopen=()=>st.textContent='● Yayında — bilgisayara gidiyor';
ws.onclose=()=>{if(live){st.textContent='Bağlantı koptu, yeniden deneniyor… (PhoneMic yeniden açıldıysa QR kodu tekrar tarat)';setTimeout(()=>live&&connect(node),1000);}};
node.port.onmessage=e=>{bar.style.width=Math.min(100,e.data.pk*100)+'%';
if(ws.readyState===1&&ws.bufferedAmount<48000)ws.send(e.data.b);};
}
function stop(){
live=false;b.textContent='Mikrofon Ol';b.classList.remove('live');bar.style.width='0';
if(ws){ws.onclose=null;ws.close();ws=null;}
if(stream)stream.getTracks().forEach(t=>t.stop());
if(ctx)ctx.close();ctx=null;
if(wl){wl.release();wl=null;}
if(!st.textContent.startsWith('Hata'))st.textContent='Durduruldu.';
}
document.addEventListener('visibilitychange',async()=>{if(live&&document.visibilityState==='visible'){
try{wl=await navigator.wakeLock.request('screen');}catch(e){} if(ctx&&ctx.state!=='running')ctx.resume();}});
</script></body></html>"""
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass