ELKS Sound Blaster /dev/dsp driver
==================================

The CONFIG_CHAR_DEV_DSP driver (audio-sb.c) plays digital audio on a Sound Blaster or
compatible ISA card through /dev/dsp, using the OSS ioctl interface.  It is a
playback-only driver: there is no recording path, no mixer ioctl, no MIDI and no
sequencer.  Output level is set once at boot and can be changed from user space
with audiomix(1); see "Output level" below.

Only raw unsigned 8-bit mono PCM is accepted.  Sample rate conversion, WAV
parsing and ADPCM decoding belong in user space.

Hardware resources
------------------

The card is driven with 8-bit ISA DMA on the primary 8237, channel 1 or 3
only, with a time constant for the rate.  A DSP 2.00 or later card plays
through auto-init DMA (command 0x1C), which runs continuously over the two
buffer halves and so has no gap between blocks; a Sound Blaster 1.x, and any
card reached through an OPTi MAD16, falls back to the classic single-block
command 0x14.  Any card from a Sound Blaster 1.0 upwards therefore works,
including the SB Pro and SB16 in their compatible mode.  16-bit DMA and the
SB16 high-DMA path are not used.

Defaults are SB_PORT 0x220, SB_IRQ 5 and SB_DMA 1 in arch/ports.h, which
are the Creative factory settings.  /bootopts can override them without a
rebuild:

    sb=5,220,1          IRQ, port and DMA channel
    sb=5,220,1,1        as above, plus 8237 Extended Write (see below)
    sb=7,220,1,3        the same with an OPTi MAD16 card, which needs bit 1
    sb=off              skip the driver on a machine with no card

The argument order is irq,port,dma,flags, the same as the ne0=, wd0= and
3c0= network options, which share the parser and the struct isa_conf that
holds the result.  The IRQ is read as decimal and the port and DMA channel as
hex, with an optional 0x, because an audio card keeps its DMA channel in the
ram field the NICs use for a memory address.  The flags are the fourth field.

The flag bits are the ISAF_ defines in arch/audio-sb.h:

    bit 0    1    set the 8237 DMA controller's Extended Write strobe
    bit 1    2    bring an OPTi 82C929 (MAD16) up in Sound Blaster mode
    bit 2    4    leave LPT1's interrupt alone when the card is on IRQ 7

Bit 0 exists because a machine whose DMA timing is tighter than 8-bit cards
expect - the Amstrad PC1512 and PC1640 - drops bytes without it, and plays
otherwise clean audio as heavy distortion.  Say sb=irq,port,dma,1 on such a
machine and leave it off everywhere else.  It is a controller-wide bit, so a
machine that also runs the XT MFM driver can set it there with mfm= bit 4
instead; setting it from both is harmless.

Bit 1 is described under "MAD16 boards" below.

Bit 2 concerns the printer port.  IRQ 7 is LPT1's line as well as the card's,
and the port powers up with its interrupt enabled; a floating or strobed ACK
then fires the sound ISR part way through a transfer, which is audible as
distortion.  The lp driver polls and never asks for IRQ 7, so the driver
idles LPT1's control register with the interrupt bit clear whenever the card
is on 7.  Set bit 2 to skip that on a machine that genuinely drives its
printer port from the interrupt.  The bit does nothing on any other IRQ.

The IRQ is claimed during boot rather than at open, so the sound card wins any
contest for it.  IRQ 5 is also Com3, so selecting it means the serial driver
can no longer open /dev/ttyS2.  IRQ 7 is Com4 and the second parallel port,
and additionally collects 8259 spurious interrupts, which the driver ignores.

XT machines with a hard disk
----------------------------

A Sound Blaster leaves the factory on IRQ 5 and offers DMA 1 or 3, and on an
XT-class machine with a hard disk fitted both of the defaults are already
taken.  The Amstrad PC1640 technical reference is representative:

    IRQ 2   real time clock, available on the expansion bus
    IRQ 3   spare, used by the secondary serial and SDLC ports
    IRQ 4   8250 UART (Com1)
    IRQ 5   hard disk controller
    IRQ 6   765 floppy disk controller
    IRQ 7   parallel printer port

    DMA 0   memory refresh
    DMA 1   spare for the expansion bus
    DMA 2   765 floppy disk controller
    DMA 3   external hard disk controller

So on such a machine jumper the card for IRQ 7 and DMA 1.  DMA 1 is the
driver's default and the only spare channel.  IRQ 7 is nominally the parallel
printer port, but the ELKS printer driver polls and never claims it, so it is
free in practice; the driver tolerates the 8259 spurious interrupts that also
arrive on IRQ 7.

LPT1 itself is a second source of interrupts on that line.  The printer port
powers up with its own interrupt enabled, and a floating or strobed ACK then
enters the sound card's handler part way through a transfer, which is audible
as distortion.  CONFIG_AUDIO_SB_LPTOFF, on by default, has the driver write
LPT1's control register once at boot with that interrupt bit clear.  It acts
only when the card is on IRQ 7, so it costs nothing on a machine using IRQ 5;
turn it off if something else there drives LPT1 from its interrupt.

