Skip to contentSkip to conversation

ALSA userspace API complexity

OT Heikki Orsila 7 participants 14 messages Jan 5, 2006 – Jan 10, 2006 1 message not in the archive

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

#1 lore raw
Quoted 6 lines · Alistair John Strachan

On Tuesday 03 January 2006 23:10, Tomasz K?oczko wrote:
2) ALSA API is to complicated: most applications opens single sound stream.

FUD and nonsense. I've written many DSP applications and very often I can recycle the same code for use in them.

It's not FUD and it's very true. I've written ALSA support for many programs and I still can't remember the tricks that are needed to get even basic things working.

Just look at error handling of libao-0.8.6 for a great example how complicated it is to write code for ALSA. The following code is directly from the source:

                /* try to write the entire buffer at once */
                err = internal->writei(internal->pcm_handle, ptr, len);

                /* it's possible that no data was transferred */
                if (err == -EAGAIN) {
                        continue;
                }

                if (err < 0) {
                        /* this might be an error, or an exception */
                        err = alsa_error_recovery(internal, err);
                        if (err < 0) {
                                fprintf(stderr,"ALSA write error: %s\n",
                                                snd_strerror(err));
                                return 0;
                        }

                        /* abandon the rest of the buffer */
                        break;
                }

alsa_error_recovery() expands to 30 lines of more logic. This is pretty insane considering that libao _only_ writes data to device and does nothing else. If ALSA was done properly, the main loop would simply be:

                err = internal->writei(internal->pcm_handle, ptr, len);

                /* it's possible that no data was transferred */
                if (err == -EAGAIN || err == -EINTR) {
                        continue;
                }

		if (err < 0) {
			/* BAD BAD */
		}

When I originally ran into this signal handling brain damage of ALSA, I had to actually look into other programs how they handle signals because ALSA documentation is so bad. The core problem is of course the broken API, not the bad documentation.

A small note, libao can not handle EINTR properly. A patch has been submitted already.

I've long ago stopped using ALSA API because it is broken. But if you wanted to make ALSA usable by real people you might considering adding 3 functions (there are ~300 already so not much loss):

	err = alsa_simple_pcm_open(nchannels, sampleformat, samplingrate, frames_in_period /* 0 for automated default */ );
	err = alsa_simple_writei(); /* handless signal brokeness automagically */
	alsa_simple_close();

Basically ogg123/mpg123 like applications would only need 3 alsa calls. Now everyone reimplementing their own buggy versions of simple mechanisms.

Signature · 3 lines
Heikki Orsila			Barbie's law:
[email protected]		"Math is hard, let's go shopping!"
http://www.iki.fi/shd
#2 lore raw
Quoted 11 lines · Heikki Orsila
Quoted 6 lines · Alistair John Strachan

On Tuesday 03 January 2006 23:10, Tomasz K?oczko wrote:
2) ALSA API is to complicated: most applications opens single sound stream.

FUD and nonsense. I've written many DSP applications and very often I can recycle the same code for use in them.

I've long ago stopped using ALSA API because it is broken. But if you wanted to make ALSA usable by real people you might considering adding 3 functions (there are ~300 already so not much loss):

This sentence makes this in my mind: real people = lazy people. The error codes are documented well. Also, aplay in the alsa-utils package has good error recovery code including test pcm.c utility in alsa-lib.

Quoted 3 lines
	err = alsa_simple_pcm_open(nchannels, sampleformat, samplingrate, frames_in_period /* 0 for automated default */ );
	err = alsa_simple_writei(); /* handless signal brokeness automagically */
	alsa_simple_close();

Well, it's better to create only "fast parameter setup" and "default error recovery" functions.

Quoted 2 lines

Basically ogg123/mpg123 like applications would only need 3 alsa calls. Now everyone reimplementing their own buggy versions of simple mechanisms.

