summaryrefslogtreecommitdiff
path: root/soundbox/stream.go
blob: 0d6fe5fe31bb5e197a7346d32a2343132ada28b4 (plain)
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
package soundbox

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"os/exec"
	"time"
)

// streamingPort is the default network port a soundbox is listening to for
// incoming audio stream data.
const streamingPort = 5316

const bufferSize = 20

const writeTimeout = 1 * time.Second

// StreamURLContext streams audio from a given URL to one or multiple soundbox
// devices. The devices are referenced via their MAC addresses given by the
// targets argument. The ctx argument is passed to cancel the streaming.
func StreamURLContext(ctx context.Context, url string, targets []net.HardwareAddr) error {
	iface, err := getInterface()
	if err != nil {
		return err
	}

	ips := make([]net.IP, 0)
	for _, target := range targets {
		ip, err := toLinkLocal(target)
		if err != nil {
			return err
		}
		ips = append(ips, ip)
	}

	conns := make([]net.Conn, 0)
	for _, ip := range ips {
		var d net.Dialer
		conn, err := d.DialContext(
			ctx,
			"tcp6",
			fmt.Sprintf("[%s%%%s]:%d", ip, iface.Name, streamingPort),
		)
		if err != nil {
			return err
		}
		conns = append(conns, conn)
	}
	defer func() {
		for _, conn := range conns {
			conn.Close()
		}
	}()

	args := []string{
		"-re",
		"-i",
		url,
		"-acodec",
		"flac",
		"-f",
		"ogg",
		"-",
	}

	cmd := exec.CommandContext(ctx, "ffmpeg", args...)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}

	err = cmd.Start()
	if err != nil {
		return err
	}

	for {
		buffer := make([]byte, bufferSize)
		i, err := stdout.Read(buffer)
		if err != nil {
			if errors.Is(err, io.EOF) {
				break
			} else {
				return err
			}
		}
		for _, conn := range conns {
			conn.SetDeadline(time.Now().Add(writeTimeout))
			_, err = conn.Write(buffer[:i])
			if err != nil {
				return err
			}
		}
	}

	return cmd.Wait()
}