aboutsummaryrefslogtreecommitdiff
path: root/engines/sci/sfx/core.cpp
blob: e37007bf8ed059d58feb74ac52c3c8c2c9170ba7 (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
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * $URL$
 * $Id$
 *
 */

/* Sound subsystem core: Event handler, sound player dispatching */

#include "sci/tools.h"
#include "sci/sci.h"
#include "sci/sfx/core.h"
#include "sci/sfx/iterator.h"
#include "sci/sfx/misc.h"
#include "sci/sfx/sci_midi.h"

#include "sci/sfx/softseq/pcjr.h"
#include "sci/sfx/softseq/adlib.h"

#include "common/system.h"
#include "common/timer.h"

#include "sound/audiostream.h"
#include "sound/mixer.h"

namespace Sci {

class SfxPlayer;
SfxPlayer *player = NULL;	// FIXME: Avoid non-const global vars


/* Plays a song iterator that found a PCM through a PCM device, if possible
** Parameters: (SongIterator *) it: The iterator to play
**             (SongHandle) handle: Debug handle
** Returns   : (int) 0 if the effect will not be played, nonzero if it will
** This assumes that the last call to 'it->next()' returned SI_PCM.
*/
static int sfx_play_iterator_pcm(SongIterator *it, SongHandle handle);


#pragma mark -


class SfxPlayer {
public:
	/** Number of voices that can play simultaneously */
	int _polyphony;

protected:
	MidiPlayer *_mididrv;

	SongIterator *_iterator;
	Audio::Timestamp _wakeupTime;
	Audio::Timestamp _currentTime;
	uint32 _pauseTimeDiff;

	bool _paused;
	bool _iteratorIsDone;
	uint32 _tempo;

	Common::Mutex *_mutex;
	int _volume;

	void play_song(SongIterator *it);
	static void player_timer_callback(void *refCon);

public:
	SfxPlayer();
	~SfxPlayer();

	/* Initializes the player
	** Parameters: (ResourceManager *) resmgr: A resource manager for driver initialization
	**             (int) expected_latency: Expected delay in between calls to 'maintenance'
	**                   (in microseconds)
	** Returns   : (int) Common::kNoError on success, Common::kUnknownError on failure
	*/
	Common::Error init(ResourceManager *resmgr, int expected_latency);

	/* Adds an iterator to the song player
	** Parameters: (songx_iterator_t *) it: The iterator to play
	**             (uint32) start_time: The time to assume as the
	**                        time the first MIDI command executes at
	** Returns   : (int) Common::kNoError on success, Common::kUnknownError on failure
	** The iterator should not be cloned (to avoid memory leaks) and
	** may be modified according to the needs of the player.
	** Implementors may use the 'sfx_iterator_combine()' function
	** to add iterators onto their already existing iterators
	*/
	Common::Error add_iterator(SongIterator *it, uint32 start_time);

	/* Stops the currently playing song and deletes the associated iterator
	** Returns   : (int) Common::kNoError on success, Common::kUnknownError on failure
	*/
	Common::Error stop();

	/* Transmits a song iterator message to the active song
	** Parameters: (SongIterator::Message) msg: The message to transmit
	** Returns   : (int) Common::kNoError on success, Common::kUnknownError on failure
	** OPTIONAL -- may be NULL
	** If this method is not present, sending messages will stop
	** and re-start playing, so it is preferred that it is present
	*/
	Common::Error iterator_message(const SongIterator::Message &msg);

	/* Pauses song playing
	** Returns   : (int) Common::kNoError on success, Common::kUnknownError on failure
	*/
	Common::Error pause();

	/* Resumes song playing after a pause
	** Returns   : (int) Common::kNoError on success, Common::kUnknownError on failure
	*/
	Common::Error resume();

	/* Pass a raw MIDI event to the synth
	Parameters: (int) argc: Length of buffer holding the midi event
	           (byte *) argv: The buffer itself
	*/
	void tell_synth(int buf_nr, byte *buf);
};

SfxPlayer::SfxPlayer() {
	_polyphony = 0;

	_mididrv = 0;

	_iterator = NULL;
	_pauseTimeDiff = 0;

	_paused = false;
	_iteratorIsDone = false;
	_tempo = 0;

	_mutex = 0;
	_volume = 15;
}

SfxPlayer::~SfxPlayer() {
	if (_mididrv) {
		_mididrv->close();
		delete _mididrv;
	}
	delete _mutex;
	delete _iterator;
	_iterator = NULL;
}

void SfxPlayer::play_song(SongIterator *it) {
	while (_iterator && _wakeupTime.msecsDiff(_currentTime) <= 0) {
		int delay;
		byte buf[8];
		int result;

		switch ((delay = songit_next(&(_iterator),
		                             buf, &result,
		                             IT_READER_MASK_ALL
		                             | IT_READER_MAY_FREE
		                             | IT_READER_MAY_CLEAN))) {

		case SI_FINISHED:
			delete _iterator;
			_iterator = NULL;
			_iteratorIsDone = true;
			return;

		case SI_IGNORE:
		case SI_LOOP:
		case SI_RELATIVE_CUE:
		case SI_ABSOLUTE_CUE:
			break;

		case SI_PCM:
			sfx_play_iterator_pcm(_iterator, 0);
			break;

		case 0:
			static_cast<MidiDriver *>(_mididrv)->send(buf[0], buf[1], buf[2]);

			break;

		default:
			_wakeupTime = _wakeupTime.addFrames(delay);
		}
	}
}

void SfxPlayer::tell_synth(int buf_nr, byte *buf) {
	byte op1 = (buf_nr < 2 ? 0 : buf[1]);
	byte op2 = (buf_nr < 3 ? 0 : buf[2]);

	static_cast<MidiDriver *>(_mididrv)->send(buf[0], op1, op2);
}

void SfxPlayer::player_timer_callback(void *refCon) {
	SfxPlayer *thePlayer = (SfxPlayer *)refCon;
	assert(refCon);
	Common::StackLock lock(*thePlayer->_mutex);

	if (thePlayer->_iterator && !thePlayer->_iteratorIsDone && !thePlayer->_paused) {
		thePlayer->play_song(thePlayer->_iterator);
	}

	thePlayer->_currentTime = thePlayer->_currentTime.addFrames(1);
}

/* API implementation */

Common::Error SfxPlayer::init(ResourceManager *resmgr, int expected_latency) {
	MidiDriverType musicDriver = MidiDriver::detectMusicDriver(MDT_PCSPK | MDT_ADLIB);

	switch(musicDriver) {
	case MD_ADLIB:
		_mididrv = new MidiPlayer_Adlib();
		break;
	case MD_PCJR:
		_mididrv = new MidiPlayer_PCJr();
		break;
	case MD_PCSPK:
		_mididrv = new MidiPlayer_PCSpeaker();
		break;
	default:
		break;
	}

	assert(_mididrv);

	_polyphony = _mididrv->getPolyphony();

	_tempo = _mididrv->getBaseTempo();
    uint32 time = g_system->getMillis();
	_currentTime = Audio::Timestamp(time, 1000000 / _tempo);
	_wakeupTime = Audio::Timestamp(time, SFX_TICKS_PER_SEC);

	_mutex = new Common::Mutex();

	_mididrv->setTimerCallback(this, player_timer_callback);
	_mididrv->open(resmgr);
	_mididrv->setVolume(_volume);

	return Common::kNoError;
}

Common::Error SfxPlayer::add_iterator(SongIterator *it, uint32 start_time) {
	Common::StackLock lock(*_mutex);
	SIMSG_SEND(it, SIMSG_SET_PLAYMASK(_mididrv->getPlayMask()));
	SIMSG_SEND(it, SIMSG_SET_RHYTHM(_mididrv->hasRhythmChannel()));

	if (_iterator == NULL) {
		// Resync with clock
		_currentTime = Audio::Timestamp(g_system->getMillis(), 1000000 / _tempo);
		_wakeupTime = Audio::Timestamp(start_time, SFX_TICKS_PER_SEC);
	}

	_iterator = sfx_iterator_combine(_iterator, it);
	_iteratorIsDone = false;

	return Common::kNoError;
}

Common::Error SfxPlayer::stop() {
	debug(3, "Player: Stopping song iterator %p", (void *)_iterator);
	Common::StackLock lock(*_mutex);
	delete _iterator;
	_iterator = NULL;
	for (int i = 0; i < MIDI_CHANNELS; i++)
		static_cast<MidiDriver *>(_mididrv)->send(0xb0 + i, SCI_MIDI_CHANNEL_NOTES_OFF, 0);

	return Common::kNoError;
}

Common::Error SfxPlayer::iterator_message(const SongIterator::Message &msg) {
	Common::StackLock lock(*_mutex);
	if (!_iterator) {
		return Common::kUnknownError;
	}

	songit_handle_message(&_iterator, msg);

	return Common::kNoError;
}

Common::Error SfxPlayer::pause() {
	Common::StackLock lock(*_mutex);

	_paused = true;
	_pauseTimeDiff = _wakeupTime.msecsDiff(_currentTime);

	_mididrv->playSwitch(false);

	return Common::kNoError;
}

Common::Error SfxPlayer::resume() {
	Common::StackLock lock(*_mutex);

	_wakeupTime = Audio::Timestamp(_currentTime.msecs() + _pauseTimeDiff, SFX_TICKS_PER_SEC);
	_mididrv->playSwitch(true);
	_paused = false;

	return Common::kNoError;
}


#pragma mark -


int sfx_pcm_available() {
	return g_system->getMixer()->isReady();
}

void sfx_reset_player() {
	if (player)
		player->stop();
}

void sfx_player_tell_synth(int buf_nr, byte *buf) {
	if (player)
		player->tell_synth(buf_nr, buf);
}

int sfx_get_player_polyphony() {
	if (player)
		return player->_polyphony;
	else
		return 0;
}

SfxState::SfxState() {
	_it = NULL;
	_flags = 0;
	_song = NULL;
	_suspended = 0;
	_soundSync = 0;
	_audioResource = 0;
}

SfxState::~SfxState() {
}


void SfxState::freezeTime() {
	/* Freezes the top song delay time */
	const Audio::Timestamp ctime = Audio::Timestamp(g_system->getMillis(), SFX_TICKS_PER_SEC);
	Song *song = _song;

	while (song) {
		song->_delay = song->_wakeupTime.frameDiff(ctime);
		if (song->_delay < 0)
			song->_delay = 0;

		song = song->_nextPlaying;
	}
}

void SfxState::thawTime() {
	/* inverse of freezeTime() */
	const Audio::Timestamp ctime = Audio::Timestamp(g_system->getMillis(), SFX_TICKS_PER_SEC);
	Song *song = _song;

	while (song) {
		song->_wakeupTime = ctime.addFrames(song->_delay);

		song = song->_nextPlaying;
	}
}

#if 0
// Unreferenced - removed
static void _dump_playing_list(SfxState *self, char *msg) {
	Song *song = self->_song;

	fprintf(stderr, "[] Song list : [ ");
	song = *(self->_songlib.lib);
	while (song) {
		fprintf(stderr, "%08lx:%d ", song->handle, song->_status);
		song = song->_nextPlaying;
	}
	fprintf(stderr, "]\n");

	fprintf(stderr, "[] Play list (%s) : [ " , msg);

	while (song) {
		fprintf(stderr, "%08lx ", song->handle);
		song = song->_nextPlaying;
	}

	fprintf(stderr, "]\n");
}
#endif

#if 0
static void _dump_songs(SfxState *self) {
	Song *song = self->_song;

	fprintf(stderr, "Cue iterators:\n");
	song = *(self->_songlib.lib);
	while (song) {
		fprintf(stderr, "  **\tHandle %08x (p%d): status %d\n",
		        song->handle, song->_priority, song->_status);
		SIMSG_SEND(song->_it, SIMSG_PRINT(1));
		song = song->_next;
	}

	if (player) {
		fprintf(stderr, "Audio iterator:\n");
		player->iterator_message(SongIterator::Message(0, SIMSG_PRINT(1)));
	}
}
#endif

bool SfxState::isPlaying(Song *song) {
	Song *playing_song = _song;

	/*	_dump_playing_list(this, "is-playing");*/

	while (playing_song) {
		if (playing_song == song)
			return true;
		playing_song = playing_song->_nextPlaying;
	}
	return false;
}

void SfxState::setSongStatus(Song *song, int status) {
	const Audio::Timestamp ctime = Audio::Timestamp(g_system->getMillis(), SFX_TICKS_PER_SEC);

	switch (status) {

	case SOUND_STATUS_STOPPED:
		// Reset
		song->_it->init();
		break;

	case SOUND_STATUS_SUSPENDED:
	case SOUND_STATUS_WAITING:
		if (song->_status == SOUND_STATUS_PLAYING) {
			// Update delay, set wakeup_time
			song->_delay += song->_wakeupTime.frameDiff(ctime);
			song->_wakeupTime = ctime;
		}
		if (status == SOUND_STATUS_SUSPENDED)
			break;

		/* otherwise... */

	case SOUND_STATUS_PLAYING:
		if (song->_status == SOUND_STATUS_STOPPED) {
			// Starting anew
			song->_wakeupTime = ctime;
		}

		if (isPlaying(song))
			status = SOUND_STATUS_PLAYING;
		else
			status = SOUND_STATUS_WAITING;
		break;

	default:
		fprintf(stderr, "%s L%d: Attempt to set invalid song"
		        " state %d!\n", __FILE__, __LINE__, status);
		return;

	}
	song->_status = status;
}

/* Update internal state iff only one song may be played */
void SfxState::updateSingleSong() {
	Song *newsong = _songlib.findFirstActive();

	if (newsong != _song) {
		freezeTime(); /* Store song delay time */

		if (player)
			player->stop();

		if (newsong) {
			if (!newsong->_it)
				return; /* Restore in progress and not ready for this yet */

			/* Change song */
			if (newsong->_status == SOUND_STATUS_WAITING)
				setSongStatus(newsong, SOUND_STATUS_PLAYING);

			/* Change instrument mappings */
		} else {
			/* Turn off sound */
		}
		if (_song) {
			if (_song->_status == SOUND_STATUS_PLAYING)
				setSongStatus(newsong, SOUND_STATUS_WAITING);
		}

		Common::String debugMessage = "[SFX] Changing active song:";
		if (!_song) {
			debugMessage += " New song:";
		} else {
			char tmp[50];
			sprintf(tmp, " pausing %08lx, now playing ", _song->_handle);
			debugMessage += tmp;
		}

		if (newsong) {
			char tmp[20];
			sprintf(tmp, "%08lx\n", newsong->_handle);
			debugMessage += tmp;
		} else {
			debugMessage += " none\n";
		}

		debugC(2, kDebugLevelSound, debugMessage.c_str());
				
		_song = newsong;
		thawTime(); /* Recover song delay time */

		if (newsong && player) {
			SongIterator *clonesong = newsong->_it->clone(newsong->_delay);

			player->add_iterator(clonesong, newsong->_wakeupTime.msecs());
		}
	}
}


void SfxState::updateMultiSong() {
	Song *oldfirst = _song;
	Song *oldseeker;
	Song *newsong = _songlib.findFirstActive();
	Song *newseeker;
	Song not_playing_anymore; /* Dummy object, referenced by
				    ** songs which are no longer
				    ** active.  */

	/*	_dump_playing_list(this, "before");*/
	freezeTime(); /* Store song delay time */

	if (!newsong)
		return;

	for (newseeker = newsong; newseeker;
	        newseeker = newseeker->_nextPlaying) {
		if (!newseeker || !newseeker->_it)
			return; /* Restore in progress and not ready for this yet */
	}

	/* First, put all old songs into the 'stopping' list and
	** mark their 'next-playing' as not_playing_anymore.  */
	for (oldseeker = oldfirst; oldseeker;
	        oldseeker = oldseeker->_nextStopping) {
		oldseeker->_nextStopping = oldseeker->_nextPlaying;
		oldseeker->_nextPlaying = &not_playing_anymore;

		if (oldseeker == oldseeker->_nextPlaying) { 
			error("updateMultiSong() failed. Breakpoint in %s, line %d", __FILE__, __LINE__);
		}
	}

	/* Second, re-generate the new song queue. */
	for (newseeker = newsong; newseeker; newseeker = newseeker->_nextPlaying) {
		newseeker->_nextPlaying = _songlib.findNextActive(newseeker);

		if (newseeker == newseeker->_nextPlaying) { 
			error("updateMultiSong() failed. Breakpoint in %s, line %d", __FILE__, __LINE__);
		}
	}
	/* We now need to update the currently playing song list, because we're
	** going to use some functions that require this list to be in a sane
	** state (particularly isPlaying(), indirectly */
	_song = newsong;

	/* Third, stop all old songs */
	for (oldseeker = oldfirst; oldseeker;
	        oldseeker = oldseeker->_nextStopping)
		if (oldseeker->_nextPlaying == &not_playing_anymore) {
			setSongStatus(oldseeker, SOUND_STATUS_SUSPENDED);
			debugC(2, kDebugLevelSound, "[SFX] Stopping song %lx\n", oldseeker->_handle);

			if (player && oldseeker->_it)
				player->iterator_message(SongIterator::Message(oldseeker->_it->ID, SIMSG_STOP));
			oldseeker->_nextPlaying = NULL; /* Clear this pointer; we don't need the tag anymore */
		}

	for (newseeker = newsong; newseeker; newseeker = newseeker->_nextPlaying) {
		if (newseeker->_status != SOUND_STATUS_PLAYING && player) {
			debugC(2, kDebugLevelSound, "[SFX] Adding song %lx\n", newseeker->_it->ID);

			SongIterator *clonesong = newseeker->_it->clone(newseeker->_delay);
			player->add_iterator(clonesong, g_system->getMillis());
		}
		setSongStatus(newseeker, SOUND_STATUS_PLAYING);
	}

	_song = newsong;
	thawTime();
	/*	_dump_playing_list(this, "after");*/
}

/* Update internal state */
void SfxState::update() {
	if (_flags & SFX_STATE_FLAG_MULTIPLAY)
		updateMultiSong();
	else
		updateSingleSong();
}

static int sfx_play_iterator_pcm(SongIterator *it, SongHandle handle) {
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Playing PCM: %08lx\n", handle);
#endif
	if (g_system->getMixer()->isReady()) {
		Audio::AudioStream *newfeed = it->getAudioStream();
		if (newfeed) {
			g_system->getMixer()->playInputStream(Audio::Mixer::kSFXSoundType, 0, newfeed);
			return 1;
		}
	}
	return 0;
}

#define DELAY (1000000 / SFX_TICKS_PER_SEC)

void SfxState::sfx_init(ResourceManager *resmgr, int flags) {
	_songlib._lib = 0;
	_song = NULL;
	_flags = flags;
	_soundSync = NULL;
	_audioResource = NULL;

	player = NULL;

	if (flags & SFX_STATE_FLAG_NOSOUND) {
		warning("[SFX] Sound disabled");
		return;
	}

#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Initialising: flags=%x\n", flags);
#endif

	/*-------------------*/
	/* Initialise player */
	/*-------------------*/

	if (!resmgr) {
		warning("[SFX] Warning: No resource manager present, cannot initialise player");
		return;
	}

	player = new SfxPlayer();

	if (!player) {
		warning("[SFX] No song player found");
		return;
	}

	if (player->init(resmgr, DELAY / 1000)) {
		warning("[SFX] Song player reported error, disabled");
		delete player;
		player = NULL;
	}
}

void SfxState::sfx_exit() {
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Uninitialising\n");
#endif

	delete player;
	player = 0;

	g_system->getMixer()->stopAll();

	_songlib.freeSounds();

	// Delete audio resources for CD talkie games
	if (_audioResource) {
		delete _audioResource;
		_audioResource = 0;
	}
}

void SfxState::sfx_suspend(bool suspend) {
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Suspending? = %d\n", suspend);
#endif
	if (suspend && (!_suspended)) {
		/* suspend */

		freezeTime();
		if (player)
			player->pause();
		/* Suspend song player */

	} else if (!suspend && (_suspended)) {
		/* unsuspend */

		thawTime();
		if (player)
			player->resume();

		/* Unsuspend song player */
	}

	_suspended = suspend;
}

int SfxState::sfx_poll(SongHandle *handle, int *cue) {
	if (!_song)
		return 0; /* No milk today */

	*handle = _song->_handle;

#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Polling any (%08lx)\n", *handle);
#endif
	return sfx_poll_specific(*handle, cue);
}

int SfxState::sfx_poll_specific(SongHandle handle, int *cue) {
	const Audio::Timestamp ctime = Audio::Timestamp(g_system->getMillis(), SFX_TICKS_PER_SEC);
	Song *song = _song;

	while (song && song->_handle != handle)
		song = song->_nextPlaying;

	if (!song)
		return 0; /* Song not playing */

	debugC(2, kDebugLevelSound, "[SFX:CUE] Polled song %08lx ", handle);

	while (1) {
		if (song->_wakeupTime.frameDiff(ctime) > 0)
			return 0; /* Patience, young hacker! */

		byte buf[8];
		int result = songit_next(&(song->_it), buf, cue, IT_READER_MASK_ALL);

		switch (result) {

		case SI_FINISHED:
			setSongStatus(song, SOUND_STATUS_STOPPED);
			update();
			/* ...fall through... */
		case SI_LOOP:
		case SI_RELATIVE_CUE:
		case SI_ABSOLUTE_CUE:
			if (result == SI_FINISHED)
				debugC(2, kDebugLevelSound, " => finished");
			else {
				if (result == SI_LOOP)
					debugC(2, kDebugLevelSound, " => Loop: %d (0x%x)", *cue, *cue);
				else
					debugC(2, kDebugLevelSound, " => Cue: %d (0x%x)", *cue, *cue);

			}
			return result;

		default:
			if (result > 0)
				song->_wakeupTime = song->_wakeupTime.addFrames(result);

			/* Delay */
			break;
		}
	}

}


/*****************/
/*  Song basics  */
/*****************/

void SfxState::sfx_add_song(SongIterator *it, int priority, SongHandle handle, int number) {
	Song *song = _songlib.findSong(handle);

#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Adding song: %08lx at %d, it=%p\n", handle, priority, it);
#endif
	if (!it) {
		error("[SFX] Attempt to add empty song with handle %08lx", handle);
		return;
	}

	it->init();

	/* If we're already playing this, stop it */
	/* Tell player to shut up */
//	_dump_songs(this);

	if (player)
		player->iterator_message(SongIterator::Message(handle, SIMSG_STOP));

	if (song) {
		setSongStatus( song, SOUND_STATUS_STOPPED);

		fprintf(stderr, "Overwriting old song (%08lx) ...\n", handle);
		if (song->_status == SOUND_STATUS_PLAYING || song->_status == SOUND_STATUS_SUSPENDED) {
			delete it;
			error("Unexpected (error): Song %ld still playing/suspended (%d)",
			        handle, song->_status);
			return;
		} else {
			_songlib.removeSong(handle); /* No duplicates */
		}

	}

	song = new Song(handle, it, priority);
	song->_resourceNum = number;
	song->_hold = 0;
	song->_loops = 0;
	song->_wakeupTime = Audio::Timestamp(g_system->getMillis(), SFX_TICKS_PER_SEC);
	_songlib.addSong(song);
	_song = NULL; /* As above */
	update();

	return;
}

void SfxState::sfx_remove_song(SongHandle handle) {
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Removing song: %08lx\n", handle);
#endif
	if (_song && _song->_handle == handle)
		_song = NULL;

	_songlib.removeSong(handle);
	update();
}



/**********************/
/* Song modifications */
/**********************/

#define ASSERT_SONG(s) if (!(s)) { warning("Looking up song handle %08lx failed in %s, L%d", handle, __FILE__, __LINE__); return; }

void SfxState::sfx_song_set_status(SongHandle handle, int status) {
	Song *song = _songlib.findSong(handle);
	ASSERT_SONG(song);
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Setting song status to %d"
	        " (0:stop, 1:play, 2:susp, 3:wait): %08lx\n", status, handle);
#endif

	setSongStatus(song, status);

	update();
}

void SfxState::sfx_song_set_fade(SongHandle handle, fade_params_t *params) {
#ifdef DEBUG_SONG_API
	static const char *stopmsg[] = {"??? Should not happen", "Do not stop afterwards", "Stop afterwards"};
#endif
	Song *song = _songlib.findSong(handle);

	ASSERT_SONG(song);

#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Setting fade params of %08lx to "
	        "final volume %d in steps of %d per %d ticks. %s.",
	        handle, fade->final_volume, fade->step_size, fade->ticks_per_step,
	        stopmsg[fade->action]);
#endif

	SIMSG_SEND_FADE(song->_it, params);

	update();
}

