aboutsummaryrefslogtreecommitdiffstats
path: root/src/modules/snd/libkvisnd.cpp
blob: ab170402ed8a4cfe3b7358ec45c0028cb90315aa (about) (plain) (blame)
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//=============================================================================
//
//   File : libkvisnd.cpp
//   Creation date : Thu Dec 27 2002 17:13:12 GMT by Juanjo Alvarez
//
//   This file is part of the KVIrc irc client distribution
//   Copyright (C) 2002 Juanjo Alvarez (juanjux at yahoo dot es)
//   Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net)
//
//   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 opinion) 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include "libkvisnd.h"

#include "KviModule.h"
#include "kvi_debug.h"
#include "KviFileUtils.h"
#include "KviMemory.h"
#include "KviWindow.h"
#include "kvi_out.h"
#include "KviLocale.h"
#include "KviQString.h"

#include <QSound>

#ifdef COMPILE_PHONON_SUPPORT
	#include <phonon/mediaobject.h>
	#include <phonon/mediasource.h>
	#include <phonon/path.h>
	#include <QUrl>
#endif //!COMPILE_PHONON_SUPPORT

#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW)
	#include <mmsystem.h>
#else //!COMPILE_ON_WINDOWS

	#include <QFile>
	#include <unistd.h>
	#include <errno.h>

	#ifdef COMPILE_ESD_SUPPORT
		#include <esd.h>
	#endif //COMPILE_ESD_SUPPORT

	#ifdef COMPILE_OSS_SUPPORT
		#include <fcntl.h>
		#include <sys/ioctl.h>
		#ifdef HAVE_LINUX_SOUNDCARD_H
			#include <linux/soundcard.h>
		#else
			// Hint by Andy Fawcett: Thnx :)
			#ifdef HAVE_SYS_SOUNDCARD_H
				#include <sys/soundcard.h>
			#else
				#ifdef HAVE_MACHINE_SOUNDCARD_H
					#include <machine/soundcard.h>
				#else
					#warning "Ops.. have no soundcard.h ? ... we're going to fail here :/"
				#endif
			#endif
		#endif
		#ifdef COMPILE_AUDIOFILE_SUPPORT
			#include <audiofile.h>
		#endif //COMPILE_AUDIOFILE_SUPPORT
	#endif //COMPILE_OSS_SUPPORT
#endif

static KviSoundPlayer * g_pSoundPlayer = 0;

KviSoundPlayer::KviSoundPlayer()
: QObject()
{
	m_pThreadList = new KviPointerList<KviSoundThread>;
	m_pThreadList->setAutoDelete(true);

#ifdef COMPILE_PHONON_SUPPORT
	m_pPhononPlayer = NULL;
#endif //!COMPILE_PHONON_SUPPORT

	m_pLastUsedSoundPlayerEntry = NULL;

	m_pSoundSystemDict = new KviPointerHashTable<QString,KviSoundPlayerEntry>(17,false);
	m_pSoundSystemDict->setAutoDelete(true);

#ifdef COMPILE_PHONON_SUPPORT
	m_pSoundSystemDict->insert("phonon",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playPhonon),KVI_PTR2MEMBER(KviSoundPlayer::cleanupPhonon)));
#endif //!COMPILE_PHONON_SUPPORT

#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW)
	m_pSoundSystemDict->insert("winmm",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playWinmm),KVI_PTR2MEMBER(KviSoundPlayer::cleanupWinmm)));
#else //!COMPILE_ON_WINDOWS

	#ifdef COMPILE_OSS_SUPPORT
		#ifdef COMPILE_AUDIOFILE_SUPPORT
			m_pSoundSystemDict->insert("oss+audiofile",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playOssAudiofile),KVI_PTR2MEMBER(KviSoundPlayer::cleanupOssAudiofile)));
		#endif //COMPILE_AUDIOFILE_SUPPORT
		m_pSoundSystemDict->insert("oss",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playOss),KVI_PTR2MEMBER(KviSoundPlayer::cleanupOss)));
	#endif //COMPILE_OSS_SUPPORT

	#ifdef COMPILE_ESD_SUPPORT
		m_pSoundSystemDict->insert("esd",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playEsd),KVI_PTR2MEMBER(KviSoundPlayer::cleanupEsd)));
	#endif //COMPILE_ESD_SUPPORT

