Porteus Linux: A portable Linux with a difference

Xfce spin of Live Linux distribution Porteus Linux - As-installed desktop on a 1280x1024 monitor.

Xfce spin of Live Linux distribution Porteus Linux - As-installed desktop on a 1280x1024 monitor.

I’m writing this in Porteus Linux v5.0rc1 for x86_64, a Live Linux distribution booted from a USB pendrive. It is fast, good-looking and has a good range of applications and utilities. I stumbled upon Porteus recently while looking for a compact Live Linux distribution to install on a couple of spare SD cards. It seemed ideal, as it is a portable distribution designed for USB pendrives and CDs, and optionally can be configured to be persistent between reboots and shutdowns. Porteus is based on Slackware, although I gather the developers might switch to Arch Linux at some undefined future date. Spins of Porteus with various Desktop Environments are available, and I settled on Xfce after trying a couple of the others.

Although my original objective was to install a portable Linux distribution on SD cards, I only managed to install Porteus on an SD card by using YUMI Multiboot USB Creator for Windows, which I run using WINE in Linux, rather than in Windows. The reason Porteus boots from an SD card when installed by YUMI is because YUMI installs its own boot manager on the SD card and chainloads the OS. Actually, if an SD card or USB pendrive has sufficient capacity, YUMI can install several OSs on a single SD card or single USB pendrive and you can choose from the YUMI bootloader menu which OS to boot.

Anyway, Porteus is interesting because, optionally, it can be configured quite easily to be persistent. I.e. if you want it to, Porteus can save new files, applications you install, browser bookmarks, edited configuration files and so on between reboots/shutdowns. However, I was unable to get persistence working with Porteus installed by YUMI on an SD card, but persistence works perfectly when I install Porteus on USB pendrives, which is the medium Porteus is really designed to be installed on.

I happened to have a couple of spare USB 2.0 pendrives (2GB and 32GB), and I have installed Porteus on both. I opted to configure both to have persistence. There are several ways of making Porteus persistent. The first method is to create a so-called ‘save file’ on the FAT32-formatted pendrive. The second method is to create a second partition on the pendrive, formatted with a Linux filesystem (ext2, ext4, Btrfs, XFS, etc.). Another method is to use ‘Magic Folders’, but I won’t go into that here. I decided to use the first method on the 2GB FAT32-formatted pendrive, and the second method on the 32GB pendrive, which I repartitioned with a 1GB FAT32 partition and the remaining space as an ext4 partition with journalling disabled. Both methods work well. Furthermore, both pendrives boot on a desktop with UEFI firmware and on a laptop with PC BIOS firmware. Neither of the pendrives has its FAT32 partition type set as ef00.

Both pendrives initially had an msdos partition table and a single FAT32 partition. Whether you are installing Porteus from Windows or Linux, it is not mandatory to use UNetbootin, Rufus, YUMI, UUI, dd or any of the other usual methods of installing ISOs on USB pendrives. The unpacked ISO contains the shell script Porteus-installer-for-Linux.com for Linux and the program Porteus-installer-for-Windows.exe for Windows. Instructions for installing to a USB pendrive from either Windows or Linux are given on the Porteus Web site.

I downloaded an ISO file from one of the Porteus repository mirrors listed on the Porteus Web site and used the Linux command line.

Installation on a USB pendrive with a single FAT32 partition

I used a UEFI desktop machine running Lubuntu 18.04, but any machine (either UEFI or BIOS firmware) and Linux distribution would suffice. For my unbranded 2GB pendrive with an msdos partition table and single FAT32 partition, I did the following to install Porteus:

$ sudo blkid # Find which device is the pendrive (sdb in my case)
$ sudo mkdir /mnt/iso
$ sudo mount /home/fitzcarraldo/Downloads/Porteus-XFCE-v5.0rc1-x86_64.iso /mnt/iso
$ sudo mkdir /mnt/pendrive
$ sudo mount /dev/sdb1 /mnt/pendrive
$ sudo cp -a /mnt/iso/* /mnt/pendrive/
$ cd /mnt/pendrive/boot/
$ sudo ./Porteus-installer-for-Linux.com

To enable persistence I needed to edit two configuration files and create a ‘save file’ as follows:

1. Edit /mnt/sdb1/boot/syslinux/porteus.cfg

$ sudo nano /mnt/sdb1/boot/syslinux/porteus.cfg

Change ‘APPEND changes=/porteus‘ to ‘APPEND changes=EXIT:/porteus/porteussave.dat‘:

LABEL GRAPHICAL
MENU LABEL Graphics mode
KERNEL /boot/syslinux/vmlinuz
INITRD /boot/syslinux/initrd.xz
APPEND changes=EXIT:/porteus/porteussave.dat
TEXT HELP
    Run Porteus the best way we can.
    Try to autoconfigure graphics
    card and use the maximum
    allowed resolution
ENDTEXT

Note: The ‘EXIT:‘ makes Porteus save changes when you shutdown or reboot Porteus. If I understand the Porteus tutorials and forum posts correctly, without the ‘EXIT:‘ Porteus would save changes in real time. However, this did not happen in my case, so I had no choice but to add the ‘EXIT:‘ in order to save changes.

2. Edit /mnt/sdb1/porteus/porteus-v5.0-x86_64.cfg

$ sudo nano /mnt/sdb1/porteus/porteus-v5.0-x86_64.cfg

Add the following lines:

changes=/porteus/porteussave.dat
timezone=Europe/London
kmap=gb,us,br

Obviously change the timezone according to your location. You can specify up to three keyboard layouts of your choice. I chose British, US and Brazilian keyboard layouts.

Check you edited the file correctly:

$ grep -v ^# /mnt/sdb1/porteus/porteus-v5.0-x86_64.cfg | grep -v ^$
changes=/porteus/porteussave.dat
timezone=Europe/London
kmap=gb,us,br

3. Create the ‘save file’ when booted into Porteus

The GUI utility ‘Porteus save file manager’ is used to create the file used to save any changes you make in the Live environment. I chose the name porteussave.dat but you can use any name you want, suffixed with .dat. It is mandatory to use such a file if the filesystem is FAT32 or NTFS. Use ‘Applications’ > ‘System’ > ‘Porteus save file manager’ to create a new save file /mnt/sdb1/porteus/porteussave.dat.

With persistence enabled, all my files, browser bookmarks, browsing history and browser configurations remain whenever I boot Porteus. As I explain further down, the configuration changes to ALSA and PulseAudio that I made in order to get Skype working properly persist across reboots.

Porteus ‘modules’

In addition to the configuration for persistence of changes using a ‘save file’ or separate partition, Porteus uses what it calls ‘modules’, pre-packaged binaries with the suffix ‘.xzm‘ that contain either a Desktop Environment or an application. For example, I wanted to install Skype in Porteus and make it persistent, so I downloaded a Slackware package in the Live environment, installed it in the Live environment (right-click and select ‘Install package’), then converted the package to a Porteus module (right-click and select ‘txz2xzm’) and copied the module to the dedicated directory for such modules:

guest@porteus:~$ ls /mnt/sdb1/porteus/modules
firefox-70.0.1-x86_64-en-GB-1.xzm* skypeforlinux-8.18.0.6-x86_64-1_slonly.xzm*

Actually, the Porteus mirrors have some modules already available (‘bundles’), and there is a GUI utility to download and activate them. Alternatively you can download one of these modules yourself from one of the Porteus mirrors and activate it manually by double-clicking on it. To make it persistent you then copy it to the above-mentioned directory /mnt/sdb1/porteus/modules/. There is also a dedicated GUI utility to install a Web browser of your choice and activate the browser module. As you can see in the terminal output copied above, I opted to install Firefox and make it persistent.

The base OS and Desktop Environment are also Porteus modules:

guest@porteus:~$ ls /mnt/sdb1/porteus/base
000-kernel.xzm* 001-core.xzm* 002-xorg.xzm* 003-xfce.xzm*

As I wanted to try the other Desktop Environments, I downloaded the Porteus modules for those and put them in a directory that exists for optional modules:

guest@porteus:~$ ls /mnt/sdb1/porteus/optional
003-cinnamon.xzm* 003-lxde.xzm* 003-mate.xzm*
003-kde.xzm* 003-lxqt.xzm* 003-openbox.xzm*

I can then replace the module /mnt/sdb1/porteus/base/003-xfce.xzm with, for example, 003-kde.xzm to make Porteus use KDE instead of Xfce. Actually, a configuration file can be edited to load a desired Desktop Environment module and inhibit loading the base Desktop Environment module, but I have not tried that method yet.

I downloaded the Porteus modules 07-printing-x86_64-2019-11-12.xzm and 07-printing-lxqt-xfce-x86_64-2019-08-15.xzm from a link given in a Porteus Forums post, copied them to the directory /mnt/sdb1/porteus/modules/ then activated them by double-clicking on each. I was then able to configure CUPS in a browser window (http://localhost:631/admin) and get my old Canon PIXMA MP510 to print using the Gutenprint driver that was already installed without me having to install the Gutenprint printer drivers package. The two modules also enable both XSane and Document Scanner to use the Canon PIXMA MP510’s scanner.

Another ‘bundle’ module I downloaded is onlyoffice-5.0rc1-alldesktops.xzm, an open-source office suite produced by the Latvian company Ascensio System SIA. I had not heard of OnlyOffice before, but it works nicely and has text, spreadsheet and presentation editors with features similar to Microsoft Office (Word, Excel and PowerPoint). I have only tried it very briefly so far and was able to open a Word .docx document, but not an Excel .xlsx spreadsheet, but I still need to evaluate it thoroughly. It not only allows you to create and edit local files, but also to access files in the Cloud. I was able to access my remote ownCloud server documents, for example.

Installation on a USB pendrive using a second partition for persistence

Below I cover in detail the installation and configuration of Porteus on my 32GB USB pendrive.

I used a UEFI desktop machine running Lubuntu 18.04, but any machine (either UEFI or BIOS firmware) and Linux distribution would suffice.

As I wanted to install the Porteus Xfce spin on the pendrive, I downloaded the file Porteus-XFCE-v5.0rc1-x86_64.iso from from one of the Porteus Linux mirrors.

I inserted my Kingston Data Traveller 2.0 32GB USB pendrive into one of the USB ports on the front of the running desktop machine.

Note that I could have used a GUI utility such as GParted to partition and format the pendrive, but I decided to use the command line to do that part.

I opened a terminal window and typed the commands shown below.

1. Find out which device is the USB pendrive

$ sudo blkid # Find out which device the USB pendrive is. It should be sdb if no other drives are connected.
/dev/sda1: UUID="2905-DB96" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="36e3693c-b81f-4797-88fb-de3710bff86e"
/dev/sda2: LABEL="ROOT" UUID="dce73116-10fa-4169-b2d9-fb6ac8ffb83b" TYPE="ext4" PARTUUID="738fed12-239c-486d-b6e1-d90143f43ea7"
/dev/sdb1: LABEL="KINGSTON" UUID="A516-23A5" TYPE="vfat" PARTUUID="6cd1a8de-01"

Notice that, in my case, the pendrive is /dev/sdb.

2. Create a new partition table and two partitions

$ sudo fdisk /dev/sdb

Welcome to fdisk (util-linux 2.31.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): d
Selected partition 1
Partition 1 has been deleted.

Command (m for help): d
No partition is defined yet!

Command (m for help): o

Created a new DOS disklabel with disk identifier 0x8e8bace5.

Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): 
Partition number (1-4, default 1): 
First sector (2048-60978815, default 2048): 
Last sector, +sectors or +size{K,M,G,T,P} (2048-60978815, default 60978815): +1G

Created a new partition 1 of type 'Linux' and of size 1 GiB.
Partition #1 contains a vfat signature.

Do you want to remove the signature? [Y]es/[N]o: Y

The signature will be removed by a write command.

Command (m for help): n
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p): 
Partition number (2-4, default 2): 
First sector (2099200-60978815, default 2099200): 
Last sector, +sectors or +size{K,M,G,T,P} (2099200-60978815, default 60978815): 

Created a new partition 2 of type 'Linux' and of size 28.1 GiB.

Command (m for help): t
Partition number (1,2, default 2): 1
Hex code (type L to list all codes): b

Changed type of partition 'Linux' to 'W95 FAT32'.

Command (m for help): t
Partition number (1,2, default 2): 
Hex code (type L to list all codes): 83

Changed type of partition 'Linux' to 'Linux'.

Command (m for help): a
Partition number (1,2, default 2): 1

The bootable flag on partition 1 is enabled now.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Synching disks.

3. Double-check that the partitions have been created correctly

$ sudo fdisk /dev/sdb # Just to check partitions have been created as required.

Welcome to fdisk (util-linux 2.31.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p
Disk /dev/sdb: 29.1 GiB, 31221153792 bytes, 60978816 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x8e8bace5

Device     Boot   Start      End  Sectors  Size Id Type
/dev/sdb1  *       2048  2099199  2097152    1G  b W95 FAT32
/dev/sdb2       2099200 60978815 58879616 28.1G 83 Linux

Command (m for help): q

4. Format the partitions

$ sudo mkfs.fat -F 32 /dev/sdb1
mkfs.fat 4.1 (2017-01-24)
$ sudo mkfs.ext4 -O ^has_journal /dev/sdb2 # I opted to disable journaling.
mke2fs 1.44.1 (24-Mar-2018)
Creating filesystem with 7359952 4k blocks and 1843200 inodes
Filesystem UUID: 4b837147-bca3-4e31-a9f1-77da19682f77
Superblock backups stored on blocks: 
	32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
	4096000

Allocating group tables: done                            
Writing inode tables: done                            
Writing superblocks and filesystem accounting information: done   

5. Install Porteus

$ sudo mkdir /mnt/iso
$ sudo mkdir /mnt/sdb1
$ sudo mount /home/fitzcarraldo/Downloads/Porteus-XFCE-v5.0rc1-x86_64.iso /mnt/iso
mount: /mnt/iso: WARNING: device write-protected, mounted read-only.
$ sudo mount /dev/sdb1 /mnt/sdb1
$ sudo cp -a /mnt/iso/* /mnt/sdb1/
$ cd /mnt/sdb1/boot
$ sudo ./Porteus-installer-for-Linux.com
Verifying archive integrity... All good.
Uncompressing Porteus Installer......

                             _.====.._
                           ,:._       ~-_
                               '\        ~-_
                                 \        \.
                               ,/           ~-_
                      -..__..-''   PORTEUS   ~~--..__

==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Installing Porteus to /dev/sdb1
WARNING: Make sure this is the right partition before proceeding.

Type 'ok' to continue or press Ctrl+c to exit.
ok
Flushing filesystem buffers...

Using extlinux bootloader.

Installation finished successfully.
You may reboot your PC now and start using Porteus.
Please check the /boot/docs folder for additional information about
the installation process, Porteus requirements and booting parameters.
In case of making tweaks to the bootloader config,
please edit: /mnt/sdb1/boot/syslinux/porteus.cfg file.

Press Enter to exit.

6. Configure Porteus to be persistent across reboots/shutdowns

$ sudo nano /mnt/sdb1/porteus/porteus-v5.0-x86_64.cfg

Add the following lines:

from=/mnt/sdb1/porteus
changes=/mnt/sdb2/changes
timezone=Europe/London
kmap=gb,us,br

Change the timezone according to your location. You can specify up to three keyboard layouts of your choice. I chose British, US and Brazilian keyboard layouts.

Check you have made the edits correctly:

$ grep -v ^# /mnt/sdb1/porteus/porteus-v5.0-x86_64.cfg | grep -v ^$
from=/mnt/sdb1/porteus
changes=/mnt/sdb2/changes
timezone=Europe/London
kmap=gb,us,br

$ sudo nano /mnt/sdb1/boot/syslinux/porteus.cfg

Change ‘APPEND changes=/porteus‘ to ‘APPEND changes=EXIT:/mnt/sdb2‘:

LABEL GRAPHICAL
MENU LABEL Graphics mode
KERNEL /boot/syslinux/vmlinuz
INITRD /boot/syslinux/initrd.xz
APPEND changes=EXIT:/mnt/sdb2
TEXT HELP
    Run Porteus the best way we can.
    Try to autoconfigure graphics
    card and use the maximum
    allowed resolution
ENDTEXT

Note: The ‘EXIT:‘ makes Porteus save changes when you shutdown or reboot Porteus. If I understand the Porteus tutorials and forum posts correctly, without the ‘EXIT:‘ Porteus would save changes in real time. However, this did not happen in my case, so I had no choice but to add the ‘EXIT:‘ in order to save changes.

7. Unmount the ISO and pendrive

$ cd
$ sudo umount /mnt/iso
$ sudo umount /mnt/sdb1

The configuration of ‘changes=‘ in /mnt/sdb1/boot/syslinux/porteus.cfg means that, when you reboot or shutdown from the Live session, Porteus will save any and all changes during a session. And that means every change: new files; edited files; browser bookmarks, browser history; desktop environment configuration; and so on. However, you can define precisely what is persistent by editing the file /etc/changes-exit.conf:

guest@porteus:~$ cat /etc/changes-exit.conf 
# Folders listed in this config file will be saved during reboot and shutdown when 'changes=EXIT:' cheatcode is used.
# Folders starting with '!' are omitted. This is useful if you want to save whole folder except for particular subfolder(s).
# An example is inclued in default config below: Porteus will save whole /var folder except for /var/run and /var/tmp subfolders.
# Other example: "!/home/guest/.mozilla/firefox/c3pp43bg.default/Cache" will skip saving of Firefox caches from guest account.
# Thanks to Rava for suggesting implementation of '!' exceptions.

/bin
/etc
/home
/lib
/lib64
/opt
/root
/sbin
/usr
/var
!/var/run
!/var/tmp

Note: In the case of a pendrive using a ‘save file’ for persistence, relative paths are specified for ‘changes=‘, therefore the pendrive will be able to boot even if several drives are connected to the machine (i.e. it will not matter if the pendrive is device sdb, sdc, sdd or whatever). However, in the case of a pendrive using a second partition for persistence, absolute paths are specified for ‘changes=‘ and ‘from=‘, therefore the device letter may be different if more than just drive sda and the pendrive are connected to the machine. Therefore you may need to edit the two .cfg files to change the device from sdb to sdc or whatever in the path specified for ‘changes=‘ and ‘from=‘. Whenever you boot the pendrive a message is displayed indicating whether or not the changes partition has been found. If it has not, simply edit the two .cfg files from the Live environment and change the paths accordingly (use the command ‘sudo blkid‘ to find out which device is the pendrive now), then reboot.

8. Reboot

You may have to press F12 at boot (or whatever key your machine requires you to press in order to display a Boot Menu) and select the USB pendrive to boot from. The desktop machine I am using has UEFI firmware (notice the partitions on /dev/sda in Step 1 above, and, furthermore, /sys/firmware/efi/ exists when Lubuntu is running) and the USB pendrive boots fine. My laptops use PC BIOS and the USB pendrive boots fine on those too.

You will find that Porteus automatically creates the directory /changes on the partition of the USB pendrive with the Linux filesystem.

Installing Skype for Linux and fixing distorted sound in Skype

You can install Skype in Porteus. Download the Slackware package skypeforlinux-8.18.0.6-x86_64-1_slonly.txz, right-click on the package and select ‘Install package’. Don’t forget to also convert it to a Porteus module (right-click on the package and select ‘txz2xzm’) and copy skypeforlinux-8.18.0.6-x86_64-1_slonly.xzm to /mnt/sdb1/porteus/modules/ so that it persists.

You may find that sound in Skype is distorted/scratchy. The problem is due to PulseAudio. You can fix this as follows:

$ env PULSE_LATENCY_MSEC=90 /usr/bin/skypeforlinux

Experiement with the value if ‘90‘ does not work. If that improves the sound in Skype, edit the file /home/guest/.config/autostart/skypeforlinux.desktop (if it exists) and change the Exec line as follows:

Exec=env PULSE_LATENCY_MSEC=90 /usr/bin/skypeforlinux

and edit (as root user) the file /usr/share/applications/skypeforlinux.desktop and change the Exec line as follows:

Exec=env PULSE_LATENCY_MSEC=90 /usr/bin/skypeforlinux %U

Also edit the file /etc/pulse/daemon.conf as root user and insert the line ‘realtime-scheduling = no‘:

[...]
; realtime-scheduling = yes
; realtime-priority = 5
realtime-scheduling = no
[...]

Also, run alsamixer from the command line:

$ alsamixer -c 0 # Press F6 to select your soundcard if necessary

Adjust the volume levels in alsamixer and unmute any muted channels so that you can both hear the caller and your own recorded voice when you make a test call in Skype, then save the alsamixer settings to a file:

$ /usr/sbin/alsactl --file /home/guest/.config/asound.state store

Edit the file /etc/rc.d/rc.local as root user and add the following line to load the ALSA settings when Porteus next boots:

alsactl --file /home/guest/.config/asound.state restore

Summary

Xfce spin of Live Linux distribution Porteus Linux.

Xfce spin of Live Linux distribution Porteus Linux.

I like Porteus. The upsides are:

  • Easy and quick to install on USB pendrives.
  • Can be installed without using an ISO installer (UNetbootin, Rufus, YUMI, UUI or whatever).
  • Boots fast.
  • Fast performance.
  • Polished GUI (I have tried Openbox, Xfce and KDE so far, and settled on Xfce).
  • A good range of applications are already installed out-of-the-box.
  • The Porteus module concept is easy and fast to use.
  • Persistence works well.
  • There are a number of Porteus modules available to download (‘bundles’).
  • Converting Slackware packages to Porteus modules is easy. I right-click on the downloaded Slackware package and select ‘txz2xzm’ from the drop-down menu.
  • Switching to a different Desktop Environment is easy. Modules for all the DEs are available to download from Porteus repository mirrors such as http://ftp.nluug.nl/os/Linux/distr/porteus/x86_64/Porteus-v5.0/.

The downsides I have come across so far are:

  • The Unified Slackware Package Manager (USM) does not work. When I click on ‘Download’ to download a package, a window pops up with the message ‘Fatal error LIBS.TXT’, even though I have updated USM and all the package databases. Therefore I use a Web browser to download the relevant Slackware package (a file ending in .txz), right-click on the package and select ‘Install package’ from the drop-down menu.
  • Slackware does not have the latest versions of some packages (signal-desktop is just one example).
  • The first time I installed Porteus, when I clicked on ‘Browse Networks’ in the Thunar file manager I could browse SMB shares on a server connected to my home network (without me having edited the installed /etc/samba/smb.conf). However, in subsequent re-installations of Porteus, when I clicked on ‘Browse Networks’ a window popped up displaying the following message:

    Failed to open "/ on ".
    Message recipient disconnected from message bus without replying.

    I edited smb.conf to use the parameters for my network (see my blog post ‘A correct method of configuring Samba for browsing SMB shares in a home network‘), but that made no difference. I don’t know yet how to fix this, although on my 32GB pendrive ‘Browse Networks’ is now working again for some reason. I had installed LXDE’s PCManFM in Xfce to see if ‘Browse Networks’ would work in that, but it didn’t so I uninstalled it. Then I noticed a new console message ‘cp: can't stat‘ during boot because Porteus could not find a PCManFM file, so I deleted the /changes directory on the Linux partition to get rid of that message (Porteus creates a new /changes directory automatically, although of course you need to redo whatever was lost). It could be a coincidence, but the next time I booted Porteus, ‘Browse Network’ in Thunar worked (with the as-installed smb.conf) and continues to work.

There is quite a bit more to Porteus than I have covered in this post; for example I have not covered ‘Magic Folders’. You can find out more by reading the Porteus online documentation and forums, as well as the documention installed on USB pendrives in the directories /mnt/sdb1/ and /mnt/sdb1/boot/docs/. Although the development team is small, I am impressed with what they have implemented. Porteus will be my portable Linux distribution of choice from now on, and I look forward to learning more about it and using it in the field.

Trouble again with PulseAudio and Thunderbird sound notifications

In an earlier post I described how I fixed a scratchy-sounding sound file which the Thunderbird e-mail client plays when a new message arrives. Well, the problem started again recently, but this time the contents of /etc/pulse/daemon.conf looked OK to me. Furthermore, the sound file sounds fine when played using following commands:

aplay ~/Music/wav/E-mail_notifications/halmsg.wav
paplay ~/Music/wav/E-mail_notifications/halmsg.wav
mplayer ~/Music/wav/E-mail_notifications/halmsg.wav
cvlc ~/Music/wav/E-mail_notifications/halmsg.wav

Now, Thunderbird uses libcanberra to play sounds, so I began to wonder if the problem lay with libcanberra. As it happens, libcanberra is maintained by the same person who invented PulseAudio. However, I notice from the libcanberra Git repository that its source code has not been changed since 2012.

My Gentoo Linux installation had libcanberra installed with support for both ALSA and PulseAudio:

root # eix -I libcanberra
[I] media-libs/libcanberra
     Available versions:  0.30-r5 {alsa gnome gstreamer +gtk +gtk3 oss pulseaudio +sound tdb udev ABI_MIPS="n32 n64 o32" ABI_PPC="32 64" ABI_S390="32 64" ABI_X86="32 64 x32"}
     Installed versions:  0.30-r5(08:27:41 18/05/18)(alsa gtk gtk3 pulseaudio sound udev -gnome -gstreamer -oss -tdb ABI_MIPS="-n32 -n64 -o32" ABI_PPC="-32 -64" ABI_S390="-32 -64" ABI_X86="32 64 -x32")
     Homepage:            http://git.0pointer.net/libcanberra.git/
     Description:         Portable sound event library

So, even though my installation uses PulseAudio, I decided to try and re-install libcanberra without PulseAudio support, only ALSA support:

root # USE="-pulseaudio" emerge -1v libcanberra
root # eix -I libcanberra
[I] media-libs/libcanberra
     Available versions:  0.30-r5 {alsa gnome gstreamer +gtk +gtk3 oss pulseaudio +sound tdb udev ABI_MIPS="n32 n64 o32" ABI_PPC="32 64" ABI_S390="32 64" ABI_X86="32 64 x32"}
     Installed versions:  0.30-r5(15:47:14 26/05/18)(alsa gtk gtk3 sound udev -gnome -gstreamer -oss -pulseaudio -tdb ABI_MIPS="-n32 -n64 -o32" ABI_PPC="-32 -64" ABI_S390="-32 -64" ABI_X86="32 64 -x32")
     Homepage:            http://git.0pointer.net/libcanberra.git/
     Description:         Portable sound event library

Lo and behold, Thunderbird (libcanberra) plays the sound file correctly now. So I have added the following line to my file /etc/portage/package.use/thunderbird in order to make the change permanent:

media-libs/libcanberra -pulseaudio

PulseAudio 🙄

Another look at beeps in Linux

Following my previous post I experimented further with the Linux Kernel configuration options for event beeps (sometimes called ‘system beeps’), and I now have a better understanding of how the Kernel options interact (on one of my laptops, at least).

The sound card in my Clevo W230SS laptop has a VIA VT1802S audio codec chip. I looked at the audio circuit schematic in the service manual; one of the digital input pins on the VT1802S is labelled ‘PCBEEP’, and one of its analogue output pins is labelled ‘PCBEEP’ and is connected to the laptop’s speaker circuit. So there is no PC Speaker in this laptop and it emulates the PC Speaker via the laptop’s sound card, as mentioned in my previous post.

Before I describe my latest results, there are a couple of influencing factors I forgot to mention in my previous post:

  • In some computers the BIOS Menu has one or more options for enabling/disabling beeps. The BIOS menu of my Clevo laptop does not have an option to enable/disable all beeps from the (emulated) PC Speaker, but it does have a couple of options to enable/disable ‘Power On Boot Beep’ and ‘Battery Low Alarm Beep’ (I have disabled them both). Anyway, if you are still not getting beeps after trying everything else, be sure to check the BIOS menu just in case it has an option to enable/disable the PC Speaker.

  • Make sure that bell-style is not set to ‘none‘ (you could set it to ‘audible‘ if you wanted to be sure):

    root # grep bell /etc/inputrc
    # do not bell on tab-completion
    #set bell-style none

The Kernel configuration was initially as shown below. With this configuration no beeps were emitted in a VT (Virtual Terminal) or in an X Windows terminal. As explained in my previous post, I therefore configured the XKB Event Daemon to play an audio file (bell.oga) whenever X Windows detects a BEL character (ASCII 007) or Backspace key (ASCII 008).

root # grep PCSP /usr/src/linux/.config
CONFIG_HAVE_PCSPKR_PLATFORM=y
CONFIG_PCSPKR_PLATFORM=y
# CONFIG_INPUT_PCSPKR is not set
# CONFIG_SND_PCSP is not set
root # grep BEEP /usr/src/linux/.config
CONFIG_SND_HDA_INPUT_BEEP=y
CONFIG_SND_HDA_INPUT_BEEP_MODE=1

Then I rebuilt the Kernel with CONFIG_INPUT_PCSPKR=M and CONFIG_SND_PCSP=M:

root # cd /usr/src/linux
root # mount /dev/sda1 /boot
root # make menuconfig
root # make && make modules_install
root # make install
root # grep PCSP /usr/src/linux/.config
CONFIG_HAVE_PCSPKR_PLATFORM=y
CONFIG_PCSPKR_PLATFORM=y
CONFIG_INPUT_PCSPKR=m
CONFIG_SND_PCSP=m
root # grep BEEP /usr/src/linux/.config
CONFIG_SND_HDA_INPUT_BEEP=y
CONFIG_SND_HDA_INPUT_BEEP_MODE=1

Then I created the file /etc/modprobe.d/blacklist.conf in order to blacklist the modules pcspkr and snd-pcsp so that only I could load them after boot:

root # cat /etc/modprobe.d/blacklist.conf
blacklist pcspkr
blacklist snd-pcsp

Then I added the line ‘options snd-pcsp index=2‘ to the file /etc/modprobe.d/alsa.conf so that the virtual sound card pcsp would not become the default sound card:

root # tail /etc/modprobe.d/alsa.conf
alias /dev/midi snd-seq-oss

# Set this to the correct number of cards.
options snd cards_limit=1

# See https://bugs.launchpad.net/ubuntu/+source/alsa-driver/+bug/1313904
options snd-hda-intel patch=,clevo-hda-patch

# See Kernel Help text for CONFIG_SND_PCSP
options snd-pcsp index=2

Then I rebooted and checked that neither module was loaded:

root # lsmod | grep pcsp
root # echo -e '\a'

root #

As neither module was loaded, the situation was the same as before: a) no beep in a VT; b) no beep in Konsole/Yakuake (I will ignore KDE terminal programs anyway because of KDE bug report no. 177861);* c) the same bell.oga beep in xterm due to my use of xkbevd; d) no changes in ALSA Mixer.

* Regarding Konsole and Yakuake, see my update of October 9, 2016 at the bottom of this post.

Then I loaded the module pcspkr:

root # modprobe pcspkr
root # lsmod | grep pcsp
pcspkr                  1875  0
root # echo -e '\a'

root #

There were no changes in ALSA Mixer. But now the BEL character and Backspace in a VT did result in a beep (I’ll call this a ‘pcbeep’ to distinguish it from the different-sounding beep produced using bell.oga). There was the usual bell.oga beep in xterm due to my use of xkbevd. If I stopped xkbevd, there was no pcbeep in X Windows from the shell commands shown in my previous post, although the following commands from any terminal in X Windows (even Konsole/Yakuake) did emit a pcbeep:

user $ sudo sh -c "echo -e '\a' > /dev/console"

user $ sudo sh -c "tput bel > /dev/console"

root # echo -e '\a' > /dev/console

root # tput bel > /dev/console

Then I unloaded the module pcspkr and loaded the module snd-pcsp:

root # modprobe -r pcspkr
root # modprobe snd-pcsp
root # lsmod | grep pcsp
snd_pcsp                7918  1
root # echo -e '\a'

root #

ALSA Mixer showed a new sound card named ‘pcsp‘ (Sound Card 2) with three channels: ‘Master’, ‘Beep’ and ‘BaseFRQ’. I could mute/unmute ‘Beep’ by pressing ‘M’ on the keyboard as usual, and I could toggle ‘BaseFRQ’ between two values:18643 and 37286. The BEL character and Backspace in a VT resulted in a pcbeep. There was the usual bell.oga beep in xterm due to my use of xkbevd. If I stopped xkbevd, there was no pcbeep in X Windows from the shell commands shown in my previous post, although the following commands from any terminal in X Windows (even Konsole/Yakuake) did emit a pcbeep:

user $ sudo sh -c "echo -e '\a' > /dev/console"

user $ sudo sh -c "tput bel > /dev/console"

root # echo -e '\a' > /dev/console

root # tput bel > /dev/console

Muting ‘Beep’ in ALSA Mixer did not mute the bell.oga beeps in X Windows, but it did mute the pcbeeps in the VTs.

Unlike the situation with the pcspkr module, occasionally there were brief low-volume crackles and pops from the laptop’s speakers.

So both drivers worked, but pcspkr performed better, although it could not be muted via ALSA Mixer. My recommendation to use pcspkr rather than snd-pcsp still stands.

Unlike pcspkr, I had to force the unloading of snd-pcsp:

root # modprobe -r snd-pcsp
modprobe: FATAL: Module snd_pcsp is in use.
root # rmmod -f snd_pcsp
root #

I then removed the Kernel’s ‘digital beep’ interface for the Intel HDA driver by rebuilding the Kernel with CONFIG_SND_HDA_INPUT_BEEP=N:

root # cd /usr/src/linux
root # mount /dev/sda1 /boot
root # make menuconfig
root # make && make modules_install
root # make install
root # grep PCSP /usr/src/linux/.config
CONFIG_HAVE_PCSPKR_PLATFORM=y
CONFIG_PCSPKR_PLATFORM=y
CONFIG_INPUT_PCSPKR=m
CONFIG_SND_PCSP=m
root # grep BEEP /usr/src/linux/.config
# CONFIG_SND_HDA_INPUT_BEEP is not set
root #

After I rebooted, the behaviour was exactly the same as for CONFIG_SND_HDA_INPUT_BEEP=Y and CONFIG_SND_HDA_INPUT_BEEP_MODE=1.

So, there you have it. I believe my previous post was essentially correct regarding the functional design of the Kernel options. If you have a computer without a PC Speaker but it emulates one via the computer’s sound card, you have to set either CONFIG_INPUT_PCSPKR or CONFIG_SND_PCSP to get a beep in a VT, not set just CONFIG_SND_HDA_INPUT_BEEP and CONFIG_SND_HDA_INPUT_BEEP_MODE. However, even when my laptop emits beeps in a VT from the (emulated) PC Speaker, no beeps from the (emulated) PC Speaker are emitted in X Windows unless the user is the root user and the output is redirected to /dev/console. So, if you want to emit beeps in X Windows it is still better in my opinion to use xkbevd to play an audio file of a beep, as described in my previous post.

Update (October 9, 2016): Regarding KDE’s terminal applications emitting beeps, I am currently using KDE Plasma 5.7.5 and have been able to configure Konsole and Yakuake to play an audio file of a beep (as opposed to emitting a pcbeep) as follows:

  • In Konsole, click on ‘Settings’ > ‘Configure Notifications…’, select ‘Bell in Visible Session’ and ensure ‘Play a sound’ is ticked and a file is specified there (I specify /usr/share/sounds/freedesktop/stereo/bell.oga). If you wish, do the same for ‘Bell in Non-Visible Session’.
  • For Yakuake, press F12 to display the Yakuake window, click on the ‘Open Menu’ icon, select ‘Configure Notifications…’, select ‘Bell in Visible Session’ and ensure ‘Play a sound’ is ticked and a file is specified there (I specify /usr/share/sounds/freedesktop/stereo/bell.oga). If you wish, do the same for ‘Bell in Non-Visible Session’.

To beep, or not to beep, that is the question

Introduction

If your computer running Linux has the necessary hardware and is configured appropriately, applications and shell scripts can trigger a beep to signal an event such as an invalid keyboard entry, shutdown initiation, and so on. To check the current situation with your computer, enter the command shown below. Try it first in a Linux VT (virtual terminal) and then in a terminal window in X Windows. Do you hear a beep in each case?

user $ echo -e '\a'

The above command outputs the BEL character (ASCII code 007).

An alternative to the above command is:

user $ echo -e '\007'

Another command that should produce a beep is:

user $ tput bel

The tput utility is part of the ncurses package.

If you install the package app-misc/beep you can also use the ‘beep’ command (enter the command ‘man beep‘ to see its options):

user $ beep

Although you can enter the above-mentioned commands on the command line, they are intended to be used in shell scripts to notify the user about something.

There are thousands of posts on the Web regarding beeps in Linux, the majority of them concerned with disabling beeps because many people find them annoying. Historically, such beeps were emitted by the so-called ‘PC speaker‘. Note that the PC Speaker is not the same as the speakers connected to the sound card in your computer; the term refers to a small internal loudspeaker (moving-coil or piezoelectric) wired directly to the motherboard and intended solely to emit beeps to notify the user about something. Many modern computers, especially laptops, do not have a PC Speaker and either emulate one via the sound card or do nothing at all.

The reason people sometimes use the terms ‘bell’ and ‘ring’ instead of ‘beep’ is because old teletypwriters and teleprinters actually had an electromechanical bell which would ring when a certain dedicated character was received. I use the terms ‘beep’ and ‘bell’ interchangeably, although I prefer to use the term ‘beep’ when talking about audible notifications by computers.

I was motivated to write this post after helping a Gentoo Linux user to get his laptop to produce beeps (see the Gentoo Linux Forums thread ‘i want to beep [solved]‘). Producing a beep in Linux turns out to be more complicated than you would expect, and I’m not sure I fully understand the functional design of the applicable configuration options in the Kernel, nor their relevance (if any) to the X Windows server’s bell. Now, on the face of it the functionality of the applicable Kernel configuration options appears straightforward, but that is not the case in practice. Anyway, let’s look at how I believe a beep can be achieved (and disabled) in Linux…

PC Speaker drivers

Four Kernel options relate directly to a PC Speaker:

CONFIG_HAVE_PCSPKR_PLATFORM

If this is not set in the Kernel then CONFIG_PCSPKR_PLATFORM cannot be enabled.

CONFIG_PCSPKR_PLATFORM

Enable PC-Speaker support

This option allows to disable the internal PC-Speaker
support, saving some memory.

CONFIG_INPUT_PCSPKR

PC Speaker support

Say Y here if you want the standard PC Speaker to be used for
bells and whistles.

If unsure, say Y.

To compile this driver as a module, choose M here: the
module will be called pcspkr.

CONFIG_SND_PCSP

PC-Speaker support (READ HELP!)

If you don’t have a sound card in your computer, you can include a
driver for the PC speaker which allows it to act like a primitive
sound card.
This driver also replaces the pcspkr driver for beeps.

You can compile this as a module which will be called snd-pcsp.

WARNING: if you already have a soundcard, enabling this
driver may lead to a problem. Namely, it may get loaded
before the other sound driver of yours, making the
pc-speaker a default sound device. Which is likely not
what you want. To make this driver play nicely with other
sound driver, you can add this into your /etc/modprobe.conf:
options snd-pcsp index=2

You don’t need this driver if you only want your pc-speaker to beep.
You don’t need this driver if you have a tablet piezo beeper
in your PC instead of the real speaker.

Say N if you have a sound card.
Say M if you don’t.
Say Y only if you really know what you do.

If your computer does have a PC Speaker, you would use either CONFIG_INPUT_PCSPKR or CONFIG_SND_PCSP, but not both. When configuring the Kernel you can specify ‘M’ to build the driver as an external module, in which case you can decide in userspace whether or not to load it. Or you can specify ‘Y’ to build the driver into the Kernel (do not specify both as ‘Y’ simultaneously, though).

If your computer does have a PC Speaker, an advantage of using CONFIG_SND_PCSP instead of CONFIG_INPUT_PCSPKR is that the former adds a virtual sound card named ‘pcsp’ with a channel (without volume control) named ‘Beep’, and you should be able to mute it via ALSA Mixer.

If you have a computer that has a sound card but does not have a PC Speaker (a laptop’s internal speakers are connected to a sound card, not a PC Speaker), the above two drivers do not really apply. I have always disabled them both in the Kernel, as my laptop does not have a PC Speaker.  Update (September 29, 2016): This is not always the case: if a computer uses a sound card to emulate a PC Speaker (typically laptops do this), then you do need to use one of these two drivers if you want to be able to hear event beeps in a VT — see my latest post Another look at beeps in Linux.

However, apparently for some laptops ALSA Mixer shows a channel named ‘Beep’ (with volume control) for the Intel HDA (High Definition Audio) sound card if CONFIG_INPUT_PCSPKR is set to ‘Y’ or ‘M’. I believe such laptops were designed to use their sound card to emulate a PC Speaker. I do not know whether or not the ‘digital beep’ Kernel options (see further on) are set in such cases, but Kernel bug report no. 13651 would appear to indicate that the design intention is for them to be set.

So, already things are confusing.

Of course, if your computer does have a PC Speaker and you don’t want it to emit beeps, set both CONFIG_INPUT_PCSPKR and CONFIG_INPUT_PCSP to ‘N’ in the Kernel. If either already exists as an external module and you do not wish to rebuild the Kernel, make sure the modules pcspkr and snd-pcsp are not loaded (blacklist them, for example).

Digital Beep

Now, there are two other Kernel options relating to event beeps. These are not for driving a PC Speaker, they are to enable the ALSA Intel HDA driver to emit event beeps in lieu of a PC Speaker: the so-called ‘digital beep’. In other words, these two options are intended to provide an alternative to using a PC Speaker. The two options are:

CONFIG_SND_HDA_INPUT_BEEP

Support digital beep via input layer

Say Y here to build a digital beep interface for HD-audio
driver. This interface is used to generate digital beeps.

CONFIG_SND_HDA_INPUT_BEEP_MODE

Digital beep registration mode (0=off, 1=on)

Set 0 to disable the digital beep interface for HD-audio by default.
Set 1 to always enable the digital beep interface for HD-audio by
default.

Note that the mode ‘2’ is no longer an option in newer Kernels.

So, if your installation uses the Intel HDA driver and you want your computer’s sound card to be able to emit beeps instead of a PC Speaker (which your computer may or may not have), set these two accordingly in the Kernel configuration:

user $ grep CONFIG_SND_HDA_INPUT_BEEP /usr/src/linux/.config
CONFIG_SND_HDA_INPUT_BEEP=y
CONFIG_SND_HDA_INPUT_BEEP_MODE=1

The functional design of these Kernel options is not clear, but Kernel bug report no. 13651 appears to indicate that the design intention is for CONFIG_SND_HDA_INPUT_BEEP and CONFIG_SND_HDA_INPUT_BEEP_MODE to be used in addition to either CONFIG_INPUT_PCSPKR or CONFIG_SND_PCSP, not instead of them. In other words, if your computer has a PC Speaker but you want beeps to be routed via its Intel HDA sound card instead then I believe you are expected to use either of the following two sets of options:

Option 1
CONFIG_HAVE_PCSPKR_PLATFORM=Y
CONFIG_PCSPKR_PLATFORM=Y
CONFIG_INPUT_PCSPKR=Y (or =M)
CONFIG_SND_HDA_INPUT_BEEP=Y
CONFIG_SND_HDA_INPUT_BEEP_MODE=1

Option 2
CONFIG_HAVE_PCSPKR_PLATFORM=Y
CONFIG_PCSPKR_PLATFORM=Y
CONFIG_SND_PCSP=Y (or =M)
CONFIG_SND_HDA_INPUT_BEEP=Y
CONFIG_SND_HDA_INPUT_BEEP_MODE=1

On the other hand, if your computer has a PC Speaker and your installation uses the Intel HDA driver for a sound card but you do want your computer to emit beeps from the PC Speaker, I think you would set the two options as follows in the Kernel configuration:

CONFIG_SND_HDA_INPUT_BEEP=N
CONFIG_SND_HDA_INPUT_BEEP_MODE=0

If you read the comment by ALSA developer Takashi Iwai quoted in Kernel bug report no. 13651 you’ll see that the functionality is not at all straightforward. For example, on some computers, especially laptops (which normally do not have a PC Speaker), the beep may be emitted via the sound card irrespective of whether or not you set CONFIG_SND_HDA_INPUT_BEEP.

X Windows

A beep can be emitted in X Windows, and I have seen this beep referred to as the ‘X Windows server bell’ or the ‘X Windows keyboard bell’.

Given that X Windows can emit a beep via the sound card when neither the pcspkr module nor the snd-pcsp module is loaded and CONFIG_SND_HDA_INPUT_BEEP=N and CONFIG_SND_HDA_INPUT_BEEP_MODE=0, I assume X Windows emits beeps directly to the default sound card irrespective of the settings of those Kernel options. I could be wrong, but I have not found any explanation on the Web about the underlying mechanism; the X.Org Web site FAQ ‘How can I configure the Xserver bell (xkbbell) to use the sound subsystem of my computer? (ALSA, OSS, etc.)‘ simply states:

Answer (hopefully) goes here.. 🙂

*shrug*.

Below is a summary of the commands to disable, enable and configure the beep in X Windows.

To disable beeps in X Windows:

user $ xset b off

To enable beeps in X Windows:

user $ xset b on

To change the volume, pitch and duration of the beeps:

user $ xset b

For example, to set the beep volume to 25% without changing the pitch and duration:

user $ xset b 25

To return to the default settings:

user $ xset b

To view the current settings:

user $ xset q | grep bell

which displays the following (default) values in my case:

bell percent:  50        bell pitch:    400        bell duration:    100

To set the beep automatically each time X Windows starts, add the following line before the last one in the ~/.xinitrc file if you don’t use a Display Manager, otherwise use the Desktop Environment’s system settings GUI to run it at login:

xset b 20 400 20 &

PulseAudio

To confuse matters further, note that PulseAudio intercepts X11 beeps (see: PulseAudio Documentation – User Documentation – Modules – X Window system – module-x11-bell). Therefore, if your installation uses PulseAudio and you want the ability to emit event beeps in X Windows, you also need to configure PulseAudio so it does not ignore the beeps. This can either be done from the command line:

user $ pactl upload-sample /usr/share/sounds/freedesktop/stereo/bell.oga x11-bell
user $ pactl load-module module-x11-bell sample=x11-bell display=$DISPLAY

or you can edit /etc/pulse/default.pa and make sure the following lines are included in that file (they may already exist but are commented out):

load-sample-lazy x11-bell /usr/share/sounds/freedesktop/stereo/bell.oga
load-module module-x11-bell sample=x11-bell

On the other hand, if PulseAudio is installed and you want it to ignore event beeps in X Windows, delete or comment out the above-mentioned two lines in /etc/pulse/default.pa. You can achieve the same effect from the command line:

user $ pactl unload-module module-x11-bell

Configuring userspace to emit a ‘digital beep’

Installation of PulseAudio will have created the directory /usr/share/sounds/freedesktop/ and sub-directories containing various Ogg Vorbis audio files, including the ‘digital beep’ file bell.oga. If your installation does not have PulseAudio installed, you can obtain the same file /usr/share/sounds/freedesktop/stereo/bell.oga by installing the package x11-themes/sound-theme-freedesktop instead. You can configure your installation to use this file to emit a ‘digital beep’ in X Windows (but not in a VT) by using the XKB (X Windows keyboard extension) event daemon as explained in a post on the superuser Web site. That post relates to Ubuntu, but the basic principle applies whatever the Linux distribution.

Now, in my case I am using KDE Plasma 5 in Gentoo Linux, and I cannot hear any beep/bell in Konsole and Yakuake. I came across KDE bug report no. 177861 that has been outstanding since 2008, which indicated that KDE’s terminal applications will not emit beeps even if you do have a PC Speaker and your Kernel has been correctly configured to use it, or even if you have configured your installation to use a ‘digital beep’. You may have better luck with a different Desktop Environment but in KDE you will have to use a non-KDE X Windows terminal application if you want to hear beeps produced by shell scripts.

Update (October 9, 2016): Regarding KDE’s terminal applications emitting beeps, I am currently using KDE Plasma 5.7.5 and have been able to configure Konsole and Yakuake to emit a ‘digital beep’ as follows:

  • In Konsole, click on ‘Settings’ > ‘Configure Notifications…’, select ‘Bell in Visible Session’ and ensure ‘Play a sound’ is ticked and a file is specified there (I specify /usr/share/sounds/freedesktop/stereo/bell.oga). If you wish, do the same for ‘Bell in Non-Visible Session’.
  • For Yakuake, press F12 to display the Yakuake window, click on the ‘Open Menu’ icon, select ‘Configure Notifications…’, select ‘Bell in Visible Session’ and ensure ‘Play a sound’ is ticked and a file is specified there (I specify /usr/share/sounds/freedesktop/stereo/bell.oga). If you wish, do the same for ‘Bell in Non-Visible Session’.

Below I explain how I implemented a ‘digital beep’ in KDE Plasma 5.

First I installed the XKB event daemon:

root # emerge xkbevd

The package vorbis-tools was already installed, otherwise I would have installed that too in order to install an audio player for Ogg Vorbis audio files:

root # emerge vorbis-tools

PulseAudio was also already installed, and hence an appropriate audio file for a beep already existed. Had I not previously installed PulseAudio I would have installed the following package to get an appropriate Ogg Vorbis audio file:

root # emerge sound-theme-freedesktop

I created the file /home/fitzcarraldo/.config/autostart/xkbevd.desktop containing the following:

[Desktop Entry]
Comment[en_GB]=Software terminal bell
Comment=Software terminal bell
Exec=xkbevd -bg
GenericName[en_GB]=XKB Event Daemon
GenericName=XKB Event Daemon
Icon=system-run
MimeType=
Name[en_GB]=XKB Event Daemon
Name=XKB Event Daemon
Path=
StartupNotify=true
Terminal=false
TerminalOptions=
Type=Application
X-DBUS-ServiceName=
X-DBUS-StartupType=none
X-KDE-SubstituteUID=false
X-KDE-Username=fitzcarraldo	

and I changed its permissions:

user $ chmod 755 /home/fitzcarraldo/.config/autostart/xkbevd.desktop

I created the file /home/fitzcarraldo/.xkb/xkbevd.cf containing the following:

soundDirectory="/usr/share/sounds/"
soundCmd="ogg123 -q"

Bell() "freedesktop/stereo/bell.oga"

If the file /usr/share/sounds/freedesktop/stereo/bell.oga does not exist in your installation then you can copy any suitable audio file of your choice into the directory /usr/share/sounds/ or use one of the existing audio files in that directory, and specify its filename in xkbevd.cf. For example:

soundDirectory="/usr/share/sounds/"
soundCmd="aplay -q"

Bell() "beep.wav"

Notice that the choice of audio player is up to you. In the first example of xkbevd.cf I specified the ogg123 player, whereas in the second example I specified the aplay player.

The aforementioned bug in KDE Konsole and Yakuake prevented me from testing the use of the XKB event daemon, so I installed a non-KDE X Windows terminal application to see if the ‘digital beep’ would work in that:

root # emerge xterm

The command echo -e '\a' generates a beep in xterm. So the ‘digital beep’ approach does work, albeit use of the XKB event daemon means you are limited to using it in X Windows. To reiterate, as the XKB event daemon is for X Windows, no ‘digital beep’ is generated if you enter a beep command outside of X Windows (e.g. in a VT).

By the way, I’m currently using Gentoo Stable Branch and hence Version 5.6.5 of KDE Plasma, and there is another KDE bug to complicate matters further: ‘System Settings’ > ‘Autostart’ > ‘Add Program…’ does not save all the entries I make via the GUI to the .desktop file, and does not set the file permissions correctly either. I don’t know if that is an upstream bug or a bug in the Gentoo implementation of Plasma 5.6.5. Anyway, that is why I manually created xkbevd.desktop and manually set the permissions, rather than using System Settings.

Instead of launching the XKB event daemon by using a .desktop file in ~/.config/autostart/, if you don’t use a Display Manager you could launch it by adding the command in the file ~/.xinitrc.

Summary

All the following factors govern whether or not your computer will issue a beep for the BEL character:

  • the specific hardware and firmware in your computer;
  • CONFIG_HAVE_PCSPKR_PLATFORM;
  • CONFIG_PCSPKR_PLATFORM;
  • CONFIG_INPUT_PCSPKR;
  • CONFIG_SND_PCSP;
  • CONFIG_SND_HDA_INPUT_BEEP;
  • CONFIG_SND_HDA_INPUT_BEEP_MODE;
  • X Windows settings;
  • PulseAudio configuration (if installed);
  • a bug in KDE’s terminal applications (if installed).

A. If you are hearing event beeps but don’t want them:

  • Preferably, set CONFIG_HAVE_PCSPKR_PLATFORM and CONFIG_PCSPKR_PLATFORM both to ‘N’.
  • Either set both CONFIG_INPUT_PCSPKR and CONFIG_SND_PCSP to ‘N’ in your Kernel, or, if either driver exists as a module (pcspkr and snd-pcsp, respectively), blacklist it.
  • Make sure CONFIG_SND_HDA_INPUT_BEEP is set to ‘N’.
  • Make sure the X Windows bell is turned off.
  • If you also have PulseAudio installed, make sure the PulseAudio module module-x11-bell is not loaded (also check /etc/pulse/default.pa to see if it has been enabled by default).

B. If you are not hearing event beeps but you do want to hear them:

1. If you are sure your computer has a PC Speaker:

  • Make sure CONFIG_HAVE_PCSPKR_PLATFORM and CONFIG_PCSPKR_PLATFORM are set to ‘Y’.
  • Either set CONFIG_INPUT_PCSPKR to ‘M’ and CONFIG_SND_PCSP to ‘N’ in your Kernel, or, if the module snd-pcsp already exists, blacklist it.
  • Make sure the module pcspkr exists and is not blacklisted.
  • Make sure the module pcspkr is loaded after the module snd-hda-intel.
  • Make sure CONFIG_SND_HDA_INPUT_BEEP is set to ‘N’.
  • Make sure the X Windows bell is turned on and the volume is turned up.
  • If you have PulseAudio installed, make sure the PulseAudio module module-x11-bell is loaded (check /etc/pulse/default.pa to ensure it includes the applicable lines, or issue the two commands listed earlier).
  • If you use KDE, use a non-KDE terminal application until KDE bug report no. 177861 is fixed.
  • If, after doing all the above, you still do not hear a beep in X Windows, follow the procedure in the section above titled Configuring userspace to emit a ‘digital beep’.

Above I have recommended using pcspkr. However, an advantage of using snd-pcsp instead is that it adds a virtual sound card with a channel named ‘Beep’ and you should be able to mute that channel via ALSA Mixer as you wish. Therefore, if you do opt to use the module snd-pcsp instead of pcspkr then make sure you specify the module option (or Kernel Quirk if you built the driver into the Kernel) described in the Kernel Help text quoted earlier, so that pcsp does not become the default sound card instead of the Intel HDA sound card.

2. If your computer does not have a PC Speaker:

  • Preferably, set CONFIG_HAVE_PCSPKR_PLATFORM and CONFIG_PCSPKR_PLATFORM both to ‘N’. *
  • If you leave CONFIG_HAVE_PCSPKR_PLATFORM and CONFIG_PCSPKR_PLATFORM both set to ‘Y’, either set CONFIG_INPUT_PCSPKR and CONFIG_SND_PCSP both to ‘N’, or, if either module already exists, blacklist it. *
  • Make sure CONFIG_SND_HDA_INPUT_BEEP is set to ‘Y’ and CONFIG_SND_HDA_INPUT_BEEP_MODE is set to ‘1’ (I’m not sure this step is required for all computers).
  • Make sure the X Windows bell is turned on and its volume is turned up.
  • If you have PulseAudio installed, make sure the PulseAudio module module-x11-bell is loaded.
  • Use the XKB Event Daemon method to play an audio file (‘digital beep’) when the BEL character is detected in X Windows.
  • If you use KDE, use a non-KDE terminal application until KDE bug report no. 177861 is fixed.
    Update (October 9, 2016): Regarding KDE’s terminal applications emitting beeps, I am currently using KDE Plasma 5.7.5 and have been able to configure Konsole and Yakuake to emit a ‘digital beep’ — see my update in the section titled Configuring userspace to emit a ‘digital beep’.

    * If your computer’s hardware and firmware have been designed to emulate a PC Speaker via a sound card, you may find that you can use the pcspkr (or snd-pcsp) driver to generate beeps in a VT. As the saying goes, your mileage may vary.

    And Finally

    If you know precisely how all these Kernel options are supposed to interact, do comment. Or if you know the relationship, if any, between the X Windows beep (a.k.a. ‘bell’) and these Kernel options, please also comment.

    Update (September 29, 2016): See my latest post Another look at beeps in Linux for the results of some experiments with these Kernel options on my laptop, giving more insight into how to configure them and how they work.

No sound from headphones after resume from suspension / No sound from headphones after re-plug

It is not difficult to find posts on the Web regarding certain models of laptop that no longer produce sound from headphones after resuming from suspension, or no longer produce sound from their speakers or from headphones if you unplug and reconnect the headphones. My Clevo W230SS laptop suffered from these problems and more: sometimes the external microphone socket would no longer work either. I had to reboot the laptop in order to get audio working properly again.

The cause of these problems varies according to the specific hardware and software, and here I will describe a couple of fixes I implemented in Gentoo Linux for my Clevo W230SS laptop. Bear in mind that what works for one model of laptop may not necessarily work for a different model even if the symptoms are the same.

PROBLEM 1: No sound from headphones after resume from suspension

After my laptop resumed from suspension, headphones would no longer work until I rebooted the laptop. Sometimes an external microphone would also stop working until I rebooted. In 2014, Ubuntu user Kiril filed a bug report regarding this problem with the Clevo W230SS: [W230SS, VIA VT1802, Green Headphone Out, Front] No sound after suspend/resume. Actually, his original title for the bug report was: ‘[W230SS, VIA VT1802, Green Headphone Out, Front] No sound after fresh boot’. I didn’t have that problem: the headphone socket of my Clevo W230SS did produce sound after a ‘fresh boot’. Regarding Kiril‘s initial problem, ALSA developer Raymond Yau made several comments, including the following:

driver should not use same audio output for device 0 and device 2

independent headphone should be disabled on notebook by default

for desktop line out and headphone connected to different audio output nodes 0x03 and 0x04

this allow you to play different audio to line out and headphone

but this feature usually should be disabled for notebook

you need to file an upstream bug report to fix this bug in the indep_hp_possible function which should return false when there is no internal mic since some notebook have line out, headphone and Mic jack to support 5.1 or only enabled when headphone at extra front and line out at ext rear

the workaround is use hint to disable the indep_hp=0

https://git.kernel.org/cgit/linux/kernel/git/tiwai/sound.git/tree/Documentation/sound/alsa/HD-Audio.txt

Now, Kiril was using Ubuntu 14.04 and ALSA 1.0.27, whereas I’m using Gentoo and ALSA 1.0.29. Furthermore, apart from the two installations using different kernel versions, in Gentoo you configure and build the kernel yourself. So there is quite some difference between the two installations, which might explain why I do not have his original problem of no sound from headphones after a fresh boot. Where we did coincide, though, was that there was no sound from headphones following resumption from suspension.

First attempt at fixing the problem

Even though Independent HP does not stop headphones working after I boot my laptop, I decided to try to remove Independent HP anyway, to see if it would fix the suspend/resume problem with headphones in my case.

The Clevo W230SS has two sound cards:

root # lspci | grep Audio
00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)
00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 05)

The HDMI audio card is Card 0, and the analogue HD Audio card is Card 1. ALSAMixer shows an Independent HP (headphone) channel for Card 1:

user $ alsamixer -c 1

The kernel documentation for the HD Audio driver explains how to fix the problem using what is called a driver ‘hint’. There is a link to the documentation in the above-mentioned bug report, and you can also find the documentation in the file /usr/src/<kernel_release>/Documentation/sound/alsa/HD-Audio.txt on your laptop if you have installed the kernel source code. As explained in the documentation, you can remove Independent HP either via the command line:

root # echo "indep_hp = no" > /sys/class/sound/hwC1D0/hints
root # echo 1 > /sys/class/sound/hwC1D0/reconfig

or by using so-called ‘Early Patching’:

Early Patching
~~~~~~~~~~~~~~
When CONFIG_SND_HDA_PATCH_LOADER=y is set, you can pass a "patch" as a
firmware file for modifying the HD-audio setup before initializing the
codec.  This can work basically like the reconfiguration via sysfs in
the above, but it does it before the first codec configuration.

Note that the term ‘patching’ here has nothing to do with patching the driver’s source code; it refers to patching the ALSA driver’s configuration of the VIA chip’s CODEC on the Intel sound card.

The format of this particular patch file containing a ‘hint’ would be as follows:

[codec]
<vendor_id> <subsystem_id> <address_of_the_CODEC>

[hint]
indep_hp = no

The values for vendor_id and subsystem_id can be found as follows:

root # cat /sys/class/sound/hwC1D0/vendor_id
0x11068446
root # cat /sys/class/sound/hwC1D0/subsystem_id
0x15582300

(As the driver is used with Card 1, remember to look in directory hwC1D0 rather than hwC0D0.)

The required value for address_of_the_CODEC is zero in this particular case. Therefore the file /lib/firmware/clevo-hda-patch (you can choose any file name you want) should have the following contents:

[codec]
0x11068446 0x15582300 0

[hint]
indep_hp = no

If you built the HA Audio driver as a module, you would need to add the following line to the file /etc/modprobe.d/alsa.conf in order to apply the patch:

options snd-hda-intel patch=,clevo-hda-patch

Notice the comma after the equals sign. This is required because the patch applies to the second card (Card 1) rather than to the first card (Card 0).

However, I had built the HD Audio driver into the kernel rather than as a module:

root # grep HDA /usr/src/linux/.config | grep -v "is not set"
CONFIG_SND_HDA=y
CONFIG_SND_HDA_INTEL=y
CONFIG_SND_HDA_PREALLOC_SIZE=2048
CONFIG_SND_HDA_HWDEP=y
CONFIG_SND_HDA_RECONFIG=y
CONFIG_SND_HDA_INPUT_BEEP=y
CONFIG_SND_HDA_INPUT_BEEP_MODE=1
CONFIG_SND_HDA_INPUT_JACK=y
CONFIG_SND_HDA_PATCH_LOADER=y
CONFIG_SND_HDA_CODEC_VIA=y
CONFIG_SND_HDA_CODEC_HDMI=y
CONFIG_SND_HDA_I915=y
CONFIG_SND_HDA_GENERIC=y
CONFIG_SND_HDA_POWER_SAVE_DEFAULT=0

Therefore adding the option to /etc/modprobe.d/alsa.conf would have no effect, as the HD Audio driver is not a module. In this case I could have appended the following parameter to the kernel boot line in the file /boot/grub/grub.cfg instead:

snd-hda-intel.patch=,clevo-hda-patch

The above kernel boot parameter could be appended to the kernel boot line either directly by editing the file grub.cfg, or indirectly by adding it to the list of boot parameters in the variable GRUB_CMDLINE_LINUX_DEFAULT="" in the file /etc/default/grub and then using the command ‘grub2-mkconfig -o /boot/grub/grub.cfg‘ as root user to regenerate the grub.cfg file. Remember to mount /boot first if it is on a different partition.

Now, I tried applying the patch using the appropriate method in each case: HD Audio driver built into the kernel, and HD Audio driver built as a module (it didn’t take me long to modify the kernel configuration and rebuild the kernel). In both cases the following messages were included in the output of the dmesg command:

[ 0.430218] snd_hda_intel 0000:00:1b.0: Applying patch firmware 'clevo-hda-patch'
[ 0.430356] snd_hda_intel 0000:00:1b.0: Direct firmware load for clevo-hda-patch failed with error -2
[ 0.430359] snd_hda_intel 0000:00:1b.0: Cannot load firmware, aborting

I’m not sure if the reason for the failure to load the patch is the same in both cases, but certainly the reason in the case of the module is that PulseAudio is already running and using the driver by the time the OS attempts to apply the patch. In the case of the kernel boot parameter, my guess is that the patch would need to be included in an initramfs in order to be able to apply it before PulseAudio starts.

The same situation occurs if you try to apply the ‘hint’ manually from the command line after start-up:

root # echo "indep_hp = no" > /sys/class/sound/hwC1D0/hints
root # echo 1 > /sys/class/sound/hwC1D0/reconfig
bash: echo: write error: Device or resource busy

The above error message occurs because PulseAudio is running and using the driver. To apply the hint and refresh the driver in this case, the solution is to stop PulseAudio beforehand:

user $ echo "autospawn = no" >> ~/.config/pulse/client.conf
user $ pulseaudio --kill
user $ su
root # echo "indep_hp = no" > /sys/class/sound/hwC1D0/hints
root # echo 1 > /sys/class/sound/hwC1D0/reconfig
root # exit
user $ pulseaudio --start

Now, having to do the above manually every time you boot your machine is impractical. To automate the procedure I did the following…

Make sure the automatic (re)spawning of PulseAudio is disabled in the file ~/.config/pulse/client.conf (you can create the file if it does not exist):

autospawn = no

Create a Bash script in the directory /etc/local.d/ for the OS to launch automatically at boot, and in that script issue the above two commands first and then start pulseaudio. I named the script ‘99-clevo-hda-fix.start‘ and made its contents the following:

#!/bin/bash
# Fix for Intel HDA problem with Clevo W230SS
# See https://bugs.launchpad.net/ubuntu/+source/alsa-driver/+bug/1313904
# N.B. Assumes your ~/.config/pulse/client.conf contains
# 'autospawn = no' so that PulseAudio is not launched automatically.
#
# Specify the hint
echo "indep_hp = no" > /sys/class/sound/hwC1D0/hints
#
# Reinitialise the HD Audio driver so it parses the CODEC tree again
echo 1 > /sys/class/sound/hwC1D0/reconfig
#
# Start PulseAudio for my user account
su -c "pulseaudio --start" -s /bin/sh fitzcarraldo

Don’t forget to make the script executable:

root # chmod +x /etc/local.d/99-clevo-hda-fix.start

This method of applying the hint to the HD Audio driver should work irrespectively of whether the driver is a module or built-in. It’s a bit more of a hack compared to the Early Patching approach, but it does the job in my case. After logging in to the Desktop Environment, you can check if the hint has been applied by looking at the contents of /sys/class/sound/hwC1D0/hints:

root # cat /sys/class/sound/hwC1D0/hints
indep_hp = no

However, this alone does not mean the CODEC was reconfigured after the hint was applied, so you need to check if Independent HP still exists. The ALSAMixer output on my laptop now looked like the following after I implemented the above method (notice that Independent HP no longer exists):

user $ alsamixer -c 1

So, what was the result? Well, audio continued to work after I removed Independent HP, but there was still no sound from headphones after resuming from suspension. And neither was there for Kiril, so he changed the title of his bug report to that effect. Fortunately, another user, unrud, commented later in the bug report that he had written init-headphone, a Python script to fix the problem. So I decided to hack his Ubuntu package to get init-headphone working in my Gentoo Linux installation. Here is how I did it…

Second (successful!) attempt at fixing the problem

1. Download init-headphone-ubuntu-0.11.zip from https://github.com/Unrud/init-headphone-ubuntu/releases

2. Extract the contents to the directory ~/init-headphone-ubuntu-0.11/

3. Copy to pm-utils’ hook directory the script that launches init-headphone upon resuming or thawing:

root # cp /home/fitzcarraldo/init-headphone-ubuntu-0.11/etc/linux-pm-utils/init-headphone /etc/pm/sleep.d/03-init-headphone # (use whatever number you want)

4. Copy the init-headphone script itself to the system binaries directory:

root # cp /home/fitzcarraldo/init-headphone-ubuntu-0.11/src/init-headphone /usr/local/sbin/

5. The init-headphone script requires the i2c_dev and i2c_i801 modules:

REQUIRED_MODULES = ["i2c_dev", "i2c_i801"]

However, I prefer to build them into the kernel rather than as modules, so I checked to make sure they are already built into the kernel:

root # grep CONFIG_I2C /usr/src/linux/.config | grep -v "is not set"
CONFIG_I2C=y
CONFIG_I2C_BOARDINFO=y
CONFIG_I2C_COMPAT=y
CONFIG_I2C_CHARDEV=y
CONFIG_I2C_MUX=y
CONFIG_I2C_HELPER_AUTO=y
CONFIG_I2C_ALGOBIT=y
CONFIG_I2C_I801=y

Then I commented out the lines in /usr/local/sbin/init-headphone that check if the two modules are loaded:

root # diff /home/fitzcarraldo/init-headphone-ubuntu-0.11/src/init-headphone /usr/local/sbin/init-headphone
174,181c174,181
< def check_modules():
< try:
< for module in REQUIRED_MODULES:
< logging.info("Trying to add module to the kernel: %s", module)
< if subprocess.call(["modprobe", "--quiet", module]) != 0:
< logging.warning("Module is not loaded: %s", module)
< except OSError:
#def check_modules():
> # try:
> # for module in REQUIRED_MODULES:
> # logging.info("Trying to add module to the kernel: %s", module)
> # if subprocess.call(["modprobe", "--quiet", module]) != 0:
> # logging.warning("Module is not loaded: %s", module)
> # except OSError:
> # logging.warning("modprobe not found")
206c206
# check_modules()

6. I created a script /etc/local.d/99-clevo-hda-fix.start to launch init-headphone automatically at boot:

#!/bin/bash
# Fix for Intel HDA problem with Clevo W230ss
# See https://bugs.launchpad.net/ubuntu/+source/alsa-driver/+bug/1313904
exec /usr/local/sbin/init-headphone

root # chmod +x /etc/local.d/99-clevo-hda-fix.start

7. Add the kernel boot parameter ‘acpi_enforce_resources=lax‘ to the end of the kernel boot line(s) in /boot/grub/grub.cfg (don’t forget to mount /boot first if it is on another partition). You can either edit /boot/grub/grub.cfg directly, or indirectly by adding the parameter to the list of existing parameters in GRUB_CMDLINE_LINUX_DEFAULT (if any) as shown below and issuing the command ‘grub2-mkconfig -o /boot/grub/grub.cfg‘ as root user (again, don’t forget to mount /boot first if it is on another partition):

GRUB_CMDLINE_LINUX_DEFAULT="acpi_enforce_resources=lax"

8. Create a script file /etc/local.d/99-clevo-hda-fix.start to launch the init-headphone automatically at boot:

#!/bin/bash
# Fix for Intel HDA problem with Clevo W230SS
# See https://bugs.launchpad.net/ubuntu/+source/alsa-driver/+bug/1313904
exec /usr/local/sbin/init-headphone

9. As my user account does not have a path configured to the system binaries directory, I created a symlink to it from the directory /usr/local/bin/:

root # ln -s /usr/local/sbin/init-headphone /usr/local/bin/init-headphone

10. As I no longer needed to stop PulseAudio running at boot, I deleted the file /home/fitzcarraldo/.config/pulse/client.conf I had created earlier (or you could just change ‘autospawn = no‘ to ‘autospawn = yes‘).

You can also use init-headphone from the command line:

user $ sudo init-headphone --help

e.g.

user $ sudo init-headphone unmute

This looks like it has finally solved the problem; now headphones still work after my laptop resumes from suspension. I still don’t need to pass the ‘hint’ to the HD Audio driver, so Independent HP continues to appear in ALSAMixer and apparently does not cause any problems.

A big ‘Thank you’ from me to Unrud for creating init-headphone.

PROBLEM 2: No sound from headphones after re-plug

The other problem I experienced with the Clevo W230SS was that, if I unplugged working headphones, audio switched to the laptop’s speakers as expected, but, if I then plugged-in the headphones again, no more sound came from the headphones. If I again unplugged the headphones, sound would again come from the speakers. If I did all this whilst ALSAMixer was running, then:

  1. if I unplugged the headphones, as expected the ALSAMixer volume level indicator for the speaker would rise from zero and the volume level indicator for the headphones would drop to zero;
  2. if I plugged in the headphones, as expected the ALSAMixer volume level indicator for the speaker would drop to zero and the volume level indicator for the headphones would rise from zero.

Now, it is possible that this problem was due to the same thing that caused the loss of audio to headphones when the laptop resumed from suspension. Anyway, before I came across init-headphone I found the following in the Arch Linux Wiki article on PulseAudio:

Switch on connect

This is a module used to switch the output sound to the newly connected device. For example, if you plug in a USB headset, the output will be switched to that. If you unplug it, the output will be set back to the last device. This used to be quite buggy but got a lot of attention in PulseAudio 8.0 and should work quite well now.

If you just want to test the module then you can load it at runtime by calling:

root # pactl load-module module-switch-on-connect

If you want to make the change persistent you will have to add it to your local pulseaudio settings or to /etc/pulse/default.pa (system wide effect). In either case, add this line:

load-module module-switch-on-connect

So, as the file /etc/pulse/default.pa in my installation did not have that line, I added it:

# Added by fitzcarraldo
# https://wiki.archlinux.org/index.php/PulseAudio
# The headphone socket no longer worked if I
# removed and re-inserted the jack plug.
load-module module-switch-on-connect

This seemed to help, but I am not certain module-switch-on-connect is really having an effect when I plug and unplug headphones, and I have not bothered to disable it to see what happens now that init-headphone is in use (I’m just happy that audio is all working now, whatever the reason!). ALSA’s Auto-Mute Mode* appears to perform the same role as module-switch-on-connect: When I unplug the headphones with Auto-Mute Mode enabled in ALSAMixer, there is a noticeable delay before sound starts to come from the laptop’s speakers, whereas there is no such delay when I unplug the headphones with Auto-Mute Mode disabled via ALSAMixer, so presumably module-switch-on-connect is doing its job.

* The documentation file /usr/src/<kernel_release>/Documentation/sound/alsa/HD-Audio-Controls.txt explains what Auto-Mute Mode does.

Anyhow, one or both of the two software modifications (init-headphone and module-switch-on-connect) seem to have cured the problem of no sound from headphones after they are disconnected then reconnected to the laptop.

Audio in Linux becomes annoying again

At the moment I seem to be having more audio problems than usual. Last month I blogged about having to fix the ALSA Speaker volume level resetting to zero at boot, and recently two other audio problems have cropped up.

Thunderbird

I have been having trouble with Thunderbird’s ‘system sound’ that announces the arrival of a new e-mail. Lately, Thunderbird has started playing too loud and with significant distortion the audio clip it had been playing perfectly for the last four years. This is especially strange because I created that audio clip with Audacity from another audio clip that sounded too loud when Thunderbird played it. Ironically, the work-around for this latest problem was to switch to the original, much louder sound clip alert.wav instead of the quieter alert_quiet.wav. Not only does Thunderbird now play alert.wav at a lower volume than alert_quiet.wav, but the sound of alert.wav is not distorted when Thunderbird plays it. Yet if I play alert.wav and alert_quiet.wav using SMPlayer, the former is much louder than the latter and neither is distorted. Figure that one out.

The event notification sound that Thunderbird uses to remind me about an impending meeting scheduled in the calendar has now started sounding very distorted too. I still have not found a work-around for that. Event sounds played by the desktop environment I use (KDE) are not distorted, so what is Thunderbird doing? Perhaps the problem is not Thunderbird itself but the audio library it uses, so I need to investigate further.

Skype

Yet another audio problem cropped up this morning when I connected my laptop to an external monitor and keyboard (and thus I left the laptop’s lid almost closed) in an open-plan office and booted the laptop. I entered my username and password on the KDM log-in screen, and the KDE splash screen appeared as usual. After a few seconds the laptop’s speakers suddenly emitted a piercing, continuous howl; the well-known sound of audio feedback from speakers to microphone. It was LOUD. The volume control buttons on the keyboard made no difference, and the sound was so loud that everyone in the office noticed and several people came over to tell me to reset the BIOS (apparently that had fixed the problem for their laptops running Windows).

I kept my finger on the laptop’s power switch and, after several seconds, the laptop powered off. My laptop dual boots Windows 7 and Gentoo Linux, and the audio feedback did not occur when I booted Windows 7. After booting Linux again a couple of times and annoying everyone in the office even more, I discovered I could open the laptop’s lid far enough back to reduce the feedback to a low whine, so I could let KDE finish launching and display the Desktop. I then launched ALSAMixer and discovered that ‘Internal Mic Boost’ was set to 100%. So I immediately lowered it to zero. Then the penny dropped: I had used Skype the previous night without bothering to connect my headphones and external microphone, and Skype had automatically raised ‘Internal Mic Boost’ all the way up to 100%. So I immediately launched Skype, selected ‘Options’ > ‘Sound Devices’ and unticked ‘Allow Skype to automatically adjust my mixer levels’. The next thing I did was add the following lines to the script /etc/local.d/20set_alsa_volume.start mentioned in my previous blog post Fix for ALSA Speaker volume level resetting to zero at boot:

su -c "amixer -c 0 -- sset 'Internal Mic Boost' 0%" -s /bin/sh fitzcarraldo
su -c "amixer -c 0 -- sset 'Internal Mic' 0%" -s /bin/sh fitzcarraldo
su -c "amixer -c 0 -- sset 'Mic Boost' 0%" -s /bin/sh fitzcarraldo
su -c "amixer -c 0 -- sset 'Mic' 0%" -s /bin/sh fitzcarraldo

From now on, only I am allowed to adjust microphone settings! To avoid any possibility of feedback loops in future, the above-mentioned script sets all the microphone channels to zero and I will have to adjust them myself before use. I already have ALSAMixerGUI in the KDE Launcher menu, so it won’t be a big deal to do that.

This fiasco with Skype got me thinking: if Skype is set to automatically adjust mixer levels when you are in a conversation, when you exit Skype why doesn’t it automatically set mixer levels back to the way they were when Skype was launched? It could be done easily and would be more user-friendly than the current way Skype works.

Interrelationship between PulseAudio and ALSA

The final thing I did (yet again) was to adjust all the various ALSA channels and PulseAudio channels to try and get the resulting audio input and output sounding reasonable. This is easier said than done. I often have to mess around with ALSAMixer and PulseAudio Volume Control in order to get audio input and output working satisfactorily in all applications that use audio. It is actually more difficult than it sounds (ouch!) to get ALSA and PulseAudio ‘balanced’ (for want of a better word). In the days before PulseAudio existed, one only had to adjust ALSA. Now, with two agents controlling audio, the task turns out to be surprisingly awkward sometimes.

To sum up, boo to Thunderbird (or whatever it uses to play sounds), boo to Skype and boo to PulseAudio. I’m fed up with audio issues in Linux at the moment. 😡

Update (January 19, 2015): It turns out that the problem in Thunderbird was due to PulseAudio. See my next post for details of how I fixed it.

Fix for ALSA Speaker volume level resetting to zero at boot

Up until 2011 the problem of the volume level in ALSA resetting to zero at boot was a common occurrence in my Linux installations. Actually it was a common occurrence in Linux, full stop; search the Web using keywords such as “alsa reset volume” and you’ll find umpteen links. In 2012 the situation improved and I thought the problem had become a thing of the past, but it resurfaced in 2013 on my main laptop and has plagued me through every update since (well, apart from in one release of KDE). Every time I reboot, the ALSA Speaker channel’s volume is zero when I log-in to KDE. And, as KMix is a PulseAudio mixer by default these days, I have to launch ALSAMixer and raise the volume of the Speaker channel manually.

I don’t know if the source of the problem lies in KDE, PulseAudio or ALSA itself. It did disappear after one upgrade to KDE earlier this year (I don’t recall which release of KDE) but returned in the next KDE upgrade, so I suspect it is a KDE issue. In earlier days I could resolve the problem using the commands alsactrl store and alsactl restore and similar approaches. However, this time none of those fixes work for me. The problem never bothered me much, as I always connect external speakers to my laptop’s headphone socket when I’m at home, and I don’t want my laptop emitting sounds at the office. Nevertheless, the fact the problem exists niggled me, so I decided to try and fix it. Rather than expending any more effort trying to get the usual approaches to work (the Web is littered with suggested fixes over the years), I decided to reset the Speaker volume to the same level at each boot by using an automatically-launched shell script. The method I use is given below, and should work with either OpenRC or systemd in Gentoo Linux.

1. Create the file /etc/local.d/20set_alsa_volume.start containing the following:

#!/bin/bash
# Reset ALSA Speaker channel on the first sound card to 90% after booting.
su -c "amixer -c 0 -- sset Speaker playback 90%" -s /bin/sh fitzcarraldo

(Replace “fitzcarraldo” with your own user name, of course.)

2. Make the script executable:

# chmod +x 20set_alsa_volume.start

That’s all there is to it. The volume of the ALSA Speaker channel is always set to 90% after I reboot and login to the desktop environment. KMix remembers the PulseAudio volume setting from the previous session, so I can still avoid blasting the laptop’s speakers.

By the way, the manual pages for the amixer and alsamixer commands make useful reading:

$ man amixer
$ man alsamixer

For example, the first audio card (Card 0) in my main laptop has the following controls:

$ amixer -c 0 scontrols
Simple mixer control ‘Master’,0
Simple mixer control ‘Headphone’,0
Simple mixer control ‘Speaker’,0
Simple mixer control ‘PCM’,0
Simple mixer control ‘Mic’,0
Simple mixer control ‘Mic Boost’,0
Simple mixer control ‘Beep’,0
Simple mixer control ‘Capture’,0
Simple mixer control ‘Auto-Mute Mode’,0
Simple mixer control ‘Digital’,0
Simple mixer control ‘Internal Mic’,0
Simple mixer control ‘Internal Mic Boost’,0

Update (January 29, 2015): I found the cause of the problem: PulseAudio. I edited the file /usr/share/pulseaudio/alsa-mixer/paths/analog-output.conf as per user agmg‘s January 2013 post Re: [SOLVED] Problems with PulseAudio 3.0 in the PCLinuxOS Forums:

Again, I had to edit the file: /usr/share/pulseaudio/alsa-mixer/paths/analog-output.conf

and change this:

[Element Speaker]
switch = mute
volume = off

to this:

[Element Speaker]
switch = mute
volume = merge

I realized that editing the [Element Desktop Speaker] section of the above file, has no effect on the issue. Only the edit to [Element Speaker] is needed in my case.

In my case this change forces the ALSA Speaker channel volume to 100% after rebooting (irrespective of the volume levels I set via ALSAMixer and KMix before shutdown).

The contents of the file /usr/share/pulseaudio/alsa-mixer/paths/analog-output.conf also include the following comment:

; See analog-output.conf.common for an explanation on the directives

The contents of the file analog-output.conf.common include the following comment:

; volume = ignore | merge | off | zero | <volume step> # What to do with this volume: ignore it, merge it into the device
;                                                      # volume slider, always set it to the lowest value possible, or always
;                                                      # set it to 0 dB (for whatever that means), or always set it to
;                                                      # <volume step> (this only makes sense in path configurations where
;                                                      # the exact hardware and driver are known beforehand).

So I could have tried volume = <volume step> instead of volume = merge, although I have no idea what value <volume step> would need to be. Anyway, the Bash script /etc/local.d/20set_alsa_volume.start that I created does the job in a different way without me having to tinker with the troublesome PulseAudio, so I reverted to volume = off in the file analog-output.conf and reverted to using /etc/local.d/20set_alsa_volume.start as explained earlier.

Nostalgia for those ALSA mixer channels that KMix and GNOME Volume Control used to have?

These days the GUI mixers KMix and GNOME Sound Preferences display PulseAudio devices and streams rather than ALSA mixer channels. For example, prior to its integration with PulseAudio, KMix typically displayed a mixer window that looked like the one below.

KMix showing ALSA channels

KMix with ALSA channels

whereas, today, a KMix window typically looks like the following:

KMix with PulseAudio channels

KMix with PulseAudio channels

 

KMix 3.8 in KDE 4.6.1 does not provide separate speaker and headphone channels. You can alter the headphone and speaker volume by using PulseAudio Volume Control instead (see the picture below), but people are not as familiar with the PulseAudio GUI, and it is yet another step to perform.

PulseAudio Volume Control showing selection of Headphones channel

PulseAudio Volume Control showing selection of Headphones channel

 

If you are like me, you probably end up using KMix (or GNOME Sound Preferences) but also launch ALSA Mixer in a Konsole/Terminal for fine-grained control of the underlying ALSA channels:

ALSA Mixer running in Konsole

ALSA Mixer running in Konsole

This is more hassle, because you launch Konsole/Terminal and you enter the command alsamixer and press F6 (alternatively, use the command alsamixer -c 0 if your sound card is Card 0). The PulseAudio channels are displayed by default if you don’t specify your sound card when you launch ALSA Mixer.

EDIT (January 28, 2012): With recent versions of ALSA Mixer I have found that I must specify the card in the alsamixer command (e.g. alsamixer -c 0) because the command alsamixer alone results in a Segmentation fault message.

It would be handy to have an icon on the Panel or on the Desktop that you could use to launch ALSA Mixer. Well, you can. In fact, as there is also a GUI version of ALSA Mixer (albeit with a few less features than its console equivalent) you can use that instead if you prefer. Below I explain a few of the possible ways you can display ALSA Mixer easily from within a desktop environment.

Change KMix from a PulseAudio mixer to an ALSA mixer

By default KMix displays PulseAudio channels instead of ALSA channels. However, if you want to display the ALSA channels instead (as shown in the first picture above), quit KMix and enter the following command in a Konsole window or in KRunner:

export KMIX_PULSEAUDIO_DISABLE=1 && kmix

If you want to make this permanent then add KMIX_PULSEAUDIO_DISABLE=1 to the file /etc/conf.d/alsasound

Personally, though, I prefer not to do this as I want to control the PulseAudio channels via the KMix mixer. Try running two or more audio/video apps simultaneously and you’ll see what I mean – it’s useful! For example, I can control the volume of various applications separately (handy when you want to check something or are using Skype), as illustrated by the picture below:

KMix showing PulseAudio playback streams tab

KMix showing PulseAudio playback streams tab

and I run ALSA Mixer separately to tweak the underlying ALSA channels. Using Yakuake (or Guake in GNOME) is quite a good way to run ALSA Mixer in a console: it is quick and easy to pop-up a window to launch ALSA Mixer, and ALSA Mixer is displayed in colour at nearly the width of the desktop.

Launch ALSA Mixer GUI from an icon on the Panel

First, use your package manager to install the package alsamixergui. It’s a GUI equivalent of the console ALSA Mixer, but with a few less options.

Once you install it, you should find ALSA Mixer GUI in your desktop environment menu (e.g. Kickoff > Applications > Multimedia > ALSA Mixer GUI). By default this will show the PulseAudio channels, so use the menu editor (e.g. right-click on Kickoff and select Menu Editor) to change the command to the following if your sound card is Card 0:

alsamixergui -c 0

Once you have done this, save the new menu entry, log out and log in again, and when you launch ALSA Mixer GUI from the menu a window similar to the following will pop-up:

ALSA Mixer GUI

ALSA Mixer GUI

To put an icon on the Panel in order to make it even easier to launch ALSA Mixer GUI, just drag the icon from the menu to the Panel and it will be copied to the Panel. Simple as that.

Launch ALSA Mixer in a Konsole docked in the System Tray

You can do this using KDocker, which works in KDE, GNOME, Xfce and other desktop environments.

For KDE, create the following Desktop Configuration File Konsole-alsamixer.desktop (or whatever name you want) and put it in the directory ~/.kde4/Autostart/

[Desktop Entry]
Comment[en_GB]=Console (docked) running ALSA Mixer
Comment=Console (docked) running ALSA Mixer
Exec=kdocker konsole -e alsamixer -c 0
GenericName[en_GB]=Dock Konsole running ALSA Mixer in the System Tray
GenericName=Dock Konsole running ALSA Mixer in the System Tray
Icon=kmix
MimeType=
Name[en_GB]=Konsole (Docked)
Name=Konsole (Docked)
Path=
StartupNotify=true
Terminal=false
TerminalOptions=
Type=Application
X-DBUS-ServiceName=
X-DBUS-StartupType=
X-KDE-SubstituteUID=false
X-KDE-Username=
KDE System Tray showing Konsole docked using KDocker

KDE System Tray showing Konsole docked using KDocker

Clicking on the docked Konsole icon in the System Tray will pop-up a Konsole window with the familiar ALSA Mixer running in it, as shown in the fourth picture above. Clicking on the icon again will minimise the Konsole to the System Tray.

Launch ALSA Mixer in a Konsole from an icon on the Desktop

For KDE, create the following Desktop Configuration File Konsole-alsamixer.desktop (or whatever name you want) and put it in the directory ~/Desktop/

[Desktop Entry]
Comment[en_GB]=Console running ALSA Mixer
Comment=Console running ALSA Mixer
Exec=konsole -e alsamixer -c 0
GenericName[en_GB]=Konsole running ALSA Mixer
GenericName=Konsole running ALSA Mixer
Icon=kmix
MimeType=
Name[en_GB]=Konsole
Name=Konsole
Path=
StartupNotify=true
Terminal=false
TerminalOptions=
Type=Application
X-DBUS-ServiceName=
X-DBUS-StartupType=
X-KDE-SubstituteUID=false
X-KDE-Username=

You can change the icon displayed on the Desktop either by right-clicking on the icon on the Desktop and selecting Properties or by editing the file directly. For example, I specified Icon=/usr/share/icons/mono/scalable/apps/kmix.svgz which looks rather retro and I think suits the unsophisticated looks of ALSA Mixer.

Summary

I have not covered all the options for making it easy to display ALSA channels as well as PulseAudio channels, but hopefully one of the above methods will suit your needs or will spur you to experiment.