void SfxState::sfx_song_renice(SongHandle handle, int priority) {
	Song *song = _songlib.findSong(handle);
	ASSERT_SONG(song);
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Renicing song %08lx to %d\n",
	        handle, priority);
#endif

	song->_priority = priority;

	update();
}

void SfxState::sfx_song_set_loops(SongHandle handle, int loops) {
	Song *song = _songlib.findSong(handle);
	SongIterator::Message msg = SongIterator::Message(handle, SIMSG_SET_LOOPS(loops));
	ASSERT_SONG(song);

	song->_loops = loops;
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Setting loops on %08lx to %d\n",
	        handle, loops);
#endif
	songit_handle_message(&(song->_it), msg);

	if (player/* && player->send_iterator_message*/)
		/* FIXME: The above should be optional! */
		player->iterator_message(msg);
}

void SfxState::sfx_song_set_hold(SongHandle handle, int hold) {
	Song *song = _songlib.findSong(handle);
	SongIterator::Message msg = SongIterator::Message(handle, SIMSG_SET_HOLD(hold));
	ASSERT_SONG(song);

	song->_hold = hold;
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] Setting hold on %08lx to %d\n",
	        handle, hold);
#endif
	songit_handle_message(&(song->_it), msg);

	if (player/* && player->send_iterator_message*/)
		/* FIXME: The above should be optional! */
		player->iterator_message(msg);
}

