The officially official Devuan Forum!

You are not logged in.

#1 2026-05-30 18:19:11

igorzwx
Member
Registered: 2024-05-06
Posts: 511  

Firefox: Dialectics of Antagonistic Security Bugs

Firefox: Dialectics of Antagonistic Security Bugs

Firefox with unlocked preferences is an attractive target for attacks. Unprotected security preferences can be exploited as backdoors. To lock down these backdoors, you must fix antagonistic bugs with dialectical patches.

Don't panic! Debian's Firefox ESR leverages a system-wide preference lockdown that allows administrators to enforce security policies. Ordinary users, of course, may dwell in ignorance and fear. Devuan Wiki might be difficult to consume for TikTok users.

NOTE: This guide is a work in progress. Please do not post in this topic. Since the community has complained about "spoon-feeding", this guide is intended for experienced Linux users. If you have any questions, please consult the Devuan Wiki, or other knowledge repositories of the sort. If you have problems with dialectical patches, study Hegel or Monty Python.

Firefox Developer Edition
The browser made for developers
All the latest developer tools in beta in addition to features like the Multi-line Console Editor and WebSocket Inspector.
A separate profile and path so you can easily run it alongside Release or Beta Firefox.
Preferences tailored for web developers: Browser and remote debugging are enabled by default, as are the dark theme and developer toolbar button.
_https://www.firefox.com/en-US/channel/desktop/developer

It means:

about:config 
devtools.chrome.enabled = true 
devtools.theme = dark 
browser.toolbars.bookmarks.visibility = always 

Why not close backdoors with a key?

// Disable remote debugging
pref("devtools.debugger.remote-enabled", false, locked);
// Restrict connections to localhost only (default: true)
pref("devtools.debugger.force-local", true, locked);
// Disable browser chrome debugging (debugging Firefox itself). 
pref("devtools.chrome.enabled", false, locked);
// Block access to all developer tools functionality
pref("devtools.policy.disabled", true, locked); 

Security Implications of Unlocked Preferences:
1. Malicious extensions could modify security-critical preferences (like cookie behavior, remote debugging, or TLS settings)
2. Compromised user accounts could weaken protections through about:config
4. Malware could disable security features to facilitate further attacks
5. Social engineering could trick users into changing critical settings

Official Documentation: Building Firefox On Linux

_https://firefox-source-docs.mozilla.org/setup/linux_build.html
_https://firefox-source-docs.mozilla.org/build/buildsystem/mozconfigs.html

PATCHES:

$ cat PATCHES/0001-Set-MOZ_APP_UA_NAME-to-Firefox-for-clean-UA-strings.patch
From 8bd5afd0265356ddc323cffd8397208b5750227a Mon Sep 17 00:00:00 2001
From: Devuan <devuan@devuan.cargo-cult.org>
Date: Fri, 15 May 2026 23:40:28 +0200
Subject: [PATCH 1/3] Set MOZ_APP_UA_NAME to Firefox for clean UA strings

---
 browser/moz.configure | 1 +
 1 file changed, 1 insertion(+)

diff --git a/browser/moz.configure b/browser/moz.configure
index 3ea3d88b9360..0a95edc31354 100644
--- a/browser/moz.configure
+++ b/browser/moz.configure
@@ -16,6 +16,7 @@ imply_option("MOZ_APP_ID", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}")
 # Include the DevTools client, not just the server (which is the default)
 imply_option("MOZ_DEVTOOLS", "all")
 imply_option("BROWSER_CHROME_URL", "chrome://browser/content/browser.xhtml")
+imply_option("MOZ_APP_UA_NAME", "Firefox")

 with only_when(target_has_linux_kernel & compile_environment):
-- 
2.39.5
$ cat PATCHES/0002-Set-MOZ_APP_PROFILE-to-Firefox-for-clean-APP_PROFILE.patch
From 252efd229f1d9dac21e053d05a5ef9ced1ca14f3 Mon Sep 17 00:00:00 2001
From: Devuan <devuan@devuan.cargo-cult.org>
Date: Sat, 16 May 2026 18:02:08 +0200
Subject: [PATCH 2/3] Set MOZ_APP_PROFILE to Firefox for clean APP_PROFILE
 strings

---
 browser/moz.configure | 1 +
 1 file changed, 1 insertion(+)

diff --git a/browser/moz.configure b/browser/moz.configure
index 0a95edc31354..a4a4945ddbdd 100644
--- a/browser/moz.configure
+++ b/browser/moz.configure
@@ -17,6 +17,7 @@ imply_option("MOZ_APP_ID", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}")
 imply_option("MOZ_DEVTOOLS", "all")
 imply_option("BROWSER_CHROME_URL", "chrome://browser/content/browser.xhtml")
 imply_option("MOZ_APP_UA_NAME", "Firefox")
+imply_option("MOZ_APP_PROFILE", "firefox-dev")

 with only_when(target_has_linux_kernel & compile_environment):
-- 
2.39.5
$ cat PATCHES/0003-Fix-system-preferences-for-custom-firefox-dev-builds.patch
From 9f4226e27c3b85506873bea8e30645fb066709ae Mon Sep 17 00:00:00 2001
From: Devuan <devuan@devuan.cargo-cult.org>
Date: Thu, 28 May 2026 23:41:26 +0200
Subject: [PATCH 3/3] Fix system preferences for custom firefox-dev builds
 (security-critical)

This fixes two upstream bugs that prevent the system preferences security
feature from working, which is designed to lock down potential backdoors
by allowing administrators to enforce system-wide preference settings.

Bug 1: Configure option contradiction in toolkit/moz.configure
- Original code defines --disable-system-preferences but requires
  --enable-system-preferences in the when condition, creating a
  semantic contradiction that prevents the feature from being enabled
- Fixed with inline lambda pattern: when=depends("--disable-system-preferences")(lambda x: not x)

Bug 2: Dynamic app name resolution in xpcom/io/SpecialSystemDirectory.cpp
- Runtime code dynamically constructs /etc/{appname}/defaults/pref/ path
- This breaks system-wide configuration for custom builds with non-standard
  app names like firefox-dev
- Fixed by hardcoding "firefox-dev" to match the existing directory structure

REQUIREMENT: Users must add this line to their .mozconfig:
  ac_add_options --disable-system-preferences

This is a dialectical workaround: the --disable option actually enables
the feature due to the inverted lambda logic. Without this in .mozconfig,
the configure system will not set MOZ_SYSTEM_PREFERENCES.

Security Impact: System preferences load LAST, overriding application defaults.
This allows administrators to lock down preferences that could be exploited
as backdoors (telemetry, proxy settings, extensions, etc.). The upstream bugs
prevent this security mechanism from functioning.
---
 toolkit/moz.configure               |  4 ++--
 xpcom/io/SpecialSystemDirectory.cpp | 31 ++++++++++++++++-------------
 2 files changed, 19 insertions(+), 16 deletions(-)

diff --git a/toolkit/moz.configure b/toolkit/moz.configure
index 2412f33b4ef5..cd230f461282 100644
--- a/toolkit/moz.configure
+++ b/toolkit/moz.configure
@@ -4232,8 +4232,8 @@ option(
     help="Disable reading preferences from /etc/firefox",
 )
 
-set_config("MOZ_SYSTEM_PREFERENCES", True, when="--enable-system-preferences")
-set_define("MOZ_SYSTEM_PREFERENCES", True, when="--enable-system-preferences")
+set_config("MOZ_SYSTEM_PREFERENCES", True, when=depends("--disable-system-preferences")(lambda x: not x))
+set_define("MOZ_SYSTEM_PREFERENCES", True, when=depends("--disable-system-preferences")(lambda x: not x))
 
 # Allow disabling the creation a legacy profile
 # ==============================================================
diff --git a/xpcom/io/SpecialSystemDirectory.cpp b/xpcom/io/SpecialSystemDirectory.cpp
index 5e80ca881c27..3d1cdf7b3fc1 100644
--- a/xpcom/io/SpecialSystemDirectory.cpp
+++ b/xpcom/io/SpecialSystemDirectory.cpp
@@ -155,20 +155,22 @@ static nsresult GetUnixHomeDir(nsIFile** aFile) {
 #  endif
 }
 