#endif //!COMPILE_ON_WINDOWS

	m_pSoundSystemDict->insert("qt",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playQt),KVI_PTR2MEMBER(KviSoundPlayer::cleanupQt)));
	m_pSoundSystemDict->insert("null",new KviSoundPlayerEntry(KVI_PTR2MEMBER(KviSoundPlayer::playNull),KVI_PTR2MEMBER(KviSoundPlayer::cleanupNull)));
}

KviSoundPlayer::~KviSoundPlayer()
{
	if(m_pLastUsedSoundPlayerEntry)
		cleanupAfterLastPlayerEntry();

	stopAllSoundThreads();
	delete m_pThreadList;

	KviThreadManager::killPendingEvents(this);

	delete m_pSoundSystemDict;

#ifdef COMPILE_PHONON_SUPPORT
	if(m_pPhononPlayer)
		delete m_pPhononPlayer;
#endif //COMPILE_PHONON_SUPPORT

	g_pSoundPlayer = 0;
}

void KviSoundPlayer::stopAllSoundThreads()
{
	// kill any running sound thread
	m_pThreadList->setAutoDelete(false);

	while(KviSoundThread * t = m_pThreadList->first())
		delete t;

	m_pThreadList->setAutoDelete(true);
}

void KviSoundPlayer::cleanupAfterLastPlayerEntry()
{
	stopAllSoundThreads();
	if(!m_pLastUsedSoundPlayerEntry)
		return;
	SoundSystemCleanupRoutine r = m_pLastUsedSoundPlayerEntry->cleanupRoutine();
	if(r)
		(this->*r)();
	m_pLastUsedSoundPlayerEntry = NULL;
}

void KviSoundPlayer::getAvailableSoundSystems(QStringList *l)
{
	KviPointerHashTableIterator<QString,KviSoundPlayerEntry> it(*m_pSoundSystemDict);
	while(it.current())
	{
		l->append(it.currentKey());
		++it;
	}
}

bool KviSoundPlayer::havePlayingSounds()
{
	if(m_pThreadList)
		if(m_pThreadList->count() > 0)
			return true;
#ifdef COMPILE_PHONON_SUPPORT
	if(m_pPhononPlayer)
		if(m_pPhononPlayer->state() == Phonon::PlayingState)
			return true;
#endif //COMPILE_PHONON_SUPPORT
	return false;
}

void KviSoundPlayer::registerSoundThread(KviSoundThread * t)
{
	m_pThreadList->append(t);
}

void KviSoundPlayer::unregisterSoundThread(KviSoundThread * t)
{
	m_pThreadList->removeRef(t);
}

bool KviSoundPlayer::event(QEvent * e)
{
	if(e->type() == KVI_THREAD_EVENT)
	{
		KviThread * t = ((KviThreadEvent *)e)->sender();
		if(!t)return true; // huh ?
		delete (KviSoundThread *)t;
		return true;
	}
	return QObject::event(e);
}