While "official" examples exists for a long time. Also, we already noted that we are not best documentation writers, but everytime when we ask for help we hear nothing from other people.

Jaroslav

-----
Jaroslav Kysela <[email protected]>
Linux Kernel Sound Maintainer
ALSA Project, SUSE Labs

#3 lore raw
Quoted 2 lines · Jaroslav Kysela

On Thu, 5 Jan 2006, Heikki Orsila wrote:
This sentence makes this in my mind: real people = lazy people.

Yes, but it has good reasons too. The real point of userspace libraries and programs rather than kernel space is saving effort. Laziness in programming is good so long as programs are readable and correct.

Your success must be measured according to the number of bugs with ALSA programs and the time used to develop ALSA support for them. Right now it looks very bad to me. Even libao can't handle ALSA well, and knowing some XMMS developers they have hard time with ALSAs complexity. KISS.

Quoted 1 line

The error codes are documented well.

That's a bad excuse for requiring buffer underruns to be handled specially because it's not a fatal error. Errors should be handled as close to the error source as possible, and the ALSA lib is the logical place to handle underrun by default (unless the application really is interested in handling underruns specially). Passing errors through unreasonably many layers causes more complexity for programmers.

Quoted 6 lines
Quoted 3 lines
	err = alsa_simple_pcm_open(nchannels, sampleformat, samplingrate, frames_in_period /* 0 for automated default */ );
	err = alsa_simple_writei(); /* handless signal brokeness automagically */
	alsa_simple_close();

Well, it's better to create only "fast parameter setup" and "default error recovery" functions.

As long as all applications PCM code can be written into 10-20 C lines. That includes: opening device, writing pcm data and closing the device.

Quoted 4 lines
Quoted 2 lines

Basically ogg123/mpg123 like applications would only need 3 alsa calls. Now everyone reimplementing their own buggy versions of simple mechanisms.

While "official" examples exists for a long time.

btw. your official examples don't work on simple PCM playback didn't work when I last time tried. Sorry, I can't remember details because it is so long ago.

Signature · 3 lines
Heikki Orsila			Barbie's law:
[email protected]		"Math is hard, let's go shopping!"
http://www.iki.fi/shd
#4 lore raw
Quoted 9 lines · Heikki Orsila
Quoted 6 lines
Quoted 3 lines
	err = alsa_simple_pcm_open(nchannels, sampleformat, samplingrate, frames_in_period /* 0 for automated default */ );
	err = alsa_simple_writei(); /* handless signal brokeness automagically */
	alsa_simple_close();

Well, it's better to create only "fast parameter setup" and "default error recovery" functions.

As long as all applications PCM code can be written into 10-20 C lines. That includes: opening device, writing pcm data and closing the device.

I've added snd_pcm_set_params() and snd_pcm_recover() functions into alsa-lib (they're a bit experimental and I'm still waiting for any feedback from others).

The "minimal example" can be reached at:

http://cvs.sourceforge.net/viewcvs.py/alsa/alsa-lib/test/pcm_min.c?rev=1.2&view=markup

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Basically ogg123/mpg123 like applications would only need 3 alsa calls. Now everyone reimplementing their own buggy versions of simple mechanisms.

While "official" examples exists for a long time.

btw. your official examples don't work on simple PCM playback didn't work when I last time tried. Sorry, I can't remember details because it is so long ago.

Any bug report? We don't have a crystal ball to fix bugs without any information.

Jaroslav

-----
Jaroslav Kysela <[email protected]>
Linux Kernel Sound Maintainer
ALSA Project, SUSE Labs

#6 lore raw
In reply to Jaroslav Kysela
Quoted 2 lines · Jaroslav Kysela

This sentence makes this in my mind: real people = lazy people. The error codes are documented well.

Actual alsa reference documentation:

int snd_pcm_prepare(snd_pcm_t *pcm)

Prepare PCM for use.

Parameters:
pcm PCM handle

Returns:
0 on success otherwise a negative error code

