StreamBD.cpp 15.8 KB
Newer Older
jcaceres's avatar
jcaceres committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
// File: StreamBD.cpp
// Created by: User <Email>
// Created on: Tue Apr 13 22:19:53 2004
//

//#include "StreamBD.h"
#include "audioDevice.h"

extern QString *
IPv4Addr (char *namebuf);

/**
 * @brief return fifo priority for streambd.
 */
int
get_fifo_priority (bool half)
{
	int min, max, priority;

	min = sched_get_priority_min (SCHED_FIFO);
	max = sched_get_priority_max (SCHED_FIFO);
23
	if (half) priority = (max  - (max - min) / 2);
jcaceres's avatar
jcaceres committed
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
		else
	priority = max; 
//      priority=min;
	return priority;
}

/**
 * @brief Set fifo priority (if user has sufficient privileges).
 */
int
set_fifo_priority (bool half)
{
	struct sched_param p;
	int priority;
	//  scheduling priority


	if (true) // (!getuid () || !geteuid ())
	{
		priority = get_fifo_priority (half);
		p.sched_priority = priority;

		if (sched_setscheduler (0, SCHED_FIFO, &p) == -1)
		{
			fprintf (stderr,
				 "\ncould not activate scheduling with priority %d\n",
				 priority);
			return -1;
		}
		seteuid (getuid ());
		fprintf (stderr,
			 "\nset scheduling priority to %d (SCHED_FIFO)\n",
			 priority);
	}
	else
	{
		fprintf (stderr,
			 "\ninsufficient privileges to set scheduling priority\n");
		priority = 0;
	}
	return priority;
}


StreamBD::StreamBD()
{
	args = new cmdLineArgs;

}


StreamBD::~StreamBD()
{
	// TODO: put destructor code here
}

int
StreamBD::cmd (MainDialog *eventThread)
{
	// Get the local host address
	QString *localhostName = GetLocalHostName ();

	clock_t *lastTickTime = NULL;
	if (false)
	{			// change to cmd line option
		lastTickTime = new clock_t ();
		*(lastTickTime) = clock ();
	}

	AudioInfoT audioInfo = new AudioInfo (args->sampleRate, sizeof (INT16),
					      args->framesPerAudioBuffer,
					      args->audioChannels,
					      args->netHarpStrings,
					      args->secondsBetweenPlucks,
					      args->jack, lastTickTime,
							args->jack_alsa_readable_offset );

	NetworkInfoT netInfo = new NetworkInfo (*localhostName,
						audioInfo->
						getBytesPerBuffer (),
						UDP_IN_PORT +
						args->networkPortOffset,
						UDP_OUT_PORT +
						args->networkPortOffset,
						args->redundancy,
	args->networkInputQueueLengthInPackets);

	//   AudioDeviceT audioDevice;

	cout << "Creating Streams................";
	int networkInputQueueLengthInAudioBuffers = 
	args->networkInputQueueLengthInPackets * args->redundancy;
	t.streamin =
		new Stream (audioInfo, netInfo,
			    networkInputQueueLengthInAudioBuffers,
			    false);
	t.streamout =
		new Stream (audioInfo, netInfo, DEFAULT_OUTPUT_STREAM_QUEUE_LENGTH,
			    true);

	if (t.streamin != NULL && t.streamout != NULL)
	{
		cout << "SUCCESS!" << endl;
	}
	else
	{
		cout << "FAILED!" << endl;
		return -1;
	}

	switch (args->runMode)
	{
	case AUDIOINFO:
		audioDevice = new AudioDevice (true);
		exit (0);

	case NETMIRROR:
		t.netin = new UDPInput (netInfo, audioInfo);
		t.netout = new UDPOutput (netInfo, audioInfo);

		ConnectPlugins (t.netin, t.netout, t.streamout);
		break;

	case HARPT:

		t.netin = new UDPInput (netInfo, audioInfo);
		t.netout = new UDPOutput (netInfo, audioInfo);

		addSTKProcesses (t.streamin);

		ConnectPlugins (t.netin, t.netout, t.streamin);

		audioDevice = new AudioDevice (args->audioDeviceID,
					       args->
					       audioInputQueueLengthInAudioBuffers,
					       AudioDevice::DUPLEX,
					       audioInfo);

		t.audioout = new AudioOutput (audioDevice, audioInfo);

		addPlugin (t.audioout, t.streamin);

		// Synchronize network packet transfers to audio device tick rate.
		t.streamin->synchronizeOutputsTo (t.audioout);

		break;

	case HARPR:

		t.netin = new UDPInput (netInfo, audioInfo);
		t.netout = new UDPOutput (netInfo, audioInfo);

		addSTKProcesses (t.streamout);

		ConnectPlugins (t.netin, t.netout, t.streamout);

		break;

	case SNDMIRROR:
		audioDevice = new AudioDevice (args->audioDeviceID,
					       args->
					       audioInputQueueLengthInAudioBuffers,
					       AudioDevice::DUPLEX,
					       audioInfo);

		t.audioin = new AudioInput (audioDevice, audioInfo);
		t.audioout = new AudioOutput (audioDevice, audioInfo);

		ConnectPlugins (t.audioin, t.audioout, t.streamout);
		break;

	default:
		audioDevice = new AudioDevice (args->audioDeviceID,
					       args->
					       audioInputQueueLengthInAudioBuffers,
					       AudioDevice::DUPLEX,
					       audioInfo);

		t.audioin = new AudioInput (audioDevice, audioInfo);
		t.audioout = new AudioOutput (audioDevice, audioInfo);
	
audioDevice->setThreads(t);

		t.netin = new UDPInput (netInfo, audioInfo);
jcaceres's avatar
jcaceres committed
208
	t.netin->setGUI((QObject *)eventThread);
jcaceres's avatar
jcaceres committed
209
		t.netout = new UDPOutput (netInfo, audioInfo);
jcaceres's avatar
jcaceres committed
210
	t.netout->setGUI((QObject *)eventThread);
jcaceres's avatar
jcaceres committed
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

		ConnectPlugins (t.audioin, t.netout, t.streamout);
		ConnectPlugins (t.netin, t.audioout, t.streamin);

	}

	if (args->runFifo)
		set_fifo_priority (true);

	cout << "Running 0" << endl;
	// TRANSMIT, RECEIVE, and HARPT modes all use streamin
	// The other modes only use the unbuffered streamout.
	if (args->runMode == TRANSMIT || args->runMode == RECEIVE
	    || args->runMode == HARPT)
	{
		t.streamin->startThreads ();
	} 
	cout << "Running 1" << endl;

	if (args->runMode == NETMIRROR || args->runMode == HARPR)
		t.netin->start ();	// needs to run to
	// listen for peer address
	cout << "Running 2" << endl;

	// All modes except for SNDMIRROR use netin and netout
	// and therefore need to have a network connection established.
	if (args->runMode != SNDMIRROR)
		EstablishConnection (args->runMode, args->remoteHostname,
				     t.netout, t.netin);
	cout << "Running 3" << endl;

	if (args->runMode != HARPT)
		t.streamout->startThreads ();
	cout << "Running 4" << endl;

	if (args->jack && (args->runMode != NETMIRROR || args->runMode == HARPR))
		audioDevice->jackStart ();

	cout << "Running " << endl;
}


void
StreamBD::start ()
{
}

void
StreamBD::finish ()
{
	cout << "Finishing" << endl;
	if (args->jack)
		audioDevice->jackStop ();
	if (t.streamin->threadsRunning)
		t.streamin->stopThreads ();
	cout << "stopped streamin threads" << endl;
	if (t.streamout->threadsRunning)
		t.streamout->stopThreads ();
	cout << "stopped streamout threads" << endl;	
}

void
StreamBD::go ()
/* cause run loop to start */
{
	start ();
}

void
StreamBD::stop ()
/* cause run loop to finish */
{
//	loop = false; not a thread
	finish();
}

void
StreamBD::join ()
/* wait for thread to exit */
{
//	wait (); not a thread
}



/* PrintUsage(struct cmdLineArgs *args)
 * ------------------------------------
 * Print all of the command line arguments and their default values
 */
void
StreamBD::PrintUsage ()
{
	cout << "===========================================================================" << endl;
304
305
	cout << "   jacktrip	A project of the SoundWIRE group at CCRMA, Stanford." << endl;
	cout << " 		http://ccrma.stanford.edu/groups/soundwire/software/" << endl << endl;
jcaceres's avatar
jcaceres committed
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
	cout << "===========================================================================" << endl;
	cout << " Needs to be run in one of the following modes:" << endl;
	cout << "	-r		Receiver	(opens audio channels and waits" << endl;
	cout << "				 	for a connection from a transmitter)" << endl;
	cout << "	-t HOSTNAME	Transmitter 	(connects to a receiver on HOSTNAME)" << endl;
	cout << "	-n		NetMirror 	(A receiver that reflects back all" << endl;
	cout << "				 	audio sent to it by a transmitter." << endl;
	cout << "					No local audio.)" <<
		endl;
	cout << "	-s		SndMirror 	(Routes sound input to output." << endl;
	cout << "					No networking.)" <<
		endl;
	cout << "	-h HOSTNAME	HarpTransmitter	(uses network as harp strings.)" << endl;
	cout << "	-p		HarpReceiver	(uses network as harp strings.)" << endl;
	cout << "	-i		Info		(Get audio device info.)" << endl;
	cout << "---------------------------------------------------------------------------" << endl;
	cout << " Optional parameters are as follows:				(default)" << endl;
	cout << "	-z 	Number of audio frames per audio buffer.	(" << args->framesPerAudioBuffer << ")" << endl;
	cout << "	-b 	Number of audio buffers in network packet (redundancy).	(" << args->redundancy << ")" << endl;
	cout << "	-q 	Number of packets in input queue.	(" << args->networkInputQueueLengthInPackets << ")" << endl;
	cout << "	-B 	Number of audio buffers in audio input queue.	(" << args->audioInputQueueLengthInAudioBuffers << ")" << endl;
	cout << "	-c 	Number of NetHarp strings.			(" << args->netHarpStrings << ")" << endl;
	cout << "	-a 	Number of audio channels to use.		(" << args->audioChannels << ")" << endl;
	cout << "	-D 	Audio device to use if not default.		(" << args->audioDeviceID << ")" << endl;
	cout << "	-o 	Network port offset.				(" << args->networkPortOffset << ")" << endl;
	cout << "	-f 	Run fifo (scheduling priority).			(" << args->runFifo << ")" << endl;
	cout << "	-P 	Seconds between Netharp plucks.			(" << args->secondsBetweenPlucks << ")" << endl;
	cout << "	-l 	Integer % low pass filter coefficient.		(" << args->lowPassFilterCoeff << ") 0 = off" << endl;
	cout << "	-d 	Delay increment between strings (msec.) 	(" << args->delayIncrementBetweenStrings << ") 0 = off" << endl;
	cout << "	-j		jack 	(" << args->jack << ")" << endl;
	cout << "	-J		jack alsa readable offset	(" << args->jack_alsa_readable_offset << ")" << endl;
	cout << "	-g		gui	(" << args->gui << ")" << endl;
	cout << endl;
339
	cout << "	run 'src/jacktrip' to see these instructions." <<
jcaceres's avatar
jcaceres committed
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
		endl;
}

/**
 * @brief Parse the command line.
 *
 * Use default values for all cmdLineArgs entries
 * unless explicitly assigned values on the commandline.
 */
int
StreamBD::ParseCommandLine (int argc, char *argv[])
{

// Set Default Values
	args->sampleRate = DEFAULT_SAMPLE_RATE;
	args->netHarpStrings = DEFAULT_NETHARP_STRINGS;
	args->audioChannels = DEFAULT_AUDIO_CHANNELS;
	args->runFifo = DEFAULT_FIFO;
	args->audioDeviceID = DEFAULT_AUDIO_DEVICE;
	args->networkInputQueueLengthInPackets =
		DEFAULT_NETWORK_QUEUE_LENGTH;
	args->audioInputQueueLengthInAudioBuffers =
		DEFAULT_AUDIO_QUEUE_LENGTH;
	args->framesPerAudioBuffer = DEFAULT_AUDIO_BUFFER_SIZE;
	args->networkPortOffset = DEFAULT_NETWORK_PORT_OFFSET;
	args->runMode = RECEIVE;
	args->secondsBetweenPlucks = DEFAULT_SECONDS_BETWEEN_PLUCKS;
	args->lowPassFilterCoeff = DEFAULT_LOW_PASS_FILTER_COEFFICIENT;
	args->delayIncrementBetweenStrings = DEFAULT_DELAY_LINE_COEFFICIENT;
	args->jack = DEFAULT_JACK;
	args->gui = DEFAULT_GUI;
	args->redundancy = DEFAULT_PACKET_REDUNDANCY;
	args->jack_alsa_readable_offset = DEFAULT_JACK_ALSA_READABLE_OFFSET;

	// If no command arguments are given, print instructions
	if (argc <= 1)
	{
		PrintUsage ();
		return 0;
	}

	// Override defaults if expicitly specified on the command line
	char ch;
	while ((ch =
		getopt (argc, argv,
			"trnsjghpifd:o:c:z:b:B:D:l:e:a:P:q:J:")) != EOF)
		switch (ch)
		{
		case 'd':
			args->delayIncrementBetweenStrings = atoi (optarg);
			break;
		case 'l':
			args->lowPassFilterCoeff = (float) atoi (optarg);
			break;
		case 'z':
			args->framesPerAudioBuffer = atoi (optarg);
			break;
		case 'q':
			args->networkInputQueueLengthInPackets =
				atoi (optarg);
			break;
		case 'b':
			args->redundancy =
				atoi (optarg);
			break;
		case 'B':
			args->audioInputQueueLengthInAudioBuffers =
				atoi (optarg);
			break;
		case 'c':
			args->netHarpStrings = atoi (optarg);
			break;
		case 'a':
			args->audioChannels = atoi (optarg);
			break;
		case 'D':
			args->audioDeviceID = atoi (optarg);
			break;
		case 'o':
			args->networkPortOffset = atoi (optarg);
			break;
		case 's':
			args->runMode = SNDMIRROR;
			break;
		case 'j':
			args->jack = true;
			break;
		case 'J':
			args->jack_alsa_readable_offset = atoi (optarg);
			break;
		case 'g':
			args->gui = true;
			break;
		case 'n':
			args->runMode = NETMIRROR;
			break;
		case 't':
			args->runMode = TRANSMIT;
			break;
		case 'r':
			args->runMode = RECEIVE;
			break;
		case 'h':
			args->runMode = HARPT;
			break;
		case 'p':
			args->runMode = HARPR;
			break;
		case 'i':
			args->runMode = AUDIOINFO;
			break;
		case 'f':
			args->runFifo = 1;
			break;
		case 'P':
			args->secondsBetweenPlucks = atoi (optarg);
			break;
		default:
			PrintUsage ();
			return 0;
		}
	argc -= optind;
	argv += optind;

	// In harp mode, the default number of netHarpStrings is audioChannels
	if (args->runMode == HARPR || args->runMode == HARPT)
	{
		if (args->netHarpStrings <= 0)
			args->netHarpStrings = args->audioChannels;
		cerr << "Running a NetHarp with " << args->
			netHarpStrings << " strings, plucked every " << args->
			secondsBetweenPlucks << " seconds." << endl;
	}

	// If we're in transmit or harpt mode, make sure we have
	// a hostname to connect to.
	if (args->runMode == TRANSMIT || args->runMode == HARPT)
	{
		if (argc > 0)
		{		/* Copy remote hostname */
			strncpy (args->remoteHostname, argv[0], 99);
			cout << "remote hostname is " << args->
				remoteHostname << endl;
		}
		else
		{
			cerr << "You must specify a remote hostname to run in transmit mode." << endl;
			cerr << "Run streambd with no arguments for command line instructions." << endl;
			return 0;
		}
	}
	return 1;
}

void
StreamBD::ConnectPlugins (InputPlugin * from, OutputPlugin * to, Stream * through)
{
	from->setStream (through);
	to->setStream (through);

	through->addInput (from);
	through->addOutput (to);
}

void
StreamBD::addPlugin (InputPlugin * from, Stream * str)
{
	from->setStream (str);
	str->addInput (from);
}

void
StreamBD::addPlugin (OutputPlugin * to, Stream * str)
{
	to->setStream (str);
	str->addOutput (to);
}

void
StreamBD::addSTKProcesses (Stream * str)
{
// Declare STK filter processes for harp mode.
	OneZero *oneZero[args->netHarpStrings];
	STKProcess *oneZeroProcess[args->netHarpStrings];
	Delay *delay[args->netHarpStrings];
	STKProcess *delayProcess[args->netHarpStrings];

	// Add STKProcesses to every network channel.
	int thisDelay = 0;
	for (int i = 0; i < args->netHarpStrings; i++)
	{
		// The OneZero filter lowpasses the signal each time it reflects,
		// modelling the behavior of reflections from the ends of a string.
		if (args->lowPassFilterCoeff != 0)
		{
			oneZero[i] = new OneZero ();
			oneZeroProcess[i] =
				new STKProcess ((Filter *) oneZero[i]);
			oneZero[i]->setGain (args->lowPassFilterCoeff / 100.0);
			str->addProcess (oneZeroProcess[i]);
		}

		// The delay line tunes the strings so that they don't all
		// have the fundamental frequency determined by the network.
		if (args->delayIncrementBetweenStrings != 0)
		{
			thisDelay = args->delayIncrementBetweenStrings * i;
			delay[i] = new Delay ((long) thisDelay, (long) thisDelay);	// theDelay,maxDelay
			delayProcess[i] =
				new STKProcess ((Filter *) delay[i]);
			str->addProcess (delayProcess[i]);
		}
	}
}


/**
 * @brief Connects, or waits for connection depending on runMode.
 *
 * If transmit or harpt, connect to hostname.
 * If any other mode, wait for a peer, then connect back to that peer.
 */
void
StreamBD::EstablishConnection (runModeT runMode, char *hostname, UDPOutput * netout,
		     UDPInput * netin)
{
	if (runMode == TRANSMIT || runMode == HARPT)
	{
		cout << "Requesting Connection...........";
		QHostAddress *ha = new QHostAddress ();
		QString *s = IPv4Addr (hostname);	// dotted integer from name
		ha->setAddress (*s);
		netout->connect (*ha);
	}
	else
	{
		cout << endl << "Waiting for incoming connection." << endl;
		while (!netin->hasPeer ())
		{
			usleep (10000);
			 //     cout << ".";
		}
582
		cout << endl << "Connection received from: " <<
jcaceres's avatar
jcaceres committed
583
			netin->peer ().toString () << endl;
jcaceres's avatar
jcaceres committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
		cout << "Requesting return connection....";
		netout->connect (netin->peer ());
		cout << "SUCCESS!" << endl;
	}
}

/**
 * @brief Lookup the hostname of the local machine.
 */
QString *
StreamBD::GetLocalHostName ()
{
	char localhostbuf[100];
	if (gethostname (localhostbuf, 99))
	{
		perror ("gethostname");
		exit (-1);
	}
	QString *s = new QString (localhostbuf);
	return (s);
}

#include <sched.h>
int
set_realtime_priority (void)
{
	struct sched_param schp;

	memset (&schp, 0, sizeof (schp));
	schp.sched_priority = sched_get_priority_max (SCHED_FIFO);
	if (sched_setscheduler (0, SCHED_FIFO, &schp) != 0)
	{
		perror ("set_scheduler");
		return -1;
	}
	return 0;
}