void KviSoundPlayer::detectSoundSystem()
{
#ifdef COMPILE_PHONON_SUPPORT
	// FIXME: Phonon seems to freeze on windows sometimes.. maybe it's better to auto-detect winmm ?
	if(!m_pPhononPlayer)
		m_pPhononPlayer = Phonon::createPlayer(Phonon::MusicCategory);
	if(m_pPhononPlayer->state() != Phonon::ErrorState)
	{
		KVI_OPTION_STRING(KviOption_stringSoundSystem) = "phonon";
		return;
	}
#endif
#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW)
	KVI_OPTION_STRING(KviOption_stringSoundSystem) = "winmm";
#else
	#ifdef COMPILE_ESD_SUPPORT
		esd_format_t format = ESD_BITS16 | ESD_STREAM | ESD_PLAY | ESD_MONO;
		int esd_fd = esd_play_stream(format, 8012, NULL, "kvirc");
		if(esd_fd >= 0)
		{
			KVI_OPTION_STRING(KviOption_stringSoundSystem) = "esd";
			return;
		}
	#endif
	#ifdef COMPILE_OSS_SUPPORT
		#ifdef COMPILE_AUDIOFILE_SUPPORT
			KVI_OPTION_STRING(KviOption_stringSoundSystem) = "oss+audiofile";
			return;
		#endif
		KVI_OPTION_STRING(KviOption_stringSoundSystem) = "oss";
	#endif

#if (QT_VERSION < 0x050000)
	if(QSound::isAvailable())
#else
	// on qt5 QSound::isAvailable() is not available anymore
	// Note: consider the use of QMediaPlayer
	if(true)
#endif
	{
		KVI_OPTION_STRING(KviOption_stringSoundSystem) = "qt";
		return;
	}
	KVI_OPTION_STRING(KviOption_stringSoundSystem) = "null";
#endif
}

#ifdef COMPILE_PHONON_SUPPORT
bool KviSoundPlayer::playPhonon(const QString &szFileName)
{
	if(isMuted())
		return true;

	Phonon::MediaSource media(szFileName);

	if(!m_pPhononPlayer)
		m_pPhononPlayer = Phonon::createPlayer(Phonon::MusicCategory,media);
	else
		m_pPhononPlayer->setCurrentSource(media);

	m_pPhononPlayer->setTransitionTime(2000); // this fixes playback with the (very buggy) xine backend

	if(m_pPhononPlayer->state() == Phonon::ErrorState)
	{
		QString szError = m_pPhononPlayer->errorString();
		if(szError.isEmpty())
			qDebug("Phonon player in error state: can't play media '%s'",szFileName.isEmpty() ? "" : szFileName.toUtf8().data());
		else
			qDebug("Phonon player in error state: %s (can't play media '%s')",szError.toUtf8().data(),szFileName.isEmpty() ? "" : szFileName.toUtf8().data());

		return false;
	}

	m_pPhononPlayer->play();

	return true;
}

void KviSoundPlayer::cleanupPhonon()
{
	if(!m_pPhononPlayer)
		return;
	delete m_pPhononPlayer; // must be stopped
	m_pPhononPlayer = NULL;
}
#endif //!COMPILE_PHONON_SUPPORT

#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW)
	bool KviSoundPlayer::playWinmm(const QString &szFileName)
	{
		sndPlaySound(szFileName.toLocal8Bit().data(),SND_ASYNC | SND_NODEFAULT);
		return true;
	}

	void KviSoundPlayer::cleanupWinmm()
	{
		// FIXME: how to stop playing on windows ?
	}
#else //!COMPILE_ON_WINDOWS
	#ifdef COMPILE_OSS_SUPPORT
		#ifdef COMPILE_AUDIOFILE_SUPPORT
			bool KviSoundPlayer::playOssAudiofile(const QString &szFileName)
			{
				if(isMuted()) return true;
				KviOssAudiofileSoundThread * t = new KviOssAudiofileSoundThread(szFileName);
				if(!t->start())
				{
					delete t;
					return false;
				}
				return true;
			}

			void KviSoundPlayer::cleanupOssAudiofile()
			{
			}
		#endif //COMPILE_AUDIOFILE_SUPPORT
		bool KviSoundPlayer::playOss(const QString &szFileName)
		{
			if(isMuted()) return true;
			KviOssSoundThread * t = new KviOssSoundThread(szFileName);
			if(!t->start())
			{
				delete t;
				return false;
			}
			return true;
		}

		void KviSoundPlayer::cleanupOss()
		{
		}
	#endif //COMPILE_OSS_SUPPORT
	#ifdef COMPILE_ESD_SUPPORT
		bool KviSoundPlayer::playEsd(const QString &szFileName)
		{
			if(isMuted())
				return true;
			KviEsdSoundThread * t = new KviEsdSoundThread(szFileName);
			if(!t->start())
			{
				delete t;
				return false;
			}
			return true;
		}

		void KviSoundPlayer::cleanupEsd()
		{
		}
	#endif //COMPILE_ESD_SUPPORT
