Parent: [a83f25] (diff)

Download this file

sc2mpd.cpp    495 lines (420 with data), 15.0 kB

  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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
Copyright 2011-14, Linn Products Ltd. All rights reserved.
Unless otherwise stated, all code in this project is licensed under the 2-clause
(Simplified) BSD license. See BsdLicense.txt for details.
*/
/* Copyright (C) 2014 J.F.Dockes
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Modified from ohSongcast/Receiver/Receiver.cpp
*/
#include "config.h"
#include <OpenHome/OhNetTypes.h>
#include <OpenHome/Private/Ascii.h>
#include <OpenHome/Private/Thread.h>
#include <OpenHome/Private/OptionParser.h>
#include <OpenHome/Private/Debug.h>
#include <OpenHome/Net/Core/OhNet.h>
#ifdef WITH_OHBUILD
#include "Debug.h"
#include "OhmReceiver.h"
#else
#include <OpenHome/OhmReceiver.h>
#include <OpenHome/OhSongcast/Debug.h>
#endif
#include "workqueue.h"
#include "rcvqueue.h"
#include "log.h"
#include "conftree.h"
#include "chrono.h"
#include "watcher.h"
#include "songcastreceiver.h"
#ifdef WITH_WAVSC2
#include "openaudio.h"
#include "audioreader.h"
#endif
#include <vector>
#include <stdio.h>
#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <fcntl.h>
using namespace std;
WorkQueue<AudioMessage*> audioqueue("audioqueue", 4);
#ifdef _WIN32
#pragma warning(disable:4355) // use of 'this' in ctor lists safe in this case
#define CDECL __cdecl
int mygetch()
{
return (_getch());
}
#else
#define CDECL
#include <termios.h>
#include <unistd.h>
int mygetch()
{
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
#endif
int g_sockfd = -1;
bool g_quitrequest = false;
void sigcatcher(int)
{
g_quitrequest = true;
// As recvfrom() is a blocking operation we need to shut the corresponding
// socket down so that recvfrom() returns with 0.
if (g_sockfd > 0) {
shutdown(g_sockfd, SHUT_RD);
}
}
bool needswap(AudioEater::BOrder order)
{
// Songcast data is always msb-first. Convert to desired order:
// depends on what downstream wants, and just as well we do it
// here because we copy the buf anyway.
bool needswap = false;
switch (order) {
case AudioEater::BO_MSB:
break;
case AudioEater::BO_LSB:
needswap = true;
break;
case AudioEater::BO_HOST:
#ifdef WORDS_BIGENDIAN
needswap = false;
#else
needswap = true;
#endif
break;
}
return needswap;
}
void copyswap(unsigned char *dest, const unsigned char *src,
unsigned int bytes, unsigned int bits)
{
unsigned char *ocp = dest;
const unsigned char *icp = src;
if (bits == 16) {
swab(src, dest, bytes);
} else if (bits == 24) {
while (icp - src <= int(bytes) - 3) {
*ocp++ = icp[2];
*ocp++ = icp[1];
*ocp++ = *icp;
icp += 3;
}
} else if (bits == 32) {
// Never seen this but whatever...
while (icp - src <= int(bytes) - 4) {
*ocp++ = icp[3];
*ocp++ = icp[2];
*ocp++ = icp[1];
*ocp++ = *icp;
icp += 4;
}
}
}
using namespace OpenHome;
using namespace OpenHome::Net;
using namespace OpenHome::TestFramework;
using namespace OpenHome::Av;
#ifdef WITH_WAVSC2
static int playWav(const string& wavfile, AudioEater *eater,
AudioEater::Context *ctxt)
{
audioqueue.start(1, eater->worker, ctxt);
AudioReader *audio = openAudio(wavfile, "", true);
if (!audio || !audio->open() || audio->bytesPerSample() == 0 ||
audio->numChannels() == 0) {
cerr << "Audio file open failed" << endl;
return 1;
}
LOGDEB("sample rate: " << audio->sampleRate() << endl);
LOGDEB("sample size: " << audio->bytesPerSample() << endl);
LOGDEB("channels: " << audio->numChannels() << endl);
size_t packetBytes = 441 * 16 *2;
while (true) {
const unsigned char *ibuf = audio->data(packetBytes);
if (ibuf == 0) {
return 1;
}
// We allocate a bit more space to avoir reallocations in the resampler
unsigned int allocbytes = packetBytes + 100;
char *buf = (char *)malloc(allocbytes);
if (buf == 0) {
LOGERR("playWav: can't allocate " << allocbytes << " bytes\n");
return 1;
}
// Songcast data is always msb-first. Convert to desired order:
// depends on what downstream wants, and just as well we do it
// here because we copy the buf anyway.
bool needswap = false;
switch (eater->input_border) {
case AudioEater::BO_MSB:
break;
case AudioEater::BO_LSB:
needswap = true;
break;
case AudioEater::BO_HOST:
#ifdef WORDS_BIGENDIAN
needswap = false;
#else
needswap = true;
#endif
break;
}
int bitDepth = 8 * audio->bytesPerSample();
if (needswap) {
copyswap((unsigned char *)buf, ibuf, packetBytes, bitDepth);
} else {
memcpy(buf, ibuf, packetBytes);
}
// The constructor wants the number of frames as input (frame
// being all samples at given timepoint, typically 2 for
// stereo)
int frames = packetBytes /
(audio->bytesPerSample() * audio->numChannels());
AudioMessage *ap = new
AudioMessage(bitDepth, audio->numChannels(), frames,
audio->sampleRate(), buf, allocbytes);
// There is nothing special we can do if put fails: no way to
// return status. Should we just exit ?
if (!audioqueue.put(ap, false)) {
LOGERR("sc2mpd: queue dead: exiting\n");
return 1;
}
}
return 0;
}
#endif
#define SOCK_PATH "/tmp/sc2mpd.sock"
#define BUF_SIZE 16
void HandleUserCmd(OhmReceiver* receiver, SongcastReceiver* driver,
AudioEater* audio, const Brx& aUri)
{
struct sockaddr_un server_addr, client_addr;
socklen_t len;
ssize_t num_bytes;
char buf[BUF_SIZE];
LOGDEB("OhmReceiver: Running user command handler\n");
g_sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (g_sockfd == -1) {
LOGERR("Error: Cannot create socket: " << strerror(errno) << endl);
goto _leave;
}
if (remove(SOCK_PATH) == -1 && errno != ENOENT) {
LOGERR("Error: Cannot remove socket path: " << strerror(errno) << endl);
goto _close_socket;
}
memset(&server_addr, 0, sizeof(struct sockaddr_un));
server_addr.sun_family = AF_UNIX;
strncpy(server_addr.sun_path, SOCK_PATH, sizeof(server_addr.sun_path) - 1);
if (bind(g_sockfd, (struct sockaddr *) &server_addr,
sizeof(struct sockaddr_un)) == -1) {
LOGERR("Error: Cannot bind to socket: " << strerror(errno) << endl);
goto _close_socket;
}
while (!g_quitrequest) {
len = sizeof(struct sockaddr_un);
// recvfrom() is a blocking call and will wait for messages to arrive.
// If no data has been received within `read_timeout` then -1 is
// returned by `recvfrom()` with errno set to EAGAIN or EWOULDBLOCK.
num_bytes = recvfrom(g_sockfd, buf, BUF_SIZE, 0,
(struct sockaddr *) &client_addr, &len);
if (num_bytes == -1) {
LOGERR("Error: Failed to receive from socket: " <<
strerror(errno) << endl);
continue; // Ignore failed request
}
if (num_bytes > 0) {
string response("OK");
LOGDEB("HandleUserCmd: Received " << num_bytes << " bytes: " <<
string(buf, num_bytes) << endl);
if (strncmp("play", buf, num_bytes) == 0)
receiver->Play(aUri);
else if (strncmp("stop", buf, num_bytes) == 0)
receiver->Stop();
else if (strncmp("state", buf, num_bytes) == 0) {
if (audio->state) {
switch (audio->state()) {
case AudioEater::AudioState::STOPPED:
response = "Stopped"; break;
case AudioEater::AudioState::PLAYING:
response = "Playing"; break;
case AudioEater::AudioState::UNKNOWN:
response = "Unknown";
break;
}
}
}
else if (strncmp("connstate", buf, num_bytes) == 0) {
response = driver->IsConnected() ? "Connected"
: "Disconnected";
}
ssize_t bytes_sent = sendto(g_sockfd, (const void *)response.c_str(),
response.length(), 0,
(struct sockaddr *)&client_addr, len);
if (bytes_sent == -1) {
LOGERR("Error: Cannot write to socket: " <<
strerror(errno) << endl);
}
}
}
_close_socket:
if (g_sockfd > 0)
close(g_sockfd);
_leave:
LOGDEB("OhmReceiver: Leaving user command handler\n");
}
int CDECL main(int aArgc, char* aArgv[])
{
string logfilename;
int loglevel(Logger::LLINF);
OptionParser parser;
OptionUint optionAdapter("-a", "--adapter", 0,
"[adapter] index of network adapter to use");
parser.AddOption(&optionAdapter);
OptionUint optionTtl("-t", "--ttl", 1, "[ttl] ttl");
parser.AddOption(&optionTtl);
OptionUint optionInteract("-i", "--interact", 0, "[interact] interactive");
parser.AddOption(&optionInteract);
OptionString optionUri("-u", "--uri", Brn("mpus://0.0.0.0:0"),
"[uri] uri of the sender");
parser.AddOption(&optionUri);
OptionString optionConfig("-c", "--config", Brn("/etc/upmpdcli.conf"),
"[config] upmpdcli configuration file path");
parser.AddOption(&optionConfig);
OptionBool optionDevice("-d", "--direct-alsa",
"[stream] Use alsa directly instead of producing "
"http stream");
parser.AddOption(&optionDevice);
OptionBool optionWatcher("-W", "--watcher",
"[watcher] Start a watcher thread"
"(needs --direct-alsa)");
parser.AddOption(&optionWatcher);
#ifdef WITH_WAVSC2
OptionString optionWav("-w", "--wav somefile.wav", Brn(""),
"Test audio with wav file instead of sender");
parser.AddOption(&optionWav);
#endif
if (!parser.Parse(aArgc, aArgv)) {
cerr << "Bad options, exiting\n";
return 1;
}
string uconfigfile = (const char *)optionConfig.Value().Ptr();
bool cfspecified = true;
if (uconfigfile.empty()) {
cfspecified = false;
uconfigfile = "/etc/upmpdcli.conf";
}
ConfSimple config(uconfigfile.c_str(), 1, true);
if (!config.ok()) {
cerr << "Could not open config: " << uconfigfile << endl;
if (cfspecified)
return 1;
}
config.get("sclogfilename", logfilename);
string value;
if (config.get("scloglevel", value))
loglevel = atoi(value.c_str());
if (Logger::getTheLog(logfilename) == 0) {
cerr << "Can't initialize log" << endl;
return 1;
}
Logger::getTheLog("")->setLogLevel(Logger::LogLevel(loglevel));
AudioEater::Context *ctxt = new AudioEater::Context(&audioqueue);
ctxt->config = &config;
#ifdef WITH_WAVSC2
string wavname(Brhz(optionWav.Value()).CString());
if (!wavname.empty()) {
string value;
if (!config.get("sccvttype", value) ||
value.compare("NONE")) {
cerr << "Wav input play test. NEEDS sccvttype == NONE\n";
return 1;
}
return playWav(wavname, &alsaAudioEater, ctxt);
}
#endif
InitialisationParams* initParams = InitialisationParams::Create();
Library* lib = new Library(initParams);
std::vector<NetworkAdapter*>* subnetList = lib->CreateSubnetList();
TIpAddress subnet = (*subnetList)[optionAdapter.Value()]->Subnet();
TIpAddress adapter = (*subnetList)[optionAdapter.Value()]->Address();
Library::DestroySubnetList(subnetList);
TUint ttl = optionTtl.Value();
Brhz uri(optionUri.Value());
LOGINF("scmpdcli: using subnet " << (subnet & 0xff) << "." <<
((subnet >> 8) & 0xff) << "." << ((subnet >> 16) & 0xff) << "." <<
((subnet >> 24) & 0xff) << endl);
AudioEater* eater = optionDevice.Value() ?
&alsaAudioEater : &httpAudioEater;
SongcastReceiver* driver = new SongcastReceiver(eater, ctxt);
OhmReceiver* receiver = new OhmReceiver(lib->Env(), adapter, ttl, *driver);
CpStack* cpStack = lib->StartCp(subnet);
cpStack = cpStack; // avoid unused variable warning
Debug::SetLevel(Debug::kMedia);
signal(SIGINT, sigcatcher);
signal(SIGTERM, sigcatcher);
if (optionInteract.Value()) {
printf("q = quit\n");
for (;;) {
int key = mygetch();
if (key == 'q') {
printf("QUIT\n");
break;
} else if (key == 'p') {
printf("PLAY %s\n", uri.CString());
receiver->Play(uri);
} else if (key == 's') {
printf("STOP\n");
receiver->Stop();
}
}
} else {
if (optionDevice.Value() && optionWatcher.Value()) {
startWatcher(config);
}
receiver->Play(uri);
for (;;) {
HandleUserCmd(receiver, driver, eater, uri);
if (g_quitrequest) {
LOGDEB("Quit requested\n");
break;
}
sleep(1000);
}
}
delete(receiver);
delete driver;
delete lib;
if (optionInteract.Value())
printf("\n");
LOGDEB("EXIT\n");
return (0);
}