{ config, lib, pkgs, ... }:

{
  # Enable sound with pipewire.
  services.pulseaudio.enable = false;

  musnix = {
    enable = true;
    alsaSeq.enable = true;
    rtcqs.enable = true;
  };

  services.pipewire = {
    enable = true;

    alsa = {
      enable = true;
      support32Bit = true;
    };

    pulse.enable = true;
    jack.enable = true;

    wireplumber = {
      enable = true;
    };

    extraConfig = {
      pipewire."91-null-sinks" = {
        "context.modules" = [
          {
            name = "libpipewire-module-loopback";
            args = {
              "node.description" = "Default Playback";
              "capture.props" = {
                "node.name" = "BixSix_or_fallback_Playback";
                "media.class" = "Audio/Sink";
                "audio.position" = "[FL FR]";
              };
              "playback.props" = {
                "node.name" = "playback.BixSixWithFallbackPlayback";
                "audio.position" = "[AUX14 AUX15]";
                "target.object" = "alsa_output.usb-Solid_State_Logic_BiG_SiX-00.pro-output-0";
                "stream.dont-remix" = true;
                "node.passive" = true;
              };
            };
          }
        ];
      };
      pipewire."92-low-latency" = {
        context.properties = {
          default.clock.rate = 48000;
          default.clock.quantum = 32;
          default.clock.min-quantum = 32;
          default.clock.max-quantum = 32;
        };
      };
      pipewire-pulse."92-low-latency" = {
        context.modules = [
          {
            name = "libpipewire-module-protocol-pulse";
            args = {
              pulse.min.req = "32/48000";
              pulse.default.req = "32/48000";
              pulse.max.req = "32/48000";
              pulse.min.quantum = "32/48000";
              pulse.max.quantum = "32/48000";
            };
          }
        ];
        stream.properties = {
          node.latency = "32/48000";
          resample.quality = 1;
        };
      };
      pipewire."10-airplay" = {
        "context.modules" = [
          {
            name = "libpipewire-module-raop-discover";

            # increase the buffer size if you get dropouts/glitches
            # args = {
            #   "raop.latency.ms" = 500;
            # };
          }
        ];
      };
    };
  };
}