#endif //!COMPILE_ON_WINDOWS

bool KviSoundPlayer::playQt(const QString &szFileName)
{
	if(isMuted())
		return true;
	QSound::play(szFileName);
	return true;
}

void KviSoundPlayer::cleanupQt()
{
	// how to stop Qt sounds ?
	// using the play/stop slots instead of the static ::play (TODO)
}

bool KviSoundPlayer::playNull(const QString &)
{
	// null sound system
	return true;
}

void KviSoundPlayer::cleanupNull()
{
}

bool KviSoundPlayer::play(const QString &szFileName)
{
	if(isMuted())
		return true;

	KviSoundPlayerEntry * e = m_pSoundSystemDict->find(KVI_OPTION_STRING(KviOption_stringSoundSystem));

	if(!e)
	{
		if(
				(!KVI_OPTION_STRING(KviOption_stringSoundSystem).isEmpty()) &&
				(!KviQString::equalCI(KVI_OPTION_STRING(KviOption_stringSoundSystem),"unknown"))
			)
		{
			qDebug(
					"Sound system '%s' is not valid, you may want to re-configure it in the options dialog...",
					KVI_OPTION_STRING(KviOption_stringSoundSystem).toUtf8().data()
				);
			return false; // detection already attempted (and failed?)
		}

		detectSoundSystem();
		e = m_pSoundSystemDict->find(KVI_OPTION_STRING(KviOption_stringSoundSystem));
		if(!e)
			return false;
	}

	if(e != m_pLastUsedSoundPlayerEntry)
	{
		// if the sound player changed, cleanup after the previous one
		if(m_pLastUsedSoundPlayerEntry)
			cleanupAfterLastPlayerEntry();
		m_pLastUsedSoundPlayerEntry = e;
	}

	SoundSystemPlayRoutine r = e->playRoutine();
	Q_ASSERT(r); // MUST BE THERE

	return (this->*r)(szFileName);
}


KviSoundThread::KviSoundThread(const QString &szFileName)
: KviThread()
{
	g_pSoundPlayer->registerSoundThread(this);
	m_szFileName = szFileName;
	m_bTerminate = false;
}

KviSoundThread::~KviSoundThread()
{
	m_bTerminate = true; // force a termination request (since the base class will wait())
	g_pSoundPlayer->unregisterSoundThread(this);
}

void KviSoundThread::terminate()
{
	m_bTerminate = true;
}

void KviSoundThread::play()
{
}

void KviSoundThread::run()
{
	play();
#if !defined(COMPILE_ON_WINDOWS) && !defined(COMPILE_ON_MINGW)
	postEvent(g_pSoundPlayer,new KviThreadEvent(KVI_THREAD_EVENT_SUCCESS));
#endif
}