[Beautifully documented error codes and causes]

snd_pcm_sframes_t snd_pcm_writei(snd_pcm_t * pcm,

		const void *buffer,
		snd_pcm_uframes_t size
	)  	

Write interleaved frames to a PCM.

Parameters:
pcm PCM handle
buffer frames containing buffer
size frames to be written

Returns:
a positive number of frames actually written otherwise a negative error code

Return values:
-EBADFD PCM is not in the right state (SND_PCM_STATE_PREPARED or SND_PCM_STATE_RUNNING)
-EPIPE an underrun occurred
-ESTRPIPE a suspend event occurred (stream is suspended and waiting for an application recovery)

If the blocking behaviour is selected, then routine waits until all requested bytes are played or put to the playback ring buffer. The count of bytes can be less only if a signal or underrun occurred.

If the non-blocking behaviour is selected, then routine doesn't wait at all.

[Count of bytes less than the frame count when an underrun, which returns -EPIPE, happened? -EBADFD when the state is XRUN (not it doesn't)? Cause and handling of suspend events?]

Anybody who says the alsa documentation is good never had to use it. At that point I know my simple playing code is incorrect and I have no clue on how to fix it.

Quoted 2 lines

Also, aplay in the alsa-utils package has
good error recovery code including test pcm.c utility in alsa-lib.

A sleep(1) in the error recovery path? Are you people nuts?

Incidentally:

- "A small demo which sends a simple sinusoidal wave to the speakers" requiring close to 900 lines is demented. That's the size of glxgears.c, with 50% of that one being printer support. A complete smartflow example getting a sound stream on the network and playing it with oss takes 160 lines, with 20 lines of copyright-ish at the start. The actual sound part of that is _30_ lines.

- Error and state handling after writei changes depending on the call. We're supposed to guess which one is correct?

Make simple things simple, guys.

OG.

#7 lore raw
Quoted 1 line · Olivier Galibert

Make simple things simple, guys.

Sorry for hijacking the thread, but it is very true. ALSA is just too flexible so that the ALSA equivalent (if it indeed exists) of http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=339951 cannot be fixed. OSS allows specification of device name, and one can set up udev rules so that e.g. /dev/dsp-creative it is always a symlink to a SB PCI sound card and /dev/dsp-fortemedia is for FM801. Then one can tell xine to play sound through /dev/dsp-fortemedia. ALSA accepts only numbers in its plughw:x,y,z notation, and applications are unfixable when kernel device numbers become random.

Signature · 1 line
Alexander E. Patrakov
#8 lore raw
Quoted 4 lines · Alexander E. Patrakov
Quoted 1 line · Olivier Galibert

Make simple things simple, guys.

Quoted 8 lines

Sorry for hijacking the thread, but it is very true. ALSA is just too flexible so that the ALSA equivalent (if it indeed exists) of
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=339951 cannot be fixed. OSS allows specification of device name, and one can set up udev rules so that e.g. /dev/dsp-creative it is always a symlink to a SB PCI sound card and /dev/dsp-fortemedia is for FM801. Then one can tell xine to play sound through /dev/dsp-fortemedia. ALSA accepts only numbers in its plughw:x,y,z notation, and applications are unfixable when kernel device numbers become random.

It's not true. You can also use plughw:CARDID,0 or so notation. Identification of cards are available via control interface or look to /proc/asound/cards file. The card ID string can be set via a module option. Also you can fix the card index numbers with a module option.

Jaroslav

-----
Jaroslav Kysela <[email protected]>
Linux Kernel Sound Maintainer
ALSA Project, SUSE Labs

#9 lore raw
Quoted 3 lines · Jaroslav Kysela

You can also use plughw:CARDID,0 or so notation.

Thanks, it works here indeed.

Quoted 5 lines

Identification of cards are available via control interface or look to /proc/asound/cards file. The card ID string can be set via a module option. Also you can fix the card index numbers with
a module option.

The point here is that virtually every other subsystem can use udev to rename devices and/or create symlinks. For ALSA, an ALSA-specific solution has to be used. Although, I admit that udev offers nothing over this solution for my sound card.

Signature · 1 line
Alexander E. Patrakov
#10 lore raw
In reply to Alexander E. Patrakov
Quoted 4 lines · On Thu, 05 Jan 2006 20:26:36 +0500 "Alexander E. Patrakov"…
Quoted 1 line · Olivier Galibert

Make simple things simple, guys.

Quoted 9 lines

Sorry for hijacking the thread, but it is very true. ALSA is just too flexible so that the ALSA equivalent (if it indeed exists) of
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=339951 cannot be fixed. OSS allows specification of device name, and one can set up udev rules so that e.g. /dev/dsp-creative it is always a symlink to a SB PCI sound card and /dev/dsp-fortemedia is for FM801. Then one can tell xine to play sound through /dev/dsp-fortemedia. ALSA accepts only numbers in its plughw:x,y,z notation, and applications are unfixable when kernel device numbers become random.

maybe i misunderstood your point, but:

a] every alsa driver can have an option "index" which tells it what card number to grab, so either pass it as module load option or at kernel boot time..

b] applications should actually allow the user to enter _any_ string as a device name (well "any" is actually too much). This enables the user to define his own pcm devices (i.e. using alsa pcm LADSPA plugin) and use these in any native ALSA app.

