{
  config,
  lib,
  pkgs,
  ...
}: let
  cfg = config.hive.sound;
in {
  options = {
    hive.sound = {
      enable = lib.mkOption {
        type = lib.types.bool;
        default = false;
        description = "Enable sound with pipewire.";
      };
      noisetorch = lib.mkOption {
        type = lib.types.bool;
        default = false;
        description = "Enable Noisetorch for noise cancellation.";
      };
      noisetorch-threshold = lib.mkOption {
        type = lib.types.int;
        default = -1;
        description = "Set the noise cancellation threshold for Noisetorch.";
      };
    };
  };
  config = lib.mkIf cfg.enable {
    # Enable sound with pipewire.
    services.pulseaudio.enable = false;
    security.rtkit.enable = true;
    services.pipewire = {
      enable = true;
      alsa.enable = true;
      alsa.support32Bit = true;
      pulse.enable = true;
      # If you want to use JACK applications, uncomment this
      #jack.enable = true;

      # use the example session manager (no others are packaged yet so this is enabled by default,
      # no need to redefine it in your config for now)
      #media-session.enable = true;
    };
    programs.noisetorch.enable = cfg.noisetorch;
    systemd.user.services.noisetorch-autoload = lib.mkIf cfg.noisetorch {
      description = "Automatically load Noisetorch on user login";
      after = ["pipewire.service"];
      requires = ["pipewire.service"];
      serviceConfig = {
        Type = "oneshot";
        ExecStart = "${pkgs.writeShellScript "load-noisetorch" ''
          set -euo pipefail
          NOISETORCH="${pkgs.noisetorch}/bin/noisetorch"
          WPCTL="${pkgs.wireplumber}/bin/wpctl"
          GREP="${pkgs.gnugrep}/bin/grep"
          AWK="${pkgs.gawk}/bin/awk"
          HEAD="${pkgs.coreutils}/bin/head"

          sleep 2
          $NOISETORCH -i -t ${toString cfg.noisetorch-threshold};
          sleep 2
          FILTER_ID=$($WPCTL status | $GREP NoiseTorch | $AWK 'match($0, /[0-9]+(\.[0-9]+)?/) { print substr($0, RSTART, RLENGTH) }' | head -n1)
          if [ -n "$FILTER_ID" ]; then
            $WPCTL set-default $FILTER_ID
          else
            echo "Noisetorch filter not found, skipping setting default source."
          fi
        ''}";
        ExecStop = "${pkgs.noisetorch}/bin/noisetorch -u";
        RemainAfterExit = true;
      };
      wantedBy = ["default.target"];
    };
  };
}
