pluginapi

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: AGPL-3.0 Imports: 20 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 pluginapi defines the local interfaces used by platform adapters. A host or desktop runner supplies these services and mounts the adapter's MyGo windows.

Package pluginapi defines contracts used by music platform plugins and their host.

Index

Constants

View Source
const SpectrumBands = 24

SpectrumBands is the number of frequency bands sampled during playback.

Variables

View Source
var ErrQueueFeedUnavailable = errors.New("queue feed unavailable")
View Source
var ErrUnavailable = errors.New("this song isn't available to stream")

ErrUnavailable indicates that the service cannot stream a track.

View Source
var Levels = []string{"standard", "higher", "exhigh", "lossless", "hires"}

Levels are the legacy playback quality identifiers, from the lowest.

Functions

func ArtworkURL

func ArtworkURL(instance ID, ref string) string

ArtworkURL gives an opaque provider reference an instance-specific cache key.

func BindSettings

func BindSettings[T any](store SettingsStore, defaults T) (*T, func())

BindSettings loads the caller's schema over its defaults and returns a callback that saves the same value after changes.

func PlayPagedList

func PlayPagedList(player PlayerPort, pages *paging.Pager[Track], index int)

PlayPagedList starts at the selected item and asks the pager for the remaining pages. The cursor advances only after the host accepts a batch.

func PlaybackLoadingText

func PlaybackLoadingText(p PlaybackControls) string

PlaybackLoadingText describes preparation if the host provides more detail.

func RecordSearch

func RecordSearch(history []string, query string) []string

RecordSearch moves the submitted query to the front and keeps up to 20 entries.

func Retry

func Retry(ctx context.Context, delays []time.Duration, run func(context.Context) error) error

Retry runs an operation at the plugin's chosen delays until it succeeds or its activation ends. A delay applies before the corresponding attempt.

Types

type Activation

type Activation struct {
	Context   context.Context
	Main      *mygo.Window
	ColdStart bool
}

Activation is sent when the plugin's native windows are ready.

type Adapter

type Adapter interface {
	Configured() bool
	// FetchArtwork reports whether this plugin recognized the resource reference.
	FetchArtwork(ctx context.Context, ref string, size int) (data []byte, handled bool, err error)
	PlaybackMedia() PlaybackMedia
	OwnsTrack(*Track) bool
}

Adapter describes the status and media that the host routes between plugins and services.

type Album

type Album struct {
	ID     int64  `json:"id"`
	Name   string `json:"name"`
	PicURL string `json:"picUrl"`
}

type Artist

type Artist struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

type Audio

type Audio interface {
	SampleRate() int
	Channels() int
	Read(dst []float32) (int, error)
	// SetPosition goes to a frame, of SampleRate a second.
	SetPosition(frame int64) error
	Close() error
}

Audio decodes a second copy of the current track. Read returns interleaved PCM at SampleRate frames per second.

type AudioDevice

type AudioDevice struct {
	Name        string
	Description string
}

type AudioPreferences

type AudioPreferences struct {
	Quality   string
	Normalize bool
}

AudioPreferences describes the stream quality and normalization selected by the plugin that owns the active playback controls.

type CastingDevice

type CastingDevice struct {
	ID, Name string
}

type CastingState

type CastingState struct {
	Available, Sending, Scanning bool
	Devices                      []CastingDevice
	Active                       *CastingDevice
	ScanTask, OutputTask         DesktopTask
}

type ChartLine

type ChartLine struct {
	First  string `json:"first"`
	Second string `json:"second"`
}

ChartLine is a song at the top of a chart: its name and its artist.

type Comment

type Comment struct {
	ID   int64 `json:"commentId"`
	User struct {
		ID        int64  `json:"userId"`
		Nickname  string `json:"nickname"`
		AvatarURL string `json:"avatarUrl"`
	} `json:"user"`
	Content    string `json:"content"`
	Time       int64  `json:"time"` // Unix milliseconds
	LikedCount int    `json:"likedCount"`
	Liked      bool   `json:"liked"` // by the listener signed in
	IPLocation struct {
		Location string `json:"location"`
	} `json:"ipLocation"`
	// BeReplied holds the comment this one replies to.
	BeReplied []struct {
		User struct {
			Nickname string `json:"nickname"`
		} `json:"user"`
		Content string `json:"content"`
	} `json:"beReplied"`
}

