Child: [137578] (diff)

Download this file

mpd2sc.cpp    518 lines (448 with data), 17.5 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*
Copyright 2012, OpenHome. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY OPENHOME ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation
are those of the authors and should not be interpreted as representing
official policies, either expressed or implied, of OpenHome.
*/
#include <OpenHome/OhNetTypes.h>
#include <OpenHome/Net/Core/DvDevice.h>
#include <OpenHome/Net/Core/OhNet.h>
#include <OpenHome/Net/Core/CpDevice.h>
#include <OpenHome/Net/Core/CpDeviceUpnp.h>
#include <OpenHome/Private/Ascii.h>
#include <OpenHome/Private/Thread.h>
#include <OpenHome/Private/OptionParser.h>
#include <OpenHome/Private/Debug.h>
#include <OpenHome/Os.h>
#include <OpenHome/Private/Env.h>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#ifdef WITH_OHBUILD
#include "OhmSender.h"
#else
#include <OpenHome/OhmSender.h>
#endif
#include "log.h"
#include "icon.h"
#include "audioreader.h"
#include "openaudio.h"
#include "base64.hxx"
using namespace std;
using namespace OpenHome;
using namespace OpenHome::Net;
using namespace OpenHome::TestFramework;
using namespace OpenHome::Av;
// Sig catcher so that we can interrupt the pause() which will be
// waiting for playing to end. Also set a flag for the benefit of busyRdWr()
bool g_quitrequest = false;
void sigcatcher(int)
{
LOGDEB("sigcatcher\n");
g_quitrequest = true;
}
class PcmSender {
public:
static const TUint kPeriodMs = 10;
static const TUint kSpeedNormal = 100;
static const TUint kSpeedMin = 75;
static const TUint kSpeedMax = 150;
static const TUint kMaxPacketBytes = 4096;
public:
PcmSender(Environment& aEnv, OhmSender* aSender,
OhmSenderDriver* aDriver, const Brx& aUri,
AudioReader* audio, bool paced);
bool Start();
void Pause();
void Restart();
~PcmSender();
void busyRdWr();
private:
void CalculatePacketBytes();
void TimerExpired();
private:
Environment& iEnv;
OhmSender* iSender;
OhmSenderDriver* iDriver;
Bws<OhmSender::kMaxTrackUriBytes> iUri;
AudioReader *m_audio;
Timer iTimer;
Mutex iMutex;
TBool iPaused;
TUint iSpeed; // percent, 100%=normal
TUint iIndex; // byte offset read position in source data
TUint iPacketBytes; // how many bytes of audio in each packet
TUint iPacketFrames; // how many audio frames in each packet
TUint iPacketTime; // how much audio time in each packet, uS
TUint64 iLastTimeUs; // last time stamp from system
TInt32 iTimeOffsetUs; // running offset in usec from ideal time
// <0 means sender is behind
// >0 means sender is ahead
TBool iVerbose;
TBool iPaced;
};
PcmSender::PcmSender(Environment& aEnv, OhmSender* aSender,
OhmSenderDriver* aDriver,
const Brx& aUri, AudioReader* audio, bool paced)
: iEnv(aEnv)
, iSender(aSender)
, iDriver(aDriver)
, iUri(aUri)
, m_audio(audio)
, iTimer(aEnv, MakeFunctor(*this, &PcmSender::TimerExpired), "PcmSender")
, iMutex("WAVP")
, iPaused(false)
, iSpeed(kSpeedNormal)
, iIndex(0)
, iLastTimeUs(0)
, iTimeOffsetUs(0)
, iVerbose(false)
, iPaced(paced)
{
CalculatePacketBytes();
LOGDEB("bytes per packet: " << iPacketBytes << endl);
LOGDEB("frames per packet: " << iPacketFrames << endl);
LOGDEB("usec per packet: "<< iPacketTime << endl);
}
// We return true if the main thread should pause.
bool PcmSender::Start()
{
iDriver->SetAudioFormat(m_audio->sampleRate(), m_audio->byteRate() * 8,
m_audio->numChannels(),
m_audio->bitsPerSample(), true, Brn("WAV"));
iSender->SetEnabled(true);
iSender->SetTrack(iUri, Brx::Empty(), m_audio->sampleCount(), 0);
iSender->SetMetatext(Brn("PcmSender repeated play"));
// It seems that both hijacking the main thread and using the
// timer with a short timeout (see TimerExpired()) work.
// Don't know what's best. The timer approach is closer to the original
// code and leaves the main thread free for control ops if needed.
// Otoh, if no data appears on the fifo, the timer thread is stuck in read
// and the upnp side stops working (no sender advertised).
// Maybe the best approach would be to start a separate thread and
// use busyreading. Using the main thread for now.
static const bool optionbusy = true;
if (iPaced || !optionbusy) {
LOGDEB("PcmSender::Start: using timers\n");
iTimer.FireIn(kPeriodMs);
return true;
} else {
LOGDEB("PcmSender::Start: block on reading only\n");
busyRdWr();
return false;
}
}
void PcmSender::Pause()
{
iMutex.Wait();
if (iPaused) {
iPaused = false;
iLastTimeUs = 0;
iTimeOffsetUs = 0;
iTimer.FireIn(kPeriodMs);
} else {
iPaused = true;
}
iMutex.Signal();
}
void PcmSender::Restart()
{
iMutex.Wait();
iIndex = 0;
iMutex.Signal();
}
void PcmSender::CalculatePacketBytes()
{
// in order to let wavsender change the playback rate,
// we keep constant it's idea of how much audio time is in each packet,
// but vary the amount of data that is actually sent
// calculate the amount of time in each packet
TUint norm_bytes = (m_audio->sampleRate() * m_audio->bytesPerFrame() *
kPeriodMs) / 1000;
if (norm_bytes > kMaxPacketBytes) {
norm_bytes = kMaxPacketBytes;
}
TUint norm_packet_samples = norm_bytes / m_audio->bytesPerFrame();
iPacketTime = (norm_packet_samples*1000000/(m_audio->sampleRate()/10) + 5)/10;
// calculate the adjusted speed packet size
TUint bytes = (norm_bytes * iSpeed) / 100;
if (bytes > kMaxPacketBytes) {
bytes = kMaxPacketBytes;
}
iPacketFrames = bytes / m_audio->bytesPerFrame();
iPacketBytes = iPacketFrames * m_audio->bytesPerFrame();
}
void PcmSender::busyRdWr()
{
LOGDEB("PcmSender:busyRdWr: packetbytes " << iPacketBytes << endl);
while (true) {
if (g_quitrequest) {
return;
}
const unsigned char *cp = m_audio->data((size_t)iPacketBytes);
if (cp == 0) {
return;
}
if (g_quitrequest) {
return;
}
iDriver->SendAudio(cp, iPacketBytes);
}
}
void PcmSender::TimerExpired()
{
iMutex.Wait();
if (!iPaused) {
TUint64 now = OsTimeInUs(iEnv.OsCtx());
const unsigned char *cp = m_audio->data((size_t)iPacketBytes);
if (cp == 0) {
static bool sigsent = false;
if (!sigsent) {
LOGDEB("PcmSender::TimerExpired: killing myself\n");
kill(getpid(), SIGUSR1);
sigsent = true;
}
} else {
iDriver->SendAudio(cp, iPacketBytes);
}
if (!iPaced) {
// Means we're doing blocking reads on the source, and
// it's setting the pace. I'd like to actually use 0 here
// (ala qt processEvents()), but this appears to busyloop
// and not let the sender do its thing. Anyway, as long
// as we can read from the fifo in much less than (period-2),
// which should always be true, we should be ok.
// I can see not much difference between doing this or
// hijacking the main thread for busy read/write
iTimer.FireIn(2);
} else {
// skip the first packet, and any time the clock value wraps
if (iLastTimeUs && iLastTimeUs < now) {
// will contain the new time out in ms
TUint new_timer_ms = kPeriodMs;
// the difference in usec from where we should be
TInt32 diff = (TInt32)(now - iLastTimeUs) - iPacketTime;
// increment running offset
iTimeOffsetUs -= diff;
// determine new timer value based upon current offset from ideal
if (iTimeOffsetUs < -1000) {
// we are late
TInt32 time_offset_ms = iTimeOffsetUs/1000;
if (time_offset_ms < 1-(TInt32)kPeriodMs) {
// in case callback is severely late, we can only
// catch up so much
new_timer_ms = 1;
} else {
new_timer_ms = kPeriodMs + time_offset_ms;
}
} else if (iTimeOffsetUs > 1000) {
// we are early
new_timer_ms = kPeriodMs+1;
} else {
// we are about on time
new_timer_ms = kPeriodMs;
}
// set timer
iTimer.FireIn(new_timer_ms);
// logging
if (iVerbose) {
if (iTimeOffsetUs >= 1000)
printf ("tnow:%d tlast:%d actual:%4d diff:%4d offset:%5d timer:%d\n", (TUint)now, (TUint)iLastTimeUs, (TUint)(now-iLastTimeUs), diff, iTimeOffsetUs, new_timer_ms);
else
printf ("tnow:%d tlast:%d actual:%4d diff:%4d offset:%4d timer:%d\n", (TUint)now, (TUint)iLastTimeUs, (TUint)(now-iLastTimeUs), diff, iTimeOffsetUs, new_timer_ms);
}
} else {
iTimer.FireIn(kPeriodMs);
}
iLastTimeUs = now;
}
}
iMutex.Signal();
}
PcmSender::~PcmSender()
{
iTimer.Cancel();
delete (iSender);
delete (iDriver);
}
static char *thisprog;
static char usage [] =
" -h, --help, show this help message and exit.\n"
" -A, --audio, [44100:16:2:0/1] audio params only if they can't be obtained\n"
" from the file. Conflicting values will cause error."
" -a, --adapter, [adapter] index of network adapter to use.\n"
" -c, --channel, [0..65535] sender channel.\n"
" -d, --disabled, [disabled] start up disabled.\n"
" -f, --file, [file] file name to read and send.\n"
" Use xx.wav for an actual wav,\n"
" xx or xx.fifo for a fifo, stdin for stdin.\n"
" -l, --latency, [latency] latency in ms.\n"
" -m, --multicast, [multicast] use multicast instead of unicast.\n"
" -p, --pace, Use internal timer to pace source. Implicit for regular files.\n"
" -n, --name, [name] name of the sender.\n"
" -t, --ttl, [ttl] ttl.\n"
" -u, --udn, [udn] udn for the upnp device.\n"
;
static void
Usage(FILE *fp = stderr)
{
fprintf(fp, "%s: usage:\n%s", thisprog, usage);
exit(1);
}
#include <getopt.h>
static int op_flags;
#define OPT_A 0x1
#define OPT_a 0x2
#define OPT_c 0x4
#define OPT_d 0x8
#define OPT_f 0x10
#define OPT_l 0x20
#define OPT_m 0x40
#define OPT_n 0x80
#define OPT_p 0x100
#define OPT_t 0x200
#define OPT_u 0x400
static struct option long_options[] = {
{"audio", required_argument, 0, 'A'},
{"adapter", required_argument, 0, 'a'},
{"channel", required_argument, 0, 'c'},
{"disabled", 0, 0, 'd'},
{"file", required_argument, 0, 'f'},
{"latency", required_argument, 0, 'l'},
{"multicast", 0, 0, 'm'},
{"name", required_argument, 0, 'n'},
{"pace", 0, 0, 'p'},
{"ttl", required_argument, 0, 't'},
{"udn", required_argument, 0, 'u'},
{0, 0, 0, 0}
};
int main(int argc, char **argv)
{
thisprog = argv[0];
int ret;
(void)op_flags;
string audioparams, sfile, sname("Openhome WavSender"), sudn("12345678");
unsigned int adaptidx(0), channel(0), ttl(1), latency(100);
while ((ret = getopt_long(argc, argv, "A:a:c:df:l:mn:pt:u:",
long_options, NULL)) != -1) {
switch (ret) {
case 'A': audioparams = optarg;op_flags |= OPT_A; break;
case 'a': adaptidx = atoi(optarg);op_flags |= OPT_a; break;
case 'c': channel = atoi(optarg);op_flags |= OPT_c; break;
case 'd': op_flags |= OPT_d; break;
case 'f': sfile = optarg;op_flags |= OPT_f; break;
case 'h': Usage(stdout);break;
case 'l': latency = atoi(optarg); op_flags |= OPT_l; break;
case 'm': op_flags |= OPT_m; break;
case 'n': sname = optarg;op_flags |= OPT_n; break;
case 'p': op_flags |= OPT_p; break;
case 't': ttl = atoi(optarg);op_flags |= OPT_t; break;
case 'u': sudn = optarg;op_flags |= OPT_u; break;
default:
Usage();
}
}
if (optind != argc )
Usage();
InitialisationParams* initParams = InitialisationParams::Create();
Library* lib = new Library(initParams);
std::vector<NetworkAdapter*>* subnetList = lib->CreateSubnetList();
LOGDEB("adapter list:\n");
for (unsigned i=0; i<subnetList->size(); ++i) {
TIpAddress addr = (*subnetList)[i]->Address();
LOGDEB(" " << i << ": " << (addr&0xff) << "." <<
((addr>>8)&0xff) << "." << ((addr>>16)&0xff) << "." <<
((addr>>24)&0xff) << endl);
}
if (subnetList->size() <= adaptidx) {
LOGERR("ERROR: adapter " << adaptidx << "doesn't exist\n");
return (1);
}
TIpAddress subnet = (*subnetList)[adaptidx]->Subnet();
TIpAddress adapter = (*subnetList)[adaptidx]->Address();
Library::DestroySubnetList(subnetList);
lib->SetCurrentSubnet(subnet);
LOGDEB("using subnet " << (subnet&0xff) << "." << ((subnet>>8)&0xff) << "."
<< ((subnet>>16)&0xff) << "." << ((subnet>>24)&0xff) << endl);
if (sfile.empty()) {
LOGERR("No input file specified\n");
return (1);
}
Brhz file(sfile.c_str());
Brhz udn(sudn.c_str());
Brhz name(sname.c_str());
TBool multicast = op_flags & OPT_m;
TBool disabled = op_flags & OPT_d;
TBool needpace = op_flags & OPT_p;
AudioReader *audio = openAudio(sfile, audioparams, !needpace);
if (!audio || !audio->open()) {
cerr << "Audio file open failed" << endl;
return 1;
}
needpace = !audio->isblocking();
LOGDEB("sample rate: " << audio->sampleRate() << endl);
LOGDEB("sample size: " << audio->bytesPerSample() << endl);
LOGDEB("channels: " << audio->numChannels() << endl);
DvStack* dvStack = lib->StartDv();
DvDeviceStandard* device = new DvDeviceStandard(*dvStack, udn);
device->SetAttribute("Upnp.Domain", "av.openhome.org");
device->SetAttribute("Upnp.Type", "Sender");
device->SetAttribute("Upnp.Version", "1");
device->SetAttribute("Upnp.FriendlyName", name.CString());
device->SetAttribute("Upnp.Manufacturer", "Openhome");
device->SetAttribute("Upnp.ManufacturerUrl", "http://www.openhome.org");
device->SetAttribute("Upnp.ModelDescription", "Openhome WavSender");
device->SetAttribute("Upnp.ModelName", "Openhome WavSender");
device->SetAttribute("Upnp.ModelNumber", "1");
device->SetAttribute("Upnp.ModelUrl", "http://www.openhome.org");
device->SetAttribute("Upnp.SerialNumber", "");
device->SetAttribute("Upnp.Upc", "");
OhmSenderDriver* driver = new OhmSenderDriver(lib->Env());
Brn icon(icon_png, icon_png_len);
OhmSender* sender =
new OhmSender(lib->Env(), *device, *driver, name, channel, adapter, ttl,
latency, multicast, !disabled, icon, Brn("image/png"), 0);
PcmSender* pcmsender = new PcmSender(lib->Env(), sender, driver, file,
audio, needpace);
device->SetEnabled();
const Brx& suri(sender->SenderUri());
string uri((const char*)suri.Ptr(), suri.Bytes());
const Brx& smeta(sender->SenderMetadata());
string meta((const char*)smeta.Ptr(), smeta.Bytes());
cout << "URI " << UPnPP::base64_encode(uri) <<
" METADATA " << UPnPP::base64_encode(meta) << endl;
// cout << "URI " << uri << " METADATA " << meta << endl;
cout.flush();
signal(SIGUSR1, sigcatcher);
signal(SIGINT, sigcatcher);
signal(SIGTERM, sigcatcher);
if (pcmsender->Start()) {
pause();
}
LOGDEB("Main: cleaning up\n");
delete (pcmsender);
delete (device);
UpnpLibrary::Close();
return (0);
}