/*-
* Copyright (c) 2008 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Andrew Doran.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Copyright (c) 1991-1993 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Computer Systems
* Engineering Group at Lawrence Berkeley Laboratory.
* 4. Neither the name of the University nor of the Laboratory may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Terminology: "sample", "channel", "frame", "block", "track":
*
* channel frame
* | ........
* v : : \
* +------:------:------:- -+------+ : +------+-.. |
* #0(L) |sample|sample|sample| .. |sample| : |sample| |
* +------:------:------:- -+------+ : +------+-.. |
* #1(R) |sample|sample|sample| .. |sample| : |sample| |
* +------:------:------:- -+------+ : +------+-.. | track
* : : : : |
* +------:------:------:- -+------+ : +------+-.. |
* |sample|sample|sample| .. |sample| : |sample| |
* +------:------:------:- -+------+ : +------+-.. |
* : : /
* ........
*
* \--------------------------------/ \--------..
* block
*
* - A "frame" is the minimum unit in the time axis direction, and consists
* of samples for the number of channels.
* - A "block" is basic length of processing. The audio layer basically
* handles audio data stream block by block, asks underlying hardware to
* process them block by block, and then the hardware raises interrupt by
* each block.
* - A "track" is single completed audio stream.
*
* For example, the hardware block is assumed to be 10 msec, and your audio
* track consists of 2.1(=3) channels 44.1kHz 16bit PCM,
*
* "channel" = 3
* "sample" = 2 [bytes]
* "frame" = 2 [bytes/sample] * 3 [channels] = 6 [bytes]
* "block" = 44100 [Hz] * (10/1000) [seconds] * 6 [bytes/frame] = 2646 [bytes]
*
* The terminologies shown here are only for this MI audio layer. Note that
* different terminologies may be used in each manufacturer's datasheet, and
* each MD driver may follow it. For example, what we call a "block" is
* called a "frame" in sys/dev/pci/yds.c.
*/
/*
* Locking: there are three locks per device.
*
* - sc_lock, provided by the underlying driver. This is an adaptive lock,
* returned in the second parameter to hw_if->get_locks(). It is known
* as the "thread lock".
*
* It serializes access to state in all places except the
* driver's interrupt service routine. This lock is taken from process
* context (example: access to /dev/audio). It is also taken from soft
* interrupt handlers in this module, primarily to serialize delivery of
* wakeups. This lock may be used/provided by modules external to the
* audio subsystem, so take care not to introduce a lock order problem.
* LONG TERM SLEEPS MUST NOT OCCUR WITH THIS LOCK HELD.
*
* - sc_intr_lock, provided by the underlying driver. This may be either a
* spinlock (at IPL_SCHED or IPL_VM) or an adaptive lock (IPL_NONE or
* IPL_SOFT*), returned in the first parameter to hw_if->get_locks(). It
* is known as the "interrupt lock".
*
* It provides atomic access to the device's hardware state, and to audio
* channel data that may be accessed by the hardware driver's ISR.
* In all places outside the ISR, sc_lock must be held before taking
* sc_intr_lock. This is to ensure that groups of hardware operations are
* made atomically. SLEEPS CANNOT OCCUR WITH THIS LOCK HELD.
*
* - sc_exlock, private to this module. This is a variable protected by
* sc_lock. It is known as the "critical section".
* Some operations release sc_lock in order to allocate memory, to wait
* for in-flight I/O to complete, to copy to/from user context, etc.
* sc_exlock provides a critical section even under the circumstance.
* "+" in following list indicates the interfaces which necessary to be
* protected by sc_exlock.
*
* List of hardware interface methods, and which locks are held when each
* is called by this module:
*
* METHOD INTR THREAD NOTES
* ----------------------- ------- ------- -------------------------
* open x x +
* close x x +
* query_format - x
* set_format - x
* round_blocksize - x
* commit_settings - x
* init_output x x
* init_input x x
* start_output x x +
* start_input x x +
* halt_output x x +
* halt_input x x +
* speaker_ctl x x
* getdev - -
* set_port - x +
* get_port - x +
* query_devinfo - x
* allocm - - +
* freem - - +
* round_buffersize - x
* get_props - - Called at attach time
* trigger_output x x +
* trigger_input x x +
* dev_ioctl - x
* get_locks - - Called at attach time
*
* In addition, there is an additional lock.
*
* - track->lock. This is an atomic variable and is similar to the
* "interrupt lock". This is one for each track. If any thread context
* (and software interrupt context) and hardware interrupt context who
* want to access some variables on this track, they must acquire this
* lock before. It protects track's consistency between hardware
* interrupt context and others.
*/
static int mlog_refs; /* reference counter */
static char *mlog_buf[2]; /* double buffer */
static int mlog_buflen; /* buffer length */
static int mlog_used; /* used length */
static int mlog_full; /* number of dropped lines by buffer full */
static int mlog_drop; /* number of dropped lines by busy */
static volatile uint32_t mlog_inuse; /* in-use */
static int mlog_wpage; /* active page */
static void *mlog_sih; /* softint handle */
n = 0;
buf[0] = '\0';
n += snprintf(buf + n, sizeof(buf) - n, "%s@%d %s",
funcname, device_unit(sc->sc_dev), header);
n += vsnprintf(buf + n, sizeof(buf) - n, fmt, ap);
/*
* Default hardware blocksize in msec.
*
* We use 10 msec for most modern platforms. This period is good enough to
* play audio and video synchronizely.
* In contrast, for very old platforms, this is usually too short and too
* severe. Also such platforms usually can not play video confortably, so
* it's not so important to make the blocksize shorter. If the platform
* defines its own value as __AUDIO_BLK_MS in its <machine/param.h>, it
* uses this instead.
*
* In either case, you can overwrite AUDIO_BLK_MS by your kernel
* configuration file if you wish.
*/
#if !defined(AUDIO_BLK_MS)
# if defined(__AUDIO_BLK_MS)
# define AUDIO_BLK_MS __AUDIO_BLK_MS
# else
# define AUDIO_BLK_MS (10)
# endif
#endif
/* Device timeout in msec */
#define AUDIO_TIMEOUT (3000)
/*
* Returns encoding name corresponding to AUDIO_ENCODING_*.
* Note that it may return a local buffer because it is mainly for debugging.
*/
const char *
audio_encoding_name(int encoding)
{
static char buf[16];
/*
* Init track mixers. If at least one direction is available on
* attach time, we assume a success.
*/
error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
if (sc->sc_pmixer == NULL && sc->sc_rmixer == NULL) {
aprint_error_dev(self,
"audio_mixers_init failed: errno=%d\n", error);
goto bad;
}
/*
* Initialize hardware mixer.
* This function is called from audioattach().
*/
static void
mixer_init(struct audio_softc *sc)
{
mixer_devinfo_t mi;
int iclass, mclass, oclass, rclass;
int record_master_found, record_source_found;
iclass = mclass = oclass = rclass = -1;
sc->sc_inports.index = -1;
sc->sc_inports.master = -1;
sc->sc_inports.nports = 0;
sc->sc_inports.isenum = false;
sc->sc_inports.allports = 0;
sc->sc_inports.isdual = false;
sc->sc_inports.mixerout = -1;
sc->sc_inports.cur_port = -1;
sc->sc_outports.index = -1;
sc->sc_outports.master = -1;
sc->sc_outports.nports = 0;
sc->sc_outports.isenum = false;
sc->sc_outports.allports = 0;
sc->sc_outports.isdual = false;
sc->sc_outports.mixerout = -1;
sc->sc_outports.cur_port = -1;
sc->sc_monitor_port = -1;
/*
* Read through the underlying driver's list, picking out the class
* names from the mixer descriptions. We'll need them to decode the
* mixer descriptions on the next pass through the loop.
*/
mutex_enter(sc->sc_lock);
for(mi.index = 0; ; mi.index++) {
if (audio_query_devinfo(sc, &mi) != 0)
break;
/*
* The type of AUDIO_MIXER_CLASS merely introduces a class.
* All the other types describe an actual mixer.
*/
if (mi.type == AUDIO_MIXER_CLASS) {
if (strcmp(mi.label.name, AudioCinputs) == 0)
iclass = mi.mixer_class;
if (strcmp(mi.label.name, AudioCmonitor) == 0)
mclass = mi.mixer_class;
if (strcmp(mi.label.name, AudioCoutputs) == 0)
oclass = mi.mixer_class;
if (strcmp(mi.label.name, AudioCrecord) == 0)
rclass = mi.mixer_class;
}
}
mutex_exit(sc->sc_lock);
/*
* This is where we assign each control in the "audio" model, to the
* underlying "mixer" control. We walk through the whole list once,
* assigning likely candidates as we come across them.
*/
record_master_found = 0;
record_source_found = 0;
mutex_enter(sc->sc_lock);
for(mi.index = 0; ; mi.index++) {
if (audio_query_devinfo(sc, &mi) != 0)
break;
KASSERT(mi.index < sc->sc_nmixer_states);
if (mi.type == AUDIO_MIXER_CLASS)
continue;
if (mi.mixer_class == iclass) {
/*
* AudioCinputs is only a fallback, when we don't
* find what we're looking for in AudioCrecord, so
* check the flags before accepting one of these.
*/
if (strcmp(mi.label.name, AudioNmaster) == 0
&& record_master_found == 0)
sc->sc_inports.master = mi.index;
if (strcmp(mi.label.name, AudioNsource) == 0
&& record_source_found == 0) {
if (mi.type == AUDIO_MIXER_ENUM) {
int i;
for(i = 0; i < mi.un.e.num_mem; i++)
if (strcmp(mi.un.e.member[i].label.name,
AudioNmixerout) == 0)
sc->sc_inports.mixerout =
mi.un.e.member[i].ord;
}
au_setup_ports(sc, &sc->sc_inports, &mi,
itable);
}
if (strcmp(mi.label.name, AudioNdac) == 0 &&
sc->sc_outports.master == -1)
sc->sc_outports.master = mi.index;
} else if (mi.mixer_class == mclass) {
if (strcmp(mi.label.name, AudioNmonitor) == 0)
sc->sc_monitor_port = mi.index;
} else if (mi.mixer_class == oclass) {
if (strcmp(mi.label.name, AudioNmaster) == 0)
sc->sc_outports.master = mi.index;
if (strcmp(mi.label.name, AudioNselect) == 0)
au_setup_ports(sc, &sc->sc_outports, &mi,
otable);
} else if (mi.mixer_class == rclass) {
/*
* These are the preferred mixers for the audio record
* controls, so set the flags here, but don't check.
*/
if (strcmp(mi.label.name, AudioNmaster) == 0) {
sc->sc_inports.master = mi.index;
record_master_found = 1;
}
#if 1 /* Deprecated. Use AudioNmaster. */
if (strcmp(mi.label.name, AudioNrecord) == 0) {
sc->sc_inports.master = mi.index;
record_master_found = 1;
}
if (strcmp(mi.label.name, AudioNvolume) == 0) {
sc->sc_inports.master = mi.index;
record_master_found = 1;
}
#endif
if (strcmp(mi.label.name, AudioNsource) == 0) {
if (mi.type == AUDIO_MIXER_ENUM) {
int i;
for(i = 0; i < mi.un.e.num_mem; i++)
if (strcmp(mi.un.e.member[i].label.name,
AudioNmixerout) == 0)
sc->sc_inports.mixerout =
mi.un.e.member[i].ord;
}
au_setup_ports(sc, &sc->sc_inports, &mi,
itable);
record_source_found = 1;
}
}
}
mutex_exit(sc->sc_lock);
}
/* device is not initialized */
if (sc->hw_if == NULL)
return 0;
/* Start draining existing accessors of the device. */
error = config_detach_children(self, flags);
if (error)
return error;
/*
* Prevent new opens and wait for existing opens to complete.
*
* At the moment there are only four bits in the minor for the
* unit number, so we only revoke if the unit number could be
* used in a device node.
*
* XXX If we want more audio units, we need to encode them
* more elaborately in the minor space.
*/
maj = cdevsw_lookup_major(&audio_cdevsw);
mn = device_unit(self);
if (mn <= 0xf) {
vdevgone(maj, mn|SOUND_DEVICE, mn|SOUND_DEVICE, VCHR);
vdevgone(maj, mn|AUDIO_DEVICE, mn|AUDIO_DEVICE, VCHR);
vdevgone(maj, mn|AUDIOCTL_DEVICE, mn|AUDIOCTL_DEVICE, VCHR);
vdevgone(maj, mn|MIXER_DEVICE, mn|MIXER_DEVICE, VCHR);
}
/*
* This waits currently running sysctls to finish if exists.
* After this, no more new sysctls will come.
*/
sysctl_teardown(&sc->sc_log);
mutex_enter(sc->sc_lock);
sc->sc_dying = true;
cv_broadcast(&sc->sc_exlockcv);
if (sc->sc_pmixer)
cv_broadcast(&sc->sc_pmixer->outcv);
if (sc->sc_rmixer)
cv_broadcast(&sc->sc_rmixer->outcv);
/*
* Wait for existing users to drain.
* - pserialize_perform waits for all pserialize_read sections on
* all CPUs; after this, no more new psref_acquire can happen.
* - psref_target_destroy waits for all extant acquired psrefs to
* be psref_released.
*/
pserialize_perform(sc->sc_psz);
psref_target_destroy(&sc->sc_psref, audio_psref_class);
/*
* We are now guaranteed that there are no calls to audio fileops
* that hold sc, and any new calls with files that were for sc will
* fail. Thus, we now have exclusive access to the softc.
*/
sc->sc_exlock = 1;
/*
* Clean up all open instances.
*/
mutex_enter(sc->sc_lock);
while ((file = SLIST_FIRST(&sc->sc_files)) != NULL) {
mutex_enter(sc->sc_intr_lock);
SLIST_REMOVE_HEAD(&sc->sc_files, entry);
mutex_exit(sc->sc_intr_lock);
if (file->ptrack || file->rtrack) {
mutex_exit(sc->sc_lock);
audio_unlink(sc, file);
mutex_enter(sc->sc_lock);
}
}
mutex_exit(sc->sc_lock);
/*
* Called from hardware driver. This is where the MI audio driver gets
* probed/attached to the hardware driver.
*/
device_t
audio_attach_mi(const struct audio_hw_if *ahwp, void *hdlp, device_t dev)
{
struct audio_attach_args arg;
/*
* audio_printf() outputs fmt... with the audio device name and MD device
* name prefixed. If the message is considered to be related to the MD
* driver, use this one instead of device_printf().
*/
static void
audio_printf(struct audio_softc *sc, const char *fmt, ...)
{
va_list ap;
/*
* Enter critical section and also keep sc_lock.
* If successful, returns 0 with sc_lock held. Otherwise returns errno.
* Must be called without sc_lock held.
*/
static int
audio_exlock_mutex_enter(struct audio_softc *sc)
{
int error;
mutex_enter(sc->sc_lock);
if (sc->sc_dying) {
mutex_exit(sc->sc_lock);
return EIO;
}
while (__predict_false(sc->sc_exlock != 0)) {
error = cv_wait_sig(&sc->sc_exlockcv, sc->sc_lock);
if (sc->sc_dying)
error = EIO;
if (error) {
mutex_exit(sc->sc_lock);
return error;
}
}
/* Acquire */
sc->sc_exlock = 1;
return 0;
}
/*
* Exit critical section and exit sc_lock.
* Must be called with sc_lock held.
*/
static void
audio_exlock_mutex_exit(struct audio_softc *sc)
{
/*
* Enter critical section.
* If successful, it returns 0. Otherwise returns errno.
* Must be called without sc_lock held.
* This function returns without sc_lock held.
*/
static int
audio_exlock_enter(struct audio_softc *sc)
{
int error;
/*
* Get sc from file, and increment reference counter for this sc.
* This is intended to be used for methods other than open.
* If successful, returns sc. Otherwise returns NULL.
*/
struct audio_softc *
audio_sc_acquire_fromfile(audio_file_t *file, struct psref *refp)
{
int s;
bool dying;
/* Block audiodetach while we acquire a reference */
s = pserialize_read_enter();
/* If close or audiodetach already ran, tough -- no more audio */
dying = atomic_load_relaxed(&file->dying);
if (dying) {
pserialize_read_exit(s);
return NULL;
}
/* Acquire a reference */
psref_acquire(refp, &file->sc->sc_psref, audio_psref_class);
/* Now sc won't go away until we drop the reference count */
pserialize_read_exit(s);
return file->sc;
}
/*
* Decrement reference counter for this sc.
*/
void
audio_sc_release(struct audio_softc *sc, struct psref *refp)
{
/*
* Wait for I/O to complete, releasing sc_lock.
* Must be called with sc_lock held.
*/
static int
audio_track_waitio(struct audio_softc *sc, audio_track_t *track,
const char *mess)
{
int error;
/* Wait for pending I/O to complete. */
error = cv_timedwait_sig(&track->mixer->outcv, sc->sc_lock,
mstohz(AUDIO_TIMEOUT));
if (sc->sc_suspending) {
/* If it's about to suspend, ignore timeout error. */
if (error == EWOULDBLOCK) {
TRACET(2, track, "timeout (suspending)");
return 0;
}
}
if (sc->sc_dying) {
error = EIO;
}
if (error) {
TRACET(2, track, "cv_timedwait_sig failed %d", error);
if (error == EWOULDBLOCK) {
audio_ring_t *usrbuf = &track->usrbuf;
audio_ring_t *outbuf = &track->outbuf;
audio_printf(sc,
"%s: device timeout, seq=%d, usrbuf=%d/H%d, outbuf=%d/%d\n",
mess, (int)track->seq,
usrbuf->used, track->usrbuf_usedhigh,
outbuf->used, outbuf->capacity);
}
} else {
TRACET(3, track, "wakeup");
}
return error;
}
/*
* Try to acquire track lock.
* It doesn't block if the track lock is already acquired.
* Returns true if the track lock was acquired, or false if the track
* lock was already acquired.
*/
static __inline bool
audio_track_lock_tryenter(audio_track_t *track)
{
static int
audioopen(dev_t dev, int flags, int ifmt, struct lwp *l)
{
struct audio_softc *sc;
int error;
/*
* Find the device. Because we wired the cdevsw to the audio
* autoconf instance, the system ensures it will not go away
* until after we return.
*/
sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
if (sc == NULL || sc->hw_if == NULL)
return ENXIO;
error = audio_exlock_enter(sc);
if (error)
return error;
static int
audioclose(struct file *fp)
{
struct audio_softc *sc;
struct psref sc_ref;
audio_file_t *file;
int bound;
int error;
dev_t dev;
KASSERT(fp->f_audioctx);
file = fp->f_audioctx;
dev = file->dev;
error = 0;
/*
* audioclose() must
* - unplug track from the trackmixer (and unplug anything from softc),
* if sc exists.
* - free all memory objects, regardless of sc.
*/
static int
audiommap(struct file *fp, off_t *offp, size_t len, int prot, int *flagsp,
int *advicep, struct uvm_object **uobjp, int *maxprotp)
{
struct audio_softc *sc;
struct psref sc_ref;
audio_file_t *file;
dev_t dev;
int bound;
int error;
KASSERT(len > 0);
KASSERT(fp->f_audioctx);
file = fp->f_audioctx;
dev = file->dev;
/*
* Open for audiobell.
* It stores allocated file to *filep.
* If successful returns 0, otherwise errno.
*/
int
audiobellopen(dev_t dev, audio_file_t **filep)
{
device_t audiodev = NULL;
struct audio_softc *sc;
bool exlock = false;
int error;
/*
* Find the autoconf instance and make sure it doesn't go away
* while we are opening it.
*/
audiodev = device_lookup_acquire(&audio_cd, AUDIOUNIT(dev));
if (audiodev == NULL) {
error = ENXIO;
goto out;
}
/* If attach failed, it's hopeless -- give up. */
sc = device_private(audiodev);
if (sc->hw_if == NULL) {
error = ENXIO;
goto out;
}
/* Take the exclusive configuration lock. */
error = audio_exlock_enter(sc);
if (error)
goto out;
exlock = true;
/* Open the audio device. */
device_active(sc->sc_dev, DVA_SYSTEM);
error = audio_open(dev, sc, FWRITE, 0, curlwp, filep);
out: if (exlock)
audio_exlock_exit(sc);
if (audiodev)
device_release(audiodev);
return error;
}
/* Close for audiobell */
int
audiobellclose(audio_file_t *file)
{
struct audio_softc *sc;
struct psref sc_ref;
int bound;
int error;
error = 0;
/*
* audiobellclose() must
* - unplug track from the trackmixer if sc exist.
* - free all memory objects, regardless of sc.
*/
bound = curlwp_bind();
sc = audio_sc_acquire_fromfile(file, &sc_ref);
if (sc) {
error = audio_close(sc, file);
audio_sc_release(sc, &sc_ref);
}
curlwp_bindx(bound);
/*
* Must be called with sc_exlock held and without sc_lock held.
*/
int
audio_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
struct lwp *l, audio_file_t **bellfile)
{
struct audio_info ai;
struct file *fp;
audio_file_t *af;
audio_ring_t *hwbuf;
bool fullduplex;
bool cred_held;
bool hw_opened;
bool rmixer_started;
bool inserted;
int fd;
int error;
/*
* On half duplex hardware,
* 1. if mode is (PLAY | REC), let mode PLAY.
* 2. if mode is PLAY, let mode PLAY if no rec tracks, otherwise error.
* 3. if mode is REC, let mode REC if no play tracks, otherwise error.
*/
if (fullduplex == false) {
if ((af->mode & AUMODE_PLAY)) {
if (sc->sc_ropens != 0) {
TRACE(1, "record track already exists");
error = ENODEV;
goto bad;
}
/* Play takes precedence */
af->mode &= ~AUMODE_RECORD;
}
if ((af->mode & AUMODE_RECORD)) {
if (sc->sc_popens != 0) {
TRACE(1, "play track already exists");
error = ENODEV;
goto bad;
}
}
}
/* Create tracks */
if ((af->mode & AUMODE_PLAY))
af->ptrack = audio_track_create(sc, sc->sc_pmixer);
if ((af->mode & AUMODE_RECORD))
af->rtrack = audio_track_create(sc, sc->sc_rmixer);
/* Set parameters */
AUDIO_INITINFO(&ai);
if (bellfile) {
/* If audiobell, only sample_rate will be set later. */
ai.play.sample_rate = audio_default.sample_rate;
ai.play.encoding = AUDIO_ENCODING_SLINEAR_NE;
ai.play.channels = 1;
ai.play.precision = 16;
ai.play.pause = 0;
} else if (ISDEVAUDIO(dev)) {
/* If /dev/audio, initialize everytime. */
ai.play.sample_rate = audio_default.sample_rate;
ai.play.encoding = audio_default.encoding;
ai.play.channels = audio_default.channels;
ai.play.precision = audio_default.precision;
ai.play.pause = 0;
ai.record.sample_rate = audio_default.sample_rate;
ai.record.encoding = audio_default.encoding;
ai.record.channels = audio_default.channels;
ai.record.precision = audio_default.precision;
ai.record.pause = 0;
} else {
/* If /dev/sound, take over the previous parameters. */
ai.play.sample_rate = sc->sc_sound_pparams.sample_rate;
ai.play.encoding = sc->sc_sound_pparams.encoding;
ai.play.channels = sc->sc_sound_pparams.channels;
ai.play.precision = sc->sc_sound_pparams.precision;
ai.play.pause = sc->sc_sound_ppause;
ai.record.sample_rate = sc->sc_sound_rparams.sample_rate;
ai.record.encoding = sc->sc_sound_rparams.encoding;
ai.record.channels = sc->sc_sound_rparams.channels;
ai.record.precision = sc->sc_sound_rparams.precision;
ai.record.pause = sc->sc_sound_rpause;
}
error = audio_file_setinfo(sc, af, &ai);
if (error)
goto bad;
if (sc->sc_popens + sc->sc_ropens == 0) {
/* First open */
/*
* Call hw_if->open() only at first open of
* combination of playback and recording.
* On full duplex hardware, the flags passed to
* hw_if->open() is always (FREAD | FWRITE)
* regardless of this open()'s flags.
* see also dev/isa/aria.c
* On half duplex hardware, the flags passed to
* hw_if->open() is either FREAD or FWRITE.
* see also arch/evbarm/mini2440/audio_mini2440.c
*/
if (fullduplex) {
hwflags = FREAD | FWRITE;
} else {
/* Construct hwflags from af->mode. */
hwflags = 0;
if ((af->mode & AUMODE_PLAY) != 0)
hwflags |= FWRITE;
if ((af->mode & AUMODE_RECORD) != 0)
hwflags |= FREAD;
}
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
error = sc->hw_if->open(sc->hw_hdl, hwflags);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
if (error)
goto bad;
}
/*
* Regardless of whether we called hw_if->open (whether
* hw_if->open exists) or not, we move to the Opened phase
* here. Therefore from this point, we have to call
* hw_if->close (if exists) whenever abort.
* Note that both of hw_if->{open,close} are optional.
*/
hw_opened = true;
/*
* Set speaker mode when a half duplex.
* XXX I'm not sure this is correct.
*/
if (1/*XXX*/) {
if (sc->hw_if->speaker_ctl) {
int on;
if (af->ptrack) {
on = 1;
} else {
on = 0;
}
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
error = sc->hw_if->speaker_ctl(sc->hw_hdl, on);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
if (error)
goto bad;
}
}
} else if (sc->sc_multiuser == false) {
uid_t euid = kauth_cred_geteuid(kauth_cred_get());
if (euid != 0 && euid != kauth_cred_geteuid(sc->sc_cred)) {
error = EPERM;
goto bad;
}
}
/* Call init_output if this is the first playback open. */
if (af->ptrack && sc->sc_popens == 0) {
if (sc->hw_if->init_output) {
hwbuf = &sc->sc_pmixer->hwbuf;
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
error = sc->hw_if->init_output(sc->hw_hdl,
hwbuf->mem,
hwbuf->capacity *
hwbuf->fmt.channels * hwbuf->fmt.stride / NBBY);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
if (error)
goto bad;
}
}
/*
* Call init_input and start rmixer, if this is the first recording
* open. See pause consideration notes.
*/
if (af->rtrack && sc->sc_ropens == 0) {
if (sc->hw_if->init_input) {
hwbuf = &sc->sc_rmixer->hwbuf;
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
error = sc->hw_if->init_input(sc->hw_hdl,
hwbuf->mem,
hwbuf->capacity *
hwbuf->fmt.channels * hwbuf->fmt.stride / NBBY);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
if (error)
goto bad;
}
/*
* This is the last sc_lock section in the function, so we have to
* examine sc_dying again before starting the rest tasks. Because
* audiodeatch() may have been invoked (and it would set sc_dying)
* from the time audioopen() was executed until now. If it happens,
* audiodetach() may already have set file->dying for all sc_files
* that exist at that point, so that audioopen() must abort without
* inserting af to sc_files, in order to keep consistency.
*/
mutex_enter(sc->sc_lock);
if (sc->sc_dying) {
mutex_exit(sc->sc_lock);
error = ENXIO;
goto bad;
}
/* Count up finally */
if (af->ptrack)
sc->sc_popens++;
if (af->rtrack)
sc->sc_ropens++;
mutex_enter(sc->sc_intr_lock);
SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
inserted = true;
if (bellfile) {
*bellfile = af;
} else {
error = fd_allocfile(&fp, &fd);
if (error)
goto bad;
bad:
if (inserted) {
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
SLIST_REMOVE(&sc->sc_files, af, audio_file, entry);
mutex_exit(sc->sc_intr_lock);
if (af->ptrack)
sc->sc_popens--;
if (af->rtrack)
sc->sc_ropens--;
mutex_exit(sc->sc_lock);
}
if (rmixer_started) {
mutex_enter(sc->sc_lock);
audio_rmixer_halt(sc);
mutex_exit(sc->sc_lock);
}
if (hw_opened) {
if (sc->hw_if->close) {
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
sc->hw_if->close(sc->hw_hdl);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
}
}
if (cred_held) {
kauth_cred_free(sc->sc_cred);
}
/*
* Since track here is not yet linked to sc_files,
* you can call track_destroy() without sc_intr_lock.
*/
if (af->rtrack) {
audio_track_destroy(af->rtrack);
af->rtrack = NULL;
}
if (af->ptrack) {
audio_track_destroy(af->ptrack);
af->ptrack = NULL;
}
kmem_free(af, sizeof(*af));
return error;
}
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
audio_close(struct audio_softc *sc, audio_file_t *file)
{
int error;
/*
* Drain first.
* It must be done before unlinking(acquiring exlock).
*/
if (file->ptrack) {
mutex_enter(sc->sc_lock);
audio_track_drain(sc, file->ptrack);
mutex_exit(sc->sc_lock);
}
error = audio_exlock_enter(sc);
if (error) {
/*
* If EIO, this sc is about to detach. In this case, even if
* we don't do subsequent _unlink(), audiodetach() will do it.
*/
if (error == EIO)
return error;
/* XXX This should not happen but what should I do ? */
panic("%s: can't acquire exlock: errno=%d", __func__, error);
}
audio_unlink(sc, file);
audio_exlock_exit(sc);
return 0;
}
/*
* Unlink this file, but not freeing memory here.
* Must be called with sc_exlock held and without sc_lock held.
*/
static void
audio_unlink(struct audio_softc *sc, audio_file_t *file)
{
kauth_cred_t cred = NULL;
int error;
if (file->ptrack) {
TRACET(3, file->ptrack, "dropframes=%" PRIu64,
file->ptrack->dropframes);
KASSERT(sc->sc_popens > 0);
sc->sc_popens--;
/* Call hw halt_output if this is the last playback track. */
if (sc->sc_popens == 0 && sc->sc_pbusy) {
error = audio_pmixer_halt(sc);
if (error) {
audio_printf(sc,
"halt_output failed: errno=%d (ignored)\n",
error);
}
}
/* Restore mixing volume if all tracks are gone. */
if (sc->sc_popens == 0) {
/* intr_lock is not necessary, but just manners. */
mutex_enter(sc->sc_intr_lock);
sc->sc_pmixer->volume = 256;
sc->sc_pmixer->voltimer = 0;
mutex_exit(sc->sc_intr_lock);
}
}
if (file->rtrack) {
TRACET(3, file->rtrack, "dropframes=%" PRIu64,
file->rtrack->dropframes);
KASSERT(sc->sc_ropens > 0);
sc->sc_ropens--;
/* Call hw halt_input if this is the last recording track. */
if (sc->sc_ropens == 0 && sc->sc_rbusy) {
error = audio_rmixer_halt(sc);
if (error) {
audio_printf(sc,
"halt_input failed: errno=%d (ignored)\n",
error);
}
}
}
/* Call hw close if this is the last track. */
if (sc->sc_popens + sc->sc_ropens == 0) {
if (sc->hw_if->close) {
TRACE(2, "hw_if close");
mutex_enter(sc->sc_intr_lock);
sc->hw_if->close(sc->hw_hdl);
mutex_exit(sc->sc_intr_lock);
}
cred = sc->sc_cred;
sc->sc_cred = NULL;
}
mutex_exit(sc->sc_lock);
if (cred)
kauth_cred_free(cred);
TRACE(3, "done");
}
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
audio_read(struct audio_softc *sc, struct uio *uio, int ioflag,
audio_file_t *file)
{
audio_track_t *track;
audio_ring_t *usrbuf;
audio_ring_t *input;
int error;
/*
* On half-duplex hardware, O_RDWR is treated as O_WRONLY.
* However read() system call itself can be called because it's
* opened with O_RDWR. So in this case, deny this read().
*/
track = file->rtrack;
if (track == NULL) {
return EBADF;
}
/* I think it's better than EINVAL. */
if (track->mmapped)
return EPERM;
if (file->ptrack)
audio_track_clear(sc, file->ptrack);
if (file->rtrack)
audio_track_clear(sc, file->rtrack);
}
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
audio_write(struct audio_softc *sc, struct uio *uio, int ioflag,
audio_file_t *file)
{
audio_track_t *track;
audio_ring_t *usrbuf;
audio_ring_t *outbuf;
int error;
track = file->ptrack;
if (track == NULL)
return EPERM;
/* I think it's better than EINVAL. */
if (track->mmapped)
return EPERM;
/* uiomove to usrbuf as many bytes as possible. */
bytes = uimin(track->usrbuf_usedhigh - usrbuf->used,
uio->uio_resid);
while (bytes > 0) {
int tail = auring_tail(usrbuf);
int len = uimin(bytes, usrbuf->capacity - tail);
error = uiomove((uint8_t *)usrbuf->mem + tail, len,
uio);
if (error) {
audio_track_lock_exit(track);
device_printf(sc->sc_dev,
"%s: uiomove(%d) failed: errno=%d\n",
__func__, len, error);
goto abort;
}
auring_push(usrbuf, len);
TRACET(3, track, "uiomove(len=%d) usrbuf=%d/%d/C%d",
len,
usrbuf->head, usrbuf->used, usrbuf->capacity);
bytes -= len;
}
/* Convert them as many blocks as possible. */
while (usrbuf->used >= track->usrbuf_blksize &&
outbuf->used < outbuf->capacity) {
audio_track_play(track);
}
error = 0;
switch (cmd) {
case FIONBIO:
/* All handled in the upper FS layer. */
break;
case FIONREAD:
/* Get the number of bytes that can be read. */
track = file->rtrack;
if (track) {
val = audio_track_readablebytes(track);
*(int *)addr = val;
TRACET(2, track, "pid=%d.%d FIONREAD bytes=%d",
(int)curproc->p_pid, (int)l->l_lid, val);
} else {
TRACEF(2, file, "pid=%d.%d FIONREAD no track",
(int)curproc->p_pid, (int)l->l_lid);
}
break;
case AUDIO_FLUSH:
/* XXX TODO: clear errors and restart? */
TRACEF(2, file, "%s", pre);
audio_file_clear(sc, file);
break;
case AUDIO_PERROR:
case AUDIO_RERROR:
/*
* Number of dropped bytes during playback/record. We don't
* know where or when they were dropped (including conversion
* stage). Therefore, the number of accurate bytes or samples
* is also unknown.
*/
track = (cmd == AUDIO_PERROR) ? file->ptrack : file->rtrack;
if (track) {
val = frametobyte(&track->usrbuf.fmt,
track->dropframes);
*(int *)addr = val;
TRACET(2, track, "%s bytes=%d", pre, val);
} else {
TRACEF(2, file, "%s no track", pre);
}
break;
case AUDIO_GETIOFFS:
ao = (struct audio_offset *)addr;
track = file->rtrack;
if (track == NULL) {
ao->samples = 0;
ao->deltablks = 0;
ao->offset = 0;
TRACEF(2, file, "%s no rtrack", pre);
break;
}
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
/* figure out where next transfer will start */
stamp = track->stamp;
offset = auring_tail(track->input);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
/* samples will overflow soon but is as per spec. */
ao->samples = stamp * track->usrbuf_blksize;
ao->deltablks = stamp - track->last_stamp;
ao->offset = audio_track_inputblk_as_usrbyte(track, offset);
TRACET(2, track, "%s samples=%u deltablks=%u offset=%u",
pre, ao->samples, ao->deltablks, ao->offset);
track->last_stamp = stamp;
break;
case AUDIO_GETOOFFS:
ao = (struct audio_offset *)addr;
track = file->ptrack;
if (track == NULL) {
ao->samples = 0;
ao->deltablks = 0;
ao->offset = 0;
TRACEF(2, file, "%s no ptrack", pre);
break;
}
mutex_enter(sc->sc_lock);
mutex_enter(sc->sc_intr_lock);
/* figure out where next transfer will start */
stamp = track->stamp;
offset = track->usrbuf.head;
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
/* samples will overflow soon but is as per spec. */
ao->samples = stamp * track->usrbuf_blksize;
ao->deltablks = stamp - track->last_stamp;
ao->offset = offset;
TRACET(2, track, "%s samples=%u deltablks=%u offset=%u",
pre, ao->samples, ao->deltablks, ao->offset);
track->last_stamp = stamp;
break;
case AUDIO_WSEEK:
track = file->ptrack;
if (track) {
val = track->usrbuf.used;
*(u_long *)addr = val;
TRACET(2, track, "%s bytes=%d", pre, val);
} else {
TRACEF(2, file, "%s no ptrack", pre);
}
break;
case AUDIO_SETINFO:
TRACEF(2, file, "%s", pre);
error = audio_exlock_enter(sc);
if (error)
break;
error = audio_file_setinfo(sc, file, (struct audio_info *)addr);
if (error) {
audio_exlock_exit(sc);
break;
}
if (ISDEVSOUND(dev))
error = audiogetinfo(sc, &sc->sc_ai, 0, file);
audio_exlock_exit(sc);
break;
case AUDIO_GETENC:
ae = (audio_encoding_t *)addr;
index = ae->index;
TRACEF(2, file, "%s index=%d", pre, index);
if (index < 0 || index >= __arraycount(audio_encodings)) {
error = EINVAL;
break;
}
*ae = audio_encodings[index];
ae->index = index;
/*
* EMULATED always.
* EMULATED flag at that time used to mean that it could
* not be passed directly to the hardware as-is. But
* currently, all formats including hardware native is not
* passed directly to the hardware. So I set EMULATED
* flag for all formats.
*/
ae->flags = AUDIO_ENCODINGFLAG_EMULATED;
break;
case AUDIO_GETFD:
/*
* Returns the current setting of full duplex mode.
* If HW has full duplex mode and there are two mixers,
* it is full duplex. Otherwise half duplex.
*/
error = audio_exlock_enter(sc);
if (error)
break;
val = (sc->sc_props & AUDIO_PROP_FULLDUPLEX)
&& (sc->sc_pmixer && sc->sc_rmixer);
audio_exlock_exit(sc);
*(int *)addr = val;
TRACEF(2, file, "%s fulldup=%d", pre, val);
break;
/*
* Convert n [frames] of the input buffer to bytes in the usrbuf format.
* n is in frames but should be a multiple of frame/block. Note that the
* usrbuf's frame/block and the input buffer's frame/block may be different
* (i.e., if frequencies are different).
*
* This function is for recording track only.
*/
static int
audio_track_inputblk_as_usrbyte(const audio_track_t *track, int n)
{
int input_fpb;
/*
* In the input buffer on recording track, these are the same.
* input_fpb = frame_per_block(track->mixer, &track->input->fmt);
*/
input_fpb = track->mixer->frames_per_block;
return (n / input_fpb) * track->usrbuf_blksize;
}
/*
* Returns the number of bytes that can be read on recording buffer.
*/
static int
audio_track_readablebytes(const audio_track_t *track)
{
int bytes;
/*
* For recording, track->input is the main block-unit buffer and
* track->usrbuf holds less than one block of byte data ("fragment").
* Note that the input buffer is in frames and the usrbuf is in bytes.
*
* Actual total capacity of these two buffers is
* input->capacity [frames] + usrbuf.capacity [bytes],
* but only input->capacity is reported to userland as buffer_size.
* So, even if the total used bytes exceed input->capacity, report it
* as input->capacity for consistency.
*/
bytes = audio_track_inputblk_as_usrbyte(track, track->input->used);
if (track->input->used < track->input->capacity) {
bytes += track->usrbuf.used;
}
return bytes;
}
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
audio_poll(struct audio_softc *sc, int events, struct lwp *l,
audio_file_t *file)
{
audio_track_t *track;
int revents;
bool in_is_valid;
bool out_is_valid;
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
audio_kqfilter(struct audio_softc *sc, audio_file_t *file, struct knote *kn)
{
struct selinfo *sip;
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
audio_mmap(struct audio_softc *sc, off_t *offp, size_t len, int prot,
int *flagsp, int *advicep, struct uvm_object **uobjp, int *maxprotp,
audio_file_t *file)
{
audio_track_t *track;
struct uvm_object *uobj;
vaddr_t vstart;
vsize_t vsize;
int error;
#if 0
/* XXX
* The idea here was to use the protection to determine if
* we are mapping the read or write buffer, but it fails.
* The VM system is broken in (at least) two ways.
* 1) If you map memory VM_PROT_WRITE you SIGSEGV
* when writing to it, so VM_PROT_READ|VM_PROT_WRITE
* has to be used for mmapping the play buffer.
* 2) Even if calling mmap() with VM_PROT_READ|VM_PROT_WRITE
* audio_mmap will get called at some point with VM_PROT_READ
* only.
* So, alas, we always map the play buffer for now.
*/
if (prot == (VM_PROT_READ|VM_PROT_WRITE) ||
prot == VM_PROT_WRITE)
track = file->ptrack;
else if (prot == VM_PROT_READ)
track = file->rtrack;
else
return EINVAL;
#else
track = file->ptrack;
#endif
if (track == NULL)
return EACCES;
/* XXX TODO: what happens when mmap twice. */
if (track->mmapped)
return EIO;
/* Create a uvm anonymous object */
vsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE), PAGE_SIZE);
if (*offp + len > vsize)
return EOVERFLOW;
uobj = uao_create(vsize, 0);
/* Map it into the kernel virtual address space */
vstart = 0;
error = uvm_map(kernel_map, &vstart, vsize, uobj, 0, 0,
UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW, UVM_INH_NONE,
UVM_ADV_RANDOM, 0));
if (error) {
device_printf(sc->sc_dev, "uvm_map failed: errno=%d\n", error);
uao_detach(uobj); /* release reference */
return error;
}
error = audio_exlock_mutex_enter(sc);
if (error)
goto abort;
/*
* mmap() will start playing immediately. XXX Maybe we lack API...
* If no one has played yet, start pmixer here.
*/
if (sc->sc_pbusy == false)
audio_pmixer_start(sc, true);
audio_exlock_mutex_exit(sc);
/* Finally, replace the usrbuf from kmem to uvm. */
audio_track_lock_enter(track);
kmem_free(track->usrbuf.mem, track->usrbuf_allocsize);
track->usrbuf.mem = (void *)vstart;
track->usrbuf_allocsize = vsize;
memset(track->usrbuf.mem, 0, vsize);
track->mmapped = true;
audio_track_lock_exit(track);
/* Acquire a reference for the mmap. munmap will release. */
uao_reference(uobj);
*uobjp = uobj;
*maxprotp = prot;
*advicep = UVM_ADV_RANDOM;
*flagsp = MAP_SHARED;
/*
* /dev/audioctl has to be able to open at any time without interference
* with any /dev/audio or /dev/sound.
* Must be called with sc_exlock held and without sc_lock held.
*/
static int
audioctl_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
struct lwp *l)
{
struct file *fp;
audio_file_t *af;
int fd;
int error;
KASSERT(sc->sc_exlock);
TRACE(1, "called");
error = fd_allocfile(&fp, &fd);
if (error)
return error;
af = kmem_zalloc(sizeof(*af), KM_SLEEP);
af->sc = sc;
af->dev = dev;
mutex_enter(sc->sc_lock);
if (sc->sc_dying) {
mutex_exit(sc->sc_lock);
kmem_free(af, sizeof(*af));
fd_abort(curproc, fp, fd);
return ENXIO;
}
mutex_enter(sc->sc_intr_lock);
SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
/*
* Free 'mem' if available, and initialize the pointer.
* For this reason, this is implemented as macro.
*/
#define audio_free(mem) do { \
if (mem != NULL) { \
kern_free(mem); \
mem = NULL; \
} \
} while (0)
/*
* (Re)allocate 'memblock' with specified 'bytes'.
* bytes must not be 0.
* This function never returns NULL.
*/
static void *
audio_realloc(void *memblock, size_t bytes)
{
KASSERT(bytes != 0);
if (memblock)
kern_free(memblock);
return kern_malloc(bytes, M_WAITOK);
}
if (track->usrbuf_allocsize != 0) {
if (track->mmapped) {
/*
* Unmap the kernel mapping. uvm_unmap releases the
* reference to the uvm object, and this should be the
* last virtual mapping of the uvm object, so no need
* to explicitly release (`detach') the object.
*/
vstart = (vaddr_t)track->usrbuf.mem;
vsize = track->usrbuf_allocsize;
uvm_unmap(kernel_map, vstart, vstart + vsize);
track->mmapped = false;
} else {
kmem_free(track->usrbuf.mem, track->usrbuf_allocsize);
}
}
track->usrbuf.mem = NULL;
track->usrbuf.capacity = 0;
track->usrbuf_allocsize = 0;
}
/*
* This filter changes the volume for each channel.
* arg->context points track->ch_volume[].
*/
static void
audio_track_chvol(audio_filter_arg_t *arg)
{
int16_t *ch_volume;
const aint_t *s;
aint_t *d;
u_int i;
u_int ch;
u_int channels;
s = arg->src;
d = arg->dst;
ch_volume = arg->context;
channels = arg->srcfmt->channels;
for (i = 0; i < arg->count; i++) {
for (ch = 0; ch < channels; ch++) {
aint2_t val;
val = *s++;
val = AUDIO_SCALEDOWN(val * ch_volume[ch], 8);
*d++ = (aint_t)val;
}
}
}
/*
* This filter performs conversion from stereo (or more channels) to mono.
*/
static void
audio_track_chmix_mixLR(audio_filter_arg_t *arg)
{
const aint_t *s;
aint_t *d;
u_int i;
DIAGNOSTIC_filter_arg(arg);
s = arg->src;
d = arg->dst;
for (i = 0; i < arg->count; i++) {
*d++ = AUDIO_SCALEDOWN(s[0], 1) + AUDIO_SCALEDOWN(s[1], 1);
s += arg->srcfmt->channels;
}
}
/*
* This filter performs conversion from mono to stereo (or more channels).
*/
static void
audio_track_chmix_dupLR(audio_filter_arg_t *arg)
{
const aint_t *s;
aint_t *d;
u_int i;
u_int ch;
u_int dstchannels;
DIAGNOSTIC_filter_arg(arg);
s = arg->src;
d = arg->dst;
dstchannels = arg->dstfmt->channels;
for (i = 0; i < arg->count; i++) {
d[0] = s[0];
d[1] = s[0];
s++;
d += dstchannels;
}
if (dstchannels > 2) {
d = arg->dst;
for (i = 0; i < arg->count; i++) {
for (ch = 2; ch < dstchannels; ch++) {
d[ch] = 0;
}
d += dstchannels;
}
}
}
/*
* This filter shrinks M channels into N channels.
* Extra channels are discarded.
*/
static void
audio_track_chmix_shrink(audio_filter_arg_t *arg)
{
const aint_t *s;
aint_t *d;
u_int i;
u_int ch;
DIAGNOSTIC_filter_arg(arg);
s = arg->src;
d = arg->dst;
for (i = 0; i < arg->count; i++) {
for (ch = 0; ch < arg->dstfmt->channels; ch++) {
*d++ = s[ch];
}
s += arg->srcfmt->channels;
}
}
/*
* This filter expands M channels into N channels.
* Silence is inserted for missing channels.
*/
static void
audio_track_chmix_expand(audio_filter_arg_t *arg)
{
const aint_t *s;
aint_t *d;
u_int i;
u_int ch;
u_int srcchannels;
u_int dstchannels;
DIAGNOSTIC_filter_arg(arg);
s = arg->src;
d = arg->dst;
srcchannels = arg->srcfmt->channels;
dstchannels = arg->dstfmt->channels;
for (i = 0; i < arg->count; i++) {
for (ch = 0; ch < srcchannels; ch++) {
*d++ = *s++;
}
for (; ch < dstchannels; ch++) {
*d++ = 0;
}
}
}
/*
* This filter performs frequency conversion (up sampling).
* It uses linear interpolation.
*/
static void
audio_track_freq_up(audio_filter_arg_t *arg)
{
audio_track_t *track;
audio_ring_t *src;
audio_ring_t *dst;
const aint_t *s;
aint_t *d;
aint_t prev[AUDIO_MAX_CHANNELS];
aint_t curr[AUDIO_MAX_CHANNELS];
aint_t grad[AUDIO_MAX_CHANNELS];
u_int i;
u_int t;
u_int step;
u_int channels;
u_int ch;
int srcused;
/*
* In order to facilitate interpolation for each block, slide (delay)
* input by one sample. As a result, strictly speaking, the output
* phase is delayed by 1/dstfreq. However, I believe there is no
* observable impact.
*
* Example)
* srcfreq:dstfreq = 1:3
*
* A - -
* |
* |
* | B - -
* +-----+-----> input timeframe
* 0 1
*
* 0 1
* +-----+-----> input timeframe
* | A
* | x x
* | x x
* x (B)
* +-+-+-+-+-+-> output timeframe
* 0 1 2 3 4 5
*/
for (i = 0; i < arg->count && t / 65536 < src->used; i++) {
const aint_t *s;
PRINTF("i=%4d t=%10d", i, t);
s = s0 + (t / 65536) * channels;
PRINTF(" s=%5ld", (s - s0) / channels);
for (ch = 0; ch < channels; ch++) {
if (ch == 0) PRINTF(" *s=%d", s[ch]);
*d++ = s[ch];
}
PRINTF("\n");
t += step;
}
t += track->freq_leap;
PRINTF("end t=%d\n", t);
auring_take(src, src->used);
auring_push(dst, i);
track->freq_current = t % 65536;
}
/*
* Creates track and returns it.
* Must be called without sc_lock held.
*/
audio_track_t *
audio_track_create(struct audio_softc *sc, audio_trackmixer_t *mixer)
{
audio_track_t *track;
static int newid = 0;
/* Do TRACE after id is assigned. */
TRACET(3, track, "for %s",
mixer->mode == AUMODE_PLAY ? "playback" : "recording");
#if defined(AUDIO_SUPPORT_TRACK_VOLUME)
track->volume = 256;
#endif
for (int i = 0; i < AUDIO_MAX_CHANNELS; i++) {
track->ch_volume[i] = 256;
}
return track;
}
/*
* Release all resources of the track and track itself.
* track must not be NULL. Don't specify the track within the file
* structure linked from sc->sc_files.
*/
static void
audio_track_destroy(audio_track_t *track)
{
/*
* It returns encoding conversion filter according to src and dst format.
* If it is not a convertible pair, it returns NULL. Either src or dst
* must be internal format.
*/
static audio_filter_t
audio_track_get_codec(audio_track_t *track, const audio_format2_t *src,
const audio_format2_t *dst)
{
if (audio_format2_is_internal(src)) {
if (dst->encoding == AUDIO_ENCODING_ULAW) {
return audio_internal_to_mulaw;
} else if (dst->encoding == AUDIO_ENCODING_ALAW) {
return audio_internal_to_alaw;
} else if (audio_format2_is_linear(dst)) {
switch (dst->stride) {
case 8:
return audio_internal_to_linear8;
case 16:
return audio_internal_to_linear16;
#if defined(AUDIO_SUPPORT_LINEAR24)
case 24:
return audio_internal_to_linear24;
#endif
case 32:
return audio_internal_to_linear32;
default:
TRACET(1, track, "unsupported %s stride %d",
"dst", dst->stride);
goto abort;
}
}
} else if (audio_format2_is_internal(dst)) {
if (src->encoding == AUDIO_ENCODING_ULAW) {
return audio_mulaw_to_internal;
} else if (src->encoding == AUDIO_ENCODING_ALAW) {
return audio_alaw_to_internal;
} else if (audio_format2_is_linear(src)) {
switch (src->stride) {
case 8:
return audio_linear8_to_internal;
case 16:
return audio_linear16_to_internal;
#if defined(AUDIO_SUPPORT_LINEAR24)
case 24:
return audio_linear24_to_internal;
#endif
case 32:
return audio_linear32_to_internal;
default:
TRACET(1, track, "unsupported %s stride %d",
"src", src->stride);
goto abort;
}
}
}
/*
* Initialize the codec stage of this track as necessary.
* If successful, it initializes the codec stage as necessary, stores updated
* last_dst in *last_dstp in any case, and returns 0.
* Otherwise, it returns errno without modifying *last_dstp.
*/
static int
audio_track_init_codec(audio_track_t *track, audio_ring_t **last_dstp)
{
audio_ring_t *last_dst;
audio_ring_t *srcbuf;
audio_format2_t *srcfmt;
audio_format2_t *dstfmt;
audio_filter_arg_t *arg;
u_int len;
int error;
/*
* Initialize the chvol stage of this track as necessary.
* If successful, it initializes the chvol stage as necessary, stores updated
* last_dst in *last_dstp in any case, and returns 0.
* Otherwise, it returns errno without modifying *last_dstp.
*/
static int
audio_track_init_chvol(audio_track_t *track, audio_ring_t **last_dstp)
{
audio_ring_t *last_dst;
audio_ring_t *srcbuf;
audio_format2_t *srcfmt;
audio_format2_t *dstfmt;
audio_filter_arg_t *arg;
u_int len;
int error;
/*
* Initialize the chmix stage of this track as necessary.
* If successful, it initializes the chmix stage as necessary, stores updated
* last_dst in *last_dstp in any case, and returns 0.
* Otherwise, it returns errno without modifying *last_dstp.
*/
static int
audio_track_init_chmix(audio_track_t *track, audio_ring_t **last_dstp)
{
audio_ring_t *last_dst;
audio_ring_t *srcbuf;
audio_format2_t *srcfmt;
audio_format2_t *dstfmt;
audio_filter_arg_t *arg;
u_int srcch;
u_int dstch;
u_int len;
int error;
srcbuf->head = 0;
srcbuf->used = 0;
/* XXX The buffer size should be able to calculate. */
srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
len = auring_bytelen(srcbuf);
srcbuf->mem = audio_realloc(srcbuf->mem, len);
/*
* Initialize the freq stage of this track as necessary.
* If successful, it initializes the freq stage as necessary, stores updated
* last_dst in *last_dstp in any case, and returns 0.
* Otherwise, it returns errno without modifying *last_dstp.
*/
static int
audio_track_init_freq(audio_track_t *track, audio_ring_t **last_dstp)
{
audio_ring_t *last_dst;
audio_ring_t *srcbuf;
audio_format2_t *srcfmt;
audio_format2_t *dstfmt;
audio_filter_arg_t *arg;
uint32_t srcfreq;
uint32_t dstfreq;
u_int dst_capacity;
u_int mod;
u_int len;
int error;
if (track->freq_step < 65536) {
track->freq.filter = audio_track_freq_up;
/* In order to carry at the first time. */
track->freq_current = 65536;
} else {
track->freq.filter = audio_track_freq_down;
track->freq_current = 0;
}
/*
* There are two unit of buffers; A block buffer and a byte buffer. Both use
* audio_ring_t. Internally, audio data is always handled in block unit.
* Converting format, sythesizing tracks, transferring from/to the hardware,
* and etc. Only one exception is usrbuf. To transfer with userland, usrbuf
* is buffered in byte unit.
* For playing back, write(2) writes arbitrary length of data to usrbuf.
* When one block is filled, it is sent to the next stage (converting and/or
* synthesizing).
* For recording, the rmixer writes one block length of data to input buffer
* (the bottom stage buffer) each time. read(2) (converts one block if usrbuf
* is empty and then) reads arbitrary length of data from usrbuf.
*
* The following charts show the data flow and buffer types for playback and
* recording track. In this example, both have two conversion stages, codec
* and freq. Every [**] represents a buffer described below.
*
* On playback track:
*
* write(2)
* |
* | uiomove
* v
* usrbuf [BB|BB ... BB|BB] .. Byte ring buffer
* |
* | memcpy one block
* v
* codec.srcbuf [FF] .. 1 block (ring) buffer
* .dst ----+
* |
* | convert
* v
* freq.srcbuf [FF] .. 1 block (ring) buffer
* .dst ----+
* |
* | convert
* v
* outbuf [FF|FF|FF|FF] .. NBLKOUT blocks ring buffer
* |
* v
* pmixer
*
* There are three different types of buffers:
*
* [BB|BB ... BB|BB] usrbuf. Is the buffer closest to userland. Mandatory.
* This is a byte buffer and its length is basically less
* than or equal to 64KB or at least AUMINNOBLK blocks.
*
* [FF] Interim conversion stage's srcbuf if necessary.
* This is one block (ring) buffer counted in frames.
*
* [FF|FF|FF|FF] outbuf. Is the buffer closest to pmixer. Mandatory.
* This is NBLKOUT blocks ring buffer counted in frames.
*
*
* On recording track:
*
* read(2)
* ^
* | uiomove
* |
* usrbuf [BB] .. Byte (ring) buffer
* ^
* | memcpy one block
* |
* outbuf [FF] .. 1 block (ring) buffer
* ^
* | convert
* |
* codec.dst ----+
* .srcbuf [FF] .. 1 block (ring) buffer
* ^
* | convert
* |
* freq.dst ----+
* .srcbuf [FF|FF ... FF|FF] .. NBLKIN blocks ring buffer
* ^
* |
* rmixer
*
* There are also three different types of buffers.
*
* [BB] usrbuf. Is the buffer closest to userland. Mandatory.
* This is a byte buffer and its length is one block.
* This buffer holds only "fragment".
*
* [FF] Interim conversion stage's srcbuf (or outbuf).
* This is one block (ring) buffer counted in frames.
*
* [FF|FF ... FF|FF] The bottom conversion stage's srcbuf (or outbuf).
* This is the buffer closest to rmixer, and mandatory.
* This is NBLKIN blocks ring buffer counted in frames.
* Also pointed by *input.
*/
/*
* Set the userland format of this track.
* usrfmt argument should have been previously verified by
* audio_track_setinfo_check().
* This function may release and reallocate all internal conversion buffers.
* It returns 0 if successful. Otherwise it returns errno with clearing all
* internal buffers.
* It must be called without sc_intr_lock since uvm_* routines require non
* intr_lock state.
* It must be called with track lock held since it may release and reallocate
* outbuf.
*/
static int
audio_track_set_format(audio_track_t *track, audio_format2_t *usrfmt)
{
audio_ring_t *last_dst;
int is_playback;
u_int newbufsize;
u_int newvsize;
u_int len;
int error;
KASSERT(track);
is_playback = audio_track_is_playback(track);
/* Once mmap is called, the track format cannot be changed. */
if (track->mmapped)
return EIO;
/* usrbuf is the closest buffer to the userland. */
track->usrbuf.fmt = *usrfmt;
/*
* Usrbuf.
* On the playback track, its capacity is less than or equal to 64KB
* (for historical reason) and must be a multiple of a block
* (constraint in this implementation). But at least AUMINNOBLK
* blocks.
* On the recording track, its capacity is one block.
*/
/*
* For references, one block size (in 40msec) is:
* 320 bytes = 204 blocks/64KB for mulaw/8kHz/1ch
* 7680 bytes = 8 blocks/64KB for s16/48kHz/2ch
* 30720 bytes = 90 KB/3blocks for s16/48kHz/8ch
* 61440 bytes = 180 KB/3blocks for s16/96kHz/8ch
* 245760 bytes = 720 KB/3blocks for s32/192kHz/8ch
*
* For example,
* 1) If usrbuf_blksize = 7056 (s16/44.1k/2ch) and PAGE_SIZE = 8192,
* newbufsize = rounddown(65536 / 7056) = 63504
* newvsize = roundup2(63504, PAGE_SIZE) = 65536
* Therefore it maps 8 * 8K pages and usrbuf->capacity = 63504.
*
* 2) If usrbuf_blksize = 7680 (s16/48k/2ch) and PAGE_SIZE = 4096,
* newbufsize = rounddown(65536 / 7680) = 61440
* newvsize = roundup2(61440, PAGE_SIZE) = 61440 (= 15 pages)
* Therefore it maps 15 * 4K pages and usrbuf->capacity = 61440.
*/
track->usrbuf_blksize = frametobyte(&track->usrbuf.fmt,
frame_per_block(track->mixer, &track->usrbuf.fmt));
track->usrbuf.head = 0;
track->usrbuf.used = 0;
if (is_playback) {
newbufsize = track->usrbuf_blksize * AUMINNOBLK;
if (newbufsize < 65536)
newbufsize = rounddown(65536, track->usrbuf_blksize);
newvsize = roundup2(newbufsize, PAGE_SIZE);
} else {
newbufsize = track->usrbuf_blksize;
newvsize = track->usrbuf_blksize;
}
/*
* Reallocate only if the number of pages changes.
* This is because we expect kmem to allocate memory on per page
* basis if the request size is about 64KB.
*/
if (newvsize != track->usrbuf_allocsize) {
if (track->usrbuf_allocsize != 0) {
kmem_free(track->usrbuf.mem, track->usrbuf_allocsize);
}
TRACET(2, track, "usrbuf_allocsize %d -> %d",
track->usrbuf_allocsize, newvsize);
track->usrbuf.mem = kmem_alloc(newvsize, KM_SLEEP);
track->usrbuf_allocsize = newvsize;
}
track->usrbuf.capacity = newbufsize;
/* Recalc water mark. */
if (is_playback) {
/* Set high at 100%, low at 75%. */
track->usrbuf_usedhigh = track->usrbuf.capacity;
track->usrbuf_usedlow = track->usrbuf.capacity * 3 / 4;
} else {
/* Set high at 100%, low at 0%. (But not used) */
track->usrbuf_usedhigh = track->usrbuf.capacity;
track->usrbuf_usedlow = 0;
}
/* Stage buffer */
last_dst = &track->outbuf;
if (is_playback) {
/* On playback, initialize from the mixer side in order. */
track->inputfmt = *usrfmt;
track->outbuf.fmt = track->mixer->track_fmt;
if ((error = audio_track_init_freq(track, &last_dst)) != 0)
goto error;
if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
goto error;
if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
goto error;
if ((error = audio_track_init_codec(track, &last_dst)) != 0)
goto error;
} else {
/* On recording, initialize from userland side in order. */
track->inputfmt = track->mixer->track_fmt;
track->outbuf.fmt = *usrfmt;
if ((error = audio_track_init_codec(track, &last_dst)) != 0)
goto error;
if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
goto error;
if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
goto error;
if ((error = audio_track_init_freq(track, &last_dst)) != 0)
goto error;
}
/*
* Output buffer.
* On the playback track, its capacity is NBLKOUT blocks.
* On the recording track, its capacity is 1 block.
*/
track->outbuf.head = 0;
track->outbuf.used = 0;
track->outbuf.capacity = frame_per_block(track->mixer,
&track->outbuf.fmt);
if (is_playback)
track->outbuf.capacity *= NBLKOUT;
len = auring_bytelen(&track->outbuf);
track->outbuf.mem = audio_realloc(track->outbuf.mem, len);
/*
* On the recording track, expand the input stage buffer, which is
* the closest buffer to rmixer, to NBLKIN blocks.
* Note that input buffer may point to outbuf.
*/
if (!is_playback) {
int input_fpb;
/*
* Fill silence frames (as the internal format) up to 1 block
* if the ring is not empty and less than 1 block.
* It returns the number of appended frames.
*/
static int
audio_append_silence(audio_track_t *track, audio_ring_t *ring)
{
int fpb;
int n;
/*
* Execute the conversion stage.
* It prepares arg from this stage and executes stage->filter.
* It must be called only if stage->filter is not NULL.
*
* For stages other than frequency conversion, the function increments
* src and dst counters here. For frequency conversion stage, on the
* other hand, the function does not touch src and dst counters and
* filter side has to increment them.
*/
static void
audio_apply_stage(audio_track_t *track, audio_stage_t *stage, bool isfreq)
{
audio_filter_arg_t *arg;
int srccount;
int dstcount;
int count;
if (!isfreq) {
auring_take(&stage->srcbuf, count);
auring_push(stage->dst, count);
}
}
}
/*
* Produce output buffer for playback from user input buffer.
* It must be called only if usrbuf is not empty and outbuf is
* available at least one free block.
*/
static void
audio_track_play(audio_track_t *track)
{
audio_ring_t *usrbuf;
audio_ring_t *input;
int count;
int framesize;
int bytes;
/* At this point usrbuf must not be empty. */
KASSERT(track->usrbuf.used > 0);
/* Also, outbuf must be available at least one block. */
count = auring_get_contig_free(&track->outbuf);
KASSERTMSG(count >= frame_per_block(track->mixer, &track->outbuf.fmt),
"count=%d fpb=%d",
count, frame_per_block(track->mixer, &track->outbuf.fmt));
usrbuf = &track->usrbuf;
input = track->input;
/*
* framesize is always 1 byte or more since all formats supported as
* usrfmt(=input) have 8bit or more stride.
*/
framesize = frametobyte(&input->fmt, 1);
KASSERT(framesize >= 1);
/* The next stage of usrbuf (=input) must be available. */
KASSERT(auring_get_contig_free(input) > 0);
/*
* Copy usrbuf up to 1block to input buffer.
* count is the number of frames to copy from usrbuf.
* bytes is the number of bytes to copy from usrbuf. However it is
* not copied less than one frame.
*/
count = uimin(usrbuf->used, track->usrbuf_blksize) / framesize;
bytes = count * framesize;
if (usrbuf->head + bytes < usrbuf->capacity) {
memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
(uint8_t *)usrbuf->mem + usrbuf->head,
bytes);
auring_push(input, count);
auring_take(usrbuf, bytes);
} else {
int bytes1;
int bytes2;
/* Encoding conversion */
if (track->codec.filter)
audio_apply_stage(track, &track->codec, false);
/* Channel volume */
if (track->chvol.filter)
audio_apply_stage(track, &track->chvol, false);
/* Channel mix */
if (track->chmix.filter)
audio_apply_stage(track, &track->chmix, false);
/* Frequency conversion */
/*
* Since the frequency conversion needs correction for each block,
* it rounds up to 1 block.
*/
if (track->freq.filter) {
int n;
n = audio_append_silence(track, &track->freq.srcbuf);
if (n > 0) {
TRACET(4, track,
"freq.srcbuf add silence %d -> %d/%d/%d",
n,
track->freq.srcbuf.head,
track->freq.srcbuf.used,
track->freq.srcbuf.capacity);
}
if (track->freq.srcbuf.used > 0) {
audio_apply_stage(track, &track->freq, true);
}
}
if (bytes < track->usrbuf_blksize) {
/*
* Clear all conversion buffer pointer if the conversion was
* not exactly one block. These conversion stage buffers are
* certainly circular buffers because of symmetry with the
* previous and next stage buffer. However, since they are
* treated as simple contiguous buffers in operation, so head
* always should point 0. This may happen during drain-age.
*/
TRACET(4, track, "reset stage");
if (track->codec.filter) {
KASSERT(track->codec.srcbuf.used == 0);
track->codec.srcbuf.head = 0;
}
if (track->chvol.filter) {
KASSERT(track->chvol.srcbuf.used == 0);
track->chvol.srcbuf.head = 0;
}
if (track->chmix.filter) {
KASSERT(track->chmix.srcbuf.used == 0);
track->chmix.srcbuf.head = 0;
}
if (track->freq.filter) {
KASSERT(track->freq.srcbuf.used == 0);
track->freq.srcbuf.head = 0;
}
}
/*
* Produce user output buffer for recording from input buffer.
*/
static void
audio_track_record(audio_track_t *track)
{
audio_ring_t *outbuf;
audio_ring_t *usrbuf;
int count;
int bytes;
int framesize;
/* Frequency conversion */
if (track->freq.filter) {
if (track->freq.srcbuf.used > 0) {
audio_apply_stage(track, &track->freq, true);
/* XXX should input of freq be from beginning of buf? */
}
}
/* Channel mix */
if (track->chmix.filter)
audio_apply_stage(track, &track->chmix, false);
/* Channel volume */
if (track->chvol.filter)
audio_apply_stage(track, &track->chvol, false);
/* Encoding conversion */
if (track->codec.filter)
audio_apply_stage(track, &track->codec, false);
/* Copy outbuf to usrbuf */
outbuf = &track->outbuf;
usrbuf = &track->usrbuf;
/* usrbuf should be empty. */
KASSERT(usrbuf->used == 0);
/*
* framesize is always 1 byte or more since all formats supported
* as usrfmt(=output) have 8bit or more stride.
*/
framesize = frametobyte(&outbuf->fmt, 1);
KASSERT(framesize >= 1);
/*
* count is the number of frames to copy to usrbuf.
* bytes is the number of bytes to copy to usrbuf.
*/
count = outbuf->used;
count = uimin(count, track->usrbuf_blksize / framesize);
bytes = count * framesize;
if (auring_tail(usrbuf) + bytes < usrbuf->capacity) {
memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
(uint8_t *)outbuf->mem + outbuf->head * framesize,
bytes);
auring_push(usrbuf, bytes);
auring_take(outbuf, count);
} else {
int bytes1;
int bytes2;
/*
* Calculate blktime [msec] from mixer(.hwbuf.fmt).
* Must be called with sc_exlock held.
*/
static u_int
audio_mixer_calc_blktime(struct audio_softc *sc, audio_trackmixer_t *mixer)
{
audio_format2_t *fmt;
u_int blktime;
u_int frames_per_block;
KASSERT(sc->sc_exlock);
fmt = &mixer->hwbuf.fmt;
blktime = sc->sc_blk_ms;
/*
* If stride is not multiples of 8, special treatment is necessary.
* For now, it is only x68k's vs(4), 4 bit/sample ADPCM.
*/
if (fmt->stride == 4) {
frames_per_block = fmt->sample_rate * blktime / 1000;
if ((frames_per_block & 1) != 0)
blktime *= 2;
}
#ifdef DIAGNOSTIC
else if (fmt->stride % NBBY != 0) {
panic("unsupported HW stride %d", fmt->stride);
}
#endif
return blktime;
}
/*
* Initialize the mixer corresponding to the mode.
* Set AUMODE_PLAY to the 'mode' for playback or AUMODE_RECORD for recording.
* sc->sc_[pr]mixer (corresponding to the 'mode') must be zero-filled.
* This function returns 0 on successful. Otherwise returns errno.
* Must be called with sc_exlock held and without sc_lock held.
*/
static int
audio_mixer_init(struct audio_softc *sc, int mode,
const audio_format2_t *hwfmt, const audio_filter_reg_t *reg)
{
char codecbuf[64];
char blkdmsbuf[8];
audio_trackmixer_t *mixer;
void (*softint_handler)(void *);
int len;
int blksize;
int capacity;
size_t bufsize;
int hwblks;
int blkms;
int blkdms;
int error;
/*
* Releases all resources of 'mixer'.
* Note that it does not release the memory area of 'mixer' itself.
* Must be called with sc_exlock held and without sc_lock held.
*/
static void
audio_mixer_destroy(struct audio_softc *sc, audio_trackmixer_t *mixer)
{
int bufsize;
if (mixer->sih) {
softint_disestablish(mixer->sih);
mixer->sih = NULL;
}
}
/*
* Starts playback mixer.
* Must be called only if sc_pbusy is false.
* Must be called with sc_lock && sc_exlock held.
* Must not be called from the interrupt context.
*/
static void
audio_pmixer_start(struct audio_softc *sc, bool force)
{
audio_trackmixer_t *mixer;
int minimum;
/*
* When playing back with MD filter:
*
* track track ...
* v v
* + mix (with aint2_t)
* | master volume (with aint2_t)
* v
* mixsample [::::] wide-int 1 block (ring) buffer
* |
* | convert aint2_t -> aint_t
* v
* codecbuf [....] 1 block (ring) buffer
* |
* | convert to hw format
* v
* hwbuf [............] NBLKHW blocks ring buffer
*
* When playing back without MD filter:
*
* mixsample [::::] wide-int 1 block (ring) buffer
* |
* | convert aint2_t -> aint_t
* | (with byte swap if necessary)
* v
* hwbuf [............] NBLKHW blocks ring buffer
*
* mixsample: slinear_NE, wide internal precision, HW ch, HW freq.
* codecbuf: slinear_NE, internal precision, HW ch, HW freq.
* hwbuf: HW encoding, HW precision, HW ch, HW freq.
*/
/*
* Performs track mixing and converts it to hwbuf.
* Note that this function doesn't transfer hwbuf to hardware.
* Must be called with sc_intr_lock held.
*/
static void
audio_pmixer_process(struct audio_softc *sc)
{
audio_trackmixer_t *mixer;
audio_file_t *f;
int frame_count;
int sample_count;
int mixed;
int i;
aint2_t *m;
aint_t *h;
if (mixed == 0) {
/* Silence */
memset(mixer->mixsample, 0,
frametobyte(&mixer->mixfmt, frame_count));
} else {
if (mixed > 1) {
/* If there are multiple tracks, do auto gain control */
audio_pmixer_agc(mixer, sample_count);
}
/* Apply master volume */
if (mixer->volume < 256) {
m = mixer->mixsample;
for (i = 0; i < sample_count; i++) {
*m = AUDIO_SCALEDOWN(*m * mixer->volume, 8);
m++;
}
/*
* Recover the volume gradually at the pace of
* several times per second. If it's too fast, you
* can recognize that the volume changes up and down
* quickly and it's not so comfortable.
*/
mixer->voltimer += mixer->blktime_n;
if (mixer->voltimer * 4 >= mixer->blktime_d) {
mixer->volume++;
mixer->voltimer = 0;
#if defined(AUDIO_DEBUG_AGC)
TRACE(1, "volume recover: %d", mixer->volume);
#endif
}
}
}
/*
* The rest is the hardware part.
*/
m = mixer->mixsample;
if (mixer->codec) {
TRACE(4, "codec count=%d", frame_count);
h = auring_tailptr_aint(&mixer->codecbuf);
for (i=0; i<sample_count; ++i)
*h++ = *m++;
/*
* Do auto gain control.
* Must be called sc_intr_lock held.
*/
static void
audio_pmixer_agc(audio_trackmixer_t *mixer, int sample_count)
{
struct audio_softc *sc __unused;
aint2_t val;
aint2_t maxval;
aint2_t minval;
aint2_t over_plus;
aint2_t over_minus;
aint2_t *m;
int newvol;
int i;
sc = mixer->sc;
/* Overflow detection */
maxval = AINT_T_MAX;
minval = AINT_T_MIN;
m = mixer->mixsample;
for (i = 0; i < sample_count; i++) {
val = *m++;
if (val > maxval)
maxval = val;
else if (val < minval)
minval = val;
}
/* Absolute value of overflowed amount */
over_plus = maxval - AINT_T_MAX;
over_minus = AINT_T_MIN - minval;
/*
* Change the volume only if new one is smaller.
* Reset the timer even if the volume isn't changed.
*/
if (newvol <= mixer->volume) {
mixer->volume = newvol;
mixer->voltimer = 0;
#if defined(AUDIO_DEBUG_AGC)
TRACE(1, "auto volume adjust: %d", mixer->volume);
#endif
}
}
}
/*
* Mix one track.
* 'mixed' specifies the number of tracks mixed so far.
* It returns the number of tracks mixed. In other words, it returns
* mixed + 1 if this track is mixed.
*/
static int
audio_pmixer_mix_track(audio_trackmixer_t *mixer, audio_track_t *track,
int mixed)
{
int count;
int sample_count;
int remain;
int i;
const aint_t *s;
aint2_t *d;
/* XXX TODO: Is this necessary for now? */
if (mixer->mixseq < track->seq)
return mixed;
s = auring_headptr_aint(&track->outbuf);
d = mixer->mixsample;
/*
* Apply track volume with double-sized integer and perform
* additive synthesis.
*
* XXX If you limit the track volume to 1.0 or less (<= 256),
* it would be better to do this in the track conversion stage
* rather than here. However, if you accept the volume to
* be greater than 1.0 (> 256), it's better to do it here.
* Because the operation here is done by double-sized integer.
*/
sample_count = count * mixer->mixfmt.channels;
if (mixed == 0) {
/* If this is the first track, assignment can be used. */
#if defined(AUDIO_SUPPORT_TRACK_VOLUME)
if (track->volume != 256) {
for (i = 0; i < sample_count; i++) {
aint2_t v;
v = *s++;
*d++ = AUDIO_SCALEDOWN(v * track->volume, 8)
}
} else
#endif
{
for (i = 0; i < sample_count; i++) {
*d++ = ((aint2_t)*s++);
}
}
/* Fill silence if the first track is not filled. */
for (; i < mixer->frames_per_block * mixer->mixfmt.channels; i++)
*d++ = 0;
} else {
/* If this is the second or later, add it. */
#if defined(AUDIO_SUPPORT_TRACK_VOLUME)
if (track->volume != 256) {
for (i = 0; i < sample_count; i++) {
aint2_t v;
v = *s++;
*d++ += AUDIO_SCALEDOWN(v * track->volume, 8);
}
} else
#endif
{
for (i = 0; i < sample_count; i++) {
*d++ += ((aint2_t)*s++);
}
}
}
auring_take(&track->outbuf, count);
/*
* The counters have to align block even if outbuf is less than
* one block. XXX Is this still necessary?
*/
remain = mixer->frames_per_block - count;
if (__predict_false(remain != 0)) {
auring_push(&track->outbuf, remain);
auring_take(&track->outbuf, remain);
}
/*
* Update track sequence.
* mixseq has previous value yet at this point.
*/
track->seq = mixer->mixseq + 1;
return mixed + 1;
}
/*
* Output one block from hwbuf to HW.
* Must be called with sc_intr_lock held.
*/
static void
audio_pmixer_output(struct audio_softc *sc)
{
audio_trackmixer_t *mixer;
audio_params_t params;
void *start;
void *end;
int blksize;
int error;
/*
* This is an interrupt handler for playback.
* It is called with sc_intr_lock held.
*
* It is usually called from hardware interrupt. However, note that
* for some drivers (e.g. uaudio) it is called from software interrupt.
*/
static void
audio_pintr(void *arg)
{
struct audio_softc *sc;
audio_trackmixer_t *mixer;
sc = arg;
KASSERT(mutex_owned(sc->sc_intr_lock));
if (sc->sc_dying)
return;
if (sc->sc_pbusy == false) {
#if defined(DIAGNOSTIC)
audio_printf(sc, "DIAGNOSTIC: %s raised stray interrupt\n",
device_xname(sc->hw_dev));
#endif
return;
}
#if defined(AUDIO_HW_SINGLE_BUFFER)
/*
* Create a new block here and output it immediately.
* It makes a latency lower but needs machine power.
*/
audio_pmixer_process(sc);
audio_pmixer_output(sc);
#else
/*
* It is called when block N output is done.
* Output immediately block N+1 created by the last interrupt.
* And then create block N+2 for the next interrupt.
* This method makes playback robust even on slower machines.
* Instead the latency is increased by one block.
*/
/* At first, output ready block. */
if (mixer->hwbuf.used >= mixer->frames_per_block) {
audio_pmixer_output(sc);
}
bool later = false;
if (mixer->hwbuf.used < mixer->frames_per_block) {
later = true;
}
/* Then, process next block. */
audio_pmixer_process(sc);
if (later) {
audio_pmixer_output(sc);
}
#endif
/*
* When this interrupt is the real hardware interrupt, disabling
* preemption here is not necessary. But some drivers (e.g. uaudio)
* emulate it by software interrupt, so kpreempt_disable is necessary.
*/
kpreempt_disable();
softint_schedule(mixer->sih);
kpreempt_enable();
}
/*
* Starts record mixer.
* Must be called only if sc_rbusy is false.
* Must be called with sc_lock && sc_exlock held.
* Must not be called from the interrupt context.
*/
static void
audio_rmixer_start(struct audio_softc *sc)
{
/*
* When recording with MD filter:
*
* hwbuf [............] NBLKHW blocks ring buffer
* |
* | convert from hw format
* v
* codecbuf [....] 1 block (ring) buffer
* | |
* v v
* track track ...
*
* When recording without MD filter:
*
* hwbuf [............] NBLKHW blocks ring buffer
* | |
* v v
* track track ...
*
* hwbuf: HW encoding, HW precision, HW ch, HW freq.
* codecbuf: slinear_NE, internal precision, HW ch, HW freq.
*/
/*
* Distribute a recorded block to all recording tracks.
*/
static void
audio_rmixer_process(struct audio_softc *sc)
{
audio_trackmixer_t *mixer;
audio_ring_t *mixersrc;
audio_ring_t tmpsrc;
audio_filter_t codec;
audio_filter_arg_t codecarg;
audio_file_t *f;
int count;
int bytes;
mixer = sc->sc_rmixer;
/*
* count is the number of frames to be retrieved this time.
* count should be one block.
*/
count = auring_get_contig_used(&mixer->hwbuf);
count = uimin(count, mixer->frames_per_block);
if (count <= 0) {
TRACE(4, "count %d: too short", count);
return;
}
bytes = frametobyte(&mixer->track_fmt, count);
/* Distribute to all tracks. */
SLIST_FOREACH(f, &sc->sc_files, entry) {
audio_track_t *track = f->rtrack;
audio_ring_t *input;
if (track == NULL)
continue;
if (track->is_pause) {
TRACET(4, track, "skip; paused");
continue;
}
if (audio_track_lock_tryenter(track) == false) {
TRACET(4, track, "skip; in use");
continue;
}
/*
* If the track buffer has less than one block of free space,
* make one block free.
*/
input = track->input;
if (input->capacity - input->used < mixer->frames_per_block) {
int drops = mixer->frames_per_block -
(input->capacity - input->used);
track->dropframes += drops;
TRACET(4, track, "drop %d frames: inp=%d/%d/%d",
drops,
input->head, input->used, input->capacity);
auring_take(input, drops);
}
/*
* Input one block from HW to hwbuf.
* Must be called with sc_intr_lock held.
*/
static void
audio_rmixer_input(struct audio_softc *sc)
{
audio_trackmixer_t *mixer;
audio_params_t params;
void *start;
void *end;
int blksize;
int error;
/*
* This is an interrupt handler for recording.
* It is called with sc_intr_lock.
*
* It is usually called from hardware interrupt. However, note that
* for some drivers (e.g. uaudio) it is called from software interrupt.
*/
static void
audio_rintr(void *arg)
{
struct audio_softc *sc;
audio_trackmixer_t *mixer;
sc = arg;
KASSERT(mutex_owned(sc->sc_intr_lock));
if (sc->sc_dying)
return;
if (sc->sc_rbusy == false) {
#if defined(DIAGNOSTIC)
audio_printf(sc, "DIAGNOSTIC: %s raised stray interrupt\n",
device_xname(sc->hw_dev));
#endif
return;
}
/* Distrubute recorded block */
audio_rmixer_process(sc);
/* Request next block */
audio_rmixer_input(sc);
/*
* When this interrupt is the real hardware interrupt, disabling
* preemption here is not necessary. But some drivers (e.g. uaudio)
* emulate it by software interrupt, so kpreempt_disable is necessary.
*/
kpreempt_disable();
softint_schedule(mixer->sih);
kpreempt_enable();
}
/*
* Halts playback mixer.
* This function also clears related parameters, so call this function
* instead of calling halt_output directly.
* Must be called only if sc_pbusy is true.
* Must be called with sc_lock && sc_exlock held.
*/
static int
audio_pmixer_halt(struct audio_softc *sc)
{
int error;
/* Halts anyway even if some error has occurred. */
sc->sc_pbusy = false;
sc->sc_pmixer->hwbuf.head = 0;
sc->sc_pmixer->hwbuf.used = 0;
sc->sc_pmixer->mixseq = 0;
sc->sc_pmixer->hwseq = 0;
mutex_exit(sc->sc_intr_lock);
return error;
}
/*
* Halts recording mixer.
* This function also clears related parameters, so call this function
* instead of calling halt_input directly.
* Must be called only if sc_rbusy is true.
* Must be called with sc_lock && sc_exlock held.
*/
static int
audio_rmixer_halt(struct audio_softc *sc)
{
int error;
/*
* Drain the track.
* track must be present and for playback.
* If successful, it returns 0. Otherwise returns errno.
* Must be called with sc_lock held.
*/
static int
audio_track_drain(struct audio_softc *sc, audio_track_t *track)
{
audio_trackmixer_t *mixer;
int done;
int error;
/* Ignore them if pause. */
if (track->is_pause) {
TRACET(3, track, "pause -> clear");
track->pstate = AUDIO_STATE_CLEAR;
}
/* Terminate early here if there is no data in the track. */
if (track->pstate == AUDIO_STATE_CLEAR) {
TRACET(3, track, "no need to drain");
return 0;
}
track->pstate = AUDIO_STATE_DRAINING;
for (;;) {
/* I want to display it before condition evaluation. */
TRACET(3, track, "pid=%d.%d trkseq=%d hwseq=%d out=%d/%d/%d",
(int)curproc->p_pid, (int)curlwp->l_lid,
(int)track->seq, (int)mixer->hwseq,
track->outbuf.head, track->outbuf.used,
track->outbuf.capacity);
/*
* Send signal to process.
* This is intended to be called only from audio_softintr_{rd,wr}.
* Must be called without sc_intr_lock held.
*/
static inline void
audio_psignal(struct audio_softc *sc, pid_t pid, int signum)
{
proc_t *p;
KASSERT(pid != 0);
/*
* psignal() must be called without spin lock held.
*/
mutex_enter(&proc_lock);
p = proc_find(pid);
if (p)
psignal(p, signum);
mutex_exit(&proc_lock);
}
/*
* This is software interrupt handler for record.
* It is called from recording hardware interrupt everytime.
* It does:
* - Deliver SIGIO for all async processes.
* - Notify to audio_read() that data has arrived.
* - selnotify() for select/poll-ing processes.
*/
/*
* XXX If a process issues FIOASYNC between hardware interrupt and
* software interrupt, (stray) SIGIO will be sent to the process
* despite the fact that it has not receive recorded data yet.
*/
static void
audio_softintr_rd(void *cookie)
{
struct audio_softc *sc = cookie;
audio_file_t *f;
pid_t pid;
/* Notify that data has arrived. */
selnotify(&sc->sc_rsel, 0, NOTE_SUBMIT);
cv_broadcast(&sc->sc_rmixer->outcv);
mutex_exit(sc->sc_lock);
}
/*
* This is software interrupt handler for playback.
* It is called from playback hardware interrupt everytime.
* It does:
* - Deliver SIGIO for all async and writable (used < lowat) processes.
* - Notify to audio_write() that outbuf block available.
* - selnotify() for select/poll-ing processes if there are any writable
* (used < lowat) processes. Checking each descriptor will be done by
* filt_audiowrite_event().
*/
static void
audio_softintr_wr(void *cookie)
{
struct audio_softc *sc = cookie;
audio_file_t *f;
bool found;
pid_t pid;
/*
* Send a signal if the process is async mode and
* used is lower than lowat.
*/
if (track->usrbuf.used <= track->usrbuf_usedlow &&
!track->is_pause) {
/* For selnotify */
found = true;
/* For SIGIO */
pid = f->async_audio;
if (pid != 0) {
TRACEF(4, f, "sending SIGIO %d", pid);
audio_psignal(sc, pid, SIGIO);
}
}
}
/*
* Notify for select/poll when someone become writable.
* It needs sc_lock (and not sc_intr_lock).
*/
if (found) {
TRACE(4, "selnotify");
selnotify(&sc->sc_wsel, 0, NOTE_SUBMIT);
}
/* Notify to audio_write() that outbuf available. */
cv_broadcast(&sc->sc_pmixer->outcv);
mutex_exit(sc->sc_lock);
}
/*
* Check (and convert) the format *p came from userland.
* If successful, it writes back the converted format to *p if necessary and
* returns 0. Otherwise returns errno (*p may be changed even in this case).
*/
static int
audio_check_params(audio_format2_t *p)
{
/*
* Convert obsolete AUDIO_ENCODING_PCM encodings.
*
* AUDIO_ENCODING_PCM16 == AUDIO_ENCODING_LINEAR
* So, it's always signed, as in SunOS.
*
* AUDIO_ENCODING_PCM8 == AUDIO_ENCODING_LINEAR8
* So, it's always unsigned, as in SunOS.
*/
if (p->encoding == AUDIO_ENCODING_PCM16) {
p->encoding = AUDIO_ENCODING_SLINEAR;
} else if (p->encoding == AUDIO_ENCODING_PCM8) {
if (p->precision == 8)
p->encoding = AUDIO_ENCODING_ULINEAR;
else
return EINVAL;
}
/*
* Convert obsoleted AUDIO_ENCODING_[SU]LINEAR without endianness
* suffix.
*/
if (p->encoding == AUDIO_ENCODING_SLINEAR)
p->encoding = AUDIO_ENCODING_SLINEAR_NE;
if (p->encoding == AUDIO_ENCODING_ULINEAR)
p->encoding = AUDIO_ENCODING_ULINEAR_NE;
switch (p->encoding) {
case AUDIO_ENCODING_ULAW:
case AUDIO_ENCODING_ALAW:
if (p->precision != 8)
return EINVAL;
break;
case AUDIO_ENCODING_ADPCM:
if (p->precision != 4 && p->precision != 8)
return EINVAL;
break;
case AUDIO_ENCODING_SLINEAR_LE:
case AUDIO_ENCODING_SLINEAR_BE:
case AUDIO_ENCODING_ULINEAR_LE:
case AUDIO_ENCODING_ULINEAR_BE:
if (p->precision != 8 && p->precision != 16 &&
p->precision != 24 && p->precision != 32)
return EINVAL;
/* 8bit format does not have endianness. */
if (p->precision == 8) {
if (p->encoding == AUDIO_ENCODING_SLINEAR_OE)
p->encoding = AUDIO_ENCODING_SLINEAR_NE;
if (p->encoding == AUDIO_ENCODING_ULINEAR_OE)
p->encoding = AUDIO_ENCODING_ULINEAR_NE;
}
if (p->precision > p->stride)
return EINVAL;
break;
case AUDIO_ENCODING_MPEG_L1_STREAM:
case AUDIO_ENCODING_MPEG_L1_PACKETS:
case AUDIO_ENCODING_MPEG_L1_SYSTEM:
case AUDIO_ENCODING_MPEG_L2_STREAM:
case AUDIO_ENCODING_MPEG_L2_PACKETS:
case AUDIO_ENCODING_MPEG_L2_SYSTEM:
case AUDIO_ENCODING_AC3:
break;
default:
return EINVAL;
}
/* sanity check # of channels*/
if (p->channels < 1 || p->channels > AUDIO_MAX_CHANNELS)
return EINVAL;
return 0;
}
/*
* Initialize playback and record mixers.
* mode (AUMODE_{PLAY,RECORD}) indicates the mixer to be initialized.
* phwfmt and rhwfmt indicate the hardware format. pfil and rfil indicate
* the filter registration information. These four must not be NULL.
* If successful returns 0. Otherwise returns errno.
* Must be called with sc_exlock held and without sc_lock held.
* Must not be called if there are any tracks.
* Caller should check that the initialization succeed by whether
* sc_[pr]mixer is not NULL.
*/
static int
audio_mixers_init(struct audio_softc *sc, int mode,
const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
const audio_filter_reg_t *pfil, const audio_filter_reg_t *rfil)
{
int error;
/*
* Select a frequency.
* Prioritize 48kHz and 44.1kHz. Otherwise choose the highest one.
* XXX Better algorithm?
*/
static int
audio_select_freq(const struct audio_format *fmt)
{
int freq;
int high;
int low;
int j;
if (fmt->frequency_type == 0) {
low = fmt->frequency[0];
high = fmt->frequency[1];
freq = 48000;
if (low <= freq && freq <= high) {
return freq;
}
freq = 44100;
if (low <= freq && freq <= high) {
return freq;
}
return high;
} else {
for (j = 0; j < fmt->frequency_type; j++) {
if (fmt->frequency[j] == 48000) {
return fmt->frequency[j];
}
}
high = 0;
for (j = 0; j < fmt->frequency_type; j++) {
if (fmt->frequency[j] == 44100) {
return fmt->frequency[j];
}
if (fmt->frequency[j] > high) {
high = fmt->frequency[j];
}
}
return high;
}
}
/*
* Choose the most preferred hardware format.
* If successful, it will store the chosen format into *cand and return 0.
* Otherwise, return errno.
* Must be called without sc_lock held.
*/
static int
audio_hw_probe(struct audio_softc *sc, audio_format2_t *cand, int mode)
{
audio_format_query_t query;
int cand_score;
int score;
int i;
int error;
/*
* Score each formats and choose the highest one.
*
* +---- priority(0-3)
* |+--- encoding/precision
* ||+-- channels
* score = 0x000000PEC
*/
cand_score = 0;
for (i = 0; ; i++) {
memset(&query, 0, sizeof(query));
query.index = i;
mutex_enter(sc->sc_lock);
error = sc->hw_if->query_format(sc->hw_hdl, &query);
mutex_exit(sc->sc_lock);
if (error == EINVAL)
break;
if (error)
return error;
/*
* Validate fmt with query_format.
* If fmt is included in the result of query_format, returns 0.
* Otherwise returns EINVAL.
* Must be called without sc_lock held.
*/
static int
audio_hw_validate_format(struct audio_softc *sc, int mode,
const audio_format2_t *fmt)
{
audio_format_query_t query;
struct audio_format *q;
int index;
int error;
int j;
for (index = 0; ; index++) {
query.index = index;
mutex_enter(sc->sc_lock);
error = sc->hw_if->query_format(sc->hw_hdl, &query);
mutex_exit(sc->sc_lock);
if (error == EINVAL)
break;
if (error)
return error;
q = &query.fmt;
/*
* Note that fmt is audio_format2_t (precision/stride) but
* q is audio_format_t (validbits/precision).
*/
if ((q->mode & mode) == 0) {
continue;
}
if (fmt->encoding != q->encoding) {
continue;
}
if (fmt->precision != q->validbits) {
continue;
}
if (fmt->stride != q->precision) {
continue;
}
if (fmt->channels != q->channels) {
continue;
}
if (q->frequency_type == 0) {
if (fmt->sample_rate < q->frequency[0] ||
fmt->sample_rate > q->frequency[1]) {
continue;
}
} else {
for (j = 0; j < q->frequency_type; j++) {
if (fmt->sample_rate == q->frequency[j])
break;
}
if (j == query.fmt.frequency_type) {
continue;
}
}
/* Matched. */
return 0;
}
return EINVAL;
}
/*
* Set track mixer's format depending on ai->mode.
* If AUMODE_PLAY is set in ai->mode, it set up the playback mixer
* with ai.play.*.
* If AUMODE_RECORD is set in ai->mode, it set up the recording mixer
* with ai.record.*.
* All other fields in ai are ignored.
* If successful returns 0. Otherwise returns errno.
* This function does not roll back even if it fails.
* Must be called with sc_exlock held and without sc_lock held.
*/
static int
audio_mixers_set_format(struct audio_softc *sc, const struct audio_info *ai)
{
audio_format2_t phwfmt;
audio_format2_t rhwfmt;
audio_filter_reg_t pfil;
audio_filter_reg_t rfil;
int mode;
int error;
KASSERT(sc->sc_exlock);
/*
* Even when setting either one of playback and recording,
* both must be halted.
*/
if (sc->sc_popens + sc->sc_ropens > 0)
return EBUSY;
if (!SPECIFIED(ai->mode) || ai->mode == 0)
return ENOTTY;
/* On non-independent devices, use the same format for both. */
if ((sc->sc_props & AUDIO_PROP_INDEPENDENT) == 0) {
if (mode == AUMODE_RECORD) {
phwfmt = rhwfmt;
} else {
rhwfmt = phwfmt;
}
mode = AUMODE_PLAY | AUMODE_RECORD;
}
/* Then, unset the direction not exist on the hardware. */
if ((sc->sc_props & AUDIO_PROP_PLAYBACK) == 0)
mode &= ~AUMODE_PLAY;
if ((sc->sc_props & AUDIO_PROP_CAPTURE) == 0)
mode &= ~AUMODE_RECORD;
/*
* Reinitialize the sticky parameters for /dev/sound.
* If the number of the hardware channels becomes less than the number
* of channels that sticky parameters remember, subsequent /dev/sound
* open will fail. To prevent this, reinitialize the sticky
* parameters whenever the hardware format is changed.
*/
sc->sc_sound_pparams = params_to_format2(&audio_default);
sc->sc_sound_rparams = params_to_format2(&audio_default);
sc->sc_sound_ppause = false;
sc->sc_sound_rpause = false;
return 0;
}
/*
* Store current mixers format into *ai.
* Must be called with sc_exlock held.
*/
static void
audio_mixers_get_format(struct audio_softc *sc, struct audio_info *ai)
{
KASSERT(sc->sc_exlock);
/*
* There is no stride information in audio_info but it doesn't matter.
* trackmixer always treats stride and precision as the same.
*/
AUDIO_INITINFO(ai);
ai->mode = 0;
if (sc->sc_pmixer) {
audio_format2_t *fmt = &sc->sc_pmixer->track_fmt;
ai->play.encoding = fmt->encoding;
ai->play.precision = fmt->precision;
ai->play.channels = fmt->channels;
ai->play.sample_rate = fmt->sample_rate;
ai->mode |= AUMODE_PLAY;
}
if (sc->sc_rmixer) {
audio_format2_t *fmt = &sc->sc_rmixer->track_fmt;
ai->record.encoding = fmt->encoding;
ai->record.precision = fmt->precision;
ai->record.channels = fmt->channels;
ai->record.sample_rate = fmt->sample_rate;
ai->mode |= AUMODE_RECORD;
}
}
/*
* audio_info details:
*
* ai.{play,record}.sample_rate (R/W)
* ai.{play,record}.encoding (R/W)
* ai.{play,record}.precision (R/W)
* ai.{play,record}.channels (R/W)
* These specify the playback or recording format.
* Ignore members within an inactive track.
*
* ai.mode (R/W)
* It specifies the playback or recording mode, AUMODE_*.
* Currently, a mode change operation by ai.mode after opening is
* prohibited. In addition, AUMODE_PLAY_ALL no longer makes sense.
* However, it's possible to get or to set for backward compatibility.
*
* ai.{hiwat,lowat} (R/W)
* These specify the high water mark and low water mark for playback
* track. The unit is block.
*
* ai.{play,record}.gain (R/W)
* It specifies the HW mixer volume in 0-255.
* It is historical reason that the gain is connected to HW mixer.
*
* ai.{play,record}.balance (R/W)
* It specifies the left-right balance of HW mixer in 0-64.
* 32 means the center.
* It is historical reason that the balance is connected to HW mixer.
*
* ai.{play,record}.port (R/W)
* It specifies the input/output port of HW mixer.
*
* ai.monitor_gain (R/W)
* It specifies the recording monitor gain(?) of HW mixer.
*
* ai.{play,record}.pause (R/W)
* Non-zero means the track is paused.
*
* ai.play.seek (R/-)
* It indicates the number of bytes written but not processed.
* ai.record.seek (R/-)
* It indicates the number of bytes to be able to read.
*
* ai.{play,record}.avail_ports (R/-)
* Mixer info.
*
* ai.{play,record}.buffer_size (R/-)
* It indicates the buffer size in bytes. Internally it means usrbuf.
*
* ai.{play,record}.samples (R/-)
* It indicates the total number of bytes played or recorded.
*
* ai.{play,record}.eof (R/-)
* It indicates the number of times reached EOF(?).
*
* ai.{play,record}.error (R/-)
* Non-zero indicates overflow/underflow has occurred.
*
* ai.{play,record}.waiting (R/-)
* Non-zero indicates that other process waits to open.
* It will never happen anymore.
*
* ai.{play,record}.open (R/-)
* Non-zero indicates the direction is opened by this process(?).
* XXX Is this better to indicate that "the device is opened by
* at least one process"?
*
* ai.{play,record}.active (R/-)
* Non-zero indicates that I/O is currently active.
*
* ai.blocksize (R/-)
* It indicates the block size in bytes.
* XXX The blocksize of playback and recording may be different.
*/
/*
* Pause consideration:
*
* Pausing/unpausing never affect [pr]mixer. This single rule makes
* operation simple. Note that playback and recording are asymmetric.
*
* For playback,
* 1. Any playback open doesn't start pmixer regardless of initial pause
* state of this track.
* 2. The first write access among playback tracks only starts pmixer
* regardless of this track's pause state.
* 3. Even a pause of the last playback track doesn't stop pmixer.
* 4. The last close of all playback tracks only stops pmixer.
*
* For recording,
* 1. The first recording open only starts rmixer regardless of initial
* pause state of this track.
* 2. Even a pause of the last track doesn't stop rmixer.
* 3. The last close of all recording tracks only stops rmixer.
*/
/*
* Set both track's parameters within a file depending on ai.
* Update sc_sound_[pr]* if set.
* Must be called with sc_exlock held and without sc_lock held.
*/
static int
audio_file_setinfo(struct audio_softc *sc, audio_file_t *file,
const struct audio_info *ai)
{
const struct audio_prinfo *pi;
const struct audio_prinfo *ri;
audio_track_t *ptrack;
audio_track_t *rtrack;
audio_format2_t pfmt;
audio_format2_t rfmt;
int pchanges;
int rchanges;
int mode;
struct audio_info saved_ai;
audio_format2_t saved_pfmt;
audio_format2_t saved_rfmt;
int error;
KASSERT(sc->sc_exlock);
pi = &ai->play;
ri = &ai->record;
pchanges = 0;
rchanges = 0;
ptrack = file->ptrack;
rtrack = file->rtrack;
#if defined(AUDIO_DEBUG)
if (audiodebug >= 2) {
char buf[256];
char p[64];
int buflen;
int plen;
#define SPRINTF(var, fmt...) do { \
var##len += snprintf(var + var##len, sizeof(var) - var##len, fmt); \
} while (0)
buflen = 0;
plen = 0;
if (SPECIFIED(pi->encoding))
SPRINTF(p, "/%s", audio_encoding_name(pi->encoding));
if (SPECIFIED(pi->precision))
SPRINTF(p, "/%dbit", pi->precision);
if (SPECIFIED(pi->channels))
SPRINTF(p, "/%dch", pi->channels);
if (SPECIFIED(pi->sample_rate))
SPRINTF(p, "/%dHz", pi->sample_rate);
if (plen > 0)
SPRINTF(buf, ",play.param=%s", p + 1);
plen = 0;
if (SPECIFIED(ri->encoding))
SPRINTF(p, "/%s", audio_encoding_name(ri->encoding));
if (SPECIFIED(ri->precision))
SPRINTF(p, "/%dbit", ri->precision);
if (SPECIFIED(ri->channels))
SPRINTF(p, "/%dch", ri->channels);
if (SPECIFIED(ri->sample_rate))
SPRINTF(p, "/%dHz", ri->sample_rate);
if (plen > 0)
SPRINTF(buf, ",record.param=%s", p + 1);
if (SPECIFIED(ai->mode))
SPRINTF(buf, ",mode=%d", ai->mode);
if (SPECIFIED(ai->hiwat))
SPRINTF(buf, ",hiwat=%d", ai->hiwat);
if (SPECIFIED(ai->lowat))
SPRINTF(buf, ",lowat=%d", ai->lowat);
if (SPECIFIED(ai->play.gain))
SPRINTF(buf, ",play.gain=%d", ai->play.gain);
if (SPECIFIED(ai->record.gain))
SPRINTF(buf, ",record.gain=%d", ai->record.gain);
if (SPECIFIED_CH(ai->play.balance))
SPRINTF(buf, ",play.balance=%d", ai->play.balance);
if (SPECIFIED_CH(ai->record.balance))
SPRINTF(buf, ",record.balance=%d", ai->record.balance);
if (SPECIFIED(ai->play.port))
SPRINTF(buf, ",play.port=%d", ai->play.port);
if (SPECIFIED(ai->record.port))
SPRINTF(buf, ",record.port=%d", ai->record.port);
if (SPECIFIED(ai->monitor_gain))
SPRINTF(buf, ",monitor_gain=%d", ai->monitor_gain);
if (SPECIFIED_CH(ai->play.pause))
SPRINTF(buf, ",play.pause=%d", ai->play.pause);
if (SPECIFIED_CH(ai->record.pause))
SPRINTF(buf, ",record.pause=%d", ai->record.pause);
/*
* Set default value and save current parameters.
* For backward compatibility, use sticky parameters for nonexistent
* track.
*/
if (ptrack) {
pfmt = ptrack->usrbuf.fmt;
saved_pfmt = ptrack->usrbuf.fmt;
saved_ai.play.pause = ptrack->is_pause;
} else {
pfmt = sc->sc_sound_pparams;
}
if (rtrack) {
rfmt = rtrack->usrbuf.fmt;
saved_rfmt = rtrack->usrbuf.fmt;
saved_ai.record.pause = rtrack->is_pause;
} else {
rfmt = sc->sc_sound_rparams;
}
saved_ai.mode = file->mode;
/*
* Overwrite if specified.
*/
mode = file->mode;
if (SPECIFIED(ai->mode)) {
/*
* Setting ai->mode no longer does anything because it's
* prohibited to change playback/recording mode after open
* and AUMODE_PLAY_ALL is obsoleted. However, it still
* keeps the state of AUMODE_PLAY_ALL itself for backward
* compatibility.
* In the internal, only file->mode has the state of
* AUMODE_PLAY_ALL flag and track->mode in both track does
* not have.
*/
if ((file->mode & AUMODE_PLAY)) {
mode = (file->mode & (AUMODE_PLAY | AUMODE_RECORD))
| (ai->mode & AUMODE_PLAY_ALL);
}
}
/*
* Write SPECIFIED() parameters within info back to fmt.
* Note that track can be NULL here.
* Return value of 1 indicates that fmt is modified.
* Return value of 0 indicates that fmt is not modified.
* Return value of -1 indicates that error EINVAL has occurred.
*/
static int
audio_track_setinfo_check(audio_track_t *track,
audio_format2_t *fmt, const struct audio_prinfo *info)
{
const audio_format2_t *hwfmt;
int changes;
changes = 0;
if (SPECIFIED(info->sample_rate)) {
if (info->sample_rate < AUDIO_MIN_FREQUENCY)
return -1;
if (info->sample_rate > AUDIO_MAX_FREQUENCY)
return -1;
fmt->sample_rate = info->sample_rate;
changes = 1;
}
if (SPECIFIED(info->encoding)) {
fmt->encoding = info->encoding;
changes = 1;
}
if (SPECIFIED(info->precision)) {
fmt->precision = info->precision;
/* we don't have API to specify stride */
fmt->stride = info->precision;
changes = 1;
}
if (SPECIFIED(info->channels)) {
/*
* We can convert between monaural and stereo each other.
* We can reduce than the number of channels that the hardware
* supports.
*/
if (info->channels > 2) {
if (track) {
hwfmt = &track->mixer->hwbuf.fmt;
if (info->channels > hwfmt->channels)
return -1;
} else {
/*
* This should never happen.
* If track == NULL, channels should be <= 2.
*/
return -1;
}
}
fmt->channels = info->channels;
changes = 1;
}
if (changes) {
if (audio_check_params(fmt) != 0)
return -1;
}
return changes;
}
/*
* Change water marks for playback track if specified.
*/
static void
audio_track_setinfo_water(audio_track_t *track, const struct audio_info *ai)
{
u_int blks;
u_int maxblks;
u_int blksize;
if (SPECIFIED(ai->hiwat)) {
blks = ai->hiwat;
if (blks > maxblks)
blks = maxblks;
if (blks < 2)
blks = 2;
track->usrbuf_usedhigh = blks * blksize;
}
if (SPECIFIED(ai->lowat)) {
blks = ai->lowat;
if (blks > maxblks - 1)
blks = maxblks - 1;
track->usrbuf_usedlow = blks * blksize;
}
if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
if (track->usrbuf_usedlow > track->usrbuf_usedhigh - blksize) {
track->usrbuf_usedlow = track->usrbuf_usedhigh -
blksize;
}
}
}
/*
* Set hardware part of *newai.
* The parameters handled here are *.port, *.gain, *.balance and monitor_gain.
* If oldai is specified, previous parameters are stored.
* This function itself does not roll back if error occurred.
* Must be called with sc_lock && sc_exlock held.
*/
static int
audio_hw_setinfo(struct audio_softc *sc, const struct audio_info *newai,
struct audio_info *oldai)
{
const struct audio_prinfo *newpi;
const struct audio_prinfo *newri;
struct audio_prinfo *oldpi;
struct audio_prinfo *oldri;
u_int pgain;
u_int rgain;
u_char pbalance;
u_char rbalance;
int error;
if (SPECIFIED(newai->monitor_gain) && sc->sc_monitor_port != -1) {
if (oldai)
oldai->monitor_gain = au_get_monitor_gain(sc);
error = au_set_monitor_gain(sc, newai->monitor_gain);
if (error) {
audio_printf(sc,
"setting monitor_gain=%d failed: errno=%d\n",
newai->monitor_gain, error);
goto abort;
}
}
/* XXX TODO */
/* sc->sc_ai = *ai; */
error = 0;
abort:
return error;
}
/*
* Setup the hardware with mixer format phwfmt, rhwfmt.
* The arguments have following restrictions:
* - setmode is the direction you want to set, AUMODE_PLAY or AUMODE_RECORD,
* or both.
* - phwfmt and rhwfmt must not be NULL regardless of setmode.
* - On non-independent devices, phwfmt and rhwfmt must have the same
* parameters.
* - pfil and rfil must be zero-filled.
* If successful,
* - pfil, rfil will be filled with filter information specified by the
* hardware driver if necessary.
* and then returns 0. Otherwise returns errno.
* Must be called without sc_lock held.
*/
static int
audio_hw_set_format(struct audio_softc *sc, int setmode,
const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
audio_filter_reg_t *pfil, audio_filter_reg_t *rfil)
{
audio_params_t pp, rp;
int error;
KASSERT(phwfmt != NULL);
KASSERT(rhwfmt != NULL);
pp = format2_to_params(phwfmt);
rp = format2_to_params(rhwfmt);
if (sc->hw_if->commit_settings) {
error = sc->hw_if->commit_settings(sc->hw_hdl);
if (error) {
mutex_exit(sc->sc_lock);
audio_printf(sc,
"commit_settings failed: errno=%d\n", error);
return error;
}
}
mutex_exit(sc->sc_lock);
return 0;
}
/*
* Fill audio_info structure. If need_mixerinfo is true, it will also
* fill the hardware mixer information.
* Must be called with sc_exlock held and without sc_lock held.
*/
static int
audiogetinfo(struct audio_softc *sc, struct audio_info *ai, int need_mixerinfo,
audio_file_t *file)
{
struct audio_prinfo *ri, *pi;
audio_track_t *track;
audio_track_t *ptrack;
audio_track_t *rtrack;
int gain;
KASSERT(sc->sc_exlock);
ri = &ai->record;
pi = &ai->play;
ptrack = file->ptrack;
rtrack = file->rtrack;
memset(ai, 0, sizeof(*ai));
if (ptrack) {
pi->sample_rate = ptrack->usrbuf.fmt.sample_rate;
pi->channels = ptrack->usrbuf.fmt.channels;
pi->precision = ptrack->usrbuf.fmt.precision;
pi->encoding = ptrack->usrbuf.fmt.encoding;
pi->pause = ptrack->is_pause;
} else {
/* Use sticky parameters if the track is not available. */
pi->sample_rate = sc->sc_sound_pparams.sample_rate;
pi->channels = sc->sc_sound_pparams.channels;
pi->precision = sc->sc_sound_pparams.precision;
pi->encoding = sc->sc_sound_pparams.encoding;
pi->pause = sc->sc_sound_ppause;
}
if (rtrack) {
ri->sample_rate = rtrack->usrbuf.fmt.sample_rate;
ri->channels = rtrack->usrbuf.fmt.channels;
ri->precision = rtrack->usrbuf.fmt.precision;
ri->encoding = rtrack->usrbuf.fmt.encoding;
ri->pause = rtrack->is_pause;
} else {
/* Use sticky parameters if the track is not available. */
ri->sample_rate = sc->sc_sound_rparams.sample_rate;
ri->channels = sc->sc_sound_rparams.channels;
ri->precision = sc->sc_sound_rparams.precision;
ri->encoding = sc->sc_sound_rparams.encoding;
ri->pause = sc->sc_sound_rpause;
}
/*
* XXX There may be different number of channels between playback
* and recording, so that blocksize also may be different.
* But struct audio_info has an united blocksize...
* Here, I use play info precedencely if ptrack is available,
* otherwise record info.
*
* XXX hiwat/lowat is a playback-only parameter. What should I
* return for a record-only descriptor?
*/
track = ptrack ? ptrack : rtrack;
if (track) {
ai->blocksize = track->usrbuf_blksize;
ai->hiwat = track->usrbuf_usedhigh / track->usrbuf_blksize;
ai->lowat = track->usrbuf_usedlow / track->usrbuf_blksize;
}
ai->mode = file->mode;
/*
* For backward compatibility, we have to pad these five fields
* a fake non-zero value even if there are no tracks.
*/
if (ptrack == NULL)
pi->buffer_size = 65536;
if (rtrack == NULL)
ri->buffer_size = 65536;
if (ptrack == NULL && rtrack == NULL) {
ai->blocksize = 2048;
ai->hiwat = ai->play.buffer_size / ai->blocksize;
ai->lowat = ai->hiwat * 3 / 4;
}
if (sc->sc_monitor_port != -1) {
gain = au_get_monitor_gain(sc);
if (gain != -1)
ai->monitor_gain = gain;
}
mutex_exit(sc->sc_lock);
}
return 0;
}
/*
* Return true if playback is configured.
* This function can be used after audioattach.
*/
static bool
audio_can_playback(struct audio_softc *sc)
{
return (sc->sc_pmixer != NULL);
}
/*
* Return true if recording is configured.
* This function can be used after audioattach.
*/
static bool
audio_can_capture(struct audio_softc *sc)
{
return (sc->sc_rmixer != NULL);
}
/*
* Get the afp->index'th item from the valid one of format[].
* If found, stores it to afp->fmt and returns 0. Otherwise return EINVAL.
*
* This is common routines for query_format.
* If your hardware driver has struct audio_format[], the simplest case
* you can write your query_format interface as follows:
*
* struct audio_format foo_format[] = { ... };
*
* int
* foo_query_format(void *hdl, audio_format_query_t *afp)
* {
* return audio_query_format(foo_format, __arraycount(foo_format), afp);
* }
*/
int
audio_query_format(const struct audio_format *format, int nformats,
audio_format_query_t *afp)
{
const struct audio_format *f;
int idx;
int i;
idx = 0;
for (i = 0; i < nformats; i++) {
f = &format[i];
if (!AUFMT_IS_VALID(f))
continue;
if (afp->index == idx) {
afp->fmt = *f;
return 0;
}
idx++;
}
return EINVAL;
}
/*
* This function is provided for the hardware driver's set_format() to
* find index matches with 'param' from array of audio_format_t 'formats'.
* 'mode' is either of AUMODE_PLAY or AUMODE_RECORD.
* It returns the matched index and never fails. Because param passed to
* set_format() is selected from query_format().
* This function will be an alternative to auconv_set_converter() to
* find index.
*/
int
audio_indexof_format(const struct audio_format *formats, int nformats,
int mode, const audio_params_t *param)
{
const struct audio_format *f;
int index;
int j;
for (index = 0; index < nformats; index++) {
f = &formats[index];
if (!AUFMT_IS_VALID(f))
continue;
if ((f->mode & mode) == 0)
continue;
if (f->encoding != param->encoding)
continue;
if (f->validbits != param->precision)
continue;
if (f->channels != param->channels)
continue;
if (f->frequency_type == 0) {
if (param->sample_rate < f->frequency[0] ||
param->sample_rate > f->frequency[1])
continue;
} else {
for (j = 0; j < f->frequency_type; j++) {
if (param->sample_rate == f->frequency[j])
break;
}
if (j == f->frequency_type)
continue;
}
/* Then, matched */
return index;
}
/* Not matched. This should not be happened. */
panic("%s: cannot find matched format\n", __func__);
}
/*
* Get or set hardware blocksize in msec.
* XXX It's for debug.
*/
static int
audio_sysctl_blk_ms(SYSCTLFN_ARGS)
{
struct sysctlnode node;
struct audio_softc *sc;
audio_format2_t phwfmt;
audio_format2_t rhwfmt;
audio_filter_reg_t pfil;
audio_filter_reg_t rfil;
int t;
int old_blk_ms;
int mode;
int error;
node = *rnode;
sc = node.sysctl_data;
error = audio_exlock_enter(sc);
if (error)
return error;
old_blk_ms = sc->sc_blk_ms;
t = old_blk_ms;
node.sysctl_data = &t;
error = sysctl_lookup(SYSCTLFN_CALL(&node));
if (error || newp == NULL)
goto abort;
/*
* Get or set multiuser mode.
*/
static int
audio_sysctl_multiuser(SYSCTLFN_ARGS)
{
struct sysctlnode node;
struct audio_softc *sc;
bool t;
int error;
node = *rnode;
sc = node.sysctl_data;
error = audio_exlock_enter(sc);
if (error)
return error;
t = sc->sc_multiuser;
node.sysctl_data = &t;
error = sysctl_lookup(SYSCTLFN_CALL(&node));
if (error || newp == NULL)
goto abort;
#if defined(AUDIO_DEBUG)
/*
* Get or set debug verbose level. (0..4)
* XXX It's for debug.
* XXX It is not separated per device.
*/
static int
audio_sysctl_debug(SYSCTLFN_ARGS)
{
struct sysctlnode node;
int t;
int error;
node = *rnode;
t = audiodebug;
node.sysctl_data = &t;
error = sysctl_lookup(SYSCTLFN_CALL(&node));
if (error || newp == NULL)
return error;
sc->sc_idle = false;
if (!device_is_active(dv)) {
/* XXX joerg How to deal with a failing resume... */
pmf_device_resume(sc->hw_dev, PMF_Q_SELF);
pmf_device_resume(dv, PMF_Q_SELF);
}
}
#endif
if (sc->sc_pbusy) {
audio_pmixer_halt(sc);
/* Reuse this as need-to-restart flag while suspending */
sc->sc_pbusy = true;
}
if (sc->sc_rbusy) {
audio_rmixer_halt(sc);
/* Reuse this as need-to-restart flag while suspending */
sc->sc_rbusy = true;
}
/*
* During from suspend to resume here, sc_[pr]busy is used as
* need-to-restart flag temporarily. After this point,
* sc_[pr]busy is returned to its original usage (busy flag).
* And note that sc_[pr]busy must be false to call [pr]mixer_start().
*/
if (sc->sc_pbusy) {
/* pmixer_start() requires pbusy is false */
sc->sc_pbusy = false;
audio_pmixer_start(sc, true);
}
if (sc->sc_rbusy) {
/* rmixer_start() requires rbusy is false */
sc->sc_rbusy = false;
audio_rmixer_start(sc);
}
n = 0;
n += snprintf(buf + n, bufsize - n, "%s",
audio_encoding_name(fmt->encoding));
if (fmt->precision == fmt->stride) {
n += snprintf(buf + n, bufsize - n, " %dbit", fmt->precision);
} else {
n += snprintf(buf + n, bufsize - n, " %d/%dbit",
fmt->precision, fmt->stride);
}
snprintf(buf + n, bufsize - n, " %uch %uHz",
fmt->channels, fmt->sample_rate);
}
#endif
KASSERTMSG(ring, "called from %s", where);
audio_diagnostic_format2(where, &ring->fmt);
KASSERTMSG(0 <= ring->capacity && ring->capacity < INT_MAX / 2,
"called from %s: ring->capacity=%d", where, ring->capacity);
KASSERTMSG(0 <= ring->used && ring->used <= ring->capacity,
"called from %s: ring->used=%d ring->capacity=%d",
where, ring->used, ring->capacity);
if (ring->capacity == 0) {
KASSERTMSG(ring->mem == NULL,
"called from %s: capacity == 0 but mem != NULL", where);
} else {
KASSERTMSG(ring->mem != NULL,
"called from %s: capacity != 0 but mem == NULL", where);
KASSERTMSG(0 <= ring->head && ring->head < ring->capacity,
"called from %s: ring->head=%d ring->capacity=%d",
where, ring->head, ring->capacity);
}
}
#endif /* DIAGNOSTIC */
/*
* Mixer driver
*/
/*
* Must be called without sc_lock held.
*/
int
mixer_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
struct lwp *l)
{
struct file *fp;
audio_file_t *af;
int error, fd;
TRACE(1, "flags=0x%x", flags);
error = fd_allocfile(&fp, &fd);
if (error)
return error;
af = kmem_zalloc(sizeof(*af), KM_SLEEP);
af->sc = sc;
af->dev = dev;
mutex_enter(sc->sc_lock);
if (sc->sc_dying) {
mutex_exit(sc->sc_lock);
kmem_free(af, sizeof(*af));
fd_abort(curproc, fp, fd);
return ENXIO;
}
mutex_enter(sc->sc_intr_lock);
SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
mutex_exit(sc->sc_intr_lock);
mutex_exit(sc->sc_lock);
/*
* Add a process to those to be signalled on mixer activity.
* If the process has already been added, do nothing.
* Must be called with sc_exlock held and without sc_lock held.
*/
static void
mixer_async_add(struct audio_softc *sc, pid_t pid)
{
int i;
KASSERT(sc->sc_exlock);
/* If already exists, returns without doing anything. */
for (i = 0; i < sc->sc_am_used; i++) {
if (sc->sc_am[i] == pid)
return;
}
/*
* Remove a process from those to be signalled on mixer activity.
* If the process has not been added, do nothing.
* Must be called with sc_exlock held and without sc_lock held.
*/
static void
mixer_async_remove(struct audio_softc *sc, pid_t pid)
{
int i;
KASSERT(sc->sc_exlock);
for (i = 0; i < sc->sc_am_used; i++) {
if (sc->sc_am[i] == pid) {
sc->sc_am[i] = sc->sc_am[--sc->sc_am_used];
TRACE(2, "am[%d](%d) removed, used=%d",
i, (int)pid, sc->sc_am_used);
/* Empty array if no longer necessary. */
if (sc->sc_am_used == 0) {
kern_free(sc->sc_am);
sc->sc_am = NULL;
sc->sc_am_capacity = 0;
TRACE(2, "released");
}
return;
}
}
}
/*
* Signal all processes waiting for the mixer.
* Must be called with sc_exlock held.
*/
static void
mixer_signal(struct audio_softc *sc)
{
proc_t *p;
int i;
KASSERT(sc->sc_exlock);
for (i = 0; i < sc->sc_am_used; i++) {
mutex_enter(&proc_lock);
p = proc_find(sc->sc_am[i]);
if (p)
psignal(p, SIGIO);
mutex_exit(&proc_lock);
}
}
/*
* Close a mixer device
*/
int
mixer_close(struct audio_softc *sc, audio_file_t *file)
{
int error;
/*
* Must be called without sc_lock nor sc_exlock held.
*/
int
mixer_ioctl(struct audio_softc *sc, u_long cmd, void *addr, int flag,
struct lwp *l)
{
mixer_devinfo_t *mi;
mixer_ctrl_t *mc;
int val;
int error;
/* we can return cached values if we are sleeping */
if (cmd != AUDIO_MIXER_READ) {
mutex_enter(sc->sc_lock);
device_active(sc->sc_dev, DVA_SYSTEM);
mutex_exit(sc->sc_lock);
}
switch (cmd) {
case FIOASYNC:
val = *(int *)addr;
TRACE(2, "%s FIOASYNC %s", pre, val ? "on" : "off");
error = audio_exlock_enter(sc);
if (error)
break;
if (val) {
mixer_async_add(sc, curproc->p_pid);
} else {
mixer_async_remove(sc, curproc->p_pid);
}
audio_exlock_exit(sc);
break;
if (error)
TRACE(2, "error=%d", error);
return error;
}
/*
* Must be called with sc_lock held.
*/
int
au_portof(struct audio_softc *sc, char *name, int class)
{
mixer_devinfo_t mi;
KASSERT(mutex_owned(sc->sc_lock));
for (mi.index = 0; audio_query_devinfo(sc, &mi) == 0; mi.index++) {
if (mi.mixer_class == class && strcmp(mi.label.name, name) == 0)
return mi.index;
}
return -1;
}
/*
* Must be called with sc_lock held.
*/
void
au_setup_ports(struct audio_softc *sc, struct au_mixer_ports *ports,
mixer_devinfo_t *mi, const struct portname *tbl)
{
int i, j;
/*
* Must be called with sc_lock && sc_exlock held.
*/
int
au_set_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
int gain, int balance)
{
mixer_ctrl_t ct;
int i, error;
int l, r;
u_int mask;
int nset;
if (balance == AUDIO_MID_BALANCE) {
l = r = gain;
} else if (balance < AUDIO_MID_BALANCE) {
l = gain;
r = (balance * gain) / AUDIO_MID_BALANCE;
} else {
r = gain;
l = ((AUDIO_RIGHT_BALANCE - balance) * gain)
/ AUDIO_MID_BALANCE;
}
TRACE(2, "gain=%d balance=%d, l=%d r=%d", gain, balance, l, r);
if (ports->index == -1) {
usemaster:
if (ports->master == -1)
return 0; /* just ignore it silently */
ct.dev = ports->master;
error = au_set_lr_value(sc, &ct, l, r);
} else {
ct.dev = ports->index;
if (ports->isenum) {
ct.type = AUDIO_MIXER_ENUM;
error = audio_get_port(sc, &ct);
if (error)
return error;
if (ports->isdual) {
if (ports->cur_port == -1)
ct.dev = ports->master;
else
ct.dev = ports->miport[ports->cur_port];
error = au_set_lr_value(sc, &ct, l, r);
} else {
for(i = 0; i < ports->nports; i++)
if (ports->misel[i] == ct.un.ord) {
ct.dev = ports->miport[i];
if (ct.dev == -1 ||
au_set_lr_value(sc, &ct, l, r))
goto usemaster;
else
break;
}
}
} else {
ct.type = AUDIO_MIXER_SET;
error = audio_get_port(sc, &ct);
if (error)
return error;
mask = ct.un.mask;
nset = 0;
for(i = 0; i < ports->nports; i++) {
if (ports->misel[i] & mask) {
ct.dev = ports->miport[i];
if (ct.dev != -1 &&
au_set_lr_value(sc, &ct, l, r) == 0)
nset++;
}
}
if (nset == 0)
goto usemaster;
}
}
if (!error)
mixer_signal(sc);
return error;
}
/*
* Must be called with sc_lock && sc_exlock held.
*/
void
au_get_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
u_int *pgain, u_char *pbalance)
{
mixer_ctrl_t ct;
int i, l, r, n;
int lgain, rgain;
/*
* Must be called with sc_lock && sc_exlock held.
*/
int
au_set_port(struct audio_softc *sc, struct au_mixer_ports *ports, u_int port)
{
mixer_ctrl_t ct;
int i, error, use_mixerout;
use_mixerout = 1;
if (port == 0) {
if (ports->allports == 0)
return 0; /* Allow this special case. */
else if (ports->isdual) {
if (ports->cur_port == -1) {
return 0;
} else {
port = ports->aumask[ports->cur_port];
ports->cur_port = -1;
use_mixerout = 0;
}
}
}
if (ports->index == -1)
return EINVAL;
ct.dev = ports->index;
if (ports->isenum) {
if (port & (port-1))
return EINVAL; /* Only one port allowed */
ct.type = AUDIO_MIXER_ENUM;
error = EINVAL;
for(i = 0; i < ports->nports; i++)
if (ports->aumask[i] == port) {
if (ports->isdual && use_mixerout) {
ct.un.ord = ports->mixerout;
ports->cur_port = i;
} else {
ct.un.ord = ports->misel[i];
}
error = audio_set_port(sc, &ct);
break;
}
} else {
ct.type = AUDIO_MIXER_SET;
ct.un.mask = 0;
for(i = 0; i < ports->nports; i++)
if (ports->aumask[i] & port)
ct.un.mask |= ports->misel[i];
if (port != 0 && ct.un.mask == 0)
error = EINVAL;
else
error = audio_set_port(sc, &ct);
}
if (!error)
mixer_signal(sc);
return error;
}
/*
* Must be called with sc_lock && sc_exlock held.
*/
int
au_get_port(struct audio_softc *sc, struct au_mixer_ports *ports)
{
mixer_ctrl_t ct;
int i, aumask;
if (ports->index == -1)
return 0;
ct.dev = ports->index;
ct.type = ports->isenum ? AUDIO_MIXER_ENUM : AUDIO_MIXER_SET;
if (audio_get_port(sc, &ct))
return 0;
aumask = 0;
if (ports->isenum) {
if (ports->isdual && ports->cur_port != -1) {
if (ports->mixerout == ct.un.ord)
aumask = ports->aumask[ports->cur_port];
else
ports->cur_port = -1;
}
if (aumask == 0)
for(i = 0; i < ports->nports; i++)
if (ports->misel[i] == ct.un.ord)
aumask = ports->aumask[i];
} else {
for(i = 0; i < ports->nports; i++)
if (ct.un.mask & ports->misel[i])
aumask |= ports->aumask[i];
}
return aumask;
}
/*
* It returns 0 if success, otherwise errno.
* Must be called only if sc->sc_monitor_port != -1.
* Must be called with sc_lock && sc_exlock held.
*/
static int
au_set_monitor_gain(struct audio_softc *sc, int monitor_gain)
{
mixer_ctrl_t ct;
/*
* It returns monitor gain if success, otherwise -1.
* Must be called only if sc->sc_monitor_port != -1.
* Must be called with sc_lock && sc_exlock held.
*/
static int
au_get_monitor_gain(struct audio_softc *sc)
{
mixer_ctrl_t ct;
if (pnp != NULL) {
arg = aux;
switch (arg->type) {
case AUDIODEV_TYPE_AUDIO:
type = "audio";
break;
case AUDIODEV_TYPE_MIDI:
type = "midi";
break;
case AUDIODEV_TYPE_OPL:
type = "opl";
break;
case AUDIODEV_TYPE_MPU:
type = "mpu";
break;
case AUDIODEV_TYPE_AUX:
type = "aux";
break;
default:
panic("audioprint: unknown type %d", arg->type);
}
aprint_normal("%s at %s", type, pnp);
}
return UNCONF;
}