Advertisement
DeaD_EyE

stream to mpv via a specific interface

Sep 1st, 2023
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. import subprocess
  2. from socket import socket, SOL_SOCKET, SO_BINDTODEVICE, SO_REUSEADDR, SO_REUSEPORT, AF_INET, AF_INET6, SOCK_STREAM
  3. from ipaddress import ip_address
  4.  
  5.  
  6. def serve(host, port, interface):
  7.     ip = ip_address(host)
  8.     af = AF_INET if ip.version == 4 else AF_INET6
  9.     sock = socket(af, SOCK_STREAM)
  10.     sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
  11.     sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
  12.     sock.setsockopt(SOL_SOCKET, SO_BINDTODEVICE, f"{interface}\0".encode())
  13.     sock.bind((host, port))
  14.     sock.listen()
  15.     return sock
  16.  
  17.  
  18. def main(host, port, interface):
  19.     with serve(host, port, interface) as sock:
  20.         client, client_addr = sock.accept()
  21.         total = 0
  22.         player = subprocess.Popen(["mpv", "-"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  23.  
  24.         with open("received.bin", "wb") as fd:
  25.             while chunk := client.recv(2**16-1):
  26.                 total += len(chunk)
  27.                 print(f"{total / 1024 ** 2:.2f} MiB")
  28.                 fd.write(chunk)
  29.                 try:
  30.                     player.stdin.write(chunk)
  31.                 except BrokenPipeError:
  32.                     break
  33.  
  34.         client.close()
  35.  
  36.  
  37. if __name__ == "__main__":
  38.     # cat audio.mp3 | nc -N ::1 8080
  39.     main("::1", 8080, "tun0")
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement