summaryrefslogtreecommitdiffstats
path: root/artsc/artscbackend.cc
blob: a9f3a91a5ec85794a84471101f7beb8648eb69c4 (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
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
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
582
583
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
    /*

    Copyright (C) 2000 Stefan Westerfeld
                       [email protected]
                  2001 Matthias Kretz
                       [email protected]

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.
  
    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    */

#include "artsc.h"
#include "soundserver.h"
#include "stdsynthmodule.h"

#include <iostream>
#include <algorithm>
#include <queue>

#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include <assert.h>
#include "arts_export.h"

#define arts_backend_debug(x) ;

using namespace std;
using namespace Arts;

/**
 * Base class for streams
 */
class Stream
{
protected:
	SoundServer server;
	float serverBufferTime;

	bool _finished, isAttached;
	int _samplingRate, _bits, _channels, pos;
	string _name;
	queue< DataPacket<mcopbyte>* > streamqueue;

	int packetCount, packetCapacity;
	int blockingIO;

	/**
	 * returns the amount of bytes that will be played in a given amount of
	 * time in milliseconds
	 */
	int timeToBytes(float time)
	{
    	float playSpeed = _channels * _samplingRate * _bits / 8;
		return (int)(playSpeed * (time / 1000.0));
	}

	/**
	 * returns the time in milliseconds it takes with the current parameters
	 * to play a given amount of bytes
	 */
	float bytesToTime(int size)
	{
    	float playSpeed = _channels * _samplingRate * _bits / 8;
		return (1000.0 * ((float)size) / playSpeed);
	}

	int bufferSize() {
		return packetCount * packetCapacity;
	}

	float bufferTime() {
		return bytesToTime(bufferSize());
	}

	int bufferSpace() {
		int space = 0;

		attach();

		/* make sure that our information is up-to-date */
		Dispatcher::the()->ioManager()->processOneEvent(false);

		if(!streamqueue.empty())
		{
			space += packetCapacity - pos;  /* the first, half filled packet */

			if(streamqueue.size() > 1)			/* and the other, empty packets */
				space += (streamqueue.size()-1)*packetCapacity;
		}
		return space;
	}

	int setBufferSize(int size)
	{
		/* don't change sizes when already streaming */
		if(isAttached)
			return ARTS_E_NOIMPL;

		/*
		 * these parameters are usually a bad idea ;-) however we have to start
		 * somewhere, and maybe in two years, with a highly optimized kernel
		 * this is possible - for now, don't request the impossible or don't
		 * complain if it doesn't work
		 */
		packetCount = 3;
		packetCapacity = 128;

		/*
		 * - do not configure stream buffers smaller than the server
		 *   recommended value
		 * - try to get more or less close to the value the application
		 *   wants
		 */
		int needSize = max(size, timeToBytes(server.minStreamBufferTime()));

		while(bufferSize() < needSize)
		{
			packetCount++;
			if(packetCount == 8)
			{
				packetCount /= 2;
				packetCapacity *= 2;
			}
		}

		return bufferSize();
	}

	int packetSettings()
	{
		int settings = 0;

		int cap = packetCapacity;
		while(cap > 1)
		{
			settings++;
			cap /= 2;
		}

		settings |= packetCount << 16;
		return settings;
	}

	int setPacketSettings(int settings)
	{
		/* don't change sizes when already streaming */
		if(isAttached)
			return ARTS_E_NOIMPL;

		packetCount = settings >> 16;
		
		packetCapacity = 1;
		int c = settings & 0xffff;
		while(c > 0) {
			packetCapacity *= 2;
			c--;
		}

		/*
		 * - do not configure stream buffers smaller than the server
		 *   recommended value
		 * - keep the packetSize the applications specified
		 */
		int needSize = timeToBytes(server.minStreamBufferTime());

		while(bufferSize() < needSize)
			packetCount++;

		return packetSettings();
	}

	/**
	 * the stream has to attach itself
	 */
	virtual void attach() = 0;

public:
	Stream(SoundServer server, int rate, int bits, int channels,
		string name) : server(server), _finished(false), isAttached(false),
		_samplingRate(rate), _bits(bits), _channels(channels), pos(0),
		_name(name)
	{
		serverBufferTime = server.serverBufferTime();
		stream_set(ARTS_P_BUFFER_SIZE,64*1024);
		stream_set(ARTS_P_BLOCKING,1);
	}
	virtual ~Stream()
	{
		//
	}

	virtual int stream_set(arts_parameter_t param, int value)
	{
		int result;

		switch(param) {
			case ARTS_P_BUFFER_SIZE:
				return setBufferSize(value);

			case ARTS_P_BUFFER_TIME:
				result = setBufferSize(timeToBytes(value));
				if(result < 0) return result;
				return (int)bufferTime();

			case ARTS_P_PACKET_SETTINGS:
				return setPacketSettings(value);

			case ARTS_P_BLOCKING:
				if(value != 0 && value != 1) return ARTS_E_NOIMPL;

				blockingIO = value;
				return blockingIO;
			/*
			 * maybe ARTS_P_TOTAL_LATENCY _could_ be made writeable, the
			 * others are of course useless
			 */
			case ARTS_P_BUFFER_SPACE:
			case ARTS_P_SERVER_LATENCY:
			case ARTS_P_TOTAL_LATENCY:
			case ARTS_P_PACKET_SIZE:
			case ARTS_P_PACKET_COUNT:
				return ARTS_E_NOIMPL;
		}
		return ARTS_E_NOIMPL;
	}

	virtual int stream_get(arts_parameter_t param)
	{
		switch(param) {
			case ARTS_P_BUFFER_SIZE:
				return bufferSize();

			case ARTS_P_BUFFER_TIME:
				return (int)bufferTime();
			
			case ARTS_P_BUFFER_SPACE:
				return bufferSpace();

			case ARTS_P_PACKET_SETTINGS:
				return packetSettings();

			case ARTS_P_SERVER_LATENCY:
				return (int)serverBufferTime;

			case ARTS_P_TOTAL_LATENCY:
				return stream_get(ARTS_P_SERVER_LATENCY)
				     + stream_get(ARTS_P_BUFFER_TIME);

			case ARTS_P_BLOCKING:
				return blockingIO;

			case ARTS_P_PACKET_SIZE:
				return packetCapacity;

			case ARTS_P_PACKET_COUNT:
				return packetCount;
		}
		return ARTS_E_NOIMPL;
	}

	virtual int write(const mcopbyte * /*data*/, int /*size*/)
	{
		return ARTS_E_NOIMPL;
	}

	virtual int read(mcopbyte * /*data*/, int /*size*/)
	{
		return ARTS_E_NOIMPL;
	}

	virtual void close() = 0;

	int suspend()
	{
		if(isAttached)
		{
			return server.suspend();
		}
		return 0;
	}

	int suspended()
	{
		if(isAttached)
		{
			return 0;
		}
		return server.suspended();
	}
};

class Receiver :	public ByteSoundReceiver_skel,
					public StdSynthModule,
					virtual public Stream
{
	/*
	 * FIXME: bsWrapper is a more or less ugly trick to be able to use
	 * this object although not using smartwrappers to access it
	 */
	ByteSoundReceiver bsWrapper;

protected:
	virtual void attach()
	{
		if(!isAttached)
		{
			isAttached = true;

			server.attachRecorder(bsWrapper);
			start();

            /*
             * TODO: this processOneEvent looks a bit strange here... it is
             * there since StdIOManager does block 5 seconds on the first
             * arts_write if it isn't - although notifications are pending
             *
             * Probably the real solution is to rewrite the
             * StdIOManager::processOneEvent function. (And maybe drop the
             * assumption that aRts will not block when an infinite amount
             * of notifications is pending - I mean: will it ever happen?)
             */
            Dispatcher::the()->ioManager()->processOneEvent(false);
		}
	}

public:
	Receiver(SoundServer server, int rate, int bits, int channels,
		string name) : Stream( server, rate, bits, channels, name)
	{
		bsWrapper = ByteSoundReceiver::_from_base(this);
	}

	virtual ~Receiver() {
		//
	}

	long samplingRate() { return _samplingRate; }
	long channels()     { return _channels; }
	long bits()         { return _bits; }
	bool finished()     { return _finished; }
	string title()      { return _name; }

	void process_indata(DataPacket<mcopbyte> *packet)
	{
		streamqueue.push(packet);
	}

	void close()
	{
		if(isAttached)
		{
			/* remove all packets from the streamqueue */
			while(!streamqueue.empty())
			{
				DataPacket<mcopbyte> *packet = streamqueue.front();
				packet->processed();
				streamqueue.pop();
			}

			server.detachRecorder(bsWrapper);
		}
		// similar effect like "delete this;"		
		bsWrapper = ByteSoundReceiver::null();
	}

	int read(mcopbyte *data, int size)
	{
		attach();

		int remaining = size;
		while(remaining)
		{
			if(blockingIO)
			{
				/* C API blocking style read */
				while(streamqueue.empty())
					Dispatcher::the()->ioManager()->processOneEvent(true);
			}
			else
			{
				/* non blocking I/O */
				if(streamqueue.empty())
					Dispatcher::the()->ioManager()->processOneEvent(false);

				/* still no more packets to read? */
				if(streamqueue.empty())
					return size - remaining;
			}

			/* get a packet */
			DataPacket<mcopbyte> *packet = streamqueue.front();

			/* copy some data from there */
			int tocopy = min(remaining,packet->size-pos);
			memcpy(data,&packet->contents[pos],tocopy);
			pos += tocopy;
			data += tocopy;
			remaining -= tocopy;

			/* have we read the whole packet? then get rid of it */
			if(pos == packet->size)
			{
				packet->processed();
				streamqueue.pop();
				pos = 0;
			}
		}

		/* no possible error conditions */
		return size;
	}
};

class Sender :	public ByteSoundProducerV2_skel,
				public StdSynthModule,
				virtual public Stream
{
	/*
	 * FIXME: bsWrapper is a more or less ugly trick to be able to use
	 * this object although not using smartwrappers to access it
	 */
	ByteSoundProducerV2 bsWrapper;

protected:
	virtual void attach()
	{
		if(!isAttached)
		{
			isAttached = true;

			server.attach(bsWrapper);
			start();

            /*
             * TODO: this processOneEvent looks a bit strange here... it is
             * there since StdIOManager does block 5 seconds on the first
             * arts_write if it isn't - although notifications are pending
             *
             * Probably the real solution is to rewrite the
             * StdIOManager::processOneEvent function. (And maybe drop the
             * assumption that aRts will not block when an infinite amount
             * of notifications is pending - I mean: will it ever happen?)
             */
            Dispatcher::the()->ioManager()->processOneEvent(false);
		}
	}

public:
	Sender(SoundServer server, int rate, int bits, int channels,
		string name) : Stream( server, rate, bits, channels, name)
	{
		bsWrapper = ByteSoundProducerV2::_from_base(this);
	}

	virtual ~Sender() {
		//
	}

	long samplingRate() { return _samplingRate; }
	long channels()     { return _channels; }
	long bits()         { return _bits; }
	bool finished()     { return _finished; }
	string title()      { return _name; }

	void streamStart()
	{
		/*
		 * start streaming
		 */
		outdata.setPull(packetCount, packetCapacity);
	}

	void request_outdata(DataPacket<mcopbyte> *packet)
	{
		streamqueue.push(packet);
	}

	void close()
	{
		if(isAttached)
		{
			if(pos != 0)
			{
				/* send the last half-filled packet */
				DataPacket<mcopbyte> *packet = streamqueue.front();
				packet->size = pos;
				packet->send();
				streamqueue.pop();
			}
			outdata.endPull();

			/* remove all packets from the streamqueue */
			while(!streamqueue.empty())
			{
				DataPacket<mcopbyte> *packet = streamqueue.front();
				packet->size = 0;
				packet->send();
				streamqueue.pop();
			}

			server.detach(bsWrapper);
		}
		// similar effect like "delete this;"		
		Arts::ByteSoundProducerV2_base* x = _copy();
		bsWrapper = ByteSoundProducerV2::null();
		x->_release();
	}

	int write(const mcopbyte *data, int size)
	{
		attach();

		int remaining = size;
		while(remaining)
		{
			if(blockingIO)
			{
				/* C API blocking style write */
				/* we're not waiting for any data here, but rather for
				 * DataPackets that we can fill */
				while(streamqueue.empty())
					Dispatcher::the()->ioManager()->processOneEvent(true);
			}
			else
			{
				/* non blocking I/O */
				if(streamqueue.empty())
					Dispatcher::the()->ioManager()->processOneEvent(false);

				/* still no more space to write? */
				if(streamqueue.empty())
					return size - remaining;
			}

			/* get a packet */
			DataPacket<mcopbyte> *packet = streamqueue.front();

			/* copy some data there */
			int tocopy = min(remaining,packetCapacity-pos);
			memcpy(&packet->contents[pos],data,tocopy);
			pos += tocopy;
			data += tocopy;
			remaining -= tocopy;

			/* have we filled up the packet? then send it */
			if(pos == packetCapacity)
			{
				packet->size = packetCapacity;
				packet->send();
				streamqueue.pop();
				pos = 0;
			}
		}

		/* no possible error conditions */
		return size;
	}
};

class ArtsCApi {
protected:
	static ArtsCApi *instance;
	int refcnt;

	Dispatcher dispatcher;
	SoundServer server;

	ArtsCApi() : refcnt(1), server(Reference("global:Arts_SoundServer"))
	{
		//
	}

public:
// C Api commands
	int init() {
		if(server.isNull())
			return ARTS_E_NOSERVER;

		return 0;
	}

	int suspend() {
		if(!server.isNull()) 
			return server.suspend()? 1:0;
		return ARTS_E_NOSERVER;
	}

	int suspended() {
		if(!server.isNull()) 
			return server.suspended()? 1:0;
		return ARTS_E_NOSERVER;
	}

	void free() {
		// nothing to do
	}

	arts_stream_t play_stream(int rate, int bits, int channels, const char *name)
	{
		if(server.isNull())
			return 0;

		return (arts_stream_t)static_cast<Stream *>(new Sender(server,rate,bits,channels,name));
	}

	arts_stream_t record_stream(int rate, int bits, int channels, const char *name)
	{
		if(server.isNull())
			return 0;

		return (arts_stream_t)static_cast<Stream *>(new Receiver(server,rate,bits,channels,name));
	}

	void close_stream(arts_stream_t stream)
	{
		if(server.isNull())
			return;

		if(!stream)
			return;

		static_cast<Stream *>(stream)->close();
	}

	int write(arts_stream_t stream, const void *data, int size)
	{
		if(server.isNull())
			return ARTS_E_NOSERVER;

		if(!stream)
			return ARTS_E_NOSTREAM;

		return static_cast<Stream *>(stream)->write((const mcopbyte *)data,size);
	}

	int read(arts_stream_t stream, void *data, int size)
	{
		if(server.isNull())
			return ARTS_E_NOSERVER;

		if(!stream)
			return ARTS_E_NOSTREAM;

		return static_cast<Stream *>(stream)->read((mcopbyte *)data,size);
	}

	int stream_set(arts_stream_t stream, arts_parameter_t param, int value)
	{
		if(server.isNull())
			return ARTS_E_NOSERVER;

		if(!stream)
			return ARTS_E_NOSTREAM;

		return static_cast<Stream *>(stream)->stream_set(param,value);
	}

	int stream_get(arts_stream_t stream, arts_parameter_t param)
	{
		if(server.isNull())
			return ARTS_E_NOSERVER;

		if(!stream)
			return ARTS_E_NOSTREAM;

		return static_cast<Stream *>(stream)->stream_get(param);
	}

// allocation and freeing of the class
	static ArtsCApi *the() {
		return instance;
	}
	static void ref() {
		if(!instance)
			instance = new ArtsCApi();
		else
			instance->refcnt++;
	}
	static void release() {
		assert(instance);
		assert(instance->refcnt > 0);
		instance->refcnt--;
		if(instance->refcnt == 0)
		{
			delete instance;
			instance = 0;
		}
	}
};

//----------------------------- static members -------------------------------

ArtsCApi *ArtsCApi::instance = 0;

//------------------ wrappers from C to C++ class ----------------------------

extern "C" ARTSC_EXPORT int arts_backend_init()
{
	arts_backend_debug("arts_backend_init");
	ArtsCApi::ref();

	// if init fails, don't expect free, and don't expect that the user
	// continues using other API functions
	int rc = ArtsCApi::the()->init();
	if(rc < 0) ArtsCApi::release();
	return rc;
}

extern "C" ARTSC_EXPORT int arts_backend_suspend()
{
	if(!ArtsCApi::the()) return ARTS_E_NOINIT;
	arts_backend_debug("arts_backend_suspend");
	return ArtsCApi::the()->suspend();	
}

extern "C" ARTSC_EXPORT int arts_backend_suspended()
{
	if(!ArtsCApi::the()) return ARTS_E_NOINIT;
	arts_backend_debug("arts_backend_suspended");
	return ArtsCApi::the()->suspended();	
}

extern "C" ARTSC_EXPORT void arts_backend_free()
{
	if(!ArtsCApi::the()) return;

	arts_backend_debug("arts_backend_free");
	ArtsCApi::the()->free();
	ArtsCApi::release();
}

extern "C" ARTSC_EXPORT arts_stream_t arts_backend_play_stream(int rate, int bits, int channels, const char *name)
{
	if(!ArtsCApi::the()) return 0;

	arts_backend_debug("arts_backend_play_stream");
	return ArtsCApi::the()->play_stream(rate,bits,channels,name);
}

extern "C" ARTSC_EXPORT arts_stream_t arts_backend_record_stream(int rate, int bits, int channels, const char *name)
{
	if(!ArtsCApi::the()) return 0;

	arts_backend_debug("arts_backend_record_stream");
	return ArtsCApi::the()->record_stream(rate,bits,channels,name);
}

extern "C" ARTSC_EXPORT void arts_backend_close_stream(arts_stream_t stream)
{
	if(!ArtsCApi::the()) return;

	arts_backend_debug("arts_backend_close_stream");
	ArtsCApi::the()->close_stream(stream);
}

extern "C" ARTSC_EXPORT int arts_backend_read(arts_stream_t stream, void *buffer, int count)
{
	if(!ArtsCApi::the()) return ARTS_E_NOINIT;

	arts_backend_debug("arts_backend_read");
	return ArtsCApi::the()->read(stream,buffer,count);
}

extern "C" ARTSC_EXPORT int arts_backend_write(arts_stream_t stream, const void *buffer,
						int count)
{
	if(!ArtsCApi::the()) return ARTS_E_NOINIT;

	arts_backend_debug("arts_backend_write");
	return ArtsCApi::the()->write(stream,buffer,count);
}

extern "C" ARTSC_EXPORT int arts_backend_stream_set(arts_stream_t stream,
						arts_parameter_t param, int value)
{
	if(!ArtsCApi::the()) return ARTS_E_NOINIT;

	arts_backend_debug("arts_stream_set");
	return ArtsCApi::the()->stream_set(stream,param,value);
}

extern "C" ARTSC_EXPORT int arts_backend_stream_get(arts_stream_t stream,
						arts_parameter_t param)
{
	if(!ArtsCApi::the()) return ARTS_E_NOINIT;

	arts_backend_debug("arts_stream_get");
	return ArtsCApi::the()->stream_get(stream,param);
}