Comment is what a listener wrote about a song or an episode.

type Comments

type Comments struct {
	// Hot are the comments most liked, on the first page only.
	Hot    []Comment `json:"hotComments"`
	Latest []Comment `json:"comments"`
	Total  int       `json:"total"`
	More   bool      `json:"more"`
}

Comments are a page of a song's or an episode's comments.

type ContentDigest

type ContentDigest struct {
	Algorithm string
	Sum       []byte
}

ContentDigest identifies the exact bytes announced by a media provider.

func (ContentDigest) Matches

func (d ContentDigest) Matches(r io.Reader) bool

type DecodedArtwork

type DecodedArtwork interface {
	Bitmap() *ui.Bitmap
	Blurred() *ui.Bitmap
	Tint() ui.Color
	Failed() bool
}

DecodedArtwork keeps the cover and its blurred bitmap alive while displayed.

type DecoderStatus

type DecoderStatus struct {
	Ready                    bool
	Downloaded               bool
	Downloading              bool
	SystemPath               string
	Done, Total              int64
	Devices                  []AudioDevice
	DownloadTask, DeleteTask DesktopTask
}

func (DecoderStatus) LatestTask

func (s DecoderStatus) LatestTask() DesktopTask

type DesktopLyricsPreferences

type DesktopLyricsPreferences struct {
	Locked          bool    `json:"locked,omitempty"`
	ShowTranslation bool    `json:"showTranslation"`
	FontSize        float32 `json:"fontSize,omitempty"`
	Color           int     `json:"color,omitempty"`
	X               int     `json:"x,omitempty"`
	Y               int     `json:"y,omitempty"`
	PositionSet     bool    `json:"positionSet,omitempty"`
}

DesktopLyricsPreferences are the desktop lyric window's persistent choices. A pointer in settings keeps older settings files compatible: missing desktop-lyrics data gets the current defaults on first use.

func DefaultDesktopLyricsPreferences

func DefaultDesktopLyricsPreferences() DesktopLyricsPreferences

type DesktopLyricsState

type DesktopLyricsState struct {
	Locked, PointerInside, ShowTranslation bool
	FontSize                               float32
	Color                                  int
}

type DesktopPlaybackServices

type DesktopPlaybackServices interface {
	Playback() PlaybackControls
	Volume() float64
	SetVolume(float64)
	Presentation() Presentation
	SetLyricsPresentation(stage bool, style string, sparks bool)
	DecodedArtwork(url string, size int, blurred bool) DecodedArtwork
	SetMainWindowButtonsTheme(mygo.ThemeSource)
	DesktopLyricsVisible() bool
	ToggleDesktopLyrics()
	DesktopLyricsLocked() bool
	ToggleDesktopLyricsLock()
	DesktopLyricsState() DesktopLyricsState
	SetDesktopLyricsStyle(translation bool, size float32, color int)
	HideDesktopLyrics()
	Casting() CastingState
	ScanCastingDevices()
	SwitchPlaybackOutput(string)
	EqualizerAvailable() bool
	EqualizerSettings() eq.Settings
	ApplyEqualizer(eq.Settings)
}

DesktopPlaybackServices connects playback to a plugin's window.

type DesktopPreferences

type DesktopPreferences struct {
	Appearance    string
	AppIcon       string
	CacheMB       int
	Notch         bool
	NotchActivity bool
	NotchVirtual  bool
	Smoke         bool
	Fog           bool

	UseMPV         bool
	MPVExclusive   bool
	MPVGapless     bool
	MPVAudioDevice string
}

DesktopPreferences are application-wide settings used by the active plugin.

type DesktopServices

type DesktopServices interface {
	DesktopSettings() DesktopSettings
	ApplyDesktopPreferences(DesktopPreferences)
	ClearAudioCache()
	DecoderStatus() DecoderStatus
	StartDecoderDownload()
	CancelDecoderDownload()
	DeleteDecoder()
	SetUpdateChecks(bool)
	SetUpdateDownloads(bool)
	CheckForUpdates()
}

DesktopServices reads and applies settings without drawing any controls.

type DesktopSettings

type DesktopSettings struct {
	Preferences     DesktopPreferences
	CacheUsed       int64
	NotchAvailable  bool
	Updates         bool
	UpdateChecks    bool
	UpdateDownloads bool
	LastUpdateCheck time.Time
	CacheTask       DesktopTask
}

type DesktopTask

