Skip to content

PulseAudio integration

borine edited this page Jul 19, 2022 · 38 revisions

Using BlueALSA and PulseAudio Together

PulseAudio (https://www.freedesktop.org/wiki/Software/PulseAudio/) is the de-facto Linux standard audio server, particularly for desktop installations. Many linux distributions' desktops require PulseAudio in order to provide full functionality.

PulseAudio has its own bluetooth audio implementation which is sufficient in many common usage scenarios. If you need to use PulseAudio for any reason then it is recommended to at least try its internal bluetooth audio implementation before attempting this integration. Conversely, if you do not need PulseAudio, then it is recommended to use BlueALSA for bluetooth audio and not to run PulseAudio at all.

Of course, there may be rare occasions when you find it necessary to run both services. This wiki article describes one method of using the two services in an integrated way. This approach should be considered as "experimental" and as such suffers many compromises and limitations.

Bluez allows only one service to register as provider of a bluetooth profile, so it is necessary to disable the PulseAudio bluetooth modules in order to use Pulseaudio in combination with BlueALSA.

Preparing PulseAudio for use with BlueALSA

Disable PulseAudio bluetooth modules

There are three ways to disable the PulseAudio bluetooth modules.

  1. Uninstall the module packages

    Many distributions deliver the PulseAudio bluetooth modules as separate packages, and so for these the simplest solution is to uninstall those packages. For example, on Ubuntu

    sudo apt purge pulseaudio-module-bluetooth
    
  2. Remove the modules from the PulseAudio configuration

    If the modules cannot be uninstalled, then they can still be disabled in the PulseAudio configuration. This is achieved by editing the file /etc/pulse/default.pa to comment out the bluetooth module entries as shown here:

    ### Automatically load driver modules for Bluetooth hardware
    #.ifexists module-bluetooth-policy.so
    #load-module module-bluetooth-policy
    #.endif
    
    #.ifexists module-bluetooth-discover.so
    #load-module module-bluetooth-discover
    #.endif
    

    Restart the PulseAudio service to read the new configuration. On most desktop systems this service is configured to automatically restart, so it is sufficient to type:

    pulseaudio --kill
    
  3. Unload the PulseAudio bluetooth modules at runtime

    It is possible to temporarily remove the modules at runtime with the commands:

    pactl unload-module module-bluetooth-policy
    pactl unload-module module-bluetooth-discover
    

    Note that these commands will have to be re-run each time PulseAudio is restarted.

Remove PulseAudio ALSA default config

PulseAudio installs itself as the default ALSA PCM device. To achieve this it uses a "hook" function that can interfere with the user's own PCM definitions. As many BlueALSA configurations depend on specific entries in the ALSA configuration it is recommended to remove the "hook" function. This can be done by deleting the symbolic link:

/etc/alsa/conf.d/99-pulse.conf

If you wish to continue using PulseAudio as the default ALSA PCM device you can do so by adding this line to your ~/.asoundrc file:

pcm.!default pulse

Adding BlueALSA Devices as PulseAudio Sinks / Sources

With the above changes, it is possible to run the BlueALSA service at the same time as PulseAudio. Applications will have to connect to ALSA directly using the ALSA API to use bluetooth devices; PulseAudio will not see them. So applications that are configured to use the PulseAudio API (including most desktop volume control panels) will unable to use bluetooth audio. That may be good enough for many systems, so this section is optional and only relevant if you need to use BlueALSA devices via the PulseAudio API (for example with Firefox on Ubuntu).

To present BlueALSA PCMs via the PulseAudio API it is necessary to do a little more preparation of the configration, and then to load the relevant modules into PulseAudio manually. The following 3 steps describe this procedure.

1. Define ALSA PCM for BlueALSA with no conversions

It is recommended to allow PulseAudio to perform any necessary audio format conversions internally, and not to use the alsa-lib "plug" or other alsa plugins. This is especially important if you have libasound version 1.1.2 or 1.1.3 which will otherwise cause the PulseAudio daemon to deadlock. A simple way to achieve this is to create a file 21-bluealsa-raw.conf in the appropriate ALSA config directory

  • /usr/share/alsa/alsa.conf.d/21-bluealsa-raw.conf ( alsa-lib version <= 1.1.6 )
  • /etc/alsa/conf.d/21-bluealsa-raw.conf ( alsa-lib version >= 1.1.7 )

Put the following into that file:

pcm.bluealsa_raw {
	@args [ DEV PROFILE CODEC VOL SOFTVOL DELAY SRV ]
	@args.DEV {
		type string
		default {
			@func refer
			name defaults.bluealsa.device
		}
	}
	@args.PROFILE {
		type string
		default {
			@func refer
			name defaults.bluealsa.profile
		}
	}
	@args.CODEC {
		type string
		default {
			@func refer
			name defaults.bluealsa.codec
		}
	}
	@args.VOL {
		type string
		default {
			@func refer
			name defaults.bluealsa.volume
		}
	}
	@args.SOFTVOL {
		type string
		default {
			@func refer
			name defaults.bluealsa.softvol
		}
	}
	@args.DELAY {
		type integer
		default {
			@func refer
			name defaults.bluealsa.delay
		}
	}
	@args.SRV {
		type string
		default {
			@func refer
			name defaults.bluealsa.service
		}
	}
	type bluealsa
	device $DEV
	profile $PROFILE
	codec $CODEC
	volume $VOL
	softvol $SOFTVOL
	delay $DELAY
	service $SRV
}

2. Configure PulseAudio to suspend on idle

This step is only necessary if you wish to use a device that offers both A2DP and HFP/HSP sinks (or both A2DP and HFP/HSP sources).

Unless configured otherwise, PulseAudio will immediately open and hold each BlueALSA PCM device that is loaded. This can cause problems for devices that support both A2DP and SCO PCMs. The only way to keep a PCM loaded but not open is to "suspend" it. However, most PulseAudio GUI tools (including pavucontrol) do not allow the user to manually suspend and unsuspend sinks and sources. The workaround for this is to enable the "suspend-on-idle" feature, with a sufficiently low timeout. Some linux distributions enable this feature, others do not. To check if your PulseAudio instance has this module loaded, type:

pactl list modules

and look for the module-suspend-on-idle entry:

Module #20
	Name: module-suspend-on-idle
	Argument: timeout=5
	Usage counter: n/a
	Properties:
		module.author = "Lennart Poettering"
		module.description = "When a sink/source is idle for too long, suspend it"
		module.version = "11.1"

The Module number, and other parameter values, may differ.

If the module is loaded, check the "Argument:" parameter. We need a low timeout value because there will be silence of that amount of time when switching from A2DP to SCO. If the Argument is blank, the default timeout is 5 seconds.

If the module is not loaded or the timeout needs to be changed, we must edit the file /etc/pulse/default.pa. Add an entry (or edit an existing entry) as:

### Automatically suspend sinks/sources that become idle for too long
load-module module-suspend-on-idle timeout=2

Important Note:

pavucontrol by default shows volume meters for each device, and these prevent the devices from being suspended while pavucontrol is running. To disable the volume meters, and thus enable the auto suspend feature when pavucontrol is running, go to the pavucontrol Configuration tab and uncheck the "Show volume meters" checkbox in the bottom left-hand corner.

3. Create sink and / or source objects

Each bluetooth device that you wish to use with PulseAudio needs to be added individually as a sink, source, or both as appropriate. If you wish to use both A2DP and SCO profiles for a single device, then they too will need to be added individually.

The way to add a device is to load the module-alsa-sink or module-alsa-source modules with appropriate parameters. In order to later remove a device, it is helpful to make a note of the module index allocated to it. The utility pactl returns that index on successful completion. The complete list of parameters for these modules can be seen here: https://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/User/Modules/

It is necessary to explicitly set the "fragments" and "fragment_size" module parameters because the defaults used by module-alsa-sink and module-alsa-source can cause PulseAudio to become unresponsive for many seconds at a time. I recommend to try fragments=1 and fragment_size=960 as a first guess, and experiment from there.

It is helpful to give the device a user-friendly description for use in the description displayed in graphical tools such as pavucontrol or other desktop sound control applications/widgets, by using the sink_properties or source_properties parameter as appropriate.

It is also possible to set the display icon in the source_properties parameter - it will default to "audio-card" but you may prefer to use "audio-speakers-bluetooth", "audio-headphones-bluetooth", "audio-headset-bluetooth", "phone-bluetooth", or maybe just "bluetooth". The icons actually available will depend on your desktop distribution.

The device must first be connected before adding to PulseAudio.

For example, to load a playback (sink) device, set its internal name (used by command line tools such as pactl and pacmd), set its user-friendly description and icon, and record its allocated module index, type:

MODULE=$(pactl load-module module-alsa-sink device='bluealsa_raw:DEV=XX:XX:XX:XX:XX:XX,PROFILE=a2dp' fragments='1' fragment_size='960' sink_name=MyFriendlyName sink_properties="device.description='My\ Friendly\ Description'device.icon_name=audio-speakers-bluetooth")

(Note the use of "bluealsa_raw" as defined above in the device field, and the need to escape space characters with a backslash in the description field. Do not leave any space between property settings)

To remove the device from PulseAudio, type

pactl unload-module $MODULE

The procedure for a capture (source) device is the same, except to use 'source' in place of 'sink' in the commands:

MODULE=$(pactl load-module module-alsa-source device='bluealsa_raw:DEV=XX:XX:XX:XX:XX:XX,PROFILE=a2dp' fragments='1' fragment_size='960' source_name=MyFriendlyName source_properties="device.description='My\ Friendly\ Description'device.icon_name=phone-bluetooth")

Automating The Addition Of BlueALSA Devices to PulseAudio

It is possible to automate the above procedure by running a service that listens for D-Bus ObjectManager events from org.bluealsa and invokes the above pactl commands in response to the addtition and removal of BlueALSA PCMs. The following example script demonstrates how that might be done by using the BlueALSA utilty bluealsa-cli to perform the event monitoring.

The script requires features of the bluealsa-cli utility were introduced in BlueALSA release v4.0.0, and will not work will older releases. Be sure to add the configure option --enable-cli to build the bluealsa-cli utility when building BlueALSA from source.

1. Create D-Bus service

#!/bin/bash

# revision 0.5

declare -A include_type

# select which device types to load into pulseaudio
# outputs (speakers, headphones) are "sinks"
# inputs (microphones) are "sources"
# either comment out lines with unwanted types, or set value to "no"
include_type[a2dp_sink]=yes
include_type[a2dp_source]=yes
include_type[sco_sink]=yes
include_type[sco_source]=yes

# experiment with these values if you experience underruns/overruns
FRAGMENTS=1
FRAGMENT_MSEC=5

# change this if you wish to use a different icon
ICON_NAME="bluetooth"

declare -A pa_format
pa_format[U8]=u8
pa_format[S16_LE]=s16le
pa_format[S24_LE]=s24le
pa_format[S32_LE]=s32le

declare -A sample_size
sample_size[U8]=1
sample_size[S16_LE]=2
sample_size[S24_LE]=3
sample_size[S32_LE]=4

declare -A new_pcm
monitor_stop=0

# an array to store pulseaudio module ids so they can be removed later
declare -A modules

# print device alias from Bluez to stdout
# $1 device dbus object path
get_alias() {
	local alias=$(dbus-send --print-reply=literal --system --dest=org.bluez "$1" \
	    org.freedesktop.DBus.Properties.Get \
		string:"org.bluez.Device1" string:"Alias")
	printf "%s" "${alias#   variant       }"
}

# add a pcm to PulseAudio
pcm_added() {
	local profile=a2dp
	[[ "${new_pcm[profile]}" = HFP || "${new_pcm[profile]}" = HSP ]] && profile=sco
	local mode="${new_pcm[mode]}"
	[[ ${include_type[${profile}_${mode}]} = yes ]] || return

	local alias=$(get_alias "${new_pcm[device]}")
	[[ -n "$alias" ]] || return

	local addr="${new_pcm[addr]}"
	local device="bluealsa_raw:DEV=$addr,PROFILE=$profile"
	local name=bluealsa.$mode.${addr//:/_}.$profile
	local description="Bluetooth:\ ${alias// /\\ }\ ($profile)"
	local format=${pa_format[${new_pcm[format]}]}
	local sample_size=${sample_size[${new_pcm[format]}]}
	[[ -n "$format" ]] || return
	local channels="${new_pcm[channels]}"
	local rate="${new_pcm[rate]}"
	[[ "$rate" -eq 0 ]] && rate=8000
	local fragment_size=$(( $FRAGMENT_MSEC * $sample_size * $channels * $rate / 1000 ))

	local module_id=$(pactl load-module "module-alsa-$mode" "format='$format'" "rate='$rate'" "channels='$channels'" "fragments='$FRAGMENTS'" "fragment_size='$fragment_size'" "fixed_latency_range='true'" "device='$device'" "${mode}_name='$name'" "${mode}_properties=device.description='$description'device.icon_name=$ICON_NAME")

	[[ -n "$module_id" ]] && modules[${new_pcm[id]}]=$module_id
}

# remove a device from PulseAudio
pcm_removed() {
	local module_id=${modules["$1"]}
	if [[ -n "$module_id" ]] ; then
		pactl unload-module $module_id 2>/dev/null
		unset modules["$1"]
	fi
}

# remove all PCMs if bluealsa service terminates
service_stopped() {
	local name
    for name in "${!modules[@]}" ; do
            pactl unload-module ${modules[$name]} 2>/dev/null
            unset modules[$name]
    done
}

# store a pcm property into the global new_pcm array
# $1 the property as printed by bluealsa-cli
set_property() {
	local temp
	case "$1" in
		Device*)
			new_pcm[device]="${1#Device: }"
			;;
		Sequence*)
			new_pcm[sequence]="${1#Sequence: }"
			;;
		Transport*)
			temp="${1#Transport: }"
			case "$temp" in
				A2DP*)
					new_pcm[profile]=A2DP
					;;
				HFP*)
					new_pcm[profile]=HFP
					;;
				HSP*)
					new_pcm[profile]=HSP
					;;
			esac
			;;
		Mode*)
			new_pcm[mode]="${1#Mode: }"
			;;
		Format*)
			new_pcm[format]="${1#Format: }"
			;;
		Channels*)
			new_pcm[channels]="${1#Channels: }"
			;;
		Sampling*)
			temp="${1#Sampling: }"
			new_pcm[rate]="${temp% Hz}"
			;;
		"Selected codec"*)
			new_pcm[codec]="${1#Selected codec: }"
			;;
	esac
}

