audio

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package audio carries Planck's game audio: capture on the host, Opus encode and decode, a jitter buffer on the client, and playback. All PCM is interleaved 48 kHz stereo int16.

Index

Constants

View Source
const (
	SampleRate = 48000
	Channels   = 2
)
View Source
const (
	ModeProcessLoopback  = "process-loopback"  // Windows, without Planck's process tree
	ModeEndpointLoopback = "endpoint-loopback" // Windows default render endpoint, Planck included
	ModeProcessTap       = "process-tap"       // macOS Core Audio tap, without Planck
	ModeScreenCaptureKit = "screencapturekit"  // macOS, without Planck
	ModeMicrophone       = "microphone"
)

Capture paths a capturer's Mode reports.

View Source
const (
	DefaultFrameDuration = 10 * time.Millisecond
	DefaultBitrate       = 128000

	// MaxPacketSize is the largest single-frame Opus packet (RFC 6716 3.2.1).
	MaxPacketSize = 1275
)
View Source
const CanExcludeProcesses = false

CanExcludeProcesses is false: a sink's monitor carries every stream on it, Planck's own and a voice chat's included.

View Source
const MicChannels = 1

MicChannels is the channel count of microphone PCM: the client captures and the host plays mono.

View Source
const MicPCMFrameDuration = 5 * time.Millisecond

MicPCMFrameDuration is the frame of the raw PCM mic codec: 240 mono samples, 480 bytes, one datagram each.

View Source
const ModePulseMonitor = "pulse-monitor"

ModePulseMonitor is the capture path of Linux: the monitor of an output device, through PulseAudio or PipeWire's PulseAudio server.

View Source
const PlanckVirtualAudio = "Planck Virtual Audio"

PlanckVirtualAudio is the name of the device the Planck Virtual Audio drivers in drivers/audio create, on Windows and macOS alike.

View Source
const VirtualMicHint = "Virtual mic not detected — install Planck Virtual Audio (or Steam Streaming Microphone / another virtual audio device)"

VirtualMicHint is what a host without a virtual input device tells the client. Planck does not install one itself: Planck Virtual Audio ships in drivers/audio/windows and the user installs it.

Variables

View Source
var (
	// ErrNoVirtualMic: no user-installed virtual input device matched.
	ErrNoVirtualMic = errors.New("audio: " + VirtualMicHint)
	// ErrVirtualMicSetup: a virtual mic was found but will not pass audio
	// as it is set up; the error says what to change.
	ErrVirtualMicSetup = errors.New("audio: virtual mic needs setup")
	// ErrUnsupported: this platform has no backend for the call yet.
	ErrUnsupported = errors.New("audio: not supported on this platform")
)
View Source
var ErrClosed = errors.New("audio: closed")

Functions

func AppPIDs

func AppPIDs(names []string) ([]int, error)

AppPIDs are the processes of the running apps named names (MatchApps).

func FrameSamples

func FrameSamples(d time.Duration) int

FrameSamples is the number of samples per channel in one frame of d.

func MatchApps

func MatchApps(apps []App, names []string) []int

MatchApps are the PIDs of apps whose name starts with one of names, in any case: "Discord" takes "Discord Helper (Renderer)" too, where an Electron app plays its sound.

func MuteOutput

func MuteOutput() (restore func() error, err error)

MuteOutput mutes the default output device and returns the call that puts its mute back as it was.

func PutPCM16

func PutPCM16(b []byte, pcm []int16) int

PutPCM16 writes pcm as little-endian bytes into b and returns their length.

Types

type App

type App struct {
	PID  int
	Name string
}

App is a running process, by its executable's name without a path or ".exe".

func RunningApps

func RunningApps() ([]App, error)

RunningApps lists processes by the name the kernel keeps for them (/proc/<pid>/comm, at most 15 characters).

type CaptureOptions

type CaptureOptions struct {
	// ExcludePIDs are more processes to leave out, such as a voice chat
	// app. The macOS process tap honours them; Windows process loopback
	// takes a single process tree, so there they are not supported
	// (CanExcludeProcesses).
	ExcludePIDs []int
	// DeviceID records what one output device plays, by Device ID, Planck
	// included, on Windows; empty, or a device that is gone, records
	// everything but Planck. macOS records every device.
	DeviceID string
}

