mask off arguments for write hadlers
[gpsp.git] / sound.c
1 /* gameplaySP
2  *
3  * Copyright (C) 2006 Exophase <exophase@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of
8  * the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20
21 #include "common.h"
22 #include <SDL.h>
23 u32 global_enable_audio = 1;
24
25 direct_sound_struct direct_sound_channel[2];
26 gbc_sound_struct gbc_sound_channel[4];
27
28 u32 sound_frequency = 44100;
29
30 SDL_mutex *sound_mutex;
31 static SDL_cond *sound_cv;
32
33 #ifdef PSP_BUILD
34 u32 audio_buffer_size_number = 1;
35 #else
36 u32 audio_buffer_size_number = 8;
37 #endif
38
39 u32 sound_on;
40 static u32 audio_buffer_size;
41 static s16 sound_buffer[BUFFER_SIZE];
42 static u32 sound_buffer_base;
43
44 static u32 sound_last_cpu_ticks;
45 static fixed16_16 gbc_sound_tick_step;
46
47 static u32 sound_exit_flag;
48
49 // Queue 1, 2, or 4 samples to the top of the DS FIFO, wrap around circularly
50
51 #define sound_timer_queue(size, value)                                        \
52   *((s##size *)(ds->fifo + ds->fifo_top)) = value;                            \
53   ds->fifo_top = (ds->fifo_top + 1) % 32;                                     \
54
55 void sound_timer_queue8(u32 channel, u8 value)
56 {
57   direct_sound_struct *ds = direct_sound_channel + channel;
58   sound_timer_queue(8, value);
59 }
60
61 void sound_timer_queue16(u32 channel, u16 value)
62 {
63   direct_sound_struct *ds = direct_sound_channel + channel;
64   sound_timer_queue(8, value & 0xFF);
65   sound_timer_queue(8, value >> 8);
66 }
67
68 void sound_timer_queue32(u32 channel, u32 value)
69 {
70   direct_sound_struct *ds = direct_sound_channel + channel;
71
72   sound_timer_queue(8, value & 0xFF);
73   sound_timer_queue(8, (value >> 8) & 0xFF);
74   sound_timer_queue(8, (value >> 16) & 0xFF);
75   sound_timer_queue(8, value >> 24);
76 }
77
78 // Unqueue 1 sample from the base of the DS FIFO and place it on the audio
79 // buffer for as many samples as necessary. If the DS FIFO is 16 bytes or
80 // smaller and if DMA is enabled for the sound channel initiate a DMA transfer
81 // to the DS FIFO.
82
83 #define render_sample_null()                                                  \
84
85 #define render_sample_left()                                                  \
86   sound_buffer[buffer_index] += current_sample +                              \
87    fp16_16_to_u32((next_sample - current_sample) * fifo_fractional)           \
88
89 #define render_sample_right()                                                 \
90   sound_buffer[buffer_index + 1] += current_sample +                          \
91    fp16_16_to_u32((next_sample - current_sample) * fifo_fractional)           \
92
93 #define render_sample_both()                                                  \
94   dest_sample = current_sample +                                              \
95    fp16_16_to_u32((next_sample - current_sample) * fifo_fractional);          \
96   sound_buffer[buffer_index] += dest_sample;                                  \
97   sound_buffer[buffer_index + 1] += dest_sample                               \
98
99 #define render_samples(type)                                                  \
100   while(fifo_fractional <= 0xFFFF)                                            \
101   {                                                                           \
102     render_sample_##type();                                                   \
103     fifo_fractional += frequency_step;                                        \
104     buffer_index = (buffer_index + 2) % BUFFER_SIZE;                          \
105   }                                                                           \
106
107 void sound_timer(fixed16_16 frequency_step, u32 channel)
108 {
109   direct_sound_struct *ds = direct_sound_channel + channel;
110
111   fixed16_16 fifo_fractional = ds->fifo_fractional;
112   u32 buffer_index = ds->buffer_index;
113   s16 current_sample, next_sample, dest_sample;
114
115   current_sample = ds->fifo[ds->fifo_base] << 4;
116   ds->fifo_base = (ds->fifo_base + 1) % 32;
117   next_sample = ds->fifo[ds->fifo_base] << 4;
118
119   if(sound_on == 1)
120   {
121     if(ds->volume == DIRECT_SOUND_VOLUME_50)
122     {
123       current_sample >>= 1;
124       next_sample >>= 1;
125     }
126
127     switch(ds->status)
128     {
129       case DIRECT_SOUND_INACTIVE:
130         render_samples(null);
131         break;
132
133       case DIRECT_SOUND_RIGHT:
134         render_samples(right);
135         break;
136
137       case DIRECT_SOUND_LEFT:
138         render_samples(left);
139         break;
140
141       case DIRECT_SOUND_LEFTRIGHT:
142         render_samples(both);
143         break;
144     }
145   }
146   else
147   {
148     render_samples(null);
149   }
150
151   ds->buffer_index = buffer_index;
152   ds->fifo_fractional = fp16_16_fractional_part(fifo_fractional);
153
154   if(((ds->fifo_top - ds->fifo_base) % 32) <= 16)
155   {
156     if(dma[1].direct_sound_channel == channel)
157       dma_transfer(dma + 1);
158
159     if(dma[2].direct_sound_channel == channel)
160       dma_transfer(dma + 2);
161   }
162 }
163
164 void sound_reset_fifo(u32 channel)
165 {
166   direct_sound_struct *ds = direct_sound_channel;
167
168   memset(ds->fifo, 0, 32);
169 }
170
171 // Initial pattern data = 4bits (signed)
172 // Channel volume = 12bits
173 // Envelope volume = 14bits
174 // Master volume = 2bits
175
176 // Recalculate left and right volume as volume changes.
177 // To calculate the current sample, use (sample * volume) >> 16
178
179 // Square waves range from -8 (low) to 7 (high)
180
181 s8 square_pattern_duty[4][8] =
182 {
183   { 0xF8, 0xF8, 0xF8, 0xF8, 0x07, 0xF8, 0xF8, 0xF8 },
184   { 0xF8, 0xF8, 0xF8, 0xF8, 0x07, 0x07, 0xF8, 0xF8 },
185   { 0xF8, 0xF8, 0x07, 0x07, 0x07, 0x07, 0xF8, 0xF8 },
186   { 0x07, 0x07, 0x07, 0x07, 0xF8, 0xF8, 0x07, 0x07 },
187 };
188
189 s8 wave_samples[64];
190
191 u32 noise_table15[1024];
192 u32 noise_table7[4];
193
194 u32 gbc_sound_master_volume_table[4] = { 1, 2, 4, 0 };
195
196 u32 gbc_sound_channel_volume_table[8] =
197 {
198   fixed_div(0, 7, 12),
199   fixed_div(1, 7, 12),
200   fixed_div(2, 7, 12),
201   fixed_div(3, 7, 12),
202   fixed_div(4, 7, 12),
203   fixed_div(5, 7, 12),
204   fixed_div(6, 7, 12),
205   fixed_div(7, 7, 12)
206 };
207
208 u32 gbc_sound_envelope_volume_table[16] =
209 {
210   fixed_div(0, 15, 14),
211   fixed_div(1, 15, 14),
212   fixed_div(2, 15, 14),
213   fixed_div(3, 15, 14),
214   fixed_div(4, 15, 14),
215   fixed_div(5, 15, 14),
216   fixed_div(6, 15, 14),
217   fixed_div(7, 15, 14),
218   fixed_div(8, 15, 14),
219   fixed_div(9, 15, 14),
220   fixed_div(10, 15, 14),
221   fixed_div(11, 15, 14),
222   fixed_div(12, 15, 14),
223   fixed_div(13, 15, 14),
224   fixed_div(14, 15, 14),
225   fixed_div(15, 15, 14)
226 };
227
228 u32 gbc_sound_buffer_index = 0;
229 u32 gbc_sound_last_cpu_ticks = 0;
230 u32 gbc_sound_partial_ticks = 0;
231
232 u32 gbc_sound_master_volume_left;
233 u32 gbc_sound_master_volume_right;
234 u32 gbc_sound_master_volume;
235
236 #define update_volume_channel_envelope(channel)                               \
237   volume_##channel = gbc_sound_envelope_volume_table[envelope_volume] *       \
238    gbc_sound_channel_volume_table[gbc_sound_master_volume_##channel] *        \
239    gbc_sound_master_volume_table[gbc_sound_master_volume]                     \
240
241 #define update_volume_channel_noenvelope(channel)                             \
242   volume_##channel = gs->wave_volume *                                        \
243    gbc_sound_channel_volume_table[gbc_sound_master_volume_##channel] *        \
244    gbc_sound_master_volume_table[gbc_sound_master_volume]                     \
245
246 #define update_volume(type)                                                   \
247   update_volume_channel_##type(left);                                         \
248   update_volume_channel_##type(right)                                         \
249
250 #define update_tone_sweep()                                                   \
251   if(gs->sweep_status)                                                        \
252   {                                                                           \
253     u32 sweep_ticks = gs->sweep_ticks - 1;                                    \
254                                                                               \
255     if(sweep_ticks == 0)                                                      \
256     {                                                                         \
257       u32 rate = gs->rate;                                                    \
258                                                                               \
259       if(gs->sweep_direction)                                                 \
260         rate = rate - (rate >> gs->sweep_shift);                              \
261       else                                                                    \
262         rate = rate + (rate >> gs->sweep_shift);                              \
263                                                                               \
264       if(rate > 2048)                                                         \
265         rate = 2048;                                                          \
266                                                                               \
267       frequency_step = float_to_fp16_16(((131072.0 / (2048 - rate)) * 8.0) /  \
268        sound_frequency);                                                      \
269                                                                               \
270       gs->frequency_step = frequency_step;                                    \
271       gs->rate = rate;                                                        \
272                                                                               \
273       sweep_ticks = gs->sweep_initial_ticks;                                  \
274     }                                                                         \
275     gs->sweep_ticks = sweep_ticks;                                            \
276   }                                                                           \
277
278 #define update_tone_nosweep()                                                 \
279
280 #define update_tone_envelope()                                                \
281   if(gs->envelope_status)                                                     \
282   {                                                                           \
283     u32 envelope_ticks = gs->envelope_ticks - 1;                              \
284     envelope_volume = gs->envelope_volume;                                    \
285                                                                               \
286     if(envelope_ticks == 0)                                                   \
287     {                                                                         \
288       if(gs->envelope_direction)                                              \
289       {                                                                       \
290         if(envelope_volume != 15)                                             \
291           envelope_volume = gs->envelope_volume + 1;                          \
292       }                                                                       \
293       else                                                                    \
294       {                                                                       \
295         if(envelope_volume != 0)                                              \
296           envelope_volume = gs->envelope_volume - 1;                          \
297       }                                                                       \
298                                                                               \
299       update_volume(envelope);                                                \
300                                                                               \
301       gs->envelope_volume = envelope_volume;                                  \
302       gs->envelope_ticks = gs->envelope_initial_ticks;                        \
303     }                                                                         \
304     else                                                                      \
305     {                                                                         \
306       gs->envelope_ticks = envelope_ticks;                                    \
307     }                                                                         \
308   }                                                                           \
309
310 #define update_tone_noenvelope()                                              \
311
312 #define gbc_sound_synchronize()                                               \
313   while(((gbc_sound_buffer_index - sound_buffer_base) % BUFFER_SIZE) >        \
314    (audio_buffer_size * 2))                                                   \
315   {                                                                           \
316     SDL_CondWait(sound_cv, sound_mutex);                                      \
317   }                                                                           \
318
319 #define update_tone_counters(envelope_op, sweep_op)                           \
320   tick_counter += gbc_sound_tick_step;                                        \
321   if(tick_counter > 0xFFFF)                                                   \
322   {                                                                           \
323     if(gs->length_status)                                                     \
324     {                                                                         \
325       u32 length_ticks = gs->length_ticks - 1;                                \
326       gs->length_ticks = length_ticks;                                        \
327                                                                               \
328       if(length_ticks == 0)                                                   \
329       {                                                                       \
330         gs->active_flag = 0;                                                  \
331         break;                                                                \
332       }                                                                       \
333     }                                                                         \
334                                                                               \
335     update_tone_##envelope_op();                                              \
336     update_tone_##sweep_op();                                                 \
337                                                                               \
338     tick_counter &= 0xFFFF;                                                   \
339   }                                                                           \
340
341 #define gbc_sound_render_sample_right()                                       \
342   sound_buffer[buffer_index + 1] += (current_sample * volume_right) >> 22     \
343
344 #define gbc_sound_render_sample_left()                                        \
345   sound_buffer[buffer_index] += (current_sample * volume_left) >> 22          \
346
347 #define gbc_sound_render_sample_both()                                        \
348   gbc_sound_render_sample_right();                                            \
349   gbc_sound_render_sample_left()                                              \
350
351 #define gbc_sound_render_samples(type, sample_length, envelope_op, sweep_op)  \
352   for(i = 0; i < buffer_ticks; i++)                                           \
353   {                                                                           \
354     current_sample =                                                          \
355      sample_data[fp16_16_to_u32(sample_index) % sample_length];               \
356     gbc_sound_render_sample_##type();                                         \
357                                                                               \
358     sample_index += frequency_step;                                           \
359     buffer_index = (buffer_index + 2) % BUFFER_SIZE;                          \
360                                                                               \
361     update_tone_counters(envelope_op, sweep_op);                              \
362   }                                                                           \
363
364 #define gbc_noise_wrap_full 32767
365
366 #define gbc_noise_wrap_half 126
367
368 #define get_noise_sample_full()                                               \
369   current_sample =                                                            \
370    ((s32)(noise_table15[fp16_16_to_u32(sample_index) >> 5] <<                 \
371    (fp16_16_to_u32(sample_index) & 0x1F)) >> 31) & 0x0F                       \
372
373 #define get_noise_sample_half()                                               \
374   current_sample =                                                            \
375    ((s32)(noise_table7[fp16_16_to_u32(sample_index) >> 5] <<                  \
376    (fp16_16_to_u32(sample_index) & 0x1F)) >> 31) & 0x0F                       \
377
378 #define gbc_sound_render_noise(type, noise_type, envelope_op, sweep_op)       \
379   for(i = 0; i < buffer_ticks; i++)                                           \
380   {                                                                           \
381     get_noise_sample_##noise_type();                                          \
382     gbc_sound_render_sample_##type();                                         \
383                                                                               \
384     sample_index += frequency_step;                                           \
385                                                                               \
386     if(sample_index >= u32_to_fp16_16(gbc_noise_wrap_##noise_type))           \
387       sample_index -= u32_to_fp16_16(gbc_noise_wrap_##noise_type);            \
388                                                                               \
389     buffer_index = (buffer_index + 2) % BUFFER_SIZE;                          \
390     update_tone_counters(envelope_op, sweep_op);                              \
391   }                                                                           \
392
393 #define gbc_sound_render_channel(type, sample_length, envelope_op, sweep_op)  \
394   buffer_index = gbc_sound_buffer_index;                                      \
395   sample_index = gs->sample_index;                                            \
396   frequency_step = gs->frequency_step;                                        \
397   tick_counter = gs->tick_counter;                                            \
398                                                                               \
399   update_volume(envelope_op);                                                 \
400                                                                               \
401   switch(gs->status)                                                          \
402   {                                                                           \
403     case GBC_SOUND_INACTIVE:                                                  \
404       break;                                                                  \
405                                                                               \
406     case GBC_SOUND_LEFT:                                                      \
407       gbc_sound_render_##type(left, sample_length, envelope_op, sweep_op);    \
408       break;                                                                  \
409                                                                               \
410     case GBC_SOUND_RIGHT:                                                     \
411       gbc_sound_render_##type(right, sample_length, envelope_op, sweep_op);   \
412       break;                                                                  \
413                                                                               \
414     case GBC_SOUND_LEFTRIGHT:                                                 \
415       gbc_sound_render_##type(both, sample_length, envelope_op, sweep_op);    \
416       break;                                                                  \
417   }                                                                           \
418                                                                               \
419   gs->sample_index = sample_index;                                            \
420   gs->tick_counter = tick_counter;                                            \
421
422 #define gbc_sound_load_wave_ram(bank)                                         \
423   wave_bank = wave_samples + (bank * 32);                                     \
424   for(i = 0, i2 = 0; i < 16; i++, i2 += 2)                                    \
425   {                                                                           \
426     current_sample = wave_ram[i];                                             \
427     wave_bank[i2] = (((current_sample >> 4) & 0x0F) - 8);                     \
428     wave_bank[i2 + 1] = ((current_sample & 0x0F) - 8);                        \
429   }                                                                           \
430
431 void synchronize_sound()
432 {
433   SDL_LockMutex(sound_mutex);
434
435   gbc_sound_synchronize();
436
437   SDL_UnlockMutex(sound_mutex);
438 }
439
440 void update_gbc_sound(u32 cpu_ticks)
441 {
442   fixed16_16 buffer_ticks = float_to_fp16_16(((float)(cpu_ticks -
443    gbc_sound_last_cpu_ticks) * sound_frequency) / 16777216.0);
444   u32 i, i2;
445   gbc_sound_struct *gs = gbc_sound_channel;
446   fixed16_16 sample_index, frequency_step;
447   fixed16_16 tick_counter;
448   u32 buffer_index;
449   s32 volume_left, volume_right;
450   u32 envelope_volume;
451   s32 current_sample;
452   u32 sound_status = address16(io_registers, 0x84) & 0xFFF0;
453   s8 *sample_data;
454   s8 *wave_bank;
455   u8 *wave_ram = ((u8 *)io_registers) + 0x90;
456
457   gbc_sound_partial_ticks += fp16_16_fractional_part(buffer_ticks);
458   buffer_ticks = fp16_16_to_u32(buffer_ticks);
459
460   if(gbc_sound_partial_ticks > 0xFFFF)
461   {
462     buffer_ticks += 1;
463     gbc_sound_partial_ticks &= 0xFFFF;
464   }
465
466   SDL_LockMutex(sound_mutex);
467   if(synchronize_flag)
468   {
469     if(((gbc_sound_buffer_index - sound_buffer_base) % BUFFER_SIZE) >
470      (audio_buffer_size * 3 / 2))
471     {
472       while(((gbc_sound_buffer_index - sound_buffer_base) % BUFFER_SIZE) >
473        (audio_buffer_size * 3 / 2))
474       {
475         SDL_CondWait(sound_cv, sound_mutex);
476       }
477
478 #ifdef PSP_BUILD
479       if(current_frameskip_type == auto_frameskip)
480       {
481         sceDisplayWaitVblankStart();
482         real_frame_count = 0;
483         virtual_frame_count = 0;
484       }
485 #else
486       if(current_frameskip_type == auto_frameskip)
487       {
488 /*
489         u64 current_ticks;
490         u64 next_ticks;
491         get_ticks_us(&current_ticks);
492
493         next_ticks = ((current_ticks + 16666) / 16667) * 16667;
494         delay_us(next_ticks - current_ticks);
495
496         get_ticks_us(&frame_count_initial_timestamp);
497 */
498         /* prevent frameskip, or it will cause more audio,
499          * then more waiting here, then frame skip again, ... */
500         num_skipped_frames = 100;
501       }
502 #endif
503
504     }
505   }
506   if(sound_on == 1)
507   {
508     gs = gbc_sound_channel + 0;
509     if(gs->active_flag)
510     {
511       sound_status |= 0x01;
512       sample_data = gs->sample_data;
513       envelope_volume = gs->envelope_volume;
514       gbc_sound_render_channel(samples, 8, envelope, sweep);
515     }
516
517     gs = gbc_sound_channel + 1;
518     if(gs->active_flag)
519     {
520       sound_status |= 0x02;
521       sample_data = gs->sample_data;
522       envelope_volume = gs->envelope_volume;
523       gbc_sound_render_channel(samples, 8, envelope, nosweep);
524     }
525
526     gs = gbc_sound_channel + 2;
527     if(gbc_sound_wave_update)
528     {
529       if(gs->wave_bank == 1)
530       {
531         gbc_sound_load_wave_ram(1);
532       }
533       else
534       {
535         gbc_sound_load_wave_ram(0);
536       }
537
538       gbc_sound_wave_update = 0;
539     }
540
541     if((gs->active_flag) && (gs->master_enable))
542     {
543       sound_status |= 0x04;
544       sample_data = wave_samples;
545       if(gs->wave_type == 0)
546       {
547         if(gs->wave_bank == 1)
548           sample_data += 32;
549
550         gbc_sound_render_channel(samples, 32, noenvelope, nosweep);
551       }
552       else
553       {
554         gbc_sound_render_channel(samples, 64, noenvelope, nosweep);
555       }
556     }
557
558     gs = gbc_sound_channel + 3;
559     if(gs->active_flag)
560     {
561       sound_status |= 0x08;
562       envelope_volume = gs->envelope_volume;
563
564       if(gs->noise_type == 1)
565       {
566         gbc_sound_render_channel(noise, half, envelope, nosweep);
567       }
568       else
569       {
570         gbc_sound_render_channel(noise, full, envelope, nosweep);
571       }
572     }
573   }
574
575   address16(io_registers, 0x84) = sound_status;
576
577   gbc_sound_last_cpu_ticks = cpu_ticks;
578   gbc_sound_buffer_index =
579    (gbc_sound_buffer_index + (buffer_ticks * 2)) % BUFFER_SIZE;
580
581   SDL_UnlockMutex(sound_mutex);
582
583   SDL_CondSignal(sound_cv);
584 }
585
586 #define sound_copy_normal()                                                   \
587   current_sample = source[i]                                                  \
588
589 #define sound_copy(source_offset, length, render_type)                        \
590   _length = (length) / 2;                                                     \
591   source = (s16 *)(sound_buffer + source_offset);                             \
592   for(i = 0; i < _length; i++)                                                \
593   {                                                                           \
594     sound_copy_##render_type();                                               \
595     if(current_sample > 2047)                                                 \
596       current_sample = 2047;                                                  \
597     if(current_sample < -2048)                                                \
598       current_sample = -2048;                                                 \
599                                                                               \
600     stream_base[i] = current_sample << 4;                                     \
601     source[i] = 0;                                                            \
602   }                                                                           \
603
604 #define sound_copy_null(source_offset, length)                                \
605   _length = (length) / 2;                                                     \
606   source = (s16 *)(sound_buffer + source_offset);                             \
607   for(i = 0; i < _length; i++)                                                \
608   {                                                                           \
609     stream_base[i] = 0;                                                       \
610     source[i] = 0;                                                            \
611   }                                                                           \
612
613
614 void sound_callback(void *userdata, Uint8 *stream, int length)
615 {
616   u32 sample_length = length / 2;
617   u32 _length;
618   u32 i;
619   s16 *stream_base = (s16 *)stream;
620   s16 *source;
621   s32 current_sample;
622
623   SDL_LockMutex(sound_mutex);
624
625   while(((gbc_sound_buffer_index - sound_buffer_base) % BUFFER_SIZE) <
626    length && !sound_exit_flag)
627   {
628     SDL_CondWait(sound_cv, sound_mutex);
629   }
630
631   if(global_enable_audio)
632   {
633     if((sound_buffer_base + sample_length) >= BUFFER_SIZE)
634     {
635       u32 partial_length = (BUFFER_SIZE - sound_buffer_base) * 2;
636       sound_copy(sound_buffer_base, partial_length, normal);
637       source = (s16 *)sound_buffer;
638       sound_copy(0, length - partial_length, normal);
639       sound_buffer_base = (length - partial_length) / 2;
640     }
641     else
642     {
643       sound_copy(sound_buffer_base, length, normal);
644       sound_buffer_base += sample_length;
645     }
646   }
647   else
648   {
649     if((sound_buffer_base + sample_length) >= BUFFER_SIZE)
650     {
651       u32 partial_length = (BUFFER_SIZE - sound_buffer_base) * 2;
652       sound_copy_null(sound_buffer_base, partial_length);
653       source = (s16 *)sound_buffer;
654       sound_copy(0, length - partial_length, normal);
655       sound_buffer_base = (length - partial_length) / 2;
656     }
657     else
658     {
659       sound_copy_null(sound_buffer_base, length);
660       sound_buffer_base += sample_length;
661     }
662   }
663
664   SDL_CondSignal(sound_cv);
665
666   SDL_UnlockMutex(sound_mutex);
667 }
668
669 // Special thanks to blarrg for the LSFR frequency used in Meridian, as posted
670 // on the forum at http://meridian.overclocked.org:
671 // http://meridian.overclocked.org/cgi-bin/wwwthreads/showpost.pl?Board=merid
672 // angeneraldiscussion&Number=2069&page=0&view=expanded&mode=threaded&sb=4
673 // Hope you don't mind me borrowing it ^_-
674
675 void init_noise_table(u32 *table, u32 period, u32 bit_length)
676 {
677   u32 shift_register = 0xFF;
678   u32 mask = ~(1 << bit_length);
679   s32 table_pos, bit_pos;
680   u32 current_entry;
681   u32 table_period = (period + 31) / 32;
682
683   // Bits are stored in reverse order so they can be more easily moved to
684   // bit 31, for sign extended shift down.
685
686   for(table_pos = 0; table_pos < table_period; table_pos++)
687   {
688     current_entry = 0;
689     for(bit_pos = 31; bit_pos >= 0; bit_pos--)
690     {
691       current_entry |= (shift_register & 0x01) << bit_pos;
692
693       shift_register =
694        ((1 & (shift_register ^ (shift_register >> 1))) << bit_length) |
695        ((shift_register >> 1) & mask);
696     }
697
698     table[table_pos] = current_entry;
699   }
700 }
701
702 void reset_sound()
703 {
704   direct_sound_struct *ds = direct_sound_channel;
705   gbc_sound_struct *gs = gbc_sound_channel;
706   u32 i;
707
708   sound_on = 0;
709   sound_buffer_base = 0;
710   sound_last_cpu_ticks = 0;
711   memset(sound_buffer, 0, audio_buffer_size);
712
713   for(i = 0; i < 2; i++, ds++)
714   {
715     ds->buffer_index = 0;
716     ds->status = DIRECT_SOUND_INACTIVE;
717     ds->fifo_top = 0;
718     ds->fifo_base = 0;
719     ds->fifo_fractional = 0;
720     ds->last_cpu_ticks = 0;
721     memset(ds->fifo, 0, 32);
722   }
723
724   gbc_sound_buffer_index = 0;
725   gbc_sound_last_cpu_ticks = 0;
726   gbc_sound_partial_ticks = 0;
727
728   gbc_sound_master_volume_left = 0;
729   gbc_sound_master_volume_right = 0;
730   gbc_sound_master_volume = 0;
731   memset(wave_samples, 0, 64);
732
733   for(i = 0; i < 4; i++, gs++)
734   {
735     gs->status = GBC_SOUND_INACTIVE;
736     gs->sample_data = square_pattern_duty[2];
737     gs->active_flag = 0;
738   }
739 }
740
741 void sound_exit()
742 {
743   gbc_sound_buffer_index =
744    (sound_buffer_base + audio_buffer_size) % BUFFER_SIZE;
745   SDL_PauseAudio(1);
746   sound_exit_flag = 1;
747   SDL_CondSignal(sound_cv);
748   SDL_CloseAudio();
749 }
750
751 void init_sound()
752 {
753   SDL_AudioSpec sound_settings;
754
755 #ifdef PSP_BUILD
756   audio_buffer_size = (audio_buffer_size_number * 1024) + 3072;
757 #else
758   audio_buffer_size = 16 << audio_buffer_size_number;
759 //  audio_buffer_size = 16384;
760 #endif
761
762   SDL_AudioSpec desired_spec =
763   {
764     sound_frequency,
765     AUDIO_S16,
766     2,
767     0,
768     audio_buffer_size / 4,
769     0,
770     0,
771     sound_callback,
772     NULL
773   };
774
775   gbc_sound_tick_step =
776    float_to_fp16_16(256.0 / sound_frequency);
777
778   init_noise_table(noise_table15, 32767, 14);
779   init_noise_table(noise_table7, 127, 6);
780
781   reset_sound();
782
783   sound_mutex = SDL_CreateMutex();
784   sound_cv = SDL_CreateCond();
785
786   SDL_OpenAudio(&desired_spec, &sound_settings);
787   sound_frequency = sound_settings.freq;
788   audio_buffer_size = sound_settings.size;
789   u32 i = audio_buffer_size / 16;
790   for (audio_buffer_size_number = 0; i && (i & 1) == 0; i >>= 1)
791     audio_buffer_size_number++;
792 #ifndef PSP_BUILD
793   printf("audio: freq %d, size %d\n", sound_frequency, audio_buffer_size);
794 #endif
795
796   SDL_PauseAudio(0);
797 }
798
799 #define sound_savestate_builder(type)                                       \
800 void sound_##type##_savestate(file_tag_type savestate_file)                 \
801 {                                                                           \
802   file_##type##_variable(savestate_file, sound_on);                         \
803   file_##type##_variable(savestate_file, sound_buffer_base);                \
804   file_##type##_variable(savestate_file, sound_last_cpu_ticks);             \
805   file_##type##_variable(savestate_file, gbc_sound_buffer_index);           \
806   file_##type##_variable(savestate_file, gbc_sound_last_cpu_ticks);         \
807   file_##type##_variable(savestate_file, gbc_sound_partial_ticks);          \
808   file_##type##_variable(savestate_file, gbc_sound_master_volume_left);     \
809   file_##type##_variable(savestate_file, gbc_sound_master_volume_right);    \
810   file_##type##_variable(savestate_file, gbc_sound_master_volume);          \
811   file_##type##_array(savestate_file, wave_samples);                        \
812   file_##type##_array(savestate_file, direct_sound_channel);                \
813   file_##type##_array(savestate_file, gbc_sound_channel);                   \
814 }                                                                           \
815
816 sound_savestate_builder(read);
817 sound_savestate_builder(write_mem);
818