type DesktopTask = protocol.DesktopTask

type ID

type ID string

ID identifies a registered platform instance.

func ArtworkOwner

func ArtworkOwner(raw string) (instance ID, ref string, ok bool)

ArtworkOwner resolves a scoped reference; the outer query holds display options.

type Info

type Info struct {
	ID   ID
	Name string
	// Icon is supplied by the plugin for display by the host.
	Icon *ui.SVG
}

Info is a platform's identity presented by the host.

type Lifecycle

type Lifecycle struct {
	// Activate supplies the context and playback session access for this
	// activation. The host cancels the context before calling Deactivate.
	Activate        func(context.Context, PlaybackContinuity)
	Ready           func(Activation)
	Deactivate      func(switchingPlatform bool)
	MainFocused     func()
	PlaybackChanged func()
}

Lifecycle handles entry to and departure from the active platform.

type MenuBarPanel struct {
	CameraHousing   func() (width, height float64, present bool)
	MenuBarHeight   func() float64
	Raise           func(handle uintptr)
	Pin             func(handle uintptr, width, height float64)
	WatchPointer    func(func()) (stop func(), global bool)
	Preferences     func() QuickPlayerPreferences
	SavePreferences func(QuickPlayerPreferences)
}

MenuBarPanel provides access to native display geometry and pointer events.

type MenuID string
const (
	ApplicationMenu MenuID = "application"
	TrayMenu        MenuID = "tray"
)

type PlatformPlaylist

type PlatformPlaylist struct {
	Ref  string `json:"-"`
	Kind string `json:"-"`
	Sub  string `json:"-"`
}

type PlatformStream

type PlatformStream struct {
	Header func() http.Header `json:"-"`
	Renew  network.MediaRenew `json:"-"`
}

type PlatformTrack

type PlatformTrack struct {
	Source  string `json:"src,omitempty"`
	Ref     string `json:"ref,omitempty"`
	Format  string `json:"fmt,omitempty"`
	Cue     bool   `json:"cue,omitempty"`
	Fav     bool   `json:"fav,omitempty"`
	DiscNo  int    `json:"disc,omitempty"`
	TrackNo int    `json:"no,omitempty"`
}

type PlaybackContinuity

type PlaybackContinuity interface {
	LoadSession() (PlaybackSession, bool)
	Restore(PlaybackSession)
	RadioFrom(string, []Track, QueueFeed)
	AttachRadio(string, QueueFeed)
	OpenAudio() (Audio, error)
}

PlaybackContinuity provides paused queue restoration, resumable radio queues, and independent decoding for features such as transcription. Use it on the application thread during the activation that supplied it.

type PlaybackControls

type PlaybackControls interface {
	Current() *Track
	Playing() bool
	Loading() bool
	Ready() bool
	Err() string
	Position() time.Duration
	Duration() time.Duration
	Downloaded() (float64, bool)
	TogglePlay()
	Prev()
	Next()
	Seek(time.Duration)
	Shuffle() bool
	ToggleShuffle()
	Repeat() RepeatMode
	CycleRepeat()
	Queue() []Track
	PlayOrder() ([]int, int)
	Jump(int)
	Lyrics() ([]lyrics.Line, bool)
	Stream() *Stream
	Levels() ([SpectrumBands]float32, bool)
	Radio() string
	EndRadio()
}

PlaybackControls is the audio engine's state and commands.

type PlaybackMedia

type PlaybackMedia struct {
	Preferences func() AudioPreferences
	Stream      func(context.Context, *Track, string) (*Stream, error)
	Cover       func(context.Context, *Track) ([]byte, error)
	Lyrics      func(context.Context, *Track) (string, string, string, error)
	Started     func(*Track)

	// CastSource optionally requests an output-specific source. An empty format
	// asks for any custom source selected by the platform preferences. Returning
	// no source lets the host use the normal URL, or report that a requested
	// compatible format is unavailable. The host does not encode audio.
	CastSource func(context.Context, *Track, string) (*Stream, SegmentedSource, error)

	// ErrorMessage optionally describes a failed stream in the platform's terms.
	ErrorMessage func(*Track, error) string

	// Segments is optional. A nil source and nil error use the ordinary stream path.
	// Advanced reports whether the current output accepts formats beyond the built-in decoder.
	Segments func(ctx context.Context, track *Track, advanced bool) (*Stream, SegmentedSource, error)
}

