DeaD_EyE icon

stream to mpv via a specific interface

DeaD_EyE | PRO | 09/01/23 11:27:12 AM UTC | 0 ⭐ | 1204 👁️ | Never ⏰ | []
Python |

1.3 KB

|

None

|

0 👍

/

0 👎

import subprocess
from socket import socket, SOL_SOCKET, SO_BINDTODEVICE, SO_REUSEADDR, SO_REUSEPORT, AF_INET, AF_INET6, SOCK_STREAM
from ipaddress import ip_address
 
 
def serve(host, port, interface):
    ip = ip_address(host)
    af = AF_INET if ip.version == 4 else AF_INET6
    sock = socket(af, SOCK_STREAM)
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
    sock.setsockopt(SOL_SOCKET, SO_BINDTODEVICE, f"{interface}\0".encode())
    sock.bind((host, port))
    sock.listen()
    return sock
 
 
def main(host, port, interface):
    with serve(host, port, interface) as sock:
        client, client_addr = sock.accept()
        total = 0
        player = subprocess.Popen(["mpv", "-"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
 
        with open("received.bin", "wb") as fd:
            while chunk := client.recv(2**16-1):
                total += len(chunk)
                print(f"{total / 1024 ** 2:.2f} MiB")
                fd.write(chunk)
                try:
                    player.stdin.write(chunk)
                except BrokenPipeError:
                    break
 
        client.close()
 
 
if __name__ == "__main__":
    # cat audio.mp3 | nc -N ::1 8080
    main("::1", 8080, "tun0")
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