/* Different from the one in iterator.c */
static const int MIDI_cmdlen[16] = {0, 0, 0, 0, 0, 0, 0, 0,
                                    3, 3, 0, 3, 2, 0, 3, 0
                                   };

static const SongHandle midi_send_base = 0xffff0000;

Common::Error SfxState::sfx_send_midi(SongHandle handle, int channel,
	int command, int arg1, int arg2) {
	byte buffer[5];

	/* Yes, in that order. SCI channel mutes are actually done via
	   a counting semaphore. 0 means to decrement the counter, 1
	   to increment it. */
	static const char *channel_state[] = {"ON", "OFF"};

	if (command == 0xb0 &&
	        arg1 == SCI_MIDI_CHANNEL_MUTE) {
		warning("TODO: channel mute (channel %d %s)", channel, channel_state[arg2]);
		/* We need to have a GET_PLAYMASK interface to use
		   here. SET_PLAYMASK we've got.
		*/
		return Common::kNoError;
	}

	buffer[0] = channel | command; /* No channel remapping yet */

	switch (command) {
	case 0x80 :
	case 0x90 :
	case 0xb0 :
		buffer[1] = arg1 & 0xff;
		buffer[2] = arg2 & 0xff;
		break;
	case 0xc0 :
		buffer[1] = arg1 & 0xff;
		break;
	case 0xe0 :
		buffer[1] = (arg1 & 0x7f) | 0x80;
		buffer[2] = (arg1 & 0xff00) >> 7;
		break;
	default:
		warning("Unexpected explicit MIDI command %02x", command);
		return Common::kUnknownError;
	}

	if (player)
		player->tell_synth(MIDI_cmdlen[command >> 4], buffer);
	return Common::kNoError;
}

int SfxState::sfx_get_volume() {
	warning("FIXME: Implement volume");
	return 0;
}

void SfxState::sfx_set_volume(int volume) {
	warning("FIXME: Implement volume");
}

void SfxState::sfx_all_stop() {
#ifdef DEBUG_SONG_API
	fprintf(stderr, "[sfx-core] All stop\n");
#endif

	_songlib.freeSounds();
	update();
}

} // End of namespace Sci