EEVblog Electronics Community Forum

Products => Computers => Programming => Topic started by: RoGeorge on July 13, 2022, 09:22:29 pm

Title: Audio in Linux
Post by: RoGeorge on July 13, 2022, 09:22:29 pm
I've built a small circuit of an LC sinusoidal audio oscillator, and I would like to use the "line-in" from the desktop's sound card in order to measure the signal's distortions.

Found two programs that can do this, 'ARTA' https://artalabs.hr/ (https://artalabs.hr/) (a Windows program run in Linux through WineHQ) and a Linux native one called 'baudline' https://www.baudline.com/ (https://www.baudline.com/) but I don't understand the audio signal path in Linux.

So far I've kept googling and installing all kind of tools and making a mess mixture of ALSA, Pulse-Audio and Jack-Audio, but I don't know any of these or what's the idea.

1. - How do I route the audio signal from the 'line-in' of the sound card (Creative CA0132)?
2. - Where can I learn about sound in KDE Plasma (Kubuntu 20.04), so to understand what to do?
3. - How can I read the raw/unaltered ADC data from the line-in, preferably in Python for easier postprocessing?


Trying to list the soundcards:
Code: [Select]
#!/usr/bin/env python3

# if pyaudio not present, install it with
#       sudo apt install python3-pyaudio
import pyaudio as pa

print()
p = pa.PyAudio()

print("print PyAudio():\n", p)
print("devices:n")
for i in range(p.get_device_count()):
    #pass
    print( p.get_device_info_by_index(i) )

# if sounddevice not present, install it with
#       pip install sounddevice
import sounddevice as sd

print()
print("print sounddevice.query_devices():\n")
print(sd.query_devices())


it returns

Code: [Select]
ALSA lib pcm_dsnoop.c:641:(snd_pcm_dsnoop_open) unable to open slave
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_dmix.c:1089:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
print PyAudio():
 <pyaudio.PyAudio object at 0x7faa79323430>