CaptureOptions tunes desktop audio capture. Every backend leaves out Planck's own process, so the host never hears what it plays itself.

type Capturer

type Capturer interface {
	// Start begins capture and returns once the device is running. onPCM
	// receives interleaved stereo samples and the time of the first sample
	// in nanoseconds on the platform capture clock (mach absolute time on
	// macOS, QueryPerformanceCounter on Windows), the clock video frames are
	// stamped with. The stamps differ by platform: ScreenCaptureKit's lag
	// delivery by about 25ms, while WASAPI loopback reports the endpoint's
	// play-out time, about 27ms after delivery on bigboi. pcm is reused
	// after onPCM returns. Capture stops when ctx ends or Close is called.
	Start(ctx context.Context, onPCM func(pcm []int16, pts int64)) error
	Close() error
}

Capturer records what the host is playing.

func NewCapturer

func NewCapturer(opts CaptureOptions) (Capturer, error)

NewCapturer records what the host plays: the monitor of the default output device, or of opts.DeviceID when that device is there. Planck's own sound is not left out, and ExcludePIDs are not honoured.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder turns Opus packets back into 48 kHz PCM frames and conceals lost ones. It is not safe for concurrent use.

func NewDecoder

func NewDecoder(frameDuration time.Duration) (*Decoder, error)

NewDecoder makes a stereo decoder for frames of frameDuration (10ms or 20ms; zero selects DefaultFrameDuration), the length Conceal fills.

func NewDecoderChannels

func NewDecoderChannels(frameDuration time.Duration, channels int) (*Decoder, error)

NewDecoderChannels is NewDecoder for a channel count of 1 or 2.

func (*Decoder) Channels

func (d *Decoder) Channels() int

func (*Decoder) Conceal

func (d *Decoder) Conceal(pcm []int16) (int, error)

Conceal fills one frame of pcm with Opus packet-loss concealment.

func (*Decoder) Decode

func (d *Decoder) Decode(packet []byte, pcm []int16) (int, error)

Decode writes one frame into pcm, which must hold FrameSamples()*Channels() values, and returns the samples per channel written.

func (*Decoder) FrameSamples

func (d *Decoder) FrameSamples() int

type Device

type Device struct {
	// ID is stable across runs: a Core Audio UID on macOS, an MMDevice
	// endpoint ID on Windows.
	ID        string
	Name      string
	IsDefault bool
}

Device is an audio device of this machine.

func InputDevices

func InputDevices() ([]Device, error)

InputDevices lists the sound server's microphones, without the monitors of its sinks; a Device ID is a source name.

func OutputDevices

func OutputDevices() ([]Device, error)

OutputDevices lists the sound server's sinks; a Device ID is a sink name.

func PickDevice

func PickDevice(devs []Device, id string) (dev Device, gone bool)

PickDevice is the device of devs with id, or the default one when id is empty or names none of them; gone reports that id named a device that is not there. An empty Device stands for the default when devs has none marked.

type DevicePlayer added in v0.2.0

type DevicePlayer struct {
	// contains filtered or unexported fields
}

DevicePlayer plays PCM on the default output device through oto.

func NewPlayer added in v0.2.0

func NewPlayer(cfg PlayerConfig) (*DevicePlayer, error)

func (*DevicePlayer) Close added in v0.2.0

func (p *DevicePlayer) Close() error

func (*DevicePlayer) Read added in v0.2.0

func (p *DevicePlayer) Read(b []byte) (int, error)

Read is the oto source; it is not for callers.

func (*DevicePlayer) Stats added in v0.2.0

func (p *DevicePlayer) Stats() PlayerStats

func (*DevicePlayer) Write added in v0.2.0

func (p *DevicePlayer) Write(pcm []int16) error

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder turns 48 kHz PCM frames into Opus packets. By default it uses the Opus low-delay application (CELT only), which has the smallest algorithmic delay. It is not safe for concurrent use.

func NewEncoder

func NewEncoder(cfg EncoderConfig) (*Encoder, error)

func (*Encoder) Encode

func (e *Encoder) Encode(pcm []int16, packet []byte) (int, error)

