forked from afaden/babelpod
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
272 lines (247 loc) · 8.17 KB
/
index.js
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
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var spawn = require('child_process').spawn;
var util = require('util');
var stream = require('stream');
var mdns = require('mdns-js');
var fs = require('fs');
var AirTunes = require('airtunes2');
var airtunes = new AirTunes();
// Create ToVoid and FromVoid streams so we always have somewhere to send to and from.
util.inherits(ToVoid, stream.Writable);
function ToVoid () {
if (!(this instanceof ToVoid)) return new ToVoid();
stream.Writable.call(this);
}
ToVoid.prototype._write = function (chunk, encoding, cb) {
}
util.inherits(FromVoid, stream.Readable);
function FromVoid () {
if (!(this instanceof FromVoid)) return new FromVoid();
stream.Readable.call(this);
}
FromVoid.prototype._read = function (chunk, encoding, cb) {
}
var currentInput = "void";
var currentOutput = "void";
var inputStream = new FromVoid();
var outputStream = new ToVoid();
var airplayDevice = null;
var arecordInstance = null;
var aplayInstance = null;
var volume = 20;
var availableOutputs = [];
var availablePcmOutputs = []
var availableAirplayOutputs = [];
var availableInputs = [];
var availableBluetoothInputs = [];
var availablePcmInputs = [];
// Search for new PCM input/output devices
function pcmDeviceSearch(){
try {
var pcmDevicesString = fs.readFileSync('/proc/asound/pcm', 'utf8');
} catch (e) {
console.log("audio input/output pcm devices could not be found");
return;
}
var pcmDevicesArray = pcmDevicesString.split("\n").filter(line => line!="");
var pcmDevices = pcmDevicesArray.map(device => {var splitDev = device.split(":");return {id: "plughw:"+splitDev[0].split("-").map(num => parseInt(num, 10)).join(","), name:splitDev[2].trim(), output: splitDev.some(part => part.includes("playback")), input: splitDev.some(part => part.includes("capture"))}});
availablePcmOutputs = pcmDevices.filter(dev => dev.output);
availablePcmInputs = pcmDevices.filter(dev => dev.input);
updateAllInputs();
updateAllOutputs();
}
// Perform initial search for PCM devices
pcmDeviceSearch();
// Watch for new PCM input/output devices every 10 seconds
var pcmDeviceSearchLoop = setInterval(pcmDeviceSearch, 10000);
// Watch for new Bluetooth devices
/*blue.Bluetooth();
blue.on(blue.bluetoothEvents.Device, function (devices) {
console.log('devices:' + JSON.stringify(devices,null,2));
availableBluetoothInputs = [];
for (var device of blue.devices){
availableBluetoothInputs.push({
'name': 'Bluetooth: '+device.name,
'id': 'bluealsa:HCI=hci0,DEV='+device.mac+',PROFILE=a2dp,DELAY=10000'
});
}
updateAllInputs();
})*/
function updateAllInputs(){
var defaultInputs = [
{
'name': 'None',
'id': 'void'
}
];
availableInputs = defaultInputs.concat(availablePcmInputs, availableBluetoothInputs);
// todo only emit if updated
io.emit('available_inputs', availableInputs);
}
updateAllInputs();
function updateAllOutputs(){
var defaultOutputs = [
{
'name': 'None',
'id': 'void',
'type': 'void'
}
];
availableOutputs = defaultOutputs.concat(availablePcmOutputs, availableAirplayOutputs);
// todo only emit if updated
io.emit('available_outputs', availableOutputs);
}
updateAllOutputs();
var browser = mdns.createBrowser(mdns.tcp('raop'));
browser.on('ready', function () {
browser.discover();
});
browser.on('update', function (data) {
// console.log("service up: ", data);
// console.log(service.addresses);
// console.log(data.fullname);
if (data.fullname){
var splitName = /([^@]+)@(.*)\._raop\._tcp\.local/.exec(data.fullname);
if (splitName != null && splitName.length > 1){
var id = 'airplay_'+data.addresses[0]+'_'+data.port;
if (!availableAirplayOutputs.some(e => e.id === id)) {
availableAirplayOutputs.push({
'name': 'AirPlay: ' + splitName[2],
'id': id,
'type': 'airplay'
// 'address': service.addresses[1],
// 'port': service.port,
// 'host': service.host
});
updateAllOutputs();
}
}
}
// console.log(airplayDevices);
});
// browser.on('serviceDown', function(service) {
// console.log("service down: ", service);
// });
function cleanupCurrentInput(){
inputStream.unpipe(outputStream);
if (arecordInstance !== null){
arecordInstance.kill();
arecordInstance = null;
}
}
function cleanupCurrentOutput(){
console.log("inputStream", inputStream);
console.log("outputStream", outputStream);
inputStream.unpipe(outputStream);
if (airplayDevice !== null) {
airplayDevice.stop(function(){
console.log('stopped airplay device');
})
airplayDevice = null;
}
if (aplayInstance !== null){
aplayInstance.kill();
aplayInstance = null;
}
}
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
let logPipeError = function(e) {console.log('inputStream.pipe error: ' + e.message)};
io.on('connection', function(socket){
console.log('a user connected');
// set current state
socket.emit('available_inputs', availableInputs);
socket.emit('available_outputs', availableOutputs);
socket.emit('switched_input', currentInput);
socket.emit('switched_output', currentOutput);
socket.emit('changed_output_volume', volume);
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('change_output_volume', function(msg){
console.log('change_output_volume: ', msg);
volume = msg;
if (airplayDevice !== null) {
airplayDevice.setVolume(volume, function(){
console.log('changed airplay volume');
});
}
if (aplayInstance !== null){
console.log('todo: update correct speaker based on currentOutput device ID');
console.log(currentOutput);
var amixer = spawn("amixer", [
'-c', "1",
'--', "sset",
'Speaker', volume+"%"
]);
}
io.emit('changed_output_volume', msg);
});
socket.on('switch_output', function(msg){
console.log('switch_output: ' + msg);
currentOutput = msg;
cleanupCurrentOutput();
// TODO: rewrite how devices are stored to avoid the array split thingy
if (msg.startsWith("airplay")){
var split = msg.split("_");
var host = split[1];
var port = split[2];
console.log('adding device: ' + host + ':' + port);
airplayDevice = airtunes.add(host, {port: port, volume: volume});
airplayDevice.on('status', function(status) {
console.log('airplay status: ' + status);
if(status === 'ready'){
outputStream = airtunes;
inputStream.pipe(outputStream).on('error', logPipeError);
// at this moment the rtsp setup is not fully done yet and the status
// is still SETVOLUME. There's currently no way to check if setup is
// completed, so we just wait a second before setting the track info.
// Unfortunately we don't have the fancy input name here. Will get fixed
// with a better way of storing devices.
setTimeout(() => { airplayDevice.setTrackInfo(currentInput, 'BabelPod', '') }, 1000);
}
});
}
if (msg.startsWith("plughw:")){
aplayInstance = spawn("aplay", [
'-D', msg,
'-c', "2",
'-f', "S16_LE",
'-r', "44100"
]);
outputStream = aplayInstance.stdin;
inputStream.pipe(outputStream).on('error', logPipeError);
}
if (msg === "void"){
outputStream = new ToVoid();
inputStream.pipe(outputStream).on('error', logPipeError);
}
io.emit('switched_output', msg);
});
socket.on('switch_input', function(msg){
console.log('switch_input: ' + msg);
currentInput = msg;
cleanupCurrentInput();
if (msg === "void"){
inputStream = new FromVoid();
inputStream.pipe(outputStream).on('error', logPipeError);
}
if (msg !== "void"){
arecordInstance = spawn("arecord", [
'-D', msg,
'-c', "2",
'-f', "S16_LE",
'-r', "44100"
]);
inputStream = arecordInstance.stdout;
inputStream.pipe(outputStream).on('error', logPipeError);
}
io.emit('switched_input', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});