-static nsresult GetUnixSystemConfigDir(nsIFile** aFile) {
-#  if defined(ANDROID)
-  return NS_ERROR_FAILURE;
-#  else
-  nsAutoCString appName;
-  if (nsCOMPtr<nsIXULAppInfo> appInfo =
-          do_GetService("@mozilla.org/xre/app-info;1")) {
-    MOZ_TRY(appInfo->GetName(appName));
-  } else {
-    appName.AssignLiteral(MOZ_APP_BASENAME);
-  }
-
-  ToLowerCase(appName);
-
+static nsresult GetUnixSystemConfigDir(nsIFile** aFile) {  
+#  if defined(ANDROID)  
+  return NS_ERROR_FAILURE;  
+#  else  
+  // DIALECTICAL FIX: Hardcode firefox-dev for custom build  
+  nsAutoCString appName("firefox-dev");  
+    
+  // Original dynamic code (commented out):  
+  // if (nsCOMPtr<nsIXULAppInfo> appInfo =  
+  //         do_GetService("@mozilla.org/xre/app-info;1")) {  
+  //   MOZ_TRY(appInfo->GetName(appName));  
+  // } else {  
+  //   appName.AssignLiteral(MOZ_APP_BASENAME);  
+  // }  
+  // ToLowerCase(appName);  
+  
   nsDependentCString sysConfigDir;
   if (PR_GetEnv("XPCSHELL_TEST_PROFILE_DIR")) {
     const char* mozSystemConfigDir = PR_GetEnv("MOZ_SYSTEM_CONFIG_DIR");
@@ -181,6 +183,7 @@ static nsresult GetUnixSystemConfigDir(nsIFile** aFile) {
     sysConfigDir.Assign(nsLiteralCString("/app/etc"));
   }
 #    endif
+
   if (sysConfigDir.IsEmpty()) {
     sysConfigDir.Assign(nsLiteralCString("/etc"));
   }
-- 
2.39.5
$ cat PATCHES/0004-ALSA-backend-for-Firefox-Fix-device-enumeration-and-.patch
From 3af4931724f64c30ad3a4cf9175016ca9844ca84 Mon Sep 17 00:00:00 2001
From: Devuan  <devuan@devuan.cargo-cult.org>
Date: Sat, 13 Jun 2026 19:58:40 +0200
Subject: [PATCH 4/4] ALSA backend for Firefox: Fix device enumeration and max 
 channel count

- Replace placeholder device enumeration with proper ALSA device
  discovery using snd_card_next() and snd_ctl_pcm_next_device() to
  report actual audio devices with their real capabilities instead of
  a single fictional default device.

- Cap max channel count at 64 to sanitize unrealistic values returned
  by snd_pcm_hw_params_get_channels_max() which can report placeholder
  values like 10000 from some drivers.

These fixes ensure Firefox and web applications receive accurate device
information instead of incorrect placeholder values.
---
 media/libcubeb/src/cubeb_alsa.c | 160 +++++++++++++++++++++++---------
 1 file changed, 114 insertions(+), 46 deletions(-)

diff --git a/media/libcubeb/src/cubeb_alsa.c b/media/libcubeb/src/cubeb_alsa.c
index be9faa490cbd..b76ec4f74b61 100644
--- a/media/libcubeb/src/cubeb_alsa.c
+++ b/media/libcubeb/src/cubeb_alsa.c
@@ -1223,6 +1223,11 @@ alsa_get_max_channel_count(cubeb * ctx, uint32_t * max_channels)
     return CUBEB_ERROR;
   }
 
+  /* Cap at reasonable maximum to filter driver placeholder values */  
+  if (*max_channels > 64) {  
+    *max_channels = 64;  
+  }  
+
   alsa_stream_destroy(stm);
 
   return CUBEB_OK;
@@ -1412,61 +1417,124 @@ static int
 alsa_enumerate_devices(cubeb * context, cubeb_device_type type,
                        cubeb_device_collection * collection)
 {
-  cubeb_device_info * device = NULL;
+  cubeb_device_info * device;
+  snd_pcm_info_t * pcminfo;
+  snd_ctl_t * ctl;
+  snd_ctl_card_info_t * cardinfo;
+  int card = -1;
+  char card_name[32];
+  int err;
+  int dev;
+  snd_pcm_stream_t stream;
+
+  snd_pcm_info_alloca(&pcminfo);
+  snd_ctl_card_info_alloca(&cardinfo);
+
+  collection->count = 0;
+  collection->device = NULL;
+
+  if (snd_card_next(&card) < 0 || card < 0)
+    return CUBEB_OK;
 
-  if (!context)
-    return CUBEB_ERROR;
+  while (card >= 0) {
+    sprintf(card_name, "hw:%d", card);
+    err = snd_ctl_open(&ctl, card_name, 0);
+    if (err < 0) {
+      snd_card_next(&card);
+      continue;
+    }
 
-  uint32_t rate, max_channels;
-  int r;
+    err = snd_ctl_card_info(ctl, cardinfo);
+    if (err < 0) {
+      snd_ctl_close(ctl);
+      snd_card_next(&card);
+      continue;
+    }
 
-  r = alsa_get_preferred_sample_rate(context, &rate);
-  if (r != CUBEB_OK) {
-    return CUBEB_ERROR;
-  }
+    dev = -1;
+    while (1) {
+      if (snd_ctl_pcm_next_device(ctl, &dev) < 0)
+        break;
+      if (dev < 0)
+        break;
+
+      for (stream = 0; stream < 2; stream++) {
+        if ((type & CUBEB_DEVICE_TYPE_OUTPUT) && stream == SND_PCM_STREAM_CAPTURE)
+          continue;
+        if ((type & CUBEB_DEVICE_TYPE_INPUT) && stream == SND_PCM_STREAM_PLAYBACK)
+          continue;
+
+        snd_pcm_info_set_device(pcminfo, dev);
+        snd_pcm_info_set_subdevice(pcminfo, 0);
+        snd_pcm_info_set_stream(pcminfo, stream);
+        err = snd_ctl_pcm_info(ctl, pcminfo);
+        if (err < 0)
+          continue;
+
+        device = (cubeb_device_info *)calloc(1, sizeof(cubeb_device_info));
+        if (!device) {
+          snd_ctl_close(ctl);
+          return CUBEB_ERROR;
+        }
 
-  r = alsa_get_max_channel_count(context, &max_channels);
-  if (r != CUBEB_OK) {
-    return CUBEB_ERROR;
+        device->device_id = strdup(snd_pcm_info_get_name(pcminfo));
+        device->friendly_name = strdup(snd_pcm_info_get_name(pcminfo));
+        device->group_id = strdup(snd_ctl_card_info_get_id(cardinfo));
+        device->vendor_name = strdup(snd_ctl_card_info_get_name(cardinfo));
+
+        device->type = (stream == SND_PCM_STREAM_PLAYBACK) ? 
+                       CUBEB_DEVICE_TYPE_OUTPUT : CUBEB_DEVICE_TYPE_INPUT;
+        device->devid = (void *)(intptr_t)(card << 16 | dev);
+        device->state = CUBEB_DEVICE_STATE_ENABLED;
+        device->preferred = (dev == 0);
+        
+        device->max_channels = 8;  
+        
+        device->min_rate = 8000;   /* Conservative minimum */ 
+        device->max_rate = 192000; /* Conservative maximum */
+        device->default_format = (cubeb_device_fmt)CUBEB_SAMPLE_FLOAT32NE;
+        device->latency_lo = 0;
+        device->latency_hi = 0;
+
+        collection->count++;
+        collection->device = (cubeb_device_info *)realloc(collection->device,
+                                                         collection->count * sizeof(cubeb_device_info));
+        if (!collection->device) {
+          free((void *)device->device_id);  
+          free((void *)device->friendly_name);  
+          free((void *)device->group_id);  
+          free((void *)device->vendor_name);
+          free(device);
+          snd_ctl_close(ctl);
+          return CUBEB_ERROR;
+        }
+        collection->device[collection->count - 1] = *device;
+        free(device);
+      }
+    }
+    snd_ctl_close(ctl);
+    snd_card_next(&card);
   }
 
-  char const * a_name = "default";
-  device = (cubeb_device_info *)calloc(1, sizeof(cubeb_device_info));
-  assert(device);
-  if (!device)
-    return CUBEB_ERROR;
-
-  device->device_id = a_name;
-  device->devid = (cubeb_devid)device->device_id;
-  device->friendly_name = a_name;
-  device->group_id = a_name;
-  device->vendor_name = a_name;
-  device->type = type;
-  device->state = CUBEB_DEVICE_STATE_ENABLED;
-  device->preferred = CUBEB_DEVICE_PREF_ALL;
-  device->format = CUBEB_DEVICE_FMT_S16NE;
-  device->default_format = CUBEB_DEVICE_FMT_S16NE;
-  device->max_channels = max_channels;
-  device->min_rate = rate;
-  device->max_rate = rate;
-  device->default_rate = rate;
-  device->latency_lo = 0;
-  device->latency_hi = 0;
-
-  collection->device = device;
-  collection->count = 1;
-
   return CUBEB_OK;
 }
 
-static int
-alsa_device_collection_destroy(cubeb * context,
-                               cubeb_device_collection * collection)
-{
-  assert(collection->count == 1);
-  (void)context;
-  free(collection->device);
-  return CUBEB_OK;
+static int  
+alsa_device_collection_destroy(cubeb * context,  
+                               cubeb_device_collection * collection)  
+{  
+  size_t i;  
+  
+  (void)context;  
+  
+  for (i = 0; i < collection->count; ++i) {  
+    free((void *)collection->device[i].device_id);  
+    free((void *)collection->device[i].friendly_name);  
+    free((void *)collection->device[i].group_id);  
+    free((void *)collection->device[i].vendor_name);  
+  }  
+  free(collection->device);  
+  return CUBEB_OK;  
 }
 
 static struct cubeb_ops const alsa_ops = {
-- 
2.39.5
# Project tree:
#   BUILD/
#   ├── build_dir_ALSA-dev/     # created with ./mach build 
#   ├── debdir_ALSA-dev/        # created with ./mach install
#   ├── DEB_templates/          # 
#   │   └── make_deb.sh         # Bash script for Firefox packaging
#   ├── firefox/                # Firefox source code
#   └── PATCHES
#       ├── 0001-Set-MOZ_APP_UA_NAME-to-Firefox-for-clean-UA-strings.patch
#       ├── 0002-Set-MOZ_APP_PROFILE-to-Firefox-for-clean-APP_PROFILE.patch
#       ├── 0003-Fix-system-preferences-for-custom-firefox-dev-builds.patch 
#       └── 0004-ALSA-backend-for-Firefox-Fix-device-enumeration-and-.patch

Create firefox/.mozconfig with a text editor

nano firefox/.mozconfig 
$ cat firefox/.mozconfig
# The default mozconfig is located here: sourcedir/browser/config/mozconfig
. $topsrcdir/browser/config/mozconfig  
mk_add_options MOZ_MAKE_FLAGS="-j$(expr $(nproc) + 2)" 
mk_add_options MOZ_OBJDIR="$(dirname $topsrcdir)"/build_dir_ALSA-dev  
mk_add_options MOZ_APP_DISPLAYNAME="Firefox Developer Edition"  
mk_add_options MOZ_SIMPLE_PACKAGE_NAME=firefox-dev  
ac_add_options --with-app-basename="Firefox Developer Edition" 
ac_add_options --with-app-name=firefox-dev  
ac_add_options --prefix=/usr  
ac_add_options --without-sysroot  
ac_add_options --enable-audio-backends=alsa
mk_add_options MOZ_DEV_EDITION=1
mk_add_options MOZ_APP_REMOTINGNAME=firefox-dev
ac_add_options --with-branding=browser/branding/aurora   #  Firefox Developer Edition
ac_add_options --enable-update-channel=aurora
ac_add_options --disable-crashreporter   # Optional
ac_add_options --disable-system-preferences  # dialectical workaround to enable system preferences
export LDFLAGS="-Wl,--no-keep-memory" 

Update the sorce code:

cd firefox && git pull 

Apply pathes:

$ ls -1 ../PATCHES
0001-Set-MOZ_APP_UA_NAME-to-Firefox-for-clean-UA-strings.patch
0002-Set-MOZ_APP_PROFILE-to-Firefox-for-clean-APP_PROFILE.patch
0003-Fix-system-preferences-for-custom-firefox-dev-builds.patch
0004-ALSA-backend-for-Firefox-Fix-device-enumeration-and-.patch
patch -Np1 -i ../PATCHES/0001*
patch -Np1 -i ../PATCHES/0002*
patch -Np1 -i ../PATCHES/0003* 
patch -Np1 -i ../PATCHES/0004*

Build firefox-dev

./mach clobber
./mach configure
$ grep "MOZ_SYSTEM_PREFERENCES" ../build_dir_ALSA-dev/config.status.json
    "MOZ_SYSTEM_PREFERENCES": "1",
    "MOZ_SYSTEM_PREFERENCES": "1", 
./mach build -v --priority normal 
$ grep "MOZ_SYSTEM_PREFERENCES" ../build_dir_ALSA-dev/mozilla-config.h
#define MOZ_SYSTEM_PREFERENCES 1 

Install to debdir

DESTDIR="$(dirname $(pwd))"/debdir_ALSA-dev ./mach install 
$ tree -L 3 ../debdir_ALSA-dev
../debdir_ALSA-dev
└── usr
    ├── bin
    │   └── firefox-dev -> /usr/lib/firefox-dev/firefox-dev
    └── lib
        └── firefox-dev 
$ ../debdir_ALSA-dev/usr/lib/firefox-dev/firefox-dev
Mozilla Firefox Developer Edition 153.0a1 

Packaging

sudo apt install fakeroot
mkdir "$(dirname $(pwd))"/DEB_templates && cd "$(dirname $(pwd))"/DEB_templates 

Create a script for Firefox packaging with a text editor

nano make_deb.sh

and make it executable.

$ cat make_deb.sh
#!/bin/bash
#
# Firefox Developer Edition Debian Package Builder
# ================================================
#
# This script creates a Debian package for Firefox Developer Edition 
# with security-hardened configuration. 
#
# NOTE: Alternatively, one may try the official Mozilla ./mach repackage deb tool, 
#       though it might be an exercise in masochism.
#
# Usage: ./make_deb.sh
# Location: Run from DEB_templates directory
#
# Project structure:
#   BUILD/
#   ├── build_dir_ALSA-dev/     # Compiled Firefox binaries created with ./mach build 
#   ├── debdir_ALSA-dev/        # Package staging directory created with ./mach install
#   ├── DEB_templates/          # This directory
#   │   └── make_deb.sh         # This script
#   └── firefox/                # Firefox source tree
#
# Output: firefox-dev-ed_<version>_<arch>.deb
#
# ==============================================================================

# Bash Strict Mode
set -euo pipefail

# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
DEB_ROOT="$(dirname "$(pwd)")"/debdir_ALSA-dev
SHARE_DIR="$DEB_ROOT/usr/share"
ETC_DIR="$DEB_ROOT/etc"
LIB_DIR="$DEB_ROOT/usr/lib"
PACKAGE_NAME="firefox-dev"
DEB_PACKAGE_NAME="firefox-dev-ed"
VERSION="153.0a1-1"
ARCH="amd64"

echo "Creating Debian package for $PACKAGE_NAME $VERSION..."

# -----------------------------------------------------------------------------
# 1. Create directory structure (FHS compliant)
# -----------------------------------------------------------------------------
install -dm755 "$SHARE_DIR/$PACKAGE_NAME"/{browser/{chrome/icons/default,defaults/preferences},distribution/searchplugins/common}
install -dm755 "$SHARE_DIR/applications"
install -dm755 "$SHARE_DIR/icons/hicolor"/{16x16,32x32,48x48,64x64,128x128,symbolic}/apps
install -dm755 "$SHARE_DIR/doc/$PACKAGE_NAME"
install -dm755 "$SHARE_DIR/lintian/overrides"
install -dm755 "$SHARE_DIR/man/man1"
install -dm755 "$SHARE_DIR/mozilla/extensions"
install -dm755 "$ETC_DIR/$PACKAGE_NAME"/defaults/pref
install -dm755 "$DEB_ROOT/DEBIAN"

# -----------------------------------------------------------------------------
# 2. Create system-wide configuration files
# -----------------------------------------------------------------------------
# These files contain security-hardened Firefox preferences.
# They are placed in /etc/firefox-dev/ and symlinked to the defaults/pref directory.
# This allows system administrators to easily modify defaults.

# Primary configuration file with security preferences
install -m644 <(cat << 'EOF'
// Debian system-wide preferences for Firefox Developer Edition
// ============================================================
//
// This file contains security-hardened default settings for Firefox.
// System administrators can modify these values to change defaults.
//
// Syntax:
//   pref("preference.name", value);           // Default (user can override)
//   pref("preference.name", value, locked);   // Locked (user cannot override)
//
//   String values must be enclosed in double quotes.
//
// Security Configuration:
// ------------------------

// Extension updates
pref("extensions.update.enabled", true);

// Browser behavior
pref("browser.shell.checkDefaultBrowser", false);

// Media settings (disable GMP OpenH264 for privacy)
pref("media.gmp-gmpopenh264.enabled", false);

// Enhanced privacy: disable enhanced new tab page
pref("browser.newtabpage.enhanced", false, locked);

// Telemetry and data reporting (DISABLED for privacy)
pref("datareporting.healthreport.uploadEnabled", false, locked);

// URL bar: disable search suggestions for privacy
pref("browser.urlbar.suggest.searches", false, locked);

// Telemetry (DISABLED for privacy)
pref("toolkit.telemetry.enabled", false, locked);

// Media configuration for better sound quality
pref("media.webm.enabled", false, locked);
pref("media.resampling.enabled", false, locked);
pref("media.cubeb_latency_playback_ms", 160, locked);

// Region and localization (force US/English to prevent fingerprinting)
pref("browser.region.network.url", "", locked);
pref("browser.region.update.enabled", false, locked);
pref("browser.region.network.scan", false, locked);
pref("privacy.spoof_english", 2, locked);
pref("intl.accept_languages", "en-US, en, en-GB", locked);
pref("browser.search.region", "US", locked);
pref("browser.search.geoip.url", "", locked);
pref("distribution.searchplugins.defaultLocale", "en-US", locked);
EOF
) "$ETC_DIR/$PACKAGE_NAME/defaults/pref/firefox-dev.cfg1.js"

# -----------------------------------------------------------------------------
# 4. Create desktop entry (freedesktop.org compliant)
# -----------------------------------------------------------------------------
install -m644 <(cat << 'EOF'
[Desktop Entry]
Name=Firefox Developer Edition
Comment=Web Browser
Exec=/usr/lib/firefox-dev/firefox-dev %u
Icon=firefox-dev
Terminal=false
Type=Application
Categories=Network;WebBrowser;
MimeType=text/html;text/xml;application/xhtml+xml;application/vnd.mozilla.xul+xml;text/mml;x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;
StartupNotify=true
EOF
) "$SHARE_DIR/applications/$PACKAGE_NAME.desktop"

# -----------------------------------------------------------------------------
# 5. Create copyright file (Debian Policy compliant)
# -----------------------------------------------------------------------------
install -m644 <(cat << 'EOF'
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Firefox Developer Edition
Source: https://github.com/mozilla/firefox

License: MPL-2.0
 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
EOF
) "$SHARE_DIR/doc/$PACKAGE_NAME/copyright"

# -----------------------------------------------------------------------------
# 6. Create lintian override (suppress expected warnings)
# -----------------------------------------------------------------------------
install -m644 <(echo "$PACKAGE_NAME: binary-without-manpage") \
    "$SHARE_DIR/lintian/overrides/$PACKAGE_NAME"

# -----------------------------------------------------------------------------
# 7. Create man page
# -----------------------------------------------------------------------------
install -m644 <(cat << 'EOF'
.TH FIREFOX-DEV 1 "User Commands"
.SH NAME
firefox-dev \- Mozilla Firefox Developer Edition
.SH DESCRIPTION
Firefox Developer Edition with custom ALSA support.
This build uses ALSA directly for audio output instead of PulseAudio.
.SH FILES
.I /etc/firefox-dev/firefox-dev.cfg*.js
System-wide preference files.
.SH SEE ALSO
Firefox documentation: https://developer.mozilla.org/
EOF
) "$SHARE_DIR/man/man1/$PACKAGE_NAME.1"
gzip -9f "$SHARE_DIR/man/man1/$PACKAGE_NAME.1"

# -----------------------------------------------------------------------------
# 8. Copy icons from Firefox build directory
# -----------------------------------------------------------------------------
ICON_SOURCE_DIR="$LIB_DIR/$PACKAGE_NAME/browser/chrome/icons/default"
if [ -d "$ICON_SOURCE_DIR" ]; then
    for size in 16 32 48 64 128; do
        if [ -f "$ICON_SOURCE_DIR/default${size}.png" ]; then
            install -m644 "$ICON_SOURCE_DIR/default${size}.png" \
                "$SHARE_DIR/icons/hicolor/${size}x${size}/apps/$PACKAGE_NAME.png"
        fi
    done
fi

# -----------------------------------------------------------------------------
# 9. Calculate dependencies and Installed-Size
# -----------------------------------------------------------------------------
# This section uses dpkg-shlibdeps to automatically calculate library dependencies.
# A temporary debian directory is created for dependency calculation.

# Create control file template for dpkg-shlibdeps
mkdir -p debian
cat > debian/control << EOF
Source: ${DEB_PACKAGE_NAME}
Package: ${DEB_PACKAGE_NAME}
Depends: \${shlibs:Depends}
EOF

# Calculate dependencies using dpkg-shlibdeps
dpkg-shlibdeps -x"$PACKAGE_NAME" -l"$DEB_ROOT"/usr/lib \
    --ignore-missing-info -e $(find "$DEB_ROOT" -type f 2>/dev/null) 2>/dev/null

# Extract dependencies or use fallback
if [ -f debian/substvars ] && grep -q "shlibs:Depends" debian/substvars; then
    DEPS=$(grep "shlibs:Depends" debian/substvars | sed 's/shlibs:Depends=//')
else
    DEPS="libc6"
fi

# Add changelog (required by dpkg-gencontrol)
cat > debian/changelog << EOF
${DEB_PACKAGE_NAME} (${VERSION}) unstable; urgency=medium
  * Custom build with security enhancements and ALSA support
 -- Devuan Packaging <devuan@devuan.org>  $(date -R)
EOF

# Add misc dependencies (required by dpkg-gencontrol)
echo "misc:Depends=" >> debian/substvars
echo "misc:Pre-Depends=" >> debian/substvars

# Create control file template for dpkg-gencontrol
cat > debian/control << EOF
Source: ${DEB_PACKAGE_NAME}

Package: ${DEB_PACKAGE_NAME}
Architecture: ${ARCH}
EOF

# Run dpkg-gencontrol to calculate Installed-Size
dpkg-gencontrol -p${DEB_PACKAGE_NAME} \
    -ldebian/changelog \
    -Tdebian/substvars \
    -P"$DEB_ROOT" \
    2>/dev/null

# Extract Installed-Size
SIZE=$(sed -n 's/Installed-Size: //p' "$DEB_ROOT/DEBIAN/control")

# Clean up temporary directory
rm -rf debian

# -----------------------------------------------------------------------------
# 10. Create DEBIAN/control file with all fields in correct Debian order
# -----------------------------------------------------------------------------

cat > "$DEB_ROOT/DEBIAN/control" << EOF
Package: ${DEB_PACKAGE_NAME}
Version: ${VERSION}
Priority: optional
Section: web
Architecture: ${ARCH}
Maintainer: Devuan Packaging <devuan@devuan.org>
Installed-Size: ${SIZE}
Provides: gnome-www-browser, www-browser
Depends: ${DEPS}
Conflicts: firefox-dev
Recommends: libavcodec61 | libavcodec-extra61 | libavcodec60 | libavcodec-extra60 | libavcodec59 | libavcodec-extra59 | libavcodec58 | libavcodec-extra58 | libavcodec57 | libavcodec-extra57 | libavcodec56 | libavcodec-extra56 | libavcodec55 | libavcodec-extra55 | libavcodec54 | libavcodec-extra54 | libavcodec53 | libavcodec-extra53
Suggests: fonts-stix | otf-stix, fonts-lmodern, libgssapi-krb5-2 | libkrb53, libcanberra0
Description: Firefox Developer Edition (ALSA build)
 Firefox Developer Edition is a high-performance browser for web developers,
 featuring Multi-line Console Editor and WebSocket Inspector. It runs
 side-by-side with Release, Beta, or Nightly builds using a separate Profile
 Directory and installation path.
 .
 This custom build includes:
  * Security-hardened default preferences
  * ALSA audio support (no PulseAudio dependency)
  * Pre-configured developer defaults: remote debugging enabled, dark theme,
    and developer toolbar
EOF

# -----------------------------------------------------------------------------
# 11. Generate md5sums for all installed files
# -----------------------------------------------------------------------------
cd "$DEB_ROOT"
install -m644 <(find . -type f -not -path './DEBIAN/*' -printf '%P\0' | \
    xargs -0 md5sum | sort -k 2) DEBIAN/md5sums

# Display package structure
echo "Package structure:"
tree -L 3 .

# Return to script directory
cd "$(dirname "$(pwd)")"/DEB_templates

# -----------------------------------------------------------------------------
# 12. Build the package using dpkg-deb
# -----------------------------------------------------------------------------
echo "Building Debian package..."
fakeroot -- dpkg-deb -b "$DEB_ROOT" "${DEB_PACKAGE_NAME}_${VERSION}_${ARCH}.deb"

echo "Package built successfully: ${DEB_PACKAGE_NAME}_${VERSION}_${ARCH}.deb"

Run make_deb.sh to build Debian package

$ ./make_deb.sh
Creating Debian package for firefox-dev 153.0a1-1...
Package structure:
.
├── DEBIAN
│   ├── control
│   └── md5sums
├── etc
│   └── firefox-dev
│       └── defaults
└── usr
    ├── bin
    │   └── firefox-dev -> /usr/lib/firefox-dev/firefox-dev
    ├── lib
    │   └── firefox-dev
    └── share
        ├── applications
        ├── doc
        ├── firefox-dev
        ├── icons
        ├── lintian
        ├── man
        └── mozilla

17 directories, 3 files
Building Debian package...
dpkg-deb: building package 'firefox-dev-ed' in 'firefox-dev-ed_153.0a1-1_amd64.deb'.
Package built successfully: firefox-dev-ed_153.0a1-1_amd64.deb 
$ ls -1 *deb
firefox-dev-ed_153.0a1-1_amd64.deb

Install

sudo dpkg -i firefox-dev-ed_153.0a1-1_amd64.deb 
$ firefox-dev --version
Mozilla Firefox Developer Edition 153.0a1 

Hacking dependencies

The DEBIAN/control file is not included in DEBIAN/md5sums.
You can edit it freely without regenerating checksums.
To rebuild the package, run:

fakeroot -- dpkg-deb -b ../debdir_ALSA-dev firefox-dev-ed_153.0a1-1_amd64.deb

Repackaging

fakeroot -u -- dpkg-repack firefox-dev-ed
fakeroot -u dpkg-repack --generate <package-name> 

Example of Firefox hardened configuration:

$ cat /etc/firefox-dev/defaults/pref/firefox-dev.cfg5.js
// ============================================================================
// Firefox Security-Hardened Configuration
// ============================================================================
// This file locks all security-critical preferences to prevent 
// modification by users, extensions, or malicious code. 
// Place in /etc/firefox-dev/defaults/pref/
// ============================================================================

// -----------------------------------------------------------------------------
// Sandbox
// -----------------------------------------------------------------------------
// Linux Content Process Sandbox
// Level 6 = default-deny for ioctl (most restrictive)
pref("security.sandbox.content.level", 6, locked);
// Whitelist paths (empty string = no whitelist)
pref("security.sandbox.content.write_path_whitelist", "", locked);
pref("security.sandbox.content.read_path_whitelist", "", locked);
pref("security.sandbox.content.syscall_whitelist", "", locked);

// Socket Process Sandbox
// Level 2 = default-deny for ioctl
pref("security.sandbox.socket.process.level", 2, locked);

// Sandbox Logging (disable for security)
pref("security.sandbox.logging.enabled", false, locked);

// -----------------------------------------------------------------------------
// Remote Debugging and Developer Tools
// -----------------------------------------------------------------------------
// Disable remote debugging
pref("devtools.debugger.remote-enabled", false, locked);
// Port number for the debugging server (default: 6000)
pref("devtools.debugger.remote-port", 6000, locked);
// Restrict connections to localhost only (default: true)
pref("devtools.debugger.force-local", true, locked);
// Disable browser chrome debugging (debugging Firefox itself). Debian's default: false
pref("devtools.chrome.enabled", false, locked);
// Block access to all developer tools functionality
pref("devtools.policy.disabled", true, locked);

// -----------------------------------------------------------------------------
// Cookie and Privacy Settings
// -----------------------------------------------------------------------------
// Strongest cookie privacy setting (reject trackers, partition third-party cookies)
pref("network.cookie.cookieBehavior", 5, locked);
pref("network.cookie.cookieBehavior.pbmode", 5, locked);
// Block-by-default with opt-in partitioning (more restrictive than dFPI)
pref("network.cookie.cookieBehavior.optInPartitioning", true, locked);
pref("network.cookie.cookieBehavior.optInPartitioning.pbmode", true, locked);
// Block third-party cookies from tracking protection list
pref("network.cookie.cookieBehavior.trackerCookieBlocking", true, locked);
// Prevent sync from propagating weaker settings
pref("services.sync.prefs.sync.network.cookie.cookieBehavior", false, locked);

// Global Privacy Control
pref("privacy.globalprivacycontrol.enabled", true, locked);
pref("privacy.globalprivacycontrol.functionality.enabled", true, locked);
pref("privacy.globalprivacycontrol.pbmode.enabled", true, locked);

// Disable First Party Isolation (incompatible with behavior 5)
pref("privacy.firstparty.isolate", false, locked);
pref("privacy.firstparty.isolate.block_post_message", false, locked);
pref("privacy.firstparty.isolate.restrict_opener_access", true, locked);
pref("privacy.firstparty.isolate.use_site", false, locked);

// -----------------------------------------------------------------------------
// TLS/SSL Configuration
// -----------------------------------------------------------------------------
// Minimum TLS version (1=tls1, 2=tls1.1, 3=tls1.2, 4=tls1.3)
pref("security.tls.version.min", 3, locked);
// Maximum TLS version
pref("security.tls.version.max", 4, locked);
// Disable deprecated TLS versions
pref("security.tls.version.enable-deprecated", false, locked);

// TLS Security Features
pref("security.ssl.require_safe_negotiation", true, locked);
pref("security.tls.hello_downgrade_check", true, locked);
pref("security.ssl.enable_ocsp_stapling", true, locked);
pref("security.OCSP.require", true, locked);
pref("security.OCSP.enabled", 1, locked);

// TLS 1.3 Features
pref("security.tls.enable_0rtt_data", false, locked);
pref("security.tls.enable_post_handshake_auth", true, locked);
pref("security.tls.enable_delegated_credentials", true, locked);

// Encrypted Client Hello (ECH)
pref("network.dns.echconfig.enabled", true, locked);
pref("network.dns.http3_echconfig.enabled", true, locked);

// Disable weak cipher suites
pref("security.ssl3.rsa_aes_128_sha", false, locked);
pref("security.ssl3.rsa_aes_256_sha", false, locked);
pref("security.ssl3.rsa_aes_128_gcm_sha256", false, locked);
pref("security.ssl3.rsa_aes_256_gcm_sha384", false, locked);
pref("security.ssl3.deprecated.rsa_des_ede3_sha", false, locked);

// -----------------------------------------------------------------------------
// Content Security
// -----------------------------------------------------------------------------
pref("security.block_fileuri_script_with_wrong_mime", true, locked);
pref("security.mixed_content.block_active_content", true, locked);
pref("security.mixed_content.block_display_content", true, locked);
pref("security.mixed_content.upgrade_display_content", true, locked);
pref("security.insecure_connection_text.enabled", true, locked);
pref("security.insecure_connection_text.pbmode.enabled", true, locked);
pref("security.warn_submit_secure_to_insecure", true, locked);

// HTTPS-Only Mode
//pref("dom.security.https_only_mode", true, locked);
//pref("dom.security.https_only_mode_pbm", true, locked);
//pref("dom.security.https_first", true, locked);
//pref("dom.security.https_first_pbm", true, locked);

// HTTPS-First (less aggressive than HTTPS-Only)
pref("dom.security.https_first", true, locked);
pref("dom.security.https_first_pbm", true, locked);

// -----------------------------------------------------------------------------
// Certificate and PKI Settings
// -----------------------------------------------------------------------------
pref("security.default_personal_cert", "Ask Every Time", locked);
pref("security.pki.certificate_transparency.mode", 1, locked);
pref("security.ssl.errorReporting.enabled", true, locked);
pref("security.enterprise_roots.enabled", true, locked);

// -----------------------------------------------------------------------------
// Safe Browsing
// -----------------------------------------------------------------------------
pref("browser.safebrowsing.malware.enabled", true, locked);
pref("browser.safebrowsing.phishing.enabled", true, locked);
pref("browser.safebrowsing.downloads.enabled", true, locked);
pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", true, locked);
pref("browser.safebrowsing.downloads.remote.block_uncommon", true, locked);

// -----------------------------------------------------------------------------
// WebAuthn
// -----------------------------------------------------------------------------
pref("security.webauthn.always_allow_direct_attestation", false, locked);

// -----------------------------------------------------------------------------
// CSP Reporting
// -----------------------------------------------------------------------------
pref("security.csp.reporting.enabled", true, locked);

// -----------------------------------------------------------------------------
// Extension Security
// -----------------------------------------------------------------------------
//pref("xpinstall.whitelist.required", true, locked);
//pref("xpinstall.enabled", false, locked);
//pref("extensions.update.enabled", false, locked);

// -----------------------------------------------------------------------------
// Telemetry and Data Collection
// -----------------------------------------------------------------------------
pref("datareporting.healthreport.uploadEnabled", false, locked);
pref("toolkit.telemetry.enabled", false, locked);
pref("browser.newtabpage.activity-stream.feeds.telemetry", false, locked);
pref("browser.newtabpage.activity-stream.telemetry", false, locked);

// -----------------------------------------------------------------------------
// Network Security
// -----------------------------------------------------------------------------
pref("network.http.sendRefererHeader", 2, locked);
pref("privacy.resistFingerprinting", true, locked);
pref("privacy.trackingprotection.enabled", true, locked);
pref("privacy.trackingprotection.pbmode.enabled", true, locked);

// -----------------------------------------------------------------------------
// DNS over HTTPS
// -----------------------------------------------------------------------------
// pref("network.trr.mode", 3, locked);

// DoH with fallback (mode 2 instead of 3)
pref("network.trr.mode", 2, locked);

// -----------------------------------------------------------------------------
// Local Network Access
// -----------------------------------------------------------------------------
pref("network.lna.blocking", true, locked);

// -----------------------------------------------------------------------------
// Post-Quantum Cryptography
// -----------------------------------------------------------------------------
pref("security.tls.post_quantum_key_agreement.enabled", true, locked);

Last edited by igorzwx (2026-06-13 19:28:39)

Offline

#2 Today 00:40:42

igorzwx
Member
Registered: 2024-05-06
Posts: 511  

Re: Firefox: Dialectics of Antagonistic Security Bugs

New version of Firefox/Cubeb ALSA backend
Date:   Wed Jul 8 22:22:55 2026 +0200

    ALSA backend: Implement proper device enumeration using snd_device_name_hint()
    
    Replace the minimal placeholder enumeration that returned hardcoded
    values with proper device enumeration using snd_device_name_hint() API.
    This now correctly enumerates both physical hardware devices and virtual
    devices (BlueALSA, rate converters, plugins) with accurate format capabilities,
    channel counts, and rate ranges queried from actual hardware.
$ cat firefox/media/libcubeb/src/cubeb_alsa.c
/*
 * Copyright © 2011 Mozilla Foundation
 *
 * This program is made available under an ISC-style license.  See the
 * accompanying file LICENSE for details.
 */
#undef NDEBUG
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#if defined(__NetBSD__)
#define _NETBSD_SOURCE /* timersub() */
#endif
#define _XOPEN_SOURCE 500
#include "cubeb-internal.h"
#include "cubeb/cubeb.h"
#include "cubeb_tracing.h"
#include <alsa/asoundlib.h>
#include <assert.h>
#include <dlfcn.h>
#include <limits.h>
#include <poll.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>

#ifdef DISABLE_LIBASOUND_DLOPEN
#define WRAP(x) x
#else
#define WRAP(x) (*cubeb_##x)
#define LIBASOUND_API_VISIT(X)                                                 \
  X(snd_config)                                                                \
  X(snd_config_add)                                                            \
  X(snd_config_copy)                                                           \
  X(snd_config_delete)                                                         \
  X(snd_config_get_id)                                                         \
  X(snd_config_get_string)                                                     \
  X(snd_config_imake_integer)                                                  \
  X(snd_config_search)                                                         \
  X(snd_config_search_definition)                                              \
  X(snd_lib_error_set_handler)                                                 \
  X(snd_pcm_avail_update)                                                      \
  X(snd_pcm_close)                                                             \
  X(snd_pcm_delay)                                                             \
  X(snd_pcm_drain)                                                             \
  X(snd_pcm_frames_to_bytes)                                                   \
  X(snd_pcm_get_params)                                                        \
  X(snd_pcm_hw_params_any)                                                     \
  X(snd_pcm_hw_params_get_channels_max)                                        \
  X(snd_pcm_hw_params_get_rate)                                                \
  X(snd_pcm_hw_params_set_rate_near)                                           \
  X(snd_pcm_hw_params_sizeof)                                                  \
  X(snd_pcm_nonblock)                                                          \
  X(snd_pcm_open)                                                              \
  X(snd_pcm_open_lconf)                                                        \
  X(snd_pcm_pause)                                                             \
  X(snd_pcm_poll_descriptors)                                                  \
  X(snd_pcm_poll_descriptors_count)                                            \
  X(snd_pcm_poll_descriptors_revents)                                          \
  X(snd_pcm_readi)                                                             \
  X(snd_pcm_recover)                                                           \
  X(snd_pcm_set_params)                                                        \
  X(snd_pcm_start)                                                             \
  X(snd_pcm_state)                                                             \
  X(snd_pcm_writei)                                                            \
  X(snd_device_name_hint)                                                      \
	X(snd_device_name_get_hint)                                                  \
	X(snd_device_name_free_hint)                                                 \
	X(snd_pcm_hw_params_test_format)                                             \
	X(snd_pcm_hw_params_get_rate_min)                                            \
	X(snd_pcm_hw_params_get_rate_max)                                            \
	X(snd_pcm_hw_params_get_channels_min)                                        \
	X(snd_pcm_hw_params_get_channels_max)

#define MAKE_TYPEDEF(x) static typeof(x) * cubeb_##x;
LIBASOUND_API_VISIT(MAKE_TYPEDEF);
#undef MAKE_TYPEDEF
/* snd_pcm_hw_params_alloca is actually a macro */
#define snd_pcm_hw_params_sizeof cubeb_snd_pcm_hw_params_sizeof
#endif

#define CUBEB_STREAM_MAX 16
#define CUBEB_WATCHDOG_MS 10000

#define CUBEB_ALSA_PCM_NAME "default"

#define ALSA_PA_PLUGIN "ALSA <-> PulseAudio PCM I/O Plugin"

/* ALSA is not thread-safe.  snd_pcm_t instances are individually protected
   by the owning cubeb_stream's mutex.  snd_pcm_t creation and destruction
   is not thread-safe until ALSA 1.0.24 (see alsa-lib.git commit 91c9c8f1),
   so those calls must be wrapped in the following mutex. */
static pthread_mutex_t cubeb_alsa_mutex = PTHREAD_MUTEX_INITIALIZER;
static int cubeb_alsa_error_handler_set = 0;

static struct cubeb_ops const alsa_ops;

struct cubeb {
  struct cubeb_ops const * ops;
  void * libasound;

  pthread_t thread;

  /* Mutex for streams array, must not be held while blocked in poll(2). */
  pthread_mutex_t mutex;

  /* Sparse array of streams managed by this context. */
  cubeb_stream * streams[CUBEB_STREAM_MAX];

  /* fds and nfds are only updated by alsa_run when rebuild is set. */
  struct pollfd * fds;
  nfds_t nfds;
  int rebuild;

  int shutdown;

  /* Control pipe for forcing poll to wake and rebuild fds or recalculate the
   * timeout. */
  int control_fd_read;
  int control_fd_write;

  /* Track number of active streams.  This is limited to CUBEB_STREAM_MAX
     due to resource contraints. */
  unsigned int active_streams;

  /* Local configuration with handle_underrun workaround set for PulseAudio
     ALSA plugin.  Will be NULL if the PA ALSA plugin is not in use or the
     workaround is not required. */
  snd_config_t * local_config;
  int is_pa;
};

enum stream_state { INACTIVE, RUNNING, DRAINING, PROCESSING, ERROR };

struct cubeb_stream {
  /* Note: Must match cubeb_stream layout in cubeb.c. */
  cubeb * context;
  void * user_ptr;
  /**/
  pthread_mutex_t mutex;
  snd_pcm_t * pcm;
  cubeb_data_callback data_callback;
  cubeb_state_callback state_callback;
  snd_pcm_uframes_t stream_position;
  snd_pcm_uframes_t last_position;
  snd_pcm_uframes_t buffer_size;
  cubeb_stream_params params;

  /* Every member after this comment is protected by the owning context's
     mutex rather than the stream's mutex, or is only used on the context's
     run thread. */
  pthread_cond_t cond; /* Signaled when the stream's state is changed. */

  enum stream_state state;

  struct pollfd * saved_fds; /* A copy of the pollfds passed in at init time. */
  struct pollfd *
      fds; /* Pointer to this waitable's pollfds within struct cubeb's fds. */
  nfds_t nfds;

  struct timeval drain_timeout;

  /* XXX: Horrible hack -- if an active stream has been idle for
     CUBEB_WATCHDOG_MS it will be disabled and the error callback will be
     called.  This works around a bug seen with older versions of ALSA and
     PulseAudio where streams would stop requesting new data despite still
     being logically active and playing. */
  struct timeval last_activity;
  float volume;

  char * buffer;
  snd_pcm_uframes_t bufframes;
  snd_pcm_stream_t stream_type;

  struct cubeb_stream * other_stream;
};

static int
any_revents(struct pollfd * fds, nfds_t nfds)
{
  nfds_t i;

  for (i = 0; i < nfds; ++i) {
    if (fds[i].revents) {
      return 1;
    }
  }

  return 0;
}

static int
cmp_timeval(struct timeval * a, struct timeval * b)
{
  if (a->tv_sec == b->tv_sec) {
    if (a->tv_usec == b->tv_usec) {
      return 0;
    }
    return a->tv_usec > b->tv_usec ? 1 : -1;
  }
  return a->tv_sec > b->tv_sec ? 1 : -1;
}

static int
timeval_to_relative_ms(struct timeval * tv)
{
  struct timeval now;
  struct timeval dt;
  long long t;
  int r;

  gettimeofday(&now, NULL);
  r = cmp_timeval(tv, &now);
  if (r >= 0) {
    timersub(tv, &now, &dt);
  } else {
    timersub(&now, tv, &dt);
  }
  t = dt.tv_sec;
  t *= 1000;
  t += (dt.tv_usec + 500) / 1000;

  if (t > INT_MAX) {
    t = INT_MAX;
  } else if (t < INT_MIN) {
    t = INT_MIN;
  }

  return r >= 0 ? t : -t;
}

static int
ms_until(struct timeval * tv)
{
  return timeval_to_relative_ms(tv);
}

static int
ms_since(struct timeval * tv)
{
  return -timeval_to_relative_ms(tv);
}

static void
rebuild(cubeb * ctx)
{
  nfds_t nfds;
  int i;
  nfds_t j;
  cubeb_stream * stm;

  assert(ctx->rebuild);

  /* Always count context's control pipe fd. */
  nfds = 1;
  for (i = 0; i < CUBEB_STREAM_MAX; ++i) {
    stm = ctx->streams[i];
    if (stm) {
      stm->fds = NULL;
      if (stm->state == RUNNING) {
        nfds += stm->nfds;
      }
    }
  }

  free(ctx->fds);
  ctx->fds = calloc(nfds, sizeof(struct pollfd));
  assert(ctx->fds);
  ctx->nfds = nfds;

  /* Include context's control pipe fd. */
  ctx->fds[0].fd = ctx->control_fd_read;
  ctx->fds[0].events = POLLIN | POLLERR;

  for (i = 0, j = 1; i < CUBEB_STREAM_MAX; ++i) {
    stm = ctx->streams[i];
    if (stm && stm->state == RUNNING) {
      memcpy(&ctx->fds[j], stm->saved_fds, stm->nfds * sizeof(struct pollfd));
      stm->fds = &ctx->fds[j];
      j += stm->nfds;
    }
  }

  ctx->rebuild = 0;
}

static void
poll_wake(cubeb * ctx)
{
  if (write(ctx->control_fd_write, "x", 1) < 0) {
    /* ignore write error */
  }
}

static void
set_timeout(struct timeval * timeout, unsigned int ms)
{
  gettimeofday(timeout, NULL);
  timeout->tv_sec += ms / 1000;
  timeout->tv_usec += (ms % 1000) * 1000;
}

static void
stream_buffer_decrement(cubeb_stream * stm, long count)
{
  if (count < 0 || (snd_pcm_uframes_t)count > stm->bufframes) {
    count = stm->bufframes;
  }
  char * bufremains =
      stm->buffer + WRAP(snd_pcm_frames_to_bytes)(stm->pcm, count);
  memmove(stm->buffer, bufremains,
          WRAP(snd_pcm_frames_to_bytes)(stm->pcm, stm->bufframes - count));
  stm->bufframes -= count;
}

static void
alsa_set_stream_state(cubeb_stream * stm, enum stream_state state)
{
  cubeb * ctx;
  int r;

  ctx = stm->context;
  stm->state = state;
  r = pthread_cond_broadcast(&stm->cond);
  assert(r == 0);
  ctx->rebuild = 1;
  poll_wake(ctx);
}

static void
alsa_set_draining(cubeb_stream * stm)
{
  alsa_set_stream_state(stm, DRAINING);
  if (stm->stream_type == SND_PCM_STREAM_PLAYBACK && stm->other_stream &&
      stm->other_stream->state == RUNNING) {
    alsa_set_stream_state(stm->other_stream, DRAINING);
  }
}

static enum stream_state
alsa_process_stream(cubeb_stream * stm, int other_stream_running)
{
  unsigned short revents;
  snd_pcm_sframes_t avail;
  int draining;

  draining = 0;

  pthread_mutex_lock(&stm->mutex);

  /* Call _poll_descriptors_revents() even if we don't use it
     to let underlying plugins clear null events.  Otherwise poll()
     may wake up again and again, producing unnecessary CPU usage. */
  WRAP(snd_pcm_poll_descriptors_revents)
  (stm->pcm, stm->fds, stm->nfds, &revents);

  avail = WRAP(snd_pcm_avail_update)(stm->pcm);

  /* Got null event? Bail and wait for another wakeup. */
  if (avail == 0) {
    pthread_mutex_unlock(&stm->mutex);
    return RUNNING;
  }

  /* This could happen if we were suspended with SIGSTOP/Ctrl+Z for a long time.
   */
  if ((unsigned int)avail > stm->buffer_size) {
    avail = stm->buffer_size;
  }

  /* Capture: Read available frames */
  if (stm->stream_type == SND_PCM_STREAM_CAPTURE && avail > 0) {
    snd_pcm_sframes_t got;

    if (avail + stm->bufframes > stm->buffer_size) {
      /* Buffer overflow. Skip and overwrite with new data. */
      stm->bufframes = 0;
      // TODO: should it be marked as DRAINING?
    }

    got = WRAP(snd_pcm_readi)(stm->pcm, stm->buffer + stm->bufframes, avail);

    if (got < 0) {
      avail = got; // the error handler below will recover us
    } else {
      stm->bufframes += got;
      stm->stream_position += got;

      gettimeofday(&stm->last_activity, NULL);
    }
  }

  /* Capture: Pass read frames to callback function */
  if (stm->stream_type == SND_PCM_STREAM_CAPTURE && stm->bufframes > 0 &&
      (!stm->other_stream ||
       stm->other_stream->bufframes < stm->other_stream->buffer_size)) {
    snd_pcm_sframes_t wrote = stm->bufframes;
    snd_pcm_sframes_t requested;
    struct cubeb_stream * mainstm = stm->other_stream ? stm->other_stream : stm;
    void * other_buffer = stm->other_stream ? stm->other_stream->buffer +
                                                  stm->other_stream->bufframes
                                            : NULL;

    /* Correct write size to the other stream available space */
    if (stm->other_stream &&
        wrote > (snd_pcm_sframes_t)(stm->other_stream->buffer_size -
                                    stm->other_stream->bufframes)) {
      wrote = stm->other_stream->buffer_size - stm->other_stream->bufframes;
    }

    requested = wrote;
    pthread_mutex_unlock(&stm->mutex);
    wrote = stm->data_callback(mainstm, stm->user_ptr, stm->buffer,
                               other_buffer, wrote);
    pthread_mutex_lock(&stm->mutex);

    if (wrote < 0) {
      avail = wrote; // the error handler below will recover us
    } else {
      stream_buffer_decrement(stm, wrote);

      if (stm->other_stream) {
        stm->other_stream->bufframes += wrote;
      }
      if (wrote < requested) {
        if (!stm->other_stream) {
          pthread_mutex_unlock(&stm->mutex);
          return INACTIVE;
        }
        draining = 1;
        set_timeout(&stm->drain_timeout, 0);
      }
    }
  }

  /* Playback: Don't have enough data? Let's ask for more. */
  if (stm->stream_type == SND_PCM_STREAM_PLAYBACK &&
      avail > (snd_pcm_sframes_t)stm->bufframes &&
      (!stm->other_stream ||
       (other_stream_running && stm->other_stream->bufframes > 0))) {
    long got = avail - stm->bufframes;
    void * other_buffer = stm->other_stream ? stm->other_stream->buffer : NULL;
    char * buftail =
        stm->buffer + WRAP(snd_pcm_frames_to_bytes)(stm->pcm, stm->bufframes);
    long requested;

    /* Correct read size to the other stream available frames */
    if (stm->other_stream &&
        got > (snd_pcm_sframes_t)stm->other_stream->bufframes) {
      got = stm->other_stream->bufframes;
    }

    requested = got;
    pthread_mutex_unlock(&stm->mutex);
    got = stm->data_callback(stm, stm->user_ptr, other_buffer, buftail, got);
    pthread_mutex_lock(&stm->mutex);

    if (got < 0) {
      avail = got; // the error handler below will recover us
    } else {
      stm->bufframes += got;

      if (stm->other_stream) {
        stream_buffer_decrement(stm->other_stream, got);
      }
      if (got < requested) {
        draining = 1;
      }
    }
  }

  /* Playback: Still don't have enough data? Add some silence. */
  if (stm->stream_type == SND_PCM_STREAM_PLAYBACK &&
      avail > (snd_pcm_sframes_t)stm->bufframes) {
    long drain_frames = avail - stm->bufframes;
    double drain_time = (double)drain_frames / stm->params.rate;

    char * buftail =
        stm->buffer + WRAP(snd_pcm_frames_to_bytes)(stm->pcm, stm->bufframes);
    memset(buftail, 0, WRAP(snd_pcm_frames_to_bytes)(stm->pcm, drain_frames));
    stm->bufframes = avail;

    /* Mark as draining, unless we're waiting for capture */
    if (!stm->other_stream || draining || stm->other_stream->bufframes > 0) {
      set_timeout(&stm->drain_timeout, drain_time * 1000);

      draining = 1;
    }
  }

  /* Playback: Have enough data and no errors. Let's write it out. */
  if (stm->stream_type == SND_PCM_STREAM_PLAYBACK && avail > 0) {
    snd_pcm_sframes_t wrote;

    if (stm->params.format == CUBEB_SAMPLE_FLOAT32NE) {
      float * b = (float *)stm->buffer;
      for (uint32_t i = 0; i < avail * stm->params.channels; i++) {
        b[i] *= stm->volume;
      }
    } else {
      short * b = (short *)stm->buffer;
      for (uint32_t i = 0; i < avail * stm->params.channels; i++) {
        b[i] *= stm->volume;
      }
    }

    wrote = WRAP(snd_pcm_writei)(stm->pcm, stm->buffer, avail);
    if (wrote < 0) {
      avail = wrote; // the error handler below will recover us
    } else {
      stream_buffer_decrement(stm, wrote);

      stm->stream_position += wrote;
      gettimeofday(&stm->last_activity, NULL);
    }
  }

  /* Got some error? Let's try to recover the stream. */
  if (avail < 0) {
    avail = WRAP(snd_pcm_recover)(stm->pcm, avail, 0);

    /* Capture pcm must be started after initial setup/recover */
    if (avail >= 0 && stm->stream_type == SND_PCM_STREAM_CAPTURE &&
        WRAP(snd_pcm_state)(stm->pcm) == SND_PCM_STATE_PREPARED) {
      avail = WRAP(snd_pcm_start)(stm->pcm);
    }
  }

  /* Failed to recover, this stream must be broken. */
  if (avail < 0) {
    pthread_mutex_unlock(&stm->mutex);
    stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
    return ERROR;
  }

  pthread_mutex_unlock(&stm->mutex);
  return draining ? DRAINING : RUNNING;
}

static int
alsa_run(cubeb * ctx)
{
  int r;
  int timeout;
  int i;
  char dummy;
  cubeb_stream * stm;
  enum stream_state state;

  pthread_mutex_lock(&ctx->mutex);

  if (ctx->rebuild) {
    rebuild(ctx);
  }

  /* Wake up at least once per second for the watchdog. */
  timeout = 1000;
  for (i = 0; i < CUBEB_STREAM_MAX; ++i) {
    stm = ctx->streams[i];
    if (stm && stm->state == DRAINING) {
      r = ms_until(&stm->drain_timeout);
      if (r < 0) {
        r = 0;
      }
      if (timeout > r) {
        timeout = r;
      }
    }
  }

  pthread_mutex_unlock(&ctx->mutex);
  r = poll(ctx->fds, ctx->nfds, timeout);
  pthread_mutex_lock(&ctx->mutex);

  if (r > 0) {
    if (ctx->fds[0].revents & POLLIN) {
      if (read(ctx->control_fd_read, &dummy, 1) < 0) {
        /* ignore read error */
      }

      if (ctx->shutdown) {
        pthread_mutex_unlock(&ctx->mutex);
        return -1;
      }
    }

    for (i = 0; i < CUBEB_STREAM_MAX; ++i) {
      stm = ctx->streams[i];
      /* We can't use snd_pcm_poll_descriptors_revents here because of
         https://github.com/kinetiknz/cubeb/issues/135. */
      if (stm && stm->state == RUNNING && stm->fds &&
          any_revents(stm->fds, stm->nfds)) {
        int other_stream_running =
            !stm->other_stream || stm->other_stream->state == RUNNING;
        alsa_set_stream_state(stm, PROCESSING);
        pthread_mutex_unlock(&ctx->mutex);
        state = alsa_process_stream(stm, other_stream_running);
        pthread_mutex_lock(&ctx->mutex);
        if (state == DRAINING) {
          alsa_set_draining(stm);
        } else if (state == INACTIVE) {
          alsa_set_stream_state(stm, state);
          stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_STOPPED);
        } else {
          alsa_set_stream_state(stm, state);
        }
      }
    }
  } else if (r == 0) {
    for (i = 0; i < CUBEB_STREAM_MAX; ++i) {
      stm = ctx->streams[i];
      if (stm) {
        if (stm->state == DRAINING && ms_since(&stm->drain_timeout) >= 0) {
          alsa_set_stream_state(stm, INACTIVE);
          if (!stm->other_stream ||
              stm->stream_type == SND_PCM_STREAM_PLAYBACK) {
            stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
          }
        } else if (stm->state == RUNNING &&
                   ms_since(&stm->last_activity) > CUBEB_WATCHDOG_MS) {
          alsa_set_stream_state(stm, ERROR);
          stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
        }
      }
    }
  }

  pthread_mutex_unlock(&ctx->mutex);

  return 0;
}

static void *
alsa_run_thread(void * context)
{
  cubeb * ctx = context;
  int r;

  CUBEB_REGISTER_THREAD("cubeb rendering thread");

  do {
    r = alsa_run(ctx);
  } while (r >= 0);

  CUBEB_UNREGISTER_THREAD();

  return NULL;
}

static snd_config_t *
get_slave_pcm_node(snd_config_t * lconf, snd_config_t * root_pcm)
{
  int r;
  snd_config_t * slave_pcm;
  snd_config_t * slave_def;
  snd_config_t * pcm;
  char const * string;
  char node_name[64];

  slave_def = NULL;

  r = WRAP(snd_config_search)(root_pcm, "slave", &slave_pcm);
  if (r < 0) {
    return NULL;
  }

  r = WRAP(snd_config_get_string)(slave_pcm, &string);
  if (r >= 0) {
    r = WRAP(snd_config_search_definition)(lconf, "pcm_slave", string,
                                           &slave_def);
    if (r < 0) {
      return NULL;
    }
  }

  do {
    r = WRAP(snd_config_search)(slave_def ? slave_def : slave_pcm, "pcm", &pcm);
    if (r < 0) {
      break;
    }

    r = WRAP(snd_config_get_string)(slave_def ? slave_def : slave_pcm, &string);
    if (r < 0) {
      break;
    }

    r = snprintf(node_name, sizeof(node_name), "pcm.%s", string);
    if (r < 0 || r > (int)sizeof(node_name)) {
      break;
    }
    r = WRAP(snd_config_search)(lconf, node_name, &pcm);
    if (r < 0) {
      break;
    }

    return pcm;
  } while (0);

  if (slave_def) {
    WRAP(snd_config_delete)(slave_def);
  }

  return NULL;
}

/* Work around PulseAudio ALSA plugin bug where the PA server forces a
   higher than requested latency, but the plugin does not update its (and
   ALSA's) internal state to reflect that, leading to an immediate underrun
   situation.  Inspired by WINE's make_handle_underrun_config.
   Reference: http://mailman.alsa-project.org/pipermail/alsa-devel/2012-July/05
 */
static snd_config_t *
init_local_config_with_workaround(char const * pcm_name)
{
  int r;
  snd_config_t * lconf;
  snd_config_t * pcm_node;
  snd_config_t * node;
  char const * string;
  char node_name[64];

  lconf = NULL;

  if (WRAP(snd_config) == NULL) {
    return NULL;
  }

  r = WRAP(snd_config_copy)(&lconf, WRAP(snd_config));
  if (r < 0) {
    return NULL;
  }

  do {
    r = WRAP(snd_config_search_definition)(lconf, "pcm", pcm_name, &pcm_node);
    if (r < 0) {
      break;
    }

    r = WRAP(snd_config_get_id)(pcm_node, &string);
    if (r < 0) {
      break;
    }

    r = snprintf(node_name, sizeof(node_name), "pcm.%s", string);
    if (r < 0 || r > (int)sizeof(node_name)) {
      break;
    }
    r = WRAP(snd_config_search)(lconf, node_name, &pcm_node);
    if (r < 0) {
      break;
    }

    /* If this PCM has a slave, walk the slave configurations until we reach the
     * bottom. */
    while ((node = get_slave_pcm_node(lconf, pcm_node)) != NULL) {
      pcm_node = node;
    }

    /* Fetch the PCM node's type, and bail out if it's not the PulseAudio
     * plugin. */
    r = WRAP(snd_config_search)(pcm_node, "type", &node);
    if (r < 0) {
      break;
    }

    r = WRAP(snd_config_get_string)(node, &string);
    if (r < 0) {
      break;
    }

    if (strcmp(string, "pulse") != 0) {
      break;
    }

    /* Don't clobber an explicit existing handle_underrun value, set it only
       if it doesn't already exist. */
    r = WRAP(snd_config_search)(pcm_node, "handle_underrun", &node);
    if (r != -ENOENT) {
      break;
    }

    /* Disable pcm_pulse's asynchronous underrun handling. */
    r = WRAP(snd_config_imake_integer)(&node, "handle_underrun", 0);
    if (r < 0) {
      break;
    }

    r = WRAP(snd_config_add)(pcm_node, node);
    if (r < 0) {
      break;
    }

    return lconf;
  } while (0);

  WRAP(snd_config_delete)(lconf);

  return NULL;
}

static int
alsa_locked_pcm_open(snd_pcm_t ** pcm, char const * pcm_name,
                     snd_pcm_stream_t stream, snd_config_t * local_config)
{
  int r;

  pthread_mutex_lock(&cubeb_alsa_mutex);
  if (local_config) {
    r = WRAP(snd_pcm_open_lconf)(pcm, pcm_name, stream, SND_PCM_NONBLOCK,
                                 local_config);
  } else {
    r = WRAP(snd_pcm_open)(pcm, pcm_name, stream, SND_PCM_NONBLOCK);
  }
  pthread_mutex_unlock(&cubeb_alsa_mutex);

  return r;
}

static int
alsa_locked_pcm_close(snd_pcm_t * pcm)
{
  int r;

  pthread_mutex_lock(&cubeb_alsa_mutex);
  r = WRAP(snd_pcm_close)(pcm);
  pthread_mutex_unlock(&cubeb_alsa_mutex);

  return r;
}

static int
alsa_register_stream(cubeb * ctx, cubeb_stream * stm)
{
  int i;

  pthread_mutex_lock(&ctx->mutex);
  for (i = 0; i < CUBEB_STREAM_MAX; ++i) {
    if (!ctx->streams[i]) {
      ctx->streams[i] = stm;
      break;
    }
  }
  pthread_mutex_unlock(&ctx->mutex);

  return i == CUBEB_STREAM_MAX;
}

static void
alsa_unregister_stream(cubeb_stream * stm)
{
  cubeb * ctx;
  int i;

  ctx = stm->context;

  pthread_mutex_lock(&ctx->mutex);
  for (i = 0; i < CUBEB_STREAM_MAX; ++i) {
    if (ctx->streams[i] == stm) {
      ctx->streams[i] = NULL;
      break;
    }
  }
  pthread_mutex_unlock(&ctx->mutex);
}

static void
silent_error_handler(char const * file, int line, char const * function,
                     int err, char const * fmt, ...)
{
  (void)file;
  (void)line;
  (void)function;
  (void)err;
  (void)fmt;
}

/*static*/ int
alsa_init(cubeb ** context, char const * context_name)
{
  (void)context_name;
  void * libasound = NULL;
  cubeb * ctx;
  int r;
  int i;
  int fd[2];
  pthread_attr_t attr;
  snd_pcm_t * dummy;

  assert(context);
  *context = NULL;

#ifndef DISABLE_LIBASOUND_DLOPEN
  libasound = dlopen("libasound.so.2", RTLD_LAZY);
  if (!libasound) {
    libasound = dlopen("libasound.so", RTLD_LAZY);
    if (!libasound) {
      return CUBEB_ERROR;
    }
  }

#define LOAD(x)                                                                \
  {                                                                            \
    cubeb_##x = dlsym(libasound, #x);                                          \
    if (!cubeb_##x) {                                                          \
      dlclose(libasound);                                                      \
      return CUBEB_ERROR;                                                      \
    }                                                                          \
  }

  LIBASOUND_API_VISIT(LOAD);
#undef LOAD
#endif

  pthread_mutex_lock(&cubeb_alsa_mutex);
  if (!cubeb_alsa_error_handler_set) {
    WRAP(snd_lib_error_set_handler)(silent_error_handler);
    cubeb_alsa_error_handler_set = 1;
  }
  pthread_mutex_unlock(&cubeb_alsa_mutex);

  ctx = calloc(1, sizeof(*ctx));
  assert(ctx);

  ctx->ops = &alsa_ops;
  ctx->libasound = libasound;

  r = pthread_mutex_init(&ctx->mutex, NULL);
  assert(r == 0);

  r = pipe(fd);
  assert(r == 0);

  for (i = 0; i < 2; ++i) {
    fcntl(fd[i], F_SETFD, fcntl(fd[i], F_GETFD) | FD_CLOEXEC);
    fcntl(fd[i], F_SETFL, fcntl(fd[i], F_GETFL) | O_NONBLOCK);
  }

  ctx->control_fd_read = fd[0];
  ctx->control_fd_write = fd[1];

  /* Force an early rebuild when alsa_run is first called to ensure fds and
     nfds have been initialized. */
  ctx->rebuild = 1;

  r = pthread_attr_init(&attr);
  assert(r == 0);

  r = pthread_attr_setstacksize(&attr, 256 * 1024);
  assert(r == 0);

  r = pthread_create(&ctx->thread, &attr, alsa_run_thread, ctx);
  assert(r == 0);

  r = pthread_attr_destroy(&attr);
  assert(r == 0);

  /* Open a dummy PCM to force the configuration space to be evaluated so that
     init_local_config_with_workaround can find and modify the default node. */
  r = alsa_locked_pcm_open(&dummy, CUBEB_ALSA_PCM_NAME, SND_PCM_STREAM_PLAYBACK,
                           NULL);
  if (r >= 0) {
    alsa_locked_pcm_close(dummy);
  }
  ctx->is_pa = 0;
  pthread_mutex_lock(&cubeb_alsa_mutex);
  ctx->local_config = init_local_config_with_workaround(CUBEB_ALSA_PCM_NAME);
  pthread_mutex_unlock(&cubeb_alsa_mutex);
  if (ctx->local_config) {
    ctx->is_pa = 1;
    r = alsa_locked_pcm_open(&dummy, CUBEB_ALSA_PCM_NAME,
                             SND_PCM_STREAM_PLAYBACK, ctx->local_config);
    /* If we got a local_config, we found a PA PCM.  If opening a PCM with that
       config fails with EINVAL, the PA PCM is too old for this workaround. */
    if (r == -EINVAL) {
      pthread_mutex_lock(&cubeb_alsa_mutex);
      WRAP(snd_config_delete)(ctx->local_config);
      pthread_mutex_unlock(&cubeb_alsa_mutex);
      ctx->local_config = NULL;
    } else if (r >= 0) {
      alsa_locked_pcm_close(dummy);
    }
  }

  *context = ctx;

  return CUBEB_OK;
}

static char const *
alsa_get_backend_id(cubeb * ctx)
{
  (void)ctx;
  return "alsa";
}

static void
alsa_destroy(cubeb * ctx)
{
  int r;

  assert(ctx);

  pthread_mutex_lock(&ctx->mutex);
  ctx->shutdown = 1;
  poll_wake(ctx);
  pthread_mutex_unlock(&ctx->mutex);

  r = pthread_join(ctx->thread, NULL);
  assert(r == 0);

  close(ctx->control_fd_read);
  close(ctx->control_fd_write);
  pthread_mutex_destroy(&ctx->mutex);
  free(ctx->fds);

  if (ctx->local_config) {
    pthread_mutex_lock(&cubeb_alsa_mutex);
    WRAP(snd_config_delete)(ctx->local_config);
    pthread_mutex_unlock(&cubeb_alsa_mutex);
  }
#ifndef DISABLE_LIBASOUND_DLOPEN
  if (ctx->libasound) {
    dlclose(ctx->libasound);
  }
#endif
  free(ctx);
}

static void
alsa_stream_destroy(cubeb_stream * stm);

static int
alsa_stream_init_single(cubeb * ctx, cubeb_stream ** stream,
                        char const * stream_name, snd_pcm_stream_t stream_type,
                        cubeb_devid deviceid,
                        cubeb_stream_params * stream_params,
                        unsigned int latency_frames,
                        cubeb_data_callback data_callback,
                        cubeb_state_callback state_callback, void * user_ptr)
{
  (void)stream_name;
  cubeb_stream * stm;
  int r;
  snd_pcm_format_t format;
  snd_pcm_uframes_t period_size;
  int latency_us = 0;
  char const * pcm_name =
      deviceid ? (char const *)deviceid : CUBEB_ALSA_PCM_NAME;

  assert(ctx && stream);

  *stream = NULL;

  if (stream_params->prefs & CUBEB_STREAM_PREF_LOOPBACK) {
    return CUBEB_ERROR_NOT_SUPPORTED;
  }

  switch (stream_params->format) {
  case CUBEB_SAMPLE_S16LE:
    format = SND_PCM_FORMAT_S16_LE;
    break;
  case CUBEB_SAMPLE_S16BE:
    format = SND_PCM_FORMAT_S16_BE;
    break;
  case CUBEB_SAMPLE_FLOAT32LE:
    format = SND_PCM_FORMAT_FLOAT_LE;
    break;
  case CUBEB_SAMPLE_FLOAT32BE:
    format = SND_PCM_FORMAT_FLOAT_BE;
    break;
  default:
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  pthread_mutex_lock(&ctx->mutex);
  if (ctx->active_streams >= CUBEB_STREAM_MAX) {
    pthread_mutex_unlock(&ctx->mutex);
    return CUBEB_ERROR;
  }
  ctx->active_streams += 1;
  pthread_mutex_unlock(&ctx->mutex);

  stm = calloc(1, sizeof(*stm));
  assert(stm);

  stm->context = ctx;
  stm->data_callback = data_callback;
  stm->state_callback = state_callback;
  stm->user_ptr = user_ptr;
  stm->params = *stream_params;
  stm->state = INACTIVE;
  stm->volume = 1.0;
  stm->buffer = NULL;
  stm->bufframes = 0;
  stm->stream_type = stream_type;
  stm->other_stream = NULL;

  r = pthread_mutex_init(&stm->mutex, NULL);
  assert(r == 0);

  r = pthread_cond_init(&stm->cond, NULL);
  assert(r == 0);

  r = alsa_locked_pcm_open(&stm->pcm, pcm_name, stm->stream_type,
                           ctx->local_config);
  if (r < 0) {
    alsa_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  r = WRAP(snd_pcm_nonblock)(stm->pcm, 1);
  assert(r == 0);

  latency_us = latency_frames * 1e6 / stm->params.rate;

  /* Ugly hack: the PA ALSA plugin allows buffer configurations that can't
     possibly work.  See https://bugzilla.mozilla.org/show_bug.cgi?id=761274.
     Only resort to this hack if the handle_underrun workaround failed. */
  if (!ctx->local_config && ctx->is_pa) {
    const int min_latency = 5e5;
    latency_us = latency_us < min_latency ? min_latency : latency_us;
  }

  r = WRAP(snd_pcm_set_params)(stm->pcm, format, SND_PCM_ACCESS_RW_INTERLEAVED,
                               stm->params.channels, stm->params.rate, 1,
                               latency_us);
  if (r < 0) {
    alsa_stream_destroy(stm);
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  r = WRAP(snd_pcm_get_params)(stm->pcm, &stm->buffer_size, &period_size);
  assert(r == 0);

  /* Double internal buffer size to have enough space when waiting for the other
   * side of duplex connection */
  stm->buffer_size *= 2;
  stm->buffer =
      calloc(1, WRAP(snd_pcm_frames_to_bytes)(stm->pcm, stm->buffer_size));
  assert(stm->buffer);

  stm->nfds = WRAP(snd_pcm_poll_descriptors_count)(stm->pcm);
  assert(stm->nfds > 0);

  stm->saved_fds = calloc(stm->nfds, sizeof(struct pollfd));
  assert(stm->saved_fds);
  r = WRAP(snd_pcm_poll_descriptors)(stm->pcm, stm->saved_fds, stm->nfds);
  assert((nfds_t)r == stm->nfds);

  if (alsa_register_stream(ctx, stm) != 0) {
    alsa_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  *stream = stm;

  return CUBEB_OK;
}

static int
alsa_stream_init(cubeb * ctx, cubeb_stream ** stream, char const * stream_name,
                 cubeb_devid input_device,
                 cubeb_stream_params * input_stream_params,
                 cubeb_devid output_device,
                 cubeb_stream_params * output_stream_params,
                 unsigned int latency_frames, cubeb_data_callback data_callback,
                 cubeb_state_callback state_callback, void * user_ptr)
{
  int result = CUBEB_OK;
  cubeb_stream *instm = NULL, *outstm = NULL;

  if (result == CUBEB_OK && input_stream_params) {
    result = alsa_stream_init_single(ctx, &instm, stream_name,
                                     SND_PCM_STREAM_CAPTURE, input_device,
                                     input_stream_params, latency_frames,
                                     data_callback, state_callback, user_ptr);
  }

  if (result == CUBEB_OK && output_stream_params) {
    result = alsa_stream_init_single(ctx, &outstm, stream_name,
                                     SND_PCM_STREAM_PLAYBACK, output_device,
                                     output_stream_params, latency_frames,
                                     data_callback, state_callback, user_ptr);
  }

  if (result == CUBEB_OK && input_stream_params && output_stream_params) {
    instm->other_stream = outstm;
    outstm->other_stream = instm;
  }

  if (result != CUBEB_OK && instm) {
    alsa_stream_destroy(instm);
  }

  *stream = outstm ? outstm : instm;

  return result;
}

static void
alsa_stream_destroy(cubeb_stream * stm)
{
  int r;
  cubeb * ctx;

  assert(stm && (stm->state == INACTIVE || stm->state == ERROR ||
                 stm->state == DRAINING));

  ctx = stm->context;

  if (stm->other_stream) {
    stm->other_stream->other_stream = NULL; // to stop infinite recursion
    alsa_stream_destroy(stm->other_stream);
  }

  pthread_mutex_lock(&stm->mutex);
  if (stm->pcm) {
    if (stm->state == DRAINING) {
      WRAP(snd_pcm_drain)(stm->pcm);
    }
    alsa_locked_pcm_close(stm->pcm);
    stm->pcm = NULL;
  }
  free(stm->saved_fds);
  pthread_mutex_unlock(&stm->mutex);
  pthread_mutex_destroy(&stm->mutex);

  r = pthread_cond_destroy(&stm->cond);
  assert(r == 0);

  alsa_unregister_stream(stm);

  pthread_mutex_lock(&ctx->mutex);
  assert(ctx->active_streams >= 1);
  ctx->active_streams -= 1;
  pthread_mutex_unlock(&ctx->mutex);

  free(stm->buffer);

  free(stm);
}

static int
alsa_get_max_channel_count(cubeb * ctx, uint32_t * max_channels)
{
  int r;
  cubeb_stream * stm;
  snd_pcm_hw_params_t * hw_params;
  cubeb_stream_params params;
  params.rate = 44100;
  params.format = CUBEB_SAMPLE_FLOAT32NE;
  params.channels = 2;

  snd_pcm_hw_params_alloca(&hw_params);

  assert(ctx);

  r = alsa_stream_init(ctx, &stm, "", NULL, NULL, NULL, &params, 100, NULL,
                       NULL, NULL);
  if (r != CUBEB_OK) {
    return CUBEB_ERROR;
  }

  assert(stm);

  r = WRAP(snd_pcm_hw_params_any)(stm->pcm, hw_params);
  if (r < 0) {
    return CUBEB_ERROR;
  }

  r = WRAP(snd_pcm_hw_params_get_channels_max)(hw_params, max_channels);
  if (r < 0) {
    return CUBEB_ERROR;
  }

  /* Cap at reasonable maximum to filter driver placeholder values */  
  if (*max_channels > 64) {  
    *max_channels = 64;  
  }  

  alsa_stream_destroy(stm);

  return CUBEB_OK;
}

static int
alsa_get_preferred_sample_rate(cubeb * ctx, uint32_t * rate)
{
  (void)ctx;
  int r, dir;
  snd_pcm_t * pcm;
  snd_pcm_hw_params_t * hw_params;

  snd_pcm_hw_params_alloca(&hw_params);

  /* get a pcm, disabling resampling, so we get a rate the
   * hardware/dmix/pulse/etc. supports. */
  r = WRAP(snd_pcm_open)(&pcm, CUBEB_ALSA_PCM_NAME, SND_PCM_STREAM_PLAYBACK,
                         SND_PCM_NO_AUTO_RESAMPLE);
  if (r < 0) {
    return CUBEB_ERROR;
  }

  r = WRAP(snd_pcm_hw_params_any)(pcm, hw_params);
  if (r < 0) {
    WRAP(snd_pcm_close)(pcm);
    return CUBEB_ERROR;
  }

  r = WRAP(snd_pcm_hw_params_get_rate)(hw_params, rate, &dir);
  if (r >= 0) {
    /* There is a default rate: use it. */
    WRAP(snd_pcm_close)(pcm);
    return CUBEB_OK;
  }

  /* Use a common rate, alsa may adjust it based on hw/etc. capabilities. */
  *rate = 44100;

  r = WRAP(snd_pcm_hw_params_set_rate_near)(pcm, hw_params, rate, NULL);
  if (r < 0) {
    WRAP(snd_pcm_close)(pcm);
    return CUBEB_ERROR;
  }

  WRAP(snd_pcm_close)(pcm);

  return CUBEB_OK;
}

static int
alsa_get_min_latency(cubeb * ctx, cubeb_stream_params params,
                     uint32_t * latency_frames)
{
  (void)ctx;
  /* 40ms is found to be an acceptable minimum, even on a super low-end
   * machine. */
  *latency_frames = 40 * params.rate / 1000;

  return CUBEB_OK;
}

static int
alsa_stream_start(cubeb_stream * stm)
{
  cubeb * ctx;

  assert(stm);
  ctx = stm->context;

  if (stm->stream_type == SND_PCM_STREAM_PLAYBACK && stm->other_stream) {
    int r = alsa_stream_start(stm->other_stream);
    if (r != CUBEB_OK)
      return r;
  }

  pthread_mutex_lock(&stm->mutex);
  /* Capture pcm must be started after initial setup/recover */
  if (stm->stream_type == SND_PCM_STREAM_CAPTURE &&
      WRAP(snd_pcm_state)(stm->pcm) == SND_PCM_STATE_PREPARED) {
    WRAP(snd_pcm_start)(stm->pcm);
  }
  WRAP(snd_pcm_pause)(stm->pcm, 0);
  gettimeofday(&stm->last_activity, NULL);
  pthread_mutex_unlock(&stm->mutex);

  pthread_mutex_lock(&ctx->mutex);
  if (stm->state != INACTIVE) {
    pthread_mutex_unlock(&ctx->mutex);
    return CUBEB_ERROR;
  }
  alsa_set_stream_state(stm, RUNNING);
  pthread_mutex_unlock(&ctx->mutex);

  return CUBEB_OK;
}

static int
alsa_stream_stop(cubeb_stream * stm)
{
  cubeb * ctx;
  int r;

  assert(stm);
  ctx = stm->context;

  if (stm->stream_type == SND_PCM_STREAM_PLAYBACK && stm->other_stream) {
    int r = alsa_stream_stop(stm->other_stream);
    if (r != CUBEB_OK)
      return r;
  }

  pthread_mutex_lock(&ctx->mutex);
  while (stm->state == PROCESSING) {
    r = pthread_cond_wait(&stm->cond, &ctx->mutex);
    assert(r == 0);
  }

  alsa_set_stream_state(stm, INACTIVE);
  pthread_mutex_unlock(&ctx->mutex);

  pthread_mutex_lock(&stm->mutex);
  WRAP(snd_pcm_pause)(stm->pcm, 1);
  pthread_mutex_unlock(&stm->mutex);

  return CUBEB_OK;
}

static int
alsa_stream_get_position(cubeb_stream * stm, uint64_t * position)
{
  snd_pcm_sframes_t delay;

  assert(stm && position);

  pthread_mutex_lock(&stm->mutex);

  delay = -1;
  if (WRAP(snd_pcm_state)(stm->pcm) != SND_PCM_STATE_RUNNING ||
      WRAP(snd_pcm_delay)(stm->pcm, &delay) != 0) {
    *position = stm->last_position;
    pthread_mutex_unlock(&stm->mutex);
    return CUBEB_OK;
  }

  assert(delay >= 0);

  *position = 0;
  if (stm->stream_position >= (snd_pcm_uframes_t)delay) {
    *position = stm->stream_position - delay;
  }

  stm->last_position = *position;

  pthread_mutex_unlock(&stm->mutex);
  return CUBEB_OK;
}

static int
alsa_stream_get_latency(cubeb_stream * stm, uint32_t * latency)
{
  snd_pcm_sframes_t delay;
  /* This function returns the delay in frames until a frame written using
     snd_pcm_writei is sent to the DAC. The DAC delay should be < 1ms anyways.
   */
  if (WRAP(snd_pcm_delay)(stm->pcm, &delay)) {
    return CUBEB_ERROR;
  }

  *latency = delay;

  return CUBEB_OK;
}

static int
alsa_stream_set_volume(cubeb_stream * stm, float volume)
{
  /* setting the volume using an API call does not seem very stable/supported */
  pthread_mutex_lock(&stm->mutex);
  stm->volume = volume;
  pthread_mutex_unlock(&stm->mutex);

  return CUBEB_OK;
}

static int
alsa_enumerate_devices(cubeb * context, cubeb_device_type type,
                       cubeb_device_collection * collection)
{
  void **hints = NULL;
  void **hint;
  char *name = NULL;
  char *io = NULL;
  char *desc = NULL;
  cubeb_device_info * devinfop = NULL;
  int collection_cnt = 0;
  int r;

  if (!context)
    return CUBEB_ERROR;

  /* Get device name hints from ALSA */
  r = WRAP(snd_device_name_hint)(-1, "pcm", &hints);
  if (r < 0) {
    LOG("Failed to get device name hints: %d", r);
    return CUBEB_ERROR;
  }

  /* Count devices first */
  for (hint = hints; *hint != NULL; hint++) {
    name = WRAP(snd_device_name_get_hint)(*hint, "NAME");
    if (!name)
      continue;

    io = WRAP(snd_device_name_get_hint)(*hint, "IOID");

    /* Filter by device type */
    if (type & CUBEB_DEVICE_TYPE_INPUT && io && strcmp(io, "Output") == 0) {
      free(name);
      if (io) free(io);
      continue;
    }
    if (type & CUBEB_DEVICE_TYPE_OUTPUT && io && strcmp(io, "Input") == 0) {
      free(name);
      if (io) free(io);
      continue;
    }

    free(name);
    if (io) free(io);
    collection_cnt++;
  }

  if (collection_cnt == 0) {
    WRAP(snd_device_name_free_hint)(hints);
    return CUBEB_OK;
  }

  devinfop = calloc(collection_cnt, sizeof(cubeb_device_info));
  if (!devinfop) {
    WRAP(snd_device_name_free_hint)(hints);
    return CUBEB_ERROR;
  }

  collection_cnt = 0;
  for (hint = hints; *hint != NULL; hint++) {
    snd_pcm_t * pcm = NULL;
    snd_pcm_hw_params_t * hw_params;
    snd_pcm_stream_t stream_type;
    cubeb_device_info cdi = {0};
    uint32_t min_rate, max_rate;
    uint32_t min_channels, max_channels;
    int dir;

    name = WRAP(snd_device_name_get_hint)(*hint, "NAME");
    if (!name)
      continue;

    io = WRAP(snd_device_name_get_hint)(*hint, "IOID");
    desc = WRAP(snd_device_name_get_hint)(*hint, "DESC");

    /* Filter by device type */
    if (type & CUBEB_DEVICE_TYPE_INPUT && io && strcmp(io, "Output") == 0) {
      goto cleanup_hint;
    }
    if (type & CUBEB_DEVICE_TYPE_OUTPUT && io && strcmp(io, "Input") == 0) {
      goto cleanup_hint;
    }

    /* Determine stream type */
    if (io && strcmp(io, "Input") == 0) {
      stream_type = SND_PCM_STREAM_CAPTURE;
      cdi.type = CUBEB_DEVICE_TYPE_INPUT;
    } else if (io && strcmp(io, "Output") == 0) {
      stream_type = SND_PCM_STREAM_PLAYBACK;
      cdi.type = CUBEB_DEVICE_TYPE_OUTPUT;
    } else {
      /* Try both if IOID is not specified */
      stream_type = (type & CUBEB_DEVICE_TYPE_OUTPUT) ? 
                     SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE;
      cdi.type = (type & CUBEB_DEVICE_TYPE_OUTPUT) ? 
                 CUBEB_DEVICE_TYPE_OUTPUT : CUBEB_DEVICE_TYPE_INPUT;
    }

    /* Open device to query capabilities */
    r = WRAP(snd_pcm_open)(&pcm, name, stream_type, SND_PCM_NONBLOCK);
    if (r < 0) {
      LOG("Failed to open device %s: %d", name, r);
      goto cleanup_hint;
    }

    snd_pcm_hw_params_alloca(&hw_params);
    r = WRAP(snd_pcm_hw_params_any)(pcm, hw_params);
    if (r < 0) {
      LOG("Failed to get hw params for device %s: %d", name, r);
      WRAP(snd_pcm_close)(pcm);
      goto cleanup_hint;
    }

    /* Query format capabilities */
    cdi.format = 0;
    if (WRAP(snd_pcm_hw_params_test_format)(pcm, hw_params, SND_PCM_FORMAT_S16_LE) == 0)
      cdi.format |= CUBEB_DEVICE_FMT_S16LE;
    if (WRAP(snd_pcm_hw_params_test_format)(pcm, hw_params, SND_PCM_FORMAT_S16_BE) == 0)
      cdi.format |= CUBEB_DEVICE_FMT_S16BE;
    if (WRAP(snd_pcm_hw_params_test_format)(pcm, hw_params, SND_PCM_FORMAT_S32_LE) == 0)
      cdi.format |= CUBEB_DEVICE_FMT_S32LE;
    if (WRAP(snd_pcm_hw_params_test_format)(pcm, hw_params, SND_PCM_FORMAT_S32_BE) == 0)
      cdi.format |= CUBEB_DEVICE_FMT_S32BE;
    if (WRAP(snd_pcm_hw_params_test_format)(pcm, hw_params, SND_PCM_FORMAT_FLOAT_LE) == 0)
      cdi.format |= CUBEB_DEVICE_FMT_F32LE;
    if (WRAP(snd_pcm_hw_params_test_format)(pcm, hw_params, SND_PCM_FORMAT_FLOAT_BE) == 0)
      cdi.format |= CUBEB_DEVICE_FMT_F32BE;

    /* Set default format - prefer S32 for high-quality audio */
#if defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__)
    if (cdi.format & CUBEB_DEVICE_FMT_S32BE)
      cdi.default_format = CUBEB_DEVICE_FMT_S32BE;
    else if (cdi.format & CUBEB_DEVICE_FMT_S16BE)
      cdi.default_format = CUBEB_DEVICE_FMT_S16BE;
    else if (cdi.format & CUBEB_DEVICE_FMT_F32BE)
      cdi.default_format = CUBEB_DEVICE_FMT_F32BE;
    else
      cdi.default_format = CUBEB_DEVICE_FMT_S16BE;
#else
    if (cdi.format & CUBEB_DEVICE_FMT_S32LE)
      cdi.default_format = CUBEB_DEVICE_FMT_S32LE;
    else if (cdi.format & CUBEB_DEVICE_FMT_S16LE)
      cdi.default_format = CUBEB_DEVICE_FMT_S16LE;
    else if (cdi.format & CUBEB_DEVICE_FMT_F32LE)
      cdi.default_format = CUBEB_DEVICE_FMT_F32LE;
    else
      cdi.default_format = CUBEB_DEVICE_FMT_S16LE;
#endif

    /* Query rate range */
    r = WRAP(snd_pcm_hw_params_get_rate_min)(hw_params, &min_rate, &dir);
    if (r < 0)
      min_rate = 44100;
    r = WRAP(snd_pcm_hw_params_get_rate_max)(hw_params, &max_rate, &dir);
    if (r < 0)
      max_rate = 48000;

    /* Query channel range */
    r = WRAP(snd_pcm_hw_params_get_channels_min)(hw_params, &min_channels);
    if (r < 0)
      min_channels = 1;
    r = WRAP(snd_pcm_hw_params_get_channels_max)(hw_params, &max_channels);
    if (r < 0)
      max_channels = 2;

    /* Get default rate */
    r = WRAP(snd_pcm_hw_params_get_rate)(hw_params, &cdi.default_rate, &dir);
    if (r < 0)
      cdi.default_rate = 44100;

    WRAP(snd_pcm_close)(pcm);

    /* Fill device info */
    cdi.device_id = strdup(name);
    cdi.devid = (cubeb_devid)cdi.device_id;
    cdi.friendly_name = desc ? strdup(desc) : strdup(name);
    cdi.group_id = strdup(name);
    cdi.vendor_name = NULL;
    cdi.state = CUBEB_DEVICE_STATE_ENABLED;
    cdi.preferred = CUBEB_DEVICE_PREF_NONE;
    cdi.max_channels = max_channels;
    cdi.min_rate = min_rate;
    cdi.max_rate = max_rate;
    cdi.latency_lo = 0;
    cdi.latency_hi = 0;

    if (!cdi.device_id || !cdi.friendly_name || !cdi.group_id) {
      free((void *)cdi.device_id);
      free((void *)cdi.friendly_name);
      free((void *)cdi.group_id);
      goto cleanup_hint;
    }

    devinfop[collection_cnt++] = cdi;

cleanup_hint:
    free(name);
    if (io) free(io);
    if (desc) free(desc);
  }

  WRAP(snd_device_name_free_hint)(hints);

  collection->device = devinfop;
  collection->count = collection_cnt;

  return CUBEB_OK;
}

static int  
alsa_device_collection_destroy(cubeb * context,  
                               cubeb_device_collection * collection)  
{  
  size_t i;  
  
  (void)context;  
  
  for (i = 0; i < collection->count; ++i) {  
    free((void *)collection->device[i].device_id);  
    free((void *)collection->device[i].friendly_name);  
    free((void *)collection->device[i].group_id);  
    free((void *)collection->device[i].vendor_name);  
  }  
  free(collection->device);  
  return CUBEB_OK;  
}

static struct cubeb_ops const alsa_ops = {
    .init = alsa_init,
    .get_backend_id = alsa_get_backend_id,
    .get_max_channel_count = alsa_get_max_channel_count,
    .get_min_latency = alsa_get_min_latency,
    .get_preferred_sample_rate = alsa_get_preferred_sample_rate,
    .get_supported_input_processing_params = NULL,
    .enumerate_devices = alsa_enumerate_devices,
    .device_collection_destroy = alsa_device_collection_destroy,
    .destroy = alsa_destroy,
    .stream_init = alsa_stream_init,
    .stream_destroy = alsa_stream_destroy,
    .stream_start = alsa_stream_start,
    .stream_stop = alsa_stream_stop,
    .stream_get_position = alsa_stream_get_position,
    .stream_get_latency = alsa_stream_get_latency,
    .stream_get_input_latency = NULL,
    .stream_set_volume = alsa_stream_set_volume,
    .stream_set_name = NULL,
    .stream_get_current_device = NULL,
    .stream_set_input_mute = NULL,
    .stream_set_input_processing_params = NULL,
    .stream_device_destroy = NULL,
    .stream_register_device_changed_callback = NULL,
    .register_device_collection_changed = NULL};

Patches for Firefox

$ cat 0001-Add-S32-format-to-the-Firefox-API.patch
From 80bbf447a62e6136f54c4938b99487135383276b Mon Sep 17 00:00:00 2001
From: Devuan
Date: Tue, 7 Jul 2026 22:35:36 +0200
Subject: [PATCH 1/2] Add S32 format to the Firefox API

- Add FMT_S32LE and FMT_S32BE constants to nsIAudioDeviceInfo.idl
- Update AudioDeviceInfo.cpp assertions to accept S32 formats
- Add S32 format conversion in CubebDeviceEnumerator.cpp
- Add local S32 format definitions for external cubeb support
- Update aboutSupport.js to display S32 format information
---
 dom/media/AudioDeviceInfo.cpp              |  5 +++--
 dom/media/CubebUtils.cpp                   |  1 +
 dom/media/nsIAudioDeviceInfo.idl           |  4 +++-
 dom/media/webrtc/CubebDeviceEnumerator.cpp | 14 ++++++++++++++
 toolkit/content/aboutSupport.js            |  4 ++++
 5 files changed, 25 insertions(+), 3 deletions(-)

diff --git a/dom/media/AudioDeviceInfo.cpp b/dom/media/AudioDeviceInfo.cpp
index 072dd43d4ec1..a09e0adf71c3 100644
--- a/dom/media/AudioDeviceInfo.cpp
+++ b/dom/media/AudioDeviceInfo.cpp
@@ -49,10 +49,11 @@ AudioDeviceInfo::AudioDeviceInfo(
       mPreferred == PREF_NONE || mPreferred == PREF_ALL ||
           mPreferred & (PREF_MULTIMEDIA | PREF_VOICE | PREF_NOTIFICATION),
       "Wrong preferred value");
-  MOZ_ASSERT(mSupportedFormat & (FMT_S16LE | FMT_S16BE | FMT_F32LE | FMT_F32BE),
+  MOZ_ASSERT(mSupportedFormat & (FMT_S16LE | FMT_S16BE | FMT_F32LE | FMT_F32BE | FMT_S32LE | FMT_S32BE),
              "Wrong supported format");
   MOZ_ASSERT(mDefaultFormat == FMT_S16LE || mDefaultFormat == FMT_S16BE ||
-                 mDefaultFormat == FMT_F32LE || mDefaultFormat == FMT_F32BE,
+                 mDefaultFormat == FMT_F32LE || mDefaultFormat == FMT_F32BE ||  
+                 mDefaultFormat == FMT_S32LE || mDefaultFormat == FMT_S32BE,  
              "Wrong default format");
 }
 
diff --git a/dom/media/CubebUtils.cpp b/dom/media/CubebUtils.cpp
index 72551b795af3..a9edab7bc358 100644
--- a/dom/media/CubebUtils.cpp
+++ b/dom/media/CubebUtils.cpp
@@ -143,6 +143,7 @@ MOZ_RUNINIT std::unordered_map<std::string, BackendLabel>
         {"alsa", BackendLabel::eAlsa},
         {"jack", BackendLabel::eJack},
         {"oss", BackendLabel::eOss},
+        {"oss-fft", BackendLabel::eOss},
         {"pulse", BackendLabel::ePulse},
         {"pulse-rust", BackendLabel::ePulseRust},
         {"sndio", BackendLabel::eSndio},
diff --git a/dom/media/nsIAudioDeviceInfo.idl b/dom/media/nsIAudioDeviceInfo.idl
index 0458ec1eb927..59d90a0ad3f5 100644
--- a/dom/media/nsIAudioDeviceInfo.idl
+++ b/dom/media/nsIAudioDeviceInfo.idl
@@ -33,11 +33,13 @@ interface nsIAudioDeviceInfo : nsISupports
   const unsigned short PREF_ALL           = 0x0F;
   readonly attribute unsigned short preferred;
 
-  // supported format, default format: S16LE/S16BE/F32LE/F32BE
+  // supported format, default format: S16LE/S16BE/F32LE/F32BE/S32LE/S32BE
   const unsigned short FMT_S16LE = 0x0010;
   const unsigned short FMT_S16BE = 0x0020;
   const unsigned short FMT_F32LE = 0x1000;
   const unsigned short FMT_F32BE = 0x2000;
+  const unsigned short FMT_S32LE = 0x0040;
+  const unsigned short FMT_S32BE = 0x0080;
   readonly attribute unsigned short supportedFormat;
   readonly attribute unsigned short defaultFormat;
 
diff --git a/dom/media/webrtc/CubebDeviceEnumerator.cpp b/dom/media/webrtc/CubebDeviceEnumerator.cpp
index 6e1520c3c714..0d2043cb497c 100644
--- a/dom/media/webrtc/CubebDeviceEnumerator.cpp
+++ b/dom/media/webrtc/CubebDeviceEnumerator.cpp
@@ -17,6 +17,14 @@
 #  include "mozilla/mscom/EnsureMTA.h"
 #endif
 
+// S32 format constants for external cubeb libraries that support them  
+#ifndef CUBEB_DEVICE_FMT_S32LE  
+#define CUBEB_DEVICE_FMT_S32LE 0x0040  
+#endif  
+#ifndef CUBEB_DEVICE_FMT_S32BE  
+#define CUBEB_DEVICE_FMT_S32BE 0x0080  
+#endif
+
 namespace mozilla {
 
 using namespace CubebUtils;
@@ -183,6 +191,12 @@ static uint16_t ConvertCubebFormat(cubeb_device_fmt aFormat) {
   if (aFormat & CUBEB_DEVICE_FMT_F32BE) {
     format |= nsIAudioDeviceInfo::FMT_F32BE;
   }
+  if (aFormat & CUBEB_DEVICE_FMT_S32LE) {  
+    format |= nsIAudioDeviceInfo::FMT_S32LE;  
+  }  
+  if (aFormat & CUBEB_DEVICE_FMT_S32BE) {  
+    format |= nsIAudioDeviceInfo::FMT_S32BE;  
+  }  
   return format;
 }
 
diff --git a/toolkit/content/aboutSupport.js b/toolkit/content/aboutSupport.js
index 388f8048201f..af6e396feb7d 100644
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -974,6 +974,8 @@ var snapshotFormatters = {
       formats[deviceInfo.FMT_S16BE] = "S16BE";
       formats[deviceInfo.FMT_F32LE] = "F32LE";
       formats[deviceInfo.FMT_F32BE] = "F32BE";
+      formats[deviceInfo.FMT_S32LE] = "S32LE";
+      formats[deviceInfo.FMT_S32BE] = "S32BE";
 
       function toPreferredString(preferred) {
         if (preferred == deviceInfo.PREF_NONE) {
@@ -1001,6 +1003,8 @@ var snapshotFormatters = {
           deviceInfo.FMT_S16BE,
           deviceInfo.FMT_F32LE,
           deviceInfo.FMT_F32BE,
+          deviceInfo.FMT_S32LE,
+          deviceInfo.FMT_S32BE,
         ]) {
           if (dev.supportedFormat & fmt) {
             str += " " + formats[fmt];
-- 
2.39.5
$ cat 0002-Add-S32-format-to-the-Cubeb-API.patch
From f8d402971731b6729daf47624fe74a7e7466ee24 Mon Sep 17 00:00:00 2001
From: Devuan
Date: Thu, 9 Jul 2026 17:48:56 +0200
Subject: [PATCH 2/2] Add S32 format to the Cubeb API

- Add CUBEB_DEVICE_FMT_S32LE and CUBEB_DEVICE_FMT_S32BE constants to API
- Update log_device function to handle S32 formats in logging
- Update test_devices to handle S32 format display
---
 media/libcubeb/include/cubeb/cubeb.h | 17 ++++++++++++-----
 media/libcubeb/src/cubeb.c           | 23 +++++++++++++++++++++++
 media/libcubeb/test/test_devices.cpp | 10 ++++++++++
 3 files changed, 45 insertions(+), 5 deletions(-)

diff --git a/media/libcubeb/include/cubeb/cubeb.h b/media/libcubeb/include/cubeb/cubeb.h
index ff2f8b7b987d..322230a2df11 100644
--- a/media/libcubeb/include/cubeb/cubeb.h
+++ b/media/libcubeb/include/cubeb/cubeb.h
@@ -340,6 +340,8 @@ typedef enum {
 typedef enum {
   CUBEB_DEVICE_FMT_S16LE = 0x0010, /**< 16-bit integers, Little Endian. */
   CUBEB_DEVICE_FMT_S16BE = 0x0020, /**< 16-bit integers, Big Endian. */
+  CUBEB_DEVICE_FMT_S32LE = 0x0040, /**< 32-bit integers, Little Endian. */
+  CUBEB_DEVICE_FMT_S32BE = 0x0080, /**< 32-bit integers, Big Endian. */
   CUBEB_DEVICE_FMT_F32LE = 0x1000, /**< 32-bit floating point, Little Endian. */
   CUBEB_DEVICE_FMT_F32BE = 0x2000  /**< 32-bit floating point, Big Endian. */
 } cubeb_device_fmt;
@@ -347,25 +349,30 @@ typedef enum {
 #if defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__)
 /** 16-bit integers, native endianess, when on a Big Endian environment. */
 #define CUBEB_DEVICE_FMT_S16NE CUBEB_DEVICE_FMT_S16BE
-/** 32-bit floating points, native endianess, when on a Big Endian environment.
- */
+/** 32-bit integers, native endianess, when on a Big Endian environment. */
+#define CUBEB_DEVICE_FMT_S32NE CUBEB_DEVICE_FMT_S32BE
+/** 32-bit floating points, native endianess, when on a Big Endian environment. */
 #define CUBEB_DEVICE_FMT_F32NE CUBEB_DEVICE_FMT_F32BE
 #else
 /** 16-bit integers, native endianess, when on a Little Endian environment. */
 #define CUBEB_DEVICE_FMT_S16NE CUBEB_DEVICE_FMT_S16LE
-/** 32-bit floating points, native endianess, when on a Little Endian
- *  environment. */
+/** 32-bit integers, native endianess, when on a Little Endian environment. */
+#define CUBEB_DEVICE_FMT_S32NE CUBEB_DEVICE_FMT_S32LE
+/** 32-bit floating points, native endianess, when on a Little Endian environment. */
 #define CUBEB_DEVICE_FMT_F32NE CUBEB_DEVICE_FMT_F32LE
 #endif
 /** All the 16-bit integers types. */
 #define CUBEB_DEVICE_FMT_S16_MASK                                              \
   (CUBEB_DEVICE_FMT_S16LE | CUBEB_DEVICE_FMT_S16BE)
+/** All the 32-bit integers types. */
+#define CUBEB_DEVICE_FMT_S32_MASK                                              \
+  (CUBEB_DEVICE_FMT_S32LE | CUBEB_DEVICE_FMT_S32BE)
 /** All the 32-bit floating points types. */
 #define CUBEB_DEVICE_FMT_F32_MASK                                              \
   (CUBEB_DEVICE_FMT_F32LE | CUBEB_DEVICE_FMT_F32BE)
 /** All the device formats types. */
 #define CUBEB_DEVICE_FMT_ALL                                                   \
-  (CUBEB_DEVICE_FMT_S16_MASK | CUBEB_DEVICE_FMT_F32_MASK)
+  (CUBEB_DEVICE_FMT_S16_MASK | CUBEB_DEVICE_FMT_S32_MASK | CUBEB_DEVICE_FMT_F32_MASK)
 
 /** Channel type for a `cubeb_stream`. Depending on the backend and platform
  * used, this can control inter-stream interruption, ducking, and volume
diff --git a/media/libcubeb/src/cubeb.c b/media/libcubeb/src/cubeb.c
index 4fdead389354..1ca8582bab71 100644
--- a/media/libcubeb/src/cubeb.c
+++ b/media/libcubeb/src/cubeb.c
@@ -75,6 +75,10 @@ opensl_init(cubeb ** context, char const * context_name);
 int
 oss_init(cubeb ** context, char const * context_name);
 #endif
+#if defined(USE_OSS_FFT)  
+int  
+oss_fft_init(cubeb ** context, char const * context_name);  
+#endif
 #if defined(USE_AAUDIO)
 int
 aaudio_init(cubeb ** context, char const * context_name);
@@ -195,6 +199,10 @@ cubeb_init(cubeb ** context, char const * context_name,
     } else if (!strcmp(backend_name, "oss")) {
 #if defined(USE_OSS)
       init_oneshot = oss_init;
+#endif
+} else if (!strcmp(backend_name, "oss-fft")) {  
+#if defined(USE_OSS_FFT)  
+  init_oneshot = oss_fft_init;  
 #endif
     } else if (!strcmp(backend_name, "aaudio")) {
 #if defined(USE_AAUDIO)
@@ -237,6 +245,9 @@ cubeb_init(cubeb ** context, char const * context_name,
 #if defined(USE_OSS)
       oss_init,
 #endif
+#if defined(USE_OSS_FFT)  
+  oss_fft_init,  
+#endif
 #if defined(USE_AUDIOUNIT_RUST)
       audiounit_rust_init,
 #endif
@@ -690,6 +701,12 @@ log_device(cubeb_device_info * device_info)
   case CUBEB_DEVICE_FMT_F32BE:
     devdeffmt = "F32BE";
     break;
+	case CUBEB_DEVICE_FMT_S32LE:  
+		devdeffmt = "S32LE";  
+		break;  
+	case CUBEB_DEVICE_FMT_S32BE:  
+		devdeffmt = "S32BE";  
+		break;
   default:
     devdeffmt = "unknown?";
     break;
@@ -707,6 +724,12 @@ log_device(cubeb_device_info * device_info)
   if (device_info->format & CUBEB_DEVICE_FMT_F32BE) {
     strcat(devfmts, " F32BE");
   }
+  if (device_info->format & CUBEB_DEVICE_FMT_S32LE) {
+    strcat(devfmts, " S32LE");
+  }
+  if (device_info->format & CUBEB_DEVICE_FMT_S32BE) {
+    strcat(devfmts, " S32BE");
+  }
 
   LOG("DeviceID: \"%s\"%s\n"
       "\tName:\t\"%s\"\n"
diff --git a/media/libcubeb/test/test_devices.cpp b/media/libcubeb/test/test_devices.cpp
index d0eab2da67e6..4a8da1a4113b 100644
--- a/media/libcubeb/test/test_devices.cpp
+++ b/media/libcubeb/test/test_devices.cpp
@@ -79,6 +79,12 @@ print_device_info(cubeb_device_info * info, FILE * f)
   case CUBEB_DEVICE_FMT_F32BE:
     devdeffmt = "F32BE";
     break;
+  case CUBEB_DEVICE_FMT_S32LE:  // Add this  
+    devdeffmt = "S32LE";  
+    break;  
+  case CUBEB_DEVICE_FMT_S32BE:  // Add this  
+    devdeffmt = "S32BE";  
+    break;  
   default:
     devdeffmt = "unknown?";
     break;
@@ -92,6 +98,10 @@ print_device_info(cubeb_device_info * info, FILE * f)
     strcat(devfmts, " F32LE");
   if (info->format & CUBEB_DEVICE_FMT_F32BE)
     strcat(devfmts, " F32BE");
+	if (info->format & CUBEB_DEVICE_FMT_S32LE)  // Add this  
+		strcat(devfmts, " S32LE");  
+	if (info->format & CUBEB_DEVICE_FMT_S32BE)  // Add this  
+		strcat(devfmts, " S32BE");
 
   fprintf(f,
           "dev: \"%s\"%s\n"
-- 
2.39.5

EXAMPLE: Firefox about:support

$ firefox-dev about:support
...
Name 	Firefox Developer Edition
Version 	154.0a1
...
Update Channel 	aurora
User Agent 	Mozilla/5.0 (X11; Linux x86_64; rv:154.0) Gecko/20100101 Firefox/154.0
...
Application Binary 	/usr/lib/firefox-dev/firefox-dev
Profile Directory 	$HOME/.firefox-dev/uf30avtz.dev-edition-default
...
Audio Backend: alsa
Max Channels: 64
Preferred Sample Rate: 44100
Roundtrip latency (standard deviation): NaNms (NaN)
...
Output Devices
Name: Group, Vendor, State, Preferred, Format, Channels, Rate, Latency
Discard all samples (playback) or generate zero samples (capture): null, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 1073741823, default: 44100, support: 1 - 4294967295, 0 - 0
Rate Converter Plugin Using Libav/FFmpeg Library: lavrate, Enabled, None, default: S32LE, support: S16LE S16BE S32LE S32BE, 10000, default: 44100, support: 1 - 4294967295, 0 - 0
Rate Converter Plugin Using Samplerate Library: samplerate, Enabled, None, default: S32LE, support: S16LE S16BE S32LE S32BE, 10000, default: 44100, support: 1 - 4294967295, 0 - 0
Rate Converter Plugin Using Speex Resampler: speexrate, Enabled, None, default: S32LE, support: S16LE S16BE S32LE S32BE, 10000, default: 44100, support: 1 - 4294967295, 0 - 0
Bluetooth Audio: bluealsa, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
Plugin using Speex DSP (resample, agc, denoise, echo, dereverb): speex, Enabled, None, default: S16LE, support: S16LE, 1, default: 44100, support: 4000 - 4294967295, 0 - 0
Plugin for channel upmix (4,6,8): upmix, Enabled, None, default: S16LE, support: S16LE, 8, default: 44100, support: 4000 - 4294967295, 0 - 0
Plugin for channel downmix (stereo) with a simple spacialization: vdownmix, Enabled, None, default: S16LE, support: S16LE, 6, default: 44100, support: 4000 - 4294967295, 0 - 0
Default device: default, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, 92HD95 Analog Direct hardware device without any conversions: hw:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, HDMI 0 Direct hardware device without any conversions: hw:CARD=PCH,DEV=3, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, HDMI 1 Direct hardware device without any conversions: hw:CARD=PCH,DEV=7, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, HDMI 2 Direct hardware device without any conversions: hw:CARD=PCH,DEV=8, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, HDMI 3 Direct hardware device without any conversions: hw:CARD=PCH,DEV=9, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog Hardware device with all software conversions: plughw:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, HDMI 0 Hardware device with all software conversions: plughw:CARD=PCH,DEV=3, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, HDMI 1 Hardware device with all software conversions: plughw:CARD=PCH,DEV=7, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, HDMI 2 Hardware device with all software conversions: plughw:CARD=PCH,DEV=8, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, HDMI 3 Hardware device with all software conversions: plughw:CARD=PCH,DEV=9, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, 92HD95 Analog Default Audio Device: sysdefault:CARD=PCH, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, 92HD95 Analog Front output / input: front:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog 4.0 Surround output to Front and Rear speakers: surround40:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog 5.1 Surround output to Front, Center, Rear and Subwoofer speakers: surround51:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog 7.1 Surround output to Front, Center, Side, Rear and Woofer speakers: surround71:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, HDMI 0 HDMI Audio Output: hdmi:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, HDMI 1 HDMI Audio Output: hdmi:CARD=PCH,DEV=1, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, HDMI 2 HDMI Audio Output: hdmi:CARD=PCH,DEV=2, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, HDMI 3 HDMI Audio Output: hdmi:CARD=PCH,DEV=3, Enabled, None, default: S32LE, support: S16LE S32LE, 8, default: 44100, support: 32000 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog Direct sample mixing device: dmix:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S32LE, 2, default: 48000, support: 48000 - 48000, 0 - 0
HDA Intel PCH, HDMI 0 Direct sample mixing device: dmix:CARD=PCH,DEV=3, Enabled, None, default: S32LE, support: S32LE, 2, default: 48000, support: 48000 - 48000, 0 - 0
HDA Intel PCH, HDMI 1 Direct sample mixing device: dmix:CARD=PCH,DEV=7, Enabled, None, default: S32LE, support: S32LE, 2, default: 48000, support: 48000 - 48000, 0 - 0
HDA Intel PCH, HDMI 2 Direct sample mixing device: dmix:CARD=PCH,DEV=8, Enabled, None, default: S32LE, support: S32LE, 2, default: 48000, support: 48000 - 48000, 0 - 0
HDA Intel PCH, HDMI 3 Direct sample mixing device: dmix:CARD=PCH,DEV=9, Enabled, None, default: S32LE, support: S32LE, 2, default: 48000, support: 48000 - 48000, 0 - 0
Input Devices
Name: Group, Vendor, State, Preferred, Format, Channels, Rate, Latency
Discard all samples (playback) or generate zero samples (capture): null, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 1073741823, default: 44100, support: 1 - 4294967295, 0 - 0
Rate Converter Plugin Using Libav/FFmpeg Library: lavrate, Enabled, None, default: S32LE, support: S16LE S16BE S32LE S32BE, 10000, default: 44100, support: 1 - 4294967295, 0 - 0
Rate Converter Plugin Using Samplerate Library: samplerate, Enabled, None, default: S32LE, support: S16LE S16BE S32LE S32BE, 10000, default: 44100, support: 1 - 4294967295, 0 - 0
Rate Converter Plugin Using Speex Resampler: speexrate, Enabled, None, default: S32LE, support: S16LE S16BE S32LE S32BE, 10000, default: 44100, support: 1 - 4294967295, 0 - 0
Plugin using Speex DSP (resample, agc, denoise, echo, dereverb): speex, Enabled, None, default: S16LE, support: S16LE, 1, default: 44100, support: 4000 - 4294967295, 0 - 0
Plugin for channel upmix (4,6,8): upmix, Enabled, None, default: S16LE, support: S16LE, 8, default: 44100, support: 4000 - 4294967295, 0 - 0
Plugin for channel downmix (stereo) with a simple spacialization: vdownmix, Enabled, None, default: S16LE, support: S16LE, 6, default: 44100, support: 4000 - 4294967295, 0 - 0
Default device: default, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, 92HD95 Analog Direct hardware device without any conversions: hw:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog Hardware device with all software conversions: plughw:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, 92HD95 Analog Default Audio Device: sysdefault:CARD=PCH, Enabled, None, default: S32LE, support: S16LE S16BE F32LE F32BE S32LE S32BE, 10000, default: 44100, support: 4000 - 4294967295, 0 - 0
HDA Intel PCH, 92HD95 Analog Front output / input: front:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S16LE S32LE, 2, default: 44100, support: 44100 - 192000, 0 - 0
HDA Intel PCH, 92HD95 Analog Direct sample snooping device: dsnoop:CARD=PCH,DEV=0, Enabled, None, default: S32LE, support: S32LE, 2, default: 48000, support: 48000 - 48000, 0 - 0

NOTE: ALSA device enumeration is now exact, but ALSA drives might be buggy. Therefore, "digital" may mean "analog" and other way round. The word "virtual" usually implies linear interpolation or other sort of low quality resampling.

1. Device enumeration is exact - The ALSA library correctly enumerates available devices through the control interface and name hints control.

2. Driver descriptions can be buggy - Generic card configurations like HDA-Intel.conf make assumptions about device mappings that may not match actual hardware pin configurations.

3. "Virtual" and resampling quality - Virtual devices (using the plug plugin) perform conversions, but the quality depends on the configured rate converter. The default is often linear interpolation, but high-quality converters like fftrate can be used.

Virtual devices are software plugins that wrap hardware access. They always perform some conversion (format, rate, or channels), but the quality varies:

Default: often linear interpolation (lower quality)
Configurable: can use high-quality resamplers like fftrate

Hardware devices (hw:) provide direct kernel driver access without any conversions.

The "digital"/"analog" labels come from driver descriptions, which may be incorrect due to generic configuration assumptions not matching your specific motherboard's pin layout.

The word "direct" is also a sort of label that has a flexible meaning: "direct exclusive kernel driver access" is not possible with ALSA in any sense.

The ALSA hw plugin does communicate directly with the kernel driver through device files and ioctl calls, but this is still mediated by the ALSA library (libasound) in userspace. The snd_pcm_hw_open function opens kernel device files like /dev/snd/pcmC%iD%ip and uses ioctl calls to communicate with the kernel driver.

When ALSA documentation says the hw plugin provides "direct communication without any conversions," it means:
No software format conversion
No software rate conversion
No software channel routing
Direct ioctl calls to kernel device files

But it does NOT mean:
Bypassing the ALSA library
Exclusive hardware access (other processes can still access the device)
Bypassing potential kernel driver bugs

The ALSA path with hw:0,0 is:

Application → ALSA Library (libasound) → hw plugin → ioctl → Kernel Driver → Hardware 

The hw plugin is the closest you can get to the kernel driver while still using the ALSA API, but it's still going through the library layer.

There is no way to access the ALSA kernel driver directly from userspace without going through libasound. The "direct" terminology in ALSA documentation refers to the absence of software processing plugins, not to bypassing the library itself.
See also:
The exclusive mode of ALSA
_https://dev1galaxy.org/viewtopic.php?id=8053

In practical terms, the choice is indeed between low-quality hardware resampling and software resampling.

The fundamental tradeoff in ALSA audio processing:
Hardware resampling - Built into consumer sound cards/codecs, often poor quality due to cost-cutting and implementation limitations.
Software resampling - Performed by ALSA's rate plugin, quality depends on the converter used.

ALSA's plug plugin automatically inserts rate conversion when the application's requested rate differs from the hardware's native rate. The rate plugin supports multiple converters specified via the converter parameter.

The default linear converter provides basic linear interpolation (low quality), while high-quality external converters like fftrate can be used through the External Rate-Converter-Plugin SDK.

The optimal strategy — using high-quality software resampling (fftrate) to bypass hardware resamplers by sending a fixed high-rate stream to the hardware — effectively avoids the quality limitations of consumer hardware SRC implementations.

NOTE: This guide is a work in progress. Please do not post in this topic. If you have any questions, please consult the Devuan Wiki, or other knowledge repositories of the sort.

Offline

Board footer