Encode compresses exactly one frame (FrameSamples() times the channel count values) into packet and returns the packet length. packet should hold MaxPacketSize bytes.

func (*Encoder) FrameSamples

func (e *Encoder) FrameSamples() int

FrameSamples is the number of samples per channel Encode expects.

type EncoderConfig

type EncoderConfig struct {
	FrameDuration time.Duration // 10ms or 20ms; zero selects DefaultFrameDuration
	Bitrate       int           // bits per second; zero selects DefaultBitrate
	Channels      int           // 1 or 2; zero selects Channels
	// Voice selects the Opus VoIP application, tuned for speech, in place
	// of low delay.
	Voice bool
}

type FrameDecoder

type FrameDecoder interface {
	FrameSamples() int
	Channels() int
	Decode(packet []byte, pcm []int16) (int, error)
	Conceal(pcm []int16) (int, error)
}

FrameDecoder turns one packet into one frame of PCM, or conceals a lost one. *Decoder (Opus) and *PCMDecoder are FrameDecoders.

type JitterBuffer

type JitterBuffer struct {
	// contains filtered or unexported fields
}

JitterBuffer reorders Opus packets by sequence number and hands them out one frame per play-out tick. Its target depth grows by a frame on each underrun and shrinks by a frame after a quiet stretch, staying within [MinDepth, MaxDepth]. Push and Pop may run on different goroutines.

func NewJitterBuffer

func NewJitterBuffer(cfg JitterConfig) *JitterBuffer

func (*JitterBuffer) Pop

func (j *JitterBuffer) Pop(dst []byte) (int, PopStatus)

Pop is called once per frame duration by the play-out clock. On Packet it copies the payload into dst (which should hold MaxPacketSize bytes) and returns its length.

func (*JitterBuffer) Push

func (j *JitterBuffer) Push(seq uint16, payload []byte)

Push stores a copy of payload as packet seq.

func (*JitterBuffer) Restart

func (j *JitterBuffer) Restart()

Restart drops what is buffered; the next packet starts a new sequence, as a new stream from the same host numbers its packets afresh.

func (*JitterBuffer) Stats

func (j *JitterBuffer) Stats() JitterStats

type JitterConfig

type JitterConfig struct {
	FrameDuration time.Duration // zero selects DefaultFrameDuration
	MinDepth      time.Duration // zero selects one frame
	TargetDepth   time.Duration // starting target; zero selects 20ms
	MaxDepth      time.Duration // zero selects 40ms
}

type JitterStats

type JitterStats struct {
	Depth       time.Duration // frames queued, counting gaps, times frame duration
	Target      time.Duration
	Received    uint64
	Late        uint64 // arrived after its play-out slot
	Duplicate   uint64
	Lost        uint64 // play-out slots concealed while later packets were queued
	Underruns   uint64 // play-out slots concealed with nothing queued
	Overruns    uint64 // depth passed MaxDepth and was cut back to target
	Dropped     uint64 // packets skipped to cut depth
	Resets      uint64 // sequence jumps, either way, too large to bridge
	Concealment uint64 // Lost + Underruns
}

type MicCapturer

type MicCapturer interface {
	Start(ctx context.Context, onPCM func(pcm []int16, pts int64)) error
	Close() error
}

MicCapturer records the client's default microphone as interleaved 48 kHz mono int16. Start and Close behave as Capturer's; pts is on the same clock.

func NewMicCapturer

func NewMicCapturer() (MicCapturer, error)

NewMicCapturer records the default microphone.

func NewMicCapturerOn

func NewMicCapturerOn(id string) (MicCapturer, error)

NewMicCapturerOn records the input device with this Device ID, or the default one when id is empty or names a device that is gone.

type MicSink

type MicSink interface {
	Player
	// Device is the name of the device apps record from.
	Device() string
}

MicSink plays the client's microphone (48 kHz mono int16) into a virtual input device on the host, so voice chat and games hear it.

func OpenMicSink

func OpenMicSink(dev VirtualMic) (MicSink, error)

OpenMicSink plays mono 48 kHz PCM into dev's sink. For Planck's own virtual device it first loads module-null-sink and module-virtual-source when the server does not have them, and unloads what it loaded on Close; apps then see a microphone named "Planck Virtual Microphone".

