Debian Codegraph @

extras/osaudio/osaudio_dos_soundblaster.c

raw symbols SCIP
1 /*
2 This is only designed to work on DOS. I have only tested compiling this with OpenWatcom v2.0. Open
3 to feedback on improving compiler compatibility.
4
5 This will look at the BLASTER environment variable for the base port, IRQ and DMA channel. We're
6 only allowing a single device to be initialized at any given time. The channel will be defined by
7 the BLASTER environment variable, or if that's not set, it will default to channel 1 (for 8-bit) or
8 channel 5 (for 16-bit).
9 */
10
11 /* Keep this file empty if we're not compiling for DOS. */
12 #if defined(__MSDOS__) || defined(__DOS__)
13 #ifndef osaudio_dos_soundblaster_c
14 #define osaudio_dos_soundblaster_c
15
16 #include "osaudio.h"
17
18 #include <dos.h> /* outportb() */
19 #include <conio.h> /* delay() */
20 #include <string.h> /* memset() */
21 #include <stdlib.h> /* malloc(), free() */
22
23 int g_TESTING = 0;
24
25 #define OSAUDIO_TIMEOUT_TICKS 18 /* ~1 second timeout (just under - runs at 18.2 ticks per second). Sound Blaster specs claim it should only take about 100 microseconds so this is way overkill. */
26
27 #define OSAUDIO_SB_MIXER_PORT 0x004
28 #define OSAUDIO_SB_MIXER_DATA_PORT 0x005
29 #define OSAUDIO_SB_DSP_RESET_PORT 0x006
30 #define OSAUDIO_SB_DSP_READ_PORT 0x00A
31 #define OSAUDIO_SB_DSP_WRITE_PORT 0x00C
32 #define OSAUDIO_SB_DSP_READY_READ_PORT 0x00E
33
34 #define OSAUDIO_SB_DSP_RESET_CMD 0x01
35 #define OSAUDIO_SB_DSP_GET_VERSION 0xE1
36
37 #define OSAUDIO_ISA_DMA_MASK_REGISTER_8BIT 0x0A
38 #define OSAUDIO_ISA_DMA_MASK_REGISTER_16BIT 0xD4
39
40 #define OSAUDIO_ISA_DMA_FLIPFLOP_REGISTER_8BIT 0x0C
41 #define OSAUDIO_ISA_DMA_FLIPFLOP_REGISTER_16BIT 0xD8
42
43 #define OSAUDIO_ISA_DMA_MODE_REGISTER_8BIT 0x0B
44 #define OSAUDIO_ISA_DMA_MODE_REGISTER_16BIT 0xD6
45 #define OSAUDIO_ISA_DMA_MODE_DEMAND 0x00
46 #define OSAUDIO_ISA_DMA_MODE_SINGLE 0x40
47 #define OSAUDIO_ISA_DMA_MODE_BLOCK 0x80
48 #define OSAUDIO_ISA_DMA_MODE_CASCADE 0xC0
49 #define OSAUDIO_ISA_DMA_MODE_READ 0x08
50 #define OSAUDIO_ISA_DMA_MODE_WRITE 0x04
51 #define OSAUDIO_ISA_DMA_MODE_AUTOINIT 0x10
52
53 #define OSAUDIO_ISA_DMA_ADDRESS_REGISTER_8BIT 0x00
54 #define OSAUDIO_ISA_DMA_ADDRESS_REGISTER_16BIT 0xC0
55
56 #define OSAUDIO_ISA_DMA_COUNT_REGISTER_8BIT 0x01
57 #define OSAUDIO_ISA_DMA_COUNT_REGISTER_16BIT 0xC2
58
59 #define OSAUDIO_SB_DEVICE_NAME "Sound Blaster"
60
61 #define OSAUDIO_COUNTOF(x) (sizeof(x) / sizeof(x[0]))
62 #define OSAUDIO_ALIGN(x, a) (((x) + ((a)-1)) & ~((a)-1))
63 #define OSAUDIO_ALIGN_32(x) OSAUDIO_ALIGN(x, 4)
64
65 /* BLASTER environment variable defaults. */
66 static unsigned short OSAUDIO_SB_BASE_PORT = 0x220;
67 static unsigned short OSAUDIO_SB_IRQ = 7;
68 static unsigned short OSAUDIO_SB_DMA_CHANNEL_8 = 1;
69 static unsigned short OSAUDIO_SB_DMA_CHANNEL_16 = 5;
70
71 static signed char osaudio_g_is_sb16_present = -1;
72 static unsigned char osaudio_g_sb16_version_major = 0;
73 static unsigned char osaudio_g_sb16_version_minor = 0;
74 static osaudio_t osaudio_g_audio = NULL; /* For ISA DMA interrupt because there's no user data option. Only one device can be initialized at a time. */
75
76 static osaudio_format_t osaudio_g_supportedFormats[] =
77 {
78 OSAUDIO_FORMAT_S16, OSAUDIO_FORMAT_U8
79 };
80
81 static unsigned char osaudio_g_supportedChannels[] =
82 {
83 2, 1
84 };
85
86 static unsigned int osaudio_g_supportedSampleRates[] =
87 {
88 44100, 22050, 11025, 24000, 12000, 8000
89 };
90
91
92 struct _osaudio_t
93 {
94 void far* pDMABuffer;
95 void (_interrupt _far* old_isr)(void);
96 osaudio_info_t info;
97 osaudio_config_t config; /* info.configs will point to this. */
98 unsigned int cursor; /* The position of the write or read cursor relative to the start of the current sub-buffer. In frames. */
99 unsigned char subBufferIndex; /* When 0, the next write and read will happen in the first half of the DMA buffer, when 1, the second half. Will flip-flop between 0 and 1 each interrupt. */
100 unsigned char isActive;
101 unsigned char isPaused;
102 };
103
104 static void osaudio_outportb(unsigned short port, unsigned char value)
105 {
106 _outp(port, value);
107 }
108
109 static unsigned char osaudio_inportb(unsigned short port)
110 {
111 return _inp(port);
112 }
113
114 static void osaudio_delay(unsigned int milliseconds)
115 {
116 delay(milliseconds);
117 }
118
119 static unsigned long osaudio_get_ticks()
120 {
121 union REGS regs;
122
123 regs.h.ah = 0x00; /* Get system time */
124 int86(0x1A, &regs, &regs);
125
126 return ((unsigned long)regs.x.cx << 16) | regs.x.dx;
127 }
128
129 void far_memset(void far* dst, int c, unsigned int count)
130 {
131 unsigned char far *p = dst;
132 unsigned int i;
133
134 for (i = 0; i < count; i += 1) {
135 p[i] = c;
136 }
137 }
138
139 static void far* osaudio_dos_calloc(unsigned int sz)
140 {
141 /* This uses the DOS interrupt 0x21, function 0x48 allocation. */
142 void far* p;
143 union REGS regs;
144
145 regs.h.ah = 0x48;
146 regs.x.bx = (sz + 15) / 16;
147 int86(0x21, &regs, &regs);
148
149 if (regs.x.cflag) {
150 return NULL;
151 }
152
153 p = MK_FP(regs.x.ax, 0);
154
155 /* Clear to zero for safety. */
156 far_memset(p, 0, sz);
157
158 return p;
159 }
160
161 static void osaudio_dos_free(void far* p)
162 {
163 /* This uses the DOS interrupt 0x21, function 0x49 free. */
164 union REGS regs;
165 struct SREGS sregs;
166
167 regs.h.ah = 0x49;
168 regs.x.bx = FP_OFF(p);
169 sregs.es = FP_SEG(p);
170 intdosx(&regs, &regs, &sregs);
171 }
172
173 static void osaudio_blaster_parse_env()
174 {
175 /* This parses the BLASTER environment variable. */
176 char* pBlaster;
177 char* p;
178 int unused;
179
180 pBlaster = getenv("BLASTER");
181 if (pBlaster == NULL) {
182 return;
183 }
184
185 /* We have a BLASTER environment variable. */
186 p = pBlaster;
187
188 /*
189 I'm not sure if we can assume that each of these are present and in the same order. Therefore
190 we will do this generically and parse each segment, separated by whitespace.
191 */
192 for (;;) {
193 /* Skip whitespace. */
194 while (*p == ' ' || *p == '\t') {
195 p += 1;
196 }
197
198 if (*p == '\0') {
199 break;
200 }
201
202 /* Parse the segment. */
203 if (p[0] == 'A') {
204 /* Base port. */
205 p += 1;
206 OSAUDIO_SB_BASE_PORT = (unsigned short)strtoul(p, &p, 16);
207 /*printf("A%u\n", (unsigned int)OSAUDIO_SB_BASE_PORT);*/
208 } else if (p[0] == 'I') {
209 /* IRQ. */
210 p += 1;
211 OSAUDIO_SB_IRQ = (unsigned short)strtoul(p, &p, 10);
212 /*printf("I%u\n", (unsigned int)OSAUDIO_SB_IRQ);*/
213 } else if (p[0] == 'D') {
214 /* 8-bit DMA channel. */
215 p += 1;
216 OSAUDIO_SB_DMA_CHANNEL_8 = (unsigned short)strtoul(p, &p, 10);
217 /*printf("D%u\n", (unsigned int)OSAUDIO_SB_DMA_CHANNEL_8);*/
218 } else if (p[0] == 'H') {
219 /* 16-bit DMA channel. */
220 p += 1;
221 OSAUDIO_SB_DMA_CHANNEL_16 = (unsigned short)strtoul(p, &p, 10);
222 /*printf("H%u\n", (unsigned int)OSAUDIO_SB_DMA_CHANNEL_16);*/
223 } else if (p[0] == 'M' || p[0] == 'P' || p[0] == 'T') {
224 /* These are ignored. */
225 p += 1;
226 unused = (int)strtoul(p, &p, 16);
227 } else {
228 /* Unknown segment. Skip. */
229 p += 1;
230 unused = (int)strtoul(p, &p, 16);
231 }
232 }
233 }
234
235 static osaudio_result_t osaudio_init_sb16()
236 {
237 /* This checks for the presence of a Sound Blaster 16 card. */
238 if (osaudio_g_is_sb16_present == -1) {
239 unsigned long timeoutStart;
240
241 /*
242 Creative wants us to read settings from the BLASTER environment variable. We don't hard
243 fail here - we'll just fall back to defaults. It'll fail later if we don't have Sound
244 Blaster available.
245 */
246 osaudio_blaster_parse_env();
247
248
249 /* Getting here means we need to check for SB16. */
250 osaudio_outportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_RESET_PORT, OSAUDIO_SB_DSP_RESET_CMD);
251 osaudio_delay(1); /* Sound Blaster documentation says to wait 3 microseconds. We'll do 1 milliseconds. */
252 osaudio_outportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_RESET_PORT, 0x00);
253
254 /* Wait for DSP to be ready. */
255 timeoutStart = osaudio_get_ticks();
256 while ((osaudio_inportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_READY_READ_PORT) & 0x80) == 0) {
257 if (osaudio_get_ticks() - timeoutStart > OSAUDIO_TIMEOUT_TICKS) {
258 osaudio_g_is_sb16_present = 0;
259 return OSAUDIO_ERROR;
260 }
261 }
262
263 /* Check result of reset. */
264 if (osaudio_inportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_READ_PORT) == 0xAA) {
265 /* Wait for write port to be ready. */
266 timeoutStart = osaudio_get_ticks();
267 while (osaudio_inportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_WRITE_PORT) & 0x80) {
268 if (osaudio_get_ticks() - timeoutStart > OSAUDIO_TIMEOUT_TICKS) {
269 osaudio_g_is_sb16_present = 0;
270 return OSAUDIO_ERROR;
271 }
272 }
273
274 /* Send DSP command to get version. */
275 osaudio_outportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_WRITE_PORT, OSAUDIO_SB_DSP_GET_VERSION);
276 osaudio_g_sb16_version_major = osaudio_inportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_READ_PORT);
277 osaudio_g_sb16_version_minor = osaudio_inportb(OSAUDIO_SB_BASE_PORT | OSAUDIO_SB_DSP_READ_PORT);
278
279 if (osaudio_g_sb16_version_major == 4) {
280 osaudio_g_is_sb16_present = 1;
281 } else {
282 osaudio_g_is_sb16_present = 0;
283 }
284
285 /* Now configure the IRQ. */
286 if (osaudio_g_is_sb16_present) {
287 unsigned char irqCode;
288
289 switch (OSAUDIO_SB_IRQ) {
290 case 2: irqCode = 0x01; break;
291 case 5: irqCode = 0x02; break;
292 case 7: irqCode = 0x04; break;
293 case 10: irqCode = 0x08; break;
294 default: irqCode = 0x04; break; /* Will never hit this. */
295 }
296
297 /*
298 printf("Mixer port: %u\n", OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_PORT);
299 printf("Mixer data port: %u\n", OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_DATA_PORT);
300 printf("IRQ code: %u\n", (unsigned int)irqCode);
301 */
302
303 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_PORT, 0x80);
304 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_DATA_PORT, irqCode);
305 }
306 } else {
307 osaudio_g_is_sb16_present = 0;
308 }
309 }
310
311 if (osaudio_g_is_sb16_present) {
312 return OSAUDIO_SUCCESS;
313 } else {
314 return OSAUDIO_ERROR; /* Don't appear to have SB16. */
315 }
316 }
317
318 osaudio_result_t osaudio_enumerate(unsigned int* count, osaudio_info_t** info)
319 {
320 /*
321 We need only report a default playback device and a default capture device. We're going to
322 support both OSAUDIO_FORMAT_U8 and OSAUDIO_FORMAT_S16. Supported channel counts are mono and
323 stereo.
324 */
325 osaudio_result_t result;
326 unsigned int nativeFormatCount;
327 unsigned int iSupportedFormat;
328 unsigned int iSupportedChannels;
329 unsigned int iSupportedSampleRate;
330 osaudio_config_t* pRunningConfig;
331
332 if (count == NULL || info == NULL) {
333 return OSAUDIO_INVALID_ARGS;
334 }
335
336 result = osaudio_init_sb16();
337 if (result != OSAUDIO_SUCCESS) {
338 return result;
339 }
340
341 nativeFormatCount = OSAUDIO_COUNTOF(osaudio_g_supportedFormats) * OSAUDIO_COUNTOF(osaudio_g_supportedChannels) * OSAUDIO_COUNTOF(osaudio_g_supportedSampleRates);
342
343 *info = (osaudio_info_t*)calloc(1, sizeof(osaudio_info_t) * 2 + (sizeof(osaudio_config_t) * 2 * nativeFormatCount));
344 if (*info == NULL) {
345 return OSAUDIO_OUT_OF_MEMORY;
346 }
347
348 *count = 2;
349
350 /* Now we need to fill out the details. */
351 pRunningConfig = (osaudio_config_t*)(*info + 2);
352
353 /* Playback. */
354 strcpy((*info)[0].name, OSAUDIO_SB_DEVICE_NAME);
355 (*info)[0].direction = OSAUDIO_OUTPUT;
356 (*info)[0].config_count = nativeFormatCount;
357 (*info)[0].configs = pRunningConfig;
358
359 for (iSupportedFormat = 0; iSupportedFormat < OSAUDIO_COUNTOF(osaudio_g_supportedFormats); iSupportedFormat += 1) {
360 for (iSupportedChannels = 0; iSupportedChannels < OSAUDIO_COUNTOF(osaudio_g_supportedChannels); iSupportedChannels += 1) {
361 for (iSupportedSampleRate = 0; iSupportedSampleRate < OSAUDIO_COUNTOF(osaudio_g_supportedSampleRates); iSupportedSampleRate += 1) {
362 osaudio_config_init(pRunningConfig, OSAUDIO_OUTPUT);
363 pRunningConfig->format = osaudio_g_supportedFormats[iSupportedFormat];
364 pRunningConfig->channels = osaudio_g_supportedChannels[iSupportedChannels];
365 pRunningConfig->rate = osaudio_g_supportedSampleRates[iSupportedSampleRate];
366
367 if (pRunningConfig->channels == 1) {
368 pRunningConfig->channel_map[0] = OSAUDIO_CHANNEL_MONO;
369 } else {
370 pRunningConfig->channel_map[0] = OSAUDIO_CHANNEL_FL;
371 pRunningConfig->channel_map[1] = OSAUDIO_CHANNEL_FR;
372 }
373
374 pRunningConfig += 1;
375 }
376 }
377 }
378
379 /* Capture. */
380 strcpy((*info)[1].name, OSAUDIO_SB_DEVICE_NAME);
381 (*info)[1].direction = OSAUDIO_INPUT;
382 (*info)[1].config_count = nativeFormatCount;
383 (*info)[1].configs = pRunningConfig;
384
385 for (iSupportedFormat = 0; iSupportedFormat < OSAUDIO_COUNTOF(osaudio_g_supportedFormats); iSupportedFormat += 1) {
386 for (iSupportedChannels = 0; iSupportedChannels < OSAUDIO_COUNTOF(osaudio_g_supportedChannels); iSupportedChannels += 1) {
387 for (iSupportedSampleRate = 0; iSupportedSampleRate < OSAUDIO_COUNTOF(osaudio_g_supportedSampleRates); iSupportedSampleRate += 1) {
388 osaudio_config_init(pRunningConfig, OSAUDIO_OUTPUT);
389 pRunningConfig->format = osaudio_g_supportedFormats[iSupportedFormat];
390 pRunningConfig->channels = osaudio_g_supportedChannels[iSupportedChannels];
391 pRunningConfig->rate = osaudio_g_supportedSampleRates[iSupportedSampleRate];
392
393 if (pRunningConfig->channels == 1) {
394 pRunningConfig->channel_map[0] = OSAUDIO_CHANNEL_MONO;
395 } else {
396 pRunningConfig->channel_map[0] = OSAUDIO_CHANNEL_FL;
397 pRunningConfig->channel_map[1] = OSAUDIO_CHANNEL_FR;
398 }
399
400 pRunningConfig += 1;
401 }
402 }
403 }
404
405 return OSAUDIO_SUCCESS;
406 }
407
408 void osaudio_config_init(osaudio_config_t* config, osaudio_direction_t direction)
409 {
410 if (config == NULL) {
411 return;
412 }
413
414 memset(config, 0, sizeof(*config));
415 config->direction = direction;
416 }
417
418 static unsigned int osaudio_find_closest_rate(unsigned int rate, const unsigned int* pAvailableRates, unsigned int availableRateCount)
419 {
420 unsigned int iRate;
421 unsigned int bestRate;
422 unsigned int bestRateDelta;
423 unsigned int rateDelta;
424
425 bestRate = 0;
426 bestRateDelta = 0xFFFFFFFF;
427 for (iRate = 0; iRate < availableRateCount; iRate += 1) {
428 rateDelta = (pAvailableRates[iRate] > rate) ? (pAvailableRates[iRate] - rate) : (rate - pAvailableRates[iRate]);
429 if (rateDelta < bestRateDelta) {
430 bestRate = pAvailableRates[iRate];
431 bestRateDelta = rateDelta;
432 }
433 }
434
435 return bestRate;
436 }
437
438
439
440 #define PIC1_COMMAND 0x20
441 #define PIC1_DATA 0x21
442 #define PIC2_COMMAND 0xA0
443 #define PIC2_DATA 0xA1
444 #define PIC_EOI 0x20
445
446 static void send_eoi(int irq)
447 {
448 if (irq >= 8) {
449 /* If it's IRQ8 or higher, we have to send an EOI to both the master and slave controllers */
450 osaudio_outportb(PIC2_COMMAND, PIC_EOI);
451 }
452
453 /* Always send an EOI to the master controller */
454 osaudio_outportb(PIC1_COMMAND, PIC_EOI);
455 }
456
457
458 static void interrupt osaudio_isa_dma_interrupt_handler()
459 {
460 unsigned char status;
461 unsigned int cursor;
462
463 /* Unfortunately there's no user-data associated with the interrupt handler, so we have to use a global. */
464 osaudio_t audio = osaudio_g_audio;
465 if (audio == NULL) {
466 return;
467 }
468
469 /* In 16-bit mode, we need to check if the interrupt is for us. Only applies to SB16. */
470 #if 0
471 if (osaudio_g_sb16_version_major == 4) {
472 if (audio->config.format == OSAUDIO_FORMAT_S16) {
473 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_PORT, 0x82);
474 status = osaudio_inportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_DATA_PORT);
475 if ((status & 0x02) == 0) {
476 return; /* Not for us. */
477 }
478 }
479 }
480 #endif
481
482 /*
483 g_TESTING += 1;
484 printf("TESTING: %d\n", g_TESTING);
485 */
486
487 cursor = audio->cursor;
488
489 if (cursor < audio->config.buffer_size) {
490 /* This is an xrun. */
491 unsigned int bytesPerFrame;
492 bytesPerFrame = audio->config.channels * ((audio->config.format == OSAUDIO_FORMAT_S16) ? 2 : 1);
493
494 /* Fill the rest of the buffer with silence. */
495 //far_memset((char OSAUDIO_FAR*)audio->pDMABuffer + (audio->subBufferIndex * audio->config.buffer_size * bytesPerFrame) + (cursor * bytesPerFrame), 0, (audio->config.buffer_size - cursor) * bytesPerFrame);
496 //far_memset((char OSAUDIO_FAR*)audio->pDMABuffer + (audio->subBufferIndex * audio->config.buffer_size * bytesPerFrame), 0, audio->config.buffer_size * bytesPerFrame);
497
498 /* Now fill the entire next buffer with silence as well. */
499 //far_memset((char OSAUDIO_FAR*)audio->pDMABuffer + ((1 - audio->subBufferIndex) * audio->config.buffer_size * bytesPerFrame), 0, audio->config.buffer_size * bytesPerFrame);
500
501 far_memset((char OSAUDIO_FAR*)audio->pDMABuffer, 0, audio->config.buffer_size * bytesPerFrame * 2);
502
503 printf("XRUN: cursor = %u, subBufferIndex = %u; test = %u\n", cursor, audio->subBufferIndex, (audio->config.buffer_size * bytesPerFrame * 2));
504 return;
505 }
506
507 /* Flip the sub-buffer index. */
508 printf("Interrupt: sub-buffer index: %u\n", audio->subBufferIndex);
509 audio->subBufferIndex = 1 - audio->subBufferIndex;
510
511 /* Make sure the cursor is reset in prepration for the next half of the buffer. */
512 audio->cursor = 0;
513
514 /* Mark the sub-buffer as consumed. */
515 //audio->subBufferConsumed[audio->subBufferIndexInterrupt] = 1;
516 //audio->subBufferIndexInterrupt = 1 - audio->subBufferIndexInterrupt;
517
518 /* Interrupt acknowledgment. */
519 if (audio->config.format == OSAUDIO_FORMAT_U8) {
520 status = osaudio_inportb(OSAUDIO_SB_BASE_PORT + 0x00E);
521 } else {
522 status = osaudio_inportb(OSAUDIO_SB_BASE_PORT + 0x00F);
523 }
524
525 //printf("status: 0x%02X\n", status);
526 (void)status;
527
528 send_eoi(OSAUDIO_SB_IRQ);
529 }
530
531
532
533 #include <time.h>
534
535 void fill_random_unsigned_chars(unsigned char far* buffer, unsigned int size)
536 {
537 unsigned int i;
538
539 /* Seed the random number generator */
540 srand((unsigned)time(NULL));
541
542 for (i = 0; i < size; i++) {
543 /* Generate a random unsigned char integer */
544 buffer[i] = (unsigned char)(rand() - RAND_MAX / 2) >> 4;
545
546 //printf("buffer[%d] = %d\n", i, buffer[i]);
547 }
548 }
549
550
551 osaudio_result_t osaudio_open(osaudio_t* audio, osaudio_config_t* config)
552 {
553 osaudio_result_t result;
554 unsigned short dmaMaskRegister;
555 unsigned short flipflopRegister;
556 unsigned char dmaChannel;
557 unsigned int maxDMABufferSizeInFrames;
558 unsigned int actualDMABufferSizeInFrames;
559 unsigned int actualDMABufferSizeInBytes;
560 void far* pDMABuffer;
561 unsigned char picMask;
562
563
564 if (audio == NULL) {
565 return OSAUDIO_INVALID_ARGS;
566 }
567
568 *audio = NULL;
569
570 if (config == NULL) {
571 return OSAUDIO_INVALID_ARGS;
572 }
573
574 /* We can only have a single device open at a time. */
575 if (osaudio_g_audio != NULL) {
576 return OSAUDIO_ERROR;
577 }
578
579 /* First check that we have SB16. */
580 result = osaudio_init_sb16();
581 if (result != OSAUDIO_SUCCESS) {
582 return result;
583 }
584
585 /* Capture mode is not supported on anything older than Sound Blaster 16. */
586 if (config->direction == OSAUDIO_INPUT && osaudio_g_sb16_version_major < 4) {
587 return OSAUDIO_ERROR; /* Capture mode not supported. */
588 }
589
590 /* We're going to choose our native format configuration first. This way we can determine the Sound Blaster ports, channels and the size of the DMA buffer. */
591 if (config->format == OSAUDIO_FORMAT_UNKNOWN || (config->format != OSAUDIO_FORMAT_S16 && config->format != OSAUDIO_FORMAT_U8)) {
592 config->format = osaudio_g_supportedFormats[0];
593 }
594
595 if (config->channels == 0 || config->channels > 2) {
596 config->channels = osaudio_g_supportedChannels[0];
597 }
598
599 if (config->rate == 0) {
600 config->rate = osaudio_g_supportedSampleRates[0];
601 }
602
603 if (config->rate > 44100) {
604 config->rate = 44100;
605 }
606 if (config->rate < 8000) {
607 config->rate = 8000;
608 }
609
610 /*config->rate = osaudio_find_closest_rate(config->rate, osaudio_g_supportedSampleRates, OSAUDIO_COUNTOF(osaudio_g_supportedSampleRates));*/
611
612 /*
613 Calculate a desired buffer size if none was specified. I'm not quite sure what would be an
614 appropriate default in milliseconds, but lets go with 20ms for now. The buffer size is in
615 frames, not bytes.
616 */
617 if (config->buffer_size == 0) {
618 config->buffer_size = (80 * (unsigned long)config->rate) / 1000;
619 }
620
621
622 /*
623 Getting here means Sound Blaster 16 is available. We now need to allocate memory. There are two
624 things needing allocating - the DMA buffer, and the osaudio_t object. The allocation of the
625 osaudio_t object will use malloc().
626
627 The allocation of the DMA buffer will use the DOS interupt 0x21, function 0x48 for allocation.
628 This ensures that it will be allocated within the first 1MB which we need for Sound Blaster. In
629 addition, by making sure we don't allocate more than 65520 bytes we can ensure we don't cross a
630 64KB boundary which is another requirement.
631 */
632 maxDMABufferSizeInFrames = 65520 / config->channels / ((config->format == OSAUDIO_FORMAT_S16) ? 2 : 1); /* 65520 = max size in bytes. */
633
634 /*
635 The actual size of the buffer is equal to what we asked for in the configuration. The config
636 will contain valid values at this point.
637 */
638 actualDMABufferSizeInFrames = config->buffer_size;
639 if (actualDMABufferSizeInFrames > maxDMABufferSizeInFrames) {
640 actualDMABufferSizeInFrames = maxDMABufferSizeInFrames;
641 }
642
643 actualDMABufferSizeInBytes = actualDMABufferSizeInFrames * config->channels * ((config->format == OSAUDIO_FORMAT_S16) ? 2 : 1);
644
645 /* Now that we have the size of the DMA buffer we can allocate it. 2x because we're using double buffering. */
646 pDMABuffer = osaudio_dos_calloc(actualDMABufferSizeInBytes * 2);
647 if (pDMABuffer == NULL) {
648 return OSAUDIO_OUT_OF_MEMORY;
649 }
650
651 /*printf("actualDMABufferSizeInFrames = %d; maxDMABufferSizeInFrames = %d;\n", actualDMABufferSizeInFrames, maxDMABufferSizeInFrames);*/
652
653 /*
654 if (config->format == OSAUDIO_FORMAT_S16) {
655 fill_random_unsigned_chars(pDMABuffer, actualDMABufferSizeInFrames * config->channels * 2 * 2);
656 } else {
657 fill_random_unsigned_chars(pDMABuffer, actualDMABufferSizeInFrames * config->channels * 2);
658 }
659 */
660
661 //printf("actualDMABufferSizeInBytes = %u\n", actualDMABufferSizeInBytes);
662
663 /*
664 Allocate the osaudio_t object using malloc(). This is convenient because it means we can use a
665 near pointer for this object since that is how it's declared in osaudio.h.
666 */
667 *audio = (osaudio_t)calloc(1, sizeof(**audio));
668 if (*audio == NULL) {
669 osaudio_dos_free(pDMABuffer);
670 return OSAUDIO_OUT_OF_MEMORY;
671 }
672
673 (*audio)->subBufferIndex = 0;
674
675 /* For playback we want to start our sub-buffer at 1. */
676 if (config->direction == OSAUDIO_OUTPUT) {
677 (*audio)->subBufferIndex = 1;
678 } else {
679 (*audio)->subBufferIndex = 0;
680 }
681
682
683 /* Turn on speaker. Can this be done last? */
684 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD1);
685
686 /* Volume control. */
687 /*osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_PORT, 0x22);*/ /* 0x22 = Master Volume. */
688 /*osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_MIXER_DATA_PORT, 0xCC);*/ /* 0xLR */
689
690
691 /* Set up our interrupt. This is where we'll be notified when the buffer can be updated. */
692 (*audio)->old_isr = _dos_getvect(OSAUDIO_SB_IRQ + 8);
693 _dos_setvect(OSAUDIO_SB_IRQ + 8, osaudio_isa_dma_interrupt_handler);
694
695
696 /* Need to unmask the interrupt or else nothing will be heard. Should probably do the opposite of this when we're done with the device. */
697 picMask = osaudio_inportb(0x21);
698 picMask = picMask & ~(1 << OSAUDIO_SB_IRQ);
699 osaudio_outportb(0x21, picMask);
700
701
702 /* At this point we've allocated our memory. We can now configure the DMA. */
703
704 /* First we need to determine the mask register and the DMA channel. */
705 if (config->format == OSAUDIO_FORMAT_S16) {
706 dmaMaskRegister = OSAUDIO_ISA_DMA_MASK_REGISTER_16BIT;
707 flipflopRegister = OSAUDIO_ISA_DMA_FLIPFLOP_REGISTER_16BIT;
708 dmaChannel = OSAUDIO_SB_DMA_CHANNEL_16;
709 } else {
710 dmaMaskRegister = OSAUDIO_ISA_DMA_MASK_REGISTER_8BIT;
711 flipflopRegister = OSAUDIO_ISA_DMA_FLIPFLOP_REGISTER_8BIT;
712 dmaChannel = OSAUDIO_SB_DMA_CHANNEL_8;
713 }
714
715 /*printf("DMA Channel: %d\n", dmaChannel);*/
716
717 /* Now we can mask the channel. */
718 osaudio_outportb(dmaMaskRegister, (dmaChannel & 0x03) | 0x04);
719 {
720 osaudio_outportb(flipflopRegister, 0xFF);
721
722 /* Mode. */
723 {
724 unsigned char modeRegister = (config->format == OSAUDIO_FORMAT_S16) ? OSAUDIO_ISA_DMA_MODE_REGISTER_16BIT : OSAUDIO_ISA_DMA_MODE_REGISTER_8BIT;
725 unsigned char mode = OSAUDIO_ISA_DMA_MODE_DEMAND | OSAUDIO_ISA_DMA_MODE_AUTOINIT;
726
727 if (config->direction == OSAUDIO_OUTPUT) {
728 mode |= OSAUDIO_ISA_DMA_MODE_READ; /* From the perspective of the device. It's reading from the DMA buffer. */
729 } else {
730 mode |= OSAUDIO_ISA_DMA_MODE_WRITE; /* From the perspective of the device. It's writing to the DMA buffer. */
731 }
732
733 mode |= (dmaChannel & 0x03); /* The DMA channel. */
734
735 /* print the mode as a hex value for testing. */
736 /*printf("Mode: 0x%02x\n", mode);*/
737
738 osaudio_outportb(modeRegister, mode);
739 }
740
741 /* Address. */
742 {
743 unsigned char addressRegister;
744 unsigned char pageRegister;
745 unsigned long address;
746
747 if (config->format == OSAUDIO_FORMAT_S16) {
748 addressRegister = OSAUDIO_ISA_DMA_ADDRESS_REGISTER_16BIT + ((dmaChannel & 0x03) * 4);
749 } else {
750 addressRegister = OSAUDIO_ISA_DMA_ADDRESS_REGISTER_8BIT + ((dmaChannel & 0x03) * 2);
751 }
752
753 /* The page register is annoying. It's different depending on the DMA channel. */
754 switch (dmaChannel) {
755 case 1: pageRegister = 0x83; break;
756 case 2: pageRegister = 0x81; break;
757 case 3: pageRegister = 0x82; break;
758 case 5: pageRegister = 0x8B; break;
759 case 6: pageRegister = 0x89; break;
760 case 7: pageRegister = 0x8A; break;
761 default: pageRegister = 0; break; /* Will never get here. */
762 }
763
764 address = ((unsigned long)FP_SEG(pDMABuffer) << 4) + FP_OFF(pDMABuffer);
765
766 /*
767 Need to do a random shift by 1 bit when specifying the address in 16-bit mode. This one
768 screwed me over hardcore. Thanks to OSDev for the tip:
769
770 https://web.archive.org/web/20230731120125/https://wiki.osdev.org/ISA_DMA#16_bit_issues
771 */
772 if (config->format == OSAUDIO_FORMAT_S16) {
773 address >>= 1;
774 }
775
776 /* print the address as a hex value for testing. */
777 /*
778 printf("Address: 0x%04x\n", address);
779 printf("Address Register: 0x%02x\n", addressRegister);
780 printf("Page Register: 0x%02x\n", pageRegister);
781 */
782
783 /* Page. */
784 osaudio_outportb(pageRegister, (address >> 16) & 0xFF);
785
786 /* Address. */
787 osaudio_outportb(addressRegister, (address >> 0) & 0xFF);
788 osaudio_outportb(addressRegister, (address >> 8) & 0xFF);
789 }
790
791 /* Size */
792 {
793 unsigned char countRegister;
794 unsigned int count;
795
796 if (config->format == OSAUDIO_FORMAT_S16) {
797 countRegister = OSAUDIO_ISA_DMA_COUNT_REGISTER_16BIT + ((dmaChannel & 0x03) * 4);
798 } else {
799 countRegister = OSAUDIO_ISA_DMA_COUNT_REGISTER_8BIT + ((dmaChannel & 0x03) * 2);
800 }
801
802 /*
803 We're using a double-buffering technique which means we want to double the size of the buffer.
804 */
805 count = actualDMABufferSizeInBytes * 2; /* 2x because of double buffering. */
806 if (config->format == OSAUDIO_FORMAT_S16) {
807 count >>= 1; /* 1/2 because of 16-bit mode. */
808 }
809
810 count -= 1;
811
812 /*
813 printf("Size: 0x%04x\n", count);
814 printf("Count Register: 0x%02x\n", countRegister);
815 */
816
817 /* Size. */
818 osaudio_outportb(countRegister, (count >> 0) & 0xFF);
819 osaudio_outportb(countRegister, (count >> 8) & 0xFF);
820 }
821 }
822 osaudio_outportb(dmaMaskRegister, (dmaChannel & 0x03));
823
824 /* At this point the DMA buffer should be configured. We can now configure the DSP. */
825
826 /* Sample Rate */
827 {
828 unsigned char command;
829 unsigned short sampleRate; /* Or time constant. */
830
831 /* For Sound Blaster 16 we'll use the exact sample rate. Otherwise we'll use the time constant. */
832 if (osaudio_g_sb16_version_major == 4) {
833 if (config->direction == OSAUDIO_OUTPUT) {
834 command = 0x41;
835 } else {
836 command = 0x42;
837 }
838
839 sampleRate = config->rate;
840 } else {
841 command = 0x40;
842 sampleRate = 65536 - ((unsigned long)256000000 / (config->channels * config->rate));
843 }
844
845 /*printf("Command: 0x%02x\n", command);*/
846 /*printf("Sample Rate: %u\n", sampleRate);*/
847
848 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, command);
849
850 if (osaudio_g_sb16_version_major == 4) {
851 /* Note that it's high byte first, unlike the block size below which is low byte first. This one bit me. */
852 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, (sampleRate >> 8) & 0xFF);
853 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, (sampleRate >> 0) & 0xFF);
854 } else {
855 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, (sampleRate >> 8) & 0xFF);
856 }
857 }
858
859 /* Data Format and Block Size. */
860 {
861 unsigned char command;
862 unsigned char mode;
863 unsigned int blockSize; /* In bytes. */
864
865 if (config->format == OSAUDIO_FORMAT_S16) {
866 if (config->direction == OSAUDIO_OUTPUT) {
867 command = 0xB6;
868 } else {
869 command = 0xBE;
870 }
871
872 if (config->channels == 1) {
873 mode = 0x10;
874 } else {
875 mode = 0x30;
876 }
877 } else {
878 if (config->direction == OSAUDIO_OUTPUT) {
879 command = 0xC6;
880 } else {
881 command = 0xCE;
882 }
883
884 if (config->channels == 1) {
885 mode = 0x00;
886 } else {
887 mode = 0x20;
888 }
889 }
890
891 blockSize = actualDMABufferSizeInBytes;
892 if (config->format == OSAUDIO_FORMAT_S16) {
893 blockSize >>= 1; /* 1/2 because of 16-bit mode. */
894 }
895
896 blockSize -= 1; /* Needs to be one less than the actual size. */
897
898 /*
899 printf("Command: 0x%02x\n", command);
900 printf("Mode: 0x%02x\n", mode);
901 printf("Block Size: %u\n", blockSize);
902 */
903
904 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, command);
905 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, mode);
906 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, (blockSize >> 0) & 0xFF);
907 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, (blockSize >> 8) & 0xFF);
908 }
909
910 /* Start in a paused state. */
911 if (config->format == OSAUDIO_FORMAT_S16) {
912 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD5);
913 } else {
914 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD0);
915 }
916
917
918 (*audio)->pDMABuffer = pDMABuffer;
919 strcpy((*audio)->info.name, OSAUDIO_SB_DEVICE_NAME);
920 (*audio)->info.direction = config->direction;
921 (*audio)->info.config_count = 1;
922 (*audio)->info.configs = &(*audio)->config;
923 (*audio)->config = *config;
924 (*audio)->config.buffer_size = actualDMABufferSizeInFrames;
925
926 /* Don't forget to set the global audio object. We need this for the ISR. */
927 osaudio_g_audio = *audio;
928
929 return OSAUDIO_SUCCESS;
930 }
931
932 osaudio_result_t osaudio_close(osaudio_t audio)
933 {
934 if (audio == NULL) {
935 return OSAUDIO_INVALID_ARGS;
936 }
937
938 /* TODO: Implement me. Look at the SB docs for how to properly shut down. */
939
940 /* Restore the old ISR. */
941 _dos_setvect(OSAUDIO_SB_IRQ + 8, audio->old_isr);
942
943 /* Free the DMA buffer. */
944 osaudio_dos_free(audio->pDMABuffer);
945
946 /* Now we can free the osaudio_t object. */
947 free(audio);
948
949 return OSAUDIO_SUCCESS;
950 }
951
952 static void osaudio_activate(osaudio_t audio)
953 {
954 if (audio->config.format == OSAUDIO_FORMAT_S16) {
955 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD6);
956 } else {
957 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD4);
958 }
959
960 audio->isActive = 1;
961 }
962
963 osaudio_result_t osaudio_write(osaudio_t audio, const void OSAUDIO_FAR* data, unsigned int frame_count)
964 {
965 if (audio == NULL) {
966 return OSAUDIO_INVALID_ARGS;
967 }
968
969 //printf("ENTERED: frame_count = %u\n", frame_count);
970 while (frame_count > 0) {
971 unsigned int framesAvailable;
972
973 if (audio->config.buffer_size > audio->cursor) {
974 framesAvailable = audio->config.buffer_size - audio->cursor;
975 } else {
976 framesAvailable = 0;
977 }
978
979 if (framesAvailable > 0) {
980 void far* dst;
981 unsigned int bytesPerFrame;
982 unsigned int framesToWrite = framesAvailable;
983 if (framesToWrite > frame_count) {
984 framesToWrite = frame_count;
985 }
986
987 //printf("framesAvailable = %u - %u = %u\n", audio->config.buffer_size, audio->cursor, framesAvailable);
988 /*printf("framesToWrite = %u; framesAvailable = %u\n", framesToWrite, framesAvailable);*/
989
990 /*
991 Now we can copy the data. We're doing a cheeky little optimization here. If the input
992 data pointer is equal to the DMA destination, we can skip the copy. This might happen
993 when the caller is writing directly to the DMA buffer, which they may be doing by using
994 a self-managed DMA buffer, in combination with osaudio_get_avail().
995 */
996 bytesPerFrame = audio->config.channels * (audio->config.format == OSAUDIO_FORMAT_S16 ? 2 : 1);
997
998 dst = (void far*)((char far*)audio->pDMABuffer + (audio->subBufferIndex * audio->config.buffer_size * bytesPerFrame) + (audio->cursor * bytesPerFrame));
999 if (dst == data) {
1000 /* Don't do anything. */
1001 } else {
1002 /* Move the memory. */
1003 unsigned int i;
1004 for (i = 0; i < framesToWrite * audio->config.channels; i += 1) {
1005 if (audio->config.format == OSAUDIO_FORMAT_S16) {
1006 ((short far*)dst)[i] = ((short far*)data)[i];
1007 } else {
1008 ((char far*)dst)[i] = ((char far*)data)[i];
1009 }
1010 }
1011 }
1012
1013 /* Update the cursor. */
1014 audio->cursor += framesToWrite;
1015 frame_count -= framesToWrite;
1016 data = (char far*)data + (framesToWrite * bytesPerFrame);
1017
1018 /* Activate the device. */
1019 if (!audio->isActive) {
1020 osaudio_activate(audio);
1021 }
1022 } else {
1023 /* No room. */
1024 if (!audio->isActive) {
1025 break;
1026 } else {
1027 /* Just keep looping. Don't sleep here - in my testing there just isn't enough resolution in the sleep timer. */
1028 }
1029 }
1030 }
1031
1032 return OSAUDIO_SUCCESS;
1033 }
1034
1035 osaudio_result_t osaudio_read(osaudio_t audio, void OSAUDIO_FAR* data, unsigned int frame_count)
1036 {
1037 if (audio == NULL) {
1038 return OSAUDIO_INVALID_ARGS;
1039 }
1040
1041 /* TODO: Implement me. */
1042
1043 return OSAUDIO_SUCCESS;
1044 }
1045
1046 osaudio_result_t osaudio_drain(osaudio_t audio)
1047 {
1048 if (audio == NULL) {
1049 return OSAUDIO_INVALID_ARGS;
1050 }
1051
1052 /*
1053 It's an invalid operation to drain while the device is paused or else we'll never return from
1054 this function.
1055 */
1056 if (audio->isPaused) {
1057 return OSAUDIO_INVALID_OPERATION;
1058 }
1059
1060 /* DOS is single threaded so we don't need to worry about waiting for any pending reads or writes. */
1061
1062
1063
1064 /* TODO: Implement me. */
1065
1066 return OSAUDIO_SUCCESS;
1067 }
1068
1069 osaudio_result_t osaudio_flush(osaudio_t audio)
1070 {
1071 if (audio == NULL) {
1072 return OSAUDIO_INVALID_ARGS;
1073 }
1074
1075 /* TODO: Implement me. */
1076
1077 return OSAUDIO_SUCCESS;
1078 }
1079
1080 osaudio_result_t osaudio_pause(osaudio_t audio)
1081 {
1082 if (audio == NULL || audio != osaudio_g_audio) {
1083 return OSAUDIO_INVALID_ARGS;
1084 }
1085
1086 if (audio->isPaused) {
1087 return OSAUDIO_SUCCESS;
1088 }
1089
1090 /* No need to deactivate the device if it's already inactive. */
1091 if (audio->isActive) {
1092 if (audio->config.format == OSAUDIO_FORMAT_S16) {
1093 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD5);
1094 } else {
1095 osaudio_outportb(OSAUDIO_SB_BASE_PORT + OSAUDIO_SB_DSP_WRITE_PORT, 0xD0);
1096 }
1097 }
1098
1099 audio->isPaused = 1;
1100
1101 return OSAUDIO_SUCCESS;
1102 }
1103
1104 osaudio_result_t osaudio_resume(osaudio_t audio)
1105 {
1106 if (audio == NULL || audio != osaudio_g_audio) {
1107 return OSAUDIO_INVALID_ARGS;
1108 }
1109
1110 if (!audio->isPaused) {
1111 return OSAUDIO_SUCCESS;
1112 }
1113
1114 /* Do not activate the device if it's inactive. */
1115 if (audio->isActive) {
1116 osaudio_activate(audio);
1117 }
1118
1119 audio->isPaused = 0;
1120
1121 return OSAUDIO_SUCCESS;
1122 }
1123
1124 unsigned int osaudio_get_avail(osaudio_t audio)
1125 {
1126 /* TODO: Implement me. */
1127
1128 return 0;
1129 }
1130
1131 const osaudio_info_t* osaudio_get_info(osaudio_t audio)
1132 {
1133 if (audio == NULL) {
1134 return NULL;
1135 }
1136
1137 return &audio->info;
1138 }
1139
1140 #endif /* osaudio_dos_soundblaster_c */
1141 #endif /* __MSDOS__ || __DOS__ */