Commit

2d2d5da

TIL MacBook trackpads can play music https://github.com/os6/nospeaker Trying to make it play a famous melody:
swift
import Foundation
let wave = "Square" // "Sine", "Square", "Sawtooth"
let level: Float = 0.3 // 0...1; keep it low, 1.0 is loud and makes the driver drop segments
let bpm = 120.0
let gap = 0.5
let bars = [
  "D3 D3 D4 - A3 - - G#3 - G3 - F3 = D3 F3 G3",
  "C3 C3 D4 - A3 - - G#3 - G3 - F3 = D3 F3 G3",
  "B2 B2 D4 - A3 - - G#3 - G3 - F3 = D3 F3 G3",
  "Bb2 Bb2 D4 - A3 - - G#3 - G3 - F3 = D3 F3 G3",
]

func freq(_ name: String) -> Double {
  let semis: [Character: Int] = ["C": -9, "D": -7, "E": -5, "F": -4, "G": -2, "A": 0, "B": 2]
  var s = Substring(name)
  var n = semis[Character(s.removeFirst().uppercased())]!
  if s.first == "#" { n += 1; s.removeFirst() } else if s.first == "b" { n -= 1; s.removeFirst() }
  let octave = Int(s)!
  return 440 * pow(2, Double(n + (octave - 4) * 12) / 12)
}

var notes: [(hz: Double, sixteenths: Int)] = []
for bar in bars {
  for tok in bar.split(separator: " ").map(String.init) {
    if tok == "=" { notes[notes.count - 1].sixteenths += 1 }
    else if tok == "-" { notes.append((0, 1)) }
    else { notes.append((freq(tok), 1)) }
  }
}

// ---- trackpad motor ----
typealias ListFn = @convention(c) () -> Unmanaged<CFArray>?
typealias GetIDFn = @convention(c) (UnsafeRawPointer, UnsafeMutablePointer<UInt64>) -> Int32
typealias CreateFn = @convention(c) (UInt64) -> Unmanaged<CFTypeRef>?
typealias OpenFn = @convention(c) (CFTypeRef) -> Int32
typealias CloseFn = @convention(c) (CFTypeRef) -> Int32
typealias ActCreateFn = @convention(c) (CFDictionary, Int32) -> UnsafeMutableRawPointer?
typealias ActPlayFn = @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UInt32, Float, Float) -> Int32

let h = dlopen("/System/Library/PrivateFrameworks/MultitouchSupport.framework/MultitouchSupport", RTLD_NOW)!
func sym<T>(_ n: String, _ t: T.Type) -> T { unsafeBitCast(dlsym(h, n)!, to: t) }
let list = sym("MTDeviceCreateList", ListFn.self)
let getID = sym("MTDeviceGetDeviceID", GetIDFn.self)
let create = sym("MTActuatorCreateFromDeviceID", CreateFn.self)
let open = sym("MTActuatorOpen", OpenFn.self)
let close = sym("MTActuatorClose", CloseFn.self)
let actCreate = sym("MTActuationCreateFromDictionary", ActCreateFn.self)
let actPlay = sym("MTActuationActuate", ActPlayFn.self)

var motor: CFTypeRef? = nil
let devs = list()!.takeRetainedValue()
for i in 0..<CFArrayGetCount(devs) {
  var id: UInt64 = 0
  _ = getID(CFArrayGetValueAtIndex(devs, i)!, &id)
  if let a = create(id)?.takeRetainedValue(), open(a) == 0 { motor = a; break }
}
guard let m = motor else { fatalError("no Force Touch trackpad found") }
let mp = Unmanaged.passUnretained(m as AnyObject).toOpaque()

var tb = mach_timebase_info_data_t(); mach_timebase_info(&tb)
let tps = 1e9 * Double(tb.denom) / Double(tb.numer)
func waitUntil(_ t: UInt64) { while mach_absolute_time() < t {} }

func play(_ hz: Double, ms: Double) {
  let shape: [String: Any] = [
    "BaseWaveform": ["Type": "Gaussian", "Amplitude": 0.0, "DurationMS": ms],
    "Tones": [["Type": wave, "Amplitude": 1.0, "DurationMS": ms, "DelayMS": 0.0, "FrequencykHz": hz / 1000]],
  ]
  guard let act = actCreate(shape as CFDictionary, 0) else { return }
  _ = actPlay(act, mp, 0, level, 0)
  Unmanaged<AnyObject>.fromOpaque(act).release()
}

let sixteenth = 60 / bpm / 4
let start = mach_absolute_time()
var t = 0.0
for (f, n) in notes {
  let soundEnd = t + Double(n) * sixteenth - gap * sixteenth
  if f > 0 {
    var tt = t
    while tt < soundEnd - 0.5 / f {
      // whole cycles, about 20 ms per segment
      let seg = min(max(1, (0.02 * f).rounded()) / f, max(1, ((soundEnd - tt) * f).rounded()) / f)
      play(f, ms: seg * 1000)
      tt += seg
      waitUntil(start + UInt64(tt * tps))
    }
  }
  t += Double(n) * sixteenth
  waitUntil(start + UInt64(t * tps))
}
_ = close(m)

commit 2d2d5da