PlaybackMedia describes how a platform serves its own tracks.

type PlaybackSession

type PlaybackSession struct {
	Queue    []Track    `json:"queue"`
	Order    []int      `json:"order"`
	At       int        `json:"at"`
	Shuffle  bool       `json:"shuffle"`
	Repeat   RepeatMode `json:"repeat"`
	Position int64      `json:"position"` // milliseconds
	Radio    string     `json:"radio,omitempty"`
}

PlaybackSession persists the queue and its paused playback position.

func (PlaybackSession) ValidQueue

func (s PlaybackSession) ValidQueue() bool

ValidQueue reports whether the session identifies a current track in a complete play order.

type PlayerPort

type PlayerPort interface {
	Current() *Track
	Playing() bool
	Loading() bool
	Err() string
	TogglePlay()
	Next()
	Queue() []Track
	PlayOrder() ([]int, int)
	PlayQueue([]Track, int)
	AppendQueue([]Track)
	PlayList([]Track, int, QueueFeed)
	PlayRadio(string, []Track, QueueFeed)
	EndRadio()
	Radio() string
	SetShuffle(bool)
}

type Playlist

type Playlist struct {
	PlatformPlaylist
	ID          int64   `json:"id"`
	Name        string  `json:"name"`
	CoverURL    string  `json:"coverImgUrl"`
	PicURL      string  `json:"picUrl"`
	Description string  `json:"description"`
	PlayCount   float64 `json:"playCount"`
	TrackCount  int     `json:"trackCount"`
	UpdateFreq  string  `json:"updateFrequency"`
	SpecialType int     `json:"specialType"` // 5: the listener's liked songs
	Privacy     int     `json:"privacy"`     // 10: only its creator sees it
	Subscribed  bool    `json:"subscribed"`  // the listener saved it
	Creator     struct {
		UserID   int64  `json:"userId"`
		Nickname string `json:"nickname"`
	} `json:"creator"`
	Tracks   []Track `json:"tracks"`
	TrackIDs []struct {
		ID int64 `json:"id"`
	} `json:"trackIds"`
	// Preview holds a chart's top songs, as its card shows them.
	Preview []ChartLine `json:"-"`
}

func (*Playlist) Cover

func (p *Playlist) Cover() string

type Presentation

type Presentation struct {
	Smoke, Fog, LyricsStage, StageSparks bool
	StageStyle                           string
}

type Privilege

type Privilege struct {
	ID int64 `json:"id"`
	St int   `json:"st"` // below 0: taken down
	Pl int   `json:"pl"` // the best bit rate the listener may play; 0 for none
}

Privilege is what NetEase lets the listener signed in, or nobody, do with a track.

type QueueFeed

type QueueFeed func(context.Context, QueueFeedCursor, func([]Track, error))

QueueFeed calls done on the UI thread. An empty successful batch ends a list. A failed batch can be requested again at the same cursor.

func ShuffledQueueFeed

func ShuffledQueueFeed(pages *paging.Pager[Track], order []int, seed int64) QueueFeed

ShuffledQueueFeed builds each batch from two pages in the supplied order. The seed and cursor let a retry reproduce the same order after a failure.

type QueueFeedCursor

type QueueFeedCursor struct {
	Page            uint64
	FirstID, LastID int64
}

QueueFeedCursor identifies the next batch and the host's current queue edges.

type QuickPlayerPreferences

type QuickPlayerPreferences struct {
	Enabled, Activity, Virtual, Greeted bool
}

type Registration

type Registration struct {
	Info
	Start func(Startup) Adapter
	// LegacySettingsKey keeps a former top-level namespace in the same place.
	LegacySettingsKey string
	// LegacySettingsFields keeps selected fields at the root of the old settings file.
	LegacySettingsFields []string
}

Registration supplies the entry point for a platform instance.

type RepeatMode

type RepeatMode int
const (
	RepeatOff RepeatMode = iota
	RepeatAll
	RepeatOne
)

type SegmentedSource

type SegmentedSource interface {
	SegmentCount() int
	SegmentDuration(int) time.Duration
	TotalDuration() time.Duration
	FetchSegment(context.Context, int) ([]byte, error)
	Close()
}

SegmentedSource supplies encoded audio while the engine handles decoding and seeking.

type Services