#if !defined(COMPILE_ON_WINDOWS) && !defined(COMPILE_ON_MINGW)
	#ifdef COMPILE_OSS_SUPPORT
		#ifdef COMPILE_AUDIOFILE_SUPPORT
			KviOssAudiofileSoundThread::KviOssAudiofileSoundThread(const QString &szFileName)
			: KviSoundThread(szFileName)
			{
			}

			KviOssAudiofileSoundThread::~KviOssAudiofileSoundThread()
			{
			}

			void KviOssAudiofileSoundThread::play()
			{
				#define BUFFER_FRAMES 4096

				AFfilehandle file;
				AFframecount framesRead;
				int sampleFormat, sampleWidth, channelCount, format, freq;
				float frameSize;
				void * buffer;

				file = afOpenFile(m_szFileName.toUtf8().data(),"r",NULL);
				if(!file)
				{
					qDebug("libaudiofile could not open the file %s",m_szFileName.toUtf8().data());
					qDebug("giving up playing sound...");
					return; // screwed up
				}

				sampleFormat = -1;

				afGetVirtualSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth);

				if(sampleFormat == -1)
				{
					qDebug("libaudiofile couldn't find the sample format for file %s",m_szFileName.toUtf8().data());
					qDebug("giving up playing sound...");
					afCloseFile(file);
					return; // screwed up
				}

				frameSize = afGetVirtualFrameSize(file, AF_DEFAULT_TRACK, 1);
				channelCount = afGetVirtualChannels(file, AF_DEFAULT_TRACK);
				buffer = KviMemory::allocate(int(BUFFER_FRAMES * frameSize));

				int audiofd_c = open("/dev/dsp", O_WRONLY /*| O_EXCL | O_NDELAY*/);

				QFile audiofd;

				if(audiofd_c < 0)
				{
					qDebug("Could not open audio device /dev/dsp! [OSS+AUDIOFILE]");
					qDebug("(the device is probably busy, errno = %d)",errno);
					goto exit_thread;
				}

				audiofd.open(audiofd_c,QIODevice::WriteOnly); // ???? what the heck is this for ?

				if (sampleWidth == 8)
					format = AFMT_U8;
				else if(sampleWidth == 16)
					format = AFMT_S16_NE;

				if(ioctl(audiofd.handle(),SNDCTL_DSP_SETFMT, &format) == -1)
				{
					qDebug("Could not set format width to DSP! [OSS]");
					goto exit_thread;
				}

				if (ioctl(audiofd.handle(),SNDCTL_DSP_CHANNELS, &channelCount) == -1)
				{
					qDebug("Could not set DSP channels! [OSS]");
					goto exit_thread;
				}

				freq = (int) afGetRate(file, AF_DEFAULT_TRACK);
				if (ioctl(audiofd.handle(), SNDCTL_DSP_SPEED, &freq) == -1)
				{
					qDebug("Could not set DSP speed %d! [OSS]",freq);
					goto exit_thread;
				}

				framesRead = afReadFrames(file, AF_DEFAULT_TRACK, buffer, BUFFER_FRAMES);

				while(!m_bTerminate && (framesRead > 0))
				{
					audiofd.write((char *)buffer,(int)(framesRead * frameSize));
					framesRead = afReadFrames(file, AF_DEFAULT_TRACK, buffer,BUFFER_FRAMES);
				}

			exit_thread:
				audiofd.close();
				if(audiofd_c >= 0)close(audiofd_c);
				afCloseFile(file);
				KviMemory::free(buffer);
			}
		#endif //COMPILE_AUDIOFILE_SUPPORT


		KviOssSoundThread::KviOssSoundThread(const QString &szFileName)
		: KviSoundThread(szFileName)
		{
		}

		KviOssSoundThread::~KviOssSoundThread()
		{
		}

		void KviOssSoundThread::play()
		{
			#define OSS_BUFFER_SIZE 16384

			if(!m_szFileName.endsWith(QString(".au")))
			{
				qDebug("Oss only player supports only *.au files");
				return;
			}

			QFile f(m_szFileName);
			int fd = -1;
			char buf[OSS_BUFFER_SIZE];
			int iDataLen = 0;
			int iSize = 0;

			if(!f.open(QIODevice::ReadOnly))
			{
				qDebug("Could not open sound file %s! [OSS]",m_szFileName.toUtf8().data());
				return;
			}

			iSize = f.size();

			if(iSize < 24)
			{
				qDebug("Could not play sound, file %s too small! [OSS]",m_szFileName.toUtf8().data());
				goto exit_thread;
			}

			if(f.read(buf,24) < 24)
			{
				qDebug("Error while reading the sound file header (%s)! [OSS]",m_szFileName.toUtf8().data());
				goto exit_thread;
			}

			iSize -= 24;

			fd = open("/dev/audio",  O_WRONLY /* | O_EXCL | O_NDELAY*/);
			if(fd < 0)
			{
				qDebug("Could not open device file /dev/audio!");
				qDebug("Maybe other program is using the device? Hint: fuser -uv /dev/audio");
				goto exit_thread;
			}


			while(!m_bTerminate && (iSize > 0))
			{
				int iCanRead = OSS_BUFFER_SIZE - iDataLen;
				if(iCanRead > 0)
				{
					int iToRead = iSize > iCanRead ? iCanRead : iSize;
					int iReaded = f.read(buf + iDataLen,iToRead);
					if(iReaded < 1)
					{
						qDebug("Error while reading the file data (%s)! [OSS]",m_szFileName.toUtf8().data());
						goto exit_thread;
					}
					iSize -= iReaded;
					iDataLen += iReaded;
				}
				if(iDataLen > 0)
				{
					int iWritten = write(fd,buf,iDataLen);
					if(iWritten < 0)
					{
						if((errno != EINTR) && (errno != EAGAIN))
						{
							qDebug("Error while writing the audio data (%s)! [OSS]",m_szFileName.toUtf8().data());
							goto exit_thread;
						}
					}
					iDataLen -= iWritten;
				} else {
					// nothing to write ????
					goto exit_thread;
				}
			}

		exit_thread:
			f.close();
			if(fd > 0)close(fd);
		}


	#endif //COMPILE_OSS_SUPPORT

	#ifdef COMPILE_ESD_SUPPORT

		KviEsdSoundThread::KviEsdSoundThread(const QString &szFileName)
		: KviSoundThread(szFileName)
		{
		}

		KviEsdSoundThread::~KviEsdSoundThread()
		{
		}

		void KviEsdSoundThread::play()
		{
			// ESD has a really nice API
			if(!esd_play_file(NULL,m_szFileName.toUtf8().data(),1)) // this is sync.. FIXME: it can't be stopped!
				qDebug("Could not play sound %s! [ESD]",m_szFileName.toUtf8().data());
		}

	#endif //COMPILE_ESD_SUPPORT