There's all kind of nifty predefined pcm device definitions available, as i.e. "surround50", "surround51", etc.. One can even indicate what card number to use, i.e. "surround50:0" or "surround50:2" (for the first and third card in the system respectively). The special name "!default" can also be overridden easily to make any sane and well programmed ALSA app use a certain pcm device of the user's choice.

If i completely missed your point -> sorry

Flo

Signature · 2 lines
Palimm Palimm!
http://tapas.affenbande.org
#11 lore raw
In reply to Olivier Galibert
Quoted 6 lines · Olivier Galibert

- "A small demo which sends a simple sinusoidal wave to the speakers" requiring close to 900 lines is demented. That's the size of glxgears.c, with 50% of that one being printer support. A complete smartflow example getting a sound stream on the network and playing it with oss takes 160 lines, with 20 lines of copyright-ish at the start. The actual sound part of that is _30_ lines.

The pcm.c file shows you 7 available methods how you can send audio data to alsa-lib. It's complete example. If you remove the parsing command line, sine generation, error handling, you'll end with few lines too.

Quoted 4 lines

- Error and state handling after writei changes depending on the call. We're supposed to guess which one is correct?

Make simple things simple, guys.

Yes, we should stay with simple 1.0 linux kernel. Anyway, we're taking all points from this discussion.

Jaroslav

-----
Jaroslav Kysela <[email protected]>
Linux Kernel Sound Maintainer
ALSA Project, SUSE Labs

#12 lore raw
Quoted 3 lines · Jaroslav Kysela
Quoted 1 line

Make simple things simple, guys.

Yes, we should stay with simple 1.0 linux kernel.

This blatant attempt to defend a broken subsystem by "analogy" fails because last time I checked the semantics of system calls like read/write/open/close didn't change significantly between kernel version 1.0 and 2.6.15.

The number of system calls didn't change that much as well.

Yes it may be true that some aggregation of exhaustive crappy interfaces over time in the kernel can be indeed observed. However the very fact which makes it remain still usable are precisely those very "primitive" system calls - which are still around and kicking.

#13 lore raw
In reply to Jaroslav Kysela
Quoted 5 lines · Jaroslav Kysela
Quoted 1 line · Heikki Orsila
	err = alsa_simple_pcm_open(nchannels, sampleformat, samplingrate, frames_in_period /* 0 for automated default */ );

Well, it's better to create only "fast parameter setup" and "default error recovery" functions.

