summaryrefslogtreecommitdiff
path: root/soundbox/pipewire.go
blob: bb672f87015cd8aff8468cb46abfe72e0ce7acc3 (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
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
package soundbox

/*
#cgo pkg-config: libpipewire-0.3
#include "pipewire-binding.h"
*/
import "C"

import (
	"context"
	"io"
	"log"
	"net"
	"os/exec"
	"unsafe"
)

type pwCapture struct {
	cdata unsafe.Pointer
}

var pwAudio chan []byte

func newPWCapture(ctx context.Context) pwCapture {
	pwc := pwCapture{}

	pwAudio = make(chan []byte, 5)
	pwc.cdata = unsafe.Pointer(C.pw_go_capture_init())  // TODO pass &pwc.audio here
	go C.pw_go_capture_run(pwc.cdata)

	go func() {
		<-ctx.Done()
		C.pw_go_capture_deinit(pwc.cdata)
	}()

	return pwc
}

func (pwc pwCapture) Read(p []byte) (int, error) {
	select {
	case chunk, ok := <-pwAudio:
		if ok {
			noSilence := s16leDropSilence(chunk)
			i := copy(p, noSilence)
			return i, nil
		} else {
			return 0, io.EOF
		}
	default:
		return 0, nil
	}
}

func s16leDropSilence(input []byte) []byte {
	output := make([]byte, 0)

	cut := len(input) % 4
	length := len(input) - cut // s16 raw audio is 4 bytes per sample

	for i := 0; i < length; i += 4 {
		if input[i+0] == byte(0) &&
			input[i+1] == byte(0) &&
			input[i+2] == byte(0) &&
			input[i+3] == byte(0) {
			continue
		}
		output = append(output, input[i+0])
		output = append(output, input[i+1])
		output = append(output, input[i+2])
		output = append(output, input[i+3])
	}

	return output
}

func StreamPipewireContext(ctx context.Context, targets []net.HardwareAddr) error {
	cmd := exec.CommandContext(
		ctx,
		"ffmpeg",
		"-ac",
		"2",
		"-ar",
		"48000",
		"-f",
		"s16le",
		"-channel_layout",
		"stereo",
		"-i",
		"-",
		"-acodec",
		"flac",
		"-f",
		"ogg",
		"-",
	)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}

	pwc := newPWCapture(ctx)
	go func() {
		_, err := io.Copy(stdin, pwc)
		if err != nil {
			log.Println("Failed to copy from PipeWire to ffmpeg.")
		}
	}()

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

	err = streamContext(ctx, stdout, targets)
	if err != nil {
		return err
	}

	return cmd.Wait()
}

//export goHandleData
func goHandleData(data *C.int16_t, size C.size_t) {
	buf := C.GoBytes(unsafe.Pointer(data), C.int(size))
	pwAudio <- buf
}