#endif //!COMPILE_ON_WINDOWS


/*
	@doc: snd.play
	@type:
		command
	@title:
		snd.play
	@short:
		Play a sound file from the disk
	@syntax:
		snd.play [-q|quiet] <filename:string>
	@description:
		Play a file, using the sound system specified by the user in the options.[br]
		The supported file formats vary from one sound system to another, but the best
		bet could be Au Law (.au) files. Phonon, EsounD and Linux/OSS with audiofile support also
		support other formats like .wav files but in OSS without audiofile only .au files are
		supported.
		On windows the supported file formats are determined by the drivers installed.
		You should be able to play at least *.wav files.[br]
		(This is a task where the Windows interface is really well done, I must say that :)
	@switches:
		!sw: -q | --quiet
		Causes the command to run quietly (no complains about missing files, invalid formats...
*/

static bool snd_kvs_cmd_play(KviKvsModuleCommandCall * c)
{
	QString szFile;
	KVSM_PARAMETERS_BEGIN(c)
		KVSM_PARAMETER("file name",KVS_PT_STRING,0,szFile)
	KVSM_PARAMETERS_END(c)
	if(szFile.isEmpty() || (!KviFileUtils::fileExists(szFile)))
	{
		if(!c->hasSwitch('q',"quiet"))
			c->warning(__tr2qs("Sound file '%Q' not found"),&szFile);
		return true;
	}

	if(!g_pSoundPlayer->play(szFile))
	{
		if(!c->hasSwitch('q',"quiet"))
			c->warning(__tr2qs("Unable to play sound '%Q'"),&szFile);
	}

	return true;
}