# get connected PCMs
# uses global new_pcm array to pass data to pcm_added() function
add_initial_pcms() {
	local addr
	local REPLY
	while read; do
		case "$REPLY" in
			/*)
				[[ -n "${new_pcm[id]}" ]] && pcm_added
				new_pcm=()
				new_pcm[id]=${REPLY}
				addr=${REPLY#*dev_}
				addr=${addr%%/*}
				new_pcm[addr]=${addr//_/:}
				;;
			*)
				set_property "$REPLY"
				;;
		esac
	done <<< $(bluealsa-cli --quiet --verbose list-pcms)
	[[ -n "${new_pcm[id]}" ]] && pcm_added
}

monitor_finished() {
	service_stopped
	monitor_stop=1
}

fifo=$(mktemp -u)
mkfifo $fifo
exec {monitor_fd}<>$fifo
rm $fifo

bluealsa-cli --quiet --verbose monitor >&$monitor_fd &
cli_pid=$!
trap "kill $cli_pid; monitor_finished; exec {monitor_fd}>&-" INT TERM

add_initial_pcms

unset monitor_stop
while [[ -z "$monitor_stop" ]] && read -u $monitor_fd 2>/dev/null
do
	case "$REPLY" in
		PCMAdded*)
			new_pcm=()
			new_pcm[id]=${REPLY#PCMAdded }
			addr=${REPLY#*dev_}
			addr=${addr%%/*}
			new_pcm[addr]=${addr//_/:}
			;;
		"")
			pcm_added
			new_pcm=()
			;;
		PCMRemoved*)
			new_pcm=()
			pcm_removed "${REPLY#PCMRemoved }"
			;;
		ServiceStopped*)
			new_pcm=()
			service_stopped
			;;
		*)
			set_property "$REPLY"
			;;
	esac
done

The script should be run as a normal user, not as root.

Note that when switching a stream from an A2DP sink to a SCO sink on the same device, there will be several seconds of silence before the stream resumes, because SCO playback will only commence when the A2DP device is suspended by PulseAudio.

2. Run the D-Bus service whenever PulseAudio is running

If you are running PulseAudio within your desktop session and using systemd, then the above script (or your own improved service) can be launched whenever you log in to the desktop by enabling it as a systemd user service.

For example, if you install the above script as /usr/local/bin/bluepulse.bash, save the following systemd service file as:

/usr/local/lib/systemd/user/bluepulse.service

[Unit]
Description=BlueALSA PulseAudio Integration
BindsTo=pulseaudio.service
After=pulseaudio.service

[Service]
Type=simple
ExecStart=/usr/local/bin/bluepulse.bash
RestartSec=2
Restart=on-failure

[Install]
WantedBy=pulseaudio.service

Each user that wishes to use this service can then enable it to start at login with:

systemctl --user enable bluepulse.service

Systemd will now start the bluepulse service for that user whenever pulseaudio is started, and stop it when pulseaudio stops.