vendor/github.com/gen2brain/beeep/beep_unix.go

139 lines · 3573 bytes

  1//go:build linux || freebsd || netbsd || openbsd || illumos
  2// +build linux freebsd netbsd openbsd illumos
  3
  4package beeep
  5
  6import (
  7	"errors"
  8	"os"
  9	"syscall"
 10	"time"
 11	"unsafe"
 12)
 13
 14// Constants
 15const (
 16	// This number represents the fixed frequency of the original PC XT's timer chip, which is approximately 1.193 MHz. This number
 17	// is divided with the desired frequency to obtain a counter value, that is subsequently fed into the timer chip, tied to the PC speaker.
 18	clockTickRate = 1193180
 19
 20	// linux/kd.h, start sound generation (0 for off)
 21	kiocsound = 0x4B2F
 22
 23	// linux/input-event-codes.h
 24	evSnd   = 0x12 // Event type
 25	sndTone = 0x02 // Sound
 26)
 27
 28var (
 29	// DefaultFreq - frequency, in Hz, middle A
 30	DefaultFreq = 440.0
 31	// DefaultDuration - duration in milliseconds
 32	DefaultDuration = 200
 33)
 34
 35// inputEvent represents linux/input.h event structure.
 36type inputEvent struct {
 37	Time  syscall.Timeval // time in seconds since epoch at which event occurred
 38	Type  uint16          // event type
 39	Code  uint16          // event code related to the event type
 40	Value int32           // event value related to the event type
 41}
 42
 43// ioctl system call manipulates the underlying device parameters of special files.
 44func ioctl(fd, name, data uintptr) error {
 45	_, _, e := syscall.Syscall(syscall.SYS_IOCTL, fd, name, data)
 46	if e != 0 {
 47		return e
 48	}
 49
 50	return nil
 51}
 52
 53// Beep beeps the PC speaker (https://en.wikipedia.org/wiki/PC_speaker).
 54//
 55// On Linux it needs permission to access `/dev/tty0` or `/dev/input/by-path/platform-pcspkr-event-spkr` files for writing,
 56// and `pcspkr` module must be loaded. User must be in correct groups, usually `input` and/or `tty`.
 57//
 58// If it can not open device files, it will fallback to sending Bell character (https://en.wikipedia.org/wiki/Bell_character).
 59// For bell character in X11 terminals you can enable bell with `xset b on`. For console check `setterm` and `--blength` or `--bfreq` options.
 60//
 61// On macOS this just sends bell character. Enable `Audible bell` in Terminal --> Preferences --> Settings --> Advanced.
 62//
 63// On Windows it uses Beep function via syscall.
 64//
 65// On Web it plays hard coded beep sound.
 66func Beep(freq float64, duration int) error {
 67	if freq == 0 {
 68		freq = DefaultFreq
 69	} else if freq > 20000 {
 70		freq = 20000
 71	} else if freq < 0 {
 72		freq = DefaultFreq
 73	}
 74
 75	if duration == 0 {
 76		duration = DefaultDuration
 77	}
 78
 79	period := int(float64(clockTickRate) / freq)
 80
 81	var evdev bool
 82
 83	f, err := os.OpenFile("/dev/tty0", os.O_WRONLY, 0644)
 84	if err != nil {
 85		e := err
 86		f, err = os.OpenFile("/dev/input/by-path/platform-pcspkr-event-spkr", os.O_WRONLY, 0644)
 87		if err != nil {
 88			e = errors.New("beeep: " + e.Error() + "; " + err.Error())
 89
 90			// Output the only beep we can
 91			_, err = os.Stdout.Write([]byte{7})
 92			if err != nil {
 93				return errors.New(e.Error() + "; " + err.Error())
 94			}
 95
 96			return nil
 97		}
 98
 99		evdev = true
100	}
101
102	defer f.Close()
103
104	if evdev { // Use Linux evdev API
105		ev := inputEvent{}
106		ev.Type = evSnd
107		ev.Code = sndTone
108		ev.Value = int32(freq)
109
110		d := *(*[unsafe.Sizeof(ev)]byte)(unsafe.Pointer(&ev))
111
112		// Start beep
113		f.Write(d[:])
114
115		time.Sleep(time.Duration(duration) * time.Millisecond)
116
117		ev.Value = 0
118		d = *(*[unsafe.Sizeof(ev)]byte)(unsafe.Pointer(&ev))
119
120		// Stop beep
121		f.Write(d[:])
122	} else { // Use ioctl
123		// Start beep
124		err = ioctl(f.Fd(), kiocsound, uintptr(period))
125		if err != nil {
126			return err
127		}
128
129		time.Sleep(time.Duration(duration) * time.Millisecond)
130
131		// Stop beep
132		err = ioctl(f.Fd(), kiocsound, uintptr(0))
133		if err != nil {
134			return err
135		}
136	}
137
138	return nil
139}