static bool snd_kvs_cmd_autodetect(KviKvsModuleCommandCall * c)
{
	g_pSoundPlayer->detectSoundSystem();
	if(KviQString::equalCI(KVI_OPTION_STRING(KviOption_stringSoundSystem),"null"))
	{
		c->window()->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("Sorry, I can't find a sound system to use on this machine"));
	} else {
		c->window()->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Sound system detected to: %s"),KVI_OPTION_STRING(KviOption_stringSoundSystem).toUtf8().data());
	}
	return true;
}


/*
	@doc: snd.mute
	@type:
		command
	@title:
		snd.mute
	@short:
		Mute all sounds
	@syntax:
		snd.mute
	@description:
		Mute all sounds
*/

static bool snd_kvs_cmd_mute(KviKvsModuleCommandCall * c)
{
	KVSM_PARAMETERS_BEGIN(c)
	KVSM_PARAMETERS_END(c)
	g_pSoundPlayer->setMuted(true);
	return true;
}

/*
	@doc: snd.unmute
	@type:
		command
	@title:
		snd.unmute
	@short:
		UnMute all sounds
	@syntax:
		snd.mute
	@description:
		UnMute all sounds
*/

static bool snd_kvs_cmd_unmute(KviKvsModuleCommandCall * c)
{
	KVSM_PARAMETERS_BEGIN(c)
	KVSM_PARAMETERS_END(c)
	g_pSoundPlayer->setMuted(false);
	return true;
}

/*
	@doc: snd.isMuted
	@type:
		function
	@title:
		$snd.isMuted
	@short:
		Returns if the sounds muted
	@syntax:
		<bool> $snd.isMuted()
	@description:
		Returns if the sounds muted
*/


static bool snd_kvs_fnc_ismuted(KviKvsModuleFunctionCall * c)
{
	c->returnValue()->setBoolean(g_pSoundPlayer->isMuted());
	return true;
}

static bool snd_module_init(KviModule * m)
{
	g_pSoundPlayer = new KviSoundPlayer();

	KVSM_REGISTER_SIMPLE_COMMAND(m,"autodetect",snd_kvs_cmd_autodetect);
	KVSM_REGISTER_SIMPLE_COMMAND(m,"play",snd_kvs_cmd_play);
	KVSM_REGISTER_SIMPLE_COMMAND(m,"mute",snd_kvs_cmd_mute);
	KVSM_REGISTER_SIMPLE_COMMAND(m,"unmute",snd_kvs_cmd_unmute);

	KVSM_REGISTER_FUNCTION(m,"isMuted",snd_kvs_fnc_ismuted);

	return true;
}

static bool snd_module_cleanup(KviModule *)
{
	delete g_pSoundPlayer;
	g_pSoundPlayer = 0;
	return true;
}

static bool snd_module_can_unload(KviModule *)
{
	return !(g_pSoundPlayer->havePlayingSounds());
}

static bool snd_module_ctrl(KviModule *,const char * operation,void * param)
{
	if(kvi_strEqualCI(operation,"getAvailableSoundSystems"))
	{
		// we expect param to be a pointer to QStringList
		QStringList *l=(QStringList *)param;
		g_pSoundPlayer->getAvailableSoundSystems(l);
		return true;
	}
	if(kvi_strEqualCI(operation,"detectSoundSystem"))
	{
		g_pSoundPlayer->detectSoundSystem();
		return true;
	}
	if(kvi_strEqualCI(operation,"play"))
	{
		QString * pszFileName = (QString *)param;
		if(pszFileName)
			return g_pSoundPlayer->play(*pszFileName);
		return false;
	}
	return false;
}


KVIRC_MODULE(
	"Sound",                                                 // module name
	"4.0.0",                                                // module version
	"(C) 2002 Szymon Stefanek (pragma at kvirc dot net)," \
	"Juanjo Alvarez (juanjux at yahoo dot es)", // author & (C)
	"Sound playing commands",
	snd_module_init,
	snd_module_can_unload,
	snd_module_ctrl,
	snd_module_cleanup,
	0
)