And what would it look like? I would prefer all functions being alsa_simple_* because a user could read interface documentation alphabetically and see all the relevant functions as they are adjacent.

I would correct my earlier 'frames_in_period' to 'latency_in_frames' because most users are not interested in period size. Latency on the other hand matters. 10ms latency would just be samplingrate / 100 and the ALSA lib would choose good approximate period/buffer sizes internally. Those who need something better should just use the old way.

Signature · 3 lines
Heikki Orsila			Barbie's law:
[email protected]		"Math is hard, let's go shopping!"
http://www.iki.fi/shd
#14 lore raw
In reply to Heikki Orsila

Firstly, trimming CCs is quite rude and makes it very difficult for others to address your problems.

Quoted 11 lines · Heikki Orsila
Quoted 6 lines · Alistair John Strachan

On Tuesday 03 January 2006 23:10, Tomasz K?oczko wrote:
2) ALSA API is to complicated: most applications opens single sound stream.

FUD and nonsense. I've written many DSP applications and very often I can recycle the same code for use in them.

It's not FUD and it's very true. I've written ALSA support for many programs and I still can't remember the tricks that are needed to get even basic things working.

They're not really tricks, they're allowing developers to flexibly handle cases that they may care about, such as momentary communication problems (think USB soundcards, headsets), versus unrecoverable errors. For example, the code I wrote handles your example below somewhat more easily:

	// try to play data
	for (i = 0; i < PLAYBACK_RETRIES; i++) {
		if ((err = snd_pcm_writei (card->playback.fd, card->buffer, card->frames)) < 
0) {
			adebug ("Had to re-init playback.\n");
			if ((err = snd_pcm_prepare (card->playback.fd)) < 0)
				return -PCM_PREPARATION_FAILED;
		}
		break;
	}

	// we couldn't reprepare
	if (i == PLAYBACK_RETRIES)
		return -PCM_WRITE_FAILED;

	return ALSA_SUCCESS;

PLAYBACK_RETRIES is arbitrary. Less robust software, or programs that were very sensitive to any sort of intermittent unavailability would error out immediately, without the for loop.

However, the documentation makes it fairly clear that in the case where a writei() fails, you must "re-prepare" the card for PCM IO. This can be attempted numerous times before giving up.

I agree that some sort of layman's wrapper might be helpful here, but please don't go back to the ways of a crippled OSS API by preventing us from handling these cases

Quoted 3 lines

alsa_error_recovery() expands to 30 lines of more logic. This is pretty insane considering that libao _only_ writes data to device and does nothing else. If ALSA was done properly, the main loop would simply be:

This is ridiculous. Why bother? If libao is so simple, just break out if re-preparation fails.

Quoted 11 lines
                err = internal->writei(internal->pcm_handle, ptr, len);

                /* it's possible that no data was transferred */
                if (err == -EAGAIN || err == -EINTR) {
                        continue;
                }

		if (err < 0) {
			/* BAD BAD */
		}

This looks suspiciously like what I have above. Clear, simple, non-broken. ALSA does it already.

Quoted 4 lines

err = alsa_simple_pcm_open(nchannels, sampleformat, samplingrate,
frames_in_period /* 0 for automated default */ ); err = alsa_simple_writei(); /* handless signal brokeness automagically */ alsa_simple_close();

simple_{open,setup}() I agree with. There's no reason for that to have to be a whole stack of separate functions. Use return codes to indicate the type of failure.

simple_writei() might be okay, but it's pretty inflexible for even mildly complex problems requiring more than "just write data". The old mechanisms need to persist.

simple_close(), uhm.. snd_pcm_close (fd). Don't need it. I'm not sure why you think that is necessary.

Signature · 6 lines
Cheers,
Alistair.

'No sense being pessimistic, it probably wouldn't work anyway.'
Third year Computer Science undergraduate.
1F2 55 South Clerk Street, Edinburgh, UK.