devices:n
{'index': 0, 'structVersion': 2, 'name': 'HDA Intel HDMI: 0 (hw:0,3)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 1, 'structVersion': 2, 'name': 'HDA Intel HDMI: 1 (hw:0,7)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 2, 'structVersion': 2, 'name': 'HDA Intel HDMI: 2 (hw:0,8)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 3, 'structVersion': 2, 'name': 'HDA Intel HDMI: 3 (hw:0,9)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 4, 'structVersion': 2, 'name': 'HDA Intel HDMI: 4 (hw:0,10)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 5, 'structVersion': 2, 'name': 'HDA Intel PCH: CA0132 Analog (hw:1,0)', 'hostApi': 0, 'maxInputChannels': 2, 'maxOutputChannels': 0, 'defaultLowInputLatency': 0.008707482993197279, 'defaultLowOutputLatency': -1.0, 'defaultHighInputLatency': 0.034829931972789115, 'defaultHighOutputLatency': -1.0, 'defaultSampleRate': 44100.0}
{'index': 6, 'structVersion': 2, 'name': 'HDA Intel PCH: CA0132 Digital (hw:1,1)', 'hostApi': 0, 'maxInputChannels': 2, 'maxOutputChannels': 2, 'defaultLowInputLatency': 0.008707482993197279, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': 0.034829931972789115, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 7, 'structVersion': 2, 'name': 'HDA Intel PCH: CA0132 Analog Mic-In2 (hw:1,2)', 'hostApi': 0, 'maxInputChannels': 2, 'maxOutputChannels': 0, 'defaultLowInputLatency': 0.008707482993197279, 'defaultLowOutputLatency': -1.0, 'defaultHighInputLatency': 0.034829931972789115, 'defaultHighOutputLatency': -1.0, 'defaultSampleRate': 44100.0}
{'index': 8, 'structVersion': 2, 'name': 'HDA Intel PCH: CA0132 What U Hear (hw:1,4)', 'hostApi': 0, 'maxInputChannels': 2, 'maxOutputChannels': 0, 'defaultLowInputLatency': 0.008707482993197279, 'defaultLowOutputLatency': -1.0, 'defaultHighInputLatency': 0.034829931972789115, 'defaultHighOutputLatency': -1.0, 'defaultSampleRate': 44100.0}
{'index': 9, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 0 (hw:2,3)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 10, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 1 (hw:2,7)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 11, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 2 (hw:2,8)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 2, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 12, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 3 (hw:2,9)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 13, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 4 (hw:2,10)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 14, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 5 (hw:2,11)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 15, 'structVersion': 2, 'name': 'HDA NVidia: HDMI 6 (hw:2,12)', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 16, 'structVersion': 2, 'name': 'hdmi', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 8, 'defaultLowInputLatency': -1.0, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': -1.0, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 17, 'structVersion': 2, 'name': 'pulse', 'hostApi': 0, 'maxInputChannels': 32, 'maxOutputChannels': 32, 'defaultLowInputLatency': 0.008707482993197279, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': 0.034829931972789115, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}
{'index': 18, 'structVersion': 2, 'name': 'default', 'hostApi': 0, 'maxInputChannels': 32, 'maxOutputChannels': 32, 'defaultLowInputLatency': 0.008707482993197279, 'defaultLowOutputLatency': 0.008707482993197279, 'defaultHighInputLatency': 0.034829931972789115, 'defaultHighOutputLatency': 0.034829931972789115, 'defaultSampleRate': 44100.0}

print sounddevice.query_devices():

   0 HDA Intel HDMI: 0 (hw:0,3), ALSA (0 in, 8 out)
   1 HDA Intel HDMI: 1 (hw:0,7), ALSA (0 in, 8 out)
   2 HDA Intel HDMI: 2 (hw:0,8), ALSA (0 in, 8 out)
   3 HDA Intel HDMI: 3 (hw:0,9), ALSA (0 in, 8 out)
   4 HDA Intel HDMI: 4 (hw:0,10), ALSA (0 in, 8 out)
   5 HDA Intel PCH: CA0132 Analog (hw:1,0), ALSA (2 in, 0 out)
   6 HDA Intel PCH: CA0132 Digital (hw:1,1), ALSA (2 in, 2 out)
   7 HDA Intel PCH: CA0132 Analog Mic-In2 (hw:1,2), ALSA (2 in, 0 out)
   8 HDA Intel PCH: CA0132 What U Hear (hw:1,4), ALSA (2 in, 0 out)
   9 HDA NVidia: HDMI 0 (hw:2,3), ALSA (0 in, 8 out)
  10 HDA NVidia: HDMI 1 (hw:2,7), ALSA (0 in, 8 out)
  11 HDA NVidia: HDMI 2 (hw:2,8), ALSA (0 in, 2 out)
  12 HDA NVidia: HDMI 3 (hw:2,9), ALSA (0 in, 8 out)
  13 HDA NVidia: HDMI 4 (hw:2,10), ALSA (0 in, 8 out)
  14 HDA NVidia: HDMI 5 (hw:2,11), ALSA (0 in, 8 out)
  15 HDA NVidia: HDMI 6 (hw:2,12), ALSA (0 in, 8 out)
  16 hdmi, ALSA (0 in, 8 out)
  17 pulse, ALSA (32 in, 32 out)
* 18 default, ALSA (32 in, 32 out)


The audio back panel has the following connectors, I'm using only the analog mini-jack inputs:
Quote
Central / Bass (Orange)
Rear Speaker (Black)
Line In (Light Blue)
Front Speaker (Lime)**
Microphone (Pink)

Optical SPDIF Out Port

Chipset:  Creative Sound Core 3D (CA0132), apparently 24 bits !?! (4-channel 24-bits 101dB analog-to-digital converters)  https://sg.creative.com/corporate/pressroom?id=13233 (https://sg.creative.com/corporate/pressroom?id=13233)

7.1 CH HD Audio
Supports Surge Protection (ASRock Full Spike Protection)
Nichicon Fine Gold Series Audio Caps
Creative Sound Core3D quad-core sound and voice processor
Supports SBX Pro Studio
Supports CrystalVoice
Supports Scout Mode
Supports EAX1.0 to EAX5.0
Premium Headset Amplifier (PHA)
Title: Re: Audio in Linux
Post by: mag_therm on July 13, 2022, 09:54:45 pm
To me it is an  awful mess, but I have persisted with it until I got it working fairly well for ham radio digital modes.

You have mentionsd some  main ones I use. My comments following, assume you will use jackctl as the master or core app.
There maybe other ways that I don't know.

alsamixer is opened as user in a terminal.
If press F6 in alsamixer, it will show all you sound cards and allow to select gains of them.
You will need "mic and "mic boost" and I set them to 0dB. That seems to allow things like equalizers and spectrum analysers to run at
 0db = -20dBFS

 
Then try to install jackctl. This has a GUI, and fortunately recently a graphic display has been added which allows to pull cable between objects. When installed, jackctl will have an entry in sound menu. Without that new GUI, "GRAPH-jackctl" I can't understand how the connections are set up.

Unfortunately if you are of a certain age like me, it is very confusing. What I would call an INPUT eg a signal into the mic socket,is called an OUTPUT or a SINK. What I would call an OUTPUT, eg signal out to a speaker, is called an INPUT or a SOURCE.
Anyway once you get the jackctl GUI going open "GRAPH-jackctl" and you can make connections.

jackctl is the core, and once working, other apps like calf, or jiaa spectrum analyser will connect themselves  to jackctl when they are opened.
Then you can pull cables from say a system input, to a spectrum analyser, or a sound card output etc

To get jackctl you might have to make a config file, it was needed here. There is very little doc about it. Try to get jackctl running first  and see what happens.
Title: Re: Audio in Linux
Post by: SiliconWizard on July 13, 2022, 10:04:10 pm
I've personally used ALSA exclusively under Linux. There are a few sample programs from the ALSA project that will get you started. https://www.alsa-project.org/alsa-doc/alsa-lib/examples.html (https://www.alsa-project.org/alsa-doc/alsa-lib/examples.html)

But apparently you want to use Python, so I don't know anything about audio with Python.
But you could just record audio using a separate program and then process it with Python. If so, use any program that supports audio recording, and then just read the files with Python.

You can use 'aplay -L' to list all available ALSA devices.
Title: Re: Audio in Linux
Post by: ve7xen on July 14, 2022, 12:33:58 am
There is some overlap in capabilities, but in modern Linux it basically goes like:

ALSA is the kernel interface to the audio hardware, and a common API for audio I/O
PulseAudio is the sound server that does mixing and routing. Applications either talk directly to Pulse through its own API, or through its ALSA compatibility layer. Typically the default ALSA devices on a modern system will route to Pulse, rather than directly to audio hardware.

JACK is typically only used in high-performance applications like live audio, it has similar capabilities to PulseAudio, but is less appropriate for typical desktop use and can only handle one hardware device.

If you don't want to use a GUI application that will just let you select the input you want to record, you can set the default recording device in System Settings -> Audio. You can install/use PaVuControl to monitor levels and do live rerouting of applications currently recording / playing audio.

To record raw data from the ADCs, you can use arecord -D <device name from arecord -L> file.wav, but you will probably need to stop pulseaudio first (systemctl --user stop pulseaudio.socket && systemctl --user stop pulseaudio.service) so it can open the device directly. Or use PyAudio or some other sound API like SDL or PyGame.
Title: Re: Audio in Linux
Post by: NiHaoMike on July 14, 2022, 02:11:29 am
Take a look at Pipewire, which is designed to replace both Pulseaudio and JACK.
https://pipewire.org/
Title: Re: Audio in Linux
Post by: magic on July 14, 2022, 07:36:07 am
You use ALSA of course. List available input interfaces (aplay will do the same for the outputs).
Code: [Select]
$ arecord -l
**** List of CAPTURE Hardware Devices ****
card 0: SB [HDA ATI SB], device 0: ALC892 Analog [ALC892 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: SB [HDA ATI SB], device 2: ALC892 Alt Analog [ALC892 Alt Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 3: STX [Xonar STX], device 0: Multichannel [Multichannel]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 3: STX [Xonar STX], device 1: Digital [Digital]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

Record raw data from card 3, device 1 (Xonar STX Digital), default subdevice (not like you have much choice).
Code: [Select]
$ arecord output.wav -D hw:3,1
Recording WAVE 'stdin' : Unsigned 8 bit, Rate 8000 Hz, Mono
arecord: set_params:1343: Sample format non available
Available formats:
- S16_LE
- S32_LE

Okay, it wants sample format specification (and then sample rate and channel count).
Code: [Select]
$ arecord output.wav -D hw:3,1 -f S32_LE -c 2 -r 96000
Recording WAVE 'output.wav' : Signed 32 bit Little Endian, Rate 96000 Hz, Stereo

If you get some "resource busy" errors, make sure nothing is trying to play/record sound, if it persists then
Code: [Select]
killall pulseaudio
rm /usr/bin/pulseaudio
killall -9 pulseaudio
killall systemd
find /usr/ -name *systemd* -exec rm -rf {} \;
ps a |grep systemd |cut -f 1 |xargs kill -9
and so on, until it works ;D

edit
This can tell you which processes (PIDs) use ALSA devices. Here, something has opened the mixer interface of card 3.
Code: [Select]
fuser /dev/snd/*
/dev/snd/controlC3:  79232
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 07:44:50 am
My dear folks...

We are under Unix..   everything is just a file and not some obscure cryptic registry key

That said.. we just do
 
cat /dev/audio > file.raw
Or whatever input..
And we do use mkfifo for that

Alsa arecord is a nice wrap for that
Recommended

It is simple as that
Paul
Title: Re: Audio in Linux
Post by: magic on July 14, 2022, 08:30:54 am
It's not Unix but Loonix and ALSA is not so simple.
Code: [Select]
$ cat /dev/snd/pcmC0D0c 
cat: /dev/snd/pcmC0D0c: File descriptor in bad state

But it works.

BTW, I suppose that there is a Python library to access ALSA devices, or you could call arecord from Python ;)
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 09:13:42 am
It's not Unix but Loonix and ALSA is not so simple.
Code: [Select]
$ cat /dev/snd/pcmC0D0c 
cat: /dev/snd/pcmC0D0c: File descriptor in bad state

But it works.

BTW, I suppose that there is a Python library to access ALSA devices, or you could call arecord from Python ;)

If you are having device node issues...

Mksure  systemd is out of the way...  systemd is garbage.

The proper device nodes for  Audio and MIDI should be

Code: [Select]
crw-rw-rw- 1 root root  14,  14 Aug 30  2020 admmidi0
crw-rw-rw- 1 root root  14,  30 Aug 30  2020 admmidi1
crw-rw-rw- 1 root root  14,  46 Aug 30  2020 admmidi2
crw-rw-rw- 1 root root  14,  62 Aug 30  2020 admmidi3
lrwxrwxrwx 1 root root       10 Nov 21  2020 adsp -> /dev/adsp0
crw-rw-rw- 1 root root  14,  12 Aug 30  2020 adsp0
crw-rw-rw- 1 root root  14,  28 Aug 30  2020 adsp1
crw-rw-rw- 1 root root  14,  44 Aug 30  2020 adsp2
crw-rw-rw- 1 root root  14,  60 Aug 30  2020 adsp3
lrwxrwxrwx 1 root root       11 Nov 21  2020 amidi -> /dev/amidi0
crw-rw-rw- 1 root root  14,  13 Aug 30  2020 amidi0
crw-rw-rw- 1 root root  14,  29 Aug 30  2020 amidi1
crw-rw-rw- 1 root root  14,  45 Aug 30  2020 amidi2
crw-rw-rw- 1 root root  14,  61 Aug 30  2020 amidi3
crw-rw-rw- 1 root root  14,  11 Aug 30  2020 amixer0
crw-rw-rw- 1 root root  14,  27 Aug 30  2020 amixer1
crw-rw-rw- 1 root root  14,  43 Aug 30  2020 amixer2
crw-rw-rw- 1 root root  14,  59 Aug 30  2020 amixer3
lrwxrwxrwx 1 root root       11 Nov 21  2020 audio -> /dev/audio0
crw-rw-rw- 1 root root  14,   4 Aug 30  2020 audio0
crw-rw-rw- 1 root root  14,  20 Aug 30  2020 audio1
crw-rw-rw- 1 root root  14,  36 Aug 30  2020 audio2
crw-rw-rw- 1 root root  14,  52 Aug 30  2020 audio3


ALSA DCONF objects can do magic with these...

I use them all the time including MIDI routing for JACK

Not necessarily with these wide open permissions
Paul
Title: Re: Audio in Linux
Post by: magic on July 14, 2022, 09:18:32 am
The files you listed are part of OSS emulation, if you have it enabled on your system.
They can be used by simply reading/writing them, but you still need ioctl to set the sample rate and format.
Might as well use ALSA through their library or command line tools.

ALSA files are those in /dev/snd/. I'm sure they work similarly to OSS with read/write/ioctl, but the only officially supported way of accessing them is through libasound.
Title: Re: Audio in Linux
Post by: DiTBho on July 14, 2022, 09:23:24 am
We are under Unix..   everything is just a file and not some obscure cryptic registry key

the only thing that matters is the kernel driver and how it exports the resource to the userspace.

Some old OSS drivers export exactly like you said /dev/snd/...
Some new ALSA do not
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 09:24:26 am
From my own  results  it is the best method.

OSS layer can convert automatically several issues with clock synch and other problems

Use a clean and lean OSS emulation layer over a proper defined DCONF routing

It never failed.
I routes 16 tracks of MIDI and AUDIO under Ardour over JACK with proper DCONF

Have  it working for decade over
Paul

PS BTW -- i use cheap common  hardware for that - nothing exotic
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 09:25:32 am
We are under Unix..   everything is just a file and not some obscure cryptic registry key

the only thing that matters is the kernel driver and how it exports the resource to the userspace.

Some old OSS drivers export exactly like you said /dev/snd/...
Some new ALSA do not

Ditch SYSTEMD and do yourself a proper device node as you need it

It never failed a single byte with my workstations

Paul
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 09:32:17 am
We are under Unix..   everything is just a file and not some obscure cryptic registry key

the only thing that matters is the kernel driver and how it exports the resource to the userspace.

Some old OSS drivers export exactly like you said /dev/snd/...
Some new ALSA do not

Ditch SYSTEMD and do yourself a proper device node as you need it

It never failed a single byte with my workstations

Paul


LAST but not least....

If you need some specific output feed..

MKFIFO over a SOX PIPE..

It can literally  do anything for you

Paul
Title: Re: Audio in Linux
Post by: DiTBho on July 14, 2022, 09:36:07 am
Quote
OSS emulation

Yup, exactly. Not all the sound cards have OSS emulation.

Quote
reading/writing them, but you still need ioctl to set the sample rate and format.

Yup. On my HPPA workstation I was so tired of dealing with an Alsa-only driver that I re-implemented the whole audio-module (of the built-in, on the motherboard, audio circuit) to directly export the configuration and the data-block

/dev/snd0/dataL
/dev/snd0/dataR
/dev/snd0/ctrl

This way is super simple and you can control everything from Bash (echo "$mode $sound_ctrl_bits" > /dev/snd0/ctrl) as well as grabbing data blocks (left channel cat /dev/snd0/dataL, right channel /dev/snd0/dataR), however this way it's incompatible with everything else and I cannot play any mp3 on it without modifying other software, which I simply don't care because I use the audio-card to save and load files to/from an home made (micro)tape-unit.


So, here advice are:
- try OSS, if it's supported
- otherwise buy a USB Cypress SCOPE supported by Sigrock and use libusb to manually control it
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 09:41:25 am
Quote
OSS emulation

Yup, exactly. Not all the sound cards have OSS emulation.


Have you bothered to compile them ??
or look wtf mess systemd distro made ?

Check them
snd-mixer-oss.ko
snd-pcm-oss.ko

and recompile them  just in case
it never missed ... so far...

bu you know... POTTERRRRRIX made a messy way under a job for him

Paul
Title: Re: Audio in Linux
Post by: DiTBho on July 14, 2022, 09:48:42 am
Ditch SYSTEMD and do yourself a proper device node as you need it

I neither like nor use SystemD, but in this specific case SystemD doesn't matter, neither it matters "device names": if the kernel module doesn't support OSS emulation, you only have ALSA support.

Like in my HPPA workstation, I had three choices:

It only took me two weeks to re-implement the driver, which in this case is very simple, so the advantage is that I have full control of everything I need without needing to Google for documentation, examples, etc, about Alsa and her friends.
Title: Re: Audio in Linux
Post by: DiTBho on July 14, 2022, 09:52:44 am
(a "USB sound card" wasn't an option in my case, but someone might consider it.
There are some whose kernel module supports OSS emulation)
Title: Re: Audio in Linux
Post by: PKTKS on July 14, 2022, 09:54:03 am
Hmm never found such crippled hardware...

But  indeed found some really bad ones... bad clock bad response..

The 2nd item is my solution.

Have 3 boxes of SB ready for that ... but today.. i have not needed them even with proprietary HDA audio chipsets...  it was like that over 2000s with bad chips..

SB always solved the issue


we do have choices..  the method however is still OSS as a good convert layer
Paul

PS for the record...

A small ultra simple DCONF (Device ALSA config)  defaults capture to
Code: [Select]
pcm.!default {
type asym
playback.pcm {
type plug
slave.pcm "monitor"
}
capture.pcm {
type plug
slave.pcm "hw:0,0"
}
}

it may be easily re routed to OSS layer from the digital (SPDIF for example) via dmix plugin
Code: [Select]
pcm.dsp0 monitor
pcm.dsp {
type plug
slave.pcm "dmix"
}

that method can do magic with your clock and synch problems..
The full complete DCONF depends on each hardware on the system..
but you got the point by now
Title: Re: Audio in Linux
Post by: ve7xen on July 14, 2022, 06:26:49 pm
Code: [Select]
killall pulseaudio
rm /usr/bin/pulseaudio
killall -9 pulseaudio
killall systemd
find /usr/ -name *systemd* -exec rm -rf {} \;
ps a |grep systemd |cut -f 1 |xargs kill -9
and so on, until it works ;D

Can we not, even in jest, suggest commands that will completely break someone's system in a difficult to recover way?

Disabling Pulse, should you want to do so, does not require such wanton irreversible measures.

I don't know why any thread asking for help with Linux devolves into an anti-systemd holy war. You are not helping the OP at all, and are just making them either break their system or go down a rabbit hole of niche distros for literally no benefit. They are using Kubuntu. Kubuntu is a systemd distribution. Help them within those confines or go elsewhere to complain about systemd and pulseaudio.
Title: Re: Audio in Linux
Post by: james_s on July 14, 2022, 07:02:47 pm
I have no problem with people complaining about systemd, it is garbage and created difficulty and confusion where there was none before. On a day to day basis the part I absolutely hate is the idiotic binary logging. The standard text logging was so simple and so easy to tail, it could be copied easily, recovered from a damaged drive,  etc, it just worked. I think people should complain about it as much as possible because maybe then those that manage distros will be less likely to jump onto that bandwagon.
Title: Re: Audio in Linux
Post by: ve7xen on July 14, 2022, 07:26:57 pm
I have no problem with people complaining about systemd, it is garbage and created difficulty and confusion where there was none before. On a day to day basis the part I absolutely hate is the idiotic binary logging. The standard text logging was so simple and so easy to tail, it could be copied easily, recovered from a damaged drive,  etc, it just worked. I think people should complain about it as much as possible because maybe then those that manage distros will be less likely to jump onto that bandwagon.

The ship sailed years ago, and frankly systemd has homogenized a lot of things that used to be ad-hoc scripts and different on every distro, making it much easier to provide generic advice these days. It's the opposite of more difficult and confusing, since we're past the transition period now. It is safe to assume that the modern, systemd way is the way, or the user in question is sufficiently invested in their niche system that they are capable of dealing with things like this on their own.

There are things I don't like about it either, but as an end user, it works just fine, and this is not the place for off-topic whinging about it. Especially since the thread topic has literally nothing to do with systemd. It's so tiresome that a simple help request devolves into two pages of advice that applied in the 1990s alongside suggestions that users cripple their systems and make their job much more difficult by going backwards 10-30 years depending on who is giving the 'advice'. This is not helpful, it's not welcoming, and it's not representing Linux well. Random EEVBlog help threads are certainly not where distribution maintainers are going for design decisions...
Title: Re: Audio in Linux
Post by: SiliconWizard on July 14, 2022, 07:41:30 pm
Mostly agree with ve7xen here, even though that's not a popular opinion. But that's just how reality has unfolded, and no, even though systemd is not all great, it's not just because of some nasty conspiracy against Linux. It's just that it's reasonably homogeneous and just works for a majority of users.

I can understand people willing to stay away from it and/or thinking it's not in the spirit of Linux, and there is some valid points to that, but fortunately, there ARE distributions that do not use systemd out there, and quite a few that do but can be set up to use something else instead.

And yes, I don't get what the topic has anything to do with systemd either.

Especially if the OP wants direct access to the sound card with "bit-exact" samples, I would suggest as I (and others) have mentioned, using ALSA. (JACK is another option, but it's unnecessarily "complex" for what the OP wants to do IMHO.) Unless you have a very specific need, you can directly use the utilities from alsa-tools and call it a day. It works fine with any "sound card" I've ever tested on a variety of distributions - ALSA will always be there as it's an integral part of the Kernel now AFAIK. You may just need to install alsa-tools if the package is not already installed.

As to using ALSA directly when PulseAudio is active, it's certainly possible. You don't need to kill Pulseaudio, at least if you use an additional sound card. Right now I have a Linux box running Gnome with PulseAudio running as well, and a Presonus USB sound card. It can be accessed using alsa-tools while PulseAudio is running, you don't need to kill it. (It might be necessary if you only have ONE sound card in your system, but if you're sampling audio with some requirements about quality, I would suggest using an external card anyway.)
Title: Re: Audio in Linux
Post by: magic on July 14, 2022, 09:23:15 pm
As to using ALSA directly when PulseAudio is active, it's certainly possible. You don't need to kill Pulseaudio, at least if you use an additional sound card. Right now I have a Linux box running Gnome with PulseAudio running as well, and a Presonus USB sound card. It can be accessed using alsa-tools while PulseAudio is running, you don't need to kill it. (It might be necessary if you only have ONE sound card in your system, but if you're sampling audio with some requirements about quality, I would suggest using an external card anyway.)
It depends. In general, you cannot have two processes simultaneously using the hw:N devices. If Pulse closes its device when nothing is being played/recorded then no problem. Otherwise, it won't work.

If you can play through ALSA while Pulse is also playing something else, your stream has to be going through the ALSA→Pulse compatibility layer or both you and Pulse are using ALSA's dmix plugin behind the scenes. Either way, you aren't using the hw:N device. Exception: a few soundcards with hardware mixers, such as old SoundBlasters.

Can we not, even in jest, suggest commands that will completely break someone's system in a difficult to recover way?
Your system is already broken if those things make any difference to it.
Disabling Pulse, should you want to do so, does not require such wanton irreversible measures.
But that's the one way I know of. You are welcome to understand my intent and attempt it differently. A good habit to have in general.
I don't know why any thread asking for help with Linux devolves into an anti-systemd holy war.
Those who know the answers don't have the patience for dealing with S***MyD and vice-versa.
You are not helping the OP at all, and are just making them either break their system or go down a rabbit hole of niche distros for literally no benefit.
Or I have seen enough from the OP to assume he will know better.
Title: Re: Audio in Linux
Post by: SiliconWizard on July 14, 2022, 09:58:56 pm
You can prevent PulseAudio from "grabbing" a specific card: https://lukas.zapletalovi.com/2020/07/force-pulseaudio-to-ignore-a-card.html
which to me looks like a good way to deal with it if you wanna use ALSA on one card exclusively and let PulseAudio deal with the other(s).

Note: you can issue the following command to check which cards are being used by PulseAudio (and thus check that the above rule worked):
Code: [Select]
pacmd list-cards
Title: Re: Audio in Linux
Post by: Nominal Animal on July 14, 2022, 11:57:44 pm
How do I route the audio signal from the 'line-in' of the sound card (Creative CA0132)?
You pick the correct source.  Line-outs and speakers are sinks.  Some list them separately, others in a single list.  In either case, you pick the one you want from a list.

Where can I learn about sound in KDE Plasma (Kubuntu 20.04), so to understand what to do?
KDE (as a desktop environment) is based on Qt, and Qt does have a QtMultimedia (https://doc.qt.io/qtforpython-5/PySide2/QtMultimedia/index.html) module which provides a QAudioInput (https://doc.qt.io/qtforpython-5/PySide2/QtMultimedia/QAudioInput.html) class for processing input audio.  If it is not installed, install it for Python (python3-{pyside2|pyqt5}.qtmultimedia, depending on which flavour of Python Qt5 support you prefer).

How can I read the raw/unaltered ADC data from the line-in, preferably in Python for easier postprocessing?
First, use the QAudioDeviceInfo (https://doc.qt.io/qtforpython-5/PySide2/QtMultimedia/QAudioDeviceInfo.html) class to obtain the list of available sources, and pick the one that corresponds to your audio card line input.  The names should be more or less obvious to us humans.  The mode you want is QtMultimedia.QAudio.Mode.AudioInput.

Note that you'll want to use pydoc3 PySide2.QtMultimedia... or pydoc3.PyQt5.QtMultimedia... for the exact signatures, as the online documentation is a bit poor, containing lots of C++ code.

Next, create an instance of QtMultimedia.QAudioInput class, specifying the QAudioDeviceInfo (for the input you want), as well as the format you want.  Set the volume to 1.0f to avoid samples being modified.  You'll then get regular stateChanged signals, where your handler will check the reason, and if in the ActiveState, handle the bunch of input samples.

It should be quite straightforward, and you'll have an easy way to GUI'ify it too, at least the source selection and target file, unless you do the processing in the Python.  Audio data is only something like 44100 or 48000 samples per channel per second, and Python can easily handle that; you might wish to use numpy/scipy arrays if you do more processing, though.
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 08:05:08 am
I'll try to be really short

Imperative to understand and decide
Or you want that POTTERIX mediocre clone of so called desktop...

Or you want to setup a quality grade DAW

you will not have both
Potterix crap diverted and compromised all system resources with a spectacular monolithic glue of bad practices

Unix keep things simple by the book
Devices are meant to be administered by you and not put as some idiotic gui

That said you need to get rid of what is in the way
..

A DMIX plugin can do all you need .. by hand ... using ALSA CONFIG

Both pulse and systemd are useless then
And... they prevent you to control your hardware

Paul
Title: Re: Audio in Linux
Post by: JohanH on July 15, 2022, 09:15:08 am
Pulseaudio and Jack has been replaced by Pipewire in modern Linux distros. It is real-time with low latency. Pipewire still uses ALSA kernel interface, but comes with its own better API.

See https://pipewire.org/
Title: Re: Audio in Linux
Post by: RoGeorge on July 15, 2022, 09:18:30 am
... you'll want to use pydoc3 ...
Wow, thanks for mentioning pydoc3!  Always missed heaving such a tool (didn't know about it before).

With  pydoc3 -b  it even opens a webpage with all the local docs, and has a search, beautiful.  ^-^
From  man pydoc3
Quote
pydoc3 <name> ...
    Show text documentation on something.  <name> may be the name of a
    Python keyword, topic, function, module, or package, or a dotted
    reference to a class or function within a module or module in a
    package.  If <name> contains a '/', it is used as the path to a
    Python source file to document. If name is 'keywords', 'topics',
    or 'modules', a listing of these things is displayed.
...
pydoc3 -b
    Start an HTTP server on an arbitrary unused port and open a Web browser
    to interactively browse documentation.



At first I've searched online for pro and cons between PySide2 and PyQt5, and chose PySide2, but I'm a code-monkey and most of the examples seems to be for PyQt5, so I've just installed both:
Code: [Select]
    sudo apt update
   
    sudo apt install python3-pyqt5.qtmultimedia
    sudo apt install python3-pyside2.qtmultimedia
    sudo apt install qtmultimedia5*

Code: [Select]
    apt list *qtmultimedia*
        Listing... Done
        python3-pyqt5.qtmultimedia-dbg/focal 5.14.1+dfsg-3build1 amd64
        python3-pyqt5.qtmultimedia-dbg/focal 5.14.1+dfsg-3build1 i386
        python3-pyqt5.qtmultimedia/focal,now 5.14.1+dfsg-3build1 amd64 [installed]
        python3-pyqt5.qtmultimedia/focal 5.14.1+dfsg-3build1 i386
        python3-pyside2.qtmultimedia/focal,now 5.14.0-1~exp1ubuntu5 amd64 [installed]
        python3-pyside2.qtmultimediawidgets/focal 5.14.0-1~exp1ubuntu5 amd64
        qml-module-qtmultimedia/focal,now 5.12.8-0ubuntu1 amd64 [installed,automatic]
        qml-module-qtmultimedia/focal 5.12.8-0ubuntu1 i386
        qtmultimedia5-dev/focal,now 5.12.8-0ubuntu1 amd64 [installed]
        qtmultimedia5-dev/focal 5.12.8-0ubuntu1 i386
        qtmultimedia5-doc-html/focal,focal,now 5.12.8-0ubuntu1 all [installed]
        qtmultimedia5-doc/focal,focal,now 5.12.8-0ubuntu1 all [installed]
        qtmultimedia5-examples/focal,now 5.12.8-0ubuntu1 amd64 [installed]
        qtmultimedia5-examples/focal 5.12.8-0ubuntu1 i386

    pydoc3 -b



About audio in Linux, for now my understanding is like this:
- there are (kernel) hardware drivers for each chipset
- on top of the drivers sits another sound component ALSA (Advanced Linux Sound Architecture)
- ALSA replaced the former, now discontinued, OSS (Open Sound System)
- side info, ALSA can have an OSS compatibility mode (as a compilation switch) to trick old OSS applications into working with ALSA, but usually the switch is not set at compilation time, therefore nowadays there is no /dev/audio and alike, as it used to be in OSS
- on top of ALSA sits PulseAudio (and/or JACK), which mostly is in charge with handling and routing audio data streams between applications, or between ALSA and applications
- PulseAudio is a higher abstraction layer, therefore PulseAudio is not aware of all the audio features available in the hardware of each soundcard
- usually, JACK inhibits PulseAudio, but there are tools to make them work together (I didn't try)



About the existing hardware, inside the desktop there are 3 sound cards + an external USB soundcard
- one from the i7 CPU, i7 has an embedded video card which supports HDMI audio
- one from the nVidia GPU, nVidia video cards also support HDMI audio streams
- motherboard audio chip Creative3D (CA0132)
- an external USB audio card (which in fact is a DSP devboard, eZdsp C5535 (https://www.ti.com/tool/TMDX5535EZDSP) with a firmware that turns the devboard into a generic USB soundcard)

There is a catch, the physical audio panel (5 x 3.5 mm Jacks) is common to all the 3 internal sound cards, has detector switches for plugged/unplugged jacks, and even worst, each of these 5 jacks can be reconfigured as an input/output/mic/headphone  :scared:  ('hdajackretask' can show/change the physical jacks assignment - if not present, install it with 'sudo apt install alsa-tools-gui').



Learning to handle audio from Python, but this post already got too long.  Will shoot more software questions over the weekend.  Thank you all for the help so far.
Title: Re: Audio in Linux
Post by: JohanH on July 15, 2022, 09:26:15 am

- on top of ALSA sits PulseAudio (and/or JACK), which mostly is in charge with handling and routing audio data streams between applications, or between ALSA and applications
- PulseAudio is a higher abstraction layer, therefore PulseAudio is not aware of all the audio features available in the hardware of each soundcard
- usually, JACK inhibits PulseAudio, but there are tools to make them work together (I didn't try)


All of the above has been replaced by Pipewire on top of part of ALSA. Pipewire is lower abstraction than PulseAudio, thus faster, and it has better handling of streams.
Title: Re: Audio in Linux
Post by: gmb42 on July 15, 2022, 09:45:43 am

- on top of ALSA sits PulseAudio (and/or JACK), which mostly is in charge with handling and routing audio data streams between applications, or between ALSA and applications
- PulseAudio is a higher abstraction layer, therefore PulseAudio is not aware of all the audio features available in the hardware of each soundcard
- usually, JACK inhibits PulseAudio, but there are tools to make them work together (I didn't try)


All of the above has been replaced by Pipewire on top of part of ALSA. Pipewire is lower abstraction than PulseAudio, thus faster, and it has better handling of streams.

I have no idea, but for the OP's assistance, is Pipewire supported when using Qt or is it at a lower independent level that doesn't affect Qt sound ops?
Title: Re: Audio in Linux
Post by: janoc on July 15, 2022, 09:51:38 am
If pulseaudio is giving you trouble by locking a specific device (which I doubt, because ALSA/pulse is these days configured to share access), then all you have to do is to call your program using the pasuspender utility:

$ pasuspender -h
pasuspender [options] -- PROGRAM [ARGUMENTS ...]

Temporarily suspend PulseAudio while PROGRAM runs.

  -h, --help                            Show this help
      --version                         Show version
  -s, --server=SERVER                   The name of the server to connect to


No need to kill anything, no need for any irrelevant systemd whinging. PKTKS, I know you want to wage your holy war everywhere and every time you get the chance, but for f..k sake, whether it is mknod/udev or systemd creating the device files and starting the services makes literally zero difference here.

Also, the multiple recommendations of pipewire are irrelevant to the OP's question. And until pipewire is actually shipped by distributions, you don't want to start replacing PulseAudio and what not with that, especially if you don't know what you are doing. It is a good way to break one's system.

Finally, nobody seems to have actually read what the OP posted - there is no problem whatsoever with his setup, Pulse or anything else!
The messages from his program are completely normal - PyAudio is a Python library that is able to work with different audio systems, so the "errors" it outputs are because it is probing for the presence of the various backends.

Could we, please, stop these nonsensical rants and giving advice to replace the car's engine because you think Rudolph Diesel was an idiot whenever someone asks how to refill the coolant?  :palm:



OK, with that out of my system:


OP, you don't need to install anything apart from PyAudio. No need for Jack (please remove it, it will cause conflicts), PulseAudio is installed by default, there is no need to mess with it.

The simplest way to achieve what you want to do is to use a program like Audacity - it allows you to generate the various waveforms in the editor and play them as well, including device selection. Open Audacity, Generate->Tone. Done.

If you want to work using Python, then you can use PyAudio e.g. as described here:

https://people.csail.mit.edu/hubert/pyaudio/docs/

You create the samples for your sine wave in Python and use PyAudio to play them.  PyAudio abstracts all the low level audio complexity for you already, so no need to mess with PulseAudio, Jack, ALSA whatever!. As long as your machine has sane defaults for sound (all modern distros do, certainly Ubuntu!) and your sound is working e.g. with Youtube, it will work out of the box.

Then you use the mixer tool to send the sound to the right device while the sound is playing. E.g. in KDE (since you are using Kubuntu), go to the taskbar and the mixer is there. You can move the stream to the right device there. It will also remember it and do it automatically for you next time. The other option is pavucontrol tool that has been mentioned before. It does the same thing.

This device selection can be also done programmatically but it is unnecessarily complex for what you want to achieve.

Title: Re: Audio in Linux
Post by: RoGeorge on July 15, 2022, 09:52:37 am
All of the above [ALSA/Pulse] has been replaced by Pipewire on top of part of ALSA. Pipewire is lower abstraction than PulseAudio, thus faster, and it has better handling of streams.

The desktop is Kubuntu 20.04 LTS (Focal Fossa), which does not have PipeWire yet.

I've read that it's not trivial to backport pipewire, so I didn't try to install it, also, since PipeWire has become the default audio in Ubuntu only starting with this year, it means less examples and tools available.

To learn, I'll prefer something with more tools, docs and examples.  In terms of speed, the desktop is an i7-4790K/4.4GHz/32GB, it shouldn't be a problem to measure live distortions of a single channel, and latency on a constant sinusoidal signal doesn't matter.  PipeWire seems too new, and with no particular advantage for this application (live FFT + live display of THD and THD+noise).

Does PipeWire has any advantage for which it might worth the effort of installing it?
Title: Re: Audio in Linux
Post by: janoc on July 15, 2022, 09:55:05 am
The desktop is Kubuntu 20.04 LTS (Focal Fossa), which does not have PipeWire yet.

I've read that it's not trivial to backport pipewire, so I didn't try to install it, also, since PipeWire has become the default audio in Ubuntu only starting with this year, it means less examples and tools available.

To learn, I'll prefer something with more tools, docs and examples.  In terms of speed, the desktop is an i7-4790K/4.4GHz/32GB, it shouldn't be a problem to measure live distortions of a single channel, and latency on a constant sinusoidal signal doesn't matter.  PipeWire seems too new, and with no particular advantage for this application (live FFT + live display of THD and THD+noise).

Does PipeWire has any advantage for which it might worth the effort of installing it?

No, don't do that. It is completely irrelevant to your problem.

PipeWire is a future replacement for the PulseAudio audio server, but you both don't need it and if you don't know what you are doing, you are likely to hose your system up completely.

Either way, there is no point, the default sound server will work just fine for what you need.

If you are interested how the various Linux audio layers fit together, there is a good explanation here:
https://www.techradar.com/news/audio/linux-audio-explained-685419 (https://www.techradar.com/news/audio/linux-audio-explained-685419)

It doesn't cover PipeWire because it is an older article, but PipeWire fills the same role as PulseAudio/Jack.
Title: Re: Audio in Linux
Post by: magic on July 15, 2022, 10:43:49 am
3. - How can I read the raw/unaltered ADC data from the line-in, preferably in Python for easier postprocessing?
This is the specific point I had in mind when recommending bypassing all the sound server and multimedia framework turd and talking to ALSA directly.

ALSA is all the kernel drivers for soundcards plus a library (libasound) for talking to them though their device files in /dev/snd/ which also includes a framework of "plugins" for sample rate conversion, mixing from many applications etc, but you don't need to use them. Open the hw:N device and you have your bit-perfect playback/recording, provided that nothing else is conflicting with your use of the soundcard at the time.
Title: Re: Audio in Linux
Post by: RoGeorge on July 15, 2022, 10:45:29 am
Got it, thank you.

About generating and playing samples, this won't be needed.  The signal is generated outside of the computer by a physical circuit, an LC oscillator (I named it Peltz-Wyatt oscillator because it's a Peltz oscillator combined with a Wyatt current source in the hope of lowering the distortions existing in the sinusoidal signal).

- at first, I've evaluated the distortions with an oscilloscope, by eyeballing at the waveform, then display it as a FFT on the oscilloscope, but the oscilloscope ADC is only 8 bits, so I wanted a more precise measurement
- then, I've used an USB sound card, but that card seemed very noisy, so I wanted to use the line-in from the onboard sound card instead
- so far I've managed to use 'ARTA' and 'baudline' (programs that can display live audio spectrum and THD) but only with the USB soundcard, couldn't make them use the line-in instead
- apart from this, each measures the THD in its own way, I would like more control, and thus the idea of writing my own tool, as a Python exercise in audio.

This is the generator I want to measure its distortions, the jack connector on the left is the audio out to go into line-in of the onboard soundcard.
Title: Re: Audio in Linux
Post by: magic on July 15, 2022, 10:52:08 am
You can always record a WAV file and analyze it later with whatever tools.

For a real time analyzer, I tend to use JAAA, it is reasonably well thought out and accurate, but also has annoying warts like no horizontal log display and it's a bit of work to compile if not provided by the distribution.
http://kokkinizita.linuxaudio.org/linuxaudio/ (http://kokkinizita.linuxaudio.org/linuxaudio/)
Title: Re: Audio in Linux
Post by: janoc on July 15, 2022, 10:59:50 am
3. - How can I read the raw/unaltered ADC data from the line-in, preferably in Python for easier postprocessing?
This is the specific point I had in mind when recommending bypassing all the sound server and multimedia framework turd and talking to ALSA directly.

ALSA is all the kernel drivers for soundcards plus a library (libasound) for talking to them though their device files in /dev/snd/ which also includes a framework of "plugins" for sample rate conversion, mixing from many applications etc, but you don't need to use them. Open the hw:N device and you have your bit-perfect playback/recording, provided that nothing else is conflicting with your use of the soundcard at the time.


Well, you could do it directly with ALSA but there isn't much/any processing going on normally, so even the default PulseAudio input is most often fine - as long as you are working at the native samplerate of the hardware and no resampling is going on (e.g. trying to record at 44.1kHz but the hw supports only 48kHz -> Pulse will resample it on the fly for you).

So I would really really keep things simple. A cheap computer soundcard isn't the right tool for the job for accurate measurements of low distortions anyway.
Title: Re: Audio in Linux
Post by: magic on July 15, 2022, 11:06:46 am
TBH resampling is probably fine in this application, unless a genuinely atrocious algorithm is used, and the distortion is not low ;)

However, if you want to avoid it, it surely depends on what other applications are doing and on system configuration. With ALSA bult-in mixer plugin, the hardware always runs at a fixed sample rate (48kHz by default) and everything is resampled to that. Even if those new sound servers are smarter about it, there is nothing they can do when two applications use different sample rates - at least one will be resampled.
Title: Re: Audio in Linux
Post by: janoc on July 15, 2022, 11:10:30 am
Got it, thank you.

About generating and playing samples, this won't be needed.  The signal is generated outside of the computer by a physical circuit, an LC oscillator (I named it Peltz-Wyatt oscillator because it's a Peltz oscillator combined with a Wyatt current source in the hope of lowering the distortions existing in the sinusoidal signal).

- at first, I've evaluated the distortions with an oscilloscope, by eyeballing at the waveform, then display it as a FFT on the oscilloscope, but the oscilloscope ADC is only 8 bits, so I wanted a more precise measurement
- then, I've used an USB sound card, but that card seemed very noisy, so I wanted to use the line-in from the onboard sound card instead
- so far I've managed to use 'ARTA' and 'baudline' (programs that can display live audio spectrum and THD) but only with the USB soundcard, couldn't make them use the line-in instead
- apart from this, each measures the THD in its own way, I would like more control, and thus the idea of writing my own tool, as a Python exercise in audio.

This is the generator I want to measure its distortions, the jack connector on the left is the audio out to go into line-in of the onboard soundcard.

I am not sure a cheap sound card is a good way to perform such measurements, though. However, feel free to try. What has been said above still applies, just instead of generating and writing samples you will need to read them. PyAudio has examples for that as well, otherwise there are plenty of examples here:

https://www.geeksforgeeks.org/how-to-play-and-record-audio-in-python/ (https://www.geeksforgeeks.org/how-to-play-and-record-audio-in-python/)

And also, as magic said above, you don't need to write the code to record the audio yourself - use e.g. Audacity to record the signal from a device directly into a file (e.g. wav or raw format) and then use another tool to analyze it.

For data conversions and analysis, such as FFT  and similar you should have a look at Numpy:
https://numpy.org/ (https://numpy.org/)

And specifically its use for audio/video processing:
https://new.pythonforengineers.com/blog/audio-and-digital-signal-processingdsp-in-python/ (https://new.pythonforengineers.com/blog/audio-and-digital-signal-processingdsp-in-python/)
Title: Re: Audio in Linux
Post by: RoGeorge on July 15, 2022, 11:10:31 am
You can always record a WAV file and analyze it later with whatever tools.

For a real time analyzer, I tend to use JAAA...

I need live measurement, not recorded, so I can tweak the physical circuit while live watching at its THD.

Jaaa is in the ubuntu repos (sudo apt install jaaa), tried it some days ago and I couldn't figure how to make it listen to the signal coming from line-in (run it from either its KDE launcher or from terminal 'jaaa -A -d hw:1').  :-//

Either way, I want to at least learn more by writing something, than to endlessly google for error messages while fiddling with somebody else's software (i.e. 'baudline' only knows OSS or JACK, JACK freezes any other PulseAudio AV streams, while ALSA in ubuntu was not compiled with the OSS emulation switch, so I had to make 'baudline' read from stdin instead and launch it with 'parec --format=s16le --channels=1 --latency-msec=5 | ./baudline -stdin', and so on, all kinds of workarounds depending on what the existing programs can or can't do).
Title: Re: Audio in Linux
Post by: magic on July 15, 2022, 11:22:11 am
jaaa -A -d hw:1
That's exactly how it's done. You can use -C instead of -d to disable signal generation functions, less chance of conflict with other software. With some hardware, capture sample rate must be the same as ongoing playback.

Code: [Select]
$ jaaa -A -C hw:0
playback : not enabled
capture  :
  nchan  : 2
  rate   : 48000
  frsize : 1024
  nfrags : 2
  format : S32_LE
Connected to ALSA with 2 inputs and 0 outputs
Title: Re: Audio in Linux
Post by: DiTBho on July 15, 2022, 11:24:37 am
About audio in Linux, for now my understanding is like this:
- there are (kernel) hardware drivers for each chipset
- on top of the drivers sits another sound component ALSA (Advanced Linux Sound Architecture)

yup, there are kernel modules (drivers) for each chipset, some driver have both ALSA and OSS-emulation, some only have OSS (very old code, kernel 2.2, 2.4, and early 2.6), some have only ALSA

Then there is also Alsa-OSS emulation, so basically you can have OSS emulation at two levels
- kernel level
- userspace level

it entirely depends on the chipset || on the kernel version || sometimes on specific kernel patches || on how Alsa is compiled (with/out the magic OSS-emulation switch).


Title: Re: Audio in Linux
Post by: magic on July 15, 2022, 11:26:44 am
OSS is irrelevant on Linux. There is no need to worry about it unless you wan to impress your friends with cat sound.wav >/dev/dsp, but if you want then you have no friends anyway, so OSS is irrelevant on Linux.
Title: Re: Audio in Linux
Post by: janoc on July 15, 2022, 11:26:49 am
Either way, I want to at least learn more by writing something, than to endlessly google for error messages while fiddling with somebody else's software (i.e. 'baudline' only knows OSS or JACK, JACK freezes any other PulseAudio AV streams, while ALSA in ubuntu was not compiled with the OSS emulation switch, so I had to make 'baudline' read from stdin instead and launch it with 'parec --format=s16le --channels=1 --latency-msec=5 | ./baudline -stdin', and so on, all kinds of workarounds depending on what the existing programs can or can't do).

You should probably avoid anything requiring Jack or OSS. There are more modern/up to date tools available.

Jack is complex, conflicts with PulseAudio, so one has to mess with all sorts of things to get it to run - plus not needed for your application, it is meant for low latency audio e.g. in live recording or performances and very few applications actually use/support it (e.g. Ardour DAW was/is one of its major users).

OSS is a good 20 years or longer obsolete and if some application still requires it it means it hasn't been maintained/updated in ages. I mean, Baudline FAQ talks about Mandrake 7 and Redhat 6.2 - that was released 22 years ago!

If you want a current version that actually supports ALSA or PulseAudio properly, you need to pay for it:

Quote
A focus on audio.  The subscription baudline 1.09 has the following additions:

    Advanced Linux Sound Architecture (ALSA) driver support
    Pulse Audio driver support
    Ported to Raspberry Pi ARM systems
    Works on Mac OS X Catalina (10.15)
    Now works with XQuartz 2.7.11
    Some JACK and Core Audio bug fixes
    Improved audio playback latency

(see http://baudline.com/news.html (http://baudline.com/news.html) )



Title: Re: Audio in Linux
Post by: DiTBho on July 15, 2022, 11:43:41 am
OSS is irrelevant on Linux. There is no need to worry about it unless you wan to impress your friends with cat sound.wav >/dev/dsp, but if you want then you have no friends anyway, so OSS is irrelevant on Linux.

meh, so I am out.
Title: Re: Audio in Linux
Post by: mag_therm on July 15, 2022, 01:03:05 pm
https://app.box.com/s/glmsuoc0f43cipz3hzcxw3bxwb2dfc0z
Above the ham radio desktop with Jack, Calf EQ /Spectrum,  Fldigi (BPSK31) and Pulse ( Firefox audio, Pandora etc)
Jack was a  drama to get going, mainly by lack of manual.  Now it seems to work fairly well so I am reluctant to update
 This is Fedora 32 , I will update in about 2 ~3 years.
Latency:
patch system capture to system playback : about 7 ms
via the calf EQ/SA : about 12 ms
Latast jack ver is 0.9.7 dated 2022-04-02

Add: In the end, I think the only  items to get jack going
1.  >Options> start script : pulseaudio -k
   >Options> after start script : pacmd load-module module-jack-source channels=2; pacmd load-module module-jack-sink channels=2;

2. run alsamixer to set 0dB so that 0dB = -20dBFS
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 01:38:31 pm
Well  I understand that some folks new to DAW grade may be confused...
and may be lost with some complicated things...

However..  as the steps go anyone will understand that INTERPRETED interfaces and GUIs have absolute ZERO place at real-time high quality AUDIO and quality Instrumentation..
Obvious reasons interpreted is just a crap dog slow shit.

Even dedicated C interfaces  have issues when hardware clock is not friendly
With REAL MIDI bus you may have external clock synch..
but 99% cases you don't

I have made some cute TOYS (yepo they are just my toys) to interface UNIX with JACK along last years..
Just for fun I have some handy toys to check how good or bad I can use them..
-  A FULLY FUNCTIONAL  Function Generator  s/ spectrum + Modulator LADSPA support plugin bay
- A FULLY FUNCTIONAL  JACK ANALYSER with quality HD graphic CUSTOM FILTERS and SPECTRUMs

so far so good  all the instruments can work very reliably under JACK  (including Ardour recording)

The setup and some shots attached below...
These are TOYS  made to push limits and configure my workstations...

All C  pure C and GTK based...  nothing capable to stress upgrades..
Absolute ZERO   systemd and UDEV - all customized device nodes..

One  called JACKnerator ... the other JACKAnalyser (JA for short)

Just fun
Paul

PS> I made this today in kinda 15 seconds...
I have seen some funny typos... pl give me a break.. they are just kid keyboard typos..
i am not thatttt  ignorant in eng ... .. typos as they are .. i will not fix that ssssh

last shot is an FM (narrow) modulated generated signal...  instruments can really go up to 500KHz nicely
Title: Re: Audio in Linux
Post by: janoc on July 15, 2022, 02:01:42 pm
Well  I understand that some folks new to DAW grade may be confused...
and may be lost with some complicated things...

 :palm:

If you want to insult people who were probably editing live audio in Linux before you have even heard about it - well, be my guest.

Quote
However..  as the steps go anyone will understand that INTERPRETED interfaces and GUIs have absolute ZERO place at real-time high quality AUDIO and quality Instrumentation..
Obvious reasons interpreted is just a crap dog slow shit.

Even dedicated C interfaces  have issues when hardware clock is not friendly
With REAL MIDI bus you may have external clock synch..
but 99% cases you don't

I have made some cute TOYS (yepo they are just my toys) to interface UNIX with JACK along last years..
Just for fun I have some handy toys to check how good or bad I can use them..
-  A FULLY FUNCTIONAL  Function Generator  s/ spectrum + Modulator LADSPA support plugin bay
- A FULLY FUNCTIONAL  JACK ANALYSER with quality HD graphic CUSTOM FILTERS and SPECTRUMs

...
PS> I made this today in kinda 15 seconds...
last shot is an FM (narrow) modulated generated signal...  instruments can really go up to 500KHz nicely

Quote
All C  pure C and GTK based...  nothing capable to stress upgrades..
Absolute ZERO   systemd and UDEV - all customized device nodes..


And none of that is relevant to the OP's problem in the slightest. As always with your rants.

Please, keep this BS out of every thread. You tend to jump into literally everything that you evidently know little (but still have STRONG opinions) about, rant about unrelated/irrelevant things such as your favorite systemd bugbear or some corporate conspiracy/malfeasance, recommend stuff that is both irrelevant to the original poster in the best case and outright dangerous/detrimental in the worst (such as breaking a perfectly fine and working audio setup for no reason) - and not addressing the issue being asked about at all.

Thank you.
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 02:47:05 pm
No my dear... I take no insults.. and issue none.

The OP is confused HOW setting up a proper device node system.
I put some good directives..

I will not tolerate your gratis insults btw.  Let us both just keep  sane.

If I would insult someone you would already know now...

Not never my point
Paul
Title: Re: Audio in Linux
Post by: Nominal Animal on July 15, 2022, 04:13:06 pm
All of the above has been replaced by Pipewire on top of part of ALSA. Pipewire is lower abstraction than PulseAudio, thus faster, and it has better handling of streams.
Not in 20.04.  It is available, but not installed by default, nor officially supported (that came about in 21.04).
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 04:29:12 pm
All of the above has been replaced by Pipewire on top of part of ALSA. Pipewire is lower abstraction than PulseAudio, thus faster, and it has better handling of streams.
Not in 20.04.  It is available, but not installed by default, nor officially supported (that came about in 21.04).

Not even close the mature state of JACK.
PipeWire is one of those magic wands which will solve all things..

So far JACK works flawless with more than 16 tracks a dozen DSP filters and analyzers...
Fully threaded .. no fancy things like beeps ding dongs.

If you want to setup a proper system is simple:
 - ditch systemd and UDEV - they both are on the way
-  craft a proper device node on the system yourself
- use one of the good examples from ALSA  to setup DMIX plugins (/etc/alsa/ ) like on the fly rate cvrts
- stress your sound card to check if it will be functional with ALSA drivers.
Code: [Select]
pcm.samplerate {
@args [ SLAVE RATE CONVERTER ]
@args.SLAVE {
type string
default "plug:hw"
}
@args.RATE {
type integer
default 48000
}
@args.CONVERTER {
type string
default "samplerate"
}
type rate
converter $CONVERTER
slave {
pcm $SLAVE
rate $RATE
}
hint {
show {
@func refer
name defaults.namehint.basic
}
                description "Rate Converter Plugin Using Samplerate Library"
}
}


JACK works 100% perfectly fine.  TODAY.

BTW - i am not guessing this.. I made measures of it myself (above)

Paul

Title: Re: Audio in Linux
Post by: mag_therm on July 15, 2022, 05:01:15 pm
I just dnf  installed pipewire on another computer (Fedora32)
core error no such file
media session error no such file
No entries in shortcut menus, not in session apps
No instruction manual on gitlab, lots of issues just reported
I can't be bothered with all that again.

I think I'll just stay with jack for a long while
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 05:51:52 pm
I just dnf  installed pipewire on another computer (Fedora32)
core error no such file
media session error no such file
No entries in shortcut menus, not in session apps
No instruction manual on gitlab, lots of issues just reported
I can't be bothered with all that again.

I think I'll just stay with jack for a long while

Wise decision.

If you note..  my shots...  I let JACK running a rolling session for quite some time...
absolute ZERO xruns..  not even a bit missing  while i was taking shots and fussing things..

take JACK as your north star and just go...

Paul
Title: Re: Audio in Linux
Post by: ve7xen on July 15, 2022, 06:15:58 pm
Your system is already broken if those things make any difference to it.

You don't think deleting /usr/lib/systemd and /usr/bin/pulseaudio is going to break the system? :palm: Chances are pretty decent it won't even boot properly anymore.

But that's the one way I know of. You are welcome to understand my intent and attempt it differently. A good habit to have in general.

I already had in my previous post, I didn't think it needed to be reiterated.

Code: [Select]
systemctl --user stop pulseaudio.socket && systemctl --user stop pulseaudio.service

Quote
I just dnf  installed pipewire on another computer (Fedora32)

And this is why it's generally not recommended to try replacing core system services like the audio server with things that are not well supported by the distribution.

I dislike and don't use RedHat-style distributions, but I would guess you need a session manager like wireplumber installed, but other things might also be broken, like trying to run it in parallel with PA. JACK, ALSA, and PA support might also all be separate packages. You probably want a patch bay like qpwgraph or Helvum installed to do manual routing too.

If you have a working JACK setup though, there's not too much reason to do this. The main advantage is that it makes it easier to integrate with the rest of the system audio, but if you're doing ham stuff, you probably have dedicated audio interfaces that you can manage with JACK and that doesn't really matter.
Title: Re: Audio in Linux
Post by: SiliconWizard on July 15, 2022, 06:19:32 pm
I posted the way of making pulseaudio ignore some card so you don't even have to stop it. And I guarantee you that it works on all systems I've tried it with.

Getting rid of udev? Uh, yeah? Nice advice, especially if you're dealing with someone that may not be a Linux guru. :-DD
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 06:28:28 pm
yes .. udev is bundled in systemd...
and pulseaudio forced by everyb. throats  by the distro/desktop stuff.

In real terms?   You need none of them.

Start with a distro without systemd.  and do not install udev (EUDEV aka)
configure your device nodes just like a busybox system  static mknods

You need a decent level of experience.

MIXING these JACK/PA/SYSTEMD/UDEV  is a sack full of whinny cats..

ALSA and JACK can work out of the box clean and lean.. (see my shots..)

A BUSYBOX  distro is enough to do that... (and no busybox uses udev or even systemd)

Paul


PS BTW my hidden tip is starting with a busybox distro to see yourself how ...
then you can just shift to another say... LFS or BLFS of yours

btw for anyone grounded in busybox..  start https://busybox.net/  acquiring how you put a fully functional running system in memory without UDEV.. and not even a bit of sytemdFd....  fully functional
Title: Re: Audio in Linux
Post by: Nominal Animal on July 15, 2022, 07:26:11 pm
Devuan is systemd-free, and uses eudev for device management.  It also has the latest (0.3.54) PipeWire available, if one wants to use that.  And of course also ALSA (libasound2-1.2.7.1-1), Jack Audio (jackd2 1.9.21), and so on; all the newest stuff, letting you choose instead of forcing one on you.

Do note that if you use Qt5 and Python3, QtMultimedia will handle the interface layer regardless of which one it is. ALSA, PulseAudio, Jack, PipeWire, a combination of them, all should just work.

Because of this, I will stick with my recommendation, unless RoGeorge wishes to amend their preferences already stated (KDE and Python 3).
Whatever sound system is used on the Linux installation, does not matter in this respect.  (And while I might have an opinion, I don't think it matters here at this point.)

Because currently the Python 3 interpreter only runs Python code in one thread at a time in a given process, you'll want to use process-based parallelism if you want to do any heavy processing, to utilize a different core (from UI stuff).  The best approach then, in my opinion, is to actually combine the record-and-process to a separate command-line helper that outputs binary results.   (In the Python code, you could use e.g. a thread worker reading the data, parsing it, and emitting it to the UI via Queue or a Qt signal.)

If you do use PulseAudio, I already have C code that is quite suitable; and it would be very easy to add say FFTW3 Fourier transform or similar on top, and just emit the resulting data for the Python code to display.  I could probably write one for ALSA as well in C (depending only on libasound2; libasound2-dev at build time).  But, you can of course use Python for this too, although Python isn't that efficient in processing data streams.
Title: Re: Audio in Linux
Post by: RoGeorge on July 15, 2022, 07:30:06 pm
There's something weird with my hardware or with the drivers.

Saying this because even after stopping the PulseAudio, the signal from line-in is seen in Audacium as Mic2 (hw:1,2).  :o  Audacium uses ALSA (it's an Audacity recompiled without telemetry) and Mic2 in the motherboard manual is an internal connector, with 0.1'' pins for the audio frontpanel, which I never had.

Now, if I try to start Jaaa with 'jaaa -A -d hw:1,2' it finally works, shows the spectrum with either input 1 or 2 (Jaaa shows 8 input buttons from 1 to 8 whatever that would mean).  Though, I don't see how to display the THD, I think it can not do that.  ::)

Well, at least I can finally see something from the line-in cable.  ;D

I'll try tomorrow to boot from a live Kubuntu pendrive, just to be sure it's not some configuration that I might have messed in my previous attempts, also will try in FreeBSD to see if the channels are messed like they are now in my Kubuntu 20.04 LTS.
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 07:36:33 pm
Devuan is systemd-free, and uses eudev for device management.  It also has the latest (0.3.54) PipeWire available, if one wants to use that.  And of course also ALSA (libasound2-1.2.7.1-1), Jack Audio (jackd2 1.9.21), and so on; all the newest stuff, letting you choose instead of forcing one on you.
()

That is a nice setup.. you have much fat to strip but doable..

I HAVE JUST EXACTLY NOW UPGRADED MY JACK SETUP TO LATEST.

Awesome new cool looking.. i am sharing you guys...  just keep trying  :-+

Works out the box nicely clean...  very happy seeing the cool gizmos...  ^-^
Paul

all the usual typos in a 2 second dirt shot...  :scared:
Title: Re: Audio in Linux
Post by: PKTKS on July 15, 2022, 07:46:24 pm
There's something weird with my hardware or with the drivers.
(..)
I'll try tomorrow to boot from a live Kubuntu pendrive, just to be sure it's not some configuration that I might have messed in my previous attempts, also will try in FreeBSD to see if the channels are messed like they are now in my Kubuntu 20.04 LTS.

I put more faith in NOMINAL ANIMAL  tip..   

A DEVUAN  flat setup probably has more chances to succeed easily

Time is limited you may put a decent Devuan ready to start

Paul
Title: Re: Audio in Linux
Post by: Nominal Animal on July 15, 2022, 09:50:32 pm
RoGeorge, consider compiling the following program (list.c) via
    gcc -Wall -O2 `pkg-config --cflags alsa` list.c `pkg-config --libs alsa` -o list
and run it (./list).  It reports all ALSA PCM devices.  For me, the key entry is "hw:CARD=PCH,DEV=0": HDA Intel PCH, CX8200 Analog Direct hardware device without any conversions.  You do need to make sure you have libasound2-dev package installed.

Code: [Select]
// SPDX-License-Identifier: CC0-1.0
#define  _POSIX_C_SOURCE  200809L
#include <stdlib.h>
#include <alsa/asoundlib.h>
#include <stdio.h>
#include <errno.h>

int main(void)
{
    void **hints;
    int    err;

    err = snd_device_name_hint(-1, "pcm", &hints);
    if (err) {
        fprintf(stderr, "snd_device_name_hint(): %s.\n", snd_strerror(err));
        return EXIT_FAILURE;
    }

    for (size_t  i = 0; hints[i] != NULL; i++) {
        char *name = snd_device_name_get_hint(hints[i], "NAME");
        if (!name)
            continue;

        char *desc = snd_device_name_get_hint(hints[i], "DESC");
        if (desc) {
            char *p;

            while ((p = strchr(desc, '\n'))) *p = ' ';
            while ((p = strchr(desc, '\r'))) *p = ' ';
        }

        printf("\"%s\": %s\n", name, desc ? desc : "");

        free(desc);
        free(name);
    }

    snd_device_name_free_hint(hints);
    hints = NULL;

    return EXIT_SUCCESS;
}
I also see things like "jack": JACK Audio Connection Kit, because at least on ALSA 1.9.4 on Mint 20.04 (closest thing I have that should more or less match what you have), ALSA does support access to JACK and all those others.  So, even though you'd use plain ol' ALSA, you could still use any audio subsystem you want.

Because it has explicit direct hardware access without any conversions (hw:CARD=card,DEV=device), and it has the least dependencies (libasound2 at runtime on Debian/Devuan derivatives, libasound2-dev at build time), it would be easiest to do the capture in C.

Of course, if you want, you can still make a Python 3 GUI, just use something like the above (but perhaps better formatted) to list the sources for the user to choose, and another program to read from a source.  Then, use Python Subprocess to run them, and read their output in a pipe.  This way, if you have multiple cores (available), then the Python code runs independently from the C code.  (Typically, you'll use a separate Python thread, to read from the pipe in normal blocking manner, and pass each suitable block to your UI thread; perhaps using Queue, or Qt in KDE.)

If the Python code exists suddenly, the C code will detect that by EPIPE error, and also close gracefully; just handle the EPIPE error when writing to the pipe.  For Fourier transforms and such, I'd use FFTW3 (with optional wisdom generated to optimize the chosen FFT window size) in the C code.  It is fast and known-good implementation.

The above program really should be expanded to open each PCM device listed, and see if it can be recorded, and filter out those that are output-only.  But I'm lazy, and I think it is useful to see all the ALSA pcm devices at this point, for verification.
Title: Re: Audio in Linux
Post by: RoGeorge on July 16, 2022, 09:23:38 am
Wow!  That is absolutely great and very helpful, thank you!  :-+
It compiled without any problem on both Kubuntu and FreeBSD.

When run on FreeBSD, there is no ALSA and no PulseAudio, only OSS.  It returns:
Code: [Select]
list_FreeBSD
    "null": Discard all samples (playback) or generate zero samples (capture)
    "oss": Open Sound System


On Kubuntu, with either PulseAudio started or stopped, it returns the same ALSA list:
Code: [Select]
"surround21": 2.1 Surround output to Front and Subwoofer speakers
"surround40": 4.0 Surround output to Front and Rear speakers
"surround41": 4.1 Surround output to Front, Rear and Subwoofer speakers
"surround50": 5.0 Surround output to Front, Center and Rear speakers
"surround51": 5.1 Surround output to Front, Center, Rear and Subwoofer speakers
"surround71": 7.1 Surround output to Front, Center, Side, Rear and Woofer speakers
"null": Discard all samples (playback) or generate zero samples (capture)
"samplerate": Rate Converter Plugin Using Samplerate Library
"speexrate": Rate Converter Plugin Using Speex Resampler
"jack": JACK Audio Connection Kit
"oss": Open Sound System
"pulse": PulseAudio Sound Server
"upmix": Plugin for channel upmix (4,6,8)
"vdownmix": Plugin for channel downmix (stereo) with a simple spacialization
"hdmi:CARD=HDMI,DEV=0": HDA Intel HDMI, HDMI 0 HDMI Audio Output
"hdmi:CARD=HDMI,DEV=1": HDA Intel HDMI, HDMI 1 HDMI Audio Output
"hdmi:CARD=HDMI,DEV=2": HDA Intel HDMI, HDMI 2 HDMI Audio Output
"hdmi:CARD=HDMI,DEV=3": HDA Intel HDMI, HDMI 3 HDMI Audio Output
"hdmi:CARD=HDMI,DEV=4": HDA Intel HDMI, HDMI 4 HDMI Audio Output
"dmix:CARD=HDMI,DEV=3": HDA Intel HDMI, HDMI 0 Direct sample mixing device
"dmix:CARD=HDMI,DEV=7": HDA Intel HDMI, HDMI 1 Direct sample mixing device
"dmix:CARD=HDMI,DEV=8": HDA Intel HDMI, HDMI 2 Direct sample mixing device
"dmix:CARD=HDMI,DEV=9": HDA Intel HDMI, HDMI 3 Direct sample mixing device
"dmix:CARD=HDMI,DEV=10": HDA Intel HDMI, HDMI 4 Direct sample mixing device
"dsnoop:CARD=HDMI,DEV=3": HDA Intel HDMI, HDMI 0 Direct sample snooping device
"dsnoop:CARD=HDMI,DEV=7": HDA Intel HDMI, HDMI 1 Direct sample snooping device
"dsnoop:CARD=HDMI,DEV=8": HDA Intel HDMI, HDMI 2 Direct sample snooping device
"dsnoop:CARD=HDMI,DEV=9": HDA Intel HDMI, HDMI 3 Direct sample snooping device
"dsnoop:CARD=HDMI,DEV=10": HDA Intel HDMI, HDMI 4 Direct sample snooping device
"hw:CARD=HDMI,DEV=3": HDA Intel HDMI, HDMI 0 Direct hardware device without any conversions
"hw:CARD=HDMI,DEV=7": HDA Intel HDMI, HDMI 1 Direct hardware device without any conversions
"hw:CARD=HDMI,DEV=8": HDA Intel HDMI, HDMI 2 Direct hardware device without any conversions
"hw:CARD=HDMI,DEV=9": HDA Intel HDMI, HDMI 3 Direct hardware device without any conversions
"hw:CARD=HDMI,DEV=10": HDA Intel HDMI, HDMI 4 Direct hardware device without any conversions
"plughw:CARD=HDMI,DEV=3": HDA Intel HDMI, HDMI 0 Hardware device with all software conversions
"plughw:CARD=HDMI,DEV=7": HDA Intel HDMI, HDMI 1 Hardware device with all software conversions
"plughw:CARD=HDMI,DEV=8": HDA Intel HDMI, HDMI 2 Hardware device with all software conversions
"plughw:CARD=HDMI,DEV=9": HDA Intel HDMI, HDMI 3 Hardware device with all software conversions
"plughw:CARD=HDMI,DEV=10": HDA Intel HDMI, HDMI 4 Hardware device with all software conversions
"usbstream:CARD=HDMI": HDA Intel HDMI USB Stream Output
"default:CARD=PCH": HDA Intel PCH, CA0132 Analog Default Audio Device
"sysdefault:CARD=PCH": HDA Intel PCH, CA0132 Analog Default Audio Device
"front:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Front speakers
"surround21:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog 2.1 Surround output to Front and Subwoofer speakers
"surround40:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog 4.0 Surround output to Front and Rear speakers
"surround41:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog 4.1 Surround output to Front, Rear and Subwoofer speakers
"surround50:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog 5.0 Surround output to Front, Center and Rear speakers
"surround51:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog 5.1 Surround output to Front, Center, Rear and Subwoofer speakers
"surround71:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog 7.1 Surround output to Front, Center, Side, Rear and Woofer speakers
"iec958:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Digital IEC958 (S/PDIF) Digital Audio Output
"dmix:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Direct sample mixing device
"dmix:CARD=PCH,DEV=1": HDA Intel PCH, CA0132 Digital Direct sample mixing device
"dmix:CARD=PCH,DEV=2": HDA Intel PCH, CA0132 Analog Mic-In2 Direct sample mixing device
"dmix:CARD=PCH,DEV=4": HDA Intel PCH, CA0132 What U Hear Direct sample mixing device
"dsnoop:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Direct sample snooping device
"dsnoop:CARD=PCH,DEV=1": HDA Intel PCH, CA0132 Digital Direct sample snooping device
"dsnoop:CARD=PCH,DEV=2": HDA Intel PCH, CA0132 Analog Mic-In2 Direct sample snooping device
"dsnoop:CARD=PCH,DEV=4": HDA Intel PCH, CA0132 What U Hear Direct sample snooping device
"hw:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Direct hardware device without any conversions
"hw:CARD=PCH,DEV=1": HDA Intel PCH, CA0132 Digital Direct hardware device without any conversions
"hw:CARD=PCH,DEV=2": HDA Intel PCH, CA0132 Analog Mic-In2 Direct hardware device without any conversions
"hw:CARD=PCH,DEV=4": HDA Intel PCH, CA0132 What U Hear Direct hardware device without any conversions
"plughw:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Hardware device with all software conversions
"plughw:CARD=PCH,DEV=1": HDA Intel PCH, CA0132 Digital Hardware device with all software conversions
"plughw:CARD=PCH,DEV=2": HDA Intel PCH, CA0132 Analog Mic-In2 Hardware device with all software conversions
"plughw:CARD=PCH,DEV=4": HDA Intel PCH, CA0132 What U Hear Hardware device with all software conversions
"usbstream:CARD=PCH": HDA Intel PCH USB Stream Output
"hdmi:CARD=NVidia,DEV=0": HDA NVidia, HDMI 0 HDMI Audio Output
"hdmi:CARD=NVidia,DEV=1": HDA NVidia, HDMI 1 HDMI Audio Output
"hdmi:CARD=NVidia,DEV=2": HDA NVidia, HDMI 2 HDMI Audio Output
"hdmi:CARD=NVidia,DEV=3": HDA NVidia, HDMI 3 HDMI Audio Output
"hdmi:CARD=NVidia,DEV=4": HDA NVidia, HDMI 4 HDMI Audio Output
"hdmi:CARD=NVidia,DEV=5": HDA NVidia, HDMI 5 HDMI Audio Output
"hdmi:CARD=NVidia,DEV=6": HDA NVidia, HDMI 6 HDMI Audio Output
"dmix:CARD=NVidia,DEV=3": HDA NVidia, HDMI 0 Direct sample mixing device
"dmix:CARD=NVidia,DEV=7": HDA NVidia, HDMI 1 Direct sample mixing device
"dmix:CARD=NVidia,DEV=8": HDA NVidia, HDMI 2 Direct sample mixing device
"dmix:CARD=NVidia,DEV=9": HDA NVidia, HDMI 3 Direct sample mixing device
"dmix:CARD=NVidia,DEV=10": HDA NVidia, HDMI 4 Direct sample mixing device
"dmix:CARD=NVidia,DEV=11": HDA NVidia, HDMI 5 Direct sample mixing device
"dmix:CARD=NVidia,DEV=12": HDA NVidia, HDMI 6 Direct sample mixing device
"dsnoop:CARD=NVidia,DEV=3": HDA NVidia, HDMI 0 Direct sample snooping device
"dsnoop:CARD=NVidia,DEV=7": HDA NVidia, HDMI 1 Direct sample snooping device
"dsnoop:CARD=NVidia,DEV=8": HDA NVidia, HDMI 2 Direct sample snooping device
"dsnoop:CARD=NVidia,DEV=9": HDA NVidia, HDMI 3 Direct sample snooping device
"dsnoop:CARD=NVidia,DEV=10": HDA NVidia, HDMI 4 Direct sample snooping device
"dsnoop:CARD=NVidia,DEV=11": HDA NVidia, HDMI 5 Direct sample snooping device
"dsnoop:CARD=NVidia,DEV=12": HDA NVidia, HDMI 6 Direct sample snooping device
"hw:CARD=NVidia,DEV=3": HDA NVidia, HDMI 0 Direct hardware device without any conversions
"hw:CARD=NVidia,DEV=7": HDA NVidia, HDMI 1 Direct hardware device without any conversions
"hw:CARD=NVidia,DEV=8": HDA NVidia, HDMI 2 Direct hardware device without any conversions
"hw:CARD=NVidia,DEV=9": HDA NVidia, HDMI 3 Direct hardware device without any conversions
"hw:CARD=NVidia,DEV=10": HDA NVidia, HDMI 4 Direct hardware device without any conversions
"hw:CARD=NVidia,DEV=11": HDA NVidia, HDMI 5 Direct hardware device without any conversions
"hw:CARD=NVidia,DEV=12": HDA NVidia, HDMI 6 Direct hardware device without any conversions
"plughw:CARD=NVidia,DEV=3": HDA NVidia, HDMI 0 Hardware device with all software conversions
"plughw:CARD=NVidia,DEV=7": HDA NVidia, HDMI 1 Hardware device with all software conversions
"plughw:CARD=NVidia,DEV=8": HDA NVidia, HDMI 2 Hardware device with all software conversions
"plughw:CARD=NVidia,DEV=9": HDA NVidia, HDMI 3 Hardware device with all software conversions
"plughw:CARD=NVidia,DEV=10": HDA NVidia, HDMI 4 Hardware device with all software conversions
"plughw:CARD=NVidia,DEV=11": HDA NVidia, HDMI 5 Hardware device with all software conversions
"plughw:CARD=NVidia,DEV=12": HDA NVidia, HDMI 6 Hardware device with all software conversions
"usbstream:CARD=NVidia": HDA NVidia USB Stream Output


In all runs, the eZdsp USB devboard/soundcard was unplugged from the USB port.
The physical soundcards in the desketop are:
- HDA nVidia - digital soundcard because the nVidia graphic card can send digital sound to monitors
- HDA Intel HDMI - digital soundcard because the Intel graphic card can send digital sound to monitors
- HDA Intel PCH (which is the analog soundcard with CA0132 chipset, AFAIK that is a Creative Sound3D chip, no idea why the Creative CA0132 souncard is called Intel PCH  :-//).  This is the soundcard that I want to use, plugged to an external stereo amplifier.



As a side note, in FreeBSD 'baudline' works just fine (with OSS and no PulseAudio), but I suspect the sampling rate is always 48kHz, and when I set 196kHz from 'baudline', it's in fact just a software resample.  Saying this because of the symmetry seen in the FFT spectrum.

The attached captures are for the same signal coming from a physical Peltz oscillator connected at the line-in.  Only the sample rate was changed, from inside 'baudline'.  At 44100 the spectrum looks dirty, at 48kHz looks OK (the harmonic are real distortions from the oscillator), but at 96kHz the spectrum looks mirrored, and at 192kHz is mirrored one more time.  >:(
Title: Re: Audio in Linux
Post by: DiTBho on July 16, 2022, 11:15:27 am
The attached captures are for the same signal coming from a physical Peltz oscillator connected at the line-in.  Only the sample rate was changed, from inside 'baudline'.  At 44100 the spectrum looks dirty, at 48kHz looks OK (the harmonic are real distortions from the oscillator), but at 96kHz the spectrum looks mirrored, and at 192kHz is mirrored one more time.  >:(

I wrote a simple FFT (butterfly, C89) for my HPPA workstation and had a similar problem with my custom audio kernel driver. In my case: I forgot -1- to disable the line-in filter and, even worse, -2- to set the bit that manages the sampling mod. This way it wasn't on a regular basis but on "when the data is ready, you can trigger an interrupt".

Combined, these two defects introduce *false harmonics* in the spectrum and a very annoying "low pass" frequency.

Also, with digital sampling, you have to be careful with the "sampling window". There are many, you ave to choose the right one for your application, and be prepared to accept that none of them is perfect, they all always introduces a little distortion and phase shift.
Title: Re: Audio in Linux
Post by: Nominal Animal on July 16, 2022, 01:06:22 pm
Code: [Select]
"hw:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Direct hardware device without any conversions
"hw:CARD=PCH,DEV=1": HDA Intel PCH, CA0132 Digital Direct hardware device without any conversions
"hw:CARD=PCH,DEV=2": HDA Intel PCH, CA0132 Analog Mic-In2 Direct hardware device without any conversions
"hw:CARD=PCH,DEV=4": HDA Intel PCH, CA0132 What U Hear Direct hardware device without any conversions
It's these you want to use (with the built-in stuff).  It is called Intel PCH, because that's the driver name, snd_hda_intel (https://elixir.bootlin.com/linux/v5.18.12/source/sound/pci/hda).  The name is composed partially by ALSA (based on stuff in /etc/alsa/ and /usr/share/alsa/), and partially by the kernel driver (see e.g. /proc/asound/pcm in Linux).

If the capture program or thread gets that device name, "hw:CARD=PCH,DEV=0" or "hw:CARD=PCH,DEV=2", then it is very simple to check the natively supported sample rates and capture data.  Just let me know if you want example code. ;D

Also, with digital sampling, you have to be careful with the "sampling window". There are many, you have to choose the right one for your application, and be prepared to accept that none of them is perfect, they all always introduces a little distortion and phase shift.
Yup.  Wikipedia has more on this (https://en.wikipedia.org/wiki/Hamming_window#Spectral_analysis).  Rectangular –– applying no window function, just putting chunks through FFT –– is itself one window function.  (To apply a window function, you just multiply the samples by the window function; it is simple scaling of the samples.)
Typically, one advances the data by one half FFT block; this is called the Welch method (https://en.wikipedia.org/wiki/Welch_method).

When displaying the FFT data interactively (noting that there are around 20-25 blocks of 2000 samples per second at 44.1kHz and 48kHz sample rates per channel; twice that if you use the Welch method, which I do recommend you do), you can show both the most recent FFTs in a persistence kind of way (most recent brightest), but also show the weighted averaged FFT (which is a more realistic description of the spectral content if the waveform doesn't change).  Note that you'll want to do the averaging in the complex domain (real and imaginary parts separately averaged), not in the magnitude-phase domain.
Title: Re: Audio in Linux
Post by: PKTKS on July 16, 2022, 01:24:57 pm
Code: [Select]
"hw:CARD=PCH,DEV=0": HDA Intel PCH, CA0132 Analog Direct hardware device without any conversions
"hw:CARD=PCH,DEV=1": HDA Intel PCH, CA0132 Digital Direct hardware device without any conversions
"hw:CARD=PCH,DEV=2": HDA Intel PCH, CA0132 Analog Mic-In2 Direct hardware device without any conversions
"hw:CARD=PCH,DEV=4": HDA Intel PCH, CA0132 What U Hear Direct hardware device without any conversions
(..)

 apps which have no access to such  code can use ALSA native player as:

aplay -l    ( L lowcase stands LIST )

it reports what such apps can see at the surface of ALSA.

the OP can try and report it back... to complete the figure

Paul
Title: Re: Audio in Linux
Post by: magic on July 16, 2022, 01:44:07 pm
- HDA Intel PCH (which is the analog soundcard with CA0132 chipset, AFAIK that is a Creative Sound3D chip, no idea why the Creative CA0132 souncard is called Intel PCH  :-//).

It's the Intel "High Definition Audio" thing. It consists of a low cost "codec" (DACs, ADCs and analog bits) talking a simple serial link to a special PCI controller. Your codec is supplied by Creative and your PCI module is supplied by Intel, part of the PCH chip. This architecture is used for onboard audio everywhere since ~2000; before HDA a similar standard known as AC97 existed.
Title: Re: Audio in Linux
Post by: Nominal Animal on July 16, 2022, 02:20:27 pm
aplay -l    ( L lowcase stands LIST )
Absolutely; and
    arecord -L
lists all PCM devices one can read from.
(And why didn't I suggest that first, and instead jumped to code :palm:)

Furthermore,
    arecord -D name --dump-hw-params
lists the actual hardware capabilities for the PCM device (in recording mode).  Which for me, tells the following:
Code: [Select]
HW Params of device "hw:CARD=PCH,DEV=0":
--------------------
ACCESS:  MMAP_INTERLEAVED RW_INTERLEAVED
FORMAT:  S16_LE S32_LE
SUBFORMAT:  STD
SAMPLE_BITS: [16 32]
FRAME_BITS: [32 64]
CHANNELS: 2
RATE: [48000 96000]
PERIOD_TIME: (166 170667)
PERIOD_SIZE: [16 8192]
PERIOD_BYTES: [128 65536]
PERIODS: [2 32]
BUFFER_TIME: (333 341334)
BUFFER_SIZE: [32 16384]
BUFFER_BYTES: [128 65536]
TICK_TIME: ALL
--------------------
and so for best results, I'd use
    arecord -D hw:PCH,0 --disable-format --disable-softvol --disable-resample -t raw -c 2 -f S32_LE -r 96000 -B 20875
to output raw 32-bit little endian samples in two channels, interleaved (left right left right ...), at 96 kHz sample rate to standard output, in blocks of roughly 2004 samples per channel (1,000,000µs × 2004 / 96,000 = 20875).

The above samples the hardware channel, but you may have to use amixer to set the hardware channel configuration.
In particular, amixer -D hw:PCH contents gives (omitting the uninteresting ones)
Code: [Select]
numid=19,iface=CARD,name='Internal Mic Phantom Jack'
  ; type=BOOLEAN,access=r-------,values=1
  : values=on
numid=20,iface=CARD,name='Line Jack'
  ; type=BOOLEAN,access=r-------,values=1
  : values=off
numid=18,iface=CARD,name='Mic Jack'
  ; type=BOOLEAN,access=r-------,values=1
  : values=off
numid=23,iface=CARD,name='Speaker Phantom Jack'
  ; type=BOOLEAN,access=r-------,values=1
  : values=on
numid=16,iface=MIXER,name='Master Playback Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=on
numid=15,iface=MIXER,name='Master Playback Volume'
  ; type=INTEGER,access=rw---R--,values=1,min=0,max=74,step=0
  : values=47
  | dBscale-min=-74.00dB,step=1.00dB,mute=0
numid=5,iface=MIXER,name='Headphone Playback Switch'
  ; type=BOOLEAN,access=rw------,values=2
  : values=off,off
numid=4,iface=MIXER,name='Headphone Playback Volume'
  ; type=INTEGER,access=rw---R--,values=2,min=0,max=74,step=0
  : values=0,0
  | dBscale-min=-74.00dB,step=1.00dB,mute=0
numid=61,iface=MIXER,name='PCM Playback Volume'
  ; type=INTEGER,access=rw---RW-,values=2,min=0,max=255,step=0
  : values=253,253
  | dBscale-min=-51.00dB,step=0.20dB,mute=0
numid=12,iface=MIXER,name='Line Boost Volume'
  ; type=INTEGER,access=rw---R--,values=2,min=0,max=3,step=0
  : values=0,0
  | dBscale-min=0.00dB,step=12.00dB,mute=0
numid=10,iface=MIXER,name='Mic Boost Volume'
  ; type=INTEGER,access=rw---R--,values=2,min=0,max=3,step=0
  : values=0,0
  | dBscale-min=0.00dB,step=12.00dB,mute=0
numid=1,iface=MIXER,name='Mic Mute-LED Mode'
  ; type=ENUMERATED,access=rw------,values=1,items=4
  ; Item #0 'On'
  ; Item #1 'Off'
  ; Item #2 'Follow Capture'
  ; Item #3 'Follow Mute'
  : values=3
numid=7,iface=MIXER,name='Capture Source'
  ; type=ENUMERATED,access=rw------,values=1,items=3
  ; Item #0 'Mic'
  ; Item #1 'Internal Mic'
  ; Item #2 'Line'
  : values=1
numid=9,iface=MIXER,name='Capture Switch'
  ; type=BOOLEAN,access=rw------,values=2
  : values=off,off
numid=8,iface=MIXER,name='Capture Volume'
  ; type=INTEGER,access=rw---R--,values=2,min=0,max=80,step=0
  : values=0,0
  | dBscale-min=-74.00dB,step=1.00dB,mute=0
numid=6,iface=MIXER,name='Auto-Mute Mode'
  ; type=ENUMERATED,access=rw------,values=1,items=3
  ; Item #0 'Disabled'
  ; Item #1 'Speaker Only'
  ; Item #2 'Line Out+Speaker'
  : values=2
numid=14,iface=MIXER,name='Beep Playback Switch'
  ; type=BOOLEAN,access=rw------,values=1
  : values=on
numid=13,iface=MIXER,name='Beep Playback Volume'
  ; type=INTEGER,access=rw---R--,values=1,min=0,max=7,step=0
  : values=3
  | dBscale-min=-28.00dB,step=4.00dB,mute=0
numid=11,iface=MIXER,name='Internal Mic Boost Volume'
  ; type=INTEGER,access=rw---R--,values=2,min=0,max=3,step=0
  : values=0,0
  | dBscale-min=0.00dB,step=12.00dB,mute=0
numid=17,iface=MIXER,name='Mute-LED Mode'
  ; type=ENUMERATED,access=rw------,values=1,items=3
  ; Item #0 'On'
  ; Item #1 'Off'
  ; Item #2 'Follow Master'
  : values=2
numid=3,iface=MIXER,name='Speaker+LO Playback Switch'
  ; type=BOOLEAN,access=rw------,values=2
  : values=on,on
numid=2,iface=MIXER,name='Speaker+LO Playback Volume'
  ; type=INTEGER,access=rw---R--,values=2,min=0,max=74,step=0
  : values=74,74
  | dBscale-min=-74.00dB,step=1.00dB,mute=0
numid=25,iface=PCM,name='Capture Channel Map'
  ; type=INTEGER,access=r----R--,values=2,min=0,max=36,step=0
  : values=0,0
  | container
    | chmap-fixed=FL,FR
This tells me that I don't have anything connected to Line, but if I had, I'd need to set "numid=7,iface=MIXER,name='Capture Source'" to 2 to capture Line In, "numid=8,iface=MIXER,name='Capture Volume'" to set the hardware capture volume (right now it is set to zero), choose between 0 or 3 for "numid=12,iface=MIXER,name='Line Boost Volume'", and "numid=9,iface=MIXER,name='Capture Switch'" to True.

So, as you can see, you use the mixer to select the exact capture input jack, and the PCM device to read or write samples.

This architecture is used for onboard audio everywhere [on x86 and x86-64 architectures] since ~2000; before HDA a similar standard known as AC97 existed.
Fixed that for you ;)
Title: Re: Audio in Linux
Post by: RoGeorge on July 16, 2022, 02:56:26 pm
Just found out the funniest place to get info about ALSA cards in Kubuntu:  /proc/asaund/  :D
There are text files with status and capabilities:
Code: [Select]
$ cat /proc/asound/cards

 0 [HDMI           ]: HDA-Intel - HDA Intel HDMI
                      HDA Intel HDMI at 0xefa34000 irq 41
 1 [PCH            ]: HDA-Intel - HDA Intel PCH
                      HDA Intel PCH at 0xefa30000 irq 42
 2 [NVidia         ]: HDA-Intel - HDA NVidia
                      HDA NVidia at 0xef080000 irq 17
 3 [U0x4510x9010   ]: USB-Audio - USB Device 0x451:0x9010
                      USB Device 0x451:0x9010 at usb-0000:00:14.0-1.2, full speed


Each card has its own directory with text files about various info, for example the eZdsp USB devboard/souncard:
Code: [Select]
$ cat /proc/asound/card3/usbmixer
USB Mixer: usb_id=0x04519010, ctrlif=0, ctlerr=0
Card: USB Device 0x451:0x9010 at usb-0000:00:14.0-1.2, full speed
  Unit: 2
    Control: name="PCM Playback Volume", index=0
    Info: id=2, control=2, cmask=0x3, channels=2, type="S16"
    Volume: min=-1536, max=7424, dBmin=-600, dBmax=2900
  Unit: 2
    Control: name="PCM Playback Switch", index=0
    Info: id=2, control=1, cmask=0x0, channels=1, type="INV_BOOLEAN"
    Volume: min=0, max=1, dBmin=0, dBmax=0
  Unit: 5
    Control: name="Mic Capture Switch", index=0
    Info: id=5, control=1, cmask=0x0, channels=1, type="INV_BOOLEAN"
    Volume: min=0, max=1, dBmin=0, dBmax=0

Code: [Select]
$ cat /proc/asound/card3/stream0
USB Device 0x451:0x9010 at usb-0000:00:14.0-1.2, full speed : USB Audio

Playback:
  Status: Stop
  Interface 2
    Altset 1
    Format: S16_LE
    Channels: 2
    Endpoint: 0x02 (2 OUT) (ADAPTIVE)
    Rates: 48000, 16000
    Bits: 16
    Channel map: FL FR

Capture:
  Status: Stop
  Interface 1
    Altset 1
    Format: S16_LE
    Channels: 1
    Endpoint: 0x81 (1 IN) (ASYNC)
    Rates: 16000
    Bits: 16
    Channel map: MONO




And for the analog chipset on the motherboard:
Code: [Select]
$ cat /proc/asound/card1/codec#0
Codec: Creative CA0132
Address: 0
AFG Function Id: 0x1 (unsol 1)
Vendor Id: 0x11020011
Subsystem Id: 0x18491020
Revision Id: 0x100918
No Modem Function Group found
Default PCM:
    rates [0x0]:
    bits [0x0]:
    formats [0x0]:
Default Amp-In caps: N/A
Default Amp-Out caps: N/A
State of AFG node 0x01:
  Power states:  D0 D3 D3cold S3D3cold CLKSTOP EPSS
  Power: setting=D0, actual=D0
GPIO: io=0, o=0, i=0, unsolicited=1, wake=1
Node 0x02 [Audio Output] wcaps 0x49d: Stereo Amp-Out
  Device: name="CA0132 Analog", type="Audio", device=0
  Amp-Out caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-Out vals:  [0x44 0x44]
  Converter: stream=0, channel=0
  PCM:
    rates [0x5ec]: 16000 22050 44100 48000 88200 96000 192000
    bits [0x1f]: 8 16 20 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x03 [Audio Output] wcaps 0x49d: Stereo Amp-Out
  Amp-Out caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-Out vals:  [0x5a 0x5a]
  Converter: stream=0, channel=0
  PCM:
    rates [0x5ec]: 16000 22050 44100 48000 88200 96000 192000
    bits [0x1f]: 8 16 20 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x04 [Audio Output] wcaps 0x49d: Stereo Amp-Out
  Amp-Out caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-Out vals:  [0x5a 0x5a]
  Converter: stream=0, channel=0
  PCM:
    rates [0x5ec]: 16000 22050 44100 48000 88200 96000 192000
    bits [0x1f]: 8 16 20 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x05 [Audio Output] wcaps 0x691: Stereo Digital
  Control: name="IEC958 Playback Con Mask", index=0, device=0
  Control: name="IEC958 Playback Pro Mask", index=0, device=0
  Control: name="IEC958 Playback Default", index=0, device=0
  Control: name="IEC958 Playback Switch", index=0, device=0
  Control: name="IEC958 Default PCM Playback Switch", index=0, device=0
  Device: name="CA0132 Digital", type="SPDIF", device=1
  Converter: stream=0, channel=0
  Digital:
  Digital category: 0x0
  IEC Coding Type: 0x0
  PCM:
    rates [0x5e0]: 44100 48000 88200 96000 192000
    bits [0x1e]: 16 20 24 32
    formats [0x5]: PCM AC3
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x06 [Audio Output] wcaps 0x691: Stereo Digital
  Converter: stream=0, channel=0
  Digital:
  Digital category: 0x0
  IEC Coding Type: 0x0
  PCM:
    rates [0x5e0]: 44100 48000 88200 96000 192000
    bits [0x1e]: 16 20 24 32
    formats [0x5]: PCM AC3
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x07 [Audio Input] wcaps 0x10059b: Stereo Amp-In
  Device: name="CA0132 Analog", type="Audio", device=0
  Amp-In caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-In vals:  [0x5a 0x5a]
  Converter: stream=0, channel=0
  SDI-Select: 0
  PCM:
    rates [0x1ec]: 16000 22050 44100 48000 88200 96000
    bits [0x1f]: 8 16 20 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x12
Node 0x08 [Audio Input] wcaps 0x10059b: Stereo Amp-In
  Control: name="Analog-Mic2 Capture Volume", index=0, device=0
    ControlAmp: chs=3, dir=In, idx=0, ofs=0
  Control: name="Analog-Mic2 Capture Switch", index=0, device=0
    ControlAmp: chs=3, dir=In, idx=0, ofs=0
  Device: name="CA0132 Analog Mic-In2", type="Audio", device=2
  Amp-In caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-In vals:  [0x5a 0x5a]
  Converter: stream=0, channel=0
  SDI-Select: 0
  PCM:
    rates [0x1ec]: 16000 22050 44100 48000 88200 96000
    bits [0x1f]: 8 16 20 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x11
Node 0x09 [Audio Input] wcaps 0x100791: Stereo Digital
  Control: name="IEC958 Capture Switch", index=0, device=0
  Control: name="IEC958 Capture Default", index=0, device=0
  Device: name="CA0132 Digital", type="SPDIF", device=1
  Converter: stream=0, channel=0
  SDI-Select: 0
  Digital: Enabled
  Digital category: 0x0
  IEC Coding Type: 0x0
  PCM:
    rates [0x5f0]: 32000 44100 48000 88200 96000 192000
    bits [0x1a]: 16 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x0e
Node 0x0a [Audio Input] wcaps 0x10079b: Stereo Digital Amp-In
  Control: name="What U Hear Capture Volume", index=0, device=0
    ControlAmp: chs=3, dir=In, idx=0, ofs=0
  Control: name="What U Hear Capture Switch", index=0, device=0
    ControlAmp: chs=3, dir=In, idx=0, ofs=0
  Device: name="CA0132 What U Hear", type="Audio", device=4
  Amp-In caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-In vals:  [0x5a 0x5a]
  Converter: stream=0, channel=0
  SDI-Select: 0
  Digital:
  Digital category: 0x0
  IEC Coding Type: 0x0
  PCM:
    rates [0x1ec]: 16000 22050 44100 48000 88200 96000
    bits [0x1b]: 8 16 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x13
Node 0x0b [Pin Complex] wcaps 0x400581: Stereo
  Pincap 0x00010014: OUT EAPD Detect
  EAPD 0x2: EAPD
  Pin Default 0x01014010: [Jack] Line Out at Ext Rear
    Conn = 1/8, Color = Green
    DefAssociation = 0x1, Sequence = 0x0
  Pin-ctls: 0x40: OUT
  Unsolicited: tag=05, enabled=1
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x02
Node 0x0c [Pin Complex] wcaps 0x400701: Stereo Digital
  Pincap 0x00000010: OUT
  Pin Default 0x014580f0: [Jack] SPDIF Out at Ext Rear
    Conn = Optical, Color = Purple
    DefAssociation = 0xf, Sequence = 0x0
  Pin-ctls: 0x40: OUT
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x05
Node 0x0d [Pin Complex] wcaps 0x400701: Stereo Digital
  Pincap 0x00000010: OUT
  Pin Default 0x014570f0: [Jack] SPDIF Out at Ext Rear
    Conn = Optical, Color = Yellow
    DefAssociation = 0xf, Sequence = 0x0
  Pin-ctls: 0x00:
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x06
Node 0x0e [Pin Complex] wcaps 0x400681: Stereo Digital
  Pincap 0x00000020: IN
  Pin Default 0x01c530f0: [Jack] SPDIF In at Ext Rear
    Conn = Optical, Color = Blue
    DefAssociation = 0xf, Sequence = 0x0
  Pin-ctls: 0x00:
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x0f [Pin Complex] wcaps 0x400581: Stereo
  Pincap 0x0000001c: OUT HP Detect
  Pin Default 0x0221401f: [Jack] HP Out at Ext Front
    Conn = 1/8, Color = Green
    DefAssociation = 0x1, Sequence = 0xf
  Pin-ctls: 0x00:
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x02
Node 0x10 [Pin Complex] wcaps 0x400581: Stereo
  Pincap 0x0000001c: OUT HP Detect
  Pin Default 0x02216011: [Jack] HP Out at Ext Front
    Conn = 1/8, Color = Orange
    DefAssociation = 0x1, Sequence = 0x1
  Pin-ctls: 0x00:
  Unsolicited: tag=01, enabled=1
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x03
Node 0x11 [Pin Complex] wcaps 0x40058b: Stereo Amp-In
  Amp-In caps: ofs=0x00, nsteps=0x03, stepsize=0x27, mute=0
  Amp-In vals:  [0x00 0x00]
  Pincap 0x00003734: IN OUT Detect
    Vref caps: HIZ 50 GRD 80 100
  Pin Default 0x02012014: [Jack] Line Out at Ext Front
    Conn = 1/8, Color = Grey
    DefAssociation = 0x1, Sequence = 0x4
  Pin-ctls: 0x24: IN VREF_80
  Unsolicited: tag=04, enabled=1
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x04
Node 0x12 [Pin Complex] wcaps 0x40048b: Stereo Amp-In
  Control: name="Mic1-Boost (30dB) Capture Switch", index=0, device=0
    ControlAmp: chs=1, dir=In, idx=0, ofs=0
  Amp-In caps: ofs=0x00, nsteps=0x03, stepsize=0x27, mute=0
  Amp-In vals:  [0x00 0x00]
  Pincap 0x00003724: IN Detect
    Vref caps: HIZ 50 GRD 80 100
  Pin Default 0x37a791f0: [Jack] Mic at Oth Mobile-In
    Conn = Analog, Color = Pink
    DefAssociation = 0xf, Sequence = 0x0
    Misc = NO_PRESENCE
  Pin-ctls: 0x24: IN VREF_80
  Unsolicited: tag=02, enabled=1
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x13 [Pin Complex] wcaps 0x400681: Stereo Digital
  Pincap 0x00000020: IN
  Pin Default 0x908700f0: [Fixed] Line In at Int N/A
    Conn = Analog, Color = Unknown
    DefAssociation = 0xf, Sequence = 0x0
  Pin-ctls: 0x20: IN
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x14 [Beep Generator Widget] wcaps 0x70040c: Mono Amp-Out
  Amp-Out caps: ofs=0x1f, nsteps=0x1f, stepsize=0x05, mute=1
  Amp-Out vals:  [0x1f]
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x15 [Vendor Defined Widget] wcaps 0xf00600: Mono Digital
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x16 [Vendor Defined Widget] wcaps 0xf00680: Mono Digital
  Unsolicited: tag=03, enabled=1
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x17 [Audio Output] wcaps 0x49d: Stereo Amp-Out
  Amp-Out caps: ofs=0x5a, nsteps=0x63, stepsize=0x03, mute=1
  Amp-Out vals:  [0x5a 0x5a]
  Converter: stream=0, channel=0
  PCM:
    rates [0x5ec]: 16000 22050 44100 48000 88200 96000 192000
    bits [0x1f]: 8 16 20 24 32
    formats [0x1]: PCM
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
Node 0x18 [Pin Complex] wcaps 0x400581: Stereo
  Pincap 0x00000010: OUT
  Pin Default 0x500000f0: [N/A] Line Out at Int N/A
    Conn = Unknown, Color = Unknown
    DefAssociation = 0xf, Sequence = 0x0
  Pin-ctls: 0x00:
  Unsolicited: tag=00, enabled=0
  Power states:  D0 D3 EPSS
  Power: setting=D0, actual=D0
  Connection: 1
     0x17


From the last one it seems the Creative CA0132 chipset can only sample here (in Kubuntu/ALSA) at 96kHz, while 192kHz sampling is available only for playback.

(The previously attached spectrum pics were captured with 'baudline' in FreeBSD/OSS.  Considering Kubuntu/ALSA only has 96kHz recording, I think the 192kHz at recording in 'baudline' FreeBSD/OSS was fake.)
Title: Re: Audio in Linux
Post by: PKTKS on July 16, 2022, 02:57:51 pm
aplay -l    ( L lowcase stands LIST )
Absolutely; and
    arecord -L
lists all PCM devices one can read from.
(And why didn't I suggest that first, and instead jumped to code :palm:)

Furthermore,
    arecord -D name --dump-hw-params
lists the actual hardware capabilities for the PCM device (in recording mode). 


nah.. your code is supreme correct stuff...
you can NOT expect to use that call under C with some exec and parse results...
so your code does the correct query

But on console with dumb interpreters you can config and query DCONF setups
Code: [Select]
TRY
aplay -vv -D plug:monitor
and
arecord -D plug:capture
to check defined setups for monitor and capture

at last  try aplay -L    (L capital)

Paul  ^-^
Title: Re: Audio in Linux
Post by: JohanH on July 17, 2022, 07:42:24 am
I just dnf  installed pipewire on another computer (Fedora32)


Fedora 32 is more than two years old and has been End-of-life since 2021‑05‑25. Pipewire was shipped first in Fedora 34. Current Fedora (36) comes with Pipewire as default.
Title: Re: Audio in Linux
Post by: RoGeorge on July 17, 2022, 08:22:27 am
At this point the sound architecture in Linux seems clear enough to me, and I have no more problems understanding how OSS or ALSA interacts with JACK or with PulseAudio, thank you all for helping me with that.

This doesn't mean my onboard CA0132 works as expected.  ;D

I've started to suspect the driver, and searched for Linux driver problems with CA0132 (Creative Sound Core3D).  CA0132 is a chip embedded in many motherboards and gaming laptops, and yes, all the weird behavior I've seen so far happens to others, too.

It seems that's because of the drivers having either incomplete support, or bugs, and not because of ALSA or PulseAudio.
https://bugzilla.kernel.org/buglist.cgi?quicksearch=ca0132

Not sure if I want to go deeper in this rabbit hole.

Most of those bugs specific for CA0132 do happen in my desktop, too, and some of the bugs have experimental patches (e.g. https://bugzilla.kernel.org/show_bug.cgi?id=67071 reply #7).  I'm familiar with the idea of compiling, but don't know anything about kernel dev workflow.

1. - How difficult is to apply a patch?
2. - Do I need to recompile the whole kernel, or the driver is just a separated module to be compiled then loaded?
3. - Do I need to manually re-apply the patch and recompile forever, at each new kernel version upgrade pushed by Ubuntu updates?
4. - I've seen this:  https://help.ubuntu.com/community/Kernel/Compile Is this a good start, do I need other link to read for a brief intro about how this is usually done (applying a custom patch, then dealing with it at each future kernel version upgrade)?

These are too broad questions to google, and I'm only trying to evaluate how difficult would be, not trying to become a kernel dev.  From (4.) it seems that I shouldn't compile the whole kernel (the Ubuntu kernel compile page sais at reasons to NOT recompile the kernel "You merely need to compile a special driver. For this, you only need to install the linux-headers packages." ), but I still don't know how to apply the patch to sources and what exactly to recompile to get a patched CA0132 driver.  :-//
Title: Re: Audio in Linux
Post by: RoGeorge on July 17, 2022, 09:15:01 am
The driver for CA0132 seems to be a loaded kernel module:
Code: [Select]
$ lsmod | grep ca0132
Module                  Size  Used by
snd_hda_codec_ca0132   139264  1
snd_hda_codec         155648  3 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec_ca0132
snd_hda_core          106496  4 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec,snd_hda_codec_ca0132
snd_pcm               135168  9 snd_hda_codec_hdmi,snd_hda_intel,snd_hda_codec,snd_soc_rt5640,snd_compress,snd_soc_core,snd_hda_core,snd_hda_codec_ca0132,snd_pcm_dmaengine
snd                   102400  24 snd_seq,snd_seq_device,snd_hda_codec_hdmi,snd_hwdep,snd_hda_intel,snd_hda_codec,snd_timer,snd_compress,snd_soc_core,snd_pcm,snd_hda_codec_ca0132,snd_rawmidi

Code: [Select]
$ find /lib/modules/$(uname -r) -type f -iname '*ca0132*.ko*'
/lib/modules/5.15.0-41-generic/kernel/sound/pci/hda/snd-hda-codec-ca0132.ko

So I should patch and recompile only the "snd-hda-codec-ca0132.ko" for the given kernel version, but without recompiling the whole Linux kernel, then load the patched module instead of the official "snd-hda-codec-ca0132.ko", did I get it right?
Title: Re: Audio in Linux
Post by: DiTBho on July 17, 2022, 09:58:43 am
This doesn't mean my onboard CA0132 works as expected.  ;D

pretty like the onboard sound chip on my HPPA workstation, and if it's soldered onboard ... you cannot change it.

That's why I suggested you to buy an USB-sound card, choosing from one of the most Linux-friendly available.

weird behavior I've seen so far happens to others, too.

In my case, the sound chip is basically a couple of ADC with a FIFO and a weird ASIC circuit to control it, and there is a weird (crazy?) mode that allows the software to take samples only when the FIFO is full, this means that you are not sampling at the regular sample rate (let's say at 100Khz) because the filling of the FIFO depends on the speed with which the kernel reads the data to empty it, which must be considered "random behavior" since it depends on random factors.

To me, it makes no sense, but ... some engineers must have thought otherwise, and when some hobbyists like me tried to write a driver for Linux ... they came up with a mess (I don't blame them, it's really a very bad sound chip)... worse still for an experimental abandoned platform so you have ZERO interest from the Linux Devs

I wrote a kernel module assigning a timer to the ADC so the kernel reads the FIFO on regular frequency base and assign a timestamp to the samples. This solved my problem in a very simple way, but then ... it's not OSS compliant and it doesn't make the driver a "sound driver" (actually it's an ADC driver) therefore you have to deal with other parts of the kernel and with other parts of the userspace.

If you follow the rabbit down its hole ... well, it really goes deeper and faster than you ever imagined.

1. - How difficult is to apply a patch?
2. - Do I need to recompile the whole kernel, or the driver is just a separated module to be compiled then loaded?
3. - Do I need to manually re-apply the patch and recompile forever, at each new kernel version upgrade pushed by Ubuntu updates?
4. - I've seen this:  https://help.ubuntu.com/community/Kernel/Compile Is this a good start, do I need other link to read for a brief intro about how this is usually done (applying a custom patch, then dealing with it at each future kernel version upgrade)?

1: you have to use the program "patch". Not complex, but you have to consider how patches are generated and handled. If a patch comes from a mailing list and it's "text malformed" you have to fix it before you can apply. That's not complex, it's simply annoying, but that's it.

2: it depends. If the kernel module has some dependency with the whole kernel tree, you have to recompile everything, otherwise you can create a special Makefile that only re-compiles your kernel module, it just needs to "point" the kernel source (especially for headers) and it will compile nothing but  local files.

3: yes, unless the patch is integrated into the Vanilla source, if someone sends it to Linus Torvalds and * he * approves the code, in this case you will find it already applied into the latest binary kernel you will get from Ubuntu

4: dunno, here it's a personal path, mine started many many years ago with kernel 2.0.* , too years ago to remember how how I learned things


Code: [Select]
# mybuild

   kernel-5.14.1(arm.32/nanopi-neo)

tc) show toolchain version
up) script_update

 0) clean
 1) configure
 2) compile app
 3) app module
 4) tftp kernel-nanopi-neo@192.168.1.21:
 5) tools

app_name       = kernel-5.14.1-32bit-nanopi-neo
machine_note   = experimental
qualified_host = macmini-intel

Code: [Select]
# mybuild 5

[step5] tools
  1 - list actually used source
  2 - archive actually_used_source
  3 - backup files
  4 - list all files to be patched
  5 - apply patches
  6 - make patches
  7 - revert patches

Code: [Select]
# mybuild 5 6
[step5] tools
[step5.6] make patches
~ Makefile ... success
~ lib/dump_stack.c ... success
~ mm/page_alloc.c ... success
~ scripts/setlocalversion ... success
~ arch/arm/Kconfig ... success
~ init/main.c ... success
~ arch/arm/kernel/setup.c ... success
~ arch/arm/kernel/smp.c ... success
~ lib/dump_stack.c ... success
~ init/version.c ... success
~ mm/page_alloc.c ... success
~ kernel/printk/printk.c ... success
~ kernel/panic.c ... success
~ scripts/mkuboot.sh ... success
~ scripts/Makefile.lib ... success

Code: [Select]
# mybuild 2
[step2] compiling
kernel-5.14.1(arm/nanopi-neo)
toolchain(armv7a-unknown-linux-gnueabihf:2.34/9.3.0)
app_name       = kernel-5.14.1-32bit-nanopi-neo
machine_note   = experimental
qualified_host = macmini-intel
-----------------------------------------------
gadget_to_do(build) ... kernel/build
gadget_to_do(clean) ... kernel/clean
building kernel ... success
building dtb ... success
-----------------------------------------------
gadget_to_do(binary) ... overlay/binary
gadget_to_do(sweep) ... kernel/sweep
ram_size=32768
slice loading ... done, 22378 byte
slice saving ... done, 32768 byte
gadget_to_do(binary_report) ... kernel/binary_report

It uses a global recipe that can be overridden by a local recipe
Code: [Select]
# mybuild recipe
- version
- platform
- machine_arch_32
- machine_arch_64
- machine_loadaddr
- machine_image
- machine_note
- machine_bits
- platform
- chosen
- product
- tftp_server_ip
- toolchain_32
- toolchain_64
- binutils_ver_min
- binutils_ver_max
- gcc_ver_max
- gcc_ver_min
- gcc_opt
- qualified_host
- tftp_file_name
- overlay { check_tools.list, binary, binary_report, build, clean, sweep, uImage, dtb, tftp }
It tells you how it was compiled, on which machines (qualified hosts, can be virtual machines), with which toolchain, options, and it also reports things that are mandatory. So I can easily forget and don't care about details, this is useful when you have to deal with sources that can age faster than how you can remember or manage.
Title: Re: Audio in Linux
Post by: DiTBho on July 17, 2022, 10:06:26 am
So I should patch and recompile only the "snd-hda-codec-ca0132.ko" for the given kernel version, but without recompiling the whole Linux kernel, then load the patched module instead of the official "snd-hda-codec-ca0132.ko", did I get it right?

yup. If the patch doesn't touch nothing but the kernel audio module of you card, you can recompile only it.

I suggest you to create a local folder, copy the kernel module there, apply the patch locally, and to create a Makefile to force the local module to be compiled.

Inside the Makefile you only have to "point" the path of the kernel source of reference.
Title: Re: Audio in Linux
Post by: RoGeorge on July 17, 2022, 03:00:59 pm
Thanks for the details, it looks too complicated.

Even if it were for those patches to fix my problem, which they might not, I don't really need a patch fix.  Given that I only needed that once in many years, to measure some circuit, I could simply boot in FreeBSD and measure from there, or from Kubuntu I could use the Mic2 input (which is in fact line-in) and pipe the datastream to the stdin with arecord, then take it from there and display spectrum and distortions with existing tools like 'baudline', like this:

Code: [Select]
        systemctl --user stop pulseaudio.{socket,service}
        # !!! line-in CA0132 only working after VLC is started with CA0132 as sound device
        #     then it keeps working even when VLC is stopped, some initialization problems ???
        # Others observed CA0132 working only after rebooting from Windows to Linux
        #     i.e. last reply from baxter_stockman https://forum.level1techs.com/t/creative-core3d-audio-linux-support/112295/9

        arecord -D hw:2,2 -B 10000 -r 96000 -f S16_LE -c 2 | ./baudline -stdin -record -channels 2 -format le16
        systemctl --user start pulseaudio.{socket,service}
Title: Re: Audio in Linux
Post by: magic on July 17, 2022, 03:40:33 pm
Run alsamixer and try setting volume and unmuting relevant channels and selecting the input source. Press F4 to see the recording controls instead of playback.
Title: Re: Audio in Linux
Post by: PKTKS on July 17, 2022, 04:11:48 pm
Thanks for the details, it looks too complicated.

Even if it were for those patches to fix my problem, which they might not, I don't really need a patch fix.  Given that I only needed that once in many years, to measure some circuit, I could simply boot in FreeBSD and measure from there, or from Kubuntu I could use the Mic2 input (which is in fact line-in) and pipe the datastream to the stdin with arecord, then take it from there and display spectrum and distortions with existing tools like 'baudline', like this:

Code: [Select]
        systemctl --user stop pulseaudio.{socket,service}
        # !!! line-in CA0132 only working after VLC is started with CA0132 as sound device
        #     then it keeps working even when VLC is stopped, some initialization problems ???
        # Others observed CA0132 working only after rebooting from Windows to Linux
        #     i.e. last reply from baxter_stockman https://forum.level1techs.com/t/creative-core3d-audio-linux-support/112295/9

        arecord -D hw:2,2 -B 10000 -r 96000 -f S16_LE -c 2 | ./baudline -stdin -record -channels 2 -format le16
        systemctl --user start pulseaudio.{socket,service}

It does not seem from here a patch problem... but a proprietary firmware blob issue

issue a modinfo to see which firmware blob required
Code: [Select]
>modinfo snd-hda-codec-ca0132
description:    Creative Sound Core3D codec
license:        GPL
firmware:       ctefx-r3di.bin
firmware:       ctefx-sbz.bin
firmware:       ctefx.bin
alias:          hdaudio:v11020011r*a01*
depends:        snd-hda-core,snd-hda-codec,snd,snd-pcm
intree:         Y
name:           snd_hda_codec_ca0132
vermagic:       4.19.136 SMP mod_unload K8


fussing my firmware  repos I have none of them
firmware:       ctefx-r3di.bin
firmware:       ctefx-sbz.bin
firmware:       ctefx.bin

Not for my stable 4.xx branch ... and obviously not for the in test 5.xx SMP tree..
Paul

btw... this a typical case why  it works on winzzz (they paid support from oem and have in tree blobs) and does not for other customers which bought their card outside the winxx club...

classic case of defective by design CERTIFIED - only works with...
Title: Re: Audio in Linux
Post by: DiTBho on July 17, 2022, 05:50:48 pm
this a typical case why  it works on winzzz (they paid support from oem and have in tree blobs)

that's the same for Android, e.g. what Allwinner does with - at least - blobs for ther Thermal Units and GPUs: affected H3*, H5*, A64* SoCs


Title: Re: Audio in Linux
Post by: Nominal Animal on July 18, 2022, 05:54:13 am
Since I have microcontrollers with native USB (Teensies) that can do 1 Mbyte/s across an USB isolator by default using USB Serial in Arduino/Teensyduino, that's probably what I'd use.  Teensy LC and 3.1/3.2 have 16-bit ADCs with 12-13 bits effective, although I do also have an ADS1256 board that can do 30kSamples/s at 18-23 effective bits per sample.

The local computer store (Verkkokauppa.com) sells Delock 61645 (https://www.delock.de/produkt/61645/merkmale.html?setLanguage=en) USB 1.1 Audio dongle for 16€.  It supports 48 kHz sample rate at 16 bits per sample, mono input, using CMedia CM119 (https://www.cmedia.com.tw/support/download_center?type=495_datasheet) chipset (one of those all-in USB chipsets).  It implements USB Audio 1.0, so uses the standard USB audio drivers, not anything custom.  That is good.  It would be cheap enough to take apart, IMO, to use as a simple one-channel el-cheapo "DAQ".  (It might have microphone boost – a bias voltage – always on, but since the datasheet is available, it'd be a fun project to mangle it beyond recognition.  It also has I2C one can use to access its internal registers from a separate microcontroller, you see.)

In all cases, I'd run the "data aquisition" over USB, using an el-cheapo USB isolator (ADuM3160/4160), because me being me, I probably will do something stupid or accidentally short some parts that Should Not Be Shorted, so all I'd lose at most was anything dangling off the USB isolator.  For best results, I'd not use the downstream DC-DC 5V, but batteries instead –– maybe 9V, maybe 5-7 AA batteries or accumulators in series, followed by a 5V regulator, to minimize supply noise.

There are some sellers of Analog AD7705 (https://www.analog.com/media/en/technical-documentation/data-sheets/AD7705_7706.pdf) break-out-boards with LM285-2.5 reference voltages in Europe on Ebay, with 4.9152MHz crystal oscillators (therefore very good sample rate stability as well), which should do 76.8kHz sample rate at 16 bits per sample at even unity gain (0 to 2.5V).  (With 8× to 128× gain, 614.4kHz.)
With larger voltage swing, I'd add an op-amp buffer and a voltage divider in front, though; I'm not sure how good its internal buffer op-amp is (it can be disabled).  It has a SPI interface (400 kHz to 2.5 MHz clock frequency), so you obviously need a microcontroller to interface to one.  Teensy LC (https://www.pjrc.com/teensy/teensyLC.html) does have a real 12-bit DAC on it, so if I used that one, I could wire one of the AD7705 inputs directly (via buffer and/or voltage divider and possibly a low-pass filter, maybe) to that, to verify the actual performance characteristics.

Or I could use the Analog Discovery 2 that I have.

Me being me, if I were to use the built-in audio line-in directly, I'd for sure poke something with something conductive and release The Magic Smoke.  That's why I always keep at least one el-cheapo USB isolator at hand: I use them even when just playing in Arduino/Teensyduino with one of my microcontrollers.  You know, like belt and suspenders: it may look silly, but at least my trousers stay up.
Title: Re: Audio in Linux
Post by: PKTKS on July 18, 2022, 01:17:06 pm
Apparently ALSA team folks manage to get some blobs

https://forums.opensuse.org/showthread.php/542035-No-sound

I will download the version and check asap...

All folks with similar chipset have the same issue

Paul

PS piece of cake... they hardly miss a thing.. the blobs are on the referred package and should be manually installed
Title: Re: Audio in Linux
Post by: DiTBho on July 18, 2022, 01:37:20 pm
Analog Discovery 2

That's a great kit for low frequency projects! I will buy one soon, too!  :D
Title: Re: Audio in Linux
Post by: RoGeorge on July 18, 2022, 02:04:06 pm
Meanwhile:
- tried a live disk with Ubuntu 20.04 LTS to check against possible missconfigurations/leftovers on the native install, sound behavior with the live disk is the same as in the native install
- tried from a live pendrive the latest Pop!-OS 22.04 LTS, which is a distro based on Ubuntu 22.04 LTS, but customized and with a more recent kernel than Ubuntu, nope, same problems
- tried to replace ALSA (from Kubuntu 20.04 LTS) with native OSS4 (nota alsa oss emulation), and I couldn't, got no sound at all and installed back ALSA

- found out that there is some flags called "Quirks" in the driver sources, i.e.:
https://github.com/torvalds/linux/blob/master/sound/pci/hda/patch_ca0132.c
Code: [Select]
            /*
            * CA0132 quirks table
            */
            enum {
                QUIRK_NONE,
                QUIRK_ALIENWARE,
                QUIRK_ALIENWARE_M17XR4,
                QUIRK_SBZ,
                QUIRK_ZXR,
                QUIRK_ZXR_DBPRO,
                QUIRK_R3DI,
                QUIRK_R3D,
                QUIRK_AE5,
                QUIRK_AE7,
            };

Those names are in fact sligtly different models/boards of the same Creative Core3D chipset, and they seem to map the audio connectors and other hardware capabilities to each model.

It seems the proper Quirk is autodetected by looking at the chip ID, but I suspect the Quirk model can be forced from config files, probably from '/etc/modprobe.d/alsa-base.conf'.  There might be possible to add a line there ''options snd-hda-intel model=?my_particular_chipset_config?" but I'm not sure what to write there, the int from the enum, only the commercial name, or full C name from the enum.  I've tried with "model=r3d" and "model=alienware", then rebooted, but I see no changes.



Another aspect that intrigues me is that in the 'patch_ca0132.c' sources the sampling can be up to 384kHz, but in OSS/FreeBSD the rec sampling is 48kHz, and in ALSA/Kubuntu can be max 96kHz.  :-//

Oh, and I still couldn't find how to change between 16/24 bits sampling.  The number representation doesn't affect the sampling depth, even with arecord numbers format u8, the dynamic range seems to be the same, with a noise floor somewhere around -110...-120dB, which suggests the ADC sampling depth might be 24 bits.



... el-cheapo "DAQ"...

That's exactly what the sound card was supposed to be, el-cheapo audio DAQ yet with outstanding specs (lower noise than I would achieve breadboarding my own DAQ, and 24bits/96kHz, plus countless software tools to handle the data).

Well, except that Creative for sound is like nVidia for video, when it comes to Linux, and this desktop have them both.  ;D
Title: Re: Audio in Linux
Post by: RoGeorge on July 18, 2022, 02:20:58 pm
Analog Discovery 2

That's a great kit for low frequency projects! I will buy one soon, too!  :D

At some point I was tempted too, but I found it quite expensive, and I already have similar or better devboards.  From those searches for similar educational boards, I remember the ADALM1000, from Analog Devices.

ADALM1000 (https://www.analog.com/en/design-center/evaluation-hardware-and-software/evaluation-boards-kits/ADALM1000.html) was about 5 times cheaper, and it is in fact a dual SMU 5V/100mA that can play and record quite fast, which is a nice tool to have around the lab.

There is a newer model, ADALM2000, has more gimmicks and it's more expensive, but it lost its SMU specs, to me ADALM1000 was more tempting (but didn't buy).  Both versions have plenty of ADI classes and labs examples, just like Analog Discovery eduboards have, too.
Title: Re: Audio in Linux
Post by: magic on July 18, 2022, 09:07:34 pm
It seems the proper Quirk is autodetected by looking at the chip ID, but I suspect the Quirk model can be forced from config files, probably from '/etc/modprobe.d/alsa-base.conf'.  There might be possible to add a line there ''options snd-hda-intel model=?my_particular_chipset_config?" but I'm not sure what to write there, the int from the enum, only the commercial name, or full C name from the enum.  I've tried with "model=r3d" and "model=alienware", then rebooted, but I see no changes.
Looking at static int patch_ca0132(struct hda_codec *codec) that doesn't seem to be the case at all.

What is the actual problem you are trying to solve?

If you are absolutely sure you need the quirk, you need to patch the module. Get the patch_ca0132.c file corresponding to your kernel version and save it somewhere. You will need a few other .h files from sound/pci/hda/ too. Add the following Makefile and build the module. You will need linux-headers package installed.
Code: [Select]
obj-m += patch_ca0132.o

all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

When ready, as root:
Code: [Select]
rmmod patch_ca0132
insmod ./patch_ca0132.ko
Title: Re: Audio in Linux
Post by: RoGeorge on July 19, 2022, 11:50:53 am
What is the actual problem you are trying to solve?

That's a very good question!  ;D

The goal drifted from using a sound card as an audio spectrum analyzer  -->  audio software and OS tools in Ubuntu and FreeBSD  -->  sound system architectures for the two OSs  -->  various config files for various components  -->  particular bugs in the driver for Creative Sound Core3D chipset CA0132  -->  experimental patches for CA0132 driver  -->  how the "Intel HDA" module interacts with the CA0132 driver  -->  understanding CA0132 chipset architecture (e.g. CA0132 has a DSP blob, apparently an embedded 8051 core too, to control the DSP hardware, etc.)  -->  how to send parameters to a driver module and what parameters are supported  -->  how to recompile the Ubuntu kernel or, in this particular situation just the CA0132 driver module.  To me that was a very interesting learning journey, thank you all for guidance!

While at it, would have been nice to fix some minor inconveniences bugs for the onboard CA0132 like:
- once in a while, only at power on (either cold start or wake from a suspend to RAM), it will be no audio out
- can not switch to headphones, HP output does not work
- can only work in stereo mode, while the chipset is 5.1
- audio connectors are swapped, the 3.5mm jacks does not match the motherboard manual
- weird Mic2 instead of Line-In (didn't check yet if this Mic2-In can also turn on mic phantom power, that would be wrong to do for a line-in)



You are correct about the Quirk values in drivers, vs loading the kernel modules with parameters.  After more reading, it turns out that 'snd-hda-intel' module (common for any HDA compatible card, including for CA0132) can have a parameter 'model=generic', which can be set inside '/etc/modprobe.d/alsa-base.conf' by adding 'options snd-hda-intel model=generic'.  This will tell to the CA0132 module 'snd_hda_codec_ca0132' to load one of the "Quirk" remapings, depending on each CA0132 PCI ID vendor:model.



Just for the docs, the motherboard is Asrock model "Z97 Fatal1ty Professional", and the CA0132 id is 1102:0011, which is different from any of the values currently present in the CA0132 patch.  However, it feels like the work from similar chips with different IDs should be applicable to the one from the AsRock motherboard.  For the docs, this is the most promising thread for patching the CA0132 (especially the Connor McAdams' posts), and I would like to try that as an exercise of compiling patches and fiddling with driver modules in Linux:
https://bugzilla.kernel.org/show_bug.cgi?id=109191#c66 (https://bugzilla.kernel.org/show_bug.cgi?id=109191#c66)
https://kernelnewbies.org/KernelBuild (https://kernelnewbies.org/KernelBuild)



Back to the global goal, of using the sound card as an audio spectrum analyzer, in order to measure the distortions coming from an external Peltz oscillator, in Linux I've used 'baudline' + 'arecord'.  The 'arecord' is needed because the free version of 'baudline' was made for OSS (but 'baudline' can record from 'stdin', too  :-+).

To use 'baudline' in Linux (with ALSA), first identify the existing ALSA soundcards/inputs using 'arecord -l'.  Then, start 'arecord' and pipe the audio datastream from 'arecord' to stdin, and then read the stdin datastream with 'baudline', like this:
Code: [Select]
cd baudline_1.08_linux_x86_64
# start the alsamixer, select the soundcard, enable the sound source and set the recording volume
alsamixer
# find hw:<card>,<device> numbers
arecord -l
# mine was
#     card 1: PCH [HDA Intel PCH], device 2: CA0132 Analog Mic-In2 [CA0132 Analog Mic-In2]
#        Subdevices: 1/1
#        Subdevice #0: subdevice #0
# which means "hw:1,2" in the next command, 10000 means 10ms buffer/latency, 96kHz sampling rate, 2 channels
arecord -D hw:1,2 -B 10000 -r 96000 -f S16_LE -c 2 | ./baudline -stdin -record -channels 2 -format le16



The signal from my Peltz-Wyatt oscillator when powered from a single 1.2V battery measures about -29.7dB (3.39%) distortions, so THD > 0.00001%, audiophils:  :scared:.

(https://www.eevblog.com/forum/programming/audio-in-linux/?action=dlattach;attach=1538944;image)


Spectrum and distortions with 'arecord' + 'baudline':
(https://www.eevblog.com/forum/programming/audio-in-linux/?action=dlattach;attach=1542925;image)

The hill in the backround noise floor for frequencies above 25kHz is internal noise from the soundcard.  I don't know if the displayed THD includes the 50Hz hum and the noise, too, or only the fundamental and its harmonics.

 :-DMM
Title: Re: Audio in Linux
Post by: ve7xen on July 19, 2022, 09:22:06 pm
THD shouldn't include non-harmonic noise (that would be THD+N), and the baudline manual confirms this as well. The measurement will include the power in the harmonics, but not non-harmonic noise.

There's a bit of a 'whitepaper' on the baudline site about making various distortion measurements with a sound card at https://www.baudline.com/solutions/sine_distortion/index.html (https://www.baudline.com/solutions/sine_distortion/index.html) that might make for good reading. I believe this narrative implies that baudline's measurements are on single FFT bins, and that's not the only way to do things (more normalized measurements should be possible by using filters, but it creates a bit more ambiguity about the measurement), but it's good stuff to know especially if you're planning on using baudline to make this kind of measurement.

You should definitely make a loopback / reference measurement with a clean sine. Some of these motherboard implementations in my experience have quite poor THD performance; make sure you're actually measuring the DUT.