feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+4 -5
View File
@@ -1,5 +1,4 @@
dist/ /build/
.DS_Store /.mygo/
*.apk /dist/
*.aab mygo_windows_*.syso
*.jks
-11
View File
@@ -1,11 +0,0 @@
{
"name": "OpenChamber",
"id": "com.openchamber.native",
"version": "0.2.2",
"build": 16,
"orientations": [
"portrait",
"landscape"
],
"icon": "assets/icon.png"
}
+17 -4
View File
@@ -1,13 +1,26 @@
module github.com/openchamber/openchamber-native module github.com/openchamber/openchamber-native
go 1.26.3 go 1.27.4
tool github.com/egoist/mygo/cmd/mygo
require ( require (
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66 github.com/egoist/mygo v0.10.0
golang.org/x/net v0.62.0 golang.org/x/net v0.59.0
) )
require ( require (
github.com/ebitengine/purego v0.11.2 // indirect github.com/ProtonMail/go-crypto v1.4.1 // indirect
github.com/cloudflare/circl v1.6.2 // indirect
github.com/ebitengine/purego v0.11.1 // indirect
github.com/go-text/typesetting v0.3.5 // indirect
github.com/klauspost/compress v1.18.6 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
go.digitalxero.dev/rpm v0.3.4 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/image v0.46.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.43.0 // indirect golang.org/x/text v0.43.0 // indirect
) )
replace github.com/egoist/mygo => ./third_party/mygo
+32 -14
View File
@@ -1,16 +1,34 @@
github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU= github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66 h1:jhKkamv03qrVjkWGz0vmZtWVoX1sXBF/xOCuG0vNQOc= github.com/cloudflare/circl v1.6.2 h1:hL7VBpHHKzrV5WTfHCaBsgx/HGbBYlgrwvNXEVDYYsQ=
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66/go.mod h1:BDM4nmtZiJ7SqoPnagKW2z5vHAus2Y4Mllg0NtBaKVo= github.com/cloudflare/circl v1.6.2/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= github.com/go-text/typesetting v0.3.5/go.mod h1:XZO1hD+nQVyvVa5IicQk7FsCa4PFQaJ2soWAP1f//68=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc h1:8FGo2It5K75XkavhTiCKExUfVaVDS1feBnLCru5qeoY=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
go.digitalxero.dev/rpm v0.3.4 h1:iq+rx7zB6wQeNhLQ1mcvW92v9ZqNaxCvuu0+nPVit4w=
go.digitalxero.dev/rpm v0.3.4/go.mod h1:45EsEzHamzqInyWQx9vpj7OYpL0BrkbQF87VdrLn5wo=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+478
View File
@@ -0,0 +1,478 @@
// Package appui is the MyGo client: the windows, screens and state of the
// OpenChamber app.
package appui
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/storage"
)
// App is the whole application's state. Its view functions build the
// windows' interfaces from it, on the main thread, whenever a frame is
// needed.
type App struct {
store storage.Store
// Windows.
win *mygo.Window // the root window: servers or sessions
chatWin *mygo.Window // the pushed chat window, when a session is open
// The active connection.
client *ocapi.Client
conn storage.Connection
busy bool // a connect is in progress
// Server list / connect form state.
phase string // "" = disconnected, "form" = editing/adding, else connected
formTitle string
formLabel string
formURL string
formProxy string
formInsecure bool
formFinger string
formPassword string
formEditing *storage.Connection
formError string
// Sessions list state.
sessions []ocapi.Session
sessionsCursor string
sessionsLoad bool
searchOpen bool
searchText string
searchTimer *time.Timer
errorText string
// Live state from the event stream.
active map[string]bool
perms []ocapi.PermissionRequest
// The open chat, if any.
chat *chat
sessionListState ui.ListState
instancesOpen bool
serverActionOpen *bool
serverActionTarget *storage.Connection
confirmDelete bool
deleteTarget *storage.Connection
// Session list sheet state.
newOpen bool
newTitle string
sessionActionOpen bool
sessionActionTarget ocapi.Session
renameOpen bool
renameTarget ocapi.Session
renameText string
sessionDeleteOpen bool
sessionDeleteTarget *ocapi.Session
// Tables the UI needs on the main thread.
modelNames map[string]string
// The event stream.
streamCancel context.CancelFunc
}
// New makes the app. Call it before mygo.App.Run. A nil store makes the
// persistent store on Ready, once the app can name its data directory.
func New(store storage.Store) *App {
if store == nil {
store = &lazyStore{}
}
return &App{
store: store,
active: map[string]bool{},
modelNames: map[string]string{},
}
}
// lazyStore creates the persistent store on first use, on the main thread.
type lazyStore struct{ s storage.Store }
func (l *lazyStore) get() storage.Store {
if l.s == nil {
l.s = storage.New()
}
return l.s
}
func (l *lazyStore) Connections() []storage.Connection { return l.get().Connections() }
func (l *lazyStore) SaveConnections(c []storage.Connection) { l.get().SaveConnections(c) }
func (l *lazyStore) InstallID() string { return l.get().InstallID() }
func (l *lazyStore) LoadToken(c storage.Connection) (string, bool, error) {
return l.get().LoadToken(c)
}
func (l *lazyStore) SaveToken(id, token string) error { return l.get().SaveToken(id, token) }
func (l *lazyStore) ClearToken(c storage.Connection) error { return l.get().ClearToken(c) }
// Ready runs when the app is ready (mygo.App.WhenReady): it makes the root
// window and reconnects to the most recently used server.
func (a *App) Ready() {
a.win = mygo.NewWindow(mygo.WindowOptions{
Title: "OpenChamber",
Content: ui.View(a.view),
})
a.reconnectLast()
}
// view is the root window's interface: the server list when disconnected,
// the sessions list when connected.
func (a *App) view(c *ui.Context) {
if a.client == nil {
a.serversView(c)
return
}
a.sessionsView(c)
}
// post runs fn on the main thread and redraws the root window.
func (a *App) post(fn func()) {
if a.win != nil {
a.win.Update(fn)
}
}
// chatPost runs fn on the main thread and redraws the chat window.
func (a *App) chatPost(fn func()) {
if a.chat != nil && a.chatWin != nil {
a.chatWin.Update(fn)
return
}
a.post(fn)
}
func (a *App) reconnectLast() {
conns := a.store.Connections()
if len(conns) == 0 {
return
}
conn := conns[0]
a.connectTo(conn, "", true)
}
// connectTo builds a client for conn and authenticates. When password is
// empty it tries the saved device token first. Silent connections (the
// recent server on startup) show errors in the server list instead of a
// modal form.
func (a *App) connectTo(conn storage.Connection, password string, silent bool) {
if a.busy {
return
}
a.busy = true
a.errorText = ""
go func() {
client, err := ocapi.New(conn.URL, ocapi.Options{
Proxy: conn.Proxy,
InsecureSkipVerify: conn.Insecure,
CertFingerprint: conn.Fingerprint,
Timeout: 20 * time.Second,
})
if err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, silent, friendlyError(err))
})
return
}
token, ok, err := a.store.LoadToken(conn)
if err == nil && !ok {
// No saved token: a passwordless server needs none. Probe it.
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
st, serr := client.SessionStatus(ctx)
cancel()
if serr == nil && st.Disabled && !st.Locked {
a.post(func() {
a.busy = false
a.connected(client, conn, silent)
})
return
}
}
if err != nil || (!ok && password == "") {
if ok {
err = fmt.Errorf("无法读取已保存的凭据")
}
if err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, silent, friendlyError(err))
})
return
}
// Needs a password: ask in the form.
a.post(func() {
a.busy = false
a.promptPassword(conn)
})
return
}
if ok {
client.SetToken(token)
if err := a.verifyConnection(client); err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, silent, friendlyError(err))
})
return
}
a.post(func() { a.connected(client, conn, silent) })
return
}
// Login with the password the form gave.
res, err := client.Login(context.Background(), ocapi.LoginRequest{
Password: password,
DedupeKey: a.store.InstallID(),
ClientLabel: "OpenChamber Native",
ClientKind: "mobile",
DevicePlatform: "android",
})
if err != nil {
a.post(func() {
a.busy = false
a.failConnect(conn, false, friendlyError(err))
})
return
}
if res.ClientToken == "" {
a.post(func() {
a.busy = false
a.failConnect(conn, false, "登录成功但没有返回令牌")
})
return
}
client.SetToken(res.ClientToken)
if err := a.store.SaveToken(conn.ID, res.ClientToken); err != nil {
log.Printf("appui: save token: %v", err)
}
a.post(func() {
a.busy = false
a.connected(client, conn, silent)
})
}()
}
// verifyConnection checks the device token is accepted.
func (a *App) verifyConnection(client *ocapi.Client) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
st, err := client.SessionStatus(ctx)
if err != nil {
return err
}
if !st.Authenticated {
return fmt.Errorf("已保存的凭据已失效,请重新登录")
}
return nil
}
// connected switches to the sessions list and starts the event stream.
func (a *App) connected(client *ocapi.Client, conn storage.Connection, silent bool) {
a.client = client
a.conn = conn
a.phase = "connected"
conns := a.store.Connections()
found := false
for i := range conns {
if conns[i].ID == conn.ID {
conns[i].LastUsedAt = time.Now().UnixMilli()
found = true
break
}
}
if !found {
conn.LastUsedAt = time.Now().UnixMilli()
conns = append([]storage.Connection{conn}, conns...)
}
a.store.SaveConnections(conns)
a.startStream()
a.loadSessions()
a.loadActive()
a.loadPerms()
a.loadModels()
}
// failConnect surfaces a connect error: the connect form when not silent.
func (a *App) failConnect(conn storage.Connection, silent bool, msg string) {
a.client = nil
a.conn = storage.Connection{}
a.phase = ""
if silent {
a.errorText = fmt.Sprintf("无法连接 %s:%s", conn.Label, msg)
} else {
a.promptPassword(conn)
a.formError = msg
}
}
// promptPassword shows the connect form for conn with its password field.
func (a *App) promptPassword(conn storage.Connection) {
a.phase = "form"
a.formEditing = &conn
a.formTitle = "连接 " + conn.Label
a.formLabel = conn.Label
a.formURL = conn.URL
a.formProxy = conn.Proxy
a.formInsecure = conn.Insecure
a.formFinger = conn.Fingerprint
a.formPassword = ""
a.formError = ""
}
// disconnect drops the connection and returns to the server list.
func (a *App) disconnect() {
a.stopStream()
a.client = nil
a.conn = storage.Connection{}
a.phase = ""
a.sessions = nil
a.errorText = ""
if a.chat != nil {
a.closeChat()
}
}
// ---------------------------------------------------------------- sessions
func (a *App) loadSessions() {
if a.client == nil {
return
}
a.sessionsLoad = true
go func() {
page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{
Limit: 50,
Order: "desc",
})
a.post(func() {
a.sessionsLoad = false
if err != nil {
a.errorText = friendlyError(err)
return
}
a.sessions = page.Data
a.sessionsCursor = page.Cursor.Next
})
}()
}
func (a *App) searchSessions(q string) {
if a.client == nil {
return
}
a.sessionsLoad = true
dir := ""
if len(a.sessions) > 0 && a.sessions[0].Location != nil {
dir = a.sessions[0].Location.Directory
}
go func() {
page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{
Limit: 50, Order: "desc", Search: q, Directory: dir,
})
a.post(func() {
a.sessionsLoad = false
if err != nil {
return
}
a.sessions = page.Data
})
}()
}
func (a *App) loadActive() {
go func() {
m, err := a.client.ActiveSessions(context.Background())
a.post(func() {
if err != nil {
return
}
next := map[string]bool{}
for id := range m {
next[id] = true
}
a.active = next
})
}()
}
func (a *App) loadPerms() {
go func() {
list, err := a.client.PendingPermissions(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
a.perms = list
})
}()
}
func (a *App) loadModels() {
go func() {
models, err := a.client.Models(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
names := map[string]string{}
for _, m := range models {
name := m.Name
if name == "" {
name = m.ID
}
names[m.ProviderID+"/"+m.ID] = name
names[m.ID] = name
}
a.modelNames = names
})
}()
}
func (a *App) dir() string {
if len(a.sessions) > 0 && a.sessions[0].Location != nil {
return a.sessions[0].Location.Directory
}
if a.chat != nil {
return a.chat.dir
}
return ""
}
func (a *App) modelName(m *ocapi.ModelRef) string {
if m == nil {
return ""
}
if name := a.modelNames[m.ProviderID+"/"+m.ID]; name != "" {
return name
}
if name := a.modelNames[m.ID]; name != "" {
return name
}
return m.ID
}
func friendlyError(err error) string {
if err == nil {
return ""
}
msg := err.Error()
msg = strings.TrimSpace(msg)
if msg == "" {
return "请求失败"
}
if len(msg) > 300 {
msg = msg[:300] + "…"
}
return msg
}
+64
View File
@@ -0,0 +1,64 @@
package appui
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/openchamber/openchamber-native/internal/storage"
)
// memStore is a Store that keeps its values in memory, for tests.
type memStore struct {
conns []storage.Connection
installID string
tokens map[string]string
}
func (m *memStore) Connections() []storage.Connection { return m.conns }
func (m *memStore) SaveConnections(c []storage.Connection) { m.conns = c }
func (m *memStore) InstallID() string {
if m.installID == "" {
m.installID = "test-install"
}
return m.installID
}
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
if t, ok := m.tokens[c.ID]; ok {
return t, true, nil
}
return "", false, nil
}
func (m *memStore) SaveToken(id, token string) error {
if m.tokens == nil {
m.tokens = map[string]string{}
}
m.tokens[id] = token
return nil
}
func (m *memStore) ClearToken(c storage.Connection) error {
delete(m.tokens, c.ID)
return nil
}
// TestServersViewRenders mounts the disconnected first screen.
func TestServersViewRenders(t *testing.T) {
a := New(&memStore{})
tt := ui.NewTester(a.view, 400, 800)
if !tt.HasText("OpenChamber") {
t.Fatalf("servers view missing title: %q", tt.Texts())
}
if !tt.HasText("添加服务器") {
t.Fatalf("servers view missing add button: %q", tt.Texts())
}
}
// TestServersViewListsSaved mounts with one saved server.
func TestServersViewListsSaved(t *testing.T) {
a := New(&memStore{conns: []storage.Connection{
{ID: "s1", Label: "Home", URL: "http://10.0.0.2:3000"},
}})
tt := ui.NewTester(a.view, 400, 800)
if !tt.HasText("Home") || !tt.HasText("http://10.0.0.2:3000") {
t.Fatalf("saved server not shown: %q", tt.Texts())
}
}
+22 -174
View File
@@ -9,180 +9,17 @@ import (
"strings" "strings"
"time" "time"
"github.com/egoist/asuka/colors" "github.com/egoist/mygo"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/sdk/device"
"github.com/egoist/asuka/sdk/store"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
) )
// maxAttachmentBytes bounds one file: prompts carry their files inline, and // keepImage copies a picked image into the app's data directory so the sent
// a huge photo would make the send slow and may exceed what the server // message can show it inline after a reload clears the picker's copy.
// accepts.
const maxAttachmentBytes = 10 << 20
// attachment is a picked file waiting to ride with the next prompt.
type attachment struct {
Name string
MIME string
DataURL string
Size int64
LocalPath string // a copy in the app's data dir, for inline preview
}
func (ch *chat) attachMenu() {
ui.Alert(ui.AlertProps{
Title: "添加附件",
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("照片"), Icon: "photo", OnPress: ch.pickPhotos},
{Title: ui.Val("文件"), Icon: ui.IconFolder, OnPress: ch.pickFiles},
{Title: ui.Val("取消"), Role: ui.ActionCancel},
},
})
}
func (ch *chat) pickPhotos() {
ch.attaching.Set(true)
device.PickPhotos(5, func(paths []string, err error) {
ch.attaching.Set(false)
if err != nil {
ui.Snackbar(ui.SnackbarProps{Message: "无法选择照片:" + err.Error()})
return
}
for _, path := range paths {
mimeType := mime.TypeByExtension(strings.ToLower(filepath.Ext(path)))
if !strings.HasPrefix(mimeType, "image/") {
mimeType = "image/jpeg"
}
ch.readAttachment(path, filepath.Base(path), mimeType)
}
})
}
func (ch *chat) pickFiles() {
ch.attaching.Set(true)
device.PickFiles(device.FileOptions{Multiple: true}, func(files []device.File, err error) {
ch.attaching.Set(false)
if err != nil {
ui.Snackbar(ui.SnackbarProps{Message: "无法选择文件:" + err.Error()})
return
}
for _, f := range files {
mimeType := f.Type
if mimeType == "" {
mimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(f.Name)))
}
if mimeType == "" {
mimeType = "application/octet-stream"
}
name := f.Name
if name == "" {
name = filepath.Base(f.Path)
}
ch.readAttachment(f.Path, name, mimeType)
}
})
}
// readAttachment reads a picked file off the main thread and hands the
// composer a data URL.
func (ch *chat) readAttachment(path, name, mimeType string) {
go func() {
info, err := os.Stat(path)
if err != nil {
ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) })
return
}
if info.Size() > maxAttachmentBytes {
ui.Post(func() {
ui.Snackbar(ui.SnackbarProps{Message: fmt.Sprintf("%s 超过 10 MB,未添加", name)})
})
return
}
data, err := os.ReadFile(path)
if err != nil {
ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) })
return
}
url := "data:" + mimeType + ";base64," + base64.StdEncoding.EncodeToString(data)
kept := ""
if strings.HasPrefix(mimeType, "image/") {
kept = keepImage(path, name)
}
ui.Post(func() {
list := ch.attachments.Peek()
next := make([]attachment, len(list), len(list)+1)
copy(next, list)
next = append(next, attachment{Name: name, MIME: mimeType, DataURL: url, Size: info.Size(), LocalPath: kept})
ch.attachments.Set(next)
})
}()
}
func (ch *chat) removeAttachment(index int) {
list := ch.attachments.Peek()
if index < 0 || index >= len(list) {
return
}
next := make([]attachment, 0, len(list)-1)
next = append(next, list[:index]...)
next = append(next, list[index+1:]...)
ch.attachments.Set(next)
}
// attachmentRow shows the files the next prompt will carry.
func (ch *chat) attachmentRow() ui.Node {
return ui.Show(signal.Func(func() bool { return len(ch.attachments.Get()) > 0 }),
func() ui.Node {
return ui.Scroll(
ui.ScrollProps{Horizontal: true, Style: ui.Style{},
ContentStyle: ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6}},
ui.For(ch.attachments, func(a attachment) string { return a.Name + a.DataURL[:24] },
func(a signal.Accessor[attachment], index signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{
Style: ui.Style{Padding: ui.Symmetric(6, 10), CornerRadius: 8,
Background: colors.SecondaryBackground, Align: ui.AlignCenter},
},
ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter},
ui.Symbol("paperclip", ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
ui.Text(signal.Func(func() string {
a := a.Get()
return fmt.Sprintf("%s · %s", a.Name, humanSize(a.Size))
}), ui.Style{Font: fonts.Caption, Lines: 1}),
ui.Button(ui.ButtonProps{Icon: ui.IconClose, Label: ui.Val("移除附件"),
OnPress: func() { ch.removeAttachment(index.Get()) }}),
),
)
}),
)
})
}
func (ch *chat) attachmentFiles() []ocapi.PromptFile {
list := ch.attachments.Peek()
out := make([]ocapi.PromptFile, 0, len(list))
for _, a := range list {
out = append(out, ocapi.PromptFile{URI: a.DataURL, Name: a.Name})
}
return out
}
func (ch *chat) optimisticFiles() []ocapi.FileAttachment {
list := ch.attachments.Peek()
out := make([]ocapi.FileAttachment, 0, len(list))
for _, a := range list {
out = append(out, ocapi.FileAttachment{URI: a.DataURL, Name: a.Name, MIME: a.MIME})
}
return out
}
// keepImage copies a picked image into the app's data dir so the sent
// message can show it inline after a reload clears the caches copy.
func keepImage(source, name string) string { func keepImage(source, name string) string {
dir := filepath.Join(store.Dir(), "attachments") dir, err := mygo.App.Path(mygo.PathUserData)
if err != nil {
return ""
}
dir = filepath.Join(dir, "attachments")
_ = os.MkdirAll(dir, 0o700) _ = os.MkdirAll(dir, 0o700)
dst := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), sanitizeName(name))) dst := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), sanitizeName(name)))
if err := copyFile(source, dst); err != nil { if err := copyFile(source, dst); err != nil {
@@ -213,13 +50,24 @@ func copyFile(src, dst string) error {
return os.WriteFile(dst, data, 0o600) return os.WriteFile(dst, data, 0o600)
} }
func mimeByExt(path string) string {
if m := mime.TypeByExtension(filepath.Ext(path)); m != "" {
return m
}
return "application/octet-stream"
}
func base64URL(data []byte) string {
return base64.StdEncoding.EncodeToString(data)
}
func humanSize(bytes int64) string { func humanSize(bytes int64) string {
switch { switch {
case bytes >= 1<<20: case bytes >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(bytes)/(1<<20)) return fmt.Sprintf("%.1fMB", float64(bytes)/(1<<20))
case bytes >= 1<<10: case bytes >= 1<<10:
return fmt.Sprintf("%.0f KB", float64(bytes)/(1<<10)) return fmt.Sprintf("%.0fKB", float64(bytes)/(1<<10))
default: default:
return fmt.Sprintf("%d B", bytes) return fmt.Sprintf("%dB", bytes)
} }
} }
+685 -1528
View File
File diff suppressed because it is too large. Load diff
-457
View File
@@ -1,457 +0,0 @@
package appui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/egoist/asuka/ui"
"github.com/egoist/asuka/uitest"
)
// chatServer serves one session with a short transcript, and records the
// prompt a test sends.
type chatServer struct {
*httptest.Server
prompts chan map[string]any
replies chan map[string]any
models chan map[string]any
created chan map[string]any
forked chan map[string]any
reverted chan map[string]any
events chan string
ready chan struct{}
readyOne sync.Once
}
func (cs *chatServer) push(ev string) {
select {
case cs.events <- ev:
case <-time.After(2 * time.Second):
panic("event stream is not consuming")
}
}
func newChatServer(t *testing.T) *chatServer {
t.Helper()
cs := &chatServer{
prompts: make(chan map[string]any, 1),
replies: make(chan map[string]any, 1),
models: make(chan map[string]any, 1),
created: make(chan map[string]any, 1),
forked: make(chan map[string]any, 1),
reverted: make(chan map[string]any, 2),
events: make(chan string, 8),
ready: make(chan struct{}),
}
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true}`)
})
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
})
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":{}}`)
})
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[]}`)
})
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
"time":{"created":11,"completed":12000},"cost":0.02,
"tokens":{"input":100500,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
"content":[{"type":"text","text":"**Hello** from the agent"},
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",
"input":{"command":"echo hi"},"content":[],
"metadata":{"openchamberContentShell":{}}}},
{"type":"tool","id":"call_2","name":"read","state":{"status":"completed",
"input":{"filePath":"/home/me/project/shot.png"},"content":[],
"attachments":[{"type":"file","mime":"image/png","filename":"shot.png",
"url":"data:image/png;base64,iVBORw0KGgo="}]}}]}
],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_new/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_1/prompt", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.prompts <- body:
default:
}
cs.events <- `{"id":"evt_2","created":100,"type":"session.step.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream"}}`
cs.events <- `{"id":"evt_3","created":101,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream","ordinal":0,"delta":"streamed"}}`
fmt.Fprint(w, `{"data":{}}`)
})
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
})
mux.HandleFunc("/api/model", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"gpt-4","providerID":"openai","name":"GPT-4","limit":{"context":200000,"output":64000}},
{"id":"claude","providerID":"anthropic","name":"Claude","limit":{"context":200000,"output":32000}}]}`)
})
mux.HandleFunc("/api/agent", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"build","name":"Build","mode":"primary"},
{"id":"plan","name":"Plan","mode":"primary"},
{"id":"general","name":"General","mode":"subagent","hidden":false},
{"id":"explore","name":"Explore","mode":"subagent"}]}`)
})
mux.HandleFunc("/api/session/ses_1/model", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.models <- body:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"First session","time":{"created":1,"updated":2},
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`)
return
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.created <- body:
default:
}
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3},
"location":{"directory":"/home/me/project"}}}`)
})
mux.HandleFunc("/api/session/ses_1/message/msg_2", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
"time":{"created":11,"completed":12000},"cost":0.02,
"tokens":{"input":100500,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
"content":[{"type":"text","text":"**Hello** from the agent"},
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",
"input":{"command":"echo hi"},"content":[{"type":"text","text":"tool output here"}]}},
{"type":"tool","id":"call_2","name":"read","state":{"status":"completed",
"input":{"filePath":"/home/me/project/shot.png"},"content":[],
"attachments":[{"type":"file","mime":"image/png","filename":"shot.png",
"url":"data:image/png;base64,iVBORw0KGgo="}]}}]}`)
})
mux.HandleFunc("/api/session/ses_1/revert/stage", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.reverted <- body:
default:
}
fmt.Fprint(w, `{"data":{"messageID":"msg_1"}}`)
})
mux.HandleFunc("/api/session/ses_1/revert/commit", func(w http.ResponseWriter, r *http.Request) {
select {
case cs.reverted <- map[string]any{"commit": true}:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/session/ses_1/fork", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.forked <- body:
default:
}
fmt.Fprint(w, `{"data":{"id":"ses_fork","title":"Forked","time":{"created":20,"updated":20},
"location":{"directory":"/home/me/project"}}}`)
})
mux.HandleFunc("/api/session/ses_fork/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.replies <- body:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
cs.readyOne.Do(func() { close(cs.ready) })
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
for {
select {
case ev := <-cs.events:
fmt.Fprintf(w, "data: %s\n\n", ev)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
case <-r.Context().Done():
return
}
}
})
cs.Server = httptest.NewServer(mux)
t.Cleanup(cs.Close)
return cs
}
func TestOpenSessionAndSend(t *testing.T) {
srv := newChatServer(t)
st := &memStore{}
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
select {
case <-srv.ready:
case <-time.After(5 * time.Second):
t.Fatal("the event stream was never opened")
}
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Expect("What is this?")
a.Type("发消息…", "ping")
a.Tap("发送")
a.WaitFor("ping")
a.WaitFor("streamed")
select {
case body := <-srv.prompts:
if body["text"] != "ping" {
t.Errorf("prompt text = %v", body["text"])
}
if id, _ := body["id"].(string); len(id) < 5 || id[:4] != "msg_" {
t.Errorf("prompt id = %v", body["id"])
}
default:
t.Fatal("no prompt reached the server")
}
}
func TestPermissionCardAndReply(t *testing.T) {
srv := newChatServer(t)
// The session list's pending-permission read.
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
select {
case <-srv.ready:
case <-time.After(5 * time.Second):
t.Fatal("no event stream")
}
a.Tap("First session")
a.WaitFor("Hello from the agent")
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
a.Settle()
a.WaitFor("需要权限:bash")
a.Expect("npm test")
a.Tap("允许一次")
select {
case body := <-srv.replies:
if body["decision"] != "once" {
t.Errorf("decision = %v", body["decision"])
}
case <-time.After(3 * time.Second):
t.Fatal("no permission reply reached the server")
}
}
func TestSwitchModel(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("模型")
a.WaitFor("GPT-4")
a.Tap("GPT-4")
select {
case body := <-srv.models:
model, _ := body["model"].(map[string]any)
if model["id"] != "gpt-4" || model["providerID"] != "openai" {
t.Errorf("model switch = %v", body)
}
case <-time.After(3 * time.Second):
t.Fatal("no model switch reached the server")
}
}
func TestCreateSession(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("新建")
a.WaitFor("新建会话")
a.Type("标题(可选,留空由服务端生成)", "Test chat")
a.Tap("创建")
a.WaitFor("New chat")
select {
case body := <-srv.created:
if body["title"] != "Test chat" {
t.Errorf("created title = %v", body["title"])
}
loc, _ := body["location"].(map[string]any)
if loc["directory"] != "/home/me/project" {
t.Errorf("created location = %v", body["location"])
}
case <-time.After(3 * time.Second):
t.Fatal("no create request reached the server")
}
}
func TestAgentPickerSkipsSubagents(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("Agent")
a.WaitFor("Build")
a.Expect("Plan")
a.ExpectNo("General")
a.ExpectNo("Explore")
}
func TestTurnFooter(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// The footer names the model, the agent and how long the turn took.
a.WaitFor("GPT-4 · build · 12.0s")
a.Tap("更多操作")
a.WaitFor("复制回答")
a.Expect("从这里分叉")
a.Back()
}
func TestForkFromTurnFooter(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("更多操作")
a.Tap("从这里分叉")
a.WaitFor("Forked")
select {
case body := <-srv.forked:
if _, ok := body["before"]; ok {
t.Errorf("fork sent a before id for the last message: %v", body)
}
case <-time.After(3 * time.Second):
t.Fatal("no fork request reached the server")
}
}
func TestUserMessageActions(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("What is this?")
a.Expect("复制消息")
a.Tap("消息操作")
a.WaitFor("从这里分叉")
a.Expect("复制消息")
a.Back()
}
func TestToolResultLoadsOnExpand(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// The list page shells the tool result; opening the row fetches it.
a.ExpectNo("tool output here")
a.Tap("✓ shell echo hi ▸")
a.WaitFor("tool output here")
}
func TestRevertFromUserMessage(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("What is this?")
a.Tap("消息操作")
a.Tap("撤回此消息及之后")
a.WaitFor("撤回消息?")
a.Tap("撤回")
stage := <-srv.reverted
if _, ok := stage["commit"]; ok {
t.Fatalf("unexpected first message: %v", stage)
}
if stage["messageID"] != "msg_1" {
t.Errorf("stage messageID = %v", stage["messageID"])
}
commit := <-srv.reverted
if _, ok := commit["commit"]; !ok {
t.Errorf("commit not sent: %v", commit)
}
}
func TestContextUsageRingAndSheet(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// 100500 tokens over 200000 - min(64000, 32000).
a.WaitFor("59.8%")
a.Tap("上下文占用")
a.WaitFor("上下文上限")
a.WaitFor("200.0K")
a.WaitFor("64.0K")
}
func TestToolImagePreviewSheet(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.WaitFor("预览 shot.png")
a.Tap("预览 shot.png")
a.WaitFor("图片预览")
}
-368
View File
@@ -1,368 +0,0 @@
package appui
import (
"strings"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/storage"
)
// connectionsScreen is the first screen: the saved servers, or the
// introduction when there are none. It mirrors the first-party client: the
// server last used leads, the others follow, and adding is one tap away.
func (c *controller) connectionsScreen() ui.Node {
return ui.Dynamic(func() ui.Node {
list := c.connections.Get()
if len(list) == 0 {
return c.firstRun()
}
lead := list[0]
for _, conn := range list {
if conn.ID == c.activeID.Get() && c.connected.Get() {
lead = conn
}
}
others := make([]storage.Connection, 0, len(list))
for _, conn := range list {
if conn.ID != lead.ID {
others = append(others, conn)
}
}
return ui.Scroll(
ui.ScrollProps{
Style: ui.Style{Grow: 1},
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
},
ui.StaticText("OpenChamber", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
c.leadCard(lead),
ui.Show(signal.Func(func() bool { return len(c.connections.Get()) > 1 }), func() ui.Node {
return ui.Column(ui.Style{Gap: 6},
ui.StaticText("其他服务器", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
ui.For(c.otherConnections(lead.ID), func(conn storage.Connection) string { return conn.ID },
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
return c.connectionRow(conn)
}),
)
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("添加服务器"),
Icon: ui.IconPlus,
Variant: ui.ButtonTinted,
OnPress: c.openAddForm,
}),
)
})
}
func (c *controller) otherConnections(leadID string) signal.Accessor[[]storage.Connection] {
return signal.Func(func() []storage.Connection {
out := make([]storage.Connection, 0, len(c.connections.Get()))
for _, conn := range c.connections.Get() {
if conn.ID != leadID {
out = append(out, conn)
}
}
return out
})
}
func (c *controller) firstRun() ui.Node {
return ui.Scroll(
ui.ScrollProps{
Style: ui.Style{Grow: 1},
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
},
ui.StaticText("OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
ui.StaticText("连接到正在运行的 OpenChamber 服务器。保存过的服务器会出现在这里,可以随时切换。",
ui.Style{Color: colors.SecondaryLabel}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("手动输入地址"),
Icon: "link",
Variant: ui.ButtonFilled,
OnPress: c.openAddForm,
}),
)
}
func (c *controller) leadCard(conn storage.Connection) ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.All(16), Gap: 8, CornerRadius: 14,
Background: colors.SecondaryBackground}},
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
OnPress: func() { c.connectionActions(conn) }}),
),
ui.Show(signal.Func(func() bool { return c.activeID.Get() == conn.ID && c.connected.Get() }),
func() ui.Node {
return ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
CornerRadius: 4, Background: colors.Accent}}),
ui.StaticText("已连接", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
},
func() ui.Node {
return ui.Show(signal.Func(func() bool { return c.connecting.Get() == conn.ID }),
func() ui.Node {
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignCenter},
ui.Activity(), ui.StaticText("连接中…", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}))
},
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("连接"),
Variant: ui.ButtonFilled,
OnPress: func() { c.connectTo(conn, "", true) },
})
})
}),
)
}
func (c *controller) connectionRow(conn signal.Accessor[storage.Connection]) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() { c.selectConnection(conn.Get()) },
Style: ui.Style{Padding: ui.Symmetric(10, 12), CornerRadius: 10, Gap: 6},
}, ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.Text(signal.Func(func() string { return c.labelOf(conn.Get()) }), ui.Style{Font: fonts.Body, Lines: 1}),
ui.Text(signal.Func(func() string { return conn.Get().URL }),
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
OnPress: func() { c.connectionActions(conn.Get()) }}),
))
}
func (c *controller) selectConnection(conn storage.Connection) {
c.instancesOpen.Set(false)
if conn.ID == c.activeID.Peek() && c.connected.Peek() {
return
}
if c.connected.Peek() {
c.logout("")
}
c.connectTo(conn, "", true)
}
func (c *controller) connectionActions(conn storage.Connection) {
ui.Alert(ui.AlertProps{
Title: c.labelOf(conn),
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("连接"), Icon: "play", OnPress: func() { c.selectConnection(conn) }},
{Title: ui.Val("编辑"), Icon: "pencil", OnPress: func() { c.openEditForm(conn) }},
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDeleteConnection(conn) }},
},
})
}
func (c *controller) confirmDeleteConnection(conn storage.Connection) {
ui.Alert(ui.AlertProps{
Title: "删除服务器?",
Message: "只会删除这个客户端里保存的连接,服务器上的数据不受影响。",
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
OnPress: func() { c.deleteConnection(conn) }},
},
})
}
func (c *controller) deleteConnection(conn storage.Connection) {
if c.activeID.Peek() == conn.ID {
c.logout("")
}
list := c.connections.Peek()
next := make([]storage.Connection, 0, len(list))
for _, saved := range list {
if saved.ID != conn.ID {
next = append(next, saved)
}
}
c.st.SaveConnections(next)
c.connections.Set(next)
go func() { _ = c.st.ClearToken(conn) }()
}
// formSheet is the add/edit form, a full-screen sheet like the first-party
// client's panel.
func (c *controller) formSheet() ui.Node {
title := "添加服务器"
if c.formEditID != "" {
title = "编辑服务器"
}
submit := "连接"
if c.connected.Peek() {
submit = "保存"
}
return ui.Sheet(ui.SheetProps{
Open: c.formOpen,
FullScreen: true,
Content: func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Scroll(
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14}},
ui.Row(ui.Style{Align: ui.AlignCenter},
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.closeForm}),
),
ui.TextField(ui.TextFieldProps{
Value: c.formLabel,
Placeholder: ui.Val("名称(可选)"),
}),
ui.TextField(ui.TextFieldProps{
Value: c.url,
Placeholder: ui.Val("http://192.168.1.5:3000"),
Keyboard: ui.KeyboardURL,
ContentType: "url",
Autocapitalize: ui.CapitalizeNone,
Autocorrect: ui.AutocorrectNo,
ReturnKey: ui.ReturnNext,
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("使用代理", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.formUseProxy}),
),
ui.Show(c.formUseProxy, func() ui.Node {
return ui.TextField(ui.TextFieldProps{
Value: c.formProxy,
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
Keyboard: ui.KeyboardURL,
Autocapitalize: ui.CapitalizeNone,
Autocorrect: ui.AutocorrectNo,
})
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.formInsecure}),
),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val(submit),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool { return c.connecting.Get() != "" }),
OnPress: c.submitForm,
}),
),
)
},
})
}
func (c *controller) passwordSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.passwordOpen,
Detents: ui.DetentMedium,
Grabber: true,
OnDismiss: c.cancelPassword,
Content: func() ui.Node {
conn := c.passwordFor
for _, saved := range c.connections.Peek() {
if saved.ID == conn.ID {
conn = saved
}
}
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14},
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
ui.StaticText("这台服务器需要密码。", ui.Style{Color: colors.SecondaryLabel}),
ui.TextField(ui.TextFieldProps{
Value: c.passwordText,
Placeholder: ui.Val("密码"),
Secure: true,
ContentType: ui.ContentPassword,
ReturnKey: ui.ReturnGo,
OnSubmit: c.submitPassword,
}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Row(ui.Style{Justify: ui.JustifyEnd, Gap: 8},
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.cancelPassword}),
ui.Button(ui.ButtonProps{
Title: ui.Val("解锁"),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool {
return c.passwordBusy.Get() || strings.TrimSpace(c.passwordText.Get()) == ""
}),
OnPress: c.submitPassword,
}),
),
)
},
})
}
// instancesSheet is the switcher while connected: the same list, in a sheet.
func (c *controller) instancesSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.instancesOpen,
FullScreen: true,
Content: func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Scroll(
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 12}},
ui.Row(ui.Style{Align: ui.AlignCenter},
ui.StaticText("实例", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("关闭"),
OnPress: func() { c.instancesOpen.Set(false) }}),
),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.For(c.connections, func(conn storage.Connection) string { return conn.ID },
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
return ui.Column(ui.Style{Gap: 4},
c.connectionRow(conn),
ui.Show(signal.Func(func() bool {
return conn.Get().ID == c.activeID.Get() && c.connected.Get()
}), func() ui.Node {
return ui.StaticText("当前连接", ui.Style{Font: fonts.Footnote,
Color: colors.SecondaryLabel, Padding: ui.Symmetric(0, 12)})
}),
)
}),
ui.Show(signal.Func(func() bool { return c.connected.Get() }),
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("断开当前连接"),
Variant: ui.ButtonGray,
OnPress: func() {
c.instancesOpen.Set(false)
c.disconnect()
},
})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("添加服务器"),
Icon: ui.IconPlus,
Variant: ui.ButtonTinted,
OnPress: func() {
c.instancesOpen.Set(false)
c.openAddForm()
},
}),
),
)
},
})
}
+83 -92
View File
@@ -1,13 +1,12 @@
package appui package appui
import ( import (
"context"
"fmt" "fmt"
"math" "math"
"github.com/egoist/asuka/colors" "github.com/egoist/mygo/ui"
"github.com/egoist/asuka/fonts" "github.com/egoist/mygo/ui/mobile"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi" "github.com/openchamber/openchamber-native/internal/ocapi"
) )
@@ -18,8 +17,7 @@ type modelLimit struct {
} }
// usageReading is the context window of the last assistant message that // usageReading is the context window of the last assistant message that
// reported tokens, as the first-party client shows it. The output // reported tokens.
// reservation is capped at 32k tokens, matching its calculation.
type usageReading struct { type usageReading struct {
Used int Used int
Limit int Limit int
@@ -41,8 +39,6 @@ func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
if last == nil { if last == nil {
return usageReading{} return usageReading{}
} }
// A message the event stream added has no model yet; the session's model
// is the latest one any message reports.
model := last.Model model := last.Model
for i := len(msgs) - 1; i >= 0 && model == nil; i-- { for i := len(msgs) - 1; i >= 0 && model == nil; i-- {
if msgs[i].Type == "assistant" && msgs[i].Model != nil { if msgs[i].Type == "assistant" && msgs[i].Model != nil {
@@ -61,8 +57,7 @@ func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
} }
lim := ch.modelLimit(model) lim := ch.modelLimit(model)
r.Limit, r.Output = lim.Context, lim.Output r.Limit, r.Output = lim.Context, lim.Output
r.Model = ch.modelName(model) r.Model = ch.a.modelName(model)
// The turn's cost is every step after its prompt.
for i := len(msgs) - 1; i >= 0; i-- { for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Type == "user" { if msgs[i].Type == "user" {
break break
@@ -87,19 +82,34 @@ func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
return r return r
} }
func (ch *chat) contextUsage() usageReading {
return ch.usageReading(ch.msgs.Peek())
}
func (ch *chat) modelLimit(m *ocapi.ModelRef) modelLimit { func (ch *chat) modelLimit(m *ocapi.ModelRef) modelLimit {
if m == nil { if m == nil {
return modelLimit{} return modelLimit{}
} }
limits := ch.modelLimits.Get() if l, ok := ch.modelLimits[m.ProviderID+"/"+m.ID]; ok {
if l, ok := limits[m.ProviderID+"/"+m.ID]; ok {
return l return l
} }
return limits[m.ID] return ch.modelLimits[m.ID]
}
func (a *App) loadModelLimits() {
go func() {
models, err := a.client.Models(context.Background(), a.dir())
a.post(func() {
if err != nil {
return
}
limits := map[string]modelLimit{}
for _, m := range models {
lim := modelLimit{Context: m.Limit.Context, Output: m.Limit.Output}
limits[m.ProviderID+"/"+m.ID] = lim
limits[m.ID] = lim
}
if a.chat != nil {
a.chat.modelLimits = limits
}
})
}()
} }
func formatTokens(n int) string { func formatTokens(n int) string {
@@ -113,76 +123,6 @@ func formatTokens(n int) string {
} }
} }
// usageTone follows the first-party thresholds: 75% warns, 90% errors.
func usageTone(pct float64) ui.Color {
switch {
case pct >= 90:
return colors.Red
case pct >= 75:
return colors.Orange
default:
return colors.Green
}
}
// usageButton is the composer's context ring and percentage.
func (ch *chat) usageButton() ui.Node {
return ui.Dynamic(func() ui.Node {
r := ch.usageReading(ch.msgs.Get())
if !r.Known {
return ui.View(ui.ViewProps{})
}
progress := signal.Func(func() float64 { return r.Pct / 100 })
return ui.View(ui.ViewProps{
OnPress: func() { ch.usageOpen.Set(true) },
Label: ui.Val("上下文占用"),
Hint: ui.Val("查看上下文详情"),
Style: ui.Style{Padding: ui.All(4), Align: ui.AlignCenter},
}, ui.Row(ui.Style{Gap: 4, Align: ui.AlignCenter},
ui.ProgressRing(progress, ui.Style{Width: ui.Pt(18), Height: ui.Pt(18), Color: usageTone(r.Pct)}),
ui.StaticText(fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)),
ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
))
})
}
func (ch *chat) usageSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: ch.usageOpen,
Detents: ui.DetentMedium,
Grabber: true,
OnDismiss: func() { ch.usageOpen.Set(false) },
Content: func() ui.Node {
return ui.Dynamic(func() ui.Node {
r := ch.usageReading(ch.msgs.Get())
rows := []ui.Node{usageRow("模型", r.Model)}
if r.Known {
rows = append(rows,
usageRow("已用 tokens", formatTokens(r.Used)),
usageRow("上下文上限", formatTokens(r.Limit)),
usageRow("输出预留", formatTokens(r.Output)),
usageRow("占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999))),
)
} else {
rows = append(rows,
usageRow("已用 tokens", formatTokens(r.Used)),
usageRow("上下文上限", "未知"),
)
}
if r.Cost > 0 {
rows = append(rows, usageRow("本轮费用", formatCost(r.Cost)))
}
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 10},
ui.StaticText("上下文占用", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.Column(ui.Style{Gap: 10}, rows...),
ui.StaticText("输出预留按最多 32K tokens 计算,与官方客户端一致。",
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
})
},
})
}
func formatCost(v float64) string { func formatCost(v float64) string {
if v < 0.01 { if v < 0.01 {
return fmt.Sprintf("$%.4f", v) return fmt.Sprintf("$%.4f", v)
@@ -190,9 +130,60 @@ func formatCost(v float64) string {
return fmt.Sprintf("$%.2f", v) return fmt.Sprintf("$%.2f", v)
} }
func usageRow(label, value string) ui.Node { // usageButton is the composer's context ring and percentage.
return ui.Row(ui.Style{Gap: 12, Align: ui.AlignCenter}, func (ch *chat) usageButton(c *ui.Context) {
ui.StaticText(label, ui.Style{Font: fonts.Body, Color: colors.SecondaryLabel, Grow: 1}), t := c.Theme()
ui.StaticText(value, ui.Style{Font: fonts.Body}), r := ch.usageReading(ch.msgs)
) if !r.Known {
return
}
btn := ui.Row(c).Gap(4).AlignItems(ui.Center).Padding(4, 4).Role(ui.RoleButton).Label("上下文占用")
btn.Children(func() {
ui.Text(c, fmt.Sprintf("%.0f%%", r.Pct)).FontSize(13).TextColor(t.TextMuted)
})
if btn.Clicked() {
ch.usageOpen = true
}
}
// usageSheet shows the context detail.
func (ch *chat) usageSheet(c *ui.Context) {
if !ch.usageOpen {
return
}
t := c.Theme()
mobileSheet(c, &ch.usageOpen, 0.5, func() {
r := ch.usageReading(ch.msgs)
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
ui.Text(c, "上下文占用").FontSize(20).Bold()
usageRow(c, t, "模型", r.Model)
if r.Known {
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
usageRow(c, t, "上下文上限", formatTokens(r.Limit))
usageRow(c, t, "输出预留", formatTokens(r.Output))
usageRow(c, t, "占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)))
} else {
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
usageRow(c, t, "上下文上限", "未知")
}
if r.Cost > 0 {
usageRow(c, t, "本轮费用", formatCost(r.Cost))
}
ui.Text(c, "输出预留按最多 32K tokens 计算,与官方客户端一致。").FontSize(12).TextColor(t.TextMuted)
})
})
}
func usageRow(c *ui.Context, t *ui.Theme, label, value string) ui.Element {
row := ui.Row(c).FillWidth().Gap(12).AlignItems(ui.Center)
row.Children(func() {
ui.Text(c, label).FontSize(14).TextColor(t.TextMuted).Grow(1)
ui.Text(c, value).FontSize(14)
})
return row
}
// mobileSheet shows a sheet of a detent.
func mobileSheet(c *ui.Context, open *bool, detent float32, content func()) {
mobile.Sheet(c, open, mobile.SheetOptions{Detents: []float32{detent}}, content)
} }
-91
View File
@@ -1,91 +0,0 @@
package appui
import (
"math"
"testing"
"github.com/egoist/asuka/signal"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func usageTestChat(limits map[string]modelLimit) *chat {
return &chat{
modelLimits: signal.NewFunc(limits, nil),
modelNames: signal.NewFunc(map[string]string{}, nil),
}
}
func TestUsageReadingCapsOutputReserve(t *testing.T) {
ch := usageTestChat(map[string]modelLimit{
"p/m": {Context: 200_000, Output: 64_000},
})
msgs := []ocapi.Message{{
Type: "assistant",
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: &ocapi.TokenUsage{Total: 50_000},
Cost: 0.02,
}}
r := ch.usageReading(msgs)
if !r.Known {
t.Fatal("usage should be known")
}
if r.Limit != 200_000 || r.Output != 64_000 || r.Used != 50_000 {
t.Errorf("reading = %+v", r)
}
// 200k - min(64k, 32k) = 168k; 50k / 168k = 29.76%
want := 50_000.0 / 168_000.0 * 100
if math.Abs(r.Pct-want) > 1e-9 {
t.Errorf("pct = %v, want %v", r.Pct, want)
}
if r.Cost != 0.02 {
t.Errorf("cost = %v", r.Cost)
}
}
func TestUsageReadingFallsBackToFieldSum(t *testing.T) {
ch := usageTestChat(map[string]modelLimit{
"p/m": {Context: 100_000, Output: 8_000},
})
tokens := &ocapi.TokenUsage{Input: 10, Output: 20, Reasoning: 30}
tokens.Cache.Read = 40
tokens.Cache.Write = 50
r := ch.usageReading([]ocapi.Message{{
Type: "assistant",
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: tokens,
}})
if r.Used != 150 {
t.Errorf("used = %d, want 150", r.Used)
}
if want := 150.0 / 92_000.0 * 100; math.Abs(r.Pct-want) > 1e-9 {
t.Errorf("pct = %v, want %v", r.Pct, want)
}
}
func TestUsageReadingUnknownWithoutLimit(t *testing.T) {
ch := usageTestChat(nil)
r := ch.usageReading([]ocapi.Message{{
Type: "assistant",
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: &ocapi.TokenUsage{Total: 500},
}})
if r.Known || r.Pct != 0 {
t.Errorf("reading = %+v, want unknown", r)
}
}
func TestUsageReadingBorrowsModelFromEarlierMessage(t *testing.T) {
ch := usageTestChat(map[string]modelLimit{
"p/m": {Context: 100_000, Output: 8_000},
})
msgs := []ocapi.Message{
{Type: "assistant", Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: &ocapi.TokenUsage{Total: 1_000}},
// Added by the event stream: tokens, but no model yet.
{Type: "assistant", Tokens: &ocapi.TokenUsage{Total: 2_000}},
}
r := ch.usageReading(msgs)
if !r.Known || r.Used != 2_000 || r.Limit != 100_000 {
t.Errorf("reading = %+v", r)
}
}
+64 -100
View File
@@ -4,12 +4,11 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi" "github.com/openchamber/openchamber-native/internal/ocapi"
) )
// eventTypes are the event kinds the list and chat read. Sending the filter // eventTypes are the event kinds the list and chat read. Sending the
// keeps a phone's stream small; server.connected always arrives. // filter keeps a phone's stream small; server.connected always arrives.
var eventTypes = []string{ var eventTypes = []string{
"session.created", "session.created",
"session.renamed", "session.renamed",
@@ -77,51 +76,51 @@ type permissionData struct {
Resources []string `json:"resources"` Resources []string `json:"resources"`
} }
// startEvents subscribes to the server's event stream for the given client. // startStream subscribes to the server's event stream. Call it on the main
// It must run on the main thread (it writes the cancel function). // thread; the stream runs on a goroutine and posts events back.
func (c *controller) startEvents(client *ocapi.Client) { func (a *App) startStream() {
if c.cancelSSE != nil { if a.client == nil {
c.cancelSSE() return
} }
a.stopStream()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
c.cancelSSE = cancel a.streamCancel = cancel
// A stream that reconnects lost events; a fresh connection (the one
// made when connecting) is the list's first read, not a gap.
wasDown := false wasDown := false
client := a.client
sub := ocapi.Subscription{ sub := ocapi.Subscription{
Types: eventTypes, Types: eventTypes,
OnEvent: func(ev ocapi.Event) { OnEvent: func(ev ocapi.Event) {
ui.Post(func() { a.post(func() {
if c.client != client { if a.client != client {
return return
} }
c.applyEvent(ev) a.applyEvent(ev)
}) })
}, },
OnState: func(st ocapi.SubscriptionState, err error) { OnState: func(st ocapi.SubscriptionState, err error) {
switch st { switch st {
case ocapi.Disconnected: case ocapi.Disconnected:
wasDown = true wasDown = true
ui.Post(func() { a.post(func() {
if c.client != client { if a.client != client {
return return
} }
c.status.Set("连接中断,正在重连…") a.errorText = "连接中断,正在重连…"
}) })
case ocapi.Subscribed: case ocapi.Subscribed:
if !wasDown { if !wasDown {
return return
} }
wasDown = false wasDown = false
// Events missed while the stream was down are gone; a.post(func() {
// re-read the list and the open chat's tail. if a.client != client {
ui.Post(func() {
if c.client != client {
return return
} }
c.refresh() a.errorText = ""
if c.chat != nil { a.loadSessions()
c.chat.reloadTail() a.loadPerms()
if a.chat != nil {
a.chat.reloadTail()
} }
}) })
} }
@@ -130,14 +129,25 @@ func (c *controller) startEvents(client *ocapi.Client) {
go client.Subscribe(ctx, sub) go client.Subscribe(ctx, sub)
} }
// applyEvent folds one server event into the list state. Main thread. func (a *App) stopStream() {
func (c *controller) applyEvent(ev ocapi.Event) { if a.streamCancel != nil {
if c.chat != nil { a.streamCancel()
a.streamCancel = nil
}
}
// applyEvent folds one server event into the list and, when it belongs to
// the open chat, into the chat. Main thread.
func (a *App) applyEvent(ev ocapi.Event) {
if a.chat != nil {
var ref struct { var ref struct {
SessionID string `json:"sessionID"` SessionID string `json:"sessionID"`
} }
if ev.UnmarshalData(&ref) == nil && ref.SessionID == c.chat.id { if ev.UnmarshalData(&ref) == nil && ref.SessionID == a.chat.id {
c.chat.handleEvent(ev) a.chat.handleEvent(ev)
}
if a.chatWin != nil {
a.chatWin.Update(func() {})
} }
} }
switch ev.Type { switch ev.Type {
@@ -146,14 +156,12 @@ func (c *controller) applyEvent(ev ocapi.Event) {
if ev.UnmarshalData(&d) != nil || d.SessionID == "" { if ev.UnmarshalData(&d) != nil || d.SessionID == "" {
return return
} }
list := c.sessions.Peek() for _, s := range a.sessions {
for _, s := range list {
if s.ID == d.SessionID { if s.ID == d.SessionID {
return return
} }
} }
next := make([]ocapi.Session, 0, len(list)+1) sess := ocapi.Session{
next = append(next, ocapi.Session{
ID: d.SessionID, ID: d.SessionID,
ProjectID: d.ProjectID, ProjectID: d.ProjectID,
Title: d.Title, Title: d.Title,
@@ -161,82 +169,68 @@ func (c *controller) applyEvent(ev ocapi.Event) {
Model: d.Model, Model: d.Model,
Location: d.Location, Location: d.Location,
Time: ocapi.SessionTime{Created: ev.Created, Updated: ev.Created}, Time: ocapi.SessionTime{Created: ev.Created, Updated: ev.Created},
}) }
c.sessions.Set(append(next, list...)) a.sessions = append([]ocapi.Session{sess}, a.sessions...)
case "session.renamed": case "session.renamed":
var d sessionRenamedData var d sessionRenamedData
if ev.UnmarshalData(&d) != nil { if ev.UnmarshalData(&d) != nil {
return return
} }
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title }) a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title })
case "session.model.selected": case "session.model.selected":
var d sessionModelData var d sessionModelData
if ev.UnmarshalData(&d) != nil { if ev.UnmarshalData(&d) != nil {
return return
} }
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model }) a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model })
case "session.agent.selected": case "session.agent.selected":
var d sessionAgentData var d sessionAgentData
if ev.UnmarshalData(&d) != nil { if ev.UnmarshalData(&d) != nil {
return return
} }
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent }) a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent })
case "session.archived": case "session.archived", "session.deleted":
var d sessionRefData var d sessionRefData
if ev.UnmarshalData(&d) != nil { if ev.UnmarshalData(&d) != nil {
return return
} }
c.removeSession(d.SessionID) a.removeSession(d.SessionID)
case "session.deleted":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.removeSession(d.SessionID)
case "session.unarchived", "session.moved": case "session.unarchived", "session.moved":
// The event carries no full record; a list read is the truth. // The event carries no full record; a list read is the truth.
c.refresh() a.loadSessions()
case "session.execution.started": case "session.execution.started":
var d sessionRefData var d sessionRefData
if ev.UnmarshalData(&d) != nil { if ev.UnmarshalData(&d) != nil {
return return
} }
c.setActive(d.SessionID, true) a.active[d.SessionID] = true
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted": case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
var d sessionRefData var d sessionRefData
if ev.UnmarshalData(&d) != nil { if ev.UnmarshalData(&d) != nil {
return return
} }
c.setActive(d.SessionID, false) a.active[d.SessionID] = false
case "permission.asked": case "permission.asked":
var d permissionData var d permissionData
if ev.UnmarshalData(&d) != nil || d.ID == "" { if ev.UnmarshalData(&d) != nil || d.ID == "" {
return return
} }
list := c.perms.Peek() for _, p := range a.perms {
for _, p := range list {
if p.ID == d.ID { if p.ID == d.ID {
return return
} }
} }
next := make([]ocapi.PermissionRequest, len(list), len(list)+1) a.perms = append(a.perms, ocapi.PermissionRequest{
copy(next, list)
next = append(next, ocapi.PermissionRequest{
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources, ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
}) })
c.perms.Set(next)
if c.chat != nil {
c.chat.syncPerms()
}
case "permission.replied": case "permission.replied":
var d struct { var d struct {
@@ -245,61 +239,31 @@ func (c *controller) applyEvent(ev ocapi.Event) {
if ev.UnmarshalData(&d) != nil || d.RequestID == "" { if ev.UnmarshalData(&d) != nil || d.RequestID == "" {
return return
} }
list := c.perms.Peek() next := a.perms[:0]
next := make([]ocapi.PermissionRequest, 0, len(list)) for _, p := range a.perms {
for _, p := range list {
if p.ID != d.RequestID { if p.ID != d.RequestID {
next = append(next, p) next = append(next, p)
} }
} }
if len(next) != len(list) { a.perms = next
c.perms.Set(next)
if c.chat != nil {
c.chat.syncPerms()
}
}
} }
} }
func (c *controller) patchSession(id string, patch func(*ocapi.Session)) { func (a *App) patchSession(id string, patch func(*ocapi.Session)) {
list := c.sessions.Peek() for i := range a.sessions {
next := make([]ocapi.Session, len(list)) if a.sessions[i].ID == id {
copy(next, list) patch(&a.sessions[i])
for i := range next {
if next[i].ID == id {
patch(&next[i])
c.sessions.Set(next)
return return
} }
} }
} }
func (c *controller) removeSession(id string) { func (a *App) removeSession(id string) {
list := c.sessions.Peek() next := a.sessions[:0]
next := make([]ocapi.Session, 0, len(list)) for _, s := range a.sessions {
for _, s := range list {
if s.ID != id { if s.ID != id {
next = append(next, s) next = append(next, s)
} }
} }
if len(next) != len(list) { a.sessions = next
c.sessions.Set(next)
}
}
func (c *controller) setActive(id string, on bool) {
cur := c.active.Peek()
if cur[id] == on {
return
}
next := make(map[string]bool, len(cur)+1)
for k, v := range cur {
next[k] = v
}
if on {
next[id] = true
} else {
delete(next, id)
}
c.active.Set(next)
} }
+209
View File
@@ -0,0 +1,209 @@
package appui
import (
"encoding/json"
"strings"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// handleEvent folds a session's own events into its messages. Main thread.
func (ch *chat) handleEvent(ev ocapi.Event) {
switch ev.Type {
case "session.execution.started":
ch.running = true
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
ch.running = false
case "session.step.started":
var d struct {
AssistantMessageID string `json:"assistantMessageID"`
}
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.running = true
case "session.step.ended", "session.step.failed":
ch.applyStepEnd(ev)
case "session.text.started", "session.text.delta", "session.text.ended":
ch.applyDelta(ev, "text", ch.textSlots)
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
"session.tool.success", "session.tool.failed", "session.tool.progress":
ch.applyToolEvent(ev)
}
}
type deltaData struct {
AssistantMessageID string `json:"assistantMessageID"`
Ordinal int `json:"ordinal"`
Delta string `json:"delta"`
Text string `json:"text"`
}
type toolEventData struct {
AssistantMessageID string `json:"assistantMessageID"`
ID string `json:"id"`
Name string `json:"name"`
Input map[string]any `json:"input"`
Executed bool `json:"executed"`
Content []ocapi.ContentPart `json:"content"`
Metadata map[string]any `json:"metadata"`
Error json.RawMessage `json:"error"`
}
// applyToolEvent folds a tool call's events into its part.
func (ch *chat) applyToolEvent(ev ocapi.Event) {
var d toolEventData
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" || d.ID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
part := ch.findToolPart(m, d.ID)
if part == nil {
return
}
switch ev.Type {
case "session.tool.input.started", "session.tool.input.ended":
part.State.Status = "streaming"
case "session.tool.called":
part.State.Status = "running"
part.State.Input = d.Input
case "session.tool.progress":
if d.Metadata != nil {
part.State.Metadata = d.Metadata
}
case "session.tool.success":
part.State.Status = "completed"
part.State.Input = d.Input
part.State.Content = d.Content
part.State.Metadata = d.Metadata
case "session.tool.failed":
part.State.Status = "error"
part.State.Input = d.Input
part.State.Content = d.Content
part.State.Metadata = d.Metadata
part.State.Error = d.Error
}
})
}
// findToolPart finds a tool part by its call id, creating one if the page
// does not have it yet.
func (ch *chat) findToolPart(m *ocapi.Message, id string) *ocapi.ContentPart {
for i := range m.Content {
p := &m.Content[i]
if p.Type == "tool" && p.ID == id {
if p.State == nil {
p.State = &ocapi.ToolState{}
}
return p
}
}
// The message's first tool part with no id yet is the running call.
for i := range m.Content {
p := &m.Content[i]
if p.Type == "tool" && p.ID == "" {
p.ID = id
if p.State == nil {
p.State = &ocapi.ToolState{}
}
return p
}
}
// A call the page never saw: append it.
m.Content = append(m.Content, ocapi.ContentPart{
Type: "tool", ID: id, State: &ocapi.ToolState{Status: "running"},
})
return &m.Content[len(m.Content)-1]
}
type stepEndData struct {
AssistantMessageID string `json:"assistantMessageID"`
Finish string `json:"finish"`
Cost float64 `json:"cost"`
Tokens *ocapi.TokenUsage `json:"tokens"`
}
func (ch *chat) applyStepEnd(ev ocapi.Event) {
var d stepEndData
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
if d.Finish != "" {
m.Finish = d.Finish
}
m.Cost = d.Cost
m.Tokens = d.Tokens
m.Time.Completed = ev.Created
})
}
func (ch *chat) applyDelta(ev ocapi.Event, kind string, slots map[string]map[int]int) {
var d deltaData
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
idx := slotFor(slots, m, d.Ordinal, kind)
if idx < 0 || idx >= len(m.Content) {
return
}
part := &m.Content[idx]
switch {
case strings.HasSuffix(ev.Type, ".started"):
part.Type = kind
case strings.HasSuffix(ev.Type, ".delta"):
part.Text += d.Delta
case strings.HasSuffix(ev.Type, ".ended"):
part.Text = d.Text
}
})
}
func slotFor(slots map[string]map[int]int, m *ocapi.Message, ordinal int, kind string) int {
byOrdinal := slots[m.ID]
if byOrdinal == nil {
byOrdinal = map[int]int{}
slots[m.ID] = byOrdinal
}
if idx, ok := byOrdinal[ordinal]; ok && idx < len(m.Content) {
return idx
}
m.Content = append(m.Content, ocapi.ContentPart{Type: kind})
idx := len(m.Content) - 1
byOrdinal[ordinal] = idx
return idx
}
func (ch *chat) ensureAssistant(id string, created int64) {
if _, ok := ch.byID[id]; ok {
return
}
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
}
// toolOutput is a tool call's result text.
func toolOutput(p ocapi.ContentPart) string {
if p.State == nil {
return ""
}
var out []string
for _, c := range p.State.Content {
if c.Type == "text" {
out = append(out, c.Text)
}
}
if len(out) == 0 {
if p.State.Error != nil && len(p.State.Error) > 0 {
return string(p.State.Error)
}
return ""
}
return strings.Join(out, "\n")
}
+31 -22
View File
@@ -1,30 +1,39 @@
package appui package appui
import ( import (
"github.com/egoist/asuka/colors" "embed"
"github.com/egoist/asuka/sdk/svg" "sync"
"github.com/egoist/asuka/ui"
"github.com/egoist/mygo/ui"
) )
// serverIcon is a rack, drawn as vector paths: Asuka's built-in symbols //go:embed icons/*.png
// have no server glyph on Android, and an SVG keeps it crisp at any size. var iconFiles embed.FS
var serverIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/></svg>`)
// sparklesIcon marks the turn footer. Drawn here for the same reason as // iconBitmaps decodes the PNG icons once, on the main thread.
// the server icon: not every platform's symbol set has the name. var iconBitmaps sync.Map // name -> *ui.Bitmap
var sparklesIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l1.7 4.3L18 9l-4.3 1.7L12 15l-1.7-4.3L6 9l4.3-1.7L12 3z"/><path d="M19 15l.8 1.9L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-1.1L19 15z"/></svg>`)
// instancesButton opens the server list: one button, because picking a func iconBitmap(name string) *ui.Bitmap {
// server is also how the live one is replaced. if v, ok := iconBitmaps.Load(name); ok {
func (c *controller) instancesButton() ui.Node { return v.(*ui.Bitmap)
return ui.View(ui.ViewProps{ }
OnPress: func() { c.instancesOpen.Set(true) }, data, err := iconFiles.ReadFile("icons/" + name + ".png")
Label: ui.Val("实例"), if err != nil {
Hint: ui.Val("打开服务器列表"), return nil
Style: ui.Style{Padding: ui.All(8)}, }
}, svg.View(svg.Props{ bmp, err := ui.DecodeBitmap(data)
Icon: serverIcon, if err != nil {
Color: ui.Val(colors.Accent), return nil
Style: ui.Style{Width: ui.Pt(22), Height: ui.Pt(22)}, }
})) iconBitmaps.Store(name, bmp)
return bmp
}
// barIcon is the PNG a system navigation bar button takes on Android.
func barIcon(name string) []byte {
data, err := iconFiles.ReadFile("icons/" + name + ".png")
if err != nil {
return nil
}
return data
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 326 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 B

+73 -69
View File
@@ -10,13 +10,12 @@ import (
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"sync"
"time" "time"
"github.com/egoist/asuka/colors" "github.com/egoist/mygo"
"github.com/egoist/asuka/fonts" "github.com/egoist/mygo/ui"
"github.com/egoist/asuka/sdk/store" "github.com/egoist/mygo/ui/mobile"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi" "github.com/openchamber/openchamber-native/internal/ocapi"
) )
@@ -27,8 +26,7 @@ var imageExtensions = map[string]bool{
".webp": true, ".bmp": true, ".avif": true, ".webp": true, ".bmp": true, ".avif": true,
} }
// imageRef is one previewable image a tool call names: the Source is an // imageRef is one previewable image a tool call names.
// absolute path or a data URL, the Label what its row shows.
type imageRef struct { type imageRef struct {
Source string Source string
Label string Label string
@@ -38,9 +36,8 @@ func isImagePath(path string) bool {
return imageExtensions[strings.ToLower(filepath.Ext(path))] return imageExtensions[strings.ToLower(filepath.Ext(path))]
} }
// toolImages lists the images a tool call names: its file input, file parts // toolImages lists the images a tool call names: its file input, file
// in its output (data URLs from a read, for example), and paths in its text // parts in its output, and paths in its text output.
// output. Relative paths resolve against the session's directory.
func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef { func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
seen := map[string]bool{} seen := map[string]bool{}
out := make([]imageRef, 0, 2) out := make([]imageRef, 0, 2)
@@ -103,8 +100,6 @@ func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
} }
attachments := 0 attachments := 0
if p.State != nil { if p.State != nil {
// Server-projected tool attachments carry the image itself, so they
// come first: a read of an image needs no file request.
for _, group := range [][]ocapi.ContentPart{p.State.Attachments, p.State.Content} { for _, group := range [][]ocapi.ContentPart{p.State.Attachments, p.State.Content} {
for _, c := range group { for _, c := range group {
switch c.Type { switch c.Type {
@@ -124,7 +119,6 @@ func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
} }
} }
} }
// The attachment already is the image the call named.
if attachments == 0 { if attachments == 0 {
for _, key := range []string{"filePath", "path", "file", "file_path", "sourcePath"} { for _, key := range []string{"filePath", "path", "file", "file_path", "sourcePath"} {
if v, ok := p.State.Input[key].(string); ok { if v, ok := p.State.Input[key].(string); ok {
@@ -136,43 +130,49 @@ func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
return out return out
} }
func (ch *chat) toolImageAccessor(part signal.Accessor[ocapi.ContentPart]) signal.Accessor[[]imageRef] { // ------------------------------------------------------------- preview
return signal.Func(func() []imageRef { return ch.toolImages(part.Get()) })
}
// previewKey names a cached preview: a hash keeps data URLs out of the map.
func previewKey(source string) string { func previewKey(source string) string {
sum := sha1.Sum([]byte(source)) sum := sha1.Sum([]byte(source))
return hex.EncodeToString(sum[:]) return hex.EncodeToString(sum[:])
} }
// previewDir is where fetched previews are kept.
func previewDir() string {
dir, err := mygo.App.Path(mygo.PathUserData)
if err != nil {
return ""
}
return filepath.Join(dir, "previews")
}
func (ch *chat) previewImage(ref imageRef) { func (ch *chat) previewImage(ref imageRef) {
ch.previewSeq++ ch.previewSeq++
seq := ch.previewSeq seq := ch.previewSeq
ch.previewTitle.Set(ref.Label) ch.previewTitle = ref.Label
ch.previewPath.Set("") ch.previewPath = ""
ch.previewLoading.Set(true) ch.previewLoading = true
ch.previewOpen.Set(true) ch.previewOpen = true
key := previewKey(ref.Source) key := previewKey(ref.Source)
if local, ok := ch.previewCache[key]; ok { if local, ok := ch.previewCache[key]; ok {
ch.previewPath.Set(local) ch.previewPath = local
ch.previewLoading.Set(false) ch.previewLoading = false
return return
} }
go func() { go func() {
data, err := ch.loadPreview(ref.Source) data, err := ch.loadPreview(ref.Source)
if err != nil { if err != nil {
ui.Post(func() { ch.a.chatPost(func() {
if seq != ch.previewSeq { if seq != ch.previewSeq {
return return
} }
ch.previewLoading.Set(false) ch.previewLoading = false
ch.previewOpen.Set(false) ch.previewOpen = false
ui.Snackbar(ui.SnackbarProps{Message: "无法预览:" + friendlyError(err)}) ch.errText = "无法预览:" + friendlyError(err)
}) })
return return
} }
dir := filepath.Join(store.Dir(), "previews") dir := previewDir()
_ = os.MkdirAll(dir, 0o700) _ = os.MkdirAll(dir, 0o700)
name := strings.Map(func(r rune) rune { name := strings.Map(func(r rune) rune {
if r == '/' || r == '\\' || r == ':' || r < ' ' { if r == '/' || r == '\\' || r == ':' || r < ' ' {
@@ -182,23 +182,22 @@ func (ch *chat) previewImage(ref imageRef) {
}, ref.Label) }, ref.Label)
local := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), name)) local := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), name))
if err := os.WriteFile(local, data, 0o600); err != nil { if err := os.WriteFile(local, data, 0o600); err != nil {
ui.Post(func() { ch.a.chatPost(func() {
if seq != ch.previewSeq { if seq != ch.previewSeq {
return return
} }
ch.previewLoading.Set(false) ch.previewLoading = false
ch.previewOpen.Set(false) ch.previewOpen = false
ui.Snackbar(ui.SnackbarProps{Message: "无法保存预览"})
}) })
return return
} }
ui.Post(func() { ch.a.chatPost(func() {
if seq != ch.previewSeq { if seq != ch.previewSeq {
return return
} }
ch.previewCache[key] = local ch.previewCache[key] = local
ch.previewPath.Set(local) ch.previewPath = local
ch.previewLoading.Set(false) ch.previewLoading = false
}) })
}() }()
} }
@@ -216,9 +215,9 @@ func (ch *chat) loadPreview(source string) ([]byte, error) {
} }
return base64.StdEncoding.DecodeString(source[comma+1:]) return base64.StdEncoding.DecodeString(source[comma+1:])
} }
client := ch.client() client := ch.a.client
if client == nil { if client == nil {
return nil, fmt.Errorf("not connected") return nil, fmt.Errorf("未连接")
} }
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel() defer cancel()
@@ -226,39 +225,44 @@ func (ch *chat) loadPreview(source string) ([]byte, error) {
return data, err return data, err
} }
func (ch *chat) previewSheet() ui.Node { // previewSheet shows the fetched image.
return ui.Sheet(ui.SheetProps{ func (ch *chat) previewSheet(c *ui.Context) {
Open: ch.previewOpen, if !ch.previewOpen {
Detents: ui.DetentLarge, return
Grabber: true, }
OnDismiss: func() { ch.previewOpen.Set(false) }, mobile.Sheet(c, &ch.previewOpen, mobile.SheetOptions{Detents: []float32{0.92}}, func() {
Content: func() ui.Node { ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
return ui.View(ui.ViewProps{Label: ui.Val("图片预览"), Style: ui.Style{Grow: 1}}, ui.Text(c, ch.previewTitle).FontSize(16).FontWeight(600).MaxLines(2)
ui.SafeArea(ui.Style{Padding: ui.All(16), Gap: 10}, if ch.previewLoading {
ui.Text(ch.previewTitle, ui.Style{Font: fonts.Headline, Lines: 2}), ui.Column(c).Fill().Center().Height(300).Children(func() { ui.Spinner(c) })
ui.Show(ch.previewLoading, return
func() ui.Node { return ui.Activity() }, }
func() ui.Node { bmp := loadImageFile(ch.previewPath)
return ui.Image(ui.ImageProps{ if bmp != nil {
Source: ch.previewPath, ui.Image(c, bmp).FillWidth().Height(420).Radius(10).Clip()
Mode: ui.ImageFit, }
Style: ui.Style{Width: ui.Pct(100), Height: ui.Pt(420), CornerRadius: 10}, })
})
}),
),
)
},
}) })
} }
// imageLinkRow is one previewable image under a tool call. // loadImageFile decodes a local image file into a bitmap, caching it.
func (ch *chat) imageLinkRow(ref imageRef) ui.Node { var imageCache sync.Map // path -> *ui.Bitmap
return ui.View(ui.ViewProps{
OnPress: func() { ch.previewImage(ref) }, func loadImageFile(path string) *ui.Bitmap {
Label: ui.Val("预览 " + ref.Label), if path == "" {
Style: ui.Style{Padding: ui.Symmetric(3, 0)}, return nil
}, ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter}, }
ui.Symbol("photo", ui.Style{Font: fonts.Caption, Color: colors.Accent}), if v, ok := imageCache.Load(path); ok {
ui.StaticText(ref.Label, ui.Style{Font: fonts.Caption, Color: colors.Accent, Lines: 1}), return v.(*ui.Bitmap)
)) }
data, err := os.ReadFile(path)
if err != nil {
return nil
}
bmp, err := ui.DecodeBitmap(data)
if err != nil {
return nil
}
imageCache.Store(path, bmp)
return bmp
} }
-102
View File
@@ -1,102 +0,0 @@
package appui
import (
"bytes"
"testing"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func TestToolImagesFromOutput(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Input: map[string]any{"path": "shots/a.png"},
Content: []ocapi.ContentPart{
{Type: "text", Text: "wrote /work/shots/a.png and /work/notes.txt"},
{Type: "file", MIME: "image/png", URL: "data:image/png;base64,AAAA", Filename: "b.png"},
},
},
}
refs := ch.toolImages(part)
if len(refs) != 2 {
t.Fatalf("refs = %+v", refs)
}
if refs[0].Source != "/work/shots/a.png" || refs[0].Label != "a.png" {
t.Errorf("first = %+v", refs[0])
}
if refs[1].Source != "data:image/png;base64,AAAA" || refs[1].Label != "b.png" {
t.Errorf("second = %+v", refs[1])
}
}
func TestToolImagesPrefersReadAttachment(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Input: map[string]any{"filePath": "/tmp/upload.png"},
Attachments: []ocapi.ContentPart{{
Type: "file", MIME: "image/png", Filename: "upload.png",
URL: "data:image/png;base64,AAAA",
}},
},
}
refs := ch.toolImages(part)
if len(refs) != 1 || refs[0].Source != "data:image/png;base64,AAAA" {
t.Errorf("refs = %+v", refs)
}
}
func TestToolImagesUsesURIFileContent(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Content: []ocapi.ContentPart{{
Type: "file", MIME: "image/jpeg", Name: "shot.jpg",
URI: "file:///work/shot.jpg",
}},
},
}
refs := ch.toolImages(part)
if len(refs) != 1 || refs[0].Source != "/work/shot.jpg" || refs[0].Label != "shot.jpg" {
t.Errorf("refs = %+v", refs)
}
}
func TestToolImagesSkipsNonImages(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Input: map[string]any{"path": "/work/main.go"},
Content: []ocapi.ContentPart{
{Type: "text", Text: "read /work/main.go and /work/logo.webp"},
},
},
}
refs := ch.toolImages(part)
if len(refs) != 1 || refs[0].Source != "/work/logo.webp" {
t.Errorf("refs = %+v", refs)
}
}
func TestLoadPreviewDataURL(t *testing.T) {
ch := &chat{}
data, err := ch.loadPreview("data:image/png;base64,iVBORw0KGgo=")
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")) {
t.Errorf("data = %x", data)
}
}
func TestLoadPreviewRejectsPlainDataURL(t *testing.T) {
ch := &chat{}
if _, err := ch.loadPreview("data:text/plain,hello"); err == nil {
t.Fatal("expected an error for a non-base64 data URL")
}
}
-648
View File
@@ -1,648 +0,0 @@
// Package appui holds the OpenChamber screens and their state.
package appui
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/storage"
)
// Root is the app's root component.
func Root() ui.Node {
return rootWithStore(storage.New())
}
func rootWithStore(st storage.Store) ui.Node {
_, node := newApp(st)
return node
}
func newApp(st storage.Store) (*controller, ui.Node) {
c := newController(st)
signal.OnCleanup(c.shutdown)
return c, c.screen()
}
type controller struct {
st storage.Store
connections *signal.Signal[[]storage.Connection]
url *signal.Signal[string]
sessionQuery *signal.Signal[string]
searchOpen *signal.Signal[bool]
status *signal.Signal[string]
errorMsg *signal.Signal[string]
formOpen *signal.Signal[bool]
formConnecting bool
formEditID string
formLabel *signal.Signal[string]
formUseProxy *signal.Signal[bool]
formProxy *signal.Signal[string]
formInsecure *signal.Signal[bool]
passwordOpen *signal.Signal[bool]
passwordFor storage.Connection
passwordText *signal.Signal[string]
passwordBusy *signal.Signal[bool]
instancesOpen *signal.Signal[bool]
server *signal.Signal[string]
connected *signal.Signal[bool]
busy *signal.Signal[bool]
connecting *signal.Signal[string]
activeID *signal.Signal[string]
sessions *signal.Signal[[]ocapi.Session]
active *signal.Signal[map[string]bool]
perms *signal.Signal[[]ocapi.PermissionRequest]
defaultDir *signal.Signal[string]
newOpen *signal.Signal[bool]
newTitle *signal.Signal[string]
newDir *signal.Signal[int]
creating *signal.Signal[bool]
client *ocapi.Client
cancelSSE context.CancelFunc
chat *chat
nav *ui.Navigator
}
func newController(st storage.Store) *controller {
conns := st.Connections()
sort.SliceStable(conns, func(i, j int) bool { return conns[i].LastUsedAt > conns[j].LastUsedAt })
c := &controller{
st: st,
connections: signal.NewFunc(conns, nil),
url: signal.New(""),
sessionQuery: signal.New(""),
searchOpen: signal.New(false),
status: signal.New(""),
errorMsg: signal.New(""),
formOpen: signal.New(false),
formLabel: signal.New(""),
formUseProxy: signal.New(false),
formProxy: signal.New(""),
formInsecure: signal.New(false),
passwordOpen: signal.New(false),
passwordText: signal.New(""),
passwordBusy: signal.New(false),
instancesOpen: signal.New(false),
server: signal.New(""),
connected: signal.New(false),
busy: signal.New(false),
connecting: signal.New(""),
activeID: signal.New(""),
sessions: signal.NewFunc([]ocapi.Session{}, nil),
active: signal.NewFunc(map[string]bool{}, nil),
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
defaultDir: signal.New(""),
newOpen: signal.New(false),
newTitle: signal.New(""),
newDir: signal.New(0),
creating: signal.New(false),
}
// Come back to the server last used, as the first-party client does.
if len(conns) > 0 {
c.connectTo(conns[0], "", false)
}
return c
}
// screen is the app's tree: a navigation stack while connected (its bar
// holds the session actions), and the bare server list while not, so the
// list is not framed by a bar whose buttons would do nothing.
func (c *controller) screen() ui.Node {
return ui.Column(ui.Style{Grow: 1},
ui.Show(c.connected,
func() ui.Node {
return ui.Stack(c.sessionsScreen, ui.ScreenOptions{
Title: ui.Val("OpenChamber"),
Actions: c.barActions(),
}, ui.Style{Grow: 1})
},
func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1}, c.connectionsScreen())
}),
c.formSheet(),
c.passwordSheet(),
c.instancesSheet(),
c.newSessionSheetNode(),
)
}
func (c *controller) barActions() []ui.Action {
return []ui.Action{
{
Title: ui.Val("新建"),
Icon: ui.IconPlus,
OnPress: c.openNewSession,
},
{
Title: ui.Val("刷新"),
Icon: ui.IconRefresh,
Disabled: signal.Func(func() bool { return c.busy.Get() }),
OnPress: c.refresh,
},
}
}
func (c *controller) shutdown() {
if c.cancelSSE != nil {
c.cancelSSE()
c.cancelSSE = nil
}
c.client = nil
}
// connectTo starts a connection attempt off the main thread. password is
// the one the user typed, if any; explicit marks a tap (a password may be
// asked for), while the launch reconnect stays quiet.
func (c *controller) connectTo(conn storage.Connection, password string, explicit bool) {
if c.connecting.Peek() != "" {
return
}
c.connecting.Set(conn.ID)
c.errorMsg.Set("")
go func() {
c.establish(conn, password, explicit)
}()
}
// establish runs the whole connect sequence: health, token probe, optional
// password login, first page of sessions.
func (c *controller) establish(conn storage.Connection, password string, explicit bool) {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
fail := func(err error) {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set(friendlyError(err))
if c.formConnecting {
// The connect came from the add/edit form: bring it back
// with what the user typed so it can be fixed.
c.formConnecting = false
c.formOpen.Set(true)
}
})
}
if !strings.Contains(conn.URL, "://") {
normalized, err := ocapi.NormalizeBaseURL(conn.URL)
if err != nil {
fail(err)
return
}
conn.URL = normalized
}
client, err := ocapi.New(conn.URL, ocapi.Options{Proxy: conn.Proxy, InsecureSkipVerify: conn.Insecure})
if err != nil {
fail(err)
return
}
health, err := client.Health(ctx)
if err != nil {
fail(err)
return
}
if health.OpenChamberVersion == "" {
fail(errors.New("这个地址不是 OpenChamber 服务器"))
return
}
token := ""
if !conn.Passwordless {
if t, ok, err := c.st.LoadToken(conn); err == nil && ok {
token = t
client.SetToken(t)
}
}
passwordless := conn.Passwordless
auth, authErr := client.SessionStatus(ctx)
switch {
case authErr == nil:
passwordless = auth.Disabled
case ocapi.IsUnauthorized(authErr):
if strings.TrimSpace(password) == "" {
if explicit {
ui.Post(func() {
c.connecting.Set("")
c.askPassword(conn)
})
} else {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set("登录已失效,请重新输入密码")
c.askPassword(conn)
})
}
if token != "" {
go func() { _ = c.st.ClearToken(conn) }()
}
return
}
res, err := client.Login(ctx, ocapi.LoginRequest{
Password: password,
DedupeKey: c.st.InstallID(),
ClientLabel: "OpenChamber Native",
ClientKind: "mobile",
DevicePlatform: "android",
})
if err != nil {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set(friendlyError(err))
c.passwordBusy.Set(false)
c.passwordOpen.Set(true)
})
return
}
if res.ClientToken == "" {
fail(errors.New("登录没有返回设备 token"))
return
}
_ = c.st.SaveToken(conn.ID, res.ClientToken)
passwordless = false
default:
fail(authErr)
return
}
if loc, err := client.Location(ctx); err == nil && loc.Directory != "" {
ui.Post(func() { c.defaultDir.Set(loc.Directory) })
}
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
if err != nil {
fail(err)
return
}
active, _ := client.ActiveSessions(ctx)
running := make(map[string]bool, len(active))
for id := range active {
running[id] = true
}
perms, _ := client.PendingPermissions(ctx, "")
info := fmt.Sprintf("%s · OpenChamber %s", c.labelOf(conn), health.OpenChamberVersion)
if !health.IsOpenCodeReady {
info += " · OpenCode 未就绪"
}
conn.URL = client.BaseURL()
if conn.Label == "" {
conn.Label = hostOf(conn.URL)
}
conn.ServerID = health.ServerID
conn.Passwordless = passwordless
conn.LastUsedAt = time.Now().UnixMilli()
ui.Post(func() {
c.connecting.Set("")
c.saveConnection(conn)
c.activeID.Set(conn.ID)
c.client = client
c.sessions.Set(page.Data)
c.active.Set(running)
c.perms.Set(perms)
c.server.Set(info)
c.connected.Set(true)
c.busy.Set(false)
c.formConnecting = false
c.formOpen.Set(false)
c.passwordOpen.Set(false)
c.passwordText.Set("")
c.passwordBusy.Set(false)
c.instancesOpen.Set(false)
c.errorMsg.Set("")
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
c.startEvents(client)
})
}
func (c *controller) saveConnection(conn storage.Connection) {
conns := c.connections.Peek()
found := false
next := make([]storage.Connection, 0, len(conns)+1)
for _, existing := range conns {
if existing.ID == conn.ID {
next = append(next, conn)
found = true
} else {
next = append(next, existing)
}
}
if !found {
if conn.ID == "" {
conn.ID = storage.NewID()
}
next = append(next, conn)
}
sort.SliceStable(next, func(i, j int) bool { return next[i].LastUsedAt > next[j].LastUsedAt })
c.st.SaveConnections(next)
c.connections.Set(next)
}
func (c *controller) labelOf(conn storage.Connection) string {
label := strings.TrimSpace(conn.Label)
if label != "" && label != conn.URL {
return label
}
if host := hostOf(conn.URL); host != "" {
return host
}
return label
}
// searchSessions runs the query the search field holds.
func (c *controller) searchSessions(q string) {
if c.client == nil || c.busy.Peek() {
return
}
c.busy.Set(true)
client := c.client
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc", Search: q})
ui.Post(func() {
c.busy.Set(false)
if err != nil {
c.errorMsg.Set(friendlyError(err))
return
}
c.sessions.Set(page.Data)
if q == "" {
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
} else {
c.status.Set(fmt.Sprintf("找到 %d 个会话", len(page.Data)))
}
})
}()
}
func (c *controller) refresh() {
if c.client == nil || c.busy.Peek() {
return
}
c.busy.Set(true)
client := c.client
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{
Limit: 50, Order: "desc", Search: c.sessionQuery.Peek(),
})
active, aerr := client.ActiveSessions(ctx)
running := make(map[string]bool, len(active))
for id := range active {
running[id] = true
}
perms, perr := client.PendingPermissions(ctx, "")
ui.Post(func() {
c.busy.Set(false)
if err != nil {
if ocapi.IsUnauthorized(err) {
c.logout("登录已失效,请输入密码重新连接")
return
}
c.errorMsg.Set(friendlyError(err))
return
}
c.sessions.Set(page.Data)
if aerr == nil {
c.active.Set(running)
}
if perr == nil {
c.perms.Set(perms)
}
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
})
}()
}
// logout drops the live session but keeps the saved servers.
func (c *controller) logout(reason string) {
if c.cancelSSE != nil {
c.cancelSSE()
c.cancelSSE = nil
}
var conn storage.Connection
if id := c.activeID.Peek(); id != "" {
for _, saved := range c.connections.Peek() {
if saved.ID == id {
conn = saved
}
}
}
c.client = nil
c.connected.Set(false)
c.activeID.Set("")
c.sessions.Set(nil)
c.active.Set(map[string]bool{})
c.perms.Set(nil)
c.server.Set("")
c.sessionQuery.Set("")
c.searchOpen.Set(false)
c.errorMsg.Set(reason)
if conn.ID != "" && reason != "" {
go func() { _ = c.st.ClearToken(conn) }()
}
}
func (c *controller) disconnect() {
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
c.chat.nav.Pop()
}
c.logout("")
}
// --- form ---------------------------------------------------------------
func (c *controller) openAddForm() {
c.formEditID = ""
c.url.Set("")
c.formLabel.Set("")
c.formUseProxy.Set(false)
c.formProxy.Set("")
c.formInsecure.Set(false)
c.errorMsg.Set("")
c.formOpen.Set(true)
}
func (c *controller) openEditForm(conn storage.Connection) {
c.formEditID = conn.ID
c.url.Set(conn.URL)
c.formLabel.Set(conn.Label)
c.formUseProxy.Set(conn.Proxy != "")
c.formProxy.Set(conn.Proxy)
c.formInsecure.Set(conn.Insecure)
c.errorMsg.Set("")
c.formOpen.Set(true)
}
func (c *controller) closeForm() {
c.formOpen.Set(false)
c.errorMsg.Set("")
}
func (c *controller) submitForm() {
raw := strings.TrimSpace(c.url.Peek())
if raw == "" {
c.errorMsg.Set("请输入服务器地址")
return
}
normalized, err := ocapi.NormalizeBaseURL(raw)
if err != nil {
c.errorMsg.Set(friendlyError(err))
return
}
conn := storage.Connection{ID: c.formEditID, URL: normalized, Label: strings.TrimSpace(c.formLabel.Peek())}
if c.formUseProxy.Peek() {
conn.Proxy = strings.TrimSpace(c.formProxy.Peek())
}
conn.Insecure = c.formInsecure.Peek()
if conn.ID != "" {
for _, saved := range c.connections.Peek() {
if saved.ID == conn.ID {
conn.ServerID = saved.ServerID
conn.Passwordless = saved.Passwordless
conn.LastUsedAt = saved.LastUsedAt
}
}
}
if conn.ID == "" {
conn.ID = storage.NewID()
}
c.saveConnection(conn)
c.formOpen.Set(false)
if !c.connected.Peek() {
c.formConnecting = true
c.connectTo(conn, "", true)
return
}
c.status.Set("已保存")
}
// --- password -----------------------------------------------------------
func (c *controller) askPassword(conn storage.Connection) {
c.passwordFor = conn
c.passwordText.Set("")
c.passwordBusy.Set(false)
c.passwordOpen.Set(true)
}
func (c *controller) submitPassword() {
if c.passwordBusy.Peek() {
return
}
pw := c.passwordText.Peek()
if strings.TrimSpace(pw) == "" {
return
}
conn := c.passwordFor
c.passwordBusy.Set(true)
c.passwordOpen.Set(false)
c.connectToPassword(conn, pw)
}
func (c *controller) connectToPassword(conn storage.Connection, password string) {
if c.connecting.Peek() != "" {
return
}
c.connecting.Set(conn.ID)
c.errorMsg.Set("")
go func() { c.establish(conn, password, true) }()
}
func (c *controller) cancelPassword() {
c.passwordOpen.Set(false)
c.passwordText.Set("")
c.passwordBusy.Set(false)
}
var errUnauthorized = errors.New("这个服务器需要密码")
func friendlyError(err error) string {
if err == nil {
return ""
}
if wait, ok := ocapi.IsRateLimited(err); ok {
secs := int(wait.Seconds() + 0.5)
if secs <= 0 {
secs = 30
}
return fmt.Sprintf("尝试过于频繁,请 %d 秒后重试", secs)
}
if ocapi.IsUnauthorized(err) {
return "密码错误"
}
if errors.Is(err, errUnauthorized) {
return "该服务器需要密码"
}
msg := err.Error()
switch {
case strings.Contains(msg, "certificate"):
return "TLS 证书校验失败:" + msg
case strings.Contains(msg, "no such host"):
return "找不到这个地址:" + msg
case strings.Contains(msg, "connection refused"):
return "连接被拒绝,请确认服务器地址与端口"
case strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline exceeded"):
return "连接超时,请检查网络或代理"
case strings.Contains(msg, "proxy"):
return "代理连接失败:" + msg
}
return msg
}
func hostOf(raw string) string {
s := strings.TrimSpace(raw)
if i := strings.Index(s, "://"); i >= 0 {
s = s[i+3:]
}
if i := strings.IndexByte(s, '/'); i >= 0 {
s = s[:i]
}
return s
}
func shortPath(p string) string {
p = strings.TrimRight(p, "/")
if p == "" {
return ""
}
if i := strings.LastIndex(p, "/"); i >= 0 && i+1 < len(p) {
return p[i+1:]
}
return p
}
func relativeTime(ms int64) string {
if ms <= 0 {
return ""
}
d := time.Since(time.UnixMilli(ms))
switch {
case d < time.Minute:
return "刚刚"
case d < time.Hour:
return fmt.Sprintf("%d 分钟前", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%d 小时前", int(d.Hours()))
default:
return fmt.Sprintf("%d 天前", int(d.Hours()/24))
}
}
-355
View File
@@ -1,355 +0,0 @@
package appui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/egoist/asuka/ui"
"github.com/egoist/asuka/uitest"
"github.com/openchamber/openchamber-native/internal/storage"
)
// memStore is a storage.Store that keeps everything in memory.
type memStore struct {
mu sync.Mutex
conns []storage.Connection
tokens map[string]string
id string
}
func (m *memStore) Connections() []storage.Connection {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]storage.Connection, len(m.conns))
copy(out, m.conns)
return out
}
func (m *memStore) SaveConnections(list []storage.Connection) {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]storage.Connection, len(list))
copy(out, list)
m.conns = out
}
func (m *memStore) InstallID() string {
m.mu.Lock()
defer m.mu.Unlock()
if m.id == "" {
m.id = "test-install"
}
return m.id
}
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tokens[c.ID]
return t, ok, nil
}
func (m *memStore) SaveToken(id, token string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.tokens == nil {
m.tokens = map[string]string{}
}
m.tokens[id] = token
return nil
}
func (m *memStore) ClearToken(c storage.Connection) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.tokens, c.ID)
return nil
}
func (m *memStore) token(id string) string {
m.mu.Lock()
defer m.mu.Unlock()
return m.tokens[id]
}
func (m *memStore) connections() []storage.Connection {
return m.Connections()
}
// fakeServer stands in for OpenChamber: /health, /auth/session and the
// session list. An empty password makes it passwordless.
func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httptest.Server {
t.Helper()
if sessionTitle == "" {
sessionTitle = "First session"
}
mux := http.NewServeMux()
authorized := func(r *http.Request) bool {
if validToken == "" {
return true
}
return r.Header.Get("Authorization") == "Bearer "+validToken
}
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true,"serverId":"srv_1"}`)
})
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
if password == "" {
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
return
}
switch r.Method {
case http.MethodGet:
if authorized(r) {
fmt.Fprint(w, `{"authenticated":true,"scope":"client"}`)
return
}
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
case http.MethodPost:
var body struct {
Password string `json:"password"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Password != password {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"error":"Invalid credentials"}`)
return
}
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
}
})
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if !authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
title := sessionTitle
if q := r.URL.Query().Get("search"); q != "" {
title = "Found " + q
}
fmt.Fprintf(w, `{"data":[{"id":"ses_1","title":%q,"time":{"created":1,"updated":2},
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, title)
})
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
})
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[]}`)
})
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
<-r.Context().Done()
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func mount(t *testing.T, st *memStore) *uitest.App {
t.Helper()
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
}
// connectViaForm adds a server from the first screen (or the saved list)
// and taps Connect.
func connectViaForm(t *testing.T, a *uitest.App, url string) {
t.Helper()
if a.Has("手动输入地址") {
a.Tap("手动输入地址")
} else {
a.Tap("添加服务器")
}
a.Type("http://192.168.1.5:3000", url)
a.Tap("连接")
}
// disconnectViaInstances opens the instance list and drops the live
// connection from there; the sessions header has only the list button.
func disconnectViaInstances(t *testing.T, a *uitest.App) {
t.Helper()
a.Tap("实例")
a.Tap("断开当前连接")
}
func unlockWith(t *testing.T, a *uitest.App, password string) {
t.Helper()
a.WaitFor("这台服务器需要密码。")
a.Type("密码", password)
a.Tap("解锁")
}
func TestConnectWithPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
unlockWith(t, a, "secret")
a.WaitFor("First session")
conns := st.connections()
if len(conns) != 1 || conns[0].URL != srv.URL {
t.Fatalf("connections = %+v", conns)
}
if got := st.token(conns[0].ID); got != "oc_client_test" {
t.Errorf("token = %q", got)
}
if conns[0].Passwordless {
t.Error("password server marked passwordless")
}
}
func TestWrongPasswordThenRetry(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
unlockWith(t, a, "nope")
a.WaitFor("密码错误")
// The prompt stays up so the password can be retried.
a.Type("密码", "secret")
a.Tap("解锁")
a.WaitFor("First session")
}
func TestAutoReconnectWithStoredToken(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
tokens: map[string]string{"a": "oc_client_test"},
}
a := mount(t, st)
a.WaitFor("First session")
a.ExpectNo("手动输入地址")
a.ExpectNo("这台服务器需要密码。")
}
func TestExpiredTokenAsksForPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
tokens: map[string]string{"a": "revoked"},
}
a := mount(t, st)
a.WaitFor("登录已失效,请重新输入密码")
a.Until("the revoked token to be dropped", func() bool { return st.token("a") == "" })
unlockWith(t, a, "secret")
a.WaitFor("First session")
}
func TestPasswordlessServer(t *testing.T) {
srv := fakeServer(t, "", "", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
conns := st.connections()
if len(conns) != 1 || !conns[0].Passwordless {
t.Fatalf("connections = %+v", conns)
}
if got := st.token(conns[0].ID); got != "" {
t.Errorf("unexpected token %q", got)
}
}
func TestMultipleConnectionsAndSwitch(t *testing.T) {
srvA := fakeServer(t, "", "", "Session A")
srvB := fakeServer(t, "", "", "Session B")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 2},
{ID: "b", URL: srvB.URL, Label: "B", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Expect("A")
a.Expect("B")
a.Tap("B")
a.WaitFor("Session B")
}
func TestAddAnotherConnection(t *testing.T) {
srvA := fakeServer(t, "", "", "Session A")
srvB := fakeServer(t, "", "", "Session B")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Tap("添加服务器")
a.Type("http://192.168.1.5:3000", srvB.URL)
a.Type("名称(可选)", "B")
a.Tap("连接")
a.WaitFor("Session B")
if conns := st.connections(); len(conns) != 2 {
t.Fatalf("connections = %+v", conns)
}
}
func TestDeleteConnection(t *testing.T) {
srv := fakeServer(t, "", "", "Session A")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srv.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Tap("操作")
a.Tap("删除")
a.Tap("删除")
a.Until("the connection list to empty", func() bool { return len(st.connections()) == 0 })
a.Expect("手动输入地址")
}
func TestLabelFallsBackToHost(t *testing.T) {
c := &controller{}
conn := storage.Connection{URL: "http://192.168.1.5:3000", Label: "http://192.168.1.5:3000"}
if got := c.labelOf(conn); got != "192.168.1.5:3000" {
t.Fatalf("label = %q", got)
}
conn.Label = "Home"
if got := c.labelOf(conn); got != "Home" {
t.Fatalf("label = %q", got)
}
}
func TestFailedAddReopensTheForm(t *testing.T) {
a := mount(t, &memStore{})
a.Tap("手动输入地址")
a.Type("http://192.168.1.5:3000", "http://127.0.0.1:1")
a.Tap("连接")
a.WaitFor("连接被拒绝,请确认服务器地址与端口")
a.Expect("添加服务器")
a.Expect("取消")
}
func TestSessionSearch(t *testing.T) {
srv := fakeServer(t, "", "", "First session")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("搜索会话")
a.Type("输入关键词搜索", "deploy")
a.WaitFor("Found deploy")
a.Tap("清除")
a.WaitFor("First session")
}
-137
View File
@@ -1,137 +0,0 @@
package appui
import (
"strings"
"time"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func (c *controller) sessionsScreen() ui.Node {
nav := ui.UseNavigator()
c.nav = nav
// Live search: typing settles for a moment, then the server is asked.
signal.Effect(func() {
q := c.sessionQuery.Get()
if !c.searchOpen.Get() {
return
}
t := time.AfterFunc(350*time.Millisecond, func() {
ui.Post(func() { c.searchSessions(q) })
})
signal.OnCleanup(func() { t.Stop() })
})
return ui.SafeArea(ui.Style{Grow: 1}, ui.Column(ui.Style{Grow: 1},
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red, Lines: 2})
}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconSearch, Label: ui.Val("搜索会话"),
OnPress: func() {
open := !c.searchOpen.Peek()
c.searchOpen.Set(open)
if !open {
c.sessionQuery.Set("")
c.searchSessions("")
}
}}),
c.instancesButton(),
),
ui.Show(c.searchOpen, func() ui.Node {
return ui.Row(ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6, Align: ui.AlignCenter},
ui.TextField(ui.TextFieldProps{
Value: c.sessionQuery,
Placeholder: ui.Val("输入关键词搜索"),
ReturnKey: ui.ReturnSearch,
OnSubmit: func() { c.searchSessions(c.sessionQuery.Peek()) },
Style: ui.Style{Grow: 1},
}),
ui.Button(ui.ButtonProps{Title: ui.Val("清除"), OnPress: func() {
c.sessionQuery.Set("")
c.searchSessions("")
}}),
)
}),
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
func() ui.Node {
return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8},
ui.StaticText("还没有会话", ui.Style{Font: fonts.Headline}),
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
)
}),
ui.List(ui.ListProps{
Appearance: ui.ListPlain,
OnRefresh: c.refresh,
Refreshing: c.busy,
SwipeActions: func(i int) []ui.Action {
sess := c.sessions.Peek()[i]
return []ui.Action{{Title: ui.Val("归档"), Icon: "archivebox",
OnPress: func() { c.archiveSession(sess) }}}
},
LeadingSwipeActions: func(i int) []ui.Action {
sess := c.sessions.Peek()[i]
return []ui.Action{{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDelete(sess) }}}
},
}, c.sessions, func(s ocapi.Session) string { return s.ID },
func(s signal.Accessor[ocapi.Session], idx signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() {
sess := s.Get()
ch := c.openChat(&sess, nav)
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)})
},
OnLongPress: func() { c.sessionMenu(s.Get()) },
}, c.sessionRow(s, idx))
}),
))
}
func (c *controller) sessionRow(s signal.Accessor[ocapi.Session], _ signal.Accessor[int]) ui.Node {
return ui.Row(ui.Style{Gap: 10, Padding: ui.Symmetric(10, 16), Align: ui.AlignCenter},
ui.Show(signal.Func(func() bool { return c.active.Get()[s.Get().ID] }),
func() ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
CornerRadius: 4, Background: colors.Accent}})
}),
ui.Column(ui.Style{Gap: 3, Grow: 1},
ui.Text(signal.Func(func() string {
if t := strings.TrimSpace(s.Get().Title); t != "" {
return t
}
return "(未命名会话)"
}), ui.Style{Font: fonts.Headline, Lines: 2}),
ui.Text(signal.Func(func() string {
sess := s.Get()
dir := ""
if sess.Location != nil {
dir = sess.Location.Directory
}
updated := sess.Time.Updated
if sess.Time.Busy > updated {
updated = sess.Time.Busy
}
model := ""
if sess.Model != nil {
model = sess.Model.ID
}
parts := []string{shortPath(dir), relativeTime(updated), model}
out := make([]string, 0, len(parts))
for _, p := range parts {
if p != "" {
out = append(out, p)
}
}
return strings.Join(out, " · ")
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
)
}
+299
View File
@@ -0,0 +1,299 @@
package appui
import (
"net/url"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/storage"
)
// serversView is the first screen: the list of saved servers, or the
// connect form when one is being edited or needs a password.
func (a *App) serversView(c *ui.Context) {
t := c.Theme()
if a.phase == "form" {
a.connectFormView(c)
return
}
ui.Column(c).Fill().Background(t.Background).Children(func() {
header := ui.Column(c).FillWidth().Padding(16, 20, 8, 20)
header.Children(func() {
ui.Text(c, "OpenChamber").FontSize(28).Bold().Role(ui.RoleHeading).Level(1)
ui.Text(c, "连接你的 OpenChamber 服务器").FontSize(14).TextColor(t.TextMuted)
})
if a.errorText != "" {
ui.Text(c, a.errorText).FontSize(13).TextColor(t.Danger).Padding(12, 16, 4, 16)
}
scroll := ui.Scroll(c).Grow(1).PaddingX(16)
scroll.Children(func() {
ui.Column(c).FillWidth().Gap(10).Children(func() {
conns := a.store.Connections()
for i := range conns {
conn := &conns[i]
a.serverCard(c, conn)
}
add := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(14, 14).
Radius(14).Border(0.5, t.Border).Role(ui.RoleButton).Label("添加服务器")
add.Children(func() {
ui.Text(c, "+").FontSize(20).TextColor(t.Accent).Width(30).TextAlign(ui.Center)
ui.Text(c, "添加服务器").FontSize(16)
})
if add.Clicked() {
a.newServerForm()
}
})
})
})
}
func (a *App) serverCard(c *ui.Context, conn *storage.Connection) {
t := c.Theme()
connected := a.client != nil && a.conn.ID == conn.ID
card := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(14, 14).
Background(t.Surface).Radius(14).Role(ui.RoleButton).Label("服务器 " + conn.Label)
card.Children(func() {
info := ui.Column(c).Grow(1).Basis(0).Gap(2)
info.Children(func() {
ui.Text(c, conn.Label).FontSize(16).FontWeight(600).MaxLines(1)
ui.Text(c, conn.URL).FontSize(13).TextColor(t.TextMuted).MaxLines(1)
})
if connected {
ui.Text(c, "已连接").FontSize(13).TextColor(t.Accent)
} else if ui.Button(c, "连接").Clicked() {
a.connectTo(*conn, "", false)
}
if ui.Button(c, "⋯").Label("服务器选项").Width(40).Clicked() {
a.serverActions(conn)
}
})
}
// serverActions opens a connection's menu: connect, edit, delete.
func (a *App) serverActions(conn *storage.Connection) {
open := true
a.serverActionOpen = &open
a.serverActionTarget = conn
}
// serverActionSheet draws the open connection menu.
func (a *App) serverActionSheet(c *ui.Context) {
if a.serverActionOpen == nil || !*a.serverActionOpen {
return
}
conn := a.serverActionTarget
if conn == nil {
return
}
mobile.ActionSheet(c, a.serverActionOpen, mobile.ActionSheetOptions{
Title: conn.Label,
Cancel: "取消",
}, mobile.Action{
Label: "连接",
OnTap: func() { a.connectTo(*conn, "", false) },
}, mobile.Action{
Label: "编辑",
OnTap: func() { a.editServerForm(conn) },
}, mobile.Action{
Label: "删除",
Destructive: true,
OnTap: func() { a.deleteServer(conn) },
})
}
// deleteServer asks and removes a saved server.
func (a *App) deleteServer(conn *storage.Connection) {
a.confirmDelete = true
a.deleteTarget = conn
}
// deleteConfirmSheet asks "删除服务器?".
func (a *App) deleteConfirmSheet(c *ui.Context) {
if !a.confirmDelete {
return
}
buttons := ui.AlertDialog(c, &a.confirmDelete, "删除服务器?",
"“"+a.deleteTarget.Label+"”将从列表移除,设备令牌也会删除。", "取消", "删除")
if buttons == 1 {
if a.client != nil && a.conn.ID == a.deleteTarget.ID {
a.disconnect()
}
_ = a.store.ClearToken(*a.deleteTarget)
conns := a.store.Connections()
next := conns[:0]
for _, x := range conns {
if x.ID != a.deleteTarget.ID {
next = append(next, x)
}
}
a.store.SaveConnections(next)
}
}
// connectFormView is the add/edit form with the password field.
func (a *App) connectFormView(c *ui.Context) {
t := c.Theme()
ui.Column(c).Fill().Background(t.Background).Children(func() {
head := ui.Row(c).FillWidth().Padding(12, 12).AlignItems(ui.Center).Gap(8)
head.Children(func() {
if ui.Button(c, "‹").Label("返回").Width(40).Clicked() {
a.phase = ""
a.formEditing = nil
a.formError = ""
}
ui.Text(c, a.formTitle).FontSize(18).FontWeight(600).Grow(1)
})
scroll := ui.Scroll(c).Grow(1).PaddingX(16)
scroll.Children(func() {
ui.Column(c).FillWidth().Gap(10).Children(func() {
a.fieldLabel(c, "名称")
ui.TextInput(c, &a.formLabel).Placeholder("如 我的电脑")
a.fieldLabel(c, "服务器地址")
ui.TextInput(c, &a.formURL).Placeholder("http://192.168.1.10:3000").Keyboard(ui.KeyboardURL)
a.fieldLabel(c, "代理(可选)")
ui.TextInput(c, &a.formProxy).Placeholder("http://… 或 socks5://…").Keyboard(ui.KeyboardURL)
a.fieldLabel(c, "自签证书指纹(可选)")
ui.TextInput(c, &a.formFinger).Placeholder("SHA-256 十六进制")
row := ui.Row(c).FillWidth().AlignItems(ui.Center)
row.Children(func() {
ui.Text(c, "信任自签名证书").Grow(1).FontSize(15)
ui.Switch(c, &a.formInsecure)
})
if a.formEditing != nil {
a.fieldLabel(c, "密码")
ui.TextInput(c, &a.formPassword).Password().Placeholder("服务器密码")
}
if a.formError != "" {
ui.Text(c, a.formError).FontSize(13).TextColor(t.Danger)
}
if a.busy {
ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(4, 0).Children(func() {
ui.Spinner(c)
ui.Text(c, "连接中…").TextColor(t.TextMuted)
})
} else if ui.PrimaryButton(c, "连接").FillWidth().Padding(8, 0).Clicked() {
a.submitForm()
}
})
})
})
}
func (a *App) fieldLabel(c *ui.Context, s string) {
t := c.Theme()
ui.Text(c, s).FontSize(13).TextColor(t.TextMuted)
}
func (a *App) submitForm() {
conn := a.formEditing
if conn == nil {
conn = &storage.Connection{ID: storage.NewID()}
}
conn.Label = trimOr(a.formLabel, hostOf(a.formURL))
conn.URL = a.formURL
conn.Proxy = a.formProxy
conn.Insecure = a.formInsecure
conn.Fingerprint = a.formFinger
a.connectTo(*conn, a.formPassword, false)
}
func (a *App) editServerForm(conn *storage.Connection) {
a.phase = "form"
a.formEditing = conn
a.formTitle = "编辑 " + conn.Label
a.formLabel = conn.Label
a.formURL = conn.URL
a.formProxy = conn.Proxy
a.formInsecure = conn.Insecure
a.formFinger = conn.Fingerprint
a.formPassword = ""
a.formError = ""
}
func (a *App) newServerForm() {
a.phase = "form"
a.formEditing = nil
a.formTitle = "添加服务器"
a.formLabel = ""
a.formURL = ""
a.formProxy = ""
a.formInsecure = false
a.formFinger = ""
a.formPassword = ""
a.formError = ""
}
// -------------------------------------------------------------- instances
// instancesSheet shows the instance list: switch servers, disconnect, add.
func (a *App) instancesSheet(c *ui.Context) {
if !a.instancesOpen {
return
}
t := c.Theme()
mobile.Sheet(c, &a.instancesOpen, mobile.SheetOptions{
Detents: []float32{0.6},
Label: "服务器",
}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(2).Children(func() {
ui.Text(c, "服务器").FontSize(20).Bold().Padding(0, 0, 0, 6)
conns := a.store.Connections()
for i := range conns {
conn := &conns[i]
connected := a.client != nil && a.conn.ID == conn.ID
row := mobile.ListRow(c, mobile.RowOptions{
Title: conn.Label,
Subtitle: conn.URL,
Trailing: func() {
if connected {
ui.Text(c, "已连接").FontSize(13).TextColor(t.Accent)
}
},
})
if row.Clicked() && !connected {
a.instancesOpen = false
a.switchTo(*conn)
}
}
row := mobile.ListRow(c, mobile.RowOptions{Title: "+ 添加服务器"})
if row.Clicked() {
a.instancesOpen = false
a.newServerForm()
}
if a.client != nil {
row := mobile.ListRow(c, mobile.RowOptions{Title: "断开当前连接"})
if row.Clicked() {
a.instancesOpen = false
a.disconnect()
}
}
})
})
}
func (a *App) switchTo(conn storage.Connection) {
if a.chat != nil {
a.closeChat()
}
a.stopStream()
a.client = nil
a.conn = storage.Connection{}
a.phase = ""
a.sessions = nil
a.connectTo(conn, "", true)
}
func trimOr(s, fallback string) string {
if s == "" {
return fallback
}
return s
}
func hostOf(raw string) string {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return raw
}
return u.Host
}
+152
View File
@@ -0,0 +1,152 @@
package appui
import (
"time"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// sessionsView is the connected screen: the sessions list with its header.
func (a *App) sessionsView(c *ui.Context) {
t := c.Theme()
ui.Column(c).Fill().Background(t.Background).Children(func() {
mobile.TopBar(c, mobile.TopBarOptions{
Title: "会话",
Leading: func() {
// The single server entry: opens the instance list.
if a.iconButton(c, "server", "服务器").Clicked() {
a.instancesOpen = true
}
},
Trailing: func() {
if a.iconButton(c, "search", "搜索").Clicked() {
a.searchOpen = !a.searchOpen
if !a.searchOpen {
a.searchText = ""
a.loadSessions()
}
}
if a.iconButton(c, "plus", "新建会话").Clicked() {
a.newSessionForm()
}
},
})
if a.searchOpen {
ui.TextInput(c, &a.searchText).Placeholder("搜索会话").PaddingX(16).AutoFocus()
a.scheduleSearch()
}
if a.errorText != "" {
ui.Text(c, a.errorText).FontSize(13).TextColor(t.Danger).Padding(8, 16, 0, 16)
}
a.sessionList(c)
})
a.instancesSheet(c)
a.serverActionSheet(c)
a.deleteConfirmSheet(c)
a.newSessionSheet(c)
a.sessionActionSheet(c)
a.renameSheet(c)
a.sessionDeleteConfirm(c)
}
// iconButton is a small square button with an icon.
func (a *App) iconButton(c *ui.Context, icon, label string) ui.Element {
btn := ui.Button(c, "").Width(44).Height(44).Padding(0, 0)
btn.Children(func() {
bmp := iconBitmap(icon)
if bmp != nil {
ui.Image(c, bmp).Size(22, 22)
} else {
ui.Text(c, icon).FontSize(18)
}
})
_ = label
return btn
}
func (a *App) sessionList(c *ui.Context) {
if a.sessionsLoad && len(a.sessions) == 0 {
ui.Column(c).Fill().Center().Children(func() {
ui.Spinner(c)
})
return
}
if len(a.sessions) == 0 && !a.sessionsLoad {
ui.Column(c).Fill().Center().Gap(8).Children(func() {
ui.Text(c, "暂无会话")
if ui.PrimaryButton(c, "新建会话").Clicked() {
a.newSessionForm()
}
})
return
}
list := ui.List(c, &a.sessionListState, len(a.sessions))
list.ItemKey(func(i int) any { return a.sessions[i].ID })
list.Rows(func(r ui.ListRow) {
i := r.Index
s := a.sessions[i]
row := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(12, 16).
Role(ui.RoleButton).Label(s.Title)
row.Children(func() {
col := ui.Column(c).Grow(1).Basis(0).Gap(2)
col.Children(func() {
title := s.Title
if title == "" {
title = "(无标题会话)"
}
ui.Text(c, title).FontSize(16).FontWeight(600).MaxLines(1)
ui.Text(c, a.sessionSubtitle(s)).FontSize(13).TextColor(t(c).TextMuted).MaxLines(1)
})
if a.active[s.ID] {
ui.Text(c, "●").TextColor(t(c).Accent).FontSize(10)
}
if ui.Button(c, "⋯").Label("会话操作").Width(40).Clicked() {
a.openSessionActions(s)
}
})
if row.Clicked() {
a.openChat(s)
}
})
}
func t(c *ui.Context) *ui.Theme { return c.Theme() }
func (a *App) sessionSubtitle(s ocapi.Session) string {
parts := []string{}
if s.Agent != "" {
parts = append(parts, s.Agent)
}
if s.Model != nil {
parts = append(parts, a.modelName(s.Model))
}
if s.Time.Updated > 0 {
parts = append(parts, time.UnixMilli(s.Time.Updated).Format("01-02 15:04"))
}
out := ""
for i, p := range parts {
if i > 0 {
out += " · "
}
out += p
}
return out
}
// scheduleSearch debounces search input.
func (a *App) scheduleSearch() {
if a.searchTimer != nil {
a.searchTimer.Stop()
}
a.searchTimer = time.AfterFunc(350*time.Millisecond, func() {
a.win.Update(func() {
if a.searchText != "" {
a.searchSessions(a.searchText)
} else {
a.loadSessions()
}
})
})
}
+127 -203
View File
@@ -2,239 +2,163 @@ package appui
import ( import (
"context" "context"
"strings"
"time" "time"
"github.com/egoist/asuka/fonts" "github.com/egoist/mygo/ui"
"github.com/egoist/asuka/signal" "github.com/egoist/mygo/ui/mobile"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi" "github.com/openchamber/openchamber-native/internal/ocapi"
) )
func (c *controller) sessionMenu(s ocapi.Session) { // new session -----------------------------------------------------------
ui.Alert(ui.AlertProps{
Title: "会话", func (a *App) newSessionForm() {
ActionSheet: true, a.newTitle = ""
Actions: []ui.Action{ a.newOpen = true
{Title: ui.Val("重命名"), Icon: "pencil", OnPress: func() { c.renameSession(s) }},
{Title: ui.Val("归档"), Icon: "archivebox", OnPress: func() { c.archiveSession(s) }},
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDelete(s) }},
},
})
} }
func (c *controller) renameSession(s ocapi.Session) { func (a *App) newSessionSheet(c *ui.Context) {
name := signal.New(s.Title) if !a.newOpen {
ui.Alert(ui.AlertProps{
Title: "重命名会话",
Message: "标题留空时,服务端不会自动生成新标题。",
Fields: []ui.AlertField{{Text: name, Placeholder: "标题"}},
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("保存"), Role: ui.ActionDefault,
Disabled: signal.Func(func() bool { return strings.TrimSpace(name.Get()) == "" }),
OnPress: func() { c.patchSessionOnServer(s, name.Get()) }},
},
})
}
func (c *controller) patchSessionOnServer(s ocapi.Session, title string) {
client := c.client
if client == nil {
return return
} }
dir := sessionDir(s) mobile.Sheet(c, &a.newOpen, mobile.SheetOptions{Detents: []float32{0.4}}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(10).Children(func() {
ui.Text(c, "新建会话").FontSize(20).Bold()
ui.TextInput(c, &a.newTitle).Placeholder("标题(可选)").AutoFocus()
if ui.PrimaryButton(c, "创建").FillWidth().Clicked() {
a.newOpen = false
a.createSession()
}
})
})
}
func (a *App) createSession() {
dir := a.dir()
title := a.newTitle
go func() { go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel() defer cancel()
t := strings.TrimSpace(title) sess, err := a.client.CreateSession(ctx, ocapi.CreateSessionOptions{Title: title, Directory: dir})
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Title: &t}) a.post(func() {
ui.Post(func() {
if err != nil { if err != nil {
c.status.Set(friendlyError(err)) a.errorText = friendlyError(err)
return return
} }
c.sessions.Update(func(list []ocapi.Session) []ocapi.Session { a.sessions = append([]ocapi.Session{sess}, a.sessions...)
next := make([]ocapi.Session, len(list)) a.openChat(sess)
copy(next, list)
for i := range next {
if next[i].ID == s.ID {
next[i].Title = t
}
}
return next
})
}) })
}() }()
} }
func (c *controller) archiveSession(s ocapi.Session) { // session actions -------------------------------------------------------
client := c.client
if client == nil { func (a *App) openSessionActions(s ocapi.Session) {
a.sessionActionOpen = true
a.sessionActionTarget = s
}
func (a *App) sessionActionSheet(c *ui.Context) {
if !a.sessionActionOpen {
return return
} }
dir := sessionDir(s) s := a.sessionActionTarget
go func() { mobile.ActionSheet(c, &a.sessionActionOpen, mobile.ActionSheetOptions{Title: s.Title, Cancel: "取消"},
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) mobile.Action{Label: "重命名", OnTap: func() { a.renameSession(s) }},
defer cancel() mobile.Action{Label: "归档", OnTap: func() { a.setArchived(s, true) }},
archived := true mobile.Action{Label: "删除", Destructive: true, OnTap: func() { a.deleteSession(s) }},
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Archived: &archived})
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.removeSession(s.ID)
})
}()
}
func (c *controller) confirmDelete(s ocapi.Session) {
ui.Alert(ui.AlertProps{
Title: "删除会话?",
Message: "会话及其子会话会被永久删除,无法撤销。",
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
OnPress: func() { c.deleteSession(s) }},
},
})
}
func (c *controller) deleteSession(s ocapi.Session) {
client := c.client
if client == nil {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err := client.DeleteSession(ctx, s.ID, dir)
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.removeSession(s.ID)
})
}()
}
func sessionDir(s ocapi.Session) string {
if s.Location != nil {
return s.Location.Directory
}
return ""
}
// directories lists the working directories a new session can use: the
// server's default, then every directory the loaded sessions live in.
func (c *controller) directories() signal.Accessor[[]string] {
return signal.Func(func() []string {
seen := map[string]bool{}
out := make([]string, 0, 4)
add := func(d string) {
if d == "" || seen[d] {
return
}
seen[d] = true
out = append(out, d)
}
add(c.defaultDir.Get())
for _, s := range c.sessions.Get() {
if s.Location != nil {
add(s.Location.Directory)
}
}
return out
})
}
func chatActions(ch *chat) []ui.Action {
return []ui.Action{
{Title: ui.Val("模型"), OnPress: ch.openModelPicker},
{Title: ui.Val("Agent"), OnPress: ch.openAgentPicker},
}
}
func (c *controller) openNewSession() {
if c.client == nil {
return
}
c.newTitle.Set("")
c.newDir.Set(0)
c.creating.Set(false)
c.newOpen.Set(true)
}
func (c *controller) newSessionSheetNode() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.newOpen,
Detents: ui.DetentLarge,
Grabber: true,
Content: c.newSessionSheet,
OnDismiss: func() { c.creating.Set(false) },
})
}
func (c *controller) newSessionSheet() ui.Node {
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14, Grow: 1},
ui.StaticText("新建会话", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.TextField(ui.TextFieldProps{
Value: c.newTitle,
Placeholder: ui.Val("标题(可选,留空由服务端生成)"),
ReturnKey: ui.ReturnGo,
OnSubmit: c.createSession,
}),
ui.Picker(ui.PickerProps{
Items: c.directories(),
Selected: c.newDir,
Label: ui.Val("工作目录"),
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("创建"),
Variant: ui.ButtonFilled,
Disabled: c.creating,
OnPress: c.createSession,
}),
ui.Show(c.creating, func() ui.Node { return ui.Activity() }),
) )
} }
func (c *controller) createSession() { func (a *App) renameSession(s ocapi.Session) {
client := c.client a.renameOpen = true
nav := c.nav a.renameTarget = s
if client == nil || c.creating.Peek() { a.renameText = s.Title
}
func (a *App) renameSheet(c *ui.Context) {
if !a.renameOpen {
return return
} }
dirs := signal.Untrack(func() []string { return c.directories().Get() }) mobile.Sheet(c, &a.renameOpen, mobile.SheetOptions{Detents: []float32{0.3}}, func() {
dir := "" ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(10).Children(func() {
if idx := c.newDir.Peek(); idx >= 0 && idx < len(dirs) { ui.Text(c, "重命名").FontSize(20).Bold()
dir = dirs[idx] ui.TextInput(c, &a.renameText).AutoFocus()
} if ui.PrimaryButton(c, "保存").FillWidth().Clicked() {
title := strings.TrimSpace(c.newTitle.Peek()) a.renameOpen = false
c.creating.Set(true) a.doRename()
}
})
})
}
func (a *App) doRename() {
title := a.renameText
s := a.renameTarget
go func() { go func() {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() defer cancel()
s, err := client.CreateSession(ctx, ocapi.CreateSessionOptions{Directory: dir, Title: title}) err := a.client.UpdateSession(ctx, s.ID, a.dir(), ocapi.SessionPatch{Title: &title})
ui.Post(func() { a.post(func() {
c.creating.Set(false)
if err != nil { if err != nil {
c.status.Set(friendlyError(err)) a.errorText = friendlyError(err)
return return
} }
c.newOpen.Set(false) a.patchSession(s.ID, func(x *ocapi.Session) { x.Title = title })
c.sessions.Update(func(list []ocapi.Session) []ocapi.Session { })
next := make([]ocapi.Session, 0, len(list)+1) }()
next = append(next, s) }
return append(next, list...)
}) func (a *App) setArchived(s ocapi.Session, on bool) {
if nav != nil { go func() {
ch := c.openChat(&s, nav) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)}) defer cancel()
err := a.client.UpdateSession(ctx, s.ID, a.dir(), ocapi.SessionPatch{Archived: &on})
a.post(func() {
if err != nil {
a.errorText = friendlyError(err)
}
})
}()
}
func (a *App) deleteSession(s ocapi.Session) {
a.sessionDeleteOpen = true
target := s
a.sessionDeleteTarget = &target
}
func (a *App) sessionDeleteConfirm(c *ui.Context) {
if !a.sessionDeleteOpen {
return
}
title := ""
if a.sessionDeleteTarget != nil {
title = a.sessionDeleteTarget.Title
}
buttons := ui.AlertDialog(c, &a.sessionDeleteOpen, "删除会话?",
"“"+title+"”及其子会话将被删除,且无法恢复。", "取消", "删除")
if buttons == 1 {
a.doDeleteSession()
}
}
func (a *App) doDeleteSession() {
if a.sessionDeleteTarget == nil {
return
}
s := *a.sessionDeleteTarget
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := a.client.DeleteSession(ctx, s.ID, a.dir())
a.post(func() {
if err != nil {
a.errorText = friendlyError(err)
return
}
a.removeSession(s.ID)
if a.chat != nil && a.chat.id == s.ID {
a.closeChat()
} }
}) })
}() }()
+344
View File
@@ -0,0 +1,344 @@
package appui
import (
"context"
"os"
"strings"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/mobile"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/tts"
)
// sheets draws the chat's overlays: menus, pickers and previews.
func (ch *chat) sheets(c *ui.Context) {
ch.footerSheet(c)
ch.userSheet(c)
ch.pickerSheet(c)
ch.usageSheet(c)
ch.previewSheet(c)
ch.attachSheet(c)
ch.revertConfirm(c)
ch.a.sessionActionSheet(c)
ch.a.newSessionSheet(c)
ch.a.serverActionSheet(c)
ch.a.deleteConfirmSheet(c)
ch.a.renameSheet(c)
ch.a.sessionDeleteConfirm(c)
}
// openFooter opens the actions of the turn that finished last.
func (ch *chat) openFooter() {
for i := len(ch.msgs) - 1; i >= 0; i-- {
if ch.msgs[i].Type == "assistant" && ch.msgs[i].Time.Completed > 0 {
ch.footerOpen = true
ch.footerID = ch.msgs[i].ID
return
}
}
}
func (ch *chat) footerSheet(c *ui.Context) {
if !ch.footerOpen {
return
}
mobile.ActionSheet(c, &ch.footerOpen, mobile.ActionSheetOptions{Title: "更多操作", Cancel: "取消"},
mobile.Action{Label: "朗读回答", OnTap: func() { ch.speakAnswer(ch.footerID) }},
mobile.Action{Label: "停止朗读", OnTap: func() { _ = tts.Stop() }},
mobile.Action{Label: "复制回答", OnTap: func() { ch.copyAnswer(ch.footerID) }},
mobile.Action{Label: "从这里分叉", OnTap: func() { ch.forkFrom(ch.footerID) }},
)
}
func (ch *chat) userSheet(c *ui.Context) {
if !ch.userOpen {
return
}
mobile.ActionSheet(c, &ch.userOpen, mobile.ActionSheetOptions{Title: "消息操作", Cancel: "取消"},
mobile.Action{Label: "复制消息", OnTap: func() { ch.copyUserMessage(ch.userID) }},
mobile.Action{Label: "撤回此消息及之后", OnTap: func() { ch.askRevert(ch.userID) }},
mobile.Action{Label: "从这里分叉", OnTap: func() { ch.forkBefore(ch.userID) }},
)
}
func (ch *chat) copyAnswer(id string) {
m := ch.byID[id]
parts := make([]string, 0, len(m.Content))
for _, p := range m.Content {
if p.Type == "text" && p.Text != "" {
parts = append(parts, p.Text)
}
}
text := strings.Join(parts, "\n")
if text == "" {
text = m.Text
}
if text == "" {
ch.a.chatPost(func() { ch.errText = "没有可复制的文字" })
return
}
mygo.Clipboard.WriteText(text)
}
func (ch *chat) copyUserMessage(id string) {
m := ch.byID[id]
text := strings.TrimSpace(m.Text)
if text == "" {
ch.a.chatPost(func() { ch.errText = "没有可复制的文字" })
return
}
mygo.Clipboard.WriteText(text)
}
// ------------------------------------------------------------ read aloud
func (ch *chat) speakAnswer(id string) {
text := ""
m := ch.byID[id]
parts := make([]string, 0, len(m.Content))
for _, p := range m.Content {
if p.Type == "text" && p.Text != "" {
parts = append(parts, p.Text)
}
}
text = strings.Join(parts, " ")
if text == "" {
text = m.Text
}
if strings.TrimSpace(text) == "" {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := tts.Speak(ctx, text); err != nil {
ch.a.chatPost(func() { ch.errText = "朗读不可用:" + friendlyError(err) })
}
}()
}
// ------------------------------------------------------------ fork / revert
func (ch *chat) forkFrom(id string) {
ch.fork(false, id)
}
func (ch *chat) forkBefore(id string) {
ch.fork(true, id)
}
func (ch *chat) fork(beforeMsg bool, id string) {
before := ""
if beforeMsg {
before = id
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
sess, err := ch.a.client.ForkSession(ctx, ch.id, ch.dir, before)
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
return
}
ch.a.sessions = append([]ocapi.Session{sess}, ch.a.sessions...)
ch.a.openChat(sess)
})
}()
}
func (ch *chat) askRevert(id string) {
ch.revertID = id
ch.confirmRevert = true
}
func (ch *chat) revertConfirm(c *ui.Context) {
if !ch.confirmRevert {
return
}
buttons := ui.AlertDialog(c, &ch.confirmRevert, "撤回消息?",
"这条消息及其之后的内容会从会话中删除,且无法恢复。", "取消", "撤回")
if buttons == 1 {
ch.doRevert(ch.revertID)
}
}
func (ch *chat) doRevert(id string) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
client := ch.a.client
if client.StageRevert(ctx, ch.id, ch.dir, id) != nil {
ch.a.chatPost(func() { ch.errText = "无法撤回" })
return
}
if err := client.CommitRevert(ctx, ch.id, ch.dir); err != nil {
ch.a.chatPost(func() { ch.errText = friendlyError(err) })
return
}
ch.a.chatPost(func() { ch.reloadTail() })
}()
}
// ------------------------------------------------------------ model / agent
func (ch *chat) openPicker(kind string) {
ch.pickerKind = kind
ch.pickerFilter = ""
ch.pickerItems = nil
ch.pickerOpen = true
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
var items []pickerItem
var err error
switch kind {
case "model":
var models []ocapi.ModelInfo
models, err = ch.a.client.Models(ctx, ch.dir)
for _, m := range models {
name := m.Name
if name == "" {
name = m.ID
}
items = append(items, pickerItem{
Key: m.ProviderID + "/" + m.ID,
Title: name,
Model: &ocapi.ModelRef{ID: m.ID, ProviderID: m.ProviderID},
})
}
case "agent":
var agents []ocapi.AgentInfo
agents, err = ch.a.client.Agents(ctx, ch.dir)
for _, ag := range agents {
if ag.Mode != "primary" {
continue
}
items = append(items, pickerItem{Key: "agent/" + ag.ID, Title: ag.Name, Agent: ag.ID})
}
}
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
return
}
ch.pickerItems = items
})
}()
}
func (ch *chat) pickerSheet(c *ui.Context) {
if !ch.pickerOpen {
return
}
mobile.Sheet(c, &ch.pickerOpen, mobile.SheetOptions{Detents: []float32{0.85}}, func() {
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
title := "选择模型"
if ch.pickerKind == "agent" {
title = "选择智能体"
}
ui.Text(c, title).FontSize(20).Bold()
ui.TextInput(c, &ch.pickerFilter).Placeholder("搜索").PaddingY(4)
ui.Scroll(c).Grow(1).Children(func() {
ui.Column(c).FillWidth().Gap(2).Children(func() {
filter := strings.ToLower(ch.pickerFilter)
for _, it := range ch.pickerItems {
if filter != "" && !strings.Contains(strings.ToLower(it.Title), filter) {
continue
}
row := mobile.ListRow(c, mobile.RowOptions{Title: it.Title})
if row.Clicked() {
ch.pickerOpen = false
ch.selectPickerItem(it)
}
}
})
})
})
})
}
func (ch *chat) selectPickerItem(it pickerItem) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var err error
switch ch.pickerKind {
case "model":
err = ch.a.client.SwitchModel(ctx, ch.id, ch.dir, *it.Model)
case "agent":
err = ch.a.client.SwitchAgent(ctx, ch.id, ch.dir, it.Agent)
}
ch.a.chatPost(func() {
if err != nil {
ch.errText = friendlyError(err)
}
})
}()
}
// ------------------------------------------------------------ attachments
func (ch *chat) attachSheet(c *ui.Context) {
if !ch.attachOpen {
return
}
mobile.ActionSheet(c, &ch.attachOpen, mobile.ActionSheetOptions{Title: "添加附件", Cancel: "取消"},
mobile.Action{Label: "照片", OnTap: func() { ch.pickFiles(true) }},
mobile.Action{Label: "文件", OnTap: func() { ch.pickFiles(false) }},
)
}
func (ch *chat) pickFiles(imagesOnly bool) {
ch.a.post(func() { ch.attachBusy = true })
go func() {
opts := mygo.OpenDialogOptions{Multiple: true}
if imagesOnly {
opts.Filters = []mygo.FileFilter{{Name: "图片", MIMETypes: []string{"image/*"}}}
}
paths, err := mygo.Dialog.Open(opts)
ch.a.chatPost(func() {
ch.attachBusy = false
if err != nil {
ch.errText = friendlyError(err)
return
}
for _, p := range paths {
ch.addAttachment(p)
}
})
}()
}
func (ch *chat) addAttachment(path string) {
info, err := os.Stat(path)
if err != nil {
return
}
if info.Size() > 10<<20 {
ch.a.chatPost(func() { ch.errText = "附件不能超过 10MB" })
return
}
data, err := os.ReadFile(path)
if err != nil {
return
}
mime := mimeByExt(path)
url := "data:" + mime + ";base64," + base64URL(data)
kept := ""
if strings.HasPrefix(mime, "image/") {
kept = keepImage(path, info.Name())
}
ch.a.chatPost(func() {
if len(ch.attachments) >= 5 {
ch.errText = "最多 5 个附件"
return
}
ch.attachments = append(ch.attachments, attachment{
Name: info.Name(), MIME: mime, DataURL: url, Size: info.Size(), LocalPath: kept,
})
})
}
+67 -78
View File
@@ -1,5 +1,5 @@
// Package storage keeps saved servers in the app's store and their device // Package storage keeps saved servers in the app's data directory and
// tokens in the platform's secure storage. // their device tokens in the platform's secure storage.
package storage package storage
import ( import (
@@ -7,12 +7,13 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"net/url" "errors"
"os"
"path/filepath"
"sort" "sort"
"sync"
"github.com/egoist/asuka/sdk/secure" "github.com/egoist/mygo"
"github.com/egoist/asuka/sdk/store"
"github.com/egoist/asuka/signal"
) )
// Connection is one saved server. // Connection is one saved server.
@@ -38,84 +39,81 @@ type Store interface {
ClearToken(c Connection) error ClearToken(c Connection) error
} }
// Persistent is the app's store: servers in store.json, tokens in the // Persistent is the app's store: servers in connections.json, tokens in
// Android Keystore / Keychain. // the platform's secure store (the Android Keystore / iOS Keychain).
type Persistent struct { type Persistent struct {
conns *signal.Signal[[]Connection] mu sync.Mutex
installID *signal.Signal[string] path string
conns []Connection
installID string
} }
const ( // New makes the persistent store. It reads the servers file once; call it
connectionsKey = "openchamber.connections" // on startup, before any window shows.
installIDKey = "openchamber.installId"
// legacyKey is the single-server record earlier versions wrote.
legacyKey = "openchamber.connection"
)
// New makes the persistent store. Call it on the main thread, while a
// component builds, as any signal.
func New() *Persistent { func New() *Persistent {
conns := store.Signal(connectionsKey, []Connection{}) p := &Persistent{}
list := conns.Get() dir, err := mygo.App.Path(mygo.PathUserData)
if len(list) == 0 { if err == nil {
list = migrateLegacy() p.path = filepath.Join(dir, "connections.json")
if len(list) > 0 {
conns.Set(list)
}
}
p := &Persistent{
conns: conns,
installID: store.Signal(installIDKey, ""),
} }
p.load()
return p return p
} }
// migrateLegacy turns the old single-connection record into a list entry. func (p *Persistent) load() {
func migrateLegacy() []Connection { if p.path == "" {
var raw string return
if !store.Get(legacyKey, &raw) || raw == "" {
return nil
} }
var old Connection data, err := os.ReadFile(p.path)
if json.Unmarshal([]byte(raw), &old) != nil || old.URL == "" { if err != nil {
return nil return
} }
if old.ID == "" { var list []Connection
old.ID = newID() if json.Unmarshal(data, &list) == nil {
p.conns = list
} }
if old.Label == "" || old.Label == old.URL {
if u, err := url.Parse(old.URL); err == nil && u.Host != "" {
old.Label = u.Host
} else {
old.Label = old.URL
}
}
// Clear it so the next launch does not migrate again.
_ = store.Set(legacyKey, "")
return []Connection{old}
} }
func (p *Persistent) save() {
if p.path == "" {
return
}
if err := os.MkdirAll(filepath.Dir(p.path), 0o700); err != nil {
return
}
data, _ := json.Marshal(p.conns)
_ = os.WriteFile(p.path, data, 0o600)
}
// migrateLegacy is gone: the earlier Asuka builds kept their data in
// Asuka's own stores, which this app cannot read.
func (p *Persistent) Connections() []Connection { func (p *Persistent) Connections() []Connection {
list := p.conns.Get() p.mu.Lock()
out := make([]Connection, len(list)) defer p.mu.Unlock()
copy(out, list) out := make([]Connection, len(p.conns))
copy(out, p.conns)
return out return out
} }
func (p *Persistent) SaveConnections(list []Connection) { func (p *Persistent) SaveConnections(list []Connection) {
sort.SliceStable(list, func(i, j int) bool { return list[i].LastUsedAt > list[j].LastUsedAt }) sort.SliceStable(list, func(i, j int) bool { return list[i].LastUsedAt > list[j].LastUsedAt })
p.conns.Set(list) p.mu.Lock()
p.conns = list
p.mu.Unlock()
p.save()
} }
// InstallID is a stable random id for this installation. It names the // InstallID is a stable random id for this installation. It names the
// device when logging in, so repeated logins reuse one device record. // device when logging in, so repeated logins reuse one device record.
func (p *Persistent) InstallID() string { func (p *Persistent) InstallID() string {
if id := p.installID.Get(); id != "" { p.mu.Lock()
return id defer p.mu.Unlock()
if p.installID != "" {
return p.installID
} }
id := newID() p.installID = NewID()
p.installID.Set(id) return p.installID
return id
} }
func (p *Persistent) tokenKey(id string) string { func (p *Persistent) tokenKey(id string) string {
@@ -123,38 +121,29 @@ func (p *Persistent) tokenKey(id string) string {
return "openchamber.token." + hex.EncodeToString(sum[:12]) return "openchamber.token." + hex.EncodeToString(sum[:12])
} }
// legacyTokenKey is where earlier versions kept a token: by server URL.
func legacyTokenKey(url string) string {
sum := sha256.Sum256([]byte(url))
return "openchamber.token." + hex.EncodeToString(sum[:12])
}
func (p *Persistent) LoadToken(c Connection) (string, bool, error) { func (p *Persistent) LoadToken(c Connection) (string, bool, error) {
if tok, ok, err := secure.Get(p.tokenKey(c.ID)); err != nil || ok { tok, err := mygo.Secrets.Get(p.tokenKey(c.ID))
return tok, ok, err if errors.Is(err, mygo.ErrSecretNotFound) {
return "", false, nil
} }
// A connection migrated from the single-server record keeps its token if err != nil {
// under the old URL-based key. return "", false, err
return secure.Get(legacyTokenKey(c.URL)) }
return string(tok), true, nil
} }
func (p *Persistent) SaveToken(id, token string) error { func (p *Persistent) SaveToken(id, token string) error {
return secure.Set(p.tokenKey(id), token) return mygo.Secrets.Set(p.tokenKey(id), []byte(token))
} }
func (p *Persistent) ClearToken(c Connection) error { func (p *Persistent) ClearToken(c Connection) error {
err := secure.Delete(p.tokenKey(c.ID)) return mygo.Secrets.Delete(p.tokenKey(c.ID))
_ = secure.Delete(legacyTokenKey(c.URL))
return err
} }
func newID() string { func NewID() string {
var b [8]byte var b [8]byte
if _, err := rand.Read(b[:]); err != nil { if _, err := rand.Read(b[:]); err != nil {
return "srv_" + hex.EncodeToString(b[:4]) return "srv_" + hex.EncodeToString(b[:4])
} }
return "srv_" + hex.EncodeToString(b[:]) return "srv_" + hex.EncodeToString(b[:])
} }
// NewID returns a fresh connection id.
func NewID() string { return newID() }
+51
View File
@@ -0,0 +1,51 @@
package dev.mygo
import android.speech.tts.TextToSpeech
import org.json.JSONObject
import java.util.Locale
class TTSPlugin : MyGoPlugin {
private var engine: TextToSpeech? = null
private var ready = false
private var pending: Pair<String, PluginReply>? = null
override fun call(method: String, args: JSONObject, reply: PluginReply) {
when (method) {
"speak" -> {
val text = args.optString("text").ifEmpty { return reply.failure(PluginFailure("Empty", "no text")) }
if (ready) {
engine?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
reply.success(null)
} else {
pending = text to reply
init()
}
}
"stop" -> {
engine?.stop()
reply.success(null)
}
else -> reply.failure(PluginFailure("NoMethod", method))
}
}
private fun init() {
if (engine != null) return
engine = TextToSpeech(PluginHost.context) { status ->
if (status == TextToSpeech.SUCCESS) {
engine?.setLanguage(Locale.getDefault())
ready = true
val p = pending
pending = null
if (p != null) {
engine?.speak(p.first, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
p.second.success(null)
}
} else {
val p = pending
pending = null
if (p != null) p.second.failure(PluginFailure("Init", "text-to-speech is unavailable"))
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"mobile": {
"id": "tts",
"android": {
"sources": ["android/*.kt"],
"class": "TTSPlugin"
}
}
}
+22
View File
@@ -0,0 +1,22 @@
// Package tts speaks text aloud with the system's speech synthesizer, on
// phones. It is a thin Go binding over a small Android TextToSpeech plugin.
package tts
import (
"context"
"github.com/egoist/mygo"
)
const pluginID = "tts"
// Speak reads text aloud, stopping any speech in progress. On desktops it
// reports errors.ErrUnsupported.
func Speak(ctx context.Context, text string) error {
return mygo.Native(pluginID).Call(ctx, "speak", map[string]string{"text": text}, nil)
}
// Stop stops any speech in progress.
func Stop() error {
return mygo.Native(pluginID).Call(context.Background(), "stop", nil, nil)
}
+12 -9
View File
@@ -1,18 +1,21 @@
// OpenChamber Native is a lightweight OpenChamber client for phones, // OpenChamber Native is a lightweight OpenChamber client for phones, written
// written in Go with Asuka's native widgets. // in Go with MyGo's native UI.
package main package main
import ( import (
"github.com/egoist/asuka/app" "log"
"github.com/egoist/mygo"
"github.com/openchamber/openchamber-native/internal/appui" "github.com/openchamber/openchamber-native/internal/appui"
// The native module that lets a release build reach self-hosted // The TTS plugin: its Kotlin is compiled into the app by mygo build.
// servers over plain HTTP (its Android manifest merges the flag). It _ "github.com/openchamber/openchamber-native/internal/tts"
// has no Go API this app calls; importing it is what puts its Gradle
// module in the build.
_ "github.com/openchamber/openchamber-native/netcfg"
) )
func main() { func main() {
app.Run(appui.Root) app := appui.New(nil)
mygo.App.WhenReady(app.Ready)
if err := mygo.App.Run(); err != nil {
log.Fatal(err)
}
} }
+2
View File
@@ -0,0 +1,2 @@
[tools]
go = "1.27.4"
+9
View File
@@ -0,0 +1,9 @@
{
"name": "OpenChamber",
"identifier": "com.openchamber.native",
"version": "0.3.0",
"out": "dist",
"android": {
"minSdk": 24
}
}
-17
View File
@@ -1,17 +0,0 @@
// swift-tools-version:5.9
// The netcfg package's Swift, for iOS and macOS: the Asuka CLI builds it
// with the apps that import the package. Its dependencies (Swift
// packages) go here, as any package's.
import PackageDescription
let package = Package(
name: "NetcfgNative",
platforms: [.iOS("16.0"), .macOS("11.0")],
products: [.library(name: "NetcfgNative", targets: ["NetcfgNative"])],
dependencies: [
.package(url: "https://github.com/egoist/asuka", from: "0.1.0"),
],
targets: [
.target(name: "NetcfgNative", dependencies: [.product(name: "Asuka", package: "asuka")], path: "swift"),
]
)
-15
View File
@@ -1,15 +0,0 @@
// The netcfg package's Kotlin for Android: a library module the Asuka CLI
// builds into the apps that import the package. Its Kotlin is in its
// namespace; its dependencies (Maven's) go here, its permissions and
// services in src/main/AndroidManifest.xml.
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.github.openchamber.openchamber_native.netcfg"
}
dependencies {
}
@@ -1,7 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- OpenChamber servers are often self-hosted on a LAN over plain HTTP.
Asuka's own debug manifest enables cleartext, but a release build
would block it, so this library module merges the flag into every
variant. Remove this module to require HTTPS everywhere. -->
<application android:usesCleartextTraffic="true" />
</manifest>
@@ -1,72 +0,0 @@
// Code generated by asuka native. DO NOT EDIT.
// asuka:native f84252246ecd432c
// What the package's Go declares (package netcfg), as its Kotlin implements
// it. The Kotlin (in this package) writes the functions that make each:
//
// fun makeNetcfg(): Netcfg
@file:Suppress("unused", "RedundantVisibilityModifier")
package com.github.openchamber.openchamber_native.netcfg
import dev.asuka.AsukaModuleProvider
import dev.asuka.AsukaModules
import dev.asuka.AsukaNativeContext
import dev.asuka.AsukaNativeReader
import dev.asuka.AsukaNativeView
import dev.asuka.AsukaNativeWriter
import dev.asuka.AsukaDeclaredError
import dev.asuka.AsukaUnsupportedException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* Netcfg greets in each platform's own code.
*/
public interface Netcfg {
/**
* Hello greets name.
*/
fun hello(name: String): String
}
/** The package's native code as the host finds it (by its class's name): what makes, calls and shows what the package declares. */
public object AsukaModule : AsukaModuleProvider {
override fun make(iface: Int): Any = when (iface) {
0 -> makeNetcfg()
else -> throw AsukaUnsupportedException("no interface $iface")
}
override fun call(obj: Any, iface: Int, method: Int, r: AsukaNativeReader, w: AsukaNativeWriter) {
when (iface) {
0 -> {
val o = obj as Netcfg
when (method) {
1 -> { // Hello
val name = r.string()
r.check()
val v = o.hello(name)
w.string(v)
}
else -> throw AsukaUnsupportedException("no method $iface.$method")
}
}
else -> throw AsukaUnsupportedException("no interface $iface")
}
}
override fun start(obj: Any, iface: Int, method: Int, r: AsukaNativeReader, done: (Result<AsukaNativeWriter>) -> kotlin.Unit): Job? {
when (iface) {
}
throw AsukaUnsupportedException("no method $iface.$method")
}
override fun makeView(name: String, ctx: AsukaNativeContext): AsukaNativeView? = when (name) {
else -> null
}
}
/** The package's values on the wire (package native's format). */
private object Wire {
}
@@ -1,9 +0,0 @@
// The netcfg package's Kotlin: what its Go declares, implemented on
// Android (Netcfg.asuka.kt, beside it, is what asuka native generates).
package com.github.openchamber.openchamber_native.netcfg
private class KotlinNetcfg : Netcfg {
override fun hello(name: String) = "Hello, $name, from Kotlin"
}
fun makeNetcfg(): Netcfg = KotlinNetcfg()
-11
View File
@@ -1,11 +0,0 @@
// Package netcfg is a native module: Netcfg, which each platform's native
// code implements (asuka native).
package netcfg
// Netcfg greets in each platform's own code.
//
//asuka:native
type Netcfg interface {
// Hello greets name.
Hello(name string) (string, error)
}
-13
View File
@@ -1,13 +0,0 @@
//go:build windows || (linux && !android)
package netcfg
// On Windows and Linux the package's native code is Go: NewNetcfg returns
// this.
func init() {
implementNetcfg(func() (Netcfg, error) { return goHello{}, nil })
}
type goHello struct{}
func (goHello) Hello(name string) (string, error) { return "Hello, " + name + ", from Go", nil }
-50
View File
@@ -1,50 +0,0 @@
// Code generated by asuka native. DO NOT EDIT.
// asuka:native f84252246ecd432c
package netcfg
import (
"github.com/egoist/asuka/native"
)
// nativeModule is the package's native code, as the hosts find it.
var nativeModule = &native.Module{ID: "github.com/openchamber/openchamber-native/netcfg", Swift: "AsukaModule_github_com_openchamber_openchamber_native_netcfg", Kotlin: "com.github.openchamber.openchamber_native.netcfg.AsukaModule", Errors: []error{}}
// NewNetcfg makes the platform's Netcfg: Go's, where the package implements it
// in Go (implementNetcfg), else its native code's (Swift on iOS and macOS,
// Kotlin on Android, JavaScript on the web). Without one, it returns an
// error that is errors.ErrUnsupported.
func NewNetcfg() (Netcfg, error) {
if nativeImplNetcfg != nil {
return nativeImplNetcfg()
}
o, err := nativeModule.New(0, "Netcfg")
if err != nil {
return nil, err
}
return &nativeNetcfg{o}, nil
}
var nativeImplNetcfg func() (Netcfg, error)
// implementNetcfg makes NewNetcfg return Go's implementation: call it from an
// init function of a file built for the platforms where the package's
// native code is Go (Windows, Linux).
func implementNetcfg(make func() (Netcfg, error)) { nativeImplNetcfg = make }
// nativeNetcfg is a Netcfg on the platform's side.
type nativeNetcfg struct{ o *native.Object }
func (x *nativeNetcfg) Hello(name string) (string, error) {
w := native.NewWriter()
w.String(name)
r, err := x.o.Call(1, w)
if err != nil {
return "", err
}
v := r.String()
if err := r.Done(); err != nil {
return "", err
}
return v, nil
}
-58
View File
@@ -1,58 +0,0 @@
// Code generated by asuka native. DO NOT EDIT.
// asuka:native f84252246ecd432c
// What the package's Go declares (package netcfg), as its Swift implements
// it. The Swift writes the functions that make each:
//
// func makeNetcfg() throws -> any Netcfg
import Foundation
import Asuka
/// Netcfg greets in each platform's own code.
public protocol Netcfg: AnyObject {
/// Hello greets name.
func hello(name: String) throws -> String
}
/// The package's native code as the host finds it (by its Objective-C
/// name): what makes, calls and shows what the package declares.
@objc(AsukaModule_github_com_openchamber_openchamber_native_netcfg) public final class AsukaModule_github_com_openchamber_openchamber_native_netcfg: NSObject, AsukaModuleProvider {
public static func make(_ iface: UInt32) throws -> AnyObject {
switch iface {
case 0: return try makeNetcfg()
default: throw AsukaNativeError.unsupported("no interface \(iface)")
}
}
public static func call(_ object: AnyObject, _ iface: UInt32, _ method: UInt32, _ r: inout AsukaNativeReader, _ w: inout AsukaNativeWriter) throws {
switch (iface, method) {
case (0, 1): // Netcfg.Hello
let o = object as! any Netcfg
let name = r.string()
try r.check()
let v = try o.hello(name: name)
w.string(v)
default: throw AsukaNativeError.unsupported("no method \(iface).\(method)")
}
}
public static func start(_ object: AnyObject, _ iface: UInt32, _ method: UInt32, _ input: AsukaNativeReader, _ done: @escaping (Result<AsukaNativeWriter, Error>) -> Void) -> Task<Void, Never>? {
var r = input
switch (iface, method) {
default:
done(.failure(AsukaNativeError.unsupported("no method \(iface).\(method)")))
return nil
}
}
@MainActor public static func makeView(_ name: String, _ ctx: AsukaNativeContext) -> AsukaNativeView? {
switch name {
default: return nil
}
}
}
/// The package's values on the wire (package native's format).
fileprivate enum Wire {
}
-10
View File
@@ -1,10 +0,0 @@
// The netcfg package's Swift: what its Go declares, implemented on iOS
// and macOS (Netcfg.asuka.swift, beside it, is what asuka native generates).
import Asuka
import Foundation
final class SwiftNetcfg: Netcfg {
func hello(name: String) throws -> String { "Hello, \(name), from Swift" }
}
func makeNetcfg() throws -> any Netcfg { SwiftNetcfg() }
-55
View File
@@ -1,55 +0,0 @@
// Code generated by asuka native. DO NOT EDIT.
// asuka:native f84252246ecd432c
// What the package's Go declares (package netcfg), as its JavaScript
// implements it. netcfg.js exports the functions that make each:
//
// export function makeNetcfg() // returns its methods (lowerCamelCase)
//
// A method that takes a context in Go is async, and gets an AbortSignal
// first. int64 and uint64 are BigInts; a time is a Date; a duration is
// milliseconds; a []byte is a Uint8Array.
import * as impl from "./netcfg.js";
const { NativeWriter, NativeReader, DeclaredError, UnsupportedError, registerModule, retain, object } = globalThis.asuka.native;
const provider = {
make(iface) {
switch (iface) {
case 0: return impl.makeNetcfg();
}
throw new UnsupportedError(`no interface ${iface}`);
},
call(o, iface, method, r, w) {
switch (iface * 65536 + method) {
case 1: { // Netcfg.Hello
const name = r.string();
r.check();
const v = o.hello(name);
w.string(v);
return;
}
}
throw new UnsupportedError(`no method ${iface}.${method}`);
},
start(o, iface, method, r, signal) {
switch (iface * 65536 + method) {
}
throw new UnsupportedError(`no method ${iface}.${method}`);
},
makeView(name, ctx) {
switch (name) {
}
return null;
},
};
registerModule("github.com/openchamber/openchamber-native/netcfg", provider);
// The package's values on the wire (package native's format).
const Wire = {
};
-8
View File
@@ -1,8 +0,0 @@
// The netcfg package's JavaScript: what its Go declares, implemented on
// the web (netcfg.asuka.js, beside it, is what asuka native generates).
export function makeNetcfg() {
return {
hello: (name) => `Hello, ${name}, from the web`,
};
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 63 KiB

+1
View File
@@ -0,0 +1 @@
1.4.4
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
+15
View File
@@ -0,0 +1,15 @@
node_modules
dist/
.mygo/
examples/*/dist/
examples/*/build/
/mygo
/cmd/mygo/mygo
packages/cli/npm/*/bin/
.DS_Store
mygo.ts
benchmarks/*/target/
# What Zig 0.16 fetches into the packages of native libraries.
zig-pkg/
.zig-cache/
+222
View File
@@ -0,0 +1,222 @@
# AGENTS.md
MyGo is a desktop application framework in Go. Windows show web pages in the
system webview (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows),
with typed Go ↔ TypeScript IPC, or native UI that MyGo draws itself (package
`ui`).
**Read [docs/architecture.md](docs/architecture.md) before changing code.** It
describes the layers, the threading model, native interop without cgo, the IPC
wire protocol, TypeScript generation, and the checklist for adding features.
## Hard rules
- **No cgo**, but to link for phones. Everything must build with
`CGO_ENABLED=0` for desktops and browsers. Call native code through
purego (`internal/darwin`, `internal/linux`) or `syscall`
(`internal/windows`), never `import "C"`. iOS and Android link with
their own toolchains (`CGO_ENABLED=1`, Xcode's and the NDK's clang), as
Go needs for them: `import "C"` is only in `internal/mobile`'s glue, and
on iOS purego reaches Metal and Core Text alone, the hosts (Swift,
Kotlin) everything else (see "Phones" in the architecture guide).
- **Bun is dev tooling only.** The repository is a Bun workspace
(`packages/bridge`, `packages/runtime`, `packages/cli` with its platform
packages, the plugins' packages in `plugins/`, and examples with a frontend, which keep it at their root like
the project template, and `website`); Bun also installs and runs the template's scripts
(Vite, the mygo-cli package). Nothing in an app may need Bun at run time.
- **Scope:** system webview on macOS, Linux and Windows (WebView2), on
iOS and Android (`internal/mobile`, with Swift and Kotlin hosts), and
native UI that MyGo draws itself (`WindowOptions.Content`, package `ui`;
see "Native UI" in the architecture guide), which also runs in browsers
(`GOOS=js GOARCH=wasm`, `internal/web`, drawn with WebGL 2 by the GL
renderer; see "Browsers"). The bundled CEF option is out of scope until
asked. Other platforms must keep compiling through
`internal/unsupported`.
- **Great DX over Electron parity.** Keep the familiar feel (app lifecycle,
windows, menus) but design Go-first APIs: typed IPC via `mygo.Bind` and
`mygo.NewEvent[T]` with the generated client, not string channels.
- **Threading.** Backend methods and handler callbacks run on the main thread.
Public methods must be safe from any goroutine (`onMain`/`postMain`/`await`
in `loop.go`). Never block the main thread waiting on work that needs it.
- **purego callbacks are a scarce, never-freed resource.** Create them once
per signature at startup and route by user data, never per window or call.
- **Apps pay only for what they use.** A feature must not grow apps that
don't use it: `examples/counter-native` (native UI) and `examples/hello`
(webview) are measured on every push. What every app reaches (`App.Run`,
windows, the default menus, `init` functions, the backends' methods)
must not call into opt-in features: reach them through functions their
constructor registers (as `linkedDocuments`), and keep heavy
dependencies and data out of those paths. Never call
`reflect.Type.Method`, `Value.Method` or `MethodByName` there: it makes
the linker keep every exported method of the program (2.5 MB). Measure
both apps before and after a change to `mygo`, `ui`, a backend or the
dependencies; explain any growth of an app that doesn't use the feature
in the PR, and find its cause with `-dumpdep` ("Binary size" in the
architecture guide).
## Commands
```sh
go build ./... && GOOS=linux go build ./... && GOOS=windows go build ./... # all must pass
go vet ./... && GOOS=linux go vet ./... && GOOS=windows go vet ./...
go vet -tags mygo_noinspector ./... # production builds, without the inspector of native UI
GOOS=js GOARCH=wasm go vet $(GOOS=js GOARCH=wasm go list ./... | grep -v /cmd/mygo) # browsers, all but the CLI
GOOS=ios GOARCH=arm64 CGO_ENABLED=1 CC="$(xcrun --sdk iphoneos --find clang) -isysroot $(xcrun --sdk iphoneos --show-sdk-path) -arch arm64" go vet ./... # iPhones (Xcode)
GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=$NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android26-clang go vet ./... # Android (the NDK)
go test ./... # core (fake backend), tsgen, CLI, accelerator
go build -trimpath -tags mygo_noinspector -ldflags "-s -w -X github.com/egoist/mygo.production=1" -o /tmp/counter-native ./examples/counter-native # an app's release size, as the benchmarks build it
MYGO_E2E=1 go test ./internal/e2e # real GUI tests (macOS desktop session)
bun install && bun run test && bun run typecheck # the workspace, from the root
bun run build # build internal/bridge/bridge.js and the npm packages' dist/
bun run --cwd packages/cli binaries # cross-compile the CLI into the mygo-cli platform packages
go run ./cmd/mygo generate examples/todo # regenerate an example's TypeScript client
go run ./cmd/mygo dev examples/todo # live reload (dev bundle in examples/todo/.mygo)
go run ./cmd/mygo dev -web examples/counter-native # native UI in the browser, with live reload
go run ./cmd/mygo build examples/todo # .app + .dmg in examples/todo/build
go run ./cmd/mygo generate examples/native-module # regenerate a native module, build its Swift package (macOS)
go run ./cmd/mygo native check examples/native-module/modules/language # a native module's problems, as file:line
go run ./cmd/mygo build -platform web examples/counter-native # a static site in examples/counter-native/dist/web
go run ./cmd/mygo dev -platform ios examples/todo # on the booted iOS simulator (Xcode)
go run ./cmd/mygo dev -platform android examples/todo # on the device or emulator adb reaches (SDK + NDK)
go run ./cmd/mygo build -platform ios/simulator examples/counter-native # an .app for the simulator (ios: a signed .ipa)
go run ./cmd/mygo build -platform android examples/counter-native # an .apk and an .aab
go generate ./internal/mobile/wire # the messages of phones' backend and hosts: Go, Swift, Kotlin
go run ./cmd/mygo dev -platform ios examples/mobile # phones' gestures, widgets, plugins (ui/mobile)
go run ./examples/gallery # the native UI toolkit's tour
go run ./examples/code-editor # the code editor and the diff viewer (ui/editor)
go run ./examples/markdown-chat # Markdown replies streaming in (ui/markdown)
go run ./examples/notes # the rich text editor (ui/richtext), in a notes app
go run ./examples/terminal # a terminal (downloads libghostty-vt once)
go run ./examples/loading # loading.dev's 29 indicators (plugins/loading)
go run ./examples/permissionflow # the system's permissions, asked for and guided to (plugins/permissionflow)
go run ./examples/render # a video of native UI, drawn on the GPU (plugins/render); -preview plays it in a window
go run ./plugins/automation/cmd/mygo-automation skills # the automation CLI's guide, for agents driving an app
go run ./examples/sf-symbols # the system's SF Symbols on macOS (plugins/sfsymbols)
go run ./cmd/mygo native build -target host examples/rust-native # build a package's Rust/Zig library for go run and go test (cargo)
go run ./cmd/mygo native build ./pkg # its libraries for every platform, into mygo-plugin.json, ready to publish
go generate ./plugins/terminal # build libghostty-vt for every platform (with Zig), write Ghostty's themes
go generate ./internal/gpu/d3d11 # recompile the Direct3D shader (on Windows)
go generate ./internal/gpu/metal # recompile the Metal shader (on macOS, with Xcode)
go generate ./cmd/mygo # the Mandarin readings of slugs (cmd/mygo/pinyin.bin), from Unicode's Unihan
go generate ./internal/l10n # MyGo's own strings: their functions, and the packages of translations in locales/
go generate ./plugins/glass # recompile the glass plugin's shaders (on macOS, and on Windows)
bun run --cwd website dev # the website, with docs/ at /docs (see website/README.md)
bun scripts/bench.ts run [--e2e] # benchmarks and app sizes, medians of 6 runs (CI: bench.yml, /measures)
go run ./benchmarks/run -out benchmarks/results.json # MyGo, GPUI, GPUI Fast and egui on the same apps, for /benchmarks (opens windows, on a real Mac)
go run ./internal/idlemem app... # apps' memory once idle, with their webviews' processes
go run ./internal/inputlatency # native UI's input-to-screen latency on macOS (opens windows)
```
Linux GUI tests cross-compile and run in a container with WebKitGTK and Xvfb;
Windows GUI tests need Windows with the WebView2 Runtime (a GitHub Actions
`windows-latest` runner has it). See "Testing" in the architecture guide.
## Conventions
- Never write `[skip ci]` (or `[ci skip]`, `[no ci]`) in a commit message,
not even quoted in its body: GitHub skips the push's workflows, CI and
benchmarks included, and Cloudflare the website's deploy. Only the
benchmarks branch's commits say it.
- New behavior goes into `package mygo` first; backends only translate
`internal/platform` calls to native ones. Implement every platform method in
`darwin`, `linux`, `windows`, `web`, `mobile`, `fake` and `unsupported`.
A call of `mobile`'s host is a message of `internal/mobile/wire/gen/spec.go`,
implemented in the Swift host (`internal/mobile/ios`) and the Kotlin one
(`internal/mobile/android`).
- Objective-C: `alloc`/`init` objects are owned and must be released; wrap
temporary objects in `withPool`; copy blocks you call later.
- Native modules (`native`, `internal/nativegen`, docs/native-modules.md):
keep the generated example (`examples/native-module`) up to date, which
`TestExampleUpToDate` checks, and change the Swift glue in
`internal/nativegen/support.go` with `TestScaffoldBuilds` passing
without warnings. The Rust and Zig glue (`rustsupport.go`,
`zigsupport.go`) is checked by the roundtrip module built in each
language: `go run ./cmd/mygo native build -target host -lang <swift|rust|zig>
native/internal/roundtrip && go test ./native/internal/roundtrip`. On
phones the same checks (`native/internal/roundtrip/check`) run in the app
`native/internal/roundtrip/app`, with its Swift on the iOS simulator and
its Kotlin (the runtime in `internal/mobile/android/.../Native.kt`) on
Android's emulator, which CI's phone jobs launch and read the log of;
`TestKotlinUpToDate` checks the committed Kotlin.
- Official plugins live in `plugins/<name>`: the Go package and its npm
package (`@mygo-plugins/<name>`) side by side, released with
mygo-runtime's version. The updater plugin is Go only; its `native`
package draws the update window in native UI. The terminal plugin is Go
only too, for native UI, with libghostty-vt loaded through purego. Its
`native/` (a Zig package pinning Ghostty's commit) is a native library
like any: `mygo-plugin.json` names its published builds (release assets
`libghostty-vt-<commit>`), each with the hash of its sources, and
`go generate` publishes new ones (`mygo native build`, with Zig 0.16.0).
The SQLite plugin's SQLite is a native module,
`plugins/sqlite/internal/sqlitecore`: Zig on desktops, which `mygo
native build -target host` builds for its tests and `-upload`
publishes, Swift on iOS (linking `CSQLite.xcframework`, which
`swift/build-xcframework.sh` builds on a Mac and the release
`native-sqlitecore` holds) and Kotlin with C (CMake) on Android, all
the same SQLite version and options. The glass
plugin is Go only too, an effect of the renderers (`scene.Effect`): its
shader in Metal, HLSL and GLSL with a CPU twin that must draw the same
pixels, compiled ahead of time by `go generate` on macOS and Windows.
The game plugin is Go only too, what games need beyond what apps do,
opt-in, kept out of core `ui`: a game loop and a camera for native UI,
and `plugins/game/gamepad`, which reads controllers. The loading plugin
is Go only too, loading.dev's indicators drawn with `ui.Painter` on
ui's public API: keep them as loading-dev draws them in a browser.
The sfsymbols plugin is Go only too: on macOS it rasterizes the system's
SF Symbols through purego, and elsewhere it has none (`Image` says so).
The automation plugin is Go only too, gated with the inspector
(`mygo_noinspector`): a socket (`MYGO_AUTOMATION`) through which
other processes drive the app, reaching native UI only through
`surface.Automate`, which it sets. Its command line client for agents,
`mygo-automation` (`plugins/automation/cmd/mygo-automation`, the code
in `internal/automationcli`), uses the socket alone and Go's standard
library; keep its embedded `SKILL.md` true to its commands.
The location, imagepicker, camera, videoplayer, biometrics, sensors and
push plugins are for phones, with Swift and Kotlin beside the Go, which
their `mygo-plugin.json`'s `mobile` names: they reach it with
`mygo.Native`, and an app has none of it unless it imports them. Package
`ui/mobile` is phones' widgets on ui's public API.
The permissionflow plugin is Go only too, after PermissionFlow: TCC's
permissions through purego on macOS, with a panel of AppKit under
System Settings to drag the app from, the consent store on Windows,
and errors.ErrUnsupported elsewhere.
The render plugin is Go only too: videos of native UI, built frame by
frame by `ui.Recorder` at the video's times, drawn by the GPU
renderers' frame targets (`metal.Frames`, `d3d11.Frames`,
`gl.Offscreen`) or `internal/raster`, and encoded with AVFoundation,
Media Foundation or GStreamer through purego and syscall, or ffmpeg
when asked. Its tests check frames against the CPU renderer's and the
files' tracks; Media Foundation and GStreamer run on temp-runner and in
Docker.
- The `dist/` of npm packages is not committed: run `bun run build` after
`bun install` (CI and releases do). Commit `internal/bridge/bridge.js`
whenever its sources change, and keep the generated clients of examples
(`examples/*/src/mygo.ts`) up to date. Built frontends are not
committed: `mygo build` embeds them.
- `mygo-runtime` (`packages/runtime`) and `mygo-cli` (`packages/cli`, with
its per-platform packages in `packages/cli/npm`) are released to npm with
the same version as the Go module (`mygo.Version`, also the CLI's
`version`), which `bun scripts/version.ts <version>` sets everywhere; the
template depends on both. Pushing a `v<version>` tag releases everything
(`.github/workflows/release.yml`, see "Releasing" in the architecture
guide); never commit the CLI's binaries.
- Native libraries of apps and plugins (Rust crates, Zig packages, C) are
named in the binding package's `mygo-plugin.json` (`internal/nativelib`)
and loaded and bound with package `ffi`, never with a loader of their
own: the CLI builds those with `build` from their sources in `mygo dev`
and `mygo build`, and `mygo native build` publishes them for the apps of
others.
- The configuration types of `packages/cli/index.d.ts` (for `mygo.config.ts`)
mirror `Config` in `cmd/mygo/config.go`; `TestConfigTypes` checks them.
- Tests: unit tests through `internal/fake`; GUI behavior in `internal/e2e`.
- Tests never pass or fail on wall-clock time ("Waiting in tests" in the
architecture guide): wait for the condition or event with
`internal/wait`, whose one-minute guard only turns a hang into a
failure and is never tuned; advance a `ui.Tester`'s clock instead of
sleeping; measure work by counts, not durations. A test that can time
out while the code is right has a race to fix, in the test or the
product, not a timeout to raise or a rerun to hide behind.
GUI tests share a process and, on Linux, an X server: what one leaves
behind ("What tests leave behind" in the architecture guide) fails it, not
the tests after it. Before calling a failure older than a pull request,
reproduce it on a new X server, without running the branch's binary on it.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 MyGo contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+134
View File
@@ -0,0 +1,134 @@
<p align="center">
<img width="800" height="360" alt="MyGo!!!!!" src="https://github.com/user-attachments/assets/c3eee9bc-5f22-4032-95b6-776e8381910a" />
</p>
**Desktop apps in Go, with native UI or a web frontend.**
Sponsored by:
<p align="center">
<a href="https://openuptime.app/?utm_source=github&utm_medium=sponsor&utm_campaign=mygo">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://openuptime.app/sponsor/banner-dark.png">
<img width="600" alt="OpenUptime: open-source uptime monitoring and status pages" src="https://openuptime.app/sponsor/banner-light.png">
</picture>
</a>
</p>
<p align="center">
<a href="https://mygo.egoist.dev/sponsors">Become a sponsor</a>
</p>
---
Each MyGo window shows one of two kinds of interface, and one app, or one
window, can mix them:
- **A web page**, in the webview the OS already has: WKWebView on macOS,
WebKitGTK on Linux, WebView2 on Windows. Build the frontend with any web
tools; it calls your Go code through a TypeScript client generated from it.
- **Native UI**, written in Go alone with package `ui` and
drawn by MyGo itself on the GPU: no HTML, no JavaScript and no webview, so
the window opens at once and takes little memory.
Either way, an app is a single Go binary of a few megabytes, focused on low
memory and CPU use.
- **Pure Go, no cgo**: build for every desktop from any machine.
- **Phones too**: the same app on iOS and Android, pages in their web
views and native UI on their GPUs, with live reload on a simulator,
an emulator or a device, and builds for the App Store and Google Play.
- **Typed IPC** for pages: bind Go services, stream values through channels
and send typed events; the TypeScript client is generated from your Go
code.
- **A Go UI toolkit** for native UI: flexbox and grid layout, widgets, text
editing with input methods, virtualized lists, SVG icons, animations,
screen reader support, and views you test without a window; Liquid Glass
on every platform with the glass plugin; web pages inside native UI, under
the menus and dialogs it shows over them.
- **Desktop APIs** for both: windows, menus, tray, dialogs, notifications,
global shortcuts, deep links, file associations, recent documents, Now
Playing and the media keys, the system accent color and accessibility
settings, watching files, and more.
- **Ready to ship**: app bundles and disk images, Windows installers, Debian
and RPM packages, PKGBUILDs for Arch Linux and a Linux install script, code signing, notarization, and signed
auto-updates with delta updates and an update window in the manner of
Sparkle.
A window with a web page, whose frontend calls Go:
```go
type Greeter struct{}
// Greet returns a greeting.
func (Greeter) Greet(name string) string { return "Hello, " + name }
func main() {
mygo.Bind(Greeter{})
mygo.App.WhenReady(func() {
mygo.NewWindow(mygo.WindowOptions{Title: "Hello", URL: "/"})
})
if err := mygo.App.Run(); err != nil {
log.Fatal(err)
}
}
```
```ts
import { Greeter } from "./mygo"; // generated
document.body.textContent = await Greeter.greet("Ada");
```
A window with native UI, whose view is a Go function of the app's state:
```go
type counter struct{ n int }
func (s *counter) view(c *ui.Context) {
ui.Column(c).Fill().Center().Gap(12).Children(func() {
ui.Text(c, fmt.Sprint(s.n)).FontSize(40).Bold()
if ui.PrimaryButton(c, "Increment").Clicked() {
s.n++
}
})
}
func main() {
s := &counter{}
mygo.App.WhenReady(func() {
mygo.NewWindow(mygo.WindowOptions{
Title: "Counter",
Content: ui.View(s.view),
})
})
if err := mygo.App.Run(); err != nil {
log.Fatal(err)
}
}
```
## Getting started
With [Go](https://go.dev/dl/) 1.27.3+ and [Bun](https://bun.sh), create an app
with a web frontend:
```sh
bunx mygo-cli init my-app # or: npx mygo-cli init my-app
cd my-app
bun run dev
```
An app of native UI needs Go alone:
```sh
go run github.com/egoist/mygo/cmd/mygo@latest init -template native my-app
cd my-app
go tool mygo dev
```
Read the [documentation](docs/README.md).
## License
MIT
+91
View File
@@ -0,0 +1,91 @@
package mygo
import "slices"
// A window is drawn as active while the user's input goes to it, as native
// apps tell which of their windows has it: macOS fades a sidebar's
// material and the accent of selections and controls to gray in the
// others, Windows draws their Mica as a solid fill, GTK styles them
// :backdrop. A window is active while it has the keyboard, or one of its
// flyouts does (a menu or popover of a window belongs to it), and always
// when SetActiveAppearance keeps it so. Panels and flyouts without a
// parent float over whatever app is in front, never active as the system
// tells it, and are drawn active as their materials are. A window that
// never had the keyboard, and was not shown without it, counts as active,
// so that the first frame of a window about to take it does not show it
// otherwise.
//
// Its native UI reads it with ui.Context.WindowActive, and its pages from
// the attribute data-mygo-window-inactive of their <html>, which the bridge
// sets while it is not. The system's materials follow the system's own
// state, which agrees: macOS keeps a window whose flyout has the keyboard
// drawn as its main window, and Windows its owner (flyoutActivate).
// activeScheduled tells that updateActive is posted. Main thread only.
var activeScheduled bool
// scheduleActive has the windows' active states worked out once the
// event being handled returns: a window's flyout taking the keyboard
// blurs the window first, which would draw it inactive for a frame. Main
// thread only.
func scheduleActive() {
if !activeScheduled {
activeScheduled = true
postMain(updateActive)
}
}
// updateActive works out which windows are drawn as active, and tells
// those that changed. Main thread only.
func updateActive() {
activeScheduled = false
windows.Lock()
list, focused := slices.Clone(windows.list), windows.focused
windows.Unlock()
for _, w := range list {
if w.native != nil {
w.setActive(w.drawnActive(focused))
}
}
}
// drawnActive reports whether w is drawn as active while focused has the
// keyboard. Main thread only.
func (w *Window) drawnActive(focused *Window) bool {
switch {
case w.keepActive:
return true
case w.flyout != nil && w.parent != nil:
return w.parent.drawnActive(focused)
case w.flyout != nil, w.panel, !w.focusKnown:
return true
}
for x := focused; x != nil; x = x.parent {
if x == w {
return true
}
if x.flyout == nil {
break
}
}
return false
}
// setActive draws w as active or not: its native UI, or its page and those
// of its web views. Main thread only.
func (w *Window) setActive(active bool) {
if w.active == active {
return
}
w.active = active
if c := w.conn; c != nil && c.ActiveChanged != nil {
c.ActiveChanged()
}
w.sendActive()
windows.Lock()
views := slices.Clone(w.webViews)
windows.Unlock()
for _, v := range views {
v.sendActive()
}
}
+155
View File
@@ -0,0 +1,155 @@
//go:build !js
package mygo
import (
"encoding/json"
"strings"
"testing"
"github.com/egoist/mygo/internal/fake"
"github.com/egoist/mygo/internal/surface"
)
// activeContent is a Content that records what its window tells of its
// active state.
type activeContent struct {
conn *surface.Conn
changes []bool
}
func (c *activeContent) AttachContent(conn *surface.Conn) {
c.conn = conn
conn.ActiveChanged = func() { c.changes = append(c.changes, conn.Active()) }
}
// active reports whether w is drawn as active, once the update its focus
// events posted ran: a call on the main thread queues behind it.
func active(w *Window) bool { return onMainValue(func() bool { return w.active }) }
// activeEvents returns the values of the mygo:window-active events the page
// of fw was sent, in order.
func activeEvents(fw *fake.Window) []any {
var got []any
for _, s := range onMainValue(fw.Scripts) {
const prefix = "__mygo.receive("
var msgs []map[string]any
if !strings.HasPrefix(s, prefix) || json.Unmarshal([]byte(strings.TrimSuffix(strings.TrimPrefix(s, prefix), ")")), &msgs) != nil {
continue
}
for _, m := range msgs {
if m["n"] == "mygo:window-active" {
got = append(got, m["p"])
}
}
}
return got
}
// TestWindowActiveFollowsFocus checks that a window is drawn as active
// while it has the keyboard, and that its native UI and its page hear the
// changes.
func TestWindowActiveFollowsFocus(t *testing.T) {
content := &activeContent{}
a, fa := testWindow(t, WindowOptions{Content: content})
b, fb := readyWindow(t, WindowOptions{})
if !active(a) || !active(b) || !content.conn.Active() {
t.Fatal("windows that never had the keyboard start inactive")
}
onMain(fa.Focus)
if !active(a) || !active(b) {
t.Errorf("one window focused: active %v and %v, the other never focused", active(a), active(b))
}
onMain(func() { fa.Blur(); fb.Focus() })
if active(a) || !active(b) {
t.Errorf("the other focused: active %v and %v", active(a), active(b))
}
// The app goes to the background.
onMain(fb.Blur)
if active(a) || active(b) {
t.Errorf("none focused: active %v and %v", active(a), active(b))
}
onMain(fa.Focus)
if !active(a) {
t.Error("focused again, not active")
}
if got := onMainValue(func() []bool { return content.changes }); len(got) != 2 || got[0] || !got[1] {
t.Errorf("the content heard %v, want [false true]", got)
}
// b's page: inactive as the app went to the background, and since.
if got := activeEvents(fb); len(got) != 1 || got[0] != false {
t.Errorf("the page heard %v, want [false]", got)
}
}
// TestWindowActivePageEvents checks what a page hears: nothing while its
// window stays active, false and true as it changes, and false as a page
// loads in an inactive window, as pages start active.
func TestWindowActivePageEvents(t *testing.T) {
w, fw := readyWindow(t, WindowOptions{})
onMain(fw.Focus)
_ = active(w)
if got := activeEvents(fw); len(got) != 0 {
t.Errorf("an active window told its page %v", got)
}
onMain(fw.Blur)
received(t, fw, func(m map[string]any) bool { return m["n"] == "mygo:window-active" && m["p"] == false })
// A page loading in the inactive window hears it at dom-ready.
onMain(fw.ClearScripts)
onMain(func() { fw.H.NavigationCommitted("about:blank") })
page(fw, `{"t":"dom-ready"}`)
received(t, fw, func(m map[string]any) bool { return m["n"] == "mygo:window-active" && m["p"] == false })
onMain(fw.ClearScripts)
onMain(fw.Focus)
received(t, fw, func(m map[string]any) bool { return m["n"] == "mygo:window-active" && m["p"] == true })
}
// TestWindowActiveFlyout checks that a window stays active while its
// flyout has the keyboard, as a window's menus and popovers leave it, and
// that a flyout without the keyboard is as active as its parent.
func TestWindowActiveFlyout(t *testing.T) {
parent, fp := readyWindow(t, WindowOptions{})
onMain(fp.Focus)
fl, ff := testFlyout(t, FlyoutOptions{Parent: parent, Focusable: true, Width: 100, Height: 100})
tip, _ := testFlyout(t, FlyoutOptions{Parent: parent, Width: 100, Height: 20})
// The parent loses the keyboard to its flyout within one event.
onMain(func() { fp.Blur(); ff.Focus() })
if !active(parent) || !active(fl) || !active(tip) {
t.Errorf("a flyout has the keyboard: parent active %v, flyout %v, the other %v", active(parent), active(fl), active(tip))
}
if got := activeEvents(fp); len(got) != 0 {
t.Errorf("the parent's page heard %v as its flyout took the keyboard", got)
}
// Another app comes in front.
onMain(ff.Blur)
if active(parent) || active(fl) || active(tip) {
t.Errorf("none focused: parent active %v, flyout %v, the other %v", active(parent), active(fl), active(tip))
}
}
// TestWindowActiveKept checks the windows drawn active whatever has the
// keyboard: panels, flyouts of trays, those SetActiveAppearance keeps
// active, and a window that never had the keyboard; and that one shown
// without it is not.
func TestWindowActiveKept(t *testing.T) {
panel, fpanel := testWindow(t, WindowOptions{Panel: true})
kept, fk := testWindow(t, WindowOptions{})
shown, _ := testWindow(t, WindowOptions{Hidden: true})
other, fo := testWindow(t, WindowOptions{})
onMain(func() { fpanel.Focus(); fpanel.Blur(); fk.Focus(); fk.Blur() })
kept.SetActiveAppearance(true)
shown.ShowInactive()
onMain(fo.Focus)
if !active(panel) || !active(kept) || !fk.ActiveAppearance() {
t.Errorf("active: panel %v, kept %v (backend %v)", active(panel), active(kept), fk.ActiveAppearance())
}
if active(shown) || !active(other) {
t.Errorf("active: shown without the keyboard %v, focused %v", active(shown), active(other))
}
kept.SetActiveAppearance(false)
if active(kept) {
t.Error("active after SetActiveAppearance(false)")
}
}
+834
View File
@@ -0,0 +1,834 @@
package mygo
import (
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/egoist/mygo/internal/platform"
)
// ActivationPolicy controls how a macOS application appears in the Dock and
// app switcher.
type ActivationPolicy string
// Activation policies.
const (
// ActivationPolicyRegular is an ordinary app with a Dock icon and menu bar.
ActivationPolicyRegular ActivationPolicy = "regular"
// ActivationPolicyAccessory hides the Dock icon; windows can still be
// shown. Typical for menu bar (tray) apps.
ActivationPolicyAccessory ActivationPolicy = "accessory"
// ActivationPolicyProhibited hides the app entirely.
ActivationPolicyProhibited ActivationPolicy = "prohibited"
)
// DMABUFRenderer says whether WebKitGTK draws web pages with its DMA-BUF
// renderer on Linux; see Application.SetDMABUFRenderer.
type DMABUFRenderer string
// DMA-BUF renderer settings.
const (
// DMABUFRendererOff turns the renderer off, unless the user set
// WEBKIT_DISABLE_DMABUF_RENDERER: the default.
DMABUFRendererOff DMABUFRenderer = "off"
// DMABUFRendererOn leaves the renderer to WebKitGTK, which uses it
// wherever it can.
DMABUFRendererOn DMABUFRenderer = "on"
// DMABUFRendererAuto leaves the renderer on where the host is known to
// draw with it: on Wayland, with a GPU of Mesa's, outside containers
// and virtual machines. Elsewhere it is off.
DMABUFRendererAuto DMABUFRenderer = "auto"
)
// Application controls the event loop and the lifecycle of the process.
// Use the App singleton.
type Application struct {
mu sync.Mutex
name string
version string
policy ActivationPolicy
dmabuf DMABUFRenderer
running bool
ready bool
readyCh chan struct{}
whenReady []func()
menu *Menu
menuSet bool
paths map[PathName]string
// stateStore is the WindowStateStore, or nil for the file.
stateStore WindowStateStore
finished sync.Once
// quitting is only touched on the main thread.
quitting bool
stopping bool // the quit sequence ran: the event loop is to stop (main thread)
ended bool // the event loop stopped: finish runs (main thread)
relaunch bool // Relaunch: start again once quit (main thread)
initialized bool // Run initialized the backend (main thread)
// relaunchArgs are Relaunch's arguments, nil for the ones the app
// started with (main thread).
relaunchArgs []string
// Dock controls the Dock icon on macOS.
Dock *Dock
// JumpList controls the jump list of the taskbar button on Windows.
JumpList *JumpList
onReady listeners[func()]
onWindowAllClosed listeners[func()]
onBeforeQuit listeners[func(*QuitEvent)]
onWillQuit listeners[func(*QuitEvent)]
onQuitCanceled listeners[func()]
onQuit listeners[func()]
onMemoryWarning listeners[func()]
saveState func() []byte
keepingState bool
onActivate listeners[func(bool)]
onDidBecomeActive listeners[func()]
onDidResignActive listeners[func()]
onOpenURL listeners[func(string)]
onOpenFile listeners[func(string)]
onWindowCreated listeners[func(*Window)]
onNotificationClick listeners[func(string)]
}
// App is the application singleton.
var App = &Application{readyCh: make(chan struct{}), Dock: &Dock{}, JumpList: &JumpList{}}
// Run starts the native event loop and blocks until the application quits.
// It must be called from the main goroutine, usually as the last statement
// of main.
//
// SIGINT and SIGTERM quit the application like Quit; a second signal exits
// immediately.
//
// When the MYGO_GENERATE environment variable is set (see `mygo generate`),
// Run writes the TypeScript client for the bound services to that path, or
// nothing when the app binds none, and returns without starting the event
// loop.
func (a *Application) Run() error {
if out := os.Getenv("MYGO_GENERATE"); out != "" {
return writeClient(out)
}
takeDevMarker()
if !isMainThread() {
return errors.New("mygo: App.Run must be called from the main goroutine")
}
a.mu.Lock()
if a.running {
a.mu.Unlock()
return errors.New("mygo: App.Run called twice")
}
a.running = true
a.mu.Unlock()
go cleanUpdateLeftovers()
b := backend()
if err := b.Init(appHandler{}, platform.AppOptions{
Name: a.Name(),
ActivationPolicy: string(a.ActivationPolicy()),
DMABUFRenderer: string(a.dmabuf),
Background: devBackground,
}); err != nil {
return err
}
a.initialized = true
// Settings made before Run, which the backend could not take yet.
Theme.apply()
if load := pendingGTKCSS; load != nil {
pendingGTKCSS = nil
load()
}
a.startLocale()
if m := a.Dock.Menu(); m != nil {
b.App().SetDockMenu(m.snapshot())
}
quitOnSignals()
// Run whatever was scheduled before the event loop existed.
b.Signal()
err := b.Run()
a.finish()
return err
}
// needsApp panics when main calls something that needs the running app
// before Run: the backend is not initialized yet (on Linux its libraries
// are not even loaded), and main cannot wait for it. Other goroutines
// wait for the app to start instead. call names the method.
func needsApp(call string) {
if isMainThread() && !App.initialized {
panic("mygo: " + call + " called before App.Run; call it once the application is ready (App.WhenReady)")
}
}
// WhenReady calls fn on the main thread once the application has finished
// launching. Windows can only be created after that point. If the
// application is already ready, fn is scheduled right away.
func (a *Application) WhenReady(fn func()) {
a.mu.Lock()
if !a.ready {
a.whenReady = append(a.whenReady, fn)
a.mu.Unlock()
return
}
a.mu.Unlock()
postMain(fn)
}
// IsReady reports whether the application has finished launching.
func (a *Application) IsReady() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.ready
}
// Quit closes all windows and then quits. OnBeforeQuit and OnWillQuit
// listeners, as well as the OnClose listeners of every window, can cancel
// it.
func (a *Application) Quit() {
postMain(func() {
if a.stopping {
backend().Quit()
return
}
if a.prepareQuit() {
a.stopLoop()
}
})
}
// stopGrace is how long the event loop has to stop once the quit sequence
// has run, before the app finishes and exits without it; 0 waits on.
var stopGrace = 3 * time.Second
// stopLoop stops the event loop once the quit sequence has run.
func (a *Application) stopLoop() {
a.loopStopping()
backend().Quit()
}
// loopStopping records that the quit sequence has run. Its windows closed,
// the app must not stay behind should the event loop go on: AppKit's has
// been seen to after a relaunch asked for from a daemon's reconnection,
// when every later quit was taken for one already under way. A later quit
// asks the loop to stop again (Quit, QuitRequested), and after stopGrace
// the app finishes and exits anyway.
func (a *Application) loopStopping() {
a.stopping = true
if stopGrace > 0 {
time.AfterFunc(stopGrace, func() { postMain(a.forceStop) })
}
}
// forceStop finishes the app and exits, should its event loop not have
// stopped in time.
func (a *Application) forceStop() {
if a.ended {
return
}
a.finish()
os.Exit(0)
}
// Exit terminates the process immediately with the given exit code,
// without emitting quit events or asking windows.
func (a *Application) Exit(code int) {
onMain(func() {
for _, w := range Windows() {
w.destroy()
}
saveWindowStates()
backendExiting()
})
os.Exit(code)
}
// prepareQuit runs the quit sequence on the main thread and reports whether
// the application may quit.
func (a *Application) prepareQuit() bool {
if a.quitting {
return false
}
before := &QuitEvent{}
fire1(&a.onBeforeQuit, before)
if before.prevented {
fire(&a.onQuitCanceled)
return false
}
a.quitting = true
for _, w := range Windows() {
if !w.close() {
a.quitting = false
fire(&a.onQuitCanceled)
return false
}
}
will := &QuitEvent{}
fire1(&a.onWillQuit, will)
if will.prevented {
a.quitting = false
fire(&a.onQuitCanceled)
return false
}
// Providers are application-owned, independent of the windows just
// closed. Persist them before the native loop ends; callers needing
// error handling may Flush explicitly from a quit listener.
_ = Clipboard.Flush()
stopNativeCalls()
return true
}
// endSession runs the quit sequence when the OS ends the session
// (Terminating: logout, restart or shutdown on Windows and macOS), on
// the main thread before finish. The OS has decided, so it cannot be
// canceled: QuitEvent.SessionEnding is set, and what OnBeforeQuit,
// OnClose and OnWillQuit listeners prevent is ignored. A quit whose
// sequence ran, or is running in a nested loop, already called them,
// so they are not called again.
func (a *Application) endSession() {
if a.quitting || a.stopping || a.ended {
return
}
a.quitting = true // the windows closing below do not quit
a.stopping = true // a Quit from a listener only asks the loop to stop
fire1(&a.onBeforeQuit, &QuitEvent{SessionEnding: true})
for _, w := range Windows() {
if w.native != nil {
fire1(&w.onClose, &CloseEvent{Window: w})
w.destroy()
}
}
fire1(&a.onWillQuit, &QuitEvent{SessionEnding: true})
_ = Clipboard.Flush()
stopNativeCalls()
}
// finish runs once after the event loop has stopped.
func (a *Application) finish() {
a.finished.Do(func() {
a.ended = true
stopNativeCalls()
stopFileWatches()
clipboardStopped = true
backend().Clipboard().Close()
saveWindowStates()
fire(&a.onQuit)
backendExiting()
if a.relaunch {
// After OnQuit, which stops taking the command lines of later
// instances: the new one waits for this process to exit, which
// holds the single instance lock until then.
relaunchNow()
}
loop.shutdown()
})
}
// backendExiting tells the backend that the process is about to exit,
// once the app has finished (or Exit was called): see
// platform.ExitBackend. Main thread only.
func backendExiting() {
if b, ok := backend().(platform.ExitBackend); ok {
b.Exiting()
}
}
// lastWindowClosed is called on the main thread when the last window has
// been closed.
func (a *Application) lastWindowClosed() {
if a.quitting {
return
}
if a.onWindowAllClosed.len() > 0 {
fire(&a.onWindowAllClosed)
return
}
a.Quit()
}
func (a *Application) handleReady() {
a.mu.Lock()
menuSet := a.menuSet
a.mu.Unlock()
var def *Menu
if !menuSet {
// Built outside the lock: role labels need App.Name.
def = defaultMenu()
}
a.mu.Lock()
a.ready = true
fns := a.whenReady
a.whenReady = nil
if !a.menuSet {
a.menu = def
}
menu := a.menu
a.mu.Unlock()
close(a.readyCh)
backend().SetApplicationMenu(menu.snapshot())
fire(&a.onReady)
for _, fn := range fns {
fn()
}
// After the windows the app opens when ready, which URLs may target.
postMain(launchArgs)
}
// waitReady blocks a goroutine other than the main one until the
// application is ready.
func (a *Application) waitReady() { <-a.readyCh }
// Name returns the application name. It defaults to the bundle name of a
// packaged app, else to the executable name.
func (a *Application) Name() string {
a.mu.Lock()
name := a.name
a.mu.Unlock()
if name != "" {
return name
}
if info, ok := packageInfo(); ok && info.Name != "" {
return info.Name
}
exe, err := os.Executable()
if err != nil {
return "MyGo"
}
return strings.TrimSuffix(filepath.Base(exe), ".exe")
}
// SetName overrides the application name. Call it before Run.
func (a *Application) SetName(name string) {
a.mu.Lock()
a.name = name
a.mu.Unlock()
}
// Version returns the application version, which defaults to the version of
// the packaged app.
func (a *Application) Version() string {
a.mu.Lock()
v := a.version
a.mu.Unlock()
if v == "" {
if info, ok := packageInfo(); ok {
return info.Version
}
}
return v
}
// SetVersion overrides the application version.
func (a *Application) SetVersion(v string) {
a.mu.Lock()
a.version = v
a.mu.Unlock()
}
// IsPackaged reports whether the application runs from an app bundle
// (created by `mygo dev` and `mygo build`) rather than a plain executable.
func (a *Application) IsPackaged() bool {
_, ok := packageInfo()
return ok
}
// SetMenu sets the application menu: the menu bar on macOS and the menu bar
// of windows without their own menu on Linux and Windows. nil removes it.
// Without a call to SetMenu a default menu with the usual App, Edit, View
// and Window items is installed.
func (a *Application) SetMenu(m *Menu) {
a.mu.Lock()
a.menu = m
a.menuSet = true
ready := a.ready
a.mu.Unlock()
if ready {
onMain(func() { backend().SetApplicationMenu(m.snapshot()) })
}
}
// Menu returns the application menu.
func (a *Application) Menu() *Menu {
a.mu.Lock()
defer a.mu.Unlock()
return a.menu
}
// ActivationPolicy returns how the app appears in the Dock (macOS):
// ActivationPolicyRegular unless SetActivationPolicy changed it.
func (a *Application) ActivationPolicy() ActivationPolicy {
a.mu.Lock()
defer a.mu.Unlock()
if a.policy == "" {
return ActivationPolicyRegular
}
return a.policy
}
// SetActivationPolicy changes how the app appears in the Dock (macOS).
func (a *Application) SetActivationPolicy(p ActivationPolicy) {
a.mu.Lock()
a.policy = p
running := a.running
a.mu.Unlock()
if running {
onMain(func() { backend().App().SetActivationPolicy(string(p)) })
}
}
// SetDMABUFRenderer sets whether WebKitGTK may draw web pages with its
// DMA-BUF renderer on Linux, which MyGo turns off by default because it
// shows blank windows on NVIDIA's driver, in virtual machines and in
// containers. Where it works, pages scroll at several times the frame
// rate with less CPU. WEBKIT_DISABLE_DMABUF_RENDERER, set by the user,
// overrides it. Call it before Run; other systems ignore it.
func (a *Application) SetDMABUFRenderer(r DMABUFRenderer) {
if r == DMABUFRendererAuto {
linkDMABUFProbe()
}
a.mu.Lock()
a.dmabuf = r
a.mu.Unlock()
}
// Focus brings the application to the foreground.
func (a *Application) Focus() {
needsApp("App.Focus")
onMain(func() { backend().App().Activate() })
}
// IsActive reports whether the application is the active one: the app in
// front on macOS, the app with the window that has the keyboard on Windows
// and Linux, the focused page in browsers.
func (a *Application) IsActive() bool {
needsApp("App.IsActive")
return onMainValue(func() bool { return backend().App().IsActive() })
}
// Hide hides all windows of the application (macOS).
func (a *Application) Hide() {
needsApp("App.Hide")
onMain(func() { backend().App().Hide() })
}
// Show shows the application after Hide (macOS).
func (a *Application) Show() {
needsApp("App.Show")
onMain(func() { backend().App().Unhide() })
}
// IsHidden reports whether the application is hidden (macOS).
func (a *Application) IsHidden() bool {
needsApp("App.IsHidden")
return onMainValue(func() bool { return backend().App().IsHidden() })
}
// SetBadgeCount shows a counter on the application icon. Zero clears it.
func (a *Application) SetBadgeCount(n int) {
needsApp("App.SetBadgeCount")
label := ""
if n > 0 {
label = strconv.Itoa(n)
}
a.Dock.SetBadge(label)
}
// AboutPanelOptions customizes the standard about panel.
type AboutPanelOptions struct {
ApplicationName string
ApplicationVersion string
// Version is the build version shown next to ApplicationVersion.
Version string
Copyright string
Credits string
}
// ShowAboutPanel shows the standard about panel (macOS).
func (a *Application) ShowAboutPanel(opts AboutPanelOptions) {
needsApp("App.ShowAboutPanel")
onMain(func() { backend().App().ShowAboutPanel(platform.AboutPanelOptions(opts)) })
}
// OnReady is called once the application has finished launching.
func (a *Application) OnReady(fn func()) (off func()) { return a.onReady.add(fn, false) }
// OnWindowAllClosed is called when the last window has been closed, unless
// the application is quitting. Without listeners the application quits;
// registering one keeps it running (the common choice on macOS).
func (a *Application) OnWindowAllClosed(fn func()) (off func()) {
return a.onWindowAllClosed.add(fn, false)
}
// OnBeforeQuit is called when a quit starts, before windows are closed.
// e.PreventDefault cancels the quit.
//
// When the OS ends the session (logout, restart, shutdown), on Windows
// (WM_ENDSESSION) and macOS (applicationWillTerminate:), OnBeforeQuit,
// the windows' OnClose and OnWillQuit listeners are called too, with
// e.SessionEnding set: the quit cannot be canceled, and the process may
// be ended as soon as the listeners and OnQuit return, so they must do
// their work synchronously, without dialogs or goroutines to wait for.
// They are not called twice: when a quit had already called them, the
// session's end only finishes it. On Linux, MyGo hears of no session end:
// at shutdown, and at a logout that stops the user's processes, the app
// gets SIGTERM, which quits like Quit, cancelable.
func (a *Application) OnBeforeQuit(fn func(e *QuitEvent)) (off func()) {
return a.onBeforeQuit.add(fn, false)
}
// OnWillQuit is called after all windows have been closed, right before the
// event loop stops. e.PreventDefault cancels the quit, unless the OS ends
// the session (e.SessionEnding; see OnBeforeQuit).
func (a *Application) OnWillQuit(fn func(e *QuitEvent)) (off func()) {
return a.onWillQuit.add(fn, false)
}
// OnQuitCanceled is called when a quit that started was canceled: a
// listener prevented it in OnBeforeQuit or OnWillQuit, or a window kept
// itself open in OnClose. The windows a canceled OnWillQuit had already
// closed stay closed. Apps that track the quit in their own state from
// OnBeforeQuit clear it here; without this event that state would stay set
// although the app goes on running.
func (a *Application) OnQuitCanceled(fn func()) (off func()) {
return a.onQuitCanceled.add(fn, false)
}
// OnQuit is called after the event loop has stopped, and after the
// windows' states are saved (WindowOptions.StateKey). When the OS ends
// the session, it is called after OnBeforeQuit and OnWillQuit (see
// OnBeforeQuit), and the process may end as soon as it returns: it is the
// last hook, and must finish its work synchronously.
func (a *Application) OnQuit(fn func()) (off func()) { return a.onQuit.add(fn, false) }
// OnSaveState has fn give what the app needs to come back as it was, called on
// the main thread as a phone's app goes to the background, where the system may
// end it without a word. The next launch finds it in RestoredState. Keep it
// small: it is written before the app may do no more. Desktops never call it,
// but under mygo dev, which restarts the app as the code changes: it is called
// every second there, for the app to come back as it was on every platform.
func (a *Application) OnSaveState(fn func() []byte) {
a.saveState = fn
a.keepStateInDevelopment()
}
// RestoredState returns what OnSaveState gave as the app went to the background,
// if the system ended it there. Android tells when the user meant to leave, which
// gives nil. iOS doesn't say by the time the app starts: an app the user force-quit
// from the background gets it too. An end while the app is on screen, as a crash,
// gives nil.
func (a *Application) RestoredState() []byte { return restoredState() }
// OnMemoryWarning is called on the main thread when the system is short of
// memory: let go of what can be made again, as caches. Phones end apps that
// keep too much; desktops do not report it. Native UI drops its own caches
// after these listeners ran, and the garbage collector returns what it can.
func (a *Application) OnMemoryWarning(fn func()) (off func()) {
return a.onMemoryWarning.add(fn, false)
}
// OnActivate is called when the application is re-activated, for example by
// clicking its Dock icon (macOS). Apps usually open a window when
// hasVisibleWindows is false.
func (a *Application) OnActivate(fn func(hasVisibleWindows bool)) (off func()) {
return a.onActivate.add(fn, false)
}
// OnDidBecomeActive is called when the application becomes the active one.
func (a *Application) OnDidBecomeActive(fn func()) (off func()) {
return a.onDidBecomeActive.add(fn, false)
}
// OnDidResignActive is called when the application stops being active.
func (a *Application) OnDidResignActive(fn func()) (off func()) {
return a.onDidResignActive.add(fn, false)
}
// OnOpenURL is called when the application is asked to open a URL of a
// scheme it handles: one listed in urlSchemes in mygo.config.ts or registered
// with RegisterURLScheme. Register it before Run to receive the URL the app
// was launched with. On Windows and Linux, where a URL starts a new
// instance of the app, use RequestSingleInstanceLock so that the first
// instance gets the URLs of later ones.
func (a *Application) OnOpenURL(fn func(url string)) (off func()) {
return a.onOpenURL.add(fn, false)
}
// OnOpenFile is called when a file is opened with the application: one of
// the types of fileAssociations in mygo.config.ts opened from the file manager,
// a file dropped on the Dock icon (macOS), or one passed on the command
// line. Register it before Run to receive the files the app was launched
// with; on Windows and Linux, RequestSingleInstanceLock makes the first
// instance get those of later ones.
func (a *Application) OnOpenFile(fn func(path string)) (off func()) {
return a.onOpenFile.add(fn, false)
}
// OnNotificationClick is called with the ID of every notification of the
// app that the user clicks, after its OnClick listeners: also one of an
// earlier run, which no Notification of this run holds, such as the one
// whose click launched the app (macOS). Register it before Run to receive
// that one. Give notifications IDs of the app's own, such as the
// conversation they are about, to know what to open.
func (a *Application) OnNotificationClick(fn func(id string)) (off func()) {
return a.onNotificationClick.add(fn, false)
}
// OnWindowCreated is called for every new window.
func (a *Application) OnWindowCreated(fn func(w *Window)) (off func()) {
return a.onWindowCreated.add(fn, false)
}
// ClearBrowsingData deletes what the app's pages stored in the default
// session: cookies, local and session storage, IndexedDB, service workers
// and caches, e.g. when the user signs out. Open pages keep what they hold
// in memory until they are reloaded. Session.ClearData clears the data of
// other sessions, or some kinds of data.
func (a *Application) ClearBrowsingData() error {
needsApp("App.ClearBrowsingData")
ch := make(chan error, 1)
onMain(func() {
backend().App().ClearBrowsingData(nil, platform.SiteDataAll, func(err error) { deliver(ch, err) })
})
return await(ch)
}
// Dock controls the application's Dock icon (macOS). Its methods do
// nothing on other platforms.
type Dock struct {
mu sync.Mutex
menu *Menu
}
// SetMenu sets the menu the Dock icon shows above the standard items, e.g.
// to open a new window; nil removes it. It may be called before App.Run.
func (d *Dock) SetMenu(m *Menu) {
d.mu.Lock()
d.menu = m // its items must stay reachable for clicks
d.mu.Unlock()
onMain(func() {
if App.initialized { // else Run installs it
// The menu set last: calls may reach the main thread in
// another order.
backend().App().SetDockMenu(d.Menu().snapshot())
}
})
}
// Menu returns the menu set with SetMenu.
func (d *Dock) Menu() *Menu {
d.mu.Lock()
defer d.mu.Unlock()
return d.menu
}
// SetBadge shows text on the Dock icon; "" clears it.
func (d *Dock) SetBadge(text string) {
needsApp("App.Dock.SetBadge")
onMain(func() { backend().App().SetBadge(text) })
}
// Badge returns the text shown on the Dock icon.
func (d *Dock) Badge() string {
needsApp("App.Dock.Badge")
return onMainValue(func() string { return backend().App().Badge() })
}
// Bounce bounces the Dock icon to request attention and returns an id for
// CancelBounce. Critical bounces continue until the app is activated.
func (d *Dock) Bounce(critical bool) int {
needsApp("App.Dock.Bounce")
return onMainValue(func() int { return backend().App().Bounce(critical) })
}
// CancelBounce stops a bounce started with Bounce.
func (d *Dock) CancelBounce(id int) {
needsApp("App.Dock.CancelBounce")
onMain(func() { backend().App().CancelBounce(id) })
}
// SetIcon replaces the Dock icon with a PNG image.
func (d *Dock) SetIcon(png []byte) error {
needsApp("App.Dock.SetIcon")
return onMainValue(func() error { return backend().App().SetDockIcon(png) })
}
// Hide removes the Dock icon (accessory activation policy).
func (d *Dock) Hide() { App.SetActivationPolicy(ActivationPolicyAccessory) }
// Show restores the Dock icon (regular activation policy).
func (d *Dock) Show() { App.SetActivationPolicy(ActivationPolicyRegular) }
// appHandler receives application events from the backend.
type appHandler struct{}
func (appHandler) Ready() { App.handleReady() }
func (appHandler) Dispatch() { loop.drain() }
func (appHandler) QuitRequested() bool {
if App.stopping {
// The loop goes on although asked to stop: ask again.
return true
}
if !App.prepareQuit() {
return false
}
// The backend stops its loop itself.
App.loopStopping()
return true
}
func (appHandler) Terminating() {
App.endSession()
App.finish()
}
func (appHandler) Activated(visible bool) {
fire1(&App.onActivate, visible)
}
func (appHandler) DidBecomeActive() {
backgroundShow = false
fire(&App.onDidBecomeActive)
}
func (appHandler) DidResignActive() { fire(&App.onDidResignActive) }
func (appHandler) OpenURLs(urls []string) {
for _, u := range urls {
fire1(&App.onOpenURL, u)
}
}
func (appHandler) OpenFiles(paths []string) {
for _, p := range paths {
fire1(&App.onOpenFile, p)
}
}
func (appHandler) MenuItemClicked(id int) { menuItemClicked(id, FocusedWindow()) }
func (appHandler) ThemeChanged() {
updateBackgrounds()
contentThemeChanged()
Theme.changed()
// Pages hear the accent and the settings of accessibility, which the
// media queries do not tell them.
sendPreferences()
}
func (appHandler) MemoryWarning() { fire(&App.onMemoryWarning) }
func (appHandler) DisplaysChanged() { Screen.changed() }
func (appHandler) LocaleChanged() { App.localeChangedFromSystem() }
func (appHandler) PowerEvent(event string) {
switch event {
case "suspend":
App.writeState()
case "resume":
forgetKeptState()
}
Power.event(event)
}
func (appHandler) HotkeyPressed(id int) { GlobalShortcut.pressed(id) }
func (appHandler) NotificationClicked(id string) { notificationClicked(id) }
func (appHandler) NetworkChanged(s platform.NetworkStatus) { Network.changed(networkStatus(s)) }
func (appHandler) HotkeyBound(id int, keys string) { GlobalShortcut.bound(id, keys) }
+85
View File
@@ -0,0 +1,85 @@
package mygo
import (
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
)
// Windows refuses to replace or delete a file that another program has
// open without sharing its deletion, as Go opens files, and antivirus
// software and indexers do while they scan new files; and it refuses to
// open a file while it is being replaced. The app's own files (window
// states, recovery copies, recent documents) are replaced in place, so
// their renames and reads retry for a few seconds while Windows reports
// them in use, rather than lose what they hold. The app's own reads share
// the file's deletion (readShared) and its replaces rename with POSIX
// semantics (renameOver), so that a goroutine reading an app file never
// keeps another from saving it.
// rename renames a file of the app, retrying while Windows reports it in
// use.
func rename(from, to string) error {
return retryInUse(func() error { return os.Rename(from, to) })
}
// replaceAppFile renames from over to, its sibling, retrying while
// Windows reports it in use: a read by readAppFile does not, only another
// program holding to open without sharing its deletion.
func replaceAppFile(from, to string) error {
return retryInUse(func() error { return renameOver(from, to) })
}
// readAppFile reads a file of the app, retrying while Windows reports it
// in use, or reports it missing while it is being replaced: Windows can
// fail to open the name for a moment while a rename replaces the file.
func readAppFile(path string) (data []byte, err error) {
read := func() error {
data, err = readShared(path)
return err
}
for i := 1; ; i++ {
err = retryInUse(read)
if i == 5 || runtime.GOOS != "windows" || !errors.Is(err, fs.ErrNotExist) {
return data, err
}
if !beingReplaced(path) {
// A replace that finished since the read left the file in place.
err = retryInUse(read)
return data, err
}
time.Sleep(time.Duration(i) * 10 * time.Millisecond)
}
}
// beingReplaced reports whether path is being replaced: writeAppFile's
// temporary sibling (createSibling) stays in place until its rename is
// done.
func beingReplaced(path string) bool {
dir, base := filepath.Split(path)
entries, _ := os.ReadDir(dir)
for _, e := range entries {
if name := e.Name(); strings.HasPrefix(name, "."+base+".") && strings.HasSuffix(name, ".tmp") {
return true
}
}
return false
}
func retryInUse(f func() error) error {
for i := 1; ; i++ {
err := f()
if err == nil || i == 10 || runtime.GOOS != "windows" ||
// ERROR_SHARING_VIOLATION, or ERROR_ACCESS_DENIED for a file
// being deleted or replaced, or a directory holding an open file.
!errors.Is(err, syscall.Errno(32)) && !errors.Is(err, syscall.Errno(5)) {
return err
}
time.Sleep(time.Duration(i) * 100 * time.Millisecond)
}
}
+11
View File
@@ -0,0 +1,11 @@
//go:build !windows
package mygo
import "os"
// readShared reads the file at path, which others may replace meanwhile.
func readShared(path string) ([]byte, error) { return os.ReadFile(path) }
// renameOver renames from over to.
func renameOver(from, to string) error { return os.Rename(from, to) }
+89
View File
@@ -0,0 +1,89 @@
package mygo
import (
"io"
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
// TestAppFileReadDoesNotBlockReplace: a file of the app, open as
// readAppFile opens it, is replaced at once, without waiting for the
// reader to let go, which goes on reading what it opened.
func TestAppFileReadDoesNotBlockReplace(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "index.json")
if err := os.WriteFile(path, []byte("old"), 0o644); err != nil {
t.Fatal(err)
}
f, err := openShared(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
tmp := filepath.Join(dir, ".index.json.tmp")
if err := os.WriteFile(tmp, []byte("new"), 0o644); err != nil {
t.Fatal(err)
}
// renameOver, not replaceAppFile, which would retry until f is closed.
if err := renameOver(tmp, path); err != nil {
t.Fatalf("replacing a file the app reads: %v", err)
}
if b, err := io.ReadAll(f); err != nil || string(b) != "old" {
t.Errorf("read %q, %v from the file opened before the replace", b, err)
}
if b, err := readAppFile(path); err != nil || string(b) != "new" {
t.Errorf("read %q, %v after the replace", b, err)
}
}
// TestAppFileInUse: a file of the app that another program has open, as
// antivirus software scanning it, is replaced once it lets go, and read
// while it is being replaced.
func TestAppFileInUse(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("only Windows keeps open files from being replaced")
}
path := filepath.Join(t.TempDir(), "index.json")
if err := os.WriteFile(path, []byte("old"), 0o644); err != nil {
t.Fatal(err)
}
// Go opens files without sharing their deletion, which replacing needs.
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { f.Close() })
time.AfterFunc(500*time.Millisecond, func() { f.Close() })
if err := writeAppFile(path, func(w io.Writer) error { _, err := io.WriteString(w, "new"); return err }); err != nil {
t.Fatal(err)
}
if b, err := readAppFile(path); err != nil || string(b) != "new" {
t.Errorf("read %q, %v after the replace", b, err)
}
// Reads while it is replaced over and over.
done := make(chan struct{})
go func() {
defer close(done)
for i := 0; i < 200; i++ {
if err := writeAppFile(path, func(w io.Writer) error { _, err := io.WriteString(w, "x"); return err }); err != nil {
t.Errorf("write %d: %v", i, err)
return
}
}
}()
for {
select {
case <-done:
return
default:
}
if _, err := readAppFile(path); err != nil {
t.Errorf("read while replaced: %v", err)
<-done
return
}
}
}
+44
View File
@@ -0,0 +1,44 @@
package mygo
import (
"errors"
"io"
"os"
"path/filepath"
)
// readShared reads the file at path through openShared, which shares its
// deletion: os.ReadFile does not, and while it held the file open, a save
// replacing it was refused ("Access is denied"), so that a goroutine
// reading an app file in a loop could make another's save run out of
// retries.
func readShared(path string) ([]byte, error) {
f, err := openShared(path)
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
}
// renameOver renames from over to, its sibling, with POSIX semantics
// (os.Root.Rename), which replace a file that others hold open sharing its
// deletion, as readShared does. os.Rename's MoveFileEx is refused while
// any handle to the file is open, whatever it shares. The root comes from
// fileWatchOpenRoot, which shares the directory's deletion.
func renameOver(from, to string) error {
dir := filepath.Dir(to)
if filepath.Dir(from) != dir {
return os.Rename(from, to)
}
root, err := fileWatchOpenRoot(dir)
if err != nil {
return err
}
defer root.Close()
err = root.Rename(filepath.Base(from), filepath.Base(to))
if le := (*os.LinkError)(nil); errors.As(err, &le) {
err = &os.LinkError{Op: "rename", Old: from, New: to, Err: le.Err}
}
return err
}
+203
View File
@@ -0,0 +1,203 @@
// Package aac decodes AAC-LC for package audio, with
// github.com/tphakala/go-aac: in MP4 (.m4a, and fragmented .m4s as DASH
// streams it), through package audio/mp4, and in ADTS (.aac). Import it
// for its side effect:
//
// import _ "github.com/egoist/mygo/audio/aac"
//
// HE-AAC (AAC+, with SBR) and HE-AAC v2 it does not decode: their files
// fail to open, and mp4.Track's Decodable says so of them.
//
// go-aac is under the LGPL 2.1 or later, unlike MyGo, whose license is
// MIT: an app that imports this package links it, and takes on the LGPL's
// terms for it.
package aac
import (
"encoding/binary"
"errors"
"io"
"github.com/egoist/mygo/audio"
"github.com/egoist/mygo/audio/mp4"
aacpcm "github.com/tphakala/go-aac/pcm"
)
func init() {
mp4.RegisterCodec("mp4a", func(config []byte) (mp4.Codec, error) { return NewCodec(config) })
open := func(r io.ReadSeeker) (audio.Decoder, error) { return NewADTSDecoder(r) }
// The sync word of an ADTS header, of MPEG-4 or MPEG-2, with a CRC or
// without; MP3's differ in their layer.
for _, b := range []string{"\xff\xf1", "\xff\xf0", "\xff\xf9", "\xff\xf8"} {
audio.RegisterFormat("aac", b, open)
}
}
// FrameLength is how many frames each AAC packet decodes to.
const FrameLength = 1024
// codec decodes AAC packets, raw as in an MP4 or each with its ADTS header.
type codec struct {
fd *aacpcm.FrameDecoder
pcm []byte
}
// NewCodec returns a decoder of the raw AAC packets of a track configured
// by asc, its AudioSpecificConfig: an MP4's, for package mp4.
func NewCodec(asc []byte) (mp4.Codec, error) {
fd, err := aacpcm.NewRawDecoder(asc)
if err != nil {
return nil, err
}
return &codec{fd: fd}, nil
}
func (c *codec) SampleRate() int { return c.fd.SampleRate() }
func (c *codec) Reset() { c.fd.Reset() }
func (c *codec) Preroll() int { return 1 }
func (c *codec) PacketFrames() int { return FrameLength }
func (c *codec) Decode(dst []float32, packet []byte) ([]float32, error) {
pcm, n, err := c.fd.DecodeFrame(c.pcm[:0], packet)
if err != nil {
return dst, err
}
c.pcm = pcm
ch := c.fd.Channels()
right := 0
if ch > 1 {
right = 2
}
for i := range n {
f := pcm[i*ch*2:]
dst = append(dst,
float32(int16(binary.LittleEndian.Uint16(f)))/(1<<15),
float32(int16(binary.LittleEndian.Uint16(f[right:])))/(1<<15))
}
return dst, nil
}
var adtsRates = [...]int{96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350}
// adtsHeader reads an ADTS frame's header: its length in bytes, and its
// sample rate.
func adtsHeader(h []byte) (length, rate int, ok bool) {
if len(h) < 7 || h[0] != 0xff || h[1]&0xf6 != 0xf0 {
return 0, 0, false
}
i := int(h[2] >> 2 & 15)
length = int(h[3]&3)<<11 | int(h[4])<<3 | int(h[5]>>5)
if i >= len(adtsRates) || length < 7 {
return 0, 0, false
}
return length, adtsRates[i], true
}
// adts decodes AAC in ADTS frames, each with a header saying how long it
// is, which it finds all of as it opens, for the length and to seek.
type adts struct {
r io.ReadSeeker
c *codec
rate int
offs []int64
sizes []int
next int // the packet decoded next
skip int64 // frames to drop before the frame Read returns next
buf []byte
out []float32
pend []float32
}
// NewADTSDecoder returns a decoder of the AAC in ADTS frames r holds, as
// an .aac file, after an ID3 tag if one is first. It decodes to stereo.
func NewADTSDecoder(r io.ReadSeeker) (audio.Decoder, error) {
start, err := skipID3(r)
if err != nil {
return nil, err
}
d := &adts{r: r, c: &codec{fd: aacpcm.NewADTSDecoder()}}
var h [7]byte
for off := start; ; {
if _, err := r.Seek(off, io.SeekStart); err != nil {
return nil, err
}
if _, err := io.ReadFull(r, h[:]); err != nil {
break
}
length, rate, ok := adtsHeader(h[:])
if !ok {
break
}
if d.rate == 0 {
d.rate = rate
}
d.offs = append(d.offs, off)
d.sizes = append(d.sizes, length)
off += int64(length)
}
if len(d.offs) == 0 {
return nil, errors.New("aac: not an ADTS stream")
}
return d, d.SetPosition(0)
}
// skipID3 returns where r's audio starts: after an ID3 tag, if r starts
// with one.
func skipID3(r io.ReadSeeker) (int64, error) {
var b [10]byte
if _, err := r.Seek(0, io.SeekStart); err != nil {
return 0, err
}
if _, err := io.ReadFull(r, b[:]); err != nil || string(b[:3]) != "ID3" {
return 0, nil
}
return 10 + int64(b[6]&0x7f)<<21 | int64(b[7]&0x7f)<<14 | int64(b[8]&0x7f)<<7 | int64(b[9]&0x7f), nil
}
func (d *adts) SampleRate() int { return d.rate }
func (d *adts) Channels() int { return 2 }
func (d *adts) Len() int64 { return int64(len(d.offs)) * FrameLength }
func (d *adts) Read(dst []float32) (int, error) {
for len(d.pend) == 0 {
if d.next >= len(d.offs) {
return 0, io.EOF
}
size := d.sizes[d.next]
if cap(d.buf) < size {
d.buf = make([]byte, size)
}
d.buf = d.buf[:size]
if _, err := d.r.Seek(d.offs[d.next], io.SeekStart); err != nil {
return 0, err
}
if _, err := io.ReadFull(d.r, d.buf); err != nil {
return 0, io.EOF
}
d.next++
out, err := d.c.Decode(d.out[:0], d.buf)
d.out = out
if err != nil {
continue // a packet gone bad: on to the next
}
drop := min(d.skip, int64(len(out)/2))
d.skip -= drop
d.pend = out[drop*2:]
}
n := copy(dst[:len(dst)/2*2], d.pend)
d.pend = d.pend[n:]
return n, nil
}
// SetPosition goes to the packet holding frame, from the one before, whose
// sound overlaps it, and drops what comes before frame.
func (d *adts) SetPosition(frame int64) error {
frame = min(max(frame, 0), d.Len())
i := int(frame / FrameLength)
start := max(0, i-1)
d.c.Reset()
d.next = start
d.skip = frame - int64(start)*FrameLength
d.pend = nil
return nil
}
+156
View File
@@ -0,0 +1,156 @@
package aac_test
import (
"bytes"
"encoding/binary"
"testing"
"time"
_ "github.com/egoist/mygo/audio/aac"
_ "github.com/egoist/mygo/audio/flac"
"github.com/egoist/mygo/audio/internal/audiotest"
"github.com/egoist/mygo/audio/mp4"
)
// The source the files were encoded from.
func source(t *testing.T) []float32 {
return audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "../flac/testdata/tone.flac"), "flac"))
}
// AAC's encoder adds a packet of priming before the sound.
const prime = 1024
// An AAC .m4a drops the encoder's priming, as its edit list says, so it
// lines up with what it was encoded from and is as long. A seek decodes the
// packet before, whose sound overlaps the one sought to.
func TestMP4(t *testing.T) {
b := audiotest.Read(t, "testdata/tone.m4a")
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
if err != nil {
t.Fatal(err)
}
if tr.Codec != "mp4a" || tr.Duration != 2*time.Second || !tr.Decodable() {
t.Fatalf("%+v", tr)
}
d := audiotest.Open(t, b, "mp4")
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 88200 {
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
}
got := audiotest.ReadAll(t, d)
if len(got) != 88200*2 {
t.Fatalf("decoded %d samples", len(got))
}
if db := audiotest.SNR(got, source(t)); db < 20 {
t.Errorf("%.1f dB from the source", db)
}
// Noise the encoder substituted is random each time it's decoded.
audiotest.SeekLands(t, d, got, 0.05, 0, 1, 4096, 50000, 77777)
}
// An AAC .m4a cut into fragments, as a stream for DASH is, plays what it
// was encoded from too, with its length from its segment index. Its movie
// header has no edit list, so the encoder's priming plays; the padding of
// its last packet doesn't, as its last packet's duration says.
func TestFragmented(t *testing.T) {
b := audiotest.Read(t, "testdata/fragmented.m4a")
d := audiotest.Open(t, b, "mp4")
length := d.Len()
got := audiotest.ReadAll(t, d)
src := source(t)
if len(got) != len(src)+prime*2 {
t.Fatalf("decoded %d samples, the source %d", len(got), len(src))
}
if length*2 != int64(len(got)) || d.Len() != length {
t.Errorf("length %d, then %d, though %d frames decode", length, d.Len(), len(got)/2)
}
if db := audiotest.SNR(got[prime*2:], src); db < 20 {
t.Errorf("%.1f dB from the source", db)
}
audiotest.SeekLands(t, d, got, 0.05, 0, 1, 4096, 50000, 77777)
}
// AAC's packets each decode to 1024 frames, whatever the file says they
// last: a seek lands where decoding straight through has the frame. Some
// files have a packet near the start a few frames shorter, which would put
// every seek past it that much off.
func TestPacketsOfOtherDurations(t *testing.T) {
b := bytes.Clone(audiotest.Read(t, "testdata/fragmented.m4a"))
// The first fragment's packets last 1016 frames, its header says.
at := bytes.Index(b, []byte("tfhd"))
flags := binary.BigEndian.Uint32(b[at+4:]) & 0xffffff
if flags&0x08 == 0 {
t.Fatal("the fragment has no default duration")
}
at += 4 + 8
if flags&0x01 != 0 {
at += 8
}
if flags&0x02 != 0 {
at += 4
}
if binary.BigEndian.Uint32(b[at:]) != 1024 {
t.Fatal("no default duration of 1024 where expected")
}
binary.BigEndian.PutUint32(b[at:], 1016)
d := audiotest.Open(t, b, "mp4")
got := audiotest.ReadAll(t, d)
for _, frame := range []int64{30000, 60000, 60001} {
if err := d.SetPosition(frame); err != nil {
t.Fatal(err)
}
var read []float32
buf := make([]float32, 4096)
for len(read) < 44100 {
n, err := d.Read(buf)
read = append(read, buf[:n]...)
if err != nil || n == 0 {
break
}
}
if db := audiotest.SNR(read, got[frame*2:]); db < 20 {
t.Errorf("seek to %d: %.1f dB from decoding straight through", frame, db)
}
}
}
// An .aac of ADTS frames plays what it was encoded from, after the
// encoder's priming, which nothing says to drop.
func TestADTS(t *testing.T) {
b := audiotest.Read(t, "testdata/tone.aac")
d := audiotest.Open(t, b, "aac")
if d.SampleRate() != 44100 || d.Channels() != 2 {
t.Fatalf("%d Hz, %d channels", d.SampleRate(), d.Channels())
}
got := audiotest.ReadAll(t, d)
if int64(len(got)) != d.Len()*2 || len(got) < (88200+prime)*2 {
t.Fatalf("decoded %d samples, length %d", len(got), d.Len())
}
if db := audiotest.SNR(got[prime*2:], source(t)); db < 20 {
t.Errorf("%.1f dB from the source", db)
}
audiotest.SeekLands(t, d, got, 0.05, 0, 1, 4096, 50000, 77777)
// After an ID3 tag too.
tag := append([]byte("ID3\x04\x00\x00\x00\x00\x00\x20"), make([]byte, 32)...)
d = audiotest.Open(t, append(tag, b...), "aac")
if again := audiotest.ReadAll(t, d); len(again) != len(got) {
t.Errorf("decoded %d samples after an ID3 tag, %d without", len(again), len(got))
}
}
// HE-AAC, with SBR, isn't decoded: a track of it says so.
func TestHEAAC(t *testing.T) {
for _, tt := range []struct {
name string
config []byte
want bool
}{
{"AAC-LC", []byte{0x12, 0x10}, true},
{"HE-AAC", []byte{0x2b, 0x12, 0x08}, false},
} {
tr := mp4.Track{Codec: "mp4a", Config: tt.config}
if got := tr.Decodable(); got != tt.want {
t.Errorf("%s: decodable %v", tt.name, got)
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+610
View File
@@ -0,0 +1,610 @@
// Package audio plays sound: effects decoded into memory, music streamed
// as it plays, and sound an app makes itself, mixed in Go and sent to the
// system's audio output:
//
// click, err := audio.DecodeSound(clickWAV) // decoded once
// ...
// click.Play() // as often as it sounds, over itself
//
// music, err := audio.OpenStream(f) // decoded as it plays
// music.SetLoop(true).SetVolume(0.6).Play()
//
// WAV decodes out of the box; import audio/vorbis for Ogg Vorbis and
// audio/mp3 for MP3, which register themselves as image's formats do.
//
// The output opens when something first plays and closes a few seconds
// after everything stopped. Where no output can open, players still play
// on time, unheard, and Err says why. Every function and method is safe
// to call from any goroutine.
package audio
import (
"bufio"
"bytes"
"errors"
"io"
"math"
"runtime"
"slices"
"sync"
"time"
)
// The output's format: every player is resampled to it.
const (
sampleRate = 48000
channels = 2
)
// mu guards the voices playing and the state of every player.
var mu sync.Mutex
// A Decoder decodes audio as interleaved float32 samples in [-1, 1], one
// per channel for each frame. Formats registered with RegisterFormat
// return one; implement one to play sound an app generates itself.
type Decoder interface {
// SampleRate returns the frames per second.
SampleRate() int
// Channels returns the samples per frame: 1 for mono, 2 for stereo
// (left, right); later channels of more are not played.
Channels() int
// Read decodes the next samples into buf, a whole number of frames,
// and returns how many it wrote, with io.EOF at the end.
Read(buf []float32) (int, error)
// SetPosition moves to frame, counted from the start.
SetPosition(frame int64) error
// Len returns the frames from the start to the end, or -1 if unknown.
Len() int64
}
type format struct {
name, magic string
open func(io.ReadSeeker) (Decoder, error)
}
var (
formatsMu sync.Mutex
formats []format
)
// RegisterFormat registers a format for DecodeSound, OpenStream and
// NewDecoder: magic is the start of its files, where '?' matches any
// byte, and open returns a decoder reading r from its start. A file that
// starts with an ID3 tag is of the format its bytes after the tag match,
// and its decoder reads it from the tag. A package for a format calls it
// in its init function.
func RegisterFormat(name, magic string, open func(r io.ReadSeeker) (Decoder, error)) {
formatsMu.Lock()
defer formatsMu.Unlock()
formats = append(formats, format{name, magic, open})
}
// ErrFormat reports data of no format registered.
var ErrFormat = errors.New("audio: unknown format")
func match(magic string, b []byte) bool {
if len(magic) > len(b) {
return false
}
for i := 0; i < len(magic); i++ {
if magic[i] != '?' && magic[i] != b[i] {
return false
}
}
return true
}
// NewDecoder returns a decoder of r's format, and the format's name.
func NewDecoder(r io.ReadSeeker) (Decoder, string, error) {
start, err := r.Seek(0, io.SeekCurrent)
if err != nil {
return nil, "", err
}
var head, after [16]byte
n, err := io.ReadFull(r, head[:])
if err != nil && err != io.ErrUnexpectedEOF {
return nil, "", err
}
// An ID3 tag first, as MP3s have and some FLAC and AAC files too: the
// format is what follows it.
m := 0
if n >= 10 && string(head[:3]) == "ID3" {
size := int64(head[6]&0x7f)<<21 | int64(head[7]&0x7f)<<14 | int64(head[8]&0x7f)<<7 | int64(head[9]&0x7f)
if _, err := r.Seek(start+10+size, io.SeekStart); err == nil {
m, _ = io.ReadFull(r, after[:])
}
}
if _, err := r.Seek(start, io.SeekStart); err != nil {
return nil, "", err
}
formatsMu.Lock()
fs := formats
formatsMu.Unlock()
for _, b := range [][]byte{after[:m], head[:n]} {
for _, f := range fs {
if len(b) > 0 && match(f.magic, b) {
d, err := f.open(r)
if err != nil {
return nil, f.name, err
}
return d, f.name, nil
}
}
}
return nil, "", ErrFormat
}
// A Sound is audio decoded into memory, for effects that play often and
// over themselves: each Play is a new Player.
type Sound struct {
samples []float32
channels int
rate int
}
// DecodeSound decodes data of a registered format into memory.
func DecodeSound(data []byte) (*Sound, error) {
d, _, err := NewDecoder(bytes.NewReader(data))
if err != nil {
return nil, err
}
return ReadSound(d)
}
// reserveFrames is the most frames ReadSound reserves from a decoder's
// Len, six minutes at 44.1 kHz: a header can say any length, and a longer
// sound grows as it is decoded.
const reserveFrames = 1 << 24
// ReadSound decodes everything d has into memory.
func ReadSound(d Decoder) (*Sound, error) {
ch := d.Channels()
if ch < 1 || d.SampleRate() <= 0 {
return nil, errors.New("audio: decoder of no channels or sample rate")
}
keep := min(ch, 2)
var samples []float32
if n := d.Len(); n > 0 {
samples = make([]float32, 0, min(n, reserveFrames)*int64(keep))
}
buf := make([]float32, 4096/ch*ch)
for {
n, err := d.Read(buf)
n -= n % ch
for i := 0; i < n; i += ch {
samples = append(samples, buf[i:i+keep]...)
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if n == 0 {
return nil, io.ErrNoProgress
}
}
return &Sound{samples: samples, channels: keep, rate: d.SampleRate()}, nil
}
// NewSound returns a sound of samples, interleaved frames of 1 (mono) or 2
// (stereo) channels at sampleRate frames per second, as an app generates
// them. The sound keeps samples: don't change them afterwards.
func NewSound(sampleRate, channels int, samples []float32) *Sound {
if channels != 1 && channels != 2 {
panic("audio: NewSound takes 1 or 2 channels")
}
if sampleRate <= 0 {
panic("audio: NewSound takes a positive sample rate")
}
return &Sound{samples: samples[:len(samples)/channels*channels], channels: channels, rate: sampleRate}
}
// Duration returns how long the sound plays.
func (s *Sound) Duration() time.Duration {
return frames(int64(len(s.samples)/s.channels), s.rate)
}
// NewPlayer returns a paused player of the sound.
func (s *Sound) NewPlayer() *Player {
src := &memSource{samples: s.samples, channels: s.channels}
return newPlayer(src, s.rate, s.channels, int64(len(s.samples)/s.channels))
}
// Play plays the sound from its start, over any other of its players, and
// returns the player playing it.
func (s *Sound) Play() *Player {
p := s.NewPlayer()
p.Play()
return p
}
// OpenStream returns a paused player decoding r as it plays, for music and
// other long audio: it decodes about a second ahead. Closing the player
// closes r if r is an io.Closer.
func OpenStream(r io.ReadSeeker) (*Player, error) {
d, _, err := NewDecoder(r)
if err != nil {
return nil, err
}
if c, ok := r.(io.Closer); ok {
d = closingDecoder{d, c}
}
return NewPlayer(d), nil
}
type closingDecoder struct {
Decoder
io.Closer
}
// NewPlayer returns a paused player decoding d as it plays, about a second
// ahead. d is used by one goroutine at a time. Closing the player closes d
// if d is an io.Closer.
func NewPlayer(d Decoder) *Player {
ch := min(d.Channels(), 2)
s := newStream(d)
p := newPlayer(s, d.SampleRate(), ch, d.Len())
// A player dropped while paused would leave its decoder waiting; one
// dropped while playing plays to its end, as a sound's do.
runtime.AddCleanup(p, func(v *voice) {
mu.Lock()
defer mu.Unlock()
if v.active {
v.orphan = true
} else {
v.close()
}
}, p.v)
return p
}
// readerOf buffers r when it reads small amounts at a time, as a file.
func readerOf(r io.Reader) io.Reader {
if _, ok := r.(*bytes.Reader); ok {
return r
}
return bufio.NewReader(r)
}
// frames returns the duration of n frames at rate.
func frames(n int64, rate int) time.Duration {
return time.Duration(float64(n) * float64(time.Second) / float64(rate))
}
// A Player plays a sound or a stream: its position, volume, pan, speed and
// looping are its own.
type Player struct {
v *voice
}
func newPlayer(src source, rate, ch int, length int64) *Player {
v := &voice{src: src, rate: float64(rate), mono: ch == 1, length: length, volume: 1, speed: 1}
v.reset(0)
return &Player{v}
}
// Play plays from where the player is, or from the start if it ended.
func (p *Player) Play() {
mu.Lock()
defer mu.Unlock()
v := p.v
if v.closed || v.playing {
return
}
if v.ended() {
v.src.seek(0)
v.reset(0)
}
v.playing = true
if !v.active {
// A sound starting at its start starts at once; one resuming in
// the middle fades in, as one pausing fades out, without a click.
// One still fading out ramps back from where it is.
v.snap = v.head <= 0
v.fadeIn = !v.snap
v.active = true
voices = append(voices, v)
wakeOutput()
}
}
// Pause pauses the player where it is.
func (p *Player) Pause() {
mu.Lock()
defer mu.Unlock()
p.v.playing = false
}
// Stop pauses the player and moves it to the start.
func (p *Player) Stop() {
mu.Lock()
defer mu.Unlock()
v := p.v
if v.closed {
return
}
v.playing = false
v.src.seek(0)
v.reset(0)
}
// Playing reports whether the player plays: false once paused, stopped,
// closed, or at its end.
func (p *Player) Playing() bool {
mu.Lock()
defer mu.Unlock()
return p.v.playing
}
// endListener is a function OnEnd registered.
type endListener struct {
id uint64
fn func()
}
// OnEnd calls fn on a goroutine of its own each time the player plays to
// its end, which a looping player never does, as a playlist plays the
// next track then. off removes it.
func (p *Player) OnEnd(fn func()) (off func()) {
mu.Lock()
defer mu.Unlock()
v := p.v
v.nextEnd++
id := v.nextEnd
v.onEnd = append(v.onEnd, endListener{id, fn})
return func() {
mu.Lock()
defer mu.Unlock()
v.onEnd = slices.DeleteFunc(slices.Clone(v.onEnd), func(l endListener) bool { return l.id == id })
}
}
// Seek moves the player to t from the start.
func (p *Player) Seek(t time.Duration) {
mu.Lock()
defer mu.Unlock()
v := p.v
if v.closed {
return
}
f := max(int64(math.Round(t.Seconds()*v.rate)), 0)
if v.length >= 0 {
f = min(f, v.length)
}
v.src.seek(f)
v.reset(f)
}
// Position returns how far the player is from the start, in what is heard:
// the output mixes ahead of it (SetLatency), and the player goes on for
// as long after a pause, but it is where Seek moved it at once.
func (p *Player) Position() time.Duration {
mu.Lock()
defer mu.Unlock()
return time.Duration(p.v.position(p.v.heardAt()) / p.v.rate * float64(time.Second))
}
// Duration returns how long the player's audio is, or 0 if unknown.
func (p *Player) Duration() time.Duration {
if p.v.length < 0 {
return 0
}
return frames(p.v.length, int(p.v.rate))
}
// SetVolume sets the player's volume, a gain: 1 (the default) as decoded,
// 0 silent. Changes ramp over a few milliseconds, without a click.
func (p *Player) SetVolume(v float64) *Player {
mu.Lock()
defer mu.Unlock()
p.v.volume = max(v, 0)
return p
}
// Volume returns the player's volume.
func (p *Player) Volume() float64 {
mu.Lock()
defer mu.Unlock()
return p.v.volume
}
// SetPan places the player between the left speaker (-1) and the right
// (1); 0, the default, is the middle. A mono sound pans keeping its
// power; a stereo one keeps both channels, as Web Audio's StereoPannerNode
// does.
func (p *Player) SetPan(pan float64) *Player {
mu.Lock()
defer mu.Unlock()
p.v.pan = min(max(pan, -1), 1)
return p
}
// Pan returns the player's pan.
func (p *Player) Pan() float64 {
mu.Lock()
defer mu.Unlock()
return p.v.pan
}
// SetSpeed sets how fast the player plays, which changes its pitch with
// it, as a record's speed does: 1 (the default) as decoded, 2 twice as
// fast and an octave higher. Games vary it a little for effects that
// play often. SetPreservesPitch keeps the pitch instead.
func (p *Player) SetSpeed(s float64) *Player {
mu.Lock()
defer mu.Unlock()
if s > 0 && !math.IsInf(s, 0) {
p.v.speed = min(s, 16)
}
return p
}
// Speed returns the player's speed.
func (p *Player) Speed() float64 {
mu.Lock()
defer mu.Unlock()
return p.v.speed
}
// SetPreservesPitch sets whether the player keeps its pitch at a speed
// other than 1, as HTML media's preservesPitch does: true time-stretches
// it, as a podcast or a lecture plays at 1.5× in the voice it was
// recorded in, while false, the default, changes the pitch with the
// speed (SetSpeed). Time-stretching suits speech and other sound with a
// pitch at speeds from about 0.5 to 4, and costs a little more to mix;
// sharp attacks, as drums', come out a little smeared. A change applies
// after what the player stretched ahead, about 16 ms, without a gap.
func (p *Player) SetPreservesPitch(on bool) *Player {
mu.Lock()
defer mu.Unlock()
v := p.v
if v.closed {
return p
}
v.pitch = on
if on && v.st == nil {
v.stretch()
}
return p
}
// PreservesPitch reports whether the player keeps its pitch at its speed.
func (p *Player) PreservesPitch() bool {
mu.Lock()
defer mu.Unlock()
return p.v.pitch
}
// SetLoop sets whether the player starts again from the start when it
// ends, without a gap, or from its loop's start (SetLoopRange). A change
// is heard after what the player decoded ahead: a few milliseconds of a
// sound, up to a second of a stream.
func (p *Player) SetLoop(loop bool) *Player {
mu.Lock()
defer mu.Unlock()
if !p.v.closed {
p.v.loop = loop
p.v.src.setLoop(loop, p.v.loopStart, p.v.loopEnd)
}
return p
}
// SetLoopRange loops the player between start and end, without a gap,
// end 0 being the end of its audio: what is before start, as a tune's
// intro, plays once, and playing past end goes on from start. It sets the
// player looping; SetLoop(false) plays on past end, as far as the end.
func (p *Player) SetLoopRange(start, end time.Duration) *Player {
mu.Lock()
defer mu.Unlock()
v := p.v
if v.closed {
return p
}
s := max(int64(math.Round(start.Seconds()*v.rate)), 0)
e := max(int64(math.Round(end.Seconds()*v.rate)), 0)
if v.length >= 0 {
s, e = min(s, v.length), min(e, v.length)
}
if e != 0 && e <= s {
s, e = 0, 0 // nothing to loop: all of it
}
v.loopStart, v.loopEnd, v.loop = s, e, true
v.src.setLoop(true, s, e)
return p
}
// Loop reports whether the player loops.
func (p *Player) Loop() bool {
mu.Lock()
defer mu.Unlock()
return p.v.loop
}
// Close stops the player for good and frees what it decodes with. A
// sound's players need no closing.
func (p *Player) Close() {
mu.Lock()
defer mu.Unlock()
p.v.playing = false
p.v.close()
}
var (
volume = 1.0
latency = LatencyInteractive
outErr error
errMu sync.Mutex
)
// SetVolume sets the volume of everything played, a gain: 1 (the default)
// as decoded, 0 silent.
func SetVolume(v float64) {
mu.Lock()
defer mu.Unlock()
volume = max(v, 0)
}
// Volume returns the volume of everything played.
func Volume() float64 {
mu.Lock()
defer mu.Unlock()
return volume
}
// Latency is how far ahead of what is heard the output mixes, as Web
// Audio's latencyHint.
type Latency int
const (
// LatencyInteractive mixes about 40 ms ahead, so that sounds start,
// stop and change as soon as they are asked to, as games and
// interfaces want. It is the default.
LatencyInteractive Latency = iota
// LatencyPlayback mixes about 250 ms ahead, for apps that play music
// and other long audio: it plays on through the moments the system
// keeps an app waiting, as macOS does while its appearance changes,
// where the interactive latency runs dry and is heard to stop. Plays,
// pauses, seeks and volume changes are heard that much later.
LatencyPlayback
)
// ahead returns how much the output holds before it is heard.
func (l Latency) ahead() time.Duration {
if l == LatencyPlayback {
return 250 * time.Millisecond
}
return 40 * time.Millisecond
}
// SetLatency sets how far ahead the output mixes. An output already open
// opens again, which drops what it held.
func SetLatency(l Latency) {
mu.Lock()
defer mu.Unlock()
if l != LatencyPlayback {
l = LatencyInteractive
}
latency = l
}
// outputLatency returns the latency set.
func outputLatency() Latency {
mu.Lock()
defer mu.Unlock()
return latency
}
// Err returns why the last output to open is not the system's audio
// output, as on a machine with none, or nil.
func Err() error {
errMu.Lock()
defer errMu.Unlock()
return outErr
}
func setErr(err error) {
errMu.Lock()
defer errMu.Unlock()
outErr = err
}
+771
View File
@@ -0,0 +1,771 @@
package audio
import (
"bytes"
"encoding/binary"
"errors"
"io"
"math"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo/internal/wait"
)
// setup mixes by hand, with nothing playing.
func setup(t *testing.T) {
t.Helper()
mu.Lock()
testMode = true
for _, v := range voices {
v.active = false
}
voices = nil
volume = 1
held, unheard = 0, 0
mu.Unlock()
}
// hold makes the output hold n frames ahead of what is heard, as a device
// that just opened.
func hold(n int64) {
mu.Lock()
defer mu.Unlock()
held, unheard = n, 0
}
// render mixes n frames.
func render(n int) []float32 {
out := make([]float32, n*channels)
for i := 0; i < n; i += 256 {
mix(out[i*channels : min(n, i+256)*channels])
}
return out
}
func near(a, b float32) bool { return math.Abs(float64(a-b)) < 1e-4 }
func ramp(n int) []float32 {
s := make([]float32, n)
for i := range s {
s[i] = float32(i%100) / 200
}
return s
}
func TestSoundPlaysAsDecoded(t *testing.T) {
setup(t)
samples := ramp(1000)
p := NewSound(sampleRate, 1, samples).Play()
out := render(1200)
for i, s := range samples {
if !near(out[2*i], s) || !near(out[2*i+1], s) {
t.Fatalf("frame %d = %v %v, want %v", i, out[2*i], out[2*i+1], s)
}
}
for i := 1000; i < 1200; i++ {
if out[2*i] != 0 {
t.Fatalf("frame %d after the end = %v", i, out[2*i])
}
}
if p.Playing() {
t.Error("still playing after its end")
}
if got := p.Position(); got != p.Duration() {
t.Errorf("Position = %v at the end, want %v", got, p.Duration())
}
if len(voices) != 0 {
t.Errorf("%d voices left", len(voices))
}
}
func TestStereoKeepsChannels(t *testing.T) {
setup(t)
NewSound(sampleRate, 2, []float32{0.1, 0.2, 0.3, 0.4}).Play()
out := render(4)
if !near(out[0], 0.1) || !near(out[1], 0.2) || !near(out[2], 0.3) || !near(out[3], 0.4) {
t.Errorf("out = %v", out)
}
}
func TestPlayAgainAfterEnd(t *testing.T) {
setup(t)
p := NewSound(sampleRate, 1, ramp(100)).Play()
render(200)
p.Play()
if !p.Playing() {
t.Fatal("Play at the end did not start again")
}
out := render(100)
if !near(out[2*50], 0.25) {
t.Errorf("frame 50 = %v, want 0.25", out[2*50])
}
}
func TestOnEnd(t *testing.T) {
setup(t)
p := NewSound(sampleRate, 1, ramp(100)).NewPlayer()
ended := make(chan struct{}, 4)
off := p.OnEnd(func() { ended <- struct{}{} })
p.Play()
render(200)
wait.For(t, "the end", ended)
render(200) // ended once
p.Play()
render(50)
p.Pause()
render(200) // paused, not at the end
p.Seek(0)
off()
p.Play()
render(200)
if n := len(ended); n != 0 {
t.Errorf("%d more ends, want 0", n)
}
loop := NewSound(sampleRate, 1, ramp(100)).NewPlayer().SetLoop(true)
loop.OnEnd(func() { ended <- struct{}{} })
loop.Play()
render(350)
loop.Stop()
render(200)
if n := len(ended); n != 0 {
t.Errorf("a loop or a stopped player ended %d times", n)
}
}
func TestSoundsOverlap(t *testing.T) {
setup(t)
s := NewSound(sampleRate, 1, []float32{0.25, 0.25, 0.25, 0.25})
s.Play()
s.Play()
out := render(2)
if !near(out[0], 0.5) {
t.Errorf("two players mix to %v, want 0.5", out[0])
}
}
func TestClipping(t *testing.T) {
setup(t)
s := NewSound(sampleRate, 1, []float32{0.8, 0.8})
s.Play()
s.Play()
if out := render(1); out[0] != 1 {
t.Errorf("out = %v, want clipped to 1", out[0])
}
}
func TestLoop(t *testing.T) {
setup(t)
samples := ramp(100)
p := NewSound(sampleRate, 1, samples).NewPlayer().SetLoop(true)
p.Play()
out := render(350)
for i := range 350 {
if want := samples[i%100]; !near(out[2*i], want) {
t.Fatalf("frame %d = %v, want %v", i, out[2*i], want)
}
}
if !p.Playing() {
t.Error("a loop stopped")
}
if got, want := p.Position(), frames(50, sampleRate); got != want {
t.Errorf("Position = %v, want %v", got, want)
}
}
func TestPauseFadesOutAndResumes(t *testing.T) {
setup(t)
samples := make([]float32, 10000)
for i := range samples {
samples[i] = 0.5
}
p := NewSound(sampleRate, 1, samples).Play()
render(1000)
p.Pause()
if p.Playing() {
t.Error("Playing after Pause")
}
out := render(rampFrames + 10)
if !(out[0] > 0.45 && out[2*(rampFrames/2)] < 0.3 && out[2*(rampFrames/2)] > 0.2) {
t.Errorf("fade out = %v, %v", out[0], out[2*(rampFrames/2)])
}
if out[2*(rampFrames+5)] != 0 || len(voices) != 0 {
t.Errorf("after the fade: %v, %d voices", out[2*(rampFrames+5)], len(voices))
}
at := p.Position()
render(500)
if p.Position() != at {
t.Error("a paused player moved")
}
p.Play()
out = render(rampFrames + 10)
if !(out[0] < 0.05 && near(out[2*(rampFrames+5)], 0.5)) {
t.Errorf("fade in = %v … %v", out[0], out[2*(rampFrames+5)])
}
}
func TestVolumeRamps(t *testing.T) {
setup(t)
samples := make([]float32, 10000)
for i := range samples {
samples[i] = 0.5
}
p := NewSound(sampleRate, 1, samples).Play()
render(10)
p.SetVolume(0.5)
out := render(rampFrames * 2)
if !(out[0] > 0.45 && near(out[2*(rampFrames+10)], 0.25)) {
t.Errorf("volume ramp = %v … %v", out[0], out[2*(rampFrames+10)])
}
SetVolume(0)
out = render(rampFrames * 2)
if out[2*(rampFrames+10)] != 0 {
t.Errorf("master volume 0 = %v", out[2*(rampFrames+10)])
}
}
func TestPan(t *testing.T) {
setup(t)
mono := NewSound(sampleRate, 1, []float32{0.5, 0.5, 0.5})
mono.NewPlayer().SetPan(-1).Play()
out := render(2)
if !near(out[0], 0.5*math.Sqrt2) || !near(out[1], 0) {
t.Errorf("mono panned left = %v %v", out[0], out[1])
}
setup(t)
stereo := NewSound(sampleRate, 2, []float32{0.2, 0.4, 0.2, 0.4})
stereo.NewPlayer().SetPan(1).Play()
out = render(1)
if !near(out[0], 0) || !near(out[1], 0.6) {
t.Errorf("stereo panned right = %v %v", out[0], out[1])
}
}
func TestSpeed(t *testing.T) {
setup(t)
p := NewSound(sampleRate, 1, ramp(1000)).NewPlayer().SetSpeed(2)
p.Play()
out := render(100)
if !near(out[2*10], ramp(1000)[20]) {
t.Errorf("frame 10 at speed 2 = %v, want %v", out[2*10], ramp(1000)[20])
}
if got, want := p.Position(), frames(200, sampleRate); got != want {
t.Errorf("Position = %v, want %v", got, want)
}
}
func TestResamples(t *testing.T) {
setup(t)
// A 1 kHz sine at 24 kHz plays at 1 kHz.
const rate = 24000
samples := make([]float32, rate/10)
for i := range samples {
samples[i] = float32(math.Sin(2 * math.Pi * 1000 * float64(i) / rate))
}
p := NewSound(rate, 1, samples).Play()
out := render(sampleRate / 20)
for i := 100; i < sampleRate/20; i++ {
want := math.Sin(2 * math.Pi * 1000 * float64(i) / sampleRate)
if math.Abs(float64(out[2*i])-want) > 0.01 {
t.Fatalf("frame %d = %v, want %v", i, out[2*i], want)
}
}
if got, want := p.Position(), 50*time.Millisecond; got != want {
t.Errorf("Position = %v, want %v", got, want)
}
}
func TestSeek(t *testing.T) {
setup(t)
samples := ramp(48000)
p := NewSound(sampleRate, 1, samples).NewPlayer()
p.Seek(500 * time.Millisecond)
if got := p.Position(); got != 500*time.Millisecond {
t.Errorf("Position = %v after Seek", got)
}
p.Play()
out := render(rampFrames + 20)
if i := rampFrames + 10; !near(out[2*i], samples[24000+i]) {
t.Errorf("frame %d after seeking = %v, want %v", i, out[2*i], samples[24000+i])
}
p.Stop()
if p.Playing() || p.Position() != 0 {
t.Errorf("after Stop: playing %v at %v", p.Playing(), p.Position())
}
}
func TestClose(t *testing.T) {
setup(t)
p := NewSound(sampleRate, 1, ramp(1000)).Play()
p.Close()
p.Play()
if p.Playing() {
t.Error("a closed player plays")
}
render(10)
if len(voices) != 0 {
t.Errorf("%d voices after Close", len(voices))
}
}
// genDecoder generates frames i/1000 of a channel each, with a length.
type genDecoder struct {
ch int
pos int64
length int64
closed atomic.Bool
}
func (d *genDecoder) SampleRate() int { return sampleRate }
func (d *genDecoder) Channels() int { return d.ch }
func (d *genDecoder) Len() int64 { return d.length }
func (d *genDecoder) Close() error { d.closed.Store(true); return nil }
func (d *genDecoder) Read(buf []float32) (int, error) {
n := 0
for ; n+d.ch <= len(buf) && d.pos < d.length; n += d.ch {
for c := range d.ch {
buf[n+c] = float32(d.pos%1000)/1000 + float32(c)
}
d.pos++
}
if n == 0 {
return 0, io.EOF
}
return n, nil
}
func (d *genDecoder) SetPosition(f int64) error {
if f > d.length {
return errors.New("out of range")
}
d.pos = f
return nil
}
func waitDecoded(t *testing.T, p *Player) {
t.Helper()
s := p.v.src.(*stream)
for range 1000 {
s.mu.Lock()
n := s.n
s.mu.Unlock()
if n > 0 {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("the stream decoded nothing")
}
func TestStream(t *testing.T) {
setup(t)
d := &genDecoder{ch: 3, length: 5000}
p := NewPlayer(d)
if p.Duration() != frames(5000, sampleRate) {
t.Errorf("Duration = %v", p.Duration())
}
waitDecoded(t, p)
p.Play()
out := render(1000)
for i := range 1000 {
if l, r := out[2*i], out[2*i+1]; !near(l, float32(i)/1000) || !near(r, float32(i)/1000+1) && r != 1 {
t.Fatalf("frame %d = %v %v", i, l, r)
}
}
p.Close()
for range 1000 {
if d.closed.Load() {
return
}
time.Sleep(time.Millisecond)
}
t.Error("Close did not close the decoder")
}
func TestStreamLoopsWithoutGap(t *testing.T) {
setup(t)
d := &genDecoder{ch: 1, length: 300}
p := NewPlayer(d).SetLoop(true)
waitDecoded(t, p)
p.Play()
out := make([]float32, 0, 2000*channels)
for len(out) < 2000*channels {
chunk := make([]float32, 64*channels)
// The decoder keeps a second ahead: wait for it, as the device
// would not.
for {
s := p.v.src.(*stream)
s.mu.Lock()
n := s.n
s.mu.Unlock()
if n >= 64 {
break
}
time.Sleep(time.Millisecond)
}
mix(chunk)
out = append(out, chunk...)
}
for i := range 2000 {
if want := float32(i%300) / 1000; !near(out[2*i], want) {
t.Fatalf("frame %d = %v, want %v", i, out[2*i], want)
}
}
p.Close()
}
func TestStreamSeek(t *testing.T) {
setup(t)
d := &genDecoder{ch: 1, length: 48000}
p := NewPlayer(d)
p.Seek(frames(700, sampleRate))
waitDecoded(t, p)
p.Play()
out := render(rampFrames + 20)
if i := rampFrames + 10; !near(out[2*i], float32((700+i)%1000)/1000) {
t.Errorf("frame %d = %v, want %v", i, out[2*i], float32((700+i)%1000)/1000)
}
p.Close()
}
func TestOrphanedStreamPlaysToItsEnd(t *testing.T) {
setup(t)
d := &genDecoder{ch: 1, length: 500}
v := NewPlayer(d).v
for range 1000 {
s := v.src.(*stream)
s.mu.Lock()
n := s.n
s.mu.Unlock()
if n > 0 {
break
}
time.Sleep(time.Millisecond)
}
mu.Lock()
v.playing, v.active, v.snap = true, true, true
voices = append(voices, v)
v.orphan = true
mu.Unlock()
render(600)
if !v.closed {
t.Error("an orphaned stream was not closed at its end")
}
}
func wav(tag, bits, ch int, data []byte) []byte {
var b bytes.Buffer
w := func(v any) { binary.Write(&b, binary.LittleEndian, v) }
b.WriteString("RIFF")
w(uint32(36 + len(data) + 10))
b.WriteString("WAVE")
b.WriteString("LIST")
w(uint32(1)) // odd, padded
b.Write([]byte{0, 0})
b.WriteString("fmt ")
w(uint32(16))
w(uint16(tag))
w(uint16(ch))
w(uint32(22050))
w(uint32(22050 * ch * bits / 8))
w(uint16(ch * bits / 8))
w(uint16(bits))
b.WriteString("data")
w(uint32(len(data)))
b.Write(data)
return b.Bytes()
}
func TestWAV(t *testing.T) {
le := binary.LittleEndian
for _, tc := range []struct {
name string
tag, bits int
data []byte
}{
{"u8", 1, 8, []byte{128, 192, 64, 0}},
{"s16", 1, 16, le.AppendUint16(le.AppendUint16(le.AppendUint16(le.AppendUint16(nil, 0), 0x4000), 0xc000), 0x8000)},
{"s24", 1, 24, []byte{0, 0, 0, 0, 0, 0x40, 0, 0, 0xc0, 0, 0, 0x80}},
{"s32", 1, 32, le.AppendUint32(le.AppendUint32(le.AppendUint32(le.AppendUint32(nil, 0), 0x40000000), 0xc0000000), 0x80000000)},
{"f32", 3, 32, le.AppendUint32(le.AppendUint32(le.AppendUint32(le.AppendUint32(nil, 0), math.Float32bits(0.5)), math.Float32bits(-0.5)), math.Float32bits(-1))},
{"f64", 3, 64, le.AppendUint64(le.AppendUint64(le.AppendUint64(le.AppendUint64(nil, 0), math.Float64bits(0.5)), math.Float64bits(-0.5)), math.Float64bits(-1))},
} {
t.Run(tc.name, func(t *testing.T) {
s, err := DecodeSound(wav(tc.tag, tc.bits, 2, tc.data))
if err != nil {
t.Fatal(err)
}
want := []float32{0, 0.5, -0.5, -1}
if s.rate != 22050 || s.channels != 2 || len(s.samples) != 4 {
t.Fatalf("decoded %d Hz, %d channels, %d samples", s.rate, s.channels, len(s.samples))
}
for i := range want {
if s.samples[i] != want[i] {
t.Errorf("sample %d = %v, want %v", i, s.samples[i], want[i])
}
}
if s.Duration() != frames(2, 22050) {
t.Errorf("Duration = %v", s.Duration())
}
})
}
}
// A header can say any length: ReadSound reserves no more than a start
// for it, and keeps what the decoder had.
func TestSoundOfAWrongLength(t *testing.T) {
t.Run("a WAV cut short", func(t *testing.T) {
b := wav(1, 8, 1, []byte{128, 192, 64, 0})
binary.LittleEndian.PutUint32(b[len(b)-8:], 0xfffffffe) // the data chunk's size
s, err := DecodeSound(b)
if err != nil {
t.Fatal(err)
}
if len(s.samples) != 4 {
t.Errorf("decoded %d samples, want 4", len(s.samples))
}
if cap(s.samples) > reserveFrames {
t.Errorf("reserved %d samples for 4", cap(s.samples))
}
})
t.Run("a decoder of any length", func(t *testing.T) {
s, err := ReadSound(wrongLength{&genDecoder{ch: 2, length: 8}})
if err != nil {
t.Fatal(err)
}
if len(s.samples) != 16 {
t.Errorf("decoded %d samples, want 16", len(s.samples))
}
if cap(s.samples) > 2*reserveFrames {
t.Errorf("reserved %d samples for 16", cap(s.samples))
}
})
}
// wrongLength says its decoder is longer than any sound.
type wrongLength struct{ *genDecoder }
func (wrongLength) Len() int64 { return math.MaxInt64 }
func TestWAVSeek(t *testing.T) {
data := make([]byte, 0, 200)
for i := range 100 {
data = binary.LittleEndian.AppendUint16(data, uint16(i*100))
}
d, name, err := NewDecoder(bytes.NewReader(wav(1, 16, 1, data)))
if err != nil || name != "wav" {
t.Fatal(name, err)
}
if d.Len() != 100 {
t.Errorf("Len = %d", d.Len())
}
if err := d.SetPosition(40); err != nil {
t.Fatal(err)
}
buf := make([]float32, 4)
if n, err := d.Read(buf); n != 4 || err != nil || buf[0] != float32(4000)/(1<<15) {
t.Errorf("after SetPosition(40): %d %v %v", n, err, buf)
}
}
func TestUnknownFormat(t *testing.T) {
if _, err := DecodeSound([]byte("not audio at all")); err != ErrFormat {
t.Errorf("err = %v, want ErrFormat", err)
}
}
// The output plays on time where no device opens, and says why.
func TestNullOutput(t *testing.T) {
setup(t)
mu.Lock()
testMode = false
mu.Unlock()
defer func() {
mu.Lock()
testMode = true
mu.Unlock()
}()
failure := errors.New("no device here")
openOutput = func(time.Duration) (device, int, error) { return nil, 0, failure }
defer func() { openOutput = openDevice }()
p := NewSound(sampleRate, 1, make([]float32, sampleRate/10)).Play()
// How long it takes is TestNullDeviceKeepsTime's: a minute only
// guards against a hang.
for start := time.Now(); p.Playing(); time.Sleep(5 * time.Millisecond) {
if time.Since(start) > time.Minute {
t.Fatal("100 ms still playing after a minute")
}
}
if Err() != failure {
t.Errorf("Err = %v", Err())
}
}
// Setting the latency opens the output again, to hold as far ahead as it
// says.
func TestSetLatencyReopens(t *testing.T) {
setup(t)
opened := make(chan time.Duration, 8)
openOutput = func(ahead time.Duration) (device, int, error) {
opened <- ahead
return pacedDevice{}, nullFrames, nil
}
defer func() { openOutput = openDevice }()
mu.Lock()
testMode = false
mu.Unlock()
defer func() {
mu.Lock()
testMode = true
latency = LatencyInteractive
mu.Unlock()
}()
p := NewSound(sampleRate, 1, make([]float32, sampleRate)).NewPlayer().SetLoop(true)
p.Play()
defer p.Close()
if got := wait.For(t, "the output to open", opened); got != 40*time.Millisecond {
t.Errorf("opened %v ahead, want 40ms", got)
}
SetLatency(LatencyPlayback)
if got := wait.For(t, "the output to open again", opened); got != 250*time.Millisecond {
t.Errorf("opened again %v ahead, want 250ms", got)
}
}
// A pacedDevice takes what it is given a little at a time.
type pacedDevice struct{}
func (pacedDevice) write([]float32) error { time.Sleep(time.Millisecond); return nil }
func (pacedDevice) close() {}
// A null device takes as long as what it plays would, on a clock of its
// own here, does not hurry to catch up once behind, and fails after a
// while for the device to be tried again.
func TestNullDeviceKeepsTime(t *testing.T) {
start := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC)
clock := start
d := newNullDevice(true)
d.next, d.retry = start, start.Add(2*time.Second)
d.now = func() time.Time { return clock }
d.sleep = func(dt time.Duration) { clock = clock.Add(max(dt, 0)) }
chunk := make([]float32, nullFrames*channels) // 10 ms
for range 10 {
if err := d.write(chunk); err != nil {
t.Fatal(err)
}
}
if got := clock.Sub(start); got != 100*time.Millisecond {
t.Errorf("100 ms played in %v", got)
}
// Late by a second, as after the computer slept: the next chunk takes
// its 10 ms from now.
clock = clock.Add(time.Second)
late := clock
if err := d.write(chunk); err != nil {
t.Fatal(err)
}
if got := clock.Sub(late); got != 10*time.Millisecond {
t.Errorf("10 ms played late in %v", got)
}
clock = start.Add(2*time.Second + time.Millisecond)
if err := d.write(chunk); err != errRetry {
t.Errorf("after 2 s: %v, want errRetry", err)
}
}
// A stream's decoder sleeps while the ring is mostly full, rather than
// waking on every mix to find nothing to do.
func TestStreamWakesItsDecoderRarely(t *testing.T) {
setup(t)
const total = 10 * sampleRate // 10 s
d := &heldDecoder{
genDecoder: genDecoder{ch: 2, length: total},
held: make(chan struct{}),
release: make(chan struct{}),
}
p := NewPlayer(d)
defer p.Close()
s := p.v.src.(*stream)
// Count from its first read, while it can't be in the cond's Wait.
wait.For(t, "the first read", d.held)
s.mu.Lock()
wakes := &wakeCounter{Locker: s.cond.L}
s.cond.L = wakes
s.mu.Unlock()
close(d.release)
decoded := func(n int) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.n >= n*s.keep || s.atEOF
}
wait.Until(t, "the ring to fill", func() bool {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.ring)-s.n < decodeFrames*s.keep
})
p.Play()
const chunk = 512 // as macOS mixes
out := make([]float32, chunk*channels)
for range total / chunk {
// As fast as the decoder goes, never faster.
wait.Until(t, "the stream to decode", func() bool { return decoded(chunk) })
mix(out)
}
s.mu.Lock()
n := wakes.n
s.mu.Unlock()
// Every wake but the last follows a quarter of the ring read, less
// the chunk the decoder may have left free.
if limit := total/(len(s.ring)/4/s.keep-decodeFrames) + 1; n > limit {
t.Errorf("the decoder woke %d times in 10 s, want at most %d", n, limit)
}
}
// A heldDecoder holds its first Read until released.
type heldDecoder struct {
genDecoder
held, release chan struct{}
once sync.Once
}
func (d *heldDecoder) Read(buf []float32) (int, error) {
d.once.Do(func() { close(d.held); <-d.release })
return d.genDecoder.Read(buf)
}
// A wakeCounter counts the wakes of a cond whose L it is, as Wait locks
// L again on each.
type wakeCounter struct {
sync.Locker
n int
}
func (l *wakeCounter) Lock() { l.Locker.Lock(); l.n++ }
// Mixing allocates nothing once playing, sounds and streams alike.
func TestMixDoesNotAllocate(t *testing.T) {
setup(t)
p := NewPlayer(&genDecoder{ch: 2, length: 1 << 40})
defer p.Close()
s := p.v.src.(*stream)
wait.Until(t, "the stream to decode", func() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.n > 0
})
p.Play()
// 1.1 s, which ends within the 2.1 s mixed: ending allocates nothing
// either.
snd := NewSound(22050, 1, ramp(sampleRate/2)).Play()
out := make([]float32, 512*channels)
if n := testing.AllocsPerRun(200, func() { mix(out) }); n != 0 {
t.Errorf("mix allocated %v times a call", n)
}
if snd.Playing() {
t.Error("the sound still plays")
}
}
+30
View File
@@ -0,0 +1,30 @@
//go:build darwin || (linux && (amd64 || arm64))
package audio
import "github.com/ebitengine/purego"
// A cCaller calls C without allocating, for what a device calls on every
// write: functions RegisterLibFunc made allocate, and SyscallN's own
// arguments escape. Pointers among args must be to C memory, or to the
// heap and kept alive by the caller.
type cCaller struct{ args [6]uintptr }
// cFunc looks up C function name in lib, for a cCaller. As
// RegisterLibFunc does, it panics when lib lacks it.
func cFunc(lib uintptr, name string) uintptr {
fn, err := purego.Dlsym(lib, name)
if err != nil {
panic(err)
}
return fn
}
func (c *cCaller) call(fn uintptr, args ...uintptr) uintptr {
if len(args) > len(c.args) {
panic("audio: too many arguments to cCaller.call")
}
n := copy(c.args[:], args)
r, _, _ := purego.SyscallN(fn, c.args[:n]...)
return r
}
+33
View File
@@ -0,0 +1,33 @@
//go:build darwin || (linux && (amd64 || arm64))
package audio
import (
"runtime"
"testing"
"github.com/ebitengine/purego"
)
func TestCCallDoesNotAllocate(t *testing.T) {
name := "libc.so.6"
if runtime.GOOS == "darwin" {
name = "/usr/lib/libSystem.B.dylib"
}
lib, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
t.Skip(err)
}
labs, err := purego.Dlsym(lib, "labs")
if err != nil {
t.Fatal(err)
}
var c cCaller
minus5 := -5
if got := int(c.call(labs, uintptr(minus5))); got != 5 {
t.Fatalf("labs(-5) = %d", got)
}
if n := testing.AllocsPerRun(100, func() { c.call(labs, 7) }); n != 0 {
t.Errorf("a call allocated %v times", n)
}
}
+300
View File
@@ -0,0 +1,300 @@
// Package flac decodes FLAC for package audio, with
// github.com/mewkiz/flac: .flac files, and FLAC in MP4 through package
// audio/mp4, as lossless DASH streams carry it. Import it for its side
// effect:
//
// import _ "github.com/egoist/mygo/audio/flac"
//
// FLAC's frames stand alone, so a seek lands on the very frame of sound
// asked for, without a seek table.
package flac
import (
"bufio"
"bytes"
"errors"
"io"
"math"
"github.com/egoist/mygo/audio"
"github.com/egoist/mygo/audio/mp4"
"github.com/mewkiz/flac"
"github.com/mewkiz/flac/frame"
"github.com/mewkiz/flac/meta"
)
func init() {
open := func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) }
// After an ID3 tag too, which package audio looks past.
audio.RegisterFormat("flac", "fLaC", open)
mp4.RegisterCodec("fLaC", func(config []byte) (mp4.Codec, error) { return NewCodec(config) })
}
// decoder decodes a FLAC file. A seek finds the frame of FLAC holding the
// frame of sound asked for by its header, near where the bytes say it is,
// and decodes from there.
type decoder struct {
r io.ReadSeeker
info *meta.StreamInfo
start int64 // the first frame's byte, after the metadata
size int64
br *bufio.Reader
skip int64 // frames to drop, after a seek
pend []float32 // decoded, and not yet read: stereo
}
// NewDecoder returns a decoder of the FLAC file r holds, after an ID3 tag
// if one is first. It decodes to stereo: a mono file in both, and the
// front left and right of more channels.
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
size, err := r.Seek(0, io.SeekEnd)
if err != nil {
return nil, err
}
from, err := skipID3(r)
if err != nil {
return nil, err
}
start, err := dataStart(r, from)
if err != nil {
return nil, err
}
head := make([]byte, start-from)
if _, err := r.Seek(from, io.SeekStart); err != nil {
return nil, err
}
if _, err := io.ReadFull(r, head); err != nil {
return nil, err
}
st, err := flac.New(bytes.NewReader(head))
if err != nil {
return nil, err
}
if st.Info == nil || st.Info.NChannels == 0 || st.Info.SampleRate == 0 {
return nil, errors.New("flac: no stream info")
}
d := &decoder{r: r, info: st.Info, start: start, size: size}
if err := d.at(start); err != nil {
return nil, err
}
return d, nil
}
// skipID3 returns where r's FLAC starts: after an ID3 tag, if r starts
// with one.
func skipID3(r io.ReadSeeker) (int64, error) {
var b [10]byte
if _, err := r.Seek(0, io.SeekStart); err != nil {
return 0, err
}
if _, err := io.ReadFull(r, b[:]); err != nil || string(b[:3]) != "ID3" {
return 0, nil
}
return 10 + int64(b[6]&0x7f)<<21 | int64(b[7]&0x7f)<<14 | int64(b[8]&0x7f)<<7 | int64(b[9]&0x7f), nil
}
// dataStart returns where the first frame starts, after the "fLaC" at off
// and the metadata blocks.
func dataStart(r io.ReadSeeker, off int64) (int64, error) {
var h [4]byte
if _, err := r.Seek(off, io.SeekStart); err != nil {
return 0, err
}
if _, err := io.ReadFull(r, h[:]); err != nil || string(h[:]) != "fLaC" {
return 0, errors.New("flac: not a FLAC file")
}
off += 4
for {
if _, err := r.Seek(off, io.SeekStart); err != nil {
return 0, err
}
if _, err := io.ReadFull(r, h[:]); err != nil {
return 0, io.ErrUnexpectedEOF
}
off += 4 + (int64(h[1])<<16 | int64(h[2])<<8 | int64(h[3]))
if h[0]&0x80 != 0 { // the last
return off, nil
}
}
}
// at reads on from off.
func (d *decoder) at(off int64) error {
if _, err := d.r.Seek(off, io.SeekStart); err != nil {
return err
}
if d.br == nil {
d.br = bufio.NewReaderSize(d.r, 64<<10)
} else {
d.br.Reset(d.r)
}
return nil
}
func (d *decoder) SampleRate() int { return int(d.info.SampleRate) }
func (d *decoder) Channels() int { return 2 }
func (d *decoder) Len() int64 {
if d.info.NSamples == 0 {
return -1
}
return int64(d.info.NSamples)
}
// parse parses the frame r is at: its header, then its samples, taking
// what the header leaves to the stream info from there. The decoder may
// panic on bytes that only look like a frame.
func parse(r io.Reader, info *meta.StreamInfo) (f *frame.Frame, err error) {
defer func() {
if recover() != nil {
f, err = nil, errors.New("flac: bad frame")
}
}()
f, err = frame.New(r)
if err != nil {
return nil, err
}
if f.BitsPerSample == 0 {
f.BitsPerSample = info.BitsPerSample
}
if f.SampleRate == 0 {
f.SampleRate = info.SampleRate
}
if err := f.Parse(); err != nil {
return nil, err
}
return f, nil
}
func (d *decoder) Read(dst []float32) (int, error) {
for len(d.pend) == 0 {
f, err := parse(d.br, d.info)
if err != nil {
if err == io.ErrUnexpectedEOF {
err = io.EOF
}
return 0, err
}
drop := min(d.skip, int64(f.BlockSize))
d.skip -= drop
d.pend = stereo(d.pend[:0], f, int(drop))
}
n := copy(dst[:len(dst)/2*2], d.pend)
d.pend = d.pend[n:]
return n, nil
}
// stereo appends a frame's samples from the one at from to dst, as stereo.
func stereo(dst []float32, f *frame.Frame, from int) []float32 {
left, right := f.Subframes[0].Samples, f.Subframes[0].Samples
if len(f.Subframes) > 1 {
right = f.Subframes[1].Samples
}
scale := float32(1 / math.Exp2(float64(f.BitsPerSample-1)))
for i := from; i < int(f.BlockSize); i++ {
dst = append(dst, float32(left[i])*scale, float32(right[i])*scale)
}
return dst
}
// SetPosition goes to target: to the frame of FLAC holding it, then drops
// what comes before it there. It finds that frame by the secant method,
// guessing where in the bytes it is from the frames found on either side,
// until one is found less than a second before it.
func (d *decoder) SetPosition(target int64) error {
target = max(target, 0)
total := int64(d.info.NSamples)
if total > 0 {
target = min(target, total)
}
loOff, lo := d.start, int64(0)
hiOff, hi := d.size, total
for tries := 0; tries < 8 && target-lo > int64(d.info.SampleRate) && hi > lo; tries++ {
guess := loOff + int64(float64(hiOff-loOff)*float64(target-lo)/float64(hi-lo))
off, at, ok := d.frameAfter(max(guess, loOff+1), hiOff)
if !ok {
break
}
if at > target {
hiOff, hi = off, at
} else {
loOff, lo = off, at
}
}
d.skip, d.pend = target-lo, d.pend[:0]
return d.at(loOff)
}
// frameAfter returns where the first whole frame at or after off and before
// end starts, and the frame of sound it starts with. Bytes that only look
// like a frame's header within the audio fail its checksums.
func (d *decoder) frameAfter(off, end int64) (int64, int64, bool) {
const window = 16 << 10
buf := make([]byte, window)
for off+2 < end {
if _, err := d.r.Seek(off, io.SeekStart); err != nil {
return 0, 0, false
}
n, _ := io.ReadFull(d.r, buf[:min(window, end-off)])
if n < 2 {
return 0, 0, false
}
for i := 0; i+1 < n; i++ {
if buf[i] != 0xff || buf[i+1]&0xfe != 0xf8 {
continue
}
if at, ok := d.frameAt(off + int64(i)); ok {
return off + int64(i), at, true
}
}
off += int64(n - 1)
}
return 0, 0, false
}
// frameAt returns the frame of sound the frame of FLAC at off starts with,
// if a whole one is there.
func (d *decoder) frameAt(off int64) (int64, bool) {
if _, err := d.r.Seek(off, io.SeekStart); err != nil {
return 0, false
}
f, err := parse(bufio.NewReaderSize(d.r, 16<<10), d.info)
if err != nil || f.Channels.Count() != int(d.info.NChannels) {
return 0, false
}
return int64(f.SampleNumber()), true
}
// codec decodes FLAC frames, each an MP4's packet.
type codec struct {
info *meta.StreamInfo
r bytes.Reader
}
// NewCodec returns a decoder of the FLAC frames of an MP4's track whose
// configuration, its dfLa box's, is blocks: the metadata blocks, as a FLAC
// file has them after "fLaC".
func NewCodec(blocks []byte) (mp4.Codec, error) {
st, err := flac.New(bytes.NewReader(append([]byte("fLaC"), blocks...)))
if err != nil {
return nil, err
}
if st.Info == nil || st.Info.SampleRate == 0 || st.Info.NChannels == 0 {
return nil, errors.New("flac: no stream info")
}
return &codec{info: st.Info}, nil
}
func (c *codec) SampleRate() int { return int(c.info.SampleRate) }
func (c *codec) Reset() {}
func (c *codec) Preroll() int { return 0 }
func (c *codec) PacketFrames() int { return 0 }
func (c *codec) Decode(dst []float32, packet []byte) ([]float32, error) {
c.r.Reset(packet)
f, err := parse(&c.r, c.info)
if err != nil {
return dst, err
}
return stereo(dst, f, 0), nil
}
+62
View File
@@ -0,0 +1,62 @@
package flac_test
import (
"bytes"
"testing"
"github.com/egoist/mygo/audio/flac"
"github.com/egoist/mygo/audio/internal/audiotest"
)
// tone.flac is 2 s of two chirps at 44.1 kHz, one in each channel, in
// 16 bits: it decodes to exactly that, and a seek lands on the very frame
// asked for, near or far, as far as its last.
func TestDecode(t *testing.T) {
b := audiotest.Read(t, "testdata/tone.flac")
d := audiotest.Open(t, b, "flac")
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 88200 {
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
}
got := audiotest.ReadAll(t, d)
if len(got) != 88200*2 {
t.Fatalf("decoded %d samples", len(got))
}
if got[2000] == got[2001] {
t.Error("both channels alike")
}
audiotest.SeekLands(t, d, got, 0, 0, 1, 4095, 4096, 50000, 77777, 88199, 1000)
}
// A FLAC file may start with an ID3 tag: it decodes as without one.
func TestID3(t *testing.T) {
b := audiotest.Read(t, "testdata/tone.flac")
want := audiotest.ReadAll(t, audiotest.Open(t, b, "flac"))
tag := append([]byte("ID3\x04\x00\x00\x00\x00\x01\x00"), make([]byte, 128)...)
d := audiotest.Open(t, append(tag, b...), "flac")
got := audiotest.ReadAll(t, d)
if len(got) != len(want) || audiotest.MaxDiff(got, want) != 0 {
t.Fatalf("decoded %d samples, off by up to %g", len(got), audiotest.MaxDiff(got, want))
}
audiotest.SeekLands(t, d, want, 0, 70000)
}
// FLAC in a fragmented MP4, as a lossless DASH stream carries it, decodes
// to what the .flac does.
func TestFragmentedMP4(t *testing.T) {
want := audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "testdata/tone.flac"), "flac"))
d := audiotest.Open(t, audiotest.Read(t, "testdata/fragmented.m4a"), "mp4")
if d.SampleRate() != 44100 || d.Len() != 88200 {
t.Fatalf("%d Hz, %d frames", d.SampleRate(), d.Len())
}
got := audiotest.ReadAll(t, d)
if len(got) != len(want) || audiotest.MaxDiff(got, want) != 0 {
t.Fatalf("decoded %d samples, off by up to %g", len(got), audiotest.MaxDiff(got, want))
}
audiotest.SeekLands(t, d, want, 0, 0, 1, 4096, 30000, 88199)
}
func TestNotFLAC(t *testing.T) {
if _, err := flac.NewDecoder(bytes.NewReader([]byte("OggS and more"))); err == nil {
t.Fatal("decoded what isn't FLAC")
}
}
Binary file not shown.
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
// Package audiotest has what the tests of package audio's formats share.
package audiotest
import (
"bytes"
"math"
"os"
"testing"
"github.com/egoist/mygo/audio"
)
// Read reads a file of testdata.
func Read(t testing.TB, name string) []byte {
t.Helper()
b, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
return b
}
// Open opens b as package audio does, and checks the format's name.
func Open(t testing.TB, b []byte, name string) audio.Decoder {
t.Helper()
d, got, err := audio.NewDecoder(bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
if got != name {
t.Fatalf("format %q, not %q", got, name)
}
return d
}
// ReadAll decodes what d has left.
func ReadAll(t testing.TB, d audio.Decoder) []float32 {
t.Helper()
var out []float32
buf := make([]float32, 4096)
for {
n, err := d.Read(buf)
out = append(out, buf[:n]...)
if err != nil || n == 0 {
return out
}
}
}
// SeekLands checks that a seek to each frame reads what decoding straight
// through, ref, has there, to within tol, for a second or to the end.
func SeekLands(t testing.TB, d audio.Decoder, ref []float32, tol float64, frames ...int64) {
t.Helper()
ch := int64(d.Channels())
for _, frame := range frames {
if err := d.SetPosition(frame); err != nil {
t.Fatal(err)
}
want := ref[frame*ch:]
want = want[:min(len(want), d.SampleRate()*int(ch))]
got := make([]float32, 0, len(want))
buf := make([]float32, 4096)
for len(got) < len(want) {
n, err := d.Read(buf)
got = append(got, buf[:n]...)
if err != nil || n == 0 {
break
}
}
if len(got) < len(want) {
t.Errorf("seek to %d: read %d samples of %d", frame, len(got), len(want))
continue
}
if diff := MaxDiff(got, want); diff > tol {
t.Errorf("seek to %d: off by up to %.4f", frame, diff)
}
}
}
// MaxDiff returns how far apart a and b are at most, over the length of
// the shorter.
func MaxDiff(a, b []float32) float64 {
d := 0.0
for i := range min(len(a), len(b)) {
d = math.Max(d, math.Abs(float64(a[i]-b[i])))
}
return d
}
// SNR is how far below ref the difference between got and ref is, in dB,
// over the length of the shorter.
func SNR(got, ref []float32) float64 {
var sig, noise float64
for i := range min(len(got), len(ref)) {
sig += float64(ref[i]) * float64(ref[i])
d := float64(got[i] - ref[i])
noise += d * d
}
return 10 * math.Log10(sig/noise)
}
+94
View File
@@ -0,0 +1,94 @@
package audio
import (
"testing"
"time"
)
// A tune's intro plays once, then its loop again and again, without a gap.
func TestLoopRange(t *testing.T) {
setup(t)
samples := ramp(100) // frame i is i/200
p := NewSound(sampleRate, 1, samples).NewPlayer().
SetLoopRange(frames(30, sampleRate), frames(60, sampleRate))
p.Play()
out := render(200)
for i := range 200 {
want := i
if i >= 60 {
want = 30 + (i-60)%30
}
if !near(out[2*i], samples[want]) {
t.Fatalf("frame %d = %v, want frame %d's %v", i, out[2*i], want, samples[want])
}
}
// 200 frames in: 60 + 140 = 4 loops of 30 and 20 more.
if got, want := p.Position(), frames(50, sampleRate); got != want {
t.Errorf("Position = %v, want %v", got, want)
}
// Looping no more, it plays on past the loop's end, to the end (after
// what it read ahead, a few milliseconds).
p.SetLoop(false)
out = render(1000)
last := -1
for i := range 1000 {
if out[2*i] != 0 {
last = i
}
}
if last < 0 || !near(out[2*last], samples[99]) || p.Playing() {
t.Errorf("after SetLoop(false): last frame %d = %v, playing %v", last, out[2*max(last, 0)], p.Playing())
}
if !near(out[2*(last-39)], samples[60]) {
t.Errorf("frames 60 to 99 do not end it: %v", out[2*(last-39)])
}
}
func TestStreamLoopRange(t *testing.T) {
setup(t)
d := &genDecoder{ch: 1, length: 5000} // frame i is (i%1000)/1000
p := NewPlayer(d).SetLoopRange(frames(1000, sampleRate), frames(3000, sampleRate))
waitDecoded(t, p)
p.Play()
out := make([]float32, 0, 9000*channels)
for len(out) < 9000*channels {
chunk := make([]float32, 64*channels)
s := p.v.src.(*stream)
for {
s.mu.Lock()
n := s.n
s.mu.Unlock()
if n >= 64 {
break
}
time.Sleep(time.Millisecond)
}
mix(chunk)
out = append(out, chunk...)
}
for i := range 9000 {
f := i
if i >= 3000 {
f = 1000 + (i-3000)%2000
}
if want := float32(f%1000) / 1000; !near(out[2*i], want) {
t.Fatalf("frame %d = %v, want frame %d's %v", i, out[2*i], f, want)
}
}
p.Close()
}
func TestLoopRangeOutOfRange(t *testing.T) {
setup(t)
p := NewSound(sampleRate, 1, ramp(100)).NewPlayer()
// An end before the start loops it all.
p.SetLoopRange(frames(60, sampleRate), frames(30, sampleRate))
if p.v.loopStart != 0 || p.v.loopEnd != 0 || !p.Loop() {
t.Errorf("loop %d to %d, looping %v", p.v.loopStart, p.v.loopEnd, p.Loop())
}
// Past the end, clamped to it.
p.SetLoopRange(frames(10, sampleRate), time.Hour)
if p.v.loopStart != 10 || p.v.loopEnd != 100 {
t.Errorf("loop %d to %d", p.v.loopStart, p.v.loopEnd)
}
}
+445
View File
@@ -0,0 +1,445 @@
package audio
import (
"math"
"slices"
)
// voices are the voices playing, or fading out, under mu.
var voices []*voice
// The output's clock, under mu: the frames mixed so far, how many of the
// latest the device holds, not heard yet, and how many it holds at most.
var (
mixed int64
unheard int64
held int64
)
// setHeld tells the mixer that a device opened which holds n frames ahead
// of what is heard, and none of what was mixed before.
func setHeld(n int64) {
mu.Lock()
defer mu.Unlock()
if !testMode {
held, unheard = n, 0
}
}
// heard returns the output's frame heard now: the frames mixed before it
// are.
func heard() int64 { return mixed - unheard }
// rampFrames is how long volume changes, fades in and fades out take: 5 ms.
const rampFrames = sampleRate / 200
// A source gives a voice its frames. Its methods run under mu and never
// block.
type source interface {
// read reads frames into dst, interleaved, and returns how many it
// read: fewer than fit only at the end, where ended is true, or while
// a stream decodes, where it is false. It goes on from the start when
// looping.
read(dst []float32) (n int, ended bool)
seek(frame int64)
// setLoop sets whether the source loops, from frame start to end
// (0 for its end).
setLoop(loop bool, start, end int64)
close()
}
// A voice is a player's state: its source, where it is, and how it
// resamples to the output.
type voice struct {
src source
rate float64
mono bool
length int64 // frames, or -1
playing bool // as the API sees it
active bool // in voices, which it stays in while fading out
snap bool // starts at its start: no fade in
fadeIn bool // resumes in the middle: fades in from silence
closed bool
orphan bool // its Player is gone: close at the end
atEnd bool // played to its end, for mix to tell the OnEnd listeners
onEnd []endListener
nextEnd uint64
volume, pan, speed float64
pitch bool // preserves pitch at its speed: stretched by st
loop bool
loopStart, loopEnd int64 // frames, loopEnd 0 for the end
// The source frames around the output, stereo: frame f at f mod
// ringFrames, and again ringFrames after, so that any ringFrames in a
// row are in a row. The output is phase past frame idx, and head is
// the frame that comes in next, as far ahead as the interpolation
// reaches.
ring [][2]float32
idx int64
phase float64
head int64
end int64 // the frame after the last, once the source ended, or -1
// The sinc's weights while the voice downsamples.
bank sincBank
in []float32 // frames read from the source and not yet used
inPos int
inLen int
// Time-stretches the source once its player preserved pitch, which
// counts where hist is in the source: nil for every other voice.
st *stretcher
// The gains applied, a 2×2 matrix from the source's channels to the
// output's (ll, rl, lr, rr), ramping to target.
gain, target, step [4]float32
rampLeft int
// Where the voice was in its source as the output mixed its frames,
// oldest first, for Position to say where it is heard.
marks []mark
}
// A mark is the voice at output frame out: at frame pos of its source,
// counted on past its loop's end. Between two marks the voice moved
// evenly, or stood still where they are at the same pos.
type mark struct {
out int64
pos float64
}
// reset starts the voice over at frame f of its source, which the caller
// has moved there.
func (v *voice) reset(f int64) {
// Silence before f.
clear(v.ring)
v.idx, v.phase, v.head = f, 0, f
v.end = -1
v.inPos, v.inLen = 0, 0
if v.st != nil {
v.st.reset(f, v.pitch)
}
// What it mixed before is not where it is any more, even while heard.
v.marks = v.marks[:0]
}
// ended reports whether the voice played to the end of its source.
func (v *voice) ended() bool { return v.end >= 0 && v.idx >= v.end }
// at returns the source frame the voice mixes next, counted on past its
// loop's end.
func (v *voice) at() float64 {
if st := v.st; st != nil {
a := st.tags[v.idx&(ringFrames-1)]
return a + v.phase*(st.tags[(v.idx+1)&(ringFrames-1)]-a)
}
return float64(v.idx) + v.phase
}
// stretch gives the voice a stretcher, which goes on from the frames it
// holds, as its player starts to preserve pitch.
func (v *voice) stretch() {
ch := 2
if v.mono {
ch = 1
}
st := newStretcher(int(v.rate), ch)
// The frame coming in next is at head, and those in the ring at
// themselves.
st.reset(v.head, true)
for f := v.idx; f < v.head; f++ {
st.tags[f&(ringFrames-1)] = float64(f)
}
st.n = copy(st.buf, v.in[v.inPos:v.inLen]) / ch
st.rd += int64(st.n)
v.inPos = v.inLen
v.st = st
}
// mark notes that the output mixes frame out with the voice where it is,
// and forgets the marks before the frame heard.
func (v *voice) mark(out, heard int64) {
m := mark{out, v.at()}
if n := len(v.marks); n > 0 && v.marks[n-1] == m {
return
}
k := 0
for k+1 < len(v.marks) && v.marks[k+1].out <= heard {
k++
}
v.marks = append(v.marks[:copy(v.marks, v.marks[k:])], m)
}
// heardAt returns the source frame the voice was at when the output mixed
// what is heard now, counted on past its loop's end. Until the output plays
// what it mixed since a seek, that is where it seeked to.
func (v *voice) heardAt() float64 {
h := heard()
k := slices.IndexFunc(v.marks, func(m mark) bool { return m.out > h })
switch k {
case -1:
return v.at()
case 0:
return v.marks[0].pos
}
a, b := v.marks[k-1], v.marks[k]
return a.pos + (b.pos-a.pos)*float64(h-a.out)/float64(b.out-a.out)
}
// position returns source frame p, counted on past the loop's end, as a
// frame of the source.
func (v *voice) position(p float64) float64 {
p = max(p, 0)
if v.length == 0 {
return 0
}
if v.loop {
end := float64(v.loopEnd)
if end <= 0 {
end = float64(v.length)
}
if start := float64(v.loopStart); end > start && p >= end {
p = start + math.Mod(p-start, end-start)
}
return p
}
if v.length > 0 {
p = min(p, float64(v.length))
}
return p
}
func (v *voice) close() {
if v.closed {
return
}
v.closed = true
v.playing = false
v.src.close()
}
// next takes in the source's next frame, at head, and reports false while
// a stream has none decoded yet.
func (v *voice) next() bool {
ch := 2
if v.mono {
ch = 1
}
if v.ring == nil {
v.ring = make([][2]float32, 2*ringFrames)
}
if v.inPos >= v.inLen {
if v.end >= 0 {
// Past the end, silence.
if v.st != nil {
v.st.push(v.head, v.st.next)
}
v.push(0, 0)
return true
}
var n int
var ended bool
if v.st != nil {
n, ended = v.readStretched()
} else {
if v.in == nil {
v.in = make([]float32, 256*ch)
}
n, ended = v.src.read(v.in)
}
v.inPos, v.inLen = 0, n*ch
if n == 0 {
if !ended {
return false
}
v.end = v.head
if v.st != nil {
v.st.push(v.head, v.st.next)
}
v.push(0, 0)
return true
}
}
l := v.in[v.inPos]
r := l
if !v.mono {
r = v.in[v.inPos+1]
}
if st := v.st; st != nil {
st.push(v.head, st.tag0+float64(v.inPos/ch)*st.tagStep)
}
v.inPos += ch
v.push(l, r)
return true
}
// push puts frame head into the ring.
func (v *voice) push(l, r float32) {
k := v.head & (ringFrames - 1)
v.ring[k] = [2]float32{l, r}
v.ring[k+ringFrames] = [2]float32{l, r}
v.head++
}
// gains returns the matrix of the voice's volume and pan, and the master
// volume.
func (v *voice) gains(master float64) [4]float32 {
g := v.volume * master
if !v.playing {
g = 0
}
if v.mono {
// Equal power, the middle as decoded.
x := (v.pan + 1) / 2 * math.Pi / 2
return [4]float32{float32(g * math.Sqrt2 * math.Cos(x)), 0, 0, float32(g * math.Sqrt2 * math.Sin(x))}
}
// Web Audio's StereoPannerNode for stereo input.
if v.pan <= 0 {
x := (v.pan + 1) * math.Pi / 2
return [4]float32{float32(g), 0, float32(g * math.Cos(x)), float32(g * math.Sin(x))}
}
x := v.pan * math.Pi / 2
return [4]float32{float32(g * math.Cos(x)), float32(g * math.Sin(x)), 0, float32(g)}
}
// retarget ramps the gains to t from now.
func (v *voice) retarget(t [4]float32) {
switch {
case v.snap:
v.snap, v.fadeIn = false, false
v.gain, v.target, v.rampLeft = t, t, 0
return
case v.fadeIn:
v.fadeIn = false
v.gain = [4]float32{}
case t == v.target:
return
}
v.target = t
for i := range t {
v.step[i] = (t[i] - v.gain[i]) / rampFrames
}
v.rampLeft = rampFrames
}
// mix adds the voice's next frames to out, which the output mixes from
// its frame at, and reports whether it is still active: false once at its
// end, or faded out.
func (v *voice) mix(out []float32, master float64, at, heard int64) bool {
v.mark(at, heard)
n, ok := v.play(out, master)
v.mark(at+int64(n), heard)
return ok
}
// play adds the voice's next frames to out and returns how many it moved
// through its source for, and whether it is still active.
func (v *voice) play(out []float32, master float64) (int, bool) {
v.retarget(v.gains(master))
step := v.rate / sampleRate * v.speed
if v.st != nil && v.st.on {
// Stretched to the speed already.
step = v.rate / sampleRate
}
// The spline reaches 2 frames ahead, the sinc further the faster.
reach := 2
if step > 1 {
v.bank.set(step)
reach = v.bank.reach
}
for i := 0; i < len(out); i += 2 {
n := int64(v.phase)
for v.head <= v.idx+n+int64(reach) {
if !v.next() {
// The stream is late: silence until it catches up.
return i / 2, true
}
}
v.idx += n
v.phase -= float64(n)
if v.ended() {
v.atEnd = v.atEnd || v.playing
v.playing = false
return i / 2, false
}
if v.rampLeft > 0 {
for k := range v.gain {
v.gain[k] += v.step[k]
}
v.rampLeft--
if v.rampLeft == 0 {
v.gain = v.target
}
} else if !v.playing {
// Faded out.
return i / 2, false
}
var l, r float32
if step > 1 {
l, r = v.sinc()
} else {
l, r = v.sample()
}
out[i] += l*v.gain[0] + r*v.gain[2]
out[i+1] += l*v.gain[1] + r*v.gain[3]
v.phase += step
}
return len(out) / 2, true
}
// sample interpolates between frames idx and idx+1 with a Catmull-Rom
// spline through the frames either side.
func (v *voice) sample() (l, r float32) {
t := float32(v.phase)
o := (v.idx - 1) & (ringFrames - 1)
h := v.ring[o : o+4]
cr := func(p0, p1, p2, p3 float32) float32 {
return p1 + 0.5*t*(p2-p0+t*(2*p0-5*p1+4*p2-p3+t*(3*(p1-p2)+p3-p0)))
}
return cr(h[0][0], h[1][0], h[2][0], h[3][0]), cr(h[0][1], h[1][1], h[2][1], h[3][1])
}
// mix fills out, interleaved stereo, with the voices playing, and reports
// whether any is.
func mix(out []float32) bool {
mu.Lock()
defer mu.Unlock()
return mixLocked(out)
}
// mixLocked is mix, under mu.
func mixLocked(out []float32) bool {
clear(out)
at, h := mixed, heard()
n := 0
for _, v := range voices {
if v.closed || !v.mix(out, volume, at, h) {
if v.atEnd {
v.atEnd = false
for _, l := range v.onEnd {
go l.fn()
}
}
v.active = false
if v.orphan {
v.close()
}
continue
}
voices[n] = v
n++
}
clear(voices[n:])
voices = voices[:n]
f := int64(len(out) / channels)
mixed += f
unheard = min(unheard+f, held)
for i, s := range out {
out[i] = min(max(s, -1), 1)
}
return n > 0
}
+74
View File
@@ -0,0 +1,74 @@
// Package mp3 decodes MP3 files for package audio, with
// github.com/hajimehoshi/go-mp3. Import it for its side effect:
//
// import _ "github.com/egoist/mygo/audio/mp3"
package mp3
import (
"encoding/binary"
"io"
"github.com/egoist/mygo/audio"
gomp3 "github.com/hajimehoshi/go-mp3"
)
func init() {
open := func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) }
// An ID3 tag, or the sync word of a frame of MPEG-1 or 2 layer III.
audio.RegisterFormat("mp3", "ID3", open)
for _, b := range []string{"\xff\xfb", "\xff\xfa", "\xff\xf3", "\xff\xf2", "\xff\xe3", "\xff\xe2"} {
audio.RegisterFormat("mp3", b, open)
}
}
// NewDecoder returns a decoder of the MP3 file r, which decodes to stereo.
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
d, err := gomp3.NewDecoder(r)
if err != nil {
return nil, err
}
return &decoder{d: d}, nil
}
// go-mp3 decodes to 16-bit stereo: 4 bytes a frame.
const frameBytes = 4
type decoder struct {
d *gomp3.Decoder
buf []byte
}
func (d *decoder) SampleRate() int { return d.d.SampleRate() }
func (d *decoder) Channels() int { return 2 }
func (d *decoder) Len() int64 {
if n := d.d.Length(); n > 0 {
return n / frameBytes
}
return -1
}
func (d *decoder) Read(dst []float32) (int, error) {
n := len(dst) / 2 * frameBytes
if cap(d.buf) < n {
d.buf = make([]byte, n)
}
b := d.buf[:n]
got, err := io.ReadFull(d.d, b)
got -= got % frameBytes
for i := 0; i < got/2; i++ {
dst[i] = float32(int16(binary.LittleEndian.Uint16(b[2*i:]))) / (1 << 15)
}
if got > 0 {
return got / 2, nil
}
if err == io.ErrUnexpectedEOF {
err = io.EOF
}
return 0, err
}
func (d *decoder) SetPosition(frame int64) error {
_, err := d.d.Seek(frame*frameBytes, io.SeekStart)
return err
}
+59
View File
@@ -0,0 +1,59 @@
package mp3
import (
"bytes"
"math"
"os"
"testing"
"time"
"github.com/egoist/mygo/audio"
)
// tone.mp3 is 0.5 s of a 440 Hz sine at 44.1 kHz, in mono, which decodes
// to stereo with the encoder's padding.
func TestDecode(t *testing.T) {
data, err := os.ReadFile("testdata/tone.mp3")
if err != nil {
t.Fatal(err)
}
d, name, err := audio.NewDecoder(bytes.NewReader(data))
if err != nil || name != "mp3" {
t.Fatal(name, err)
}
if d.SampleRate() != 44100 || d.Channels() != 2 {
t.Fatalf("%d Hz, %d channels", d.SampleRate(), d.Channels())
}
// go-mp3 keeps the encoder's delay and padding, a few frames of 1152.
if n := d.Len(); n < 22050 || n > 22050+4*1152 {
t.Errorf("Len = %d", n)
}
s, err := audio.DecodeSound(data)
if err != nil {
t.Fatal(err)
}
if got := s.Duration(); got < 500*time.Millisecond || got > 610*time.Millisecond {
t.Errorf("Duration = %v", got)
}
if err := d.SetPosition(10000); err != nil {
t.Fatal(err)
}
buf := make([]float32, 2*8820)
n := 0
for n < len(buf) {
m, err := d.Read(buf[n:])
n += m
if err != nil {
break
}
}
zc := 0
for i := 2; i < n; i += 2 {
if (buf[i-2] < 0) != (buf[i] < 0) {
zc++
}
}
if f := float64(zc) / 2 / (float64(n/2) / 44100); math.Abs(f-440) > 5 {
t.Errorf("decoded %v Hz from frame 10000", f)
}
}
Binary file not shown.
+538
View File
@@ -0,0 +1,538 @@
package mp4
import (
"encoding/binary"
"errors"
"math/bits"
)
// An ALAC decoder decodes Apple Lossless packets, as an MP4 holds them, after
// Apple's own decoder (https://github.com/macosforge/alac, under the Apache
// License 2.0): each packet a frame of up to frameLength
// samples a channel, adaptively Golomb coded, then predicted from the samples
// before it. It gives stereo, of a mono file in both ears.
type alacDecoder struct {
frameLength uint32
bitDepth uint8
pb, mb, kb uint8
channels uint8
rate uint32
predictor []int32
u, v []int32 // a channel pair's, mixed
shift []uint16
left, right []int32 // the channels kept: the front pair
leftCh, rightCh int
bitsPerSample float32
coefsU, coefsV [32]int16
packet []byte // the last, with zeros after it
}
// ALAC elements, as AAC's.
const (
alacSCE = 0 // a single channel
alacCPE = 1 // a channel pair
alacCCE = 2
alacLFE = 3
alacDSE = 4
alacPCE = 5
alacFIL = 6
alacEND = 7
)
// newALACDecoder reads the stream's magic cookie: its ALACSpecificConfig, in
// an MP4 within an 'alac' atom of its own, and in QuickTime's after a 'frma'.
func newALACDecoder(cookie []byte) (*alacDecoder, error) {
for len(cookie) >= 12 {
switch string(cookie[4:8]) {
case "frma":
cookie = cookie[12:]
continue
case "alac":
cookie = cookie[12:]
continue
}
break
}
if len(cookie) < 24 {
return nil, errors.New("alac: short magic cookie")
}
d := &alacDecoder{
frameLength: binary.BigEndian.Uint32(cookie),
bitDepth: cookie[5],
pb: cookie[6],
mb: cookie[7],
kb: cookie[8],
channels: cookie[9],
rate: binary.BigEndian.Uint32(cookie[20:]),
}
switch {
case cookie[4] != 0:
return nil, errors.New("alac: unknown version")
case d.frameLength == 0 || d.frameLength > 1<<16:
return nil, errors.New("alac: bad frame length")
case d.bitDepth != 16 && d.bitDepth != 20 && d.bitDepth != 24 && d.bitDepth != 32:
return nil, errors.New("alac: bad bit depth")
case d.channels == 0 || d.channels > 8:
return nil, errors.New("alac: bad channel count")
case d.kb == 0 || d.kb > 30:
return nil, errors.New("alac: bad parameters")
}
n := int(d.frameLength)
d.predictor = make([]int32, n)
d.u, d.v = make([]int32, n), make([]int32, n)
d.shift = make([]uint16, 2*n)
d.left, d.right = make([]int32, n), make([]int32, n)
// The front left and right, of ALAC's channel layouts: C L R first from
// three channels, and C Lc Rc L R from eight.
switch d.channels {
case 1:
d.leftCh, d.rightCh = 0, 0
case 2:
d.leftCh, d.rightCh = 0, 1
case 8:
d.leftCh, d.rightCh = 3, 4
default:
d.leftCh, d.rightCh = 1, 2
}
d.bitsPerSample = 1 / float32(int64(1)<<(d.bitDepth-1))
return d, nil
}
// alacBits reads a packet's bits, most significant first. Reads past its end
// read zeros, and mark it overrun.
type alacBits struct {
b []byte // with 8 bytes of zeros after it
n uint // its bits, but the zeros
pos uint
}
func (r *alacBits) at(pos, n uint) uint32 {
if n == 0 {
return 0
}
i := pos >> 3
if i+8 > uint(len(r.b)) {
return 0
}
return uint32(binary.BigEndian.Uint64(r.b[i:]) << (pos & 7) >> (64 - n))
}
func (r *alacBits) read(n uint) uint32 {
v := r.at(r.pos, n)
r.pos += n
return v
}
func (r *alacBits) over() bool { return r.pos > r.n }
var errALACData = errors.New("alac: bad packet")
// Decode decodes a packet into dst, as stereo, and returns it.
func (d *alacDecoder) Decode(dst []float32, packet []byte) ([]float32, error) {
// With zeros after it, for reads of 8 bytes at a time near its end.
d.packet = append(append(d.packet[:0], packet...), make([]byte, 8)...)
r := &alacBits{b: d.packet, n: uint(len(packet)) * 8}
ch := 0
samples := -1
for {
if r.over() {
return dst, errALACData
}
tag := r.read(3)
switch tag {
case alacSCE, alacLFE, alacCPE:
if ch >= int(d.channels) {
return dst, errALACData
}
pair := tag == alacCPE
n, err := d.element(r, pair, ch)
if err != nil {
return dst, err
}
if samples >= 0 && n != samples {
return dst, errALACData
}
samples = n
if pair {
ch += 2
} else {
ch++
}
case alacDSE:
r.read(4) // its instance
align := r.read(1)
count := r.read(8)
if count == 255 {
count += r.read(8)
}
if align != 0 {
r.pos = (r.pos + 7) &^ 7
}
r.pos += uint(count) * 8
case alacFIL:
count := r.read(4)
if count == 15 {
count += r.read(8) - 1
}
r.pos += uint(count) * 8
case alacEND:
if samples < 0 {
return dst, errALACData
}
for i := range samples {
dst = append(dst, float32(d.left[i])*d.bitsPerSample, float32(d.right[i])*d.bitsPerSample)
}
return dst, nil
default:
return dst, errors.New("alac: unsupported element")
}
if ch >= int(d.channels) {
// Done with the channels: an END element should follow, but
// some encoders leave it out.
if r.over() || samples < 0 {
return dst, errALACData
}
for i := range samples {
dst = append(dst, float32(d.left[i])*d.bitsPerSample, float32(d.right[i])*d.bitsPerSample)
}
return dst, nil
}
}
}
// element decodes a single channel, or a pair, as channel ch on, and keeps
// what of it plays. It returns its samples a channel.
func (d *alacDecoder) element(r *alacBits, pair bool, ch int) (int, error) {
r.read(4) // its instance
if r.read(12) != 0 {
return 0, errALACData
}
header := r.read(4)
partial := header>>3 != 0
shifted := uint(header >> 1 & 3)
escape := header&1 != 0
if shifted == 3 {
return 0, errALACData
}
n := d.frameLength
if partial {
n = r.read(32)
if n == 0 || n > d.frameLength {
return 0, errALACData
}
}
chanBits := uint(d.bitDepth) - shifted*8
if pair {
chanBits++
}
if chanBits > 32 {
return 0, errALACData
}
u, v := d.u[:n], d.v[:n]
var mixBits uint32
var mixRes int32
if !escape {
mixBits = r.read(8)
mixRes = int32(int8(r.read(8)))
modeU, denU, pbU, coefsU := d.predictorHeader(r, &d.coefsU)
var modeV, denV, pbV uint32
var coefsV []int16
if pair {
modeV, denV, pbV, coefsV = d.predictorHeader(r, &d.coefsV)
}
var shiftBits alacBits
if shifted != 0 {
shiftBits = *r
ways := uint(1)
if pair {
ways = 2
}
r.pos += shifted * 8 * ways * uint(n)
}
if err := d.channel(r, u, modeU, denU, pbU, coefsU, chanBits); err != nil {
return 0, err
}
if pair {
if err := d.channel(r, v, modeV, denV, pbV, coefsV, chanBits); err != nil {
return 0, err
}
}
if shifted != 0 {
bits := shifted * 8
if pair {
for i := range n {
d.shift[2*i] = uint16(shiftBits.read(bits))
d.shift[2*i+1] = uint16(shiftBits.read(bits))
}
} else {
for i := range n {
d.shift[i] = uint16(shiftBits.read(bits))
}
}
}
} else {
// Uncompressed, and never shifted.
shifted = 0
chanBits = uint(d.bitDepth)
ext := 32 - chanBits
for i := range n {
u[i] = int32(r.read(chanBits)<<ext) >> ext
if pair {
v[i] = int32(r.read(chanBits)<<ext) >> ext
}
}
}
if r.over() {
return 0, errALACData
}
keep := func(c int, out []int32) {
switch c {
case d.leftCh:
copy(d.left, out)
if d.rightCh == c {
copy(d.right, out)
}
case d.rightCh:
copy(d.right, out)
}
}
bits := shifted * 8
if !pair {
if shifted != 0 {
for i := range n {
u[i] = u[i]<<bits | int32(d.shift[i])
}
}
keep(ch, u)
return int(n), nil
}
for i := range n {
l, rr := u[i], v[i]
if mixRes != 0 {
l = u[i] + v[i] - (mixRes*v[i])>>mixBits
rr = l - v[i]
}
if shifted != 0 {
l = l<<bits | int32(d.shift[2*i])
rr = rr<<bits | int32(d.shift[2*i+1])
}
u[i], v[i] = l, rr
}
keep(ch, u)
keep(ch+1, v)
return int(n), nil
}
// predictorHeader reads a channel's predictor: its mode, its shift, its
// rice parameter's factor and its coefficients.
func (d *alacDecoder) predictorHeader(r *alacBits, coefs *[32]int16) (mode, den, pbFactor uint32, c []int16) {
h := r.read(8)
mode, den = h>>4, h&15
h = r.read(8)
pbFactor = h >> 5
num := h & 31
for i := range num {
coefs[i] = int16(r.read(16))
}
return mode, den, pbFactor, coefs[:num]
}
// channel entropy-decodes a channel's residues, and predicts its samples
// from them, into out.
func (d *alacDecoder) channel(r *alacBits, out []int32, mode, den, pbFactor uint32, coefs []int16, chanBits uint) error {
pc := d.predictor[:len(out)]
pb := uint32(d.pb) * pbFactor / 4
if err := d.residues(r, pc, pb, chanBits); err != nil {
return err
}
if mode != 0 {
unpredict(pc, pc, nil, 31, uint32(chanBits), 0)
}
unpredict(pc, out, coefs, len(coefs), uint32(chanBits), den)
return nil
}
// The adaptive Golomb coder's constants.
const (
alacQBShift = 9
alacQB = 1 << alacQBShift
alacMMulShift = 2
alacMDenShift = alacQBShift - alacMMulShift - 1
alacMOff = 1 << (alacMDenShift - 2)
alacBitOff = 24
alacMaxPrefix = 9
)
// residues decodes len(out) residues, adapting the code to their mean as it
// goes, with runs of zeros coded apart where it's small.
func (d *alacDecoder) residues(r *alacBits, out []int32, pb uint32, maxBits uint) error {
mb := uint32(d.mb)
kb := uint32(d.kb)
wb := uint32(1)<<kb - 1
zmode := uint32(0)
for c := 0; c < len(out); {
if r.pos >= r.n {
return errALACData
}
m := mb >> alacQBShift
k := min(uint32(31-bits.LeadingZeros32(m+3)), kb)
m = 1<<k - 1
n := r.golomb32(m, k, maxBits)
nd := n + zmode
del := int32((nd + 1) >> 1)
if nd&1 != 0 {
del = -del
}
out[c] = del
c++
mb = pb*(n+zmode) + mb - (pb*mb)>>alacQBShift
if n > 0xffff {
mb = 0xffff
}
zmode = 0
if mb<<alacMMulShift < alacQB && c < len(out) {
zmode = 1
k := uint32(bits.LeadingZeros32(mb)) - alacBitOff + (mb+alacMOff)>>alacMDenShift
mz := (uint32(1)<<k - 1) & wb
run := r.golomb16(mz, k)
if c+int(run) > len(out) {
return errALACData
}
for range run {
out[c] = 0
c++
}
if run >= 0xffff {
zmode = 0
}
mb = 0
}
}
return nil
}
// golomb32 reads a residue: a unary prefix, then k bits, or else, after
// alacMaxPrefix ones, the residue in maxBits.
func (r *alacBits) golomb32(m, k uint32, maxBits uint) uint32 {
word := r.at(r.pos, 32)
pre := uint32(bits.LeadingZeros32(^word))
if pre >= alacMaxPrefix {
v := r.at(r.pos+alacMaxPrefix, maxBits)
r.pos += alacMaxPrefix + maxBits
return v
}
r.pos += uint(pre) + 1
if k == 1 {
return pre
}
v := word << (pre + 1) >> (32 - k)
r.pos += uint(k) - 1
res := pre * m
if v >= 2 {
res += v - 1
r.pos++
}
return res
}
// golomb16 reads the length of a run of zeros, as golomb32 does a residue
// but escaping to 16 bits.
func (r *alacBits) golomb16(m, k uint32) uint32 {
word := r.at(r.pos, 32)
pre := uint32(bits.LeadingZeros32(^word))
if pre >= alacMaxPrefix {
v := r.at(r.pos+alacMaxPrefix, 16)
r.pos += alacMaxPrefix + 16
return v
}
v := word << (pre + 1) >> (32 - k)
r.pos += uint(pre) + 1 + uint(k)
res := pre*m + v - 1
if v < 2 {
res = pre * m
r.pos--
}
return res
}
func signOf(i int32) int32 {
switch {
case i > 0:
return 1
case i < 0:
return -1
}
return 0
}
// unpredict undoes the adaptive linear prediction of numActive coefficients
// on pc into out, which may be the same. With 31 it's the first-order one.
func unpredict(pc, out []int32, coefs []int16, numActive int, chanBits, denShift uint32) {
num := len(out)
if num == 0 {
return
}
shift := 32 - chanBits
out[0] = pc[0]
if numActive == 0 {
copy(out[1:], pc[1:num])
return
}
if numActive == 31 {
prev := out[0]
for j := 1; j < num; j++ {
del := pc[j] + prev
prev = del << shift >> shift
out[j] = prev
}
return
}
for j := 1; j <= numActive && j < num; j++ {
del := pc[j] + out[j-1]
out[j] = del << shift >> shift
}
var half int32
if denShift > 0 {
half = 1 << (denShift - 1)
}
lim := numActive + 1
for j := lim; j < num; j++ {
top := out[j-lim]
var sum int32
for k := range numActive {
sum += int32(coefs[k]) * (out[j-1-k] - top)
}
del := pc[j]
del0 := del
sg := signOf(del)
del += top + (sum+half)>>denShift
out[j] = del << shift >> shift
switch {
case sg > 0:
for k := numActive - 1; k >= 0; k-- {
dd := top - out[j-1-k]
sgn := signOf(dd)
coefs[k] -= int16(sgn)
del0 -= int32(numActive-k) * ((sgn * dd) >> denShift)
if del0 <= 0 {
break
}
}
case sg < 0:
for k := numActive - 1; k >= 0; k-- {
dd := top - out[j-1-k]
sgn := signOf(dd)
coefs[k] += int16(sgn)
del0 -= int32(numActive-k) * ((-sgn * dd) >> denShift)
if del0 >= 0 {
break
}
}
}
}
}
func (d *alacDecoder) SampleRate() int { return int(d.rate) }
func (d *alacDecoder) Reset() {}
func (d *alacDecoder) Preroll() int { return 0 }
func (d *alacDecoder) PacketFrames() int { return 0 }
+633
View File
@@ -0,0 +1,633 @@
package mp4
import (
"encoding/binary"
"errors"
"io"
"iter"
)
// A track is an MP4's first sound track.
type track struct {
// Codec is the type of its sample entry: "mp4a", "alac", "fLaC", ...
Codec string
// Config is AAC's AudioSpecificConfig, ALAC's magic cookie, FLAC's
// metadata blocks, or another codec's boxes within the sample entry.
Config []byte
Timescale int64 // the units of its times, a second's
// Duration is how long it is, in the timescale, as its header says.
Duration int64
// Prime is where the edit list starts it: the encoder's priming, in
// the timescale, to drop.
Prime int64
// Where each packet is, and where it ends, in the timescale. Only
// read with the tables.
Offsets []int64
Sizes []uint32
Ends []int64
// Fragmented says the packets aren't in the movie header's tables but
// in fragments after it, as a stream cut up for DASH has them: the
// tables fill in as fragment reads each. Next is where the boxes after
// the movie header start.
Fragmented bool
Next int64
id uint32 // the track's ID, which its fragments name
defaults fragmentDefaults
}
// fragmentDefaults are what a fragment's packets are unless it says.
type fragmentDefaults struct {
duration, size uint32
}
// ErrNoMovie says an MP4 has no movie header: no tracks to play.
var ErrNoMovie = errors.New("mp4: no movie header")
// readTrack reads the sound track of the MP4 r holds, of size bytes. With tables,
// it reads where each packet is too. The movie header is often after the
// media data: r may wait for the bytes asked of it, as a file coming in.
func readTrack(r io.ReaderAt, size int64, tables bool) (*track, error) {
var h [16]byte
for off := int64(0); off+8 <= size; {
if _, err := r.ReadAt(h[:8], off); err != nil {
return nil, ErrNoMovie
}
n, head := int64(binary.BigEndian.Uint32(h[:])), int64(8)
switch n {
case 0: // to the end
n = size - off
case 1:
if _, err := r.ReadAt(h[8:], off+8); err != nil {
return nil, ErrNoMovie
}
n, head = int64(binary.BigEndian.Uint64(h[8:])), 16
}
if n < head || n > size-off {
return nil, errors.New("mp4: bad box")
}
if string(h[4:8]) == "moov" {
if n > 256<<20 {
return nil, errors.New("mp4: movie header too big")
}
moov := make([]byte, n-head)
if _, err := r.ReadAt(moov, off+head); err != nil {
return nil, err
}
a, err := parseMoov(moov, tables)
if err != nil || !a.Fragmented {
return a, err
}
a.Next = off + n
a.readIndex(r, size)
return a, nil
}
off += n
}
return nil, ErrNoMovie
}
// boxes walks the boxes in b, giving each one's type and body.
func boxes(b []byte) iter.Seq2[string, []byte] {
return func(yield func(string, []byte) bool) {
for len(b) >= 8 {
size, head := uint64(binary.BigEndian.Uint32(b)), uint64(8)
typ := string(b[4:8])
switch size {
case 0:
size = uint64(len(b))
case 1:
if len(b) < 16 {
return
}
size, head = binary.BigEndian.Uint64(b[8:]), 16
}
if size < head || size > uint64(len(b)) {
return
}
if !yield(typ, b[head:size]) {
return
}
b = b[size:]
}
}
}
// child returns the body of the box of type typ in b, following the path of
// types after it into the boxes within.
func child(b []byte, path ...string) []byte {
for _, typ := range path {
var found []byte
for t, body := range boxes(b) {
if t == typ {
found = body
break
}
}
if found == nil {
return nil
}
b = found
}
return b
}
// parseMoov finds the first sound track in a movie header.
func parseMoov(moov []byte, tables bool) (*track, error) {
mvex := child(moov, "mvex")
for typ, trak := range boxes(moov) {
if typ != "trak" {
continue
}
mdia := child(trak, "mdia")
if hdlr := child(mdia, "hdlr"); len(hdlr) < 12 || string(hdlr[8:12]) != "soun" {
continue
}
a, err := parseTrack(trak, mdia, mvex, tables)
if err != nil {
return nil, err
}
return a, nil
}
return nil, errors.New("mp4: no sound track")
}
var errMP4Table = errors.New("mp4: bad sample table")
func parseTrack(trak, mdia, mvex []byte, tables bool) (*track, error) {
a := &track{}
mdhd := child(mdia, "mdhd")
switch {
case len(mdhd) >= 32 && mdhd[0] == 1:
a.Timescale = int64(binary.BigEndian.Uint32(mdhd[20:]))
a.Duration = int64(binary.BigEndian.Uint64(mdhd[24:]))
case len(mdhd) >= 20:
a.Timescale = int64(binary.BigEndian.Uint32(mdhd[12:]))
a.Duration = int64(binary.BigEndian.Uint32(mdhd[16:]))
}
if a.Timescale <= 0 || a.Duration < 0 {
return nil, errors.New("mp4: no timescale")
}
stbl := child(mdia, "minf", "stbl")
if err := a.parseEntry(child(stbl, "stsd")); err != nil {
return nil, err
}
if mvex != nil && !hasSamples(stbl) {
a.Fragmented = true
if tkhd := child(trak, "tkhd"); len(tkhd) >= 16 {
at := 12
if tkhd[0] == 1 {
at = 20
}
a.id = binary.BigEndian.Uint32(tkhd[at:])
}
for typ, trex := range boxes(mvex) {
if typ == "trex" && len(trex) >= 24 && binary.BigEndian.Uint32(trex[4:]) == a.id {
a.defaults = fragmentDefaults{binary.BigEndian.Uint32(trex[12:]), binary.BigEndian.Uint32(trex[16:])}
}
}
} else if tables {
if err := a.parseTables(stbl); err != nil {
return nil, err
}
a.Duration = a.Ends[len(a.Ends)-1]
}
if elst := child(trak, "edts", "elst"); len(elst) >= 8 {
n := binary.BigEndian.Uint32(elst[4:])
b := elst[8:]
for range n {
var t int64
if elst[0] == 1 {
if len(b) < 20 {
break
}
t, b = int64(binary.BigEndian.Uint64(b[8:])), b[20:]
} else {
if len(b) < 12 {
break
}
t, b = int64(int32(binary.BigEndian.Uint32(b[4:]))), b[12:]
}
if t >= 0 { // past an empty edit, which plays nothing
a.Prime = t
if a.Duration > 0 {
a.Prime = min(t, a.Duration)
}
break
}
}
}
return a, nil
}
// parseEntry reads the track's sample description: its codec and its
// configuration, in a box within the entry, or within a 'wave' box there in
// QuickTime's own kind.
func (a *track) parseEntry(stsd []byte) error {
if len(stsd) < 8+36 {
return errors.New("mp4: no sample description")
}
entry := stsd[8:]
size := int(binary.BigEndian.Uint32(entry))
if size < 36 || size > len(entry) {
return errors.New("mp4: bad sample description")
}
a.Codec = string(entry[4:8])
inner := entry[36:size]
switch binary.BigEndian.Uint16(entry[16:]) { // the version of the sound description
case 1:
inner = inner[min(16, len(inner)):]
case 2:
inner = inner[min(36, len(inner)):]
}
if wave := child(inner, "wave"); wave != nil {
inner = wave
}
switch a.Codec {
case "alac":
cookie := child(inner, "alac")
if len(cookie) < 4 {
return errors.New("mp4: no ALAC configuration")
}
a.Config = cookie[4:]
case "fLaC":
dfla := child(inner, "dfLa")
if len(dfla) < 4+4+34 {
return errors.New("mp4: no FLAC configuration")
}
a.Config = dfla[4:]
case "mp4a":
esds := child(inner, "esds")
if len(esds) < 4 {
return errors.New("mp4: no AAC configuration")
}
asc, ok := decoderConfig(esds[4:])
if !ok {
return errors.New("mp4: not AAC")
}
a.Config = asc
default:
a.Config = inner
}
return nil
}
// decoderConfig finds the DecoderSpecificInfo in an elementary stream's
// descriptors: AAC's AudioSpecificConfig. A stream not of AAC has none it
// takes, as an MP3's in an MP4.
func decoderConfig(b []byte) ([]byte, bool) {
descriptor := func(b []byte) (tag byte, body, rest []byte, ok bool) {
if len(b) < 2 {
return 0, nil, nil, false
}
tag, b = b[0], b[1:]
n := 0
for i := 0; i < 4 && len(b) > 0; i++ {
c := b[0]
b = b[1:]
n = n<<7 | int(c&0x7f)
if c&0x80 == 0 {
break
}
}
if n > len(b) {
return 0, nil, nil, false
}
return tag, b[:n], b[n:], true
}
tag, es, _, ok := descriptor(b)
if !ok || tag != 3 || len(es) < 3 {
return nil, false
}
flags := es[2]
es = es[3:]
if flags&0x80 != 0 { // depends on a stream
es = es[min(2, len(es)):]
}
if flags&0x40 != 0 && len(es) > 0 { // a URL
es = es[min(1+int(es[0]), len(es)):]
}
if flags&0x20 != 0 { // an OCR stream
es = es[min(2, len(es)):]
}
tag, dc, _, ok := descriptor(es)
if !ok || tag != 4 || len(dc) < 13 {
return nil, false
}
switch dc[0] { // MPEG-4 audio, or MPEG-2 AAC's profiles
case 0x40, 0x66, 0x67, 0x68:
default:
return nil, false
}
tag, asc, _, ok := descriptor(dc[13:])
if !ok || tag != 5 || len(asc) < 2 {
return nil, false
}
return asc, true
}
// maxSamples bounds the tables read, against a file that claims more than it
// could hold: a day of AAC at 48 kHz.
const maxSamples = 1 << 22
// parseTables reads the sample table: each packet's size, which chunk holds
// it, where that chunk is, and how long each packet lasts.
func (a *track) parseTables(stbl []byte) error {
// Sizes.
if stsz := child(stbl, "stsz"); len(stsz) >= 12 {
fixed := binary.BigEndian.Uint32(stsz[4:])
n := int(binary.BigEndian.Uint32(stsz[8:]))
if n > maxSamples || fixed == 0 && len(stsz) < 12+4*n {
return errMP4Table
}
a.Sizes = make([]uint32, n)
for i := range a.Sizes {
if fixed != 0 {
a.Sizes[i] = fixed
} else {
a.Sizes[i] = binary.BigEndian.Uint32(stsz[12+4*i:])
}
}
} else if stz2 := child(stbl, "stz2"); len(stz2) >= 12 {
field := int(stz2[7])
n := int(binary.BigEndian.Uint32(stz2[8:]))
if n > maxSamples || field != 4 && field != 8 && field != 16 || len(stz2) < 12+(n*field+7)/8 {
return errMP4Table
}
a.Sizes = make([]uint32, n)
b := stz2[12:]
for i := range a.Sizes {
switch field {
case 4:
a.Sizes[i] = uint32(b[i/2]>>(4*(1-i%2))) & 15
case 8:
a.Sizes[i] = uint32(b[i])
case 16:
a.Sizes[i] = uint32(binary.BigEndian.Uint16(b[2*i:]))
}
}
} else {
return errMP4Table
}
if len(a.Sizes) == 0 {
return errMP4Table
}
// Where the chunks are.
var chunks []int64
if stco := child(stbl, "stco"); len(stco) >= 8 {
n := int(binary.BigEndian.Uint32(stco[4:]))
if n > maxSamples || len(stco) < 8+4*n {
return errMP4Table
}
chunks = make([]int64, n)
for i := range chunks {
chunks[i] = int64(binary.BigEndian.Uint32(stco[8+4*i:]))
}
} else if co64 := child(stbl, "co64"); len(co64) >= 8 {
n := int(binary.BigEndian.Uint32(co64[4:]))
if n > maxSamples || len(co64) < 8+8*n {
return errMP4Table
}
chunks = make([]int64, n)
for i := range chunks {
chunks[i] = int64(binary.BigEndian.Uint64(co64[8+8*i:]))
}
} else {
return errMP4Table
}
// Which packets each chunk holds, in runs of chunks alike.
stsc := child(stbl, "stsc")
if len(stsc) < 8 {
return errMP4Table
}
runs := int(binary.BigEndian.Uint32(stsc[4:]))
if runs > maxSamples || len(stsc) < 8+12*runs || runs == 0 {
return errMP4Table
}
a.Offsets = make([]int64, len(a.Sizes))
s := 0
for r := 0; r < runs && s < len(a.Sizes); r++ {
e := stsc[8+12*r:]
first := int(binary.BigEndian.Uint32(e)) - 1
per := int(binary.BigEndian.Uint32(e[4:]))
last := len(chunks)
if r+1 < runs {
last = int(binary.BigEndian.Uint32(stsc[8+12*(r+1):])) - 1
}
if first < 0 || last > len(chunks) || per <= 0 {
return errMP4Table
}
for c := first; c < last && s < len(a.Sizes); c++ {
off := chunks[c]
for range per {
if s == len(a.Sizes) {
break
}
a.Offsets[s] = off
off += int64(a.Sizes[s])
s++
}
}
}
if s < len(a.Sizes) {
a.Sizes, a.Offsets = a.Sizes[:s], a.Offsets[:s]
}
// How long each lasts.
stts := child(stbl, "stts")
if len(stts) < 8 {
return errMP4Table
}
n := int(binary.BigEndian.Uint32(stts[4:]))
if len(stts) < 8+8*n {
return errMP4Table
}
a.Ends = make([]int64, 0, len(a.Sizes))
var t int64
for i := 0; i < n && len(a.Ends) < len(a.Sizes); i++ {
count := int(binary.BigEndian.Uint32(stts[8+8*i:]))
delta := int64(binary.BigEndian.Uint32(stts[12+8*i:]))
for range min(count, len(a.Sizes)-len(a.Ends)) {
t += delta
a.Ends = append(a.Ends, t)
}
}
if len(a.Ends) == 0 {
return errMP4Table
}
a.Sizes, a.Offsets = a.Sizes[:len(a.Ends)], a.Offsets[:len(a.Ends)]
return nil
}
// hasSamples says whether a sample table lists any packets: a fragmented
// file's lists none, its packets being in the fragments.
func hasSamples(stbl []byte) bool {
if stsz := child(stbl, "stsz"); len(stsz) >= 12 {
return binary.BigEndian.Uint32(stsz[8:]) > 0
}
if stz2 := child(stbl, "stz2"); len(stz2) >= 12 {
return binary.BigEndian.Uint32(stz2[8:]) > 0
}
return false
}
// readIndex reads how long a fragmented track is from the segment index
// that comes before its first fragment, if there's one: the movie header
// of such a file says nothing of it.
func (a *track) readIndex(r io.ReaderAt, size int64) {
var h [8]byte
for off := a.Next; off+8 <= size; {
if _, err := r.ReadAt(h[:], off); err != nil {
return
}
n := int64(binary.BigEndian.Uint32(h[:]))
switch string(h[4:]) {
case "sidx":
if n < 8+24 || n > 1<<20 || n > size-off {
return
}
sidx := make([]byte, n-8)
if _, err := r.ReadAt(sidx, off+8); err != nil {
return
}
if d, ok := indexDuration(sidx); ok && a.Timescale > 0 {
a.Duration = d * a.Timescale / int64(binary.BigEndian.Uint32(sidx[8:]))
}
return
case "moof", "mdat":
return
}
if n < 8 {
return
}
off += n
}
}
// indexDuration adds up the durations of the segments a segment index lists.
func indexDuration(sidx []byte) (int64, bool) {
at := 20
if len(sidx) > 0 && sidx[0] == 1 {
at = 28
}
if len(sidx) < at+4 || binary.BigEndian.Uint32(sidx[8:]) == 0 {
return 0, false
}
b := sidx[at:]
n := int(binary.BigEndian.Uint16(b[2:]))
b = b[4:]
if len(b) < 12*n {
return 0, false
}
var d int64
for i := range n {
d += int64(binary.BigEndian.Uint32(b[12*i+4:]))
}
return d, d > 0
}
// fragment reads a fragment's movie header, the body of the moof box at off
// in the file, adding where the track's packets are in it to the tables.
func (a *track) fragment(moof []byte, off int64) error {
for typ, traf := range boxes(moof) {
if typ != "traf" {
continue
}
tfhd := child(traf, "tfhd")
if len(tfhd) < 8 || binary.BigEndian.Uint32(tfhd[4:]) != a.id {
continue
}
flags := binary.BigEndian.Uint32(tfhd) & 0xffffff
base := off // where the moof starts, unless it says
d := a.defaults
b := tfhd[8:]
field := func(flag uint32, n int) ([]byte, bool) {
if flags&flag == 0 {
return nil, false
}
if len(b) < n {
return nil, false
}
v := b[:n]
b = b[n:]
return v, true
}
if v, ok := field(0x01, 8); ok {
base = int64(binary.BigEndian.Uint64(v))
}
field(0x02, 4) // the sample description: there's one
if v, ok := field(0x08, 4); ok {
d.duration = binary.BigEndian.Uint32(v)
}
if v, ok := field(0x10, 4); ok {
d.size = binary.BigEndian.Uint32(v)
}
at := base
for typ, trun := range boxes(traf) {
if typ != "trun" {
continue
}
var err error
if at, err = a.run(trun, base, at, d); err != nil {
return err
}
}
}
return nil
}
// run reads a track run: packets one after another, from at unless it says
// where from base. It returns where the next run starts, unless it says.
func (a *track) run(trun []byte, base, at int64, d fragmentDefaults) (int64, error) {
if len(trun) < 8 {
return 0, errMP4Table
}
flags := binary.BigEndian.Uint32(trun) & 0xffffff
n := int(binary.BigEndian.Uint32(trun[4:]))
b := trun[8:]
if flags&0x01 != 0 {
if len(b) < 4 {
return 0, errMP4Table
}
at = base + int64(int32(binary.BigEndian.Uint32(b)))
b = b[4:]
}
if flags&0x04 != 0 { // the first packet's flags
if len(b) < 4 {
return 0, errMP4Table
}
b = b[4:]
}
per := 0
for _, f := range []uint32{0x100, 0x200, 0x400, 0x800} {
if flags&f != 0 {
per += 4
}
}
if n > maxSamples || len(b) < n*per || len(a.Sizes)+n > maxSamples {
return 0, errMP4Table
}
var t int64
if len(a.Ends) > 0 {
t = a.Ends[len(a.Ends)-1]
}
for range n {
duration, size := d.duration, d.size
e := b
if flags&0x100 != 0 {
duration, e = binary.BigEndian.Uint32(e), e[4:]
}
if flags&0x200 != 0 {
size = binary.BigEndian.Uint32(e)
}
b = b[per:]
t += int64(duration)
a.Offsets = append(a.Offsets, at)
a.Sizes = append(a.Sizes, size)
a.Ends = append(a.Ends, t)
at += int64(size)
}
return at, nil
}
+247
View File
@@ -0,0 +1,247 @@
package mp4
import (
"encoding/binary"
"errors"
"io"
"sort"
)
// A decoder decodes a track's packets, whose places it knows from the
// movie header's sample table or, of a fragmented file, from each
// fragment's header as it reaches it. A seek goes to the packet holding the
// frame asked for.
type decoder struct {
r io.ReaderAt
codec Codec
rate int
offs []int64
sizes []int
ends []int64 // where each packet ends, in frames
// last is where the last packet found ends, in frames, as the file
// says, when ends places packets by the codec's PacketFrames instead;
// 0 when ends is as the file says.
last int64
// more finds the next fragment's packets, and says if there were
// any. Nil once all are found.
more func() bool
prime int64 // the encoder's priming, in frames, to drop
frames int64 // the length, or -1 if unknown
exact bool // whether it is: then what's past it is padding, dropped
next int // the packet decoded next
pos int64 // the frame Read returns next
skip int64 // frames to drop before it
packet []byte
out []float32
pend []float32
}
func newDecoder(r io.ReaderAt, size int64) (*decoder, error) {
t, err := readTrack(r, size, true)
if err != nil {
return nil, err
}
c, err := openCodec(t)
if err != nil {
return nil, err
}
d := &decoder{r: r, codec: c, rate: c.SampleRate(), frames: -1}
if d.rate <= 0 {
return nil, errors.New("mp4: no sample rate")
}
// In frames, from the track's timescale: most often the same.
frames := func(v int64) int64 { return v * int64(d.rate) / t.Timescale }
d.prime = frames(t.Prime)
d.skip = d.prime
if !t.Fragmented {
for i := range t.Sizes {
d.add(t.Offsets[i], int(t.Sizes[i]), frames(t.Ends[i]))
}
if len(d.ends) == 0 {
return nil, errors.New("mp4: no packets")
}
d.frames, d.exact = d.length()-d.prime, true
return d, nil
}
d.fragments(t, size, frames)
if t.Duration > 0 {
// From the segment index: the fragments are found as they play.
d.frames = frames(t.Duration) - d.prime
} else {
for d.findMore() {
}
}
if !d.have(0) {
return nil, errors.New("mp4: no fragments")
}
return d, nil
}
func (d *decoder) SampleRate() int { return d.rate }
func (d *decoder) Channels() int { return 2 }
func (d *decoder) Len() int64 { return d.frames }
// add adds a packet of size bytes at off, ending at end frames as the file
// says.
func (d *decoder) add(off int64, size int, end int64) {
d.offs = append(d.offs, off)
d.sizes = append(d.sizes, size)
if n := d.codec.PacketFrames(); n > 0 {
d.last = end
end = int64(len(d.ends)+1) * int64(n)
}
d.ends = append(d.ends, end)
}
// length is where the packets found end, in frames, as the file says.
func (d *decoder) length() int64 {
if d.last > 0 {
return d.last
}
return d.ends[len(d.ends)-1]
}
// packetStart is the frame packet i starts at.
func (d *decoder) packetStart(i int) int64 {
if i == 0 {
return 0
}
return d.ends[i-1]
}
// have says whether packet i is known, finding more if need be.
func (d *decoder) have(i int) bool {
for i >= len(d.offs) {
if !d.findMore() {
return false
}
}
return true
}
// findMore finds the next fragment's packets, if there are any left to
// find. Once all are found, the length is known.
func (d *decoder) findMore() bool {
if d.more == nil {
return false
}
if d.more() {
return true
}
d.more = nil
if len(d.ends) > 0 {
d.frames, d.exact = d.length()-d.prime, true
}
return false
}
func (d *decoder) Read(dst []float32) (int, error) {
for len(d.pend) == 0 {
if !d.have(d.next) {
return 0, io.EOF
}
if !d.exact {
// Whether this is the last packet, whose padding is dropped:
// the next fragment's are found, if any.
d.have(d.next + 1)
}
size := d.sizes[d.next]
if cap(d.packet) < size {
d.packet = make([]byte, size)
}
d.packet = d.packet[:size]
if _, err := d.r.ReadAt(d.packet, d.offs[d.next]); err != nil {
if err == io.ErrUnexpectedEOF {
err = io.EOF // cut short
}
return 0, err
}
d.next++
out, err := d.codec.Decode(d.out[:0], d.packet)
d.out = out
if err != nil {
continue // a packet gone bad: on to the next
}
drop := min(d.skip, int64(len(out)/2))
d.skip -= drop
d.pend = out[drop*2:]
}
n := copy(dst[:len(dst)/2*2], d.pend)
if d.exact {
// What the encoder padded the last packet with.
n = int(min(int64(n), (d.frames-d.pos)*2))
if n <= 0 {
d.pend = nil
return 0, io.EOF
}
}
d.pend = d.pend[n:]
d.pos += int64(n / 2)
return n, nil
}
// SetPosition goes to the packet holding frame, from those before it its
// sound overlaps, and drops what comes before frame.
func (d *decoder) SetPosition(frame int64) error {
frame = max(frame, 0)
if d.frames >= 0 {
frame = min(frame, d.frames)
}
at := frame + d.prime
for (len(d.ends) == 0 || d.ends[len(d.ends)-1] <= at) && d.findMore() {
}
i := sort.Search(len(d.ends), func(i int) bool { return d.ends[i] > at })
start := max(0, i-d.codec.Preroll())
d.codec.Reset()
d.next, d.pos = start, frame
d.skip = at - d.packetStart(start)
d.pend = nil
return nil
}
// fragments has the decoder find a fragmented file's packets as it needs
// them, a fragment at a time, walking the boxes after the movie header.
func (d *decoder) fragments(t *track, size int64, frames func(int64) int64) {
off := t.Next
var h [16]byte
d.more = func() bool {
for off+8 <= size {
if _, err := d.r.ReadAt(h[:8], off); err != nil {
return false
}
n, head := int64(binary.BigEndian.Uint32(h[:])), int64(8)
if n == 1 {
if _, err := d.r.ReadAt(h[8:], off+8); err != nil {
return false
}
n, head = int64(binary.BigEndian.Uint64(h[8:])), 16
}
if n < head {
return false // to the end, or broken: no more fragments
}
at := off
off += n
if string(h[4:8]) != "moof" {
continue
}
if n > 16<<20 {
return false
}
moof := make([]byte, n-head)
if _, err := d.r.ReadAt(moof, at+head); err != nil {
return false
}
found := len(t.Sizes)
if err := t.fragment(moof, at); err != nil {
return false
}
for i := found; i < len(t.Sizes); i++ {
d.add(t.Offsets[i], int(t.Sizes[i]), frames(t.Ends[i]))
}
if len(t.Sizes) > found {
return true
}
}
return false
}
}
+147
View File
@@ -0,0 +1,147 @@
// Package mp4 decodes the sound of MP4 files for package audio: .m4a and
// .mp4, whole or cut into fragments as a stream for DASH is (.m4s). It
// reads the container, and a codec registered with RegisterCodec decodes
// its packets. Apple Lossless (ALAC) is built in; import package
// audio/aac for AAC, and audio/flac for FLAC in MP4:
//
// import (
// _ "github.com/egoist/mygo/audio/aac" // AAC, in MP4 too
// _ "github.com/egoist/mygo/audio/flac" // FLAC, in MP4 too
// )
//
// Each imports this package, which registers the format with package
// audio.
package mp4
import (
"errors"
"io"
"sync"
"time"
"github.com/egoist/mygo/audio"
)
func init() {
audio.RegisterFormat("mp4", "????ftyp", func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) })
RegisterCodec("alac", func(config []byte) (Codec, error) { return newALACDecoder(config) })
}
// A Codec decodes the packets of a track, one at a time, to stereo.
type Codec interface {
// SampleRate returns the frames per second it decodes to.
SampleRate() int
// Decode appends the sound of a packet to dst, as interleaved left
// and right samples in [-1, 1], and returns it. A mono track plays in
// both; of more channels, the front left and right play.
Decode(dst []float32, packet []byte) ([]float32, error)
// Reset forgets the packets decoded before, as after a seek.
Reset()
// Preroll returns how many packets before the one holding a frame
// sought to are decoded first, for codecs whose packets overlap the
// sound of the one before, as AAC's (1); 0 when packets stand alone.
Preroll() int
// PacketFrames returns how many frames every packet decodes to, when
// all do, as AAC's 1024: packets are then placed in time by counting
// them, whatever the file says they last. 0 places them as the file
// says, for codecs whose packets differ.
PacketFrames() int
}
var (
codecsMu sync.Mutex
codecs = map[string]func([]byte) (Codec, error){}
)
// RegisterCodec registers the codec of tracks whose sample entry is of
// type fourcc, as "mp4a": open returns a decoder of its packets from the
// track's configuration (see Track's Config). A package for a codec calls
// it in its init function.
func RegisterCodec(fourcc string, open func(config []byte) (Codec, error)) {
codecsMu.Lock()
defer codecsMu.Unlock()
codecs[fourcc] = open
}
func openCodec(t *track) (Codec, error) {
codecsMu.Lock()
open := codecs[t.Codec]
codecsMu.Unlock()
if open == nil {
return nil, errors.New("mp4: no codec registered for " + t.Codec)
}
return open(t.Config)
}
// Track describes an MP4's sound track, as its movie header says, for an
// app to know of a file without decoding it, as a music library scanning
// files does.
type Track struct {
// Codec is the type of the track's sample entry: "mp4a" (AAC),
// "alac", "fLaC", "Opus", ...
Codec string
// Config configures the codec: AAC's AudioSpecificConfig, ALAC's
// magic cookie, FLAC's metadata blocks, or another codec's boxes
// within the sample entry.
Config []byte
// Duration is how long it plays, without the encoder's priming, or 0
// for a fragmented file whose length its header doesn't say.
Duration time.Duration
// Fragmented says its packets are in fragments after the movie header.
Fragmented bool
}
// ReadTrack reads the first sound track of the MP4 file r holds, of size
// bytes, from its movie header.
func ReadTrack(r io.ReaderAt, size int64) (*Track, error) {
t, err := readTrack(r, size, false)
if err != nil {
return nil, err
}
return &Track{
Codec: t.Codec,
Config: t.Config,
Duration: time.Duration(max(t.Duration-t.Prime, 0) * int64(time.Second) / t.Timescale),
Fragmented: t.Fragmented,
}, nil
}
// Decodable says whether a codec registered decodes the track: HE-AAC, for
// one, package aac does not.
func (t *Track) Decodable() bool {
_, err := openCodec(&track{Codec: t.Codec, Config: t.Config})
return err == nil
}
// NewDecoder returns a decoder of the first sound track of the MP4 file r
// holds, which decodes to stereo. It reads the movie header, and the
// packets as they are played, so a file still coming in plays as it comes
// when r waits for the bytes asked of it: a fragmented one, a fragment at
// a time, with its length from its segment index. One with no index is
// read through for its length.
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
size, err := r.Seek(0, io.SeekEnd)
if err != nil {
return nil, err
}
ra, ok := r.(io.ReaderAt)
if !ok {
ra = &readerAt{r: r}
}
return newDecoder(ra, size)
}
// readerAt reads at offsets of a ReadSeeker, seeking.
type readerAt struct {
mu sync.Mutex
r io.ReadSeeker
}
func (r *readerAt) ReadAt(b []byte, off int64) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, err := r.r.Seek(off, io.SeekStart); err != nil {
return 0, err
}
return io.ReadFull(r.r, b)
}
+120
View File
@@ -0,0 +1,120 @@
package mp4_test
import (
"bytes"
"errors"
"testing"
"time"
_ "github.com/egoist/mygo/audio/flac"
"github.com/egoist/mygo/audio/internal/audiotest"
"github.com/egoist/mygo/audio/mp4"
)
// alac.m4a is the first second of ../flac/testdata/tone.flac in Apple
// Lossless: it decodes to exactly those samples, and a seek lands on the
// very frame asked for.
func TestALAC(t *testing.T) {
b := audiotest.Read(t, "testdata/alac.m4a")
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
if err != nil {
t.Fatal(err)
}
if tr.Codec != "alac" || tr.Duration != time.Second || tr.Fragmented || !tr.Decodable() {
t.Fatalf("%+v", tr)
}
d := audiotest.Open(t, b, "mp4")
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 44100 {
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
}
got := audiotest.ReadAll(t, d)
want := audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "../flac/testdata/tone.flac"), "flac"))
if len(got) != 44100*2 || audiotest.MaxDiff(got, want) != 0 {
t.Fatalf("decoded %d samples, off from the FLAC by up to %g", len(got), audiotest.MaxDiff(got, want))
}
audiotest.SeekLands(t, d, got, 0, 0, 1, 4095, 4096, 30000, 44099)
}
// A track of a codec none registered is described, and fails to decode:
// this test doesn't import package aac.
func TestNoCodec(t *testing.T) {
b := audiotest.Read(t, "../aac/testdata/tone.m4a")
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
if err != nil {
t.Fatal(err)
}
if tr.Codec != "mp4a" || len(tr.Config) < 2 || tr.Duration != 2*time.Second || tr.Decodable() {
t.Fatalf("%+v", tr)
}
if _, err := mp4.NewDecoder(bytes.NewReader(b)); err == nil {
t.Fatal("decoded AAC with no codec for it")
}
}
// coming reads a file of which only the first n bytes are in, as one
// still downloading, failing to read past them.
type coming struct {
*bytes.Reader
n int64
}
var errNotYet = errors.New("not in yet")
func (c *coming) ReadAt(b []byte, off int64) (int, error) {
if off+int64(len(b)) > c.n {
return 0, errNotYet
}
return c.Reader.ReadAt(b, off)
}
// A fragmented MP4 plays with only its first fragment in, its length from
// its segment index: the fragments after are read as it plays them.
func TestFragmentedComingIn(t *testing.T) {
b := audiotest.Read(t, "../flac/testdata/fragmented.m4a")
r := &coming{bytes.NewReader(b), 16 << 10}
tr, err := mp4.ReadTrack(r, int64(len(b)))
if err != nil {
t.Fatal(err)
}
if !tr.Fragmented || tr.Duration != 2*time.Second {
t.Fatalf("%+v", tr)
}
d, err := mp4.NewDecoder(r)
if err != nil {
t.Fatal(err)
}
if d.Len() != 88200 {
t.Fatalf("length %d", d.Len())
}
buf := make([]float32, 2*4096)
if n, err := d.Read(buf); n != len(buf) || err != nil {
t.Fatalf("read %d samples: %v", n, err)
}
// Then the rest comes in.
r.n = int64(len(b))
got := append(buf, audiotest.ReadAll(t, d)...)
if len(got) != 88200*2 {
t.Fatalf("decoded %d samples", len(got))
}
}
// A fragmented MP4 with no segment index is read through for its length.
func TestFragmentedNoIndex(t *testing.T) {
b := bytes.Clone(audiotest.Read(t, "../flac/testdata/fragmented.m4a"))
at := bytes.Index(b, []byte("sidx"))
copy(b[at:], "free")
d := audiotest.Open(t, b, "mp4")
if d.Len() != 88200 {
t.Fatalf("length %d", d.Len())
}
}
func TestNotMP4(t *testing.T) {
_, err := mp4.NewDecoder(bytes.NewReader([]byte("\x00\x00\x00\x10ftypM4A \x00\x00\x00\x00")))
if err == nil {
t.Fatal("decoded an MP4 with no movie header")
}
if _, err := mp4.NewDecoder(bytes.NewReader(nil)); err == nil {
t.Fatal("decoded nothing")
}
}
Binary file not shown.
+144
View File
@@ -0,0 +1,144 @@
package audio
import (
"errors"
"runtime"
"sync"
"time"
)
// A device is the system's audio output, opened by openDevice to hold
// about ahead of what is heard.
type device interface {
// write plays interleaved stereo frames after those written before,
// waiting while the device holds enough already. An error closes the
// device, and the output opens it again.
write(samples []float32) error
close()
}
// idleClose is how long the output stays open with nothing playing.
const idleClose = 5 * time.Second
var (
openOutput = openDevice // tests replace it
wake = make(chan struct{}, 1)
runOnce sync.Once
testMode bool // tests mix by hand
)
// wakeOutput starts the output, or tells it a voice started. The caller
// holds mu.
func wakeOutput() {
if testMode {
return
}
runOnce.Do(func() { go run() })
select {
case wake <- struct{}{}:
default:
}
}
func active() bool {
mu.Lock()
defer mu.Unlock()
return len(voices) > 0 && !testMode
}
// mixFor mixes into buf for an output open at latency lat, and reports
// whether anything plays; ok is false, and it mixes nothing, once tests
// mix by hand or the latency changed.
func mixFor(buf []float32, lat Latency) (busy, ok bool) {
mu.Lock()
defer mu.Unlock()
if testMode || latency != lat {
return false, false
}
return mixLocked(buf), true
}
// run opens the device while anything plays, and mixes into it.
func run() {
for {
for !active() {
<-wake
}
lat := outputLatency()
dev, n, err := openOutput(lat.ahead())
if err != nil {
setErr(err)
dev, n = newNullDevice(err != errUnsupported), nullFrames
// It holds nothing: what it takes is heard as it takes it.
setHeld(0)
} else {
setErr(nil)
setHeld(int64(lat.ahead() * sampleRate / time.Second))
}
buf := make([]float32, n*channels)
idle := time.Duration(0)
per := frames(int64(n), sampleRate)
for {
busy, ok := mixFor(buf, lat)
if !ok {
break
}
// write blocks in C, keeping the P, which the runtime would
// take back every 10 ms, waking more often after.
runtime.Gosched()
if err := dev.write(buf); err != nil {
// Lost, or a null device trying the real one again.
break
}
if busy {
idle = 0
} else if idle += per; idle >= idleClose {
break
}
}
dev.close()
}
}
var errUnsupported = errors.New("audio: no audio output on this platform")
// nullFrames is how many frames a null device takes at a time: 10 ms.
const nullFrames = sampleRate / 100
// A nullDevice plays nothing, on time: players still end when they would
// have. One standing in for a device that failed to open fails after a
// while, so that the output tries the device again.
type nullDevice struct {
next time.Time
retry time.Time
// now and sleep are its clock, which tests replace.
now func() time.Time
sleep func(time.Duration)
}
func newNullDevice(retry bool) *nullDevice {
d := &nullDevice{next: time.Now(), now: time.Now, sleep: time.Sleep}
if retry {
d.retry = d.next.Add(2 * time.Second)
}
return d
}
var errRetry = errors.New("audio: try the device again")
func (d *nullDevice) write(samples []float32) error {
now := d.now()
if !d.retry.IsZero() && now.After(d.retry) {
return errRetry
}
if now.Sub(d.next) > 100*time.Millisecond {
// Behind, as after a sleep: don't hurry to catch up.
d.next = now
}
d.next = d.next.Add(frames(int64(len(samples)/channels), sampleRate))
d.sleep(d.next.Sub(d.now()))
return nil
}
func (d *nullDevice) close() {}
+169
View File
@@ -0,0 +1,169 @@
//go:build !ios
package audio
import (
"fmt"
"sync"
"time"
"unsafe"
"github.com/ebitengine/purego"
)
// macOS plays through an Audio Queue on the default output, which follows
// it when it changes.
type audioStreamBasicDescription struct {
sampleRate float64
formatID uint32
formatFlags uint32
bytesPerPacket uint32
framesPerPacket uint32
bytesPerFrame uint32
channelsPerFrame uint32
bitsPerChannel uint32
reserved uint32
}
type audioQueueBuffer struct {
audioDataBytesCapacity uint32
audioData unsafe.Pointer
audioDataByteSize uint32
userData uintptr
packetDescCapacity uint32
packetDescs uintptr
packetDescCount uint32
}
const (
kAudioFormatLinearPCM = 0x6C70636D // 'lpcm'
kAudioFormatFlagIsFloat = 1
aqFrames = 512 // per buffer: 10.7 ms, as many as hold ahead
dispatchTimeNow = 0
)
var (
aqLoad sync.Once
aqErr error
audioQueueNewOutput func(format *audioStreamBasicDescription, callback uintptr, user uintptr, runLoop, runLoopMode uintptr, flags uint32, out *uintptr) int32
audioQueueAllocateBuffer func(q uintptr, size uint32, out **audioQueueBuffer) int32
audioQueueStart func(q uintptr, at uintptr) int32
audioQueueStop func(q uintptr, immediate bool) int32
audioQueueDispose func(q uintptr, immediate bool) int32
dispatchSemaphoreCreate func(value int) uintptr
dispatchRelease func(obj uintptr)
// Called on every buffer, through a cCaller.
audioQueueEnqueueBuffer uintptr
dispatchSemaphoreWait uintptr
dispatchTime uintptr
dispatchSemaphoreSignal uintptr // every queue's callback
)
func loadAudioToolbox() error {
aqLoad.Do(func() {
lib, err := purego.Dlopen("/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox", purego.RTLD_LAZY|purego.RTLD_GLOBAL)
if err != nil {
aqErr = err
return
}
purego.RegisterLibFunc(&audioQueueNewOutput, lib, "AudioQueueNewOutput")
purego.RegisterLibFunc(&audioQueueAllocateBuffer, lib, "AudioQueueAllocateBuffer")
purego.RegisterLibFunc(&audioQueueStart, lib, "AudioQueueStart")
purego.RegisterLibFunc(&audioQueueStop, lib, "AudioQueueStop")
purego.RegisterLibFunc(&audioQueueDispose, lib, "AudioQueueDispose")
purego.RegisterLibFunc(&dispatchSemaphoreCreate, purego.RTLD_DEFAULT, "dispatch_semaphore_create")
purego.RegisterLibFunc(&dispatchRelease, purego.RTLD_DEFAULT, "dispatch_release")
audioQueueEnqueueBuffer = cFunc(lib, "AudioQueueEnqueueBuffer")
dispatchSemaphoreWait = cFunc(purego.RTLD_DEFAULT, "dispatch_semaphore_wait")
dispatchSemaphoreSignal = cFunc(purego.RTLD_DEFAULT, "dispatch_semaphore_signal")
dispatchTime = cFunc(purego.RTLD_DEFAULT, "dispatch_time")
})
return aqErr
}
// An aqDevice is an Audio Queue whose callback is
// dispatch_semaphore_signal, its semaphore the user data (C on arm64 and
// x86-64 ignores the queue and buffer passed after it), so no Go runs on
// the queue's thread. The queue plays buffers in order: each signal frees
// the oldest.
type aqDevice struct {
q uintptr
sema uintptr
bufs []*audioQueueBuffer
next int // the buffer written next, the oldest enqueued once all are
queued int // buffers enqueued before the queue started
started bool
c cCaller
}
func openDevice(ahead time.Duration) (device, int, error) {
if err := loadAudioToolbox(); err != nil {
return nil, 0, err
}
desc := audioStreamBasicDescription{
sampleRate: sampleRate,
formatID: kAudioFormatLinearPCM,
formatFlags: kAudioFormatFlagIsFloat,
bytesPerPacket: channels * 4,
framesPerPacket: 1,
bytesPerFrame: channels * 4,
channelsPerFrame: channels,
bitsPerChannel: 32,
}
n := max(2, int((int64(ahead)*sampleRate/int64(time.Second)+aqFrames-1)/aqFrames))
// Fails only for a negative value.
d := &aqDevice{sema: dispatchSemaphoreCreate(0), bufs: make([]*audioQueueBuffer, n)}
if st := audioQueueNewOutput(&desc, dispatchSemaphoreSignal, d.sema, 0, 0, 0, &d.q); st != 0 {
dispatchRelease(d.sema)
return nil, 0, fmt.Errorf("audio: AudioQueueNewOutput failed (OSStatus %d)", st)
}
for i := range d.bufs {
if st := audioQueueAllocateBuffer(d.q, aqFrames*channels*4, &d.bufs[i]); st != 0 {
d.close()
return nil, 0, fmt.Errorf("audio: AudioQueueAllocateBuffer failed (OSStatus %d)", st)
}
}
return d, aqFrames, nil
}
func (d *aqDevice) write(samples []float32) error {
if d.started {
// Wait for the oldest buffer to play.
deadline := d.c.call(dispatchTime, dispatchTimeNow, uintptr(time.Second))
if d.c.call(dispatchSemaphoreWait, d.sema, deadline) != 0 {
// The queue stopped taking buffers, as when its device went.
return fmt.Errorf("audio: the audio queue stopped")
}
}
b := d.bufs[d.next]
d.next = (d.next + 1) % len(d.bufs)
copy(unsafe.Slice((*float32)(b.audioData), len(samples)), samples)
b.audioDataByteSize = uint32(len(samples) * 4)
// b is C memory, as a cCaller needs.
if st := int32(d.c.call(audioQueueEnqueueBuffer, d.q, uintptr(unsafe.Pointer(b)), 0, 0)); st != 0 {
return fmt.Errorf("audio: AudioQueueEnqueueBuffer failed (OSStatus %d)", st)
}
if !d.started {
// Start once every buffer holds something, not to begin with an
// underrun.
if d.queued++; d.queued == len(d.bufs) {
if st := audioQueueStart(d.q, 0); st != 0 {
return fmt.Errorf("audio: AudioQueueStart failed (OSStatus %d)", st)
}
d.started = true
}
}
return nil
}
func (d *aqDevice) close() {
// Synchronous: no callback runs once it returns.
audioQueueStop(d.q, true)
audioQueueDispose(d.q, true)
// Never below its initial value, which dispatch_release requires.
dispatchRelease(d.sema)
}
+183
View File
@@ -0,0 +1,183 @@
package audio
import (
"errors"
"fmt"
"syscall/js"
"time"
"unsafe"
)
// Browsers play through an AudioWorklet, which asks the page for a chunk
// whenever it used one up. One AudioContext serves the page for its life:
// closing the output suspends it. Pages may start audio only after the
// user interacted with them, so it resumes on the first input too.
const (
jsFrames = 1024 // per chunk: 21 ms
jsChunks = 3 // queued in the worklet to begin with, and at least
)
const worklet = `
class MyGoOutput extends AudioWorkletProcessor {
constructor() {
super();
this.queue = [];
this.offset = 0;
this.port.onmessage = (e) => this.queue.push(e.data);
for (let i = 0; i < %d; i++) this.port.postMessage(0);
}
process(inputs, outputs) {
const left = outputs[0][0], right = outputs[0][1];
let i = 0;
while (i < left.length) {
const chunk = this.queue[0];
if (!chunk) {
left.fill(0, i);
right.fill(0, i);
break;
}
const n = Math.min(left.length - i, chunk.length / 2 - this.offset);
for (let j = 0; j < n; j++) {
left[i + j] = chunk[2 * (this.offset + j)];
right[i + j] = chunk[2 * (this.offset + j) + 1];
}
i += n;
this.offset += n;
if (this.offset * 2 >= chunk.length) {
this.queue.shift();
this.offset = 0;
this.port.postMessage(0);
}
}
return true;
}
}
registerProcessor("mygo-output", MyGoOutput);
`
var (
jsContext js.Value
jsPort js.Value
jsCredits = make(chan struct{}, 32)
jsErr error
// jsAhead is how many chunks are queued in the worklet or asked for,
// and jsOwed how many it asks for that are to go unanswered, as the
// output holds less than it did.
jsAhead = jsChunks
jsOwed int
)
// jsSetup creates the page's AudioContext and its worklet, once: the
// context keeps the latency it began with, the worklet's queue follows
// the latency set since.
func jsSetup(ahead time.Duration) error {
if !jsContext.IsUndefined() || jsErr != nil {
return jsErr
}
class := js.Global().Get("AudioContext")
if !class.Truthy() {
jsErr = errors.New("audio: this browser has no AudioContext")
return jsErr
}
hint := "interactive"
if ahead >= LatencyPlayback.ahead() {
hint = "playback"
}
ctx := class.New(map[string]any{"sampleRate": sampleRate, "latencyHint": hint})
if !ctx.Get("audioWorklet").Truthy() {
jsErr = errors.New("audio: this browser has no AudioWorklet")
return jsErr
}
blob := js.Global().Get("Blob").New([]any{fmt.Sprintf(worklet, jsChunks)}, map[string]any{"type": "text/javascript"})
url := js.Global().Get("URL").Call("createObjectURL", blob)
done := make(chan error, 1)
var ok, fail js.Func
ok = js.FuncOf(func(this js.Value, args []js.Value) any {
done <- nil
return nil
})
fail = js.FuncOf(func(this js.Value, args []js.Value) any {
done <- fmt.Errorf("audio: loading the AudioWorklet failed: %s", js.Global().Get("String").Invoke(args[0]).String())
return nil
})
ctx.Get("audioWorklet").Call("addModule", url).Call("then", ok, fail)
err := <-done
ok.Release()
fail.Release()
js.Global().Get("URL").Call("revokeObjectURL", url)
if err != nil {
jsErr = err
return err
}
node := js.Global().Get("AudioWorkletNode").New(ctx, "mygo-output", map[string]any{
"numberOfInputs": 0,
"outputChannelCount": []any{channels},
})
node.Call("connect", ctx.Get("destination"))
jsPort = node.Get("port")
jsPort.Set("onmessage", js.FuncOf(func(this js.Value, args []js.Value) any {
select {
case jsCredits <- struct{}{}:
default:
}
return nil
}))
// The first input lets a page start audio.
resume := js.FuncOf(func(this js.Value, args []js.Value) any {
if jsContext.Get("state").String() == "suspended" && jsOpen {
jsContext.Call("resume")
}
return nil
})
for _, ev := range []string{"pointerdown", "keydown", "touchend"} {
js.Global().Call("addEventListener", ev, resume, map[string]any{"capture": true})
}
jsContext = ctx
return nil
}
// jsOpen is whether the output is open, which keeps the context running.
var jsOpen bool
type jsDevice struct{}
func openDevice(ahead time.Duration) (device, int, error) {
if err := jsSetup(ahead); err != nil {
return nil, 0, err
}
want := max(jsChunks, int((int64(ahead)*sampleRate/int64(time.Second)+jsFrames-1)/jsFrames))
if more := want - jsAhead; more > 0 {
// Asks the owed ones answer first.
cancel := min(jsOwed, more)
jsOwed -= cancel
for range more - cancel {
jsCredits <- struct{}{}
}
} else {
jsOwed -= more
}
jsAhead = want
jsOpen = true
jsContext.Call("resume")
return jsDevice{}, jsFrames, nil
}
func (jsDevice) write(samples []float32) error {
// A suspended context, until an input lets the page play, asks for
// nothing: the output waits without mixing ahead.
for ; jsOwed > 0; jsOwed-- {
<-jsCredits
}
<-jsCredits
a := js.Global().Get("Float32Array").New(len(samples))
js.CopyBytesToJS(js.Global().Get("Uint8Array").New(a.Get("buffer")), unsafe.Slice((*byte)(unsafe.Pointer(&samples[0])), len(samples)*4))
jsPort.Call("postMessage", a, []any{a.Get("buffer")})
return nil
}
func (jsDevice) close() {
jsOpen = false
jsContext.Call("suspend")
}
+190
View File
@@ -0,0 +1,190 @@
//go:build linux && !android && (amd64 || arm64) && !android
package audio
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"unsafe"
"github.com/ebitengine/purego"
)
// Linux plays through PulseAudio's simple API, which PipeWire serves as
// well, or else ALSA's default device. Both block while the device holds
// enough, from the output's goroutine.
const linuxFrames = sampleRate / 100 // per write: 10 ms
var (
pulseLoad sync.Once
pulseErr error
paSimpleNew func(server, name *byte, dir int32, dev, stream *byte, spec *paSampleSpec, chmap, attr unsafe.Pointer, err *int32) uintptr
paSimpleWrite uintptr // through a cCaller, on every write
paSimpleFree func(s uintptr)
paStrerror func(err int32) string
alsaLoad sync.Once
alsaErr error
sndPcmOpen func(pcm *uintptr, name *byte, stream int32, mode int32) int32
sndPcmSetParams func(pcm uintptr, format, access int32, channels, rate uint32, softResample int32, latency uint32) int32
sndPcmWritei uintptr // through a cCaller, on every write
sndPcmRecover func(pcm uintptr, err int32, silent int32) int32
sndPcmClose func(pcm uintptr) int32
sndStrerror func(err int32) string
)
type paSampleSpec struct {
format int32
rate uint32
channels uint8
}
type paBufferAttr struct {
maxLength, tLength, preBuf, minReq, fragSize uint32
}
const (
paStreamPlayback = 1
paSampleFloat32LE = 5
sndPcmStreamPlayback = 0
sndPcmFormatFloatLE = 14
sndPcmAccessRWInterleaved = 3
)
func cstr(s string) *byte {
b := append([]byte(s), 0)
return &b[0]
}
func appName() string {
if exe, err := os.Executable(); err == nil {
return filepath.Base(exe)
}
return "mygo"
}
func openDevice(ahead time.Duration) (device, int, error) {
d, perr := openPulse(ahead)
if perr == nil {
return d, linuxFrames, nil
}
d, aerr := openALSA(ahead)
if aerr == nil {
return d, linuxFrames, nil
}
return nil, 0, errors.Join(perr, aerr)
}
type pulseDevice struct {
s uintptr
code int32 // pa_simple_write's error
c cCaller
}
func openPulse(ahead time.Duration) (device, error) {
pulseLoad.Do(func() {
lib, err := purego.Dlopen("libpulse-simple.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
pulseErr = err
return
}
purego.RegisterLibFunc(&paSimpleNew, lib, "pa_simple_new")
paSimpleWrite = cFunc(lib, "pa_simple_write")
purego.RegisterLibFunc(&paSimpleFree, lib, "pa_simple_free")
purego.RegisterLibFunc(&paStrerror, lib, "pa_strerror")
})
if pulseErr != nil {
return nil, pulseErr
}
spec := paSampleSpec{format: paSampleFloat32LE, rate: sampleRate, channels: channels}
// ahead, asking for more every 10 ms.
const frame = channels * 4
attr := paBufferAttr{
maxLength: ^uint32(0),
tLength: uint32(int64(ahead) * sampleRate / int64(time.Second) * frame),
preBuf: ^uint32(0),
minReq: linuxFrames * frame,
fragSize: ^uint32(0),
}
var code int32
name := appName()
s := paSimpleNew(nil, cstr(name), paStreamPlayback, nil, cstr(name), &spec, nil, unsafe.Pointer(&attr), &code)
if s == 0 {
return nil, fmt.Errorf("audio: PulseAudio: %s", paStrerror(code))
}
return &pulseDevice{s: s}, nil
}
func (d *pulseDevice) write(samples []float32) error {
// samples and d.code are on the heap, as a cCaller needs.
r := int32(d.c.call(paSimpleWrite, d.s, uintptr(unsafe.Pointer(&samples[0])), uintptr(len(samples)*4), uintptr(unsafe.Pointer(&d.code))))
runtime.KeepAlive(samples)
if r < 0 {
return fmt.Errorf("audio: PulseAudio: %s", paStrerror(d.code))
}
return nil
}
func (d *pulseDevice) close() { paSimpleFree(d.s) }
type alsaDevice struct {
pcm uintptr
c cCaller
}
func openALSA(ahead time.Duration) (device, error) {
alsaLoad.Do(func() {
lib, err := purego.Dlopen("libasound.so.2", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
alsaErr = err
return
}
purego.RegisterLibFunc(&sndPcmOpen, lib, "snd_pcm_open")
purego.RegisterLibFunc(&sndPcmSetParams, lib, "snd_pcm_set_params")
sndPcmWritei = cFunc(lib, "snd_pcm_writei")
purego.RegisterLibFunc(&sndPcmRecover, lib, "snd_pcm_recover")
purego.RegisterLibFunc(&sndPcmClose, lib, "snd_pcm_close")
purego.RegisterLibFunc(&sndStrerror, lib, "snd_strerror")
})
if alsaErr != nil {
return nil, alsaErr
}
var pcm uintptr
if e := sndPcmOpen(&pcm, cstr("default"), sndPcmStreamPlayback, 0); e < 0 {
return nil, fmt.Errorf("audio: ALSA: %s", sndStrerror(e))
}
if e := sndPcmSetParams(pcm, sndPcmFormatFloatLE, sndPcmAccessRWInterleaved, channels, sampleRate, 1, uint32(ahead.Microseconds())); e < 0 {
sndPcmClose(pcm)
return nil, fmt.Errorf("audio: ALSA: %s", sndStrerror(e))
}
return &alsaDevice{pcm: pcm}, nil
}
func (d *alsaDevice) write(samples []float32) error {
for len(samples) > 0 {
// samples is on the heap, as a cCaller needs.
n := int(d.c.call(sndPcmWritei, d.pcm, uintptr(unsafe.Pointer(&samples[0])), uintptr(len(samples)/channels)))
runtime.KeepAlive(samples)
if n < 0 {
// An underrun or a suspend, recovered from by preparing the
// device again.
if e := sndPcmRecover(d.pcm, int32(n), 1); e < 0 {
return fmt.Errorf("audio: ALSA: %s", sndStrerror(e))
}
continue
}
samples = samples[n*channels:]
}
return nil
}
func (d *alsaDevice) close() { sndPcmClose(d.pcm) }
+35
View File
@@ -0,0 +1,35 @@
//go:build ios || android
package audio
import (
"time"
"unsafe"
"github.com/egoist/mygo/internal/mobile"
)
// Phones play through their hosts: AVAudioEngine on iOS, AudioTrack on Android.
// Writes block on this goroutine's thread, in the host, as the output fills.
type mobileDevice struct{}
// mobileFrames is how many frames go in a write: 10 ms.
const mobileFrames = sampleRate / 100
func openDevice(ahead time.Duration) (device, int, error) {
if err := mobile.AudioOpen(sampleRate, int(ahead/time.Millisecond)); err != nil {
return nil, 0, err
}
return mobileDevice{}, mobileFrames, nil
}
func (mobileDevice) write(samples []float32) error {
if len(samples) == 0 {
return nil
}
b := unsafe.Slice((*byte)(unsafe.Pointer(&samples[0])), len(samples)*4)
return mobile.AudioWrite(b)
}
func (mobileDevice) close() { mobile.AudioClose() }
+7
View File
@@ -0,0 +1,7 @@
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !js && !ios && !android
package audio
import "time"
func openDevice(ahead time.Duration) (device, int, error) { return nil, 0, errUnsupported }
+269
View File
@@ -0,0 +1,269 @@
//go:build windows && (amd64 || arm64)
package audio
import (
"errors"
"fmt"
"runtime"
"syscall"
"time"
"unsafe"
)
// Windows plays through WASAPI in shared mode on the default output,
// opened again when the default changes or the device goes. Every call
// runs on the output's thread, locked, in COM's multithreaded apartment.
type guid struct {
data1 uint32
data2 uint16
data3 uint16
data4 [8]byte
}
var (
clsidMMDeviceEnumerator = guid{0xbcde0395, 0xe52f, 0x467c, [8]byte{0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e}}
iidIMMDeviceEnumerator = guid{0xa95664d2, 0x9614, 0x4f35, [8]byte{0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}}
iidIAudioClient = guid{0x1cb9ad4c, 0xdbfa, 0x4c32, [8]byte{0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2}}
iidIAudioRenderClient = guid{0xf294acfc, 0x3146, 0x4483, [8]byte{0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}}
ksDataFormatSubtypeFloat = guid{0x00000003, 0x0000, 0x0010, [8]byte{0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}
ole32 = syscall.NewLazyDLL("ole32.dll")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procCoInitializeEx = ole32.NewProc("CoInitializeEx")
procCoCreateInstance = ole32.NewProc("CoCreateInstance")
procCoTaskMemFree = ole32.NewProc("CoTaskMemFree")
procCreateEventW = kernel32.NewProc("CreateEventW")
procCloseHandle = kernel32.NewProc("CloseHandle")
comInitialized bool
errDefaultDeviceChanged = errors.New("audio: the default output changed")
errAudioClientUnresponded = errors.New("audio: the audio client stopped asking for frames")
)
type waveFormatExtensible struct {
formatTag uint16
channels uint16
samplesPerSec uint32
avgBytesPerSec uint32
blockAlign uint16
bitsPerSample uint16
size uint16
validBits uint16
channelMask uint32
subFormat guid
}
const (
clsctxAll = 0x17
coinitMultithreaded = 0
eRender = 0
eConsole = 0
waveFormatExtensibleTag = 0xfffe
speakerFrontLeft = 0x1
speakerFrontRight = 0x2
audclntShareModeShared = 0
audclntStreamFlagsEventCB = 0x00040000
audclntStreamFlagsNoPersist = 0x00080000
audclntStreamFlagsAutoConvert = 0x80000000
audclntStreamFlagsSRCQuality = 0x08000000
waitObject0 = 0
windowsFrames = sampleRate / 100 // per write: 10 ms
)
// comCall calls method i of the COM interface obj. Pointers converted to
// uintptr in the call stay valid until it returns (go:uintptrescapes),
// which moves what they point to, and args, to the heap: write calls
// syscall.SyscallN and method instead.
//
//go:uintptrescapes
func comCall(obj uintptr, i int, args ...uintptr) uintptr {
var a [16]uintptr
a[0] = obj
n := copy(a[1:], args)
r, _, _ := syscall.SyscallN(method(obj, i), a[:n+1]...)
return r
}
// method returns the address of method i of the COM interface obj, to
// call with syscall.SyscallN, obj first. SyscallN keeps pointers
// converted to uintptr in its call valid without moving them to the heap
// (go:uintptrkeepalive), so such a call allocates nothing.
func method(obj uintptr, i int) uintptr {
vtbl := *(*uintptr)(native(obj))
return *(*uintptr)(unsafe.Add(native(vtbl), i*int(unsafe.Sizeof(uintptr(0)))))
}
// native converts a native address to a pointer.
func native(addr uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&addr)) }
func failed(hr uintptr) bool { return int32(uint32(hr)) < 0 }
func hresult(what string, hr uintptr) error {
return fmt.Errorf("audio: %s failed (HRESULT %#08x)", what, uint32(hr))
}
func release(obj uintptr) {
if obj != 0 {
comCall(obj, 2)
}
}
type wasapiDevice struct {
enumerator, client, render uintptr
event uintptr
frames uint32 // the client's buffer
id string // the device's endpoint ID
checked time.Time
}
// defaultID returns the endpoint ID of the default output.
func defaultID(enumerator uintptr) (string, error) {
var dev uintptr
if hr := comCall(enumerator, 4, eRender, eConsole, uintptr(unsafe.Pointer(&dev))); failed(hr) {
if uint32(hr) == 0x80070490 { // E_NOTFOUND
return "", errors.New("audio: no audio output")
}
return "", hresult("GetDefaultAudioEndpoint", hr)
}
defer release(dev)
var p *uint16
if hr := comCall(dev, 5, uintptr(unsafe.Pointer(&p))); failed(hr) {
return "", hresult("IMMDevice.GetId", hr)
}
defer procCoTaskMemFree.Call(uintptr(unsafe.Pointer(p)))
n := 0
for *(*uint16)(unsafe.Add(unsafe.Pointer(p), n*2)) != 0 {
n++
}
return syscall.UTF16ToString(unsafe.Slice(p, n)), nil
}
func openDevice(ahead time.Duration) (device, int, error) {
if !comInitialized {
// COM is initialized per thread: run's goroutine keeps this one.
runtime.LockOSThread()
// S_FALSE, already initialized, succeeds as well.
if hr, _, _ := procCoInitializeEx.Call(0, coinitMultithreaded); failed(hr) {
runtime.UnlockOSThread()
return nil, 0, hresult("CoInitializeEx", hr)
}
comInitialized = true
}
d := &wasapiDevice{}
if err := d.open(ahead); err != nil {
d.close()
return nil, 0, err
}
return d, windowsFrames, nil
}
func (d *wasapiDevice) open(ahead time.Duration) error {
if hr, _, _ := procCoCreateInstance.Call(uintptr(unsafe.Pointer(&clsidMMDeviceEnumerator)), 0, clsctxAll,
uintptr(unsafe.Pointer(&iidIMMDeviceEnumerator)), uintptr(unsafe.Pointer(&d.enumerator))); failed(hr) {
return hresult("CoCreateInstance(MMDeviceEnumerator)", hr)
}
var dev uintptr
if hr := comCall(d.enumerator, 4, eRender, eConsole, uintptr(unsafe.Pointer(&dev))); failed(hr) {
if uint32(hr) == 0x80070490 { // E_NOTFOUND
return errors.New("audio: no audio output")
}
return hresult("GetDefaultAudioEndpoint", hr)
}
defer release(dev)
id, err := defaultID(d.enumerator)
if err != nil {
return err
}
d.id = id
if hr := comCall(dev, 3, uintptr(unsafe.Pointer(&iidIAudioClient)), clsctxAll, 0, uintptr(unsafe.Pointer(&d.client))); failed(hr) {
return hresult("IMMDevice.Activate", hr)
}
f := waveFormatExtensible{
formatTag: waveFormatExtensibleTag,
channels: channels,
samplesPerSec: sampleRate,
avgBytesPerSec: sampleRate * channels * 4,
blockAlign: channels * 4,
bitsPerSample: 32,
size: 22,
validBits: 32,
channelMask: speakerFrontLeft | speakerFrontRight,
subFormat: ksDataFormatSubtypeFloat,
}
// ahead, converted to the device's format by WASAPI's resampler.
duration := uintptr(ahead / 100) // in 100 ns
flags := uintptr(audclntStreamFlagsEventCB | audclntStreamFlagsNoPersist | audclntStreamFlagsAutoConvert | audclntStreamFlagsSRCQuality)
if hr := comCall(d.client, 3, audclntShareModeShared, flags, duration, 0, uintptr(unsafe.Pointer(&f)), 0); failed(hr) {
return hresult("IAudioClient.Initialize", hr)
}
if hr := comCall(d.client, 4, uintptr(unsafe.Pointer(&d.frames))); failed(hr) {
return hresult("IAudioClient.GetBufferSize", hr)
}
if hr := comCall(d.client, 14, uintptr(unsafe.Pointer(&iidIAudioRenderClient)), uintptr(unsafe.Pointer(&d.render))); failed(hr) {
return hresult("IAudioClient.GetService", hr)
}
ev, _, err := procCreateEventW.Call(0, 0, 0, 0)
if ev == 0 {
return fmt.Errorf("audio: CreateEvent failed: %v", err)
}
d.event = ev
if hr := comCall(d.client, 13, d.event); failed(hr) {
return hresult("IAudioClient.SetEventHandle", hr)
}
if hr := comCall(d.client, 10); failed(hr) {
return hresult("IAudioClient.Start", hr)
}
d.checked = time.Now()
return nil
}
func (d *wasapiDevice) write(samples []float32) error {
n := uint32(len(samples) / channels)
deadline := time.Now().Add(time.Second)
// Called on every write: through syscall.SyscallN, not comCall, so
// padding and data stay on the stack.
for {
var padding uint32
if hr, _, _ := syscall.SyscallN(method(d.client, 6), d.client, uintptr(unsafe.Pointer(&padding))); failed(hr) {
return hresult("IAudioClient.GetCurrentPadding", hr)
}
if padding <= d.frames && d.frames-padding >= n {
break
}
if time.Now().After(deadline) {
return errAudioClientUnresponded
}
syscall.WaitForSingleObject(syscall.Handle(d.event), 100)
}
var data unsafe.Pointer
if hr, _, _ := syscall.SyscallN(method(d.render, 3), d.render, uintptr(n), uintptr(unsafe.Pointer(&data))); failed(hr) {
return hresult("IAudioRenderClient.GetBuffer", hr)
}
copy(unsafe.Slice((*float32)(data), len(samples)), samples)
if hr, _, _ := syscall.SyscallN(method(d.render, 4), d.render, uintptr(n), 0); failed(hr) {
return hresult("IAudioRenderClient.ReleaseBuffer", hr)
}
// The default output changing (headphones plugged in, a choice in
// Settings) moves a shared stream nowhere: open the new one.
if time.Since(d.checked) > 500*time.Millisecond {
d.checked = time.Now()
if id, err := defaultID(d.enumerator); err != nil || id != d.id {
return errDefaultDeviceChanged
}
}
return nil
}
func (d *wasapiDevice) close() {
if d.client != 0 {
comCall(d.client, 11)
}
release(d.render)
release(d.client)
release(d.enumerator)
d.render, d.client, d.enumerator = 0, 0, 0
if d.event != 0 {
procCloseHandle.Call(d.event)
d.event = 0
}
}
+138
View File
@@ -0,0 +1,138 @@
package audio
import (
"testing"
"time"
)
// heldFrames is what the output holds ahead in these tests: 100 ms.
const heldFrames = sampleRate / 10
// atFrame checks that p's position is source frame f.
func atFrame(t *testing.T, p *Player, f int64, when string) {
t.Helper()
got, want := p.Position(), frames(f, sampleRate)
if d := got - want; d < -time.Microsecond || d > time.Microsecond {
t.Errorf("%s: Position = %v, want %v (frame %d)", when, got, want, f)
}
}
func longSound() *Sound { return NewSound(sampleRate, 1, make([]float32, 10*sampleRate)) }
// Position is what is heard: it stands still while the device fills, and
// then lags what was mixed by what the device holds.
func TestPositionIsHeard(t *testing.T) {
setup(t)
hold(heldFrames)
p := longSound().Play()
render(heldFrames / 2)
atFrame(t, p, 0, "half the device filled")
render(heldFrames / 2)
atFrame(t, p, 0, "the device filled")
render(3000)
atFrame(t, p, 3000, "3000 frames on")
// A device opening again holds nothing of what was mixed before,
// which it dropped: the position goes on from what was mixed.
hold(heldFrames)
atFrame(t, p, heldFrames+3000, "a device opened again")
}
// Right after a seek, Position is where it seeked to, and goes on from
// there once the device plays what was mixed since.
func TestPositionHoldsAtSeek(t *testing.T) {
setup(t)
hold(heldFrames)
p := longSound().Play()
render(2 * heldFrames)
p.Seek(2 * time.Second)
atFrame(t, p, 2*sampleRate, "right after Seek")
render(heldFrames - 100)
atFrame(t, p, 2*sampleRate, "before the seek is heard")
render(600)
atFrame(t, p, 2*sampleRate+500, "500 frames into the seek heard")
p.Stop()
atFrame(t, p, 0, "after Stop")
}
// Paused, a player goes on for as long as the device plays what it holds,
// then stands still; playing again, it stands still until that is heard.
func TestPositionPlaysOutPause(t *testing.T) {
setup(t)
hold(heldFrames)
p := longSound().Play()
render(10000)
p.Pause()
atFrame(t, p, 10000-heldFrames, "at Pause")
render(2000)
atFrame(t, p, 12000-heldFrames, "2000 frames after Pause")
// It faded out over rampFrames after the pause.
render(2 * heldFrames)
atFrame(t, p, 10000+rampFrames, "played out")
render(1000)
atFrame(t, p, 10000+rampFrames, "paused, played out")
p.Play()
render(heldFrames - 100)
atFrame(t, p, 10000+rampFrames, "before playing again is heard")
render(600)
atFrame(t, p, 10000+rampFrames+500, "500 frames into playing again")
}
// With a speed, what the device holds is that many more frames of the
// source.
func TestPositionAtSpeed(t *testing.T) {
setup(t)
hold(heldFrames)
p := longSound().NewPlayer().SetSpeed(2)
p.Play()
render(3 * heldFrames)
atFrame(t, p, 4*heldFrames, "200 ms heard at speed 2")
p.SetSpeed(0.5)
render(heldFrames * 3 / 2)
// Of the 150 ms heard since, 100 ms were mixed at 2, 50 ms at 0.5.
atFrame(t, p, 4*heldFrames+2*heldFrames+heldFrames/4, "after slowing down")
}
// A looping player's position heard comes back to the loop's start.
func TestPositionWrapsLoops(t *testing.T) {
setup(t)
hold(50)
p := NewSound(sampleRate, 1, ramp(100)).NewPlayer().
SetLoopRange(frames(30, sampleRate), frames(60, sampleRate))
p.Play()
render(160)
atFrame(t, p, 50, "110 frames heard")
render(10)
// 120 heard: 60, then two loops of 30.
atFrame(t, p, 30, "120 frames heard")
}
// A stream that is late stands still while it is, as heard.
func TestLateStreamPositionIsHeard(t *testing.T) {
setup(t)
hold(heldFrames)
src := &lateSource{ready: 1000}
p := newPlayer(src, sampleRate, 1, -1)
p.Play()
// It plays 998 frames of the 1000, reading two ahead to interpolate,
// then waits for 1002.
render(heldFrames + 2000)
src.ready = 1 << 30
render(500)
atFrame(t, p, 998, "the device playing the wait")
render(heldFrames)
atFrame(t, p, 998+500, "the wait heard")
}
// A lateSource has ready frames decoded, and then waits for more.
type lateSource struct{ ready int }
func (s *lateSource) read(dst []float32) (int, bool) {
n := min(len(dst), s.ready)
clear(dst[:n])
s.ready -= n
return n, false
}
func (*lateSource) seek(int64) {}
func (*lateSource) setLoop(bool, int64, int64) {}
func (*lateSource) close() {}
+210
View File
@@ -0,0 +1,210 @@
package audio
import (
"math"
"sync"
)
// A voice that plays more than one source frame an output frame, a sound
// of more than 48 kHz or one sped up, would fold what it has above the
// output's Nyquist frequency, 24 kHz, back below it: a spline does not
// remove it. Such a voice interpolates with a windowed sinc instead, a
// low-pass at the output's rate: a Kaiser window over sincReach output
// frames either side, flat to 20 kHz, -6 dB at 22 kHz and at least 80 dB
// down from 24 kHz. In source frames, the kernel is as much wider as the
// source is faster, and its cutoff as much lower.
const (
sincReach = 32 // output frames either side
sincCutoff = 22000.0 / sampleRate // of the output's rate
sincBeta = 7.857 // the Kaiser window's: 80 dB
sincRes = 256 // entries of sincTable an output frame
// The kernels a voice keeps for the phases between two source frames
// (as many an output frame, so fewer the faster), and interpolates
// between.
sincPhases = 128
// The most source frames the kernel reaches either side: the whole
// kernel up to 8 source frames an output frame. Faster, the window
// narrows to these, which widens the band from what it passes to what
// it stops as much, and the cutoff comes down for that band to end at
// 24 kHz still, as far as half of it.
maxReach = 256
// The frames a voice keeps around where it is: enough for the kernel
// to grow to maxReach while it holds frames as far ahead.
ringFrames = 2 * maxReach
// The most weights a sincBank holds at any step: (rows+1)×2×reach.
maxWeights = 2*sincPhases*sincReach + 2*sincPhases + 4*maxReach + 4
)
// A sincBank is the kernel at a step, in source frames an output frame:
// the weights of the 2×reach frames from reach-1 before the output's to
// reach after it, for each of rows+1 phases from 0 to 1, each with the
// difference to the next phase's.
type sincBank struct {
step float64
reach int
rows int
cutoff float64 // of the output's rate
w [][2]float32
}
// set makes the bank's kernels those at step, unless they are.
func (b *sincBank) set(step float64) {
if b.step == step {
return
}
if b.w == nil {
b.w = make([][2]float32, 0, maxWeights)
}
b.step = step
b.reach = min(int(math.Ceil(sincReach*step)), maxReach)
b.rows = int(math.Ceil(sincPhases / step))
b.cutoff = sincCutoff
if sincReach*step > maxReach {
// Half the band from what it passes to what it stops, as many
// times wider as the window is narrower.
half := (0.5 - sincCutoff) * sincReach * step / maxReach
b.cutoff = max(0.5-half, half)
}
n := 2 * b.reach
b.w = b.w[:(b.rows+1)*n]
for p := range b.rows + 1 {
b.kernel(b.w[p*n:(p+1)*n], float64(p)/float64(b.rows))
}
for p := range b.rows {
w, next := b.w[p*n:(p+1)*n], b.w[(p+1)*n:(p+2)*n]
for j := range w {
w[j][1] = next[j][0] - w[j][0]
}
}
}
// kernel sets the weights in w for an output phase past the frame reach-1
// after w's first, summing to 1 so that what is constant stays as it is.
func (b *sincBank) kernel(w [][2]float32, phase float64) {
d0 := float64(1-b.reach) - phase // source frames from the output to w's first
var sum float64
if sincReach*b.step <= maxReach {
t := sincTable()
dx := sincRes / b.step
for j := range w {
x := math.Abs(d0+float64(j)) * dx
i := int(x)
h := float64(t[i][0]) + (x-float64(i))*float64(t[i][1])
w[j][0] = float32(h)
sum += h
}
} else {
// The ring cannot hold the whole kernel: the sinc at the cutoff,
// by rotation from one frame to the next, in a window as wide as
// the frames reached.
k := kaiserTable()
end := len(k) - 1
dk := float64(end) / float64(b.reach)
a := math.Pi * 2 * b.cutoff / b.step // radians a source frame
s, c := math.Sincos(a * d0)
sa, ca := math.Sincos(a)
for j := range w {
d := d0 + float64(j)
h := 0.0
if u := math.Abs(d) * dk; int(u) < end {
i := int(u)
h = k[i] + (u-float64(i))*(k[i+1]-k[i])
if th := a * d; math.Abs(th) > 1e-9 {
h *= s / th
}
}
w[j][0] = float32(h)
sum += h
s, c = s*ca+c*sa, c*ca-s*sa
}
}
for j := range w {
w[j][0] = float32(float64(w[j][0]) / sum)
}
}
// sinc interpolates the voice's frames where the output is with its bank's
// kernel, between those of the phases either side.
func (v *voice) sinc() (l, r float32) {
b := &v.bank
n := 2 * b.reach
u := v.phase * float64(b.rows)
p := int(u)
f := float32(u - float64(p))
w := b.w[p*n : (p+1)*n]
x := v.ring[(v.idx-int64(b.reach)+1)&(ringFrames-1):]
x = x[:len(w)]
switch {
case v.mono:
for j, e := range w {
l += (e[0] + f*e[1]) * x[j][0]
}
return l, l
case f == 0:
// On a phase of the bank, as every frame at a whole number of
// source frames an output frame.
for j, e := range w {
l += e[0] * x[j][0]
r += e[0] * x[j][1]
}
default:
for j, e := range w {
h, s := e[0]+f*e[1], x[j]
l += h * s[0]
r += h * s[1]
}
}
return l, r
}
// sincTable is the kernel from 0 to sincReach output frames, sincRes
// entries a frame, each with the difference to the next for interpolating
// between them, and zeros as far after as a kernel's last frame reaches.
var sincTable = sync.OnceValue(func() [][2]float32 {
n := sincReach * sincRes
t := make([][2]float32, n+2*sincRes)
next := 0.0
for i := n; i >= 0; i-- {
x := float64(i) / sincRes
h := sinc(2*sincCutoff*x) * kaiser(x/sincReach)
t[i] = [2]float32{float32(h), float32(next - h)}
next = h
}
return t
})
// kaiserTable is the window from its middle to its edge, for kernels the
// ring cannot hold whole.
var kaiserTable = sync.OnceValue(func() []float64 {
t := make([]float64, 1025)
for i := range t {
t[i] = kaiser(float64(i) / float64(len(t)-1))
}
return t
})
func sinc(x float64) float64 {
if x == 0 {
return 1
}
return math.Sin(math.Pi*x) / (math.Pi * x)
}
// kaiser returns the Kaiser window at u, from -1 to 1.
func kaiser(u float64) float64 {
return bessel0(sincBeta*math.Sqrt(max(1-u*u, 0))) / bessel0(sincBeta)
}
// bessel0 returns the modified Bessel function of the first kind, of order
// zero.
func bessel0(x float64) float64 {
sum, term := 1.0, 1.0
for k := 1; term > 1e-12*sum; k++ {
h := x / 2 / float64(k)
term *= h * h
sum += term
}
return sum
}
+212
View File
@@ -0,0 +1,212 @@
package audio
import (
"fmt"
"math"
"testing"
"time"
)
// Mixing one looping stereo voice, a buffer of 10 ms at a time, at the
// rates sounds come in.
func BenchmarkMix(b *testing.B) {
for _, rate := range []int{44100, 48000, 88200, 96000, 192000} {
b.Run(fmt.Sprint(rate), func(b *testing.B) {
mu.Lock()
testMode = true
voices = nil
volume = 1
mu.Unlock()
NewSound(rate, 2, sine(rate, 1, 440, 660)).NewPlayer().SetLoop(true).Play()
buf := make([]float32, sampleRate/100*channels)
// The first allocates the voice's ring, and its kernels.
mix(buf)
b.ReportAllocs()
for b.Loop() {
mix(buf)
}
})
}
}
func TestDownsampleAlias(t *testing.T) {
for _, tc := range []struct {
name string
rate, tone, alias int // Hz
}{
{"88k2", 88200, 30000, 18000},
{"96k", 96000, 30000, 18000},
{"192k", 192000, 90000, 6000},
} {
t.Run(tc.name, func(t *testing.T) {
setup(t)
input := make([]float32, 2*tc.rate)
for i := range tc.rate {
phase := 2 * math.Pi * float64(i) / float64(tc.rate)
input[2*i] = float32(0.1 * math.Sin(6000*phase))
input[2*i+1] = float32(0.1 * math.Sin(float64(tc.tone)*phase))
}
NewSound(tc.rate, 2, input).Play()
out := render(9600)[2*4800:] // Analyze 100 ms after startup.
pass := measuredAmplitude(out, 0, 6000)
alias := measuredAmplitude(out, 1, tc.alias)
t.Logf("control %.6f, alias %.6f", pass, alias)
if math.Abs(pass-0.1) > 0.005 {
t.Fatalf("invalid passband control: %g", pass)
}
if alias > 0.1*0.001 {
t.Errorf("alias at %d Hz exceeds -60 dB relative to input", tc.alias)
}
})
}
}
// measuredAmplitude returns the peak amplitude of channel ch of out at hz.
func measuredAmplitude(out []float32, ch, hz int) float64 {
var re, im float64
n := len(out) / 2
for i := range n {
phase := 2 * math.Pi * float64(hz*i) / 48000
x := float64(out[2*i+ch])
re += x * math.Cos(phase)
im += x * math.Sin(phase)
}
return 2 * math.Hypot(re, im) / float64(n)
}
// fold returns the frequency that hz plays at at the output's rate.
func fold(hz int) int {
hz %= sampleRate
return min(hz, sampleRate-hz)
}
// Downsampled, what is below 20 kHz plays as it is, within 0.1 dB, and
// where the source is.
func TestDownsamplePassband(t *testing.T) {
for _, rate := range []int{88200, 96000, 192000} {
for _, hz := range [][2]float64{{1000, 15000}, {6000, 20000}} {
setup(t)
p := NewSound(rate, 2, sine(rate, 0.5, hz[0], hz[1])).Play()
out := render(9600)
for c, f := range hz {
got := measuredAmplitude(out[2*4800:], c, int(f))
if db := 20 * math.Log10(got/0.5); math.Abs(db) > 0.1 {
t.Errorf("%d Hz at %d Hz plays at %+.3f dB", int(f), rate, db)
}
}
if got, want := p.Position(), 200*time.Millisecond; got-want > time.Microsecond || want-got > time.Microsecond {
t.Errorf("at %d Hz: Position = %v, want %v", rate, got, want)
}
}
}
}
// Downsampled, at the sound's rate or its speed, what is above 24 kHz
// does not fold back below it: 80 dB down from 24.5 kHz.
func TestDownsampleStopband(t *testing.T) {
// A sound at rate played at speed: a tone of pass Hz on the left, one
// of stop Hz on the right.
type tones struct {
rate int
speed float64
pass, stop int
}
var cases []tones
for _, rate := range []int{88200, 96000, 192000} {
for hz := 24500; hz < rate/2; hz += 3000 + hz/4 {
cases = append(cases, tones{rate, 1, 1000, hz})
}
}
cases = append(cases,
tones{48000, 1.25, 1000, 20000}, // 25 kHz
tones{44100, 2, 1000, 15000}, // 30 kHz
tones{96000, 3, 1000, 9000}, // 27 kHz
// Wider kernels than the ring holds.
tones{48000, 12, 1000, 2500}, // 30 kHz
tones{96000, 16, 500, 2000}, // 32 kHz
tones{192000, 16, 250, 4000}, // 64 kHz
tones{96000, 16, 500, 1580}, // 25.3 kHz
)
for _, tc := range cases {
setup(t)
p := NewSound(tc.rate, 2, sine(tc.rate, 0.25*tc.speed, float64(tc.pass), float64(tc.stop))).NewPlayer()
p.SetSpeed(tc.speed).Play()
out := render(9600)[2*4800:]
heard := int(float64(tc.stop) * tc.speed)
pass := measuredAmplitude(out, 0, int(float64(tc.pass)*tc.speed))
alias := measuredAmplitude(out, 1, fold(heard))
if db := 20 * math.Log10(pass/0.5); math.Abs(db) > 0.1 {
t.Errorf("%d Hz at %v×: %v Hz plays at %+.3f dB", tc.rate, tc.speed, float64(tc.pass)*tc.speed, db)
}
if db := 20 * math.Log10(alias/0.5); db > -80 {
t.Errorf("%d Hz at %v×: %d Hz folds to %d Hz at %.1f dB", tc.rate, tc.speed, heard, fold(heard), db)
}
}
}
// Downsampling goes on from one buffer to the next as if it mixed them
// all at once.
func TestDownsampleAcrossBuffers(t *testing.T) {
const n = 9600
samples := sine(88200, 0.2, 1000, 17000)
for i := 1000; i < 1100; i++ {
// A step, which rings.
samples[2*i] += 0.3
}
setup(t)
NewSound(88200, 2, samples).Play()
whole := make([]float32, n*channels)
mix(whole)
setup(t)
NewSound(88200, 2, samples).Play()
parts := make([]float32, n*channels)
sizes := []int{1, 7, 64, 333, 2, 480, 129}
for i, k := 0, 0; i < n; k++ {
m := min(sizes[k%len(sizes)], n-i)
mix(parts[i*channels : (i+m)*channels])
i += m
}
for i := range whole {
if whole[i] != parts[i] {
t.Fatalf("frame %d channel %d = %v in parts, %v at once", i/2, i%2, parts[i], whole[i])
}
}
}
// Changing speed, a voice goes from the spline to the sinc and back, and
// from one kernel to another, without a click.
func TestDownsampleSpeedChanges(t *testing.T) {
setup(t)
p := NewSound(sampleRate, 1, sine(sampleRate, 2, 1000)).NewPlayer()
p.Play()
var out []float32
for _, s := range []float64{1, 1.5, 3, 0.8, 2, 9, 1} {
p.SetSpeed(s)
out = append(out, render(480)...)
}
// The steepest a sine of 0.5 at 9 kHz is.
steep := 2 * math.Pi * 9000 / sampleRate * 0.5
for i := 1; i < len(out)/2; i++ {
if d := math.Abs(float64(out[2*i] - out[2*(i-1)])); d > 1.05*steep {
t.Fatalf("a click at frame %d: %v to %v", i, out[2*(i-1)], out[2*i])
}
}
}
// Downsampling allocates nothing as it mixes, as its speed changes.
func TestDownsampleAllocatesNothing(t *testing.T) {
setup(t)
p := NewSound(96000, 2, sine(96000, 0.5, 200, 300)).NewPlayer().SetLoop(true)
p.Play()
buf := make([]float32, 480*channels)
speeds := []float64{1, 1.3, 0.7, 3.7, 12, 1.001}
i := 0
if n := testing.AllocsPerRun(600, func() {
mix(buf)
if i++; i%50 == 0 {
p.SetSpeed(speeds[i/50%len(speeds)])
}
}); n != 0 {
t.Errorf("%v allocations a buffer", n)
}
}
+220
View File
@@ -0,0 +1,220 @@
package audio
import (
"io"
"sync"
)
// A memSource reads a sound's samples.
type memSource struct {
samples []float32
channels int
pos int // sample
loop bool
start, end int64 // the frames looped, end 0 for all
}
func (s *memSource) read(dst []float32) (int, bool) {
n := 0
for n < len(dst) {
limit := len(s.samples)
if s.loop && s.end > 0 {
limit = min(limit, int(s.end)*s.channels)
}
if s.pos >= limit {
if !s.loop || limit == 0 {
return n / s.channels, true
}
s.pos = int(s.start) * s.channels
if s.pos >= limit {
s.pos = 0
}
}
c := copy(dst[n:], s.samples[s.pos:limit])
c -= c % s.channels
if c == 0 {
break
}
n += c
s.pos += c
}
return n / s.channels, false
}
func (s *memSource) seek(frame int64) {
s.pos = int(min(frame*int64(s.channels), int64(len(s.samples))))
}
func (s *memSource) setLoop(loop bool, start, end int64) {
s.loop, s.start, s.end = loop, start, end
}
func (s *memSource) close() {}
// decodeFrames is how many frames a stream's decoder decodes at a time.
const decodeFrames = 2048
// A stream decodes ahead of a voice on a goroutine of its own, into a ring
// the voice reads without waiting. The decoder fills the ring and sleeps
// until a quarter of it is free, waking a few times a second.
type stream struct {
d Decoder
channels int // of d
keep int // channels kept: 1 or 2
mu sync.Mutex
cond sync.Cond
ring []float32 // frames of keep channels
r, n int // where the next sample is read, and how many there are
loop bool
start int64 // the frames looped, end 0 for all
end int64
pos int64 // the frame d decodes next
wrap bool // d decoded to the loop's end: it goes on from its start
atEOF bool // d reached its end
seekTo int64 // where to seek d next, or -1
gen int // counts seeks, to drop what was decoded before one
closed bool
full bool // the decoder sleeps until a quarter of the ring is free
}
func newStream(d Decoder) *stream {
ch := max(d.Channels(), 1)
s := &stream{d: d, channels: ch, keep: min(ch, 2), seekTo: -1}
s.cond.L = &s.mu
// About a second ahead, and a quarter holds what the decoder decodes.
frames := max(d.SampleRate(), 4*decodeFrames)
s.ring = make([]float32, frames*s.keep)
go s.decode()
return s
}
func (s *stream) decode() {
buf := make([]float32, decodeFrames*s.channels)
var kept []float32
if s.keep != s.channels {
kept = make([]float32, decodeFrames*s.keep)
}
s.mu.Lock()
defer s.mu.Unlock()
for {
for !s.closed && s.seekTo < 0 && !s.wrap && (s.atEOF && !s.loop || s.full) {
s.cond.Wait()
}
if s.closed {
if c, ok := s.d.(io.Closer); ok {
c.Close()
}
return
}
if s.seekTo >= 0 || s.wrap || s.atEOF {
// A seek, or a loop back to its start.
to := s.seekTo
if to < 0 {
to = s.start
}
s.seekTo, s.wrap = -1, false
gen := s.gen
s.mu.Unlock()
err := s.d.SetPosition(to)
s.mu.Lock()
if gen == s.gen {
// Where it cannot go, the stream ends.
s.atEOF = err != nil
s.loop = s.loop && err == nil
s.pos = to
}
continue
}
if len(s.ring)-s.n < decodeFrames*s.keep {
s.full = true
continue
}
gen := s.gen
s.mu.Unlock()
n, err := s.d.Read(buf)
n -= n % s.channels
samples := buf[:n]
if kept != nil {
k := 0
for i := 0; i < n; i += s.channels {
k += copy(kept[k:], buf[i:i+s.keep])
}
samples = kept[:k]
}
s.mu.Lock()
if gen != s.gen {
// Seeked meanwhile.
continue
}
frames := int64(n / s.channels)
if s.loop && s.end > 0 && s.pos+frames >= s.end {
// Past the loop's end: what is before it, then its start.
samples = samples[:max(s.end-s.pos, 0)*int64(s.keep)]
s.wrap = true
}
s.pos += frames
for len(samples) > 0 {
w := (s.r + s.n) % len(s.ring)
c := copy(s.ring[w:min(len(s.ring), w+len(s.ring)-s.n)], samples)
s.n += c
samples = samples[c:]
}
if err != nil || n == 0 {
// The end, or an error, which ends the stream as well.
s.atEOF = true
if err != io.EOF && err != nil || n == 0 && err == nil {
// A decoder that fails or makes no progress loops no more.
s.loop = false
}
}
}
}
func (s *stream) read(dst []float32) (int, bool) {
s.mu.Lock()
defer s.mu.Unlock()
want := min(len(dst), s.n)
want -= want % s.keep
got := 0
for got < want {
c := copy(dst[got:want], s.ring[s.r:])
got += c
s.r = (s.r + c) % len(s.ring)
s.n -= c
}
if s.full && len(s.ring)-s.n >= len(s.ring)/4 {
s.full = false
s.cond.Signal()
}
ended := got < len(dst)/s.keep*s.keep && s.n == 0 && s.atEOF && !s.loop && s.seekTo < 0
return got / s.keep, ended
}
func (s *stream) seek(frame int64) {
s.mu.Lock()
defer s.mu.Unlock()
s.seekTo = frame
s.atEOF, s.wrap = false, false
s.r, s.n = 0, 0
s.gen++
s.full = false
s.cond.Signal()
}
func (s *stream) setLoop(loop bool, start, end int64) {
s.mu.Lock()
defer s.mu.Unlock()
if s.wrap && !loop {
// Looping no more at its end: from there, where it decoded past.
s.wrap, s.seekTo = false, s.end
}
s.loop, s.start, s.end = loop, start, end
s.cond.Signal()
}
func (s *stream) close() {
s.mu.Lock()
defer s.mu.Unlock()
s.closed = true
s.cond.Signal()
}
+297
View File
@@ -0,0 +1,297 @@
package audio
import "math"
// A stretcher time-stretches a voice's source for SetPreservesPitch, by
// WSOLA (waveform similarity overlap-add): it plays segments of the
// source, two hops long, half overlapping, crossfaded with a Hann window,
// one hop of the output each. Where the speed puts the next segment, it
// looks within tolerance for the start most like the natural continuation
// of the last, so that the waveform goes on without a seam, skipping or
// repeating whole periods of it; the pitch stays. The voice then
// resamples what it gives at its rate alone, without its speed.
//
// A voice gets one the first time its player preserves pitch and keeps
// it: with it off, it passes the source through as it is, which a voice
// without one reads itself.
type stretcher struct {
ch int // channels of the source: 1 or 2
hs int // a hop: half a segment, about 16 ms
delta int64 // how far a segment may move to match, about 10 ms
dec int // the stride of the coarse search: about 16 kHz
win []float32
// Frames of the source from frame base, n of them. rd is the frame
// read next: base+n, or before base while skipping up to it.
buf []float32
base int64
n int
rd int64
end int64 // the frame after the source's last, once it ended, or -1
held int // frames of buf a pass-through read gave, dropped at the next
mono []float32 // the frames searched, mixed to mono
tm []float32 // tail, mixed to mono
tail []float32 // a hop of the natural continuation of the last segment
nat int64 // the frame tail starts at
out []float32 // a hop: what a step gives
own []float32 // the source's frames, passed through
on bool // stretching, rather than passing the source through
first bool // no segment yet since it started stretching
done bool // nothing more to give
ana float64 // the frame the speed puts the next segment at
// The source frames, counted on past its loop's end, that the frames
// of the voice's ring are at, as it holds them; those of what it read
// last, from tag0 by tagStep; and where the frames after them are.
tags []float64
tag0, tagStep float64
next float64
}
func newStretcher(rate, ch int) *stretcher {
hs := max(rate/64, 16)
delta := max(rate/96, 8)
// The frames a step reads at most, and what a voice hands over.
size := max(2*delta+2*hs+1, 256)
st := &stretcher{
ch: ch, hs: hs, delta: int64(delta), dec: max(rate/16000, 1),
win: make([]float32, hs),
buf: make([]float32, size*ch),
mono: make([]float32, 2*delta+hs+1),
tm: make([]float32, hs),
tail: make([]float32, hs*ch),
out: make([]float32, hs*ch),
own: make([]float32, 256*ch),
tags: make([]float64, ringFrames),
}
for j := range st.win {
s := math.Sin(math.Pi / 2 * (float64(j) + 0.5) / float64(hs))
st.win[j] = float32(s * s)
}
return st
}
// reset starts over at frame f, from which the source reads next, and
// sets the voice's frames before it, which it has not read yet, at the
// frames before f.
func (st *stretcher) reset(f int64, on bool) {
st.base, st.rd, st.n, st.held = f, f, 0, 0
st.end = -1
st.on, st.first, st.done = on, true, false
st.ana, st.next = float64(f), float64(f)
// The voice is at f, until frames come in.
st.tags[f&(ringFrames-1)] = float64(f)
st.tags[(f+1)&(ringFrames-1)] = float64(f + 1)
}
// push notes that frame f, coming into the voice's ring, is at tag.
func (st *stretcher) push(f int64, tag float64) {
st.tags[f&(ringFrames-1)] = tag
}
// drop forgets the frames before to; those not read yet are skipped.
func (st *stretcher) drop(to int64) {
if to <= st.base {
return
}
if k := to - st.base; k < int64(st.n) {
st.n -= int(k)
copy(st.buf, st.buf[int(k)*st.ch:(int(k)+st.n)*st.ch])
} else {
st.n = 0
}
st.base = to
}
// fill reads the source up to frame upto, or its end, and reports false
// while a stream has not decoded that far.
func (st *stretcher) fill(src source, upto int64) bool {
ch := st.ch
for st.end < 0 && st.rd < upto {
skip := st.rd < st.base
var dst []float32
if skip {
dst = st.buf[:min(st.base-st.rd, int64(len(st.buf)/ch))*int64(ch)]
} else {
dst = st.buf[st.n*ch : (st.n+int(min(upto-st.rd, int64(len(st.buf)/ch-st.n))))*ch]
}
got, ended := src.read(dst)
if !skip {
st.n += got
}
st.rd += int64(got)
if ended {
st.end = st.rd
} else if got == 0 {
return false
}
}
if st.end >= 0 && st.base+int64(st.n) < upto {
// Silence after the end.
k := int(upto - st.base)
clear(st.buf[st.n*ch : k*ch])
st.n = k
}
return true
}
// readStretched gives the voice its next frames, in v.in, as a source does:
// time-stretched while it preserves pitch, else as the source has them.
func (v *voice) readStretched() (int, bool) {
st := v.st
if st.held > 0 {
st.drop(st.base + int64(st.held))
st.held = 0
}
if st.done {
return 0, true
}
if v.pitch != st.on {
// From what is held, which goes on from the last segment.
if v.pitch {
st.first, st.ana = true, float64(st.base)
} else if !st.first && st.nat >= st.base {
st.drop(st.nat)
}
if st.end >= 0 {
// Not the silence after the end.
st.n = int(max(min(int64(st.n), st.end-st.base), 0))
}
st.on = v.pitch
}
if st.on {
n, ended := st.stretch(v.src, v.speed)
v.in = st.out
return n, ended
}
st.tagStep = 1
if st.n > 0 {
st.tag0, st.held = float64(st.base), st.n
st.next = float64(st.base + int64(st.n))
v.in = st.buf
return st.n, false
}
n, ended := v.src.read(st.own)
st.tag0 = float64(st.rd)
st.rd += int64(n)
st.base = st.rd
st.next = float64(st.rd)
v.in = st.own
return n, ended
}
// stretch puts the next frames into st.out and returns how many, with
// ended true once there are none, and none while a stream is late.
func (st *stretcher) stretch(src source, speed float64) (int, bool) {
hs, ch := st.hs, st.ch
a := int64(math.Round(st.ana))
lo, hi := a, a
if !st.first {
lo = max(a-st.delta, st.base)
hi = max(a+st.delta, lo)
}
st.drop(lo)
if !st.fill(src, hi+int64(2*hs)) {
return 0, false
}
if e := st.end; e >= 0 && a >= e {
// The speed is past the end: what was playing fades out.
st.done, st.next = true, float64(e)
if st.first {
return 0, true
}
for j := range hs {
w := 1 - st.win[j]
for k := j * ch; k < (j+1)*ch; k++ {
st.out[k] = st.tail[k] * w
}
}
st.tag0, st.tagStep = float64(e), 0
return hs, false
}
s := lo
if !st.first {
s = st.best(lo, hi)
}
in := st.buf[int(s-st.base)*ch:]
o := st.out[:hs*ch]
if st.first || s == st.nat {
// No seam: the source as it is.
copy(o, in)
} else {
for j := range hs {
w := st.win[j]
for k := j * ch; k < (j+1)*ch; k++ {
o[k] = st.tail[k] + (in[k]-st.tail[k])*w
}
}
}
copy(st.tail, in[hs*ch:2*hs*ch])
st.first = false
st.nat = s + int64(hs)
st.tag0, st.tagStep = st.ana, speed
st.ana += float64(hs) * speed
st.next = st.ana
if e := st.end; e >= 0 && st.next > float64(e) {
// Where the source ends, the frames after are at its end.
st.tagStep = max(float64(e)-st.tag0, 0) / float64(hs)
st.next = float64(e)
}
return hs, false
}
// best returns the start between lo and hi of the segment whose first hop
// is most like tail, by normalized cross-correlation in mono: every dec
// frames, then each frame around the best.
func (st *stretcher) best(lo, hi int64) int64 {
if st.nat >= lo && st.nat <= hi {
// The natural continuation itself: a perfect match.
return st.nat
}
hs, ch := st.hs, st.ch
span := int(hi - lo)
off := int(lo - st.base)
m, t := st.mono[:span+hs], st.tm
if ch == 1 {
copy(m, st.buf[off:])
copy(t, st.tail)
} else {
for i := range m {
m[i] = st.buf[2*(off+i)] + st.buf[2*(off+i)+1]
}
for i := range t {
t[i] = st.tail[2*i] + st.tail[2*i+1]
}
}
score := func(s, stride int) float32 {
var xy, yy float32
y := m[s : s+hs]
for j := 0; j < hs; j += stride {
xy += t[j] * y[j]
yy += y[j] * y[j]
}
if yy == 0 {
return 0
}
return xy / float32(math.Sqrt(float64(yy)))
}
dec := st.dec
b, bs := 0, float32(math.Inf(-1))
for s := 0; s <= span; s += dec {
if x := score(s, dec); x > bs {
b, bs = s, x
}
}
if dec > 1 {
c := b
bs = float32(math.Inf(-1))
for s := max(c-dec+1, 0); s <= min(c+dec-1, span); s++ {
if x := score(s, 1); x > bs {
b, bs = s, x
}
}
}
return lo + int64(b)
}
Loaded 100 of 2538 files, more files were not shown because too many files have changed in this diff. Show more