type Services interface {
	DesktopServices
	DesktopPlaybackServices
	Post(func())
	Invalidate()
	CurrentPlatform() ID
	ShowMain()
	OpenSettings()
	CloseSettings()
	Toast(string)
	TakeToast() string
	Player() PlayerPort
	Artwork(url string, size int) (*ui.Bitmap, bool)
	PlaybackLevels() ([SpectrumBands]float32, bool)
	CopyText(string)
	GlobalSearchHistory() []string
	RememberGlobalSearch(string)
	ClearSearchHistory()
}

Services provides desktop and media operations to window-owning plugins.

type SettingsStore

type SettingsStore interface {
	// Load overlays stored data on the caller's defaults during Start.
	Load(dst any) error
	// Save captures a snapshot before returning. During normal desktop
	// operation the host writes it on the main thread.
	Save(src any) error
}

SettingsStore loads and saves a plugin's serializable preferences in its own namespace. Credentials have a separate store.

type Startup

type Startup struct {
	Host              Services
	Settings          SettingsStore
	RegisterWindow    func(WindowID, Window)
	RegisterMenu      func(MenuID, func() *mygo.Menu)
	RegisterLifecycle func(Lifecycle)
	MenuBarPanel      *MenuBarPanel
}

Startup hands the host services to a platform's entry point.

type Stream

type Stream struct {
	PlatformStream
	URL  string `json:"-"`
	Size int64  `json:"size"` // in bytes
	// VerifyCachedContent is optional. It checks the bytes against an exact
	// content digest supplied by the service for this stream.
	VerifyCachedContent func(io.Reader) bool `json:"-"`
	Digest              *ContentDigest       `json:"-"`
	// Type is the format: mp3, or flac for the lossless levels.
	Type string `json:"type"`
	// Level is the level served, which may be below the one asked for.
	Level string `json:"level"`
	// Gain is how many dB to change the track by to sound as loud as
	// others, and Peak its loudest sample, 1 at full scale, or 0 if
	// unknown.
	Gain float64 `json:"gain"`
	Peak float64 `json:"peak"`
}

Stream is where a track streams from, and what it is.

type Track

type Track struct {
	PlatformTrack
	ID       int64    `json:"id"`
	Name     string   `json:"name"`
	Artists  []Artist `json:"ar"`
	Album    Album    `json:"al"`
	Duration int64    `json:"dt"` // milliseconds
	Fee      int      `json:"fee"`
	Alias    []string `json:"alia"`
	// Reason says why a daily recommendation was picked.
	Reason string `json:"reason"`
	// Privilege is what the listener may do with the track, if known.
	Privilege *Privilege `json:"privilege"`
	// A podcast's episode plays as a track of its audio, ID, with the
	// episode's ProgramID, the PodcastID it is in, and what it is about.
	ProgramID   int64  `json:"programId,omitempty"`
	PodcastID   int64  `json:"podcastId,omitempty"`
	Description string `json:"description,omitempty"`
}

func (*Track) ArtistNames

func (t *Track) ArtistNames() string

ArtistNames joins the track's artists as the credits read.

func (*Track) Length

func (t *Track) Length() time.Duration

func (*Track) Playable

func (t *Track) Playable() bool

Playable reports whether the listener can play the whole track: as their privilege says, or else as its fee does for anyone, VIP songs (1) and paid albums (4) giving only a preview.

type Window

type Window struct {
	Options mygo.WindowOptions
	Root    func(*ui.Context)
	// Mount connects a separately managed window to its controller.
	// The returned function releases subscriptions before the window closes.
	Mount   func(*mygo.Window) func()
	Updated func()
}

Window is a complete native window supplied by a plugin.

type WindowID

type WindowID string
const (
	MainWindow          WindowID = "main"
	SettingsWindow      WindowID = "settings"
	DesktopLyricsWindow WindowID = "desktop-lyrics"
	QuickPlayerWindow   WindowID = "quick-player"
)

Directories

Path Synopsis
Package artwork decodes covers and derives the color and low-resolution backdrop.
Package artwork decodes covers and derives the color and low-resolution backdrop.
Package eq holds the graphic equalizer's curves and settings, its presets, and the AutoEQ headphone profiles.
Package eq holds the graphic equalizer's curves and settings, its presets, and the AutoEQ headphone profiles.
Package storage provides instance-scoped paths and credentials for music plugins.
Package storage provides instance-scoped paths and credentials for music plugins.

Jump to

Keyboard shortcuts

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