IRQ 2 and IRQ 3 are the other candidates if the printer port is genuinely
needed, but check them against any network card first: an SMC Ultra reads its
own interrupt out of the card's configuration, and dmesg reports which one it
took at boot.

When the driver is built together with the XT MFM hard disk driver it enforces
this: DMA 3 is refused outright, because sharing the channel would corrupt disk
transfers, and IRQ 5 produces a warning, because sharing the interrupt only
costs spurious handler entries.

Buffering and the gap between blocks
------------------------------------

write() copies up to SB_BUFSIZE bytes (arch/ports.h, default 4096) into a
low-memory buffer of two such blocks, looping internally until the caller's
whole buffer has been consumed.

A DSP 2.00 or later card runs that buffer as a circular one under auto-init
DMA (command 0x1C with 8237 mode 0x58 plus the channel): the card interrupts
at each half and
nothing is reprogrammed between them, so playback is gapless.

Two cases fall back to a single block in flight, where write() returns only
once the previous block has drained: a Sound Blaster 1.x, which has only the
0x14 single-block command, and a card reached through an OPTi MAD16, whose
engine does not raise the per-block interrupt auto-init depends on - it was
measured hanging playback outright.  In that mode the DMA engine is idle
between blocks for the interrupt latency plus one buffer copy, a short gap
every SB_BUFSIZE/rate seconds, about every half second at 8000 Hz.  A smaller
buffer makes the gaps more frequent rather than removing them.

The fallback also sets the latency there: SNDCTL_DSP_SYNC and an interrupted
write take up to one block to take effect.

Sample rates
------------

Rates from 4000 to 20000 Hz are accepted.  The upper limit is the documented
ceiling for DSP 0x14 without the high-speed commands.

The DSP is programmed with a time constant of 256 - 1000000/rate, so the
achievable rates are quantised.  SNDCTL_DSP_SPEED is read-write and reports
the rate actually programmed, which the caller should re-read.  4000, 8000 and
20000 Hz are exact; 11025 Hz is not.

A card behind an OPTi 82C929 quantises again on top of that: the chip maps a
Sound Blaster rate onto what the codec's two crystals can produce, so a
request for 20000 Hz was measured playing at about 18900.  8000 and 16000 Hz
come out exact, which is what makes them the useful rates there.

A larger SB_BUFSIZE was measured to help a machine that cannot quite keep a
high rate fed - it halved the dropouts of an 11025 Hz network stream - but
the buffer is claimed in low memory and doubled for the two halves, so 4096
stays the default rather than spending 32K below 1M on every machine.

Supported ioctls
----------------

    SNDCTL_DSP_RESET        halt playback
    SNDCTL_DSP_SYNC         drain, then halt
    SNDCTL_DSP_SPEED        read/write sample rate
    SNDCTL_DSP_STEREO       read/write, 0 = mono
    SNDCTL_DSP_CHANNELS     read/write channel count
    SNDCTL_DSP_SETFMT       read/write format, DSP_FMT_U8 only
    SNDCTL_DSP_GETFMTS      supported format mask
    SNDCTL_DSP_GETBLKSIZE   DMA block size in bytes
    SNDCTL_DSP_POST         accepted, no effect
    SNDCTL_DSP_GETERROR     underrun count since the last call

Anything else returns EINVAL.  /dev/dsp allows a single opener at a time; a
second open returns EBUSY.  Reading from it returns end of file.

Output is mono.  SNDCTL_DSP_CHANNELS accepts a request for one channel and
SNDCTL_DSP_STEREO accepts 0, both reporting back what was set; asking for two
channels returns EINVAL.

MAD16 boards
------------

MAD16 is not a sound card and audio-mad.c is not a second /dev/dsp driver.
The OPTi 82C929 (marketed as MAD16 Pro) is a multimedia controller chip found
on a great many early-90s ISA boards, where it sits between the bus and an
AD1848 class codec and can present itself as more than one kind of card.  It
comes out of reset presenting none of them: the chip has no jumpers, so
before anything can talk to it, its MC configuration registers have to be
written to say which personality to expose and on which port, IRQ and DMA
channel.  Until that is done the board is silent and a DSP probe at 0x220
finds nothing at all.

What audio-mad.c does is exactly that one step - it puts the chip into Sound
Blaster mode.  After it returns, the board answers ordinary SB DSP commands
and audio-sb.c drives it like any other Sound Blaster; the playback path,
the DMA and the mixer are all the SB driver's.  That is why every message it
prints is prefixed "sb:" and why there is one /bootopts line, not two: the
port, IRQ and DMA come from sb= because they are the settings the card will
have once the routing is applied.

So the flag bit means "this card is an OPTi 82C929, route it to SB mode
first".  A real Sound Blaster, or anything already answering at its port,
does not need it and should not set it:

    sb=7,220,1,2        OPTi card at 0x220, IRQ 7, DMA 1
    sb=7,220,1,3        the same, plus Extended Write for a PC1512/PC1640

Only the codec side keeps a foot in audio-mad.c after boot.  The 82C929
rewrites the codec's data format register whenever it maps a rate, which
would fold linear samples about 0x80, so audio-sb.c calls back into
mad16_codec_fix_fmt() to put the companding bits back after each rate change.

The chip holds the SB route in three fields of its MC3 register:

    bit    2    SB port, clear = 0x220, set = 0x240
    bits 7:6    IRQ, 00 = 7, 01 = 10, 10 = 5, 11 = disabled
    bits 5:4    DMA, 00 = 1, 01 = 0, 10 = 3, 11 = disabled

The driver offers only the useful half of that: port 0x220 or 0x240, IRQ 5 or
7, and DMA 1 or 3.  It rejects any other request and says so:

    sb: mad16 cannot route 0x260 irq 3 dma 1, allows port 0x220/0x240
        irq 5/7 dma 1/3
    sb: mad16 82c929 not detected

Combined with the IRQ and DMA map above, a machine whose hard disk controller
owns IRQ 5 and DMA 3 leaves exactly one usable route for such a card: IRQ 7
with DMA 1, at either port.  There is no fallback if IRQ 7 is already taken,
so check it against the network card before relying on it.

Output level
------------

The driver programs the master and voice levels at every open, so a DSP reset
in between cannot leave them wherever the card's own defaults put them.  Both
go to 5 of 7 on an SB Pro, register value 0xAA, which is 11 of 15 and 0xBB on
an SB16: the same fraction of full scale in either mixer layout.

Full scale would be the obvious choice for a driver with no volume ioctl, and it
is wrong.  The voice and master attenuators are in series ahead of the output
amplifier, so all-ones in both asks for the loudest analog path the card has.
Eight-bit material already peaks near full scale, so the result clips in the
mixer and sounds distorted rather than loud.  Cards left at zero out of reset
are the opposite failure and look like a driver that runs silently, which is why
both stages are always programmed rather than left alone.

Boards differ in how much gain follows the mixer, so treat the 0xAA the driver
programs as a starting point.  audiomix(1) reads the registers back and sets them live:

    audiomix                   show the DSP version and decoded mixer levels
    audiomix -m 30 -v 30       set master and voice, as a percentage of full scale
    audiomix -s 0x22=0xAA      write a raw register value
    audiomix -r 0x0e           read one register

It decodes levels according to the DSP version, since a DSP 3.xx card reads
bits 7-5 and 3-1 as two 3-bit fields while a DSP 4.xx card reads bits 7-4 and
3-0 as two 4-bit fields.  A DSP 1.xx or 2.xx card has no mixer at all and
audiomix says so.  Run it while playback is idle: it resets the DSP to read the
version, which would interrupt a transfer in progress.

Playing audio
-------------

The play command writes raw unsigned 8-bit PCM to /dev/dsp:

    play -r 8000 tone.raw
    cat tone.raw | play

Convert material on the host first, for example:

    sox in.wav -t raw -r 8000 -c 1 -b 8 -e unsigned out.raw
    ffmpeg -i in.wav -f u8 -ar 8000 -ac 1 out.raw

play exits non-zero if the driver reported any underruns, so it can be
used as a pass/fail check.

Playing audio over the network
------------------------------

The audiorcv command listens on a TCP port and writes what arrives to
/dev/dsp, which avoids copying a file over first:

    audiorcv -r 8000                       one stream, then exit
    audiorcv -d -r 8000                    detach, serve streams forever

Nothing on the wire describes the audio, so -r has to match what the sender
was told to produce.  From the host:

    sox in.wav -t raw -r 8000 -c 1 -b 8 -e unsigned - | nc elks 4950
    ffmpeg -i in.wav -f u8 -ar 8000 -ac 1 - | nc elks 4950

With -4 the stream on the wire is Creative 4-bit ADPCM, which audiorcv
expands before writing it to the card - two samples a byte, high nibble
first, the first byte of a stream being the reference sample, with the step
tables the DOSBox and 86Box decoders use.  It halves what the network has to
carry for a given rate, which is what makes 11025 Hz reachable over a link
that cannot hold 11025 bytes a second.  The card's own ADPCM playback
commands are not used: an OPTi 82C929 does not decode Creative's encoding,
measured as a 440Hz tone coming back at 794Hz.

The port defaults to 4950 and is set with -p.  Add audiorcv to netstart= in
/etc/net.cfg to have /bin/net start it as a daemon; the command line is already
there, commented out.  "net stop" does not know the name, so kill it by hand.

Playback is real time, so the link has to sustain `rate' bytes per second, and
the slack is one DMA block: 4096 bytes, about half a second at 8000 Hz.
Ethernet manages this easily.  SLIP at 19200 baud carries around 1900 bytes per
second and cannot feed even the 4000 Hz minimum, so a serial link needs 40000
baud or better.  TCP flow control does the throttling, so a link that is too
slow breaks the audio up rather than corrupting it, and the underrun count
audiorcv prints at the end of each stream says how badly.

/dev/dsp is opened per stream, not held open, so play still works while
the daemon is idle.  Streams are served one at a time because the device has a
single opener.