type PCMDecoder

type PCMDecoder struct {
	// contains filtered or unexported fields
}

PCMDecoder is the FrameDecoder of the raw PCM16 mic codec. It conceals a lost frame by repeating the last one at half volume each time; Playout fades to silence after a few.

func NewPCMDecoder

func NewPCMDecoder(frameDuration time.Duration, channels int) *PCMDecoder

func (*PCMDecoder) Channels

func (d *PCMDecoder) Channels() int

func (*PCMDecoder) Conceal

func (d *PCMDecoder) Conceal(pcm []int16) (int, error)

func (*PCMDecoder) Decode

func (d *PCMDecoder) Decode(packet []byte, pcm []int16) (int, error)

func (*PCMDecoder) FrameSamples

func (d *PCMDecoder) FrameSamples() int

type Player

type Player interface {
	Write(pcm []int16) error
	Close() error
}

Player plays decoded audio on the client.

func NewOutputPlayer

func NewOutputPlayer(id string) (Player, error)

NewOutputPlayer plays on the output device with this Device ID, or with NewPlayer on the default one when id is empty, names the default, or names a device that is gone.

type PlayerConfig added in v0.2.0

type PlayerConfig struct {
	// DeviceBuffer is the device buffer oto asks the OS for (AudioQueue on
	// macOS, WASAPI shared mode on Windows). Zero selects 20ms; on an M5 Pro,
	// 10ms starved the AudioQueue, which then played audio about 6% slow.
	DeviceBuffer time.Duration
	// MaxQueue bounds audio written but not yet pulled by the device; older
	// samples are dropped past it. Zero selects 60ms.
	MaxQueue time.Duration
}

type PlayerStats added in v0.2.0

type PlayerStats struct {
	Queued  time.Duration // written but not yet handed to the OS
	Dropped uint64        // samples dropped to keep MaxQueue
}

type Playout

type Playout struct {
	// contains filtered or unexported fields
}

Playout turns a JitterBuffer and a FrameDecoder into a steady PCM stream: one frame per Next call, decoded, concealed, or silent.

func NewPlayout

func NewPlayout(jb *JitterBuffer, dec FrameDecoder) *Playout

func (*Playout) Next

func (p *Playout) Next(pcm []int16) (PopStatus, error)

Next fills pcm (FrameSamples()*Channels() values) with the next frame and returns what the jitter buffer produced for it.

type PopStatus

type PopStatus uint8

PopStatus says what a JitterBuffer.Pop produced.

const (
	// Buffering: the buffer is filling to its target depth; play silence.
	Buffering PopStatus = iota
	// Packet: the next packet in sequence was copied out.
	Packet
	// Missing: the next packet has not arrived; conceal one frame.
	Missing
)

type VirtualAudioStatus

type VirtualAudioStatus struct {
	// Installed: the Planck Virtual Audio driver is installed, whether or
	// not its device is running.
	Installed bool
	// Active: a Planck Virtual Audio device is running now.
	Active bool
	// DeviceName is the output device Auto picks, "" when there is none.
	DeviceName string
	// DriverName is the virtual audio driver behind DeviceName, as
	// "Planck Virtual Audio" or "Steam Streaming Microphone".
	DriverName string
	// InstallHint says how to get Planck Virtual Audio running; "" when
	// it is.
	InstallHint string
}

VirtualAudioStatus is whether Planck Virtual Audio is on this machine, and which virtual mic a host on Auto plays a client's microphone into.

func VirtualAudio

func VirtualAudio() (VirtualAudioStatus, error)

VirtualAudio reports Planck Virtual Audio's driver and device, and the virtual mic Auto would use.

type VirtualMic

type VirtualMic struct {
	ID    string
	Name  string
	Input string
	// contains filtered or unexported fields
}

VirtualMic is a user-installed virtual audio device: Planck writes to its playback side (ID, Name) and apps record from its input side (Input).

func FindVirtualMic

func FindVirtualMic(want string) (VirtualMic, error)

FindVirtualMic looks for a virtual input device among the output devices: the one whose ID is want or whose name contains it, or a known one when want is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL