Compare commits
34 Commits
5b8e89e9a2
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74043db851 | ||
|
|
be929ce55a | ||
|
|
711eb148df | ||
|
|
0010bc6cf7 | ||
|
|
a14d068ada | ||
|
|
b66e0737d0 | ||
|
|
2860102627 | ||
|
|
ebe2b26ae9 | ||
|
|
356b492629 | ||
|
|
99f26c4485 | ||
|
|
9ed1d4f60e | ||
|
|
a639558ce4 | ||
|
|
3dc4942942 | ||
|
|
ed8f9a4538 | ||
|
|
1283fdc9c4 | ||
|
|
71017f1e61 | ||
|
|
81d73e9b08 | ||
|
|
36111ff781 | ||
|
|
3a1db4e80c | ||
|
|
7284b9d4b9 | ||
|
|
206f158c8e | ||
|
|
2cd818c331 | ||
|
|
952552302a | ||
|
|
b6224cd2fd | ||
|
|
5ff7affd95 | ||
|
|
6ae4d39b92 | ||
|
|
d7eb34c7d4 | ||
|
|
46fe506585 | ||
|
|
b067dbb7bf | ||
|
|
7f7d62d7d8 | ||
|
|
c81f64d9ca | ||
|
|
c1bb24473e | ||
|
|
3a57f41fc2 | ||
|
|
be5e26486c |
117
.gitea/workflows/build.yml
Normal file
117
.gitea/workflows/build.yml
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
name: Build and Release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
tags: ['v*']
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-windows:
|
||||||
|
runs-on: windows-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: msys2 {0}
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.24'
|
||||||
|
cache: false
|
||||||
|
|
||||||
|
- name: Setup MSYS2
|
||||||
|
uses: msys2/setup-msys2@v2
|
||||||
|
with:
|
||||||
|
msystem: MINGW64
|
||||||
|
path-type: inherit
|
||||||
|
update: true
|
||||||
|
install: >-
|
||||||
|
mingw-w64-x86_64-gcc
|
||||||
|
mingw-w64-x86_64-opus
|
||||||
|
mingw-w64-x86_64-opusfile
|
||||||
|
mingw-w64-x86_64-portaudio
|
||||||
|
mingw-w64-x86_64-pkgconf
|
||||||
|
zip
|
||||||
|
|
||||||
|
- name: Build TUI
|
||||||
|
run: |
|
||||||
|
export CGO_ENABLED=1
|
||||||
|
mkdir -p dist
|
||||||
|
# More descriptive name: ts3-tui
|
||||||
|
go build -o dist/ts3-tui.exe ./cmd/tui
|
||||||
|
# Copy DLLs
|
||||||
|
cp /mingw64/bin/libogg-0.dll dist/
|
||||||
|
cp /mingw64/bin/libopus-0.dll dist/
|
||||||
|
cp /mingw64/bin/libopusfile-0.dll dist/
|
||||||
|
cp /mingw64/bin/libportaudio-2.dll dist/ || true
|
||||||
|
# Create ZIP with architecture name
|
||||||
|
cd dist && zip -r ../ts3-tui-windows-x86_64.zip . *
|
||||||
|
|
||||||
|
- name: Upload Artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: ts3-tui-windows-zip
|
||||||
|
path: ts3-tui-windows-x86_64.zip
|
||||||
|
|
||||||
|
build-linux:
|
||||||
|
runs-on: linux-x86_64
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.24'
|
||||||
|
cache: false
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y \
|
||||||
|
libportaudio2 portaudio19-dev \
|
||||||
|
libopus-dev libopusfile-dev \
|
||||||
|
libpulse-dev pkg-config gcc
|
||||||
|
|
||||||
|
- name: Build TUI
|
||||||
|
run: |
|
||||||
|
export CGO_ENABLED=1
|
||||||
|
export ARCH=$(uname -m)
|
||||||
|
mkdir -p dist
|
||||||
|
# More descriptive name: ts3-tui-linux-ARCH
|
||||||
|
go build -o dist/ts3-tui-linux-${ARCH} ./cmd/tui
|
||||||
|
|
||||||
|
- name: Upload Artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: ts3-tui-linux-binaries
|
||||||
|
path: dist/*
|
||||||
|
|
||||||
|
release:
|
||||||
|
needs: [build-windows, build-linux]
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Generate Changelog
|
||||||
|
run: |
|
||||||
|
# Get commits since the last tag (or since the beginning)
|
||||||
|
git log --oneline $(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || git rev-list --max-parents=0 HEAD)..HEAD > changelog.txt
|
||||||
|
|
||||||
|
- name: Download Artifacts
|
||||||
|
uses: actions/download-artifact@v3
|
||||||
|
|
||||||
|
- name: Create Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
with:
|
||||||
|
body_path: changelog.txt
|
||||||
|
files: |
|
||||||
|
ts3-tui-windows-zip/ts3-tui-windows-x86_64.zip
|
||||||
|
ts3-tui-linux-binaries/*
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
15
.vscode/settings.json
vendored
Normal file
15
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"go.toolsEnvVars": {
|
||||||
|
"CGO_ENABLED": "1",
|
||||||
|
"PATH": "D:\\esto_al_path\\msys64\\mingw64\\bin;${env:PATH}",
|
||||||
|
"PKG_CONFIG_PATH": "D:\\esto_al_path\\msys64\\mingw64\\lib\\pkgconfig"
|
||||||
|
},
|
||||||
|
"gopls": {
|
||||||
|
"formatting.gofumpt": true,
|
||||||
|
"ui.diagnostic.diagnosticsDelay": "300ms",
|
||||||
|
"build.directoryFilters": [
|
||||||
|
"-vendor"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"go.lintOnSave": "package"
|
||||||
|
}
|
||||||
@@ -56,6 +56,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Silence noise (ALSA/PortAudio) on Linux or if debugFile is set
|
||||||
|
redirectStderr(debugFile)
|
||||||
|
|
||||||
// Create the TUI model
|
// Create the TUI model
|
||||||
m := NewModel(*serverAddr, *nickname)
|
m := NewModel(*serverAddr, *nickname)
|
||||||
|
|
||||||
|
|||||||
561
cmd/tui/model.go
561
cmd/tui/model.go
@@ -22,6 +22,7 @@ const (
|
|||||||
FocusChat
|
FocusChat
|
||||||
FocusInput
|
FocusInput
|
||||||
FocusUserView
|
FocusUserView
|
||||||
|
FocusAbout
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListItem represents an item in the navigation tree (Channel or User)
|
// ListItem represents an item in the navigation tree (Channel or User)
|
||||||
@@ -31,6 +32,14 @@ type ListItem struct {
|
|||||||
User *UserNode
|
User *UserNode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (l ListItem) IsSpacer() bool {
|
||||||
|
if l.IsUser || l.Channel == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// TeamSpeak spacers usually look like [spacer0], [*spacer1], etc.
|
||||||
|
return strings.Contains(strings.ToLower(l.Channel.Name), "[spacer")
|
||||||
|
}
|
||||||
|
|
||||||
// ChatMessage represents a message in the chat
|
// ChatMessage represents a message in the chat
|
||||||
type ChatMessage struct {
|
type ChatMessage struct {
|
||||||
Time time.Time
|
Time time.Time
|
||||||
@@ -71,6 +80,7 @@ type Model struct {
|
|||||||
|
|
||||||
// UI State
|
// UI State
|
||||||
focus Focus
|
focus Focus
|
||||||
|
lastFocus Focus // To return from About view
|
||||||
width, height int
|
width, height int
|
||||||
channels []ChannelNode
|
channels []ChannelNode
|
||||||
items []ListItem // Flattened list for navigation
|
items []ListItem // Flattened list for navigation
|
||||||
@@ -87,12 +97,20 @@ type Model struct {
|
|||||||
talkingClients map[uint16]bool // ClientID -> isTalking
|
talkingClients map[uint16]bool // ClientID -> isTalking
|
||||||
|
|
||||||
// Audio state
|
// Audio state
|
||||||
audioPlayer *audio.Player
|
audioPlayer *audio.Player
|
||||||
audioCapturer *audio.Capturer
|
audioCapturer *audio.Capturer
|
||||||
playbackVol int // 0-100
|
playbackVol int // 0-100
|
||||||
micLevel int // 0-100 (current input level)
|
micLevel int // 0-100 (current input level)
|
||||||
isMuted bool // Mic muted
|
isMuted bool // Mic muted
|
||||||
isPTT bool // Push-to-talk active
|
isPTT bool // Push-to-talk active (Manual TX)
|
||||||
|
vadEnabled bool // Voice Activation Detection active
|
||||||
|
vadThreshold int // 0-100 threshold for VAD
|
||||||
|
vadLastTriggered time.Time // Last time VAD threshold was exceeded
|
||||||
|
|
||||||
|
// Popup State
|
||||||
|
showPokePopup bool
|
||||||
|
pokePopupSender string
|
||||||
|
pokePopupMessage string
|
||||||
|
|
||||||
// Program reference for sending messages from event handlers
|
// Program reference for sending messages from event handlers
|
||||||
program *tea.Program
|
program *tea.Program
|
||||||
@@ -101,6 +119,10 @@ type Model struct {
|
|||||||
// User View
|
// User View
|
||||||
showUserView bool
|
showUserView bool
|
||||||
viewUser *UserNode
|
viewUser *UserNode
|
||||||
|
pokeID uint16 // Target ID for pending poke
|
||||||
|
|
||||||
|
// Interactive EQ
|
||||||
|
eqBandIdx int // 0-4
|
||||||
}
|
}
|
||||||
|
|
||||||
// addLog adds a message to the log panel
|
// addLog adds a message to the log panel
|
||||||
@@ -124,6 +146,8 @@ func NewModel(serverAddr, nickname string) *Model {
|
|||||||
logMessages: []string{"Starting..."},
|
logMessages: []string{"Starting..."},
|
||||||
talkingClients: make(map[uint16]bool),
|
talkingClients: make(map[uint16]bool),
|
||||||
playbackVol: 80, // Default 80% volume
|
playbackVol: 80, // Default 80% volume
|
||||||
|
vadEnabled: true,
|
||||||
|
vadThreshold: 50,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,6 +206,16 @@ type clientLeftMsg struct {
|
|||||||
clientID uint16
|
clientID uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type clientMovedMsg struct {
|
||||||
|
clientID uint16
|
||||||
|
channelID uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
type pokeMsg struct {
|
||||||
|
senderName string
|
||||||
|
message string
|
||||||
|
}
|
||||||
|
|
||||||
type chatMsg struct {
|
type chatMsg struct {
|
||||||
senderID uint16
|
senderID uint16
|
||||||
senderName string
|
senderName string
|
||||||
@@ -239,6 +273,20 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
m.audioPlayer.PlayPCM(e.SenderID, e.PCM)
|
m.audioPlayer.PlayPCM(e.SenderID, e.PCM)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
m.client.On(ts3client.EventClientMoved, func(e *ts3client.ClientMovedEvent) {
|
||||||
|
m.program.Send(clientMovedMsg{
|
||||||
|
clientID: e.ClientID,
|
||||||
|
channelID: e.ChannelID,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
m.client.On(ts3client.EventPoke, func(e *ts3client.PokeEvent) {
|
||||||
|
m.program.Send(pokeMsg{
|
||||||
|
senderName: e.SenderName,
|
||||||
|
message: e.Message,
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize audio player
|
// Initialize audio player
|
||||||
@@ -259,16 +307,53 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
} else {
|
} else {
|
||||||
m.audioCapturer = capturer
|
m.audioCapturer = capturer
|
||||||
// Set callback to send audio to server when PTT is active
|
// Set callback to send audio to server when PTT is active
|
||||||
|
// Set callback to send audio to server when PTT is active
|
||||||
m.audioCapturer.SetCallback(func(samples []int16) {
|
m.audioCapturer.SetCallback(func(samples []int16) {
|
||||||
if m.isPTT && m.client != nil && !m.isMuted {
|
// Calculate level of this frame for VAD decision
|
||||||
|
// Note: GetLevel() is smoothed, we might want instant frame level for VAD trigger?
|
||||||
|
// But pkg/audio/level.go is efficient. Let's re-calculate for precision.
|
||||||
|
level := audio.CalculateRMSLevel(samples)
|
||||||
|
|
||||||
|
// Determine if we should transmit
|
||||||
|
shouldTransmit := false
|
||||||
|
|
||||||
|
// Manual PTT (Locked on with 'v')
|
||||||
|
if m.isPTT {
|
||||||
|
shouldTransmit = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// VAD Logic
|
||||||
|
if m.vadEnabled && !m.isMuted {
|
||||||
|
if level > m.vadThreshold {
|
||||||
|
shouldTransmit = true
|
||||||
|
m.vadLastTriggered = time.Now()
|
||||||
|
} else if !m.vadLastTriggered.IsZero() && time.Since(m.vadLastTriggered) < 1*time.Second {
|
||||||
|
// Hold VAD open for 1 second (decay)
|
||||||
|
shouldTransmit = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow transmission if forced or VAD triggered
|
||||||
|
if shouldTransmit && m.client != nil && !m.isMuted {
|
||||||
m.client.SendAudio(samples)
|
m.client.SendAudio(samples)
|
||||||
}
|
}
|
||||||
// Update mic level for display
|
|
||||||
|
// Update mic level for display (use the calculated level)
|
||||||
if m.program != nil {
|
if m.program != nil {
|
||||||
m.program.Send(micLevelMsg(m.audioCapturer.GetLevel()))
|
// Use goroutine to prevent blocking the capture loop if the UI is busy (e.g. shutting down)
|
||||||
|
go m.program.Send(micLevelMsg(level))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
m.addLog("Audio capturer initialized")
|
m.addLog("Audio capturer initialized")
|
||||||
|
|
||||||
|
// Start capture immediately if VAD is enabled or PTT is active
|
||||||
|
if m.vadEnabled || m.isPTT {
|
||||||
|
if err := m.audioCapturer.Start(); err != nil {
|
||||||
|
m.addLog("Error starting audio capture: %v", err)
|
||||||
|
} else {
|
||||||
|
m.addLog("Audio capture started (VAD/PTT active)")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connect asynchronously
|
// Connect asynchronously
|
||||||
@@ -308,16 +393,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update mic level when PTT is active (multiply for better visibility)
|
// Legacy mic level handling removed to support VAD event-driven updates
|
||||||
if m.isPTT && m.audioCapturer != nil {
|
|
||||||
level := m.audioCapturer.GetLevel() * 4 // Boost for visibility
|
|
||||||
if level > 100 {
|
|
||||||
level = 100
|
|
||||||
}
|
|
||||||
m.micLevel = level
|
|
||||||
} else {
|
|
||||||
m.micLevel = 0 // Reset when not transmitting
|
|
||||||
}
|
|
||||||
|
|
||||||
// Continue ticking (100ms for responsive mic level)
|
// Continue ticking (100ms for responsive mic level)
|
||||||
return m, tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg {
|
return m, tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg {
|
||||||
@@ -348,6 +424,36 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
|
|
||||||
|
case clientMovedMsg:
|
||||||
|
if msg.clientID == m.selfID {
|
||||||
|
chName := "Unknown"
|
||||||
|
if ch := m.client.GetChannel(msg.channelID); ch != nil {
|
||||||
|
chName = ch.Name
|
||||||
|
}
|
||||||
|
m.chatMessages = append(m.chatMessages, ChatMessage{
|
||||||
|
Time: time.Now(),
|
||||||
|
Sender: "SYSTEM",
|
||||||
|
Content: fmt.Sprintf("You moved to channel: %s", chName),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
|
||||||
|
case pokeMsg:
|
||||||
|
// Append to chat as well
|
||||||
|
m.chatMessages = append(m.chatMessages, ChatMessage{
|
||||||
|
Time: time.Now(),
|
||||||
|
Sender: "POKE",
|
||||||
|
Content: fmt.Sprintf("[%s]: %s", msg.senderName, msg.message),
|
||||||
|
})
|
||||||
|
m.addLog("Received poke from %s: %s", msg.senderName, msg.message)
|
||||||
|
|
||||||
|
// Trigger Popup
|
||||||
|
m.showPokePopup = true
|
||||||
|
m.pokePopupSender = msg.senderName
|
||||||
|
m.pokePopupMessage = msg.message
|
||||||
|
|
||||||
|
return m, nil
|
||||||
|
|
||||||
case chatMsg:
|
case chatMsg:
|
||||||
m.chatMessages = append(m.chatMessages, ChatMessage{
|
m.chatMessages = append(m.chatMessages, ChatMessage{
|
||||||
Time: time.Now(),
|
Time: time.Now(),
|
||||||
@@ -455,11 +561,50 @@ func (m *Model) updateChannelList(channels []*ts3client.Channel) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ensure selectedIdx is valid (not on a spacer)
|
||||||
|
if len(m.items) > 0 {
|
||||||
|
if m.selectedIdx >= len(m.items) {
|
||||||
|
m.selectedIdx = len(m.items) - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// If current is a spacer, find next valid one
|
||||||
|
if m.items[m.selectedIdx].IsSpacer() {
|
||||||
|
found := false
|
||||||
|
// Try going down
|
||||||
|
for i := m.selectedIdx; i < len(m.items); i++ {
|
||||||
|
if !m.items[i].IsSpacer() {
|
||||||
|
m.selectedIdx = i
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If not found, try going up
|
||||||
|
if !found {
|
||||||
|
for i := m.selectedIdx; i >= 0; i-- {
|
||||||
|
if !m.items[i].IsSpacer() {
|
||||||
|
m.selectedIdx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
func (m *Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
key := msg.String()
|
||||||
|
|
||||||
|
// Global Key Handling for Popup
|
||||||
|
if m.showPokePopup {
|
||||||
|
if key == "esc" || key == "enter" || key == "q" {
|
||||||
|
m.showPokePopup = false
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Absolute Globals (Always active)
|
// 1. Absolute Globals (Always active)
|
||||||
switch msg.String() {
|
switch key {
|
||||||
case "ctrl+c":
|
case "ctrl+c":
|
||||||
if m.client != nil {
|
if m.client != nil {
|
||||||
m.client.Disconnect()
|
m.client.Disconnect()
|
||||||
@@ -475,7 +620,16 @@ func (m *Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
case "tab":
|
case "tab":
|
||||||
// Cycle focus
|
// Cycle focus
|
||||||
m.focus = (m.focus + 1) % 3
|
m.focus = (m.focus + 1) % 4 // FocusChannels, FocusChat, FocusInput, FocusUserView
|
||||||
|
return m, nil
|
||||||
|
|
||||||
|
case "f1":
|
||||||
|
if m.focus == FocusAbout {
|
||||||
|
m.focus = m.lastFocus
|
||||||
|
} else {
|
||||||
|
m.lastFocus = m.focus
|
||||||
|
m.focus = FocusAbout
|
||||||
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -485,8 +639,8 @@ func (m *Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
return m.handleInputKeys(msg)
|
return m.handleInputKeys(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Global Shortcuts (Only when NOT in Input)
|
// 3. Global Shortcuts (Only when NOT in Input or About)
|
||||||
if m.focus != FocusInput && m.focus != FocusUserView {
|
if m.focus != FocusInput && m.focus != FocusUserView && m.focus != FocusAbout {
|
||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "q":
|
case "q":
|
||||||
// Quit (same as ctrl+c)
|
// Quit (same as ctrl+c)
|
||||||
@@ -531,16 +685,58 @@ func (m *Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
|
|
||||||
|
case "ctrl+up", "ctrl+right":
|
||||||
|
// Increase VAD threshold
|
||||||
|
m.vadThreshold += 5
|
||||||
|
if m.vadThreshold > 100 {
|
||||||
|
m.vadThreshold = 100
|
||||||
|
}
|
||||||
|
m.addLog("VAD Threshold: %d", m.vadThreshold)
|
||||||
|
return m, nil
|
||||||
|
|
||||||
|
case "ctrl+down", "ctrl+left":
|
||||||
|
// Decrease VAD threshold
|
||||||
|
m.vadThreshold -= 5
|
||||||
|
if m.vadThreshold < 0 {
|
||||||
|
m.vadThreshold = 0
|
||||||
|
}
|
||||||
|
m.addLog("VAD Threshold: %d", m.vadThreshold)
|
||||||
|
return m, nil
|
||||||
|
|
||||||
|
case "g", "G":
|
||||||
|
// Toggle VAD (Gate)
|
||||||
|
m.vadEnabled = !m.vadEnabled
|
||||||
|
state := "OFF"
|
||||||
|
if m.vadEnabled {
|
||||||
|
state = "ON"
|
||||||
|
// Ensure capturer is running if VAD is on
|
||||||
|
if m.audioCapturer != nil && !m.audioCapturer.IsRunning() {
|
||||||
|
if err := m.audioCapturer.Start(); err != nil {
|
||||||
|
m.addLog("Error starting VAD capture: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Stop if PTT is also off
|
||||||
|
if !m.isPTT && m.audioCapturer != nil && m.audioCapturer.IsRunning() {
|
||||||
|
m.audioCapturer.Stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.addLog("Voice Activation (Gate): %s", state)
|
||||||
|
return m, nil
|
||||||
|
|
||||||
case "v", "V":
|
case "v", "V":
|
||||||
// Toggle voice (PTT)
|
// Toggle voice (PTT)
|
||||||
m.isPTT = !m.isPTT
|
m.isPTT = !m.isPTT
|
||||||
if m.isPTT {
|
if m.isPTT {
|
||||||
if m.audioCapturer != nil {
|
if m.audioCapturer != nil && !m.audioCapturer.IsRunning() {
|
||||||
m.audioCapturer.Start()
|
if err := m.audioCapturer.Start(); err != nil {
|
||||||
|
m.addLog("Audio capture error: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
m.addLog("🎤 Transmitting...")
|
m.addLog("🎤 Transmitting...")
|
||||||
} else {
|
} else {
|
||||||
if m.audioCapturer != nil {
|
// Stop only if VAD is also off
|
||||||
|
if !m.vadEnabled && m.audioCapturer != nil && m.audioCapturer.IsRunning() {
|
||||||
m.audioCapturer.Stop()
|
m.audioCapturer.Stop()
|
||||||
}
|
}
|
||||||
m.addLog("🎤 Stopped transmitting")
|
m.addLog("🎤 Stopped transmitting")
|
||||||
@@ -564,11 +760,20 @@ func (m *Model) handleKeyPress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
return m.handleChatKeys(msg)
|
return m.handleChatKeys(msg)
|
||||||
case FocusUserView:
|
case FocusUserView:
|
||||||
return m.handleUserViewKeys(msg)
|
return m.handleUserViewKeys(msg)
|
||||||
|
case FocusAbout:
|
||||||
|
return m.handleAboutViewKeys(msg)
|
||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) handleChatKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
func (m *Model) handleChatKeys(_ tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) handleAboutViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
if msg.String() == "esc" || msg.String() == "f1" {
|
||||||
|
m.focus = m.lastFocus
|
||||||
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -588,6 +793,13 @@ func (m *Model) handleUserViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
m.focus = FocusChannels
|
m.focus = FocusChannels
|
||||||
m.showUserView = false
|
m.showUserView = false
|
||||||
|
|
||||||
|
case "1":
|
||||||
|
// Initiate Poke: set target, clear input, and focus it
|
||||||
|
m.pokeID = u.ID
|
||||||
|
m.focus = FocusInput
|
||||||
|
m.inputText = ""
|
||||||
|
m.addLog("Write poke message for %s and press Enter...", u.Nickname)
|
||||||
|
|
||||||
case "2":
|
case "2":
|
||||||
// Toggle mute for this user
|
// Toggle mute for this user
|
||||||
_, muted := m.audioPlayer.GetUserSettings(u.ID)
|
_, muted := m.audioPlayer.GetUserSettings(u.ID)
|
||||||
@@ -611,6 +823,28 @@ func (m *Model) handleUserViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
newVol = 0.0
|
newVol = 0.0
|
||||||
}
|
}
|
||||||
m.audioPlayer.SetUserVolume(u.ID, newVol)
|
m.audioPlayer.SetUserVolume(u.ID, newVol)
|
||||||
|
|
||||||
|
case "right", "l":
|
||||||
|
// Increase Gain for selected band
|
||||||
|
current := m.audioPlayer.GetUserGain(u.ID, m.eqBandIdx)
|
||||||
|
m.audioPlayer.SetUserGain(u.ID, m.eqBandIdx, current+1.0)
|
||||||
|
|
||||||
|
case "left", "h":
|
||||||
|
// Decrease Gain
|
||||||
|
current := m.audioPlayer.GetUserGain(u.ID, m.eqBandIdx)
|
||||||
|
m.audioPlayer.SetUserGain(u.ID, m.eqBandIdx, current-1.0)
|
||||||
|
|
||||||
|
case "up", "k":
|
||||||
|
m.eqBandIdx--
|
||||||
|
if m.eqBandIdx < 0 {
|
||||||
|
m.eqBandIdx = 4
|
||||||
|
}
|
||||||
|
|
||||||
|
case "down", "j":
|
||||||
|
m.eqBandIdx++
|
||||||
|
if m.eqBandIdx > 4 {
|
||||||
|
m.eqBandIdx = 0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
@@ -618,17 +852,37 @@ func (m *Model) handleUserViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
func (m *Model) handleChannelKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
func (m *Model) handleChannelKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "up", "k":
|
case "up", "k":
|
||||||
if m.selectedIdx > 0 {
|
for m.selectedIdx > 0 {
|
||||||
m.selectedIdx--
|
m.selectedIdx--
|
||||||
|
if !m.items[m.selectedIdx].IsSpacer() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// If we hit the top and it's a spacer, we might need to go down to find the first valid one
|
||||||
|
if m.selectedIdx == 0 && m.items[m.selectedIdx].IsSpacer() {
|
||||||
|
// Search forward for the first valid one
|
||||||
|
for i := 0; i < len(m.items); i++ {
|
||||||
|
if !m.items[i].IsSpacer() {
|
||||||
|
m.selectedIdx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case "down", "j":
|
case "down", "j":
|
||||||
if m.selectedIdx < len(m.items)-1 {
|
for m.selectedIdx < len(m.items)-1 {
|
||||||
m.selectedIdx++
|
m.selectedIdx++
|
||||||
|
if !m.items[m.selectedIdx].IsSpacer() {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case "enter":
|
case "enter":
|
||||||
// Join selected channel OR open user view
|
// Join selected channel OR open user view
|
||||||
if m.selectedIdx < len(m.items) && m.client != nil {
|
if m.selectedIdx < len(m.items) && m.client != nil {
|
||||||
item := m.items[m.selectedIdx]
|
item := m.items[m.selectedIdx]
|
||||||
|
if item.IsSpacer() {
|
||||||
|
return m, nil // Do nothing for spacers
|
||||||
|
}
|
||||||
if !item.IsUser {
|
if !item.IsUser {
|
||||||
// Channel
|
// Channel
|
||||||
ch := item.Channel
|
ch := item.Channel
|
||||||
@@ -656,11 +910,27 @@ func (m *Model) handleInputKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "enter":
|
case "enter":
|
||||||
if m.inputText != "" && m.client != nil {
|
if m.inputText != "" && m.client != nil {
|
||||||
m.client.SendChannelMessage(m.inputText)
|
if m.pokeID != 0 {
|
||||||
|
err := m.client.Poke(m.pokeID, m.inputText)
|
||||||
|
if err != nil {
|
||||||
|
m.addLog("Error poking client %d: %v", m.pokeID, err)
|
||||||
|
} else {
|
||||||
|
m.addLog("Poke sent!")
|
||||||
|
}
|
||||||
|
m.pokeID = 0
|
||||||
|
m.focus = FocusUserView
|
||||||
|
} else {
|
||||||
|
m.client.SendChannelMessage(m.inputText)
|
||||||
|
}
|
||||||
m.inputText = ""
|
m.inputText = ""
|
||||||
}
|
}
|
||||||
case "esc":
|
case "esc":
|
||||||
m.focus = FocusChannels
|
if m.pokeID != 0 {
|
||||||
|
m.pokeID = 0
|
||||||
|
m.focus = FocusUserView
|
||||||
|
} else {
|
||||||
|
m.focus = FocusChannels
|
||||||
|
}
|
||||||
m.inputText = ""
|
m.inputText = ""
|
||||||
case "backspace":
|
case "backspace":
|
||||||
if len(m.inputText) > 0 {
|
if len(m.inputText) > 0 {
|
||||||
@@ -688,6 +958,36 @@ func (m *Model) handleInputKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
// View renders the UI
|
// View renders the UI
|
||||||
func (m *Model) View() string {
|
func (m *Model) View() string {
|
||||||
|
if m.showPokePopup {
|
||||||
|
boxStyle := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.DoubleBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("196")). // Red for Poke
|
||||||
|
Padding(1, 2).
|
||||||
|
Width(50).
|
||||||
|
Align(lipgloss.Center)
|
||||||
|
|
||||||
|
titleStyle := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("226")).MarginBottom(1)
|
||||||
|
senderStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("208")).Bold(true)
|
||||||
|
msgStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("255")).Italic(true)
|
||||||
|
helpStyle := lipgloss.NewStyle().Faint(true).MarginTop(2)
|
||||||
|
|
||||||
|
content := lipgloss.JoinVertical(lipgloss.Center,
|
||||||
|
titleStyle.Render("YOU WERE POKED!"),
|
||||||
|
"",
|
||||||
|
fmt.Sprintf("From: %s", senderStyle.Render(m.pokePopupSender)),
|
||||||
|
"",
|
||||||
|
msgStyle.Render(fmt.Sprintf("%q", m.pokePopupMessage)),
|
||||||
|
"",
|
||||||
|
helpStyle.Render("(Press Esc/Enter to close)"),
|
||||||
|
)
|
||||||
|
|
||||||
|
return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, boxStyle.Render(content))
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.focus == FocusAbout {
|
||||||
|
return m.renderAboutView()
|
||||||
|
}
|
||||||
|
|
||||||
if m.width == 0 {
|
if m.width == 0 {
|
||||||
return "Loading..."
|
return "Loading..."
|
||||||
}
|
}
|
||||||
@@ -794,7 +1094,11 @@ func (m *Model) View() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Input
|
// Input
|
||||||
inputContent := "> " + m.inputText
|
prompt := "> "
|
||||||
|
if m.pokeID != 0 {
|
||||||
|
prompt = "[Poke Message] > "
|
||||||
|
}
|
||||||
|
inputContent := prompt + m.inputText
|
||||||
if m.focus == FocusInput {
|
if m.focus == FocusInput {
|
||||||
inputStyle = inputStyle.BorderForeground(lipgloss.Color("212"))
|
inputStyle = inputStyle.BorderForeground(lipgloss.Color("212"))
|
||||||
inputContent += "█"
|
inputContent += "█"
|
||||||
@@ -806,7 +1110,7 @@ func (m *Model) View() string {
|
|||||||
if m.showLog {
|
if m.showLog {
|
||||||
logHelp = "L chat"
|
logHelp = "L chat"
|
||||||
}
|
}
|
||||||
help := lipgloss.NewStyle().Faint(true).Render(fmt.Sprintf("↑↓ navigate │ Enter join │ Tab switch │ %s │ V talk │ M mute │ +/- vol │ q quit", logHelp))
|
help := lipgloss.NewStyle().Faint(true).Render(fmt.Sprintf("↑↓ nav │ Ent join │ Tab switch │ %s │ V PTT │ G VAD │ ^↕↔ thresh │ M mute │ +/- vol │ q quit", logHelp))
|
||||||
|
|
||||||
// Combine panels
|
// Combine panels
|
||||||
panels := lipgloss.JoinHorizontal(lipgloss.Top, channelPanel, rightPanel)
|
panels := lipgloss.JoinHorizontal(lipgloss.Top, channelPanel, rightPanel)
|
||||||
@@ -849,12 +1153,85 @@ func (m *Model) renderStatusBar() string {
|
|||||||
}
|
}
|
||||||
volPart := fmt.Sprintf("%s:%s%d%%", muteIcon, volBar, m.playbackVol)
|
volPart := fmt.Sprintf("%s:%s%d%%", muteIcon, volBar, m.playbackVol)
|
||||||
|
|
||||||
micBar := audio.LevelToBar(m.micLevel, 6)
|
// Custom Mic Bar with VAD Threshold
|
||||||
pttIcon := "MIC"
|
micBarWidth := 8
|
||||||
if m.isPTT {
|
var micBar string
|
||||||
pttIcon = "*TX*"
|
|
||||||
|
if m.vadEnabled {
|
||||||
|
// Calculate threshold position
|
||||||
|
threshPos := m.vadThreshold * micBarWidth / 100
|
||||||
|
if threshPos >= micBarWidth {
|
||||||
|
threshPos = micBarWidth - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate filled position based on current level
|
||||||
|
filled := m.micLevel * micBarWidth / 100
|
||||||
|
|
||||||
|
// Build bar
|
||||||
|
var sb strings.Builder
|
||||||
|
for i := 0; i < micBarWidth; i++ {
|
||||||
|
char := "░"
|
||||||
|
if i < filled {
|
||||||
|
char = "█"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overlay threshold marker
|
||||||
|
if i == threshPos {
|
||||||
|
if i < filled {
|
||||||
|
// Threshold is met
|
||||||
|
char = "▓"
|
||||||
|
} else {
|
||||||
|
// Threshold not met
|
||||||
|
char = "│"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb.WriteString(char)
|
||||||
|
}
|
||||||
|
micBar = sb.String()
|
||||||
|
} else {
|
||||||
|
micBar = audio.LevelToBar(m.micLevel, micBarWidth)
|
||||||
}
|
}
|
||||||
micPart := fmt.Sprintf("%s:%s", pttIcon, micBar)
|
|
||||||
|
pttStyle := lipgloss.NewStyle()
|
||||||
|
pttIcon := "MIC"
|
||||||
|
|
||||||
|
if m.isPTT {
|
||||||
|
pttIcon = " ON" // Manual ON
|
||||||
|
pttStyle = pttStyle.Foreground(lipgloss.Color("196")).Bold(true) // Red
|
||||||
|
} else if m.vadEnabled {
|
||||||
|
pttIcon = "VAD"
|
||||||
|
// Check if actively transmitting (using logic with decay)
|
||||||
|
isTransmitting := false
|
||||||
|
if !m.isMuted {
|
||||||
|
if m.micLevel > m.vadThreshold {
|
||||||
|
isTransmitting = true
|
||||||
|
} else if !m.vadLastTriggered.IsZero() && time.Since(m.vadLastTriggered) < 1*time.Second {
|
||||||
|
isTransmitting = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if isTransmitting {
|
||||||
|
// Transmitting via VAD: Red/Bold
|
||||||
|
pttStyle = pttStyle.Foreground(lipgloss.Color("196")).Bold(true)
|
||||||
|
} else {
|
||||||
|
// Idle VAD: Gray/Faint
|
||||||
|
pttStyle = pttStyle.Foreground(lipgloss.Color("240")).Faint(true)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Standard Mic (PTT mode but off)
|
||||||
|
pttStyle = pttStyle.Foreground(lipgloss.Color("255")) // White
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply status bar background color to prevent cutting
|
||||||
|
pttStyle = pttStyle.Background(lipgloss.Color("57")) // Matches Top Bar Background
|
||||||
|
|
||||||
|
// Style for the bar itself to maintain background continuity
|
||||||
|
barStyle := lipgloss.NewStyle().Background(lipgloss.Color("57")).Foreground(lipgloss.Color("255"))
|
||||||
|
|
||||||
|
micPart := fmt.Sprintf("%s%s%s",
|
||||||
|
pttStyle.Render(pttIcon),
|
||||||
|
barStyle.Render(":"),
|
||||||
|
barStyle.Render(micBar))
|
||||||
|
|
||||||
rightPart := fmt.Sprintf("%s | %s ", volPart, micPart)
|
rightPart := fmt.Sprintf("%s | %s ", volPart, micPart)
|
||||||
|
|
||||||
@@ -1060,14 +1437,118 @@ func (m *Model) renderUserView() string {
|
|||||||
"--- Audio Settings ---",
|
"--- Audio Settings ---",
|
||||||
fmt.Sprintf("%s %d%%", labelStyle.Render("Volume:"), int(vol*100)),
|
fmt.Sprintf("%s %d%%", labelStyle.Render("Volume:"), int(vol*100)),
|
||||||
fmt.Sprintf("%s %s", labelStyle.Render("Local Mute:"), muteStr),
|
fmt.Sprintf("%s %s", labelStyle.Render("Local Mute:"), muteStr),
|
||||||
|
}
|
||||||
|
|
||||||
|
// EQ Visualization
|
||||||
|
var eqGraph []string
|
||||||
|
if m.audioPlayer != nil {
|
||||||
|
bands := m.audioPlayer.GetEQBands(u.ID)
|
||||||
|
if len(bands) > 0 {
|
||||||
|
eqGraph = append(eqGraph, "", "--- Interactive Equalizer ---", "")
|
||||||
|
|
||||||
|
// Render bars for 5 bands
|
||||||
|
// 0: Bass, 1: Low-Mid, 2: Mid, 3: High-Mid, 4: High
|
||||||
|
labels := []string{"100Hz", "350Hz", "1kHz", "3kHz", "8kHz"}
|
||||||
|
|
||||||
|
for i, val := range bands {
|
||||||
|
if i >= len(labels) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get current gain setting
|
||||||
|
gain := m.audioPlayer.GetUserGain(u.ID, i)
|
||||||
|
|
||||||
|
// Scale 0.0-1.0 to bars (width 20)
|
||||||
|
const maxBars = 20
|
||||||
|
bars := int(val * maxBars)
|
||||||
|
if bars > maxBars {
|
||||||
|
bars = maxBars
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bar characters: █ ▇ ▆ ▅ ▄ ▃ ▂
|
||||||
|
barStr := ""
|
||||||
|
if bars > 0 {
|
||||||
|
barStr = strings.Repeat("█", bars)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Colorize based on intensity
|
||||||
|
barStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("39")) // Blue default
|
||||||
|
if val > 0.8 {
|
||||||
|
barStyle = barStyle.Foreground(lipgloss.Color("196")) // Red clipping
|
||||||
|
} else if val > 0.5 {
|
||||||
|
barStyle = barStyle.Foreground(lipgloss.Color("208")) // Orange high
|
||||||
|
} else if val > 0.2 {
|
||||||
|
barStyle = barStyle.Foreground(lipgloss.Color("46")) // Green normal
|
||||||
|
}
|
||||||
|
|
||||||
|
// Selection Indicator
|
||||||
|
selector := " "
|
||||||
|
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Width(6)
|
||||||
|
gainStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("245")).Width(6)
|
||||||
|
|
||||||
|
if i == m.eqBandIdx {
|
||||||
|
selector = "->"
|
||||||
|
labelStyle = labelStyle.Foreground(lipgloss.Color("226")).Bold(true) // Yellow for selected
|
||||||
|
gainStyle = gainStyle.Foreground(lipgloss.Color("226"))
|
||||||
|
}
|
||||||
|
|
||||||
|
gainStr := fmt.Sprintf("%+3.0fdB", gain)
|
||||||
|
|
||||||
|
line := fmt.Sprintf("%s %s %s | %s",
|
||||||
|
selector,
|
||||||
|
labelStyle.Render(labels[i]),
|
||||||
|
gainStyle.Render(gainStr),
|
||||||
|
barStyle.Render(fmt.Sprintf("%-20s", barStr)))
|
||||||
|
|
||||||
|
eqGraph = append(eqGraph, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info = append(info, eqGraph...)
|
||||||
|
info = append(info,
|
||||||
"",
|
"",
|
||||||
"--- Menu ---",
|
"--- Menu ---",
|
||||||
"1. Poke (Not Impl)",
|
"1. Poke",
|
||||||
"2. Toggle Local Mute",
|
"2. Toggle Local Mute",
|
||||||
"+/-: Adjust Volume",
|
"+/-: Adjust Volume",
|
||||||
|
"Arrows: Adjust EQ",
|
||||||
"",
|
"",
|
||||||
"(Press ESC to close)",
|
"(Press ESC to close)",
|
||||||
}
|
)
|
||||||
|
|
||||||
return lipgloss.JoinVertical(lipgloss.Left, info...)
|
return lipgloss.JoinVertical(lipgloss.Left, info...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *Model) renderAboutView() string {
|
||||||
|
titleStyle := lipgloss.NewStyle().
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("205")).
|
||||||
|
MarginBottom(1).
|
||||||
|
Align(lipgloss.Center)
|
||||||
|
|
||||||
|
boxStyle := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("62")).
|
||||||
|
Padding(2).
|
||||||
|
Width(60).
|
||||||
|
Align(lipgloss.Center)
|
||||||
|
|
||||||
|
mainContent := lipgloss.JoinVertical(lipgloss.Center,
|
||||||
|
titleStyle.Render("TS3 TUI CLIENT"),
|
||||||
|
lipgloss.NewStyle().Foreground(lipgloss.Color("250")).Render("Una terminal potente para tus comunidades."),
|
||||||
|
"",
|
||||||
|
lipgloss.NewStyle().Bold(true).Render("Realizado por JosLeDeta"),
|
||||||
|
lipgloss.NewStyle().Italic(true).Faint(true).Render("Hecho en Antigravity"),
|
||||||
|
"",
|
||||||
|
lipgloss.NewStyle().Bold(true).Render("Con la ayuda de:"),
|
||||||
|
lipgloss.NewStyle().Foreground(lipgloss.Color("212")).Render("- Gemini 3 Pro"),
|
||||||
|
lipgloss.NewStyle().Foreground(lipgloss.Color("212")).Render("- Claude Opus 4.5"),
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
lipgloss.NewStyle().Faint(true).Render("(Presiona ESC o F1 para volver)"),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Center everything on screen
|
||||||
|
return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, boxStyle.Render(mainContent))
|
||||||
|
}
|
||||||
|
|||||||
24
cmd/tui/noise_linux.go
Normal file
24
cmd/tui/noise_linux.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
func redirectStderr(f *os.File) {
|
||||||
|
if f == nil {
|
||||||
|
// Silence altogether if no debug file
|
||||||
|
null, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
|
||||||
|
if err == nil {
|
||||||
|
_ = unix.Dup2(int(null.Fd()), int(os.Stderr.Fd()))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect fd 2 (stderr) to our debug file
|
||||||
|
// This captures C-level library noise (ALSA, PortAudio) into the log
|
||||||
|
_ = unix.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
|
||||||
|
}
|
||||||
12
cmd/tui/noise_other.go
Normal file
12
cmd/tui/noise_other.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
//go:build !linux
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func redirectStderr(f *os.File) {
|
||||||
|
// No-op on other platforms for now
|
||||||
|
// Windows doesn't have the ALSA noise problem
|
||||||
|
}
|
||||||
2
go.mod
2
go.mod
@@ -13,6 +13,7 @@ require (
|
|||||||
github.com/charmbracelet/bubbletea v1.3.10
|
github.com/charmbracelet/bubbletea v1.3.10
|
||||||
github.com/charmbracelet/lipgloss v1.1.0
|
github.com/charmbracelet/lipgloss v1.1.0
|
||||||
github.com/go-ole/go-ole v1.2.6
|
github.com/go-ole/go-ole v1.2.6
|
||||||
|
github.com/gordonklaus/portaudio v0.0.0-20250206071425-98a94950218b
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
github.com/moutend/go-wca v0.3.0
|
github.com/moutend/go-wca v0.3.0
|
||||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302
|
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302
|
||||||
@@ -29,6 +30,7 @@ require (
|
|||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
|
github.com/moutend/go-equalizer v0.1.0 // indirect
|
||||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||||
github.com/muesli/termenv v0.16.0 // indirect
|
github.com/muesli/termenv v0.16.0 // indirect
|
||||||
|
|||||||
4
go.sum
4
go.sum
@@ -20,6 +20,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
|
|||||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||||
|
github.com/gordonklaus/portaudio v0.0.0-20250206071425-98a94950218b h1:WEuQWBxelOGHA6z9lABqaMLMrfwVyMdN3UgRLT+YUPo=
|
||||||
|
github.com/gordonklaus/portaudio v0.0.0-20250206071425-98a94950218b/go.mod h1:esZFQEUwqC+l76f2R8bIWSwXMaPbp79PppwZ1eJhFco=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||||
@@ -30,6 +32,8 @@ github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2J
|
|||||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
||||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
|
github.com/moutend/go-equalizer v0.1.0 h1:FDFsTr/zKUpLbNXZQmCMRDgisQhXxFOnX2q0PllJvxs=
|
||||||
|
github.com/moutend/go-equalizer v0.1.0/go.mod h1:iahcZcStDm66TNtrkMIhrQuhWdiWbFKSVjZ8yn+7Cgw=
|
||||||
github.com/moutend/go-wca v0.3.0 h1:IzhsQ44zBzMdT42xlBjiLSVya9cPYOoKx9E+yXVhFo8=
|
github.com/moutend/go-wca v0.3.0 h1:IzhsQ44zBzMdT42xlBjiLSVya9cPYOoKx9E+yXVhFo8=
|
||||||
github.com/moutend/go-wca v0.3.0/go.mod h1:7VrPO512jnjFGJ6rr+zOoCfiYjOHRPNfbttJuxAurcw=
|
github.com/moutend/go-wca v0.3.0/go.mod h1:7VrPO512jnjFGJ6rr+zOoCfiYjOHRPNfbttJuxAurcw=
|
||||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ type Client struct {
|
|||||||
PingPacketID uint16 // Type 0x04
|
PingPacketID uint16 // Type 0x04
|
||||||
PongPacketID uint16 // Type 0x05
|
PongPacketID uint16 // Type 0x05
|
||||||
AckPacketID uint16 // Type 0x06
|
AckPacketID uint16 // Type 0x06
|
||||||
|
AckLowPacketID uint16 // Type 0x07
|
||||||
|
|
||||||
// Ping RTT tracking
|
// Ping RTT tracking
|
||||||
PingSentTimes map[uint16]time.Time // Map PingPacketID -> Time sent
|
PingSentTimes map[uint16]time.Time // Map PingPacketID -> Time sent
|
||||||
@@ -48,10 +49,14 @@ type Client struct {
|
|||||||
ServerName string
|
ServerName string
|
||||||
|
|
||||||
// Fragment reassembly (packet queue like ts3j)
|
// Fragment reassembly (packet queue like ts3j)
|
||||||
CommandQueue map[uint16]*protocol.Packet // Packets waiting for reassembly
|
CommandQueue map[uint16]*protocol.Packet // Packets waiting for reassembly (Type 0x02)
|
||||||
ExpectedCommandPID uint16 // Next expected packet ID
|
ExpectedCommandPID uint16 // Next expected packet ID (Type 0x02)
|
||||||
FragmentState bool // Toggle: true = collecting, false = ready
|
FragmentState bool // Toggle: true = collecting, false = ready
|
||||||
|
|
||||||
|
CommandLowQueue map[uint16]*protocol.Packet // Packets waiting for reassembly (Type 0x03)
|
||||||
|
ExpectedCommandLowPID uint16 // Next expected packet ID (Type 0x03)
|
||||||
|
FragmentStateLow bool // Toggle: true = collecting, false = ready
|
||||||
|
|
||||||
// Server Data
|
// Server Data
|
||||||
Channels map[uint64]*Channel
|
Channels map[uint64]*Channel
|
||||||
|
|
||||||
@@ -69,17 +74,20 @@ type Client struct {
|
|||||||
|
|
||||||
func NewClient(nickname string) *Client {
|
func NewClient(nickname string) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
Nickname: nickname,
|
Nickname: nickname,
|
||||||
PacketIDCounterC2S: 1,
|
PacketIDCounterC2S: 1,
|
||||||
VoicePacketID: 1,
|
AckLowPacketID: 1,
|
||||||
Channels: make(map[uint64]*Channel),
|
VoicePacketID: 1,
|
||||||
VoiceDecoders: make(map[uint16]*opus.Decoder),
|
Channels: make(map[uint64]*Channel),
|
||||||
CommandQueue: make(map[uint16]*protocol.Packet),
|
VoiceDecoders: make(map[uint16]*opus.Decoder),
|
||||||
ExpectedCommandPID: 0,
|
CommandQueue: make(map[uint16]*protocol.Packet),
|
||||||
PingSentTimes: make(map[uint16]time.Time),
|
ExpectedCommandPID: 0,
|
||||||
PingRTT: 0,
|
CommandLowQueue: make(map[uint16]*protocol.Packet),
|
||||||
PingDeviation: 0,
|
ExpectedCommandLowPID: 0,
|
||||||
done: make(chan struct{}),
|
PingSentTimes: make(map[uint16]time.Time),
|
||||||
|
PingRTT: 0,
|
||||||
|
PingDeviation: 0,
|
||||||
|
done: make(chan struct{}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,26 +142,41 @@ func (c *Client) Connect(address string) error {
|
|||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
// Recovery from panics in the main loop
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
log.Printf("PANIC in Client loop: %v", r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-c.done:
|
||||||
|
log.Println("Client loop stopped")
|
||||||
|
return
|
||||||
|
case pkt := <-pktChan:
|
||||||
|
if pkt == nil {
|
||||||
|
// Channel closed
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := c.handlePacket(pkt); err != nil {
|
||||||
|
log.Printf("Error handling packet: %v", err)
|
||||||
|
}
|
||||||
|
case <-ticker.C:
|
||||||
|
if !c.Connected {
|
||||||
|
return // Don't send pings if not connected yet
|
||||||
|
}
|
||||||
|
// Send KeepAlive Ping (Encrypted, No NewProtocol)
|
||||||
|
if err := c.sendPing(); err != nil {
|
||||||
|
log.Printf("Error sending Ping: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
// Check if we should exit after the inner function
|
||||||
select {
|
select {
|
||||||
case <-c.done:
|
case <-c.done:
|
||||||
log.Println("Client loop stopped")
|
|
||||||
return nil
|
return nil
|
||||||
case pkt := <-pktChan:
|
default:
|
||||||
if pkt == nil {
|
|
||||||
// Channel closed
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if err := c.handlePacket(pkt); err != nil {
|
|
||||||
log.Printf("Error handling packet: %v", err)
|
|
||||||
}
|
|
||||||
case <-ticker.C:
|
|
||||||
if !c.Connected {
|
|
||||||
continue // Don't send pings if not connected yet
|
|
||||||
}
|
|
||||||
// Send KeepAlive Ping (Encrypted, No NewProtocol)
|
|
||||||
if err := c.sendPing(); err != nil {
|
|
||||||
log.Printf("Error sending Ping: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,21 @@ func sanitizeForLog(s string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
||||||
|
// Select the correct queue and counters based on PacketType
|
||||||
|
var queue map[uint16]*protocol.Packet
|
||||||
|
var expectedPID *uint16
|
||||||
|
var fragmentState *bool
|
||||||
|
|
||||||
|
if pkt.Header.PacketType() == protocol.PacketTypeCommandLow {
|
||||||
|
queue = c.CommandLowQueue
|
||||||
|
expectedPID = &c.ExpectedCommandLowPID
|
||||||
|
fragmentState = &c.FragmentStateLow
|
||||||
|
} else {
|
||||||
|
queue = c.CommandQueue
|
||||||
|
expectedPID = &c.ExpectedCommandPID
|
||||||
|
fragmentState = &c.FragmentState
|
||||||
|
}
|
||||||
|
|
||||||
// Check if Encrypted
|
// Check if Encrypted
|
||||||
// PacketTypeCommand is usually encrypted.
|
// PacketTypeCommand is usually encrypted.
|
||||||
// Flag check? The flag is in the Header (e.g. Unencrypted flag).
|
// Flag check? The flag is in the Header (e.g. Unencrypted flag).
|
||||||
@@ -100,14 +115,14 @@ func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
|||||||
|
|
||||||
// Queue-based fragment reassembly (like ts3j)
|
// Queue-based fragment reassembly (like ts3j)
|
||||||
// Store packet in queue
|
// Store packet in queue
|
||||||
c.CommandQueue[pkt.Header.PacketID] = &protocol.Packet{
|
queue[pkt.Header.PacketID] = &protocol.Packet{
|
||||||
Header: pkt.Header,
|
Header: pkt.Header,
|
||||||
Data: append([]byte{}, data...), // Clone data (already decrypted)
|
Data: append([]byte{}, data...), // Clone data (already decrypted)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to process packets in order
|
// Try to process packets in order
|
||||||
for {
|
for {
|
||||||
nextPkt, ok := c.CommandQueue[c.ExpectedCommandPID]
|
nextPkt, ok := queue[*expectedPID]
|
||||||
if !ok {
|
if !ok {
|
||||||
// Missing packet, wait for it
|
// Missing packet, wait for it
|
||||||
break
|
break
|
||||||
@@ -117,16 +132,16 @@ func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
|||||||
|
|
||||||
if isFragmented {
|
if isFragmented {
|
||||||
// Toggle fragment state
|
// Toggle fragment state
|
||||||
c.FragmentState = !c.FragmentState
|
*fragmentState = !*fragmentState
|
||||||
|
|
||||||
if c.FragmentState {
|
if *fragmentState {
|
||||||
// Starting a new fragment sequence
|
// Starting a new fragment sequence
|
||||||
// Don't process yet, wait for more
|
// Don't process yet, wait for more
|
||||||
c.ExpectedCommandPID++
|
*expectedPID++
|
||||||
continue
|
continue
|
||||||
} else {
|
} else {
|
||||||
// Ending fragment sequence - reassemble all
|
// Ending fragment sequence - reassemble all
|
||||||
reassembled, compressed := c.reassembleFragments()
|
reassembled, compressed := c.reassembleFragmentsCustom(queue, *expectedPID)
|
||||||
if reassembled == nil {
|
if reassembled == nil {
|
||||||
log.Printf("Fragment reassembly failed")
|
log.Printf("Fragment reassembly failed")
|
||||||
break
|
break
|
||||||
@@ -144,9 +159,9 @@ func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if c.FragmentState {
|
} else if *fragmentState {
|
||||||
// Middle fragment - keep collecting
|
// Middle fragment - keep collecting
|
||||||
c.ExpectedCommandPID++
|
*expectedPID++
|
||||||
continue
|
continue
|
||||||
} else {
|
} else {
|
||||||
// Non-fragmented packet - process normally
|
// Non-fragmented packet - process normally
|
||||||
@@ -165,10 +180,11 @@ func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Remove processed packet from queue
|
// Remove processed packet from queue
|
||||||
delete(c.CommandQueue, c.ExpectedCommandPID)
|
delete(queue, *expectedPID)
|
||||||
c.ExpectedCommandPID++
|
*expectedPID++
|
||||||
|
|
||||||
// Process the command
|
// Process the command
|
||||||
|
// Fix: processCommand should probably handle execution
|
||||||
if err := c.processCommand(data, nextPkt); err != nil {
|
if err := c.processCommand(data, nextPkt); err != nil {
|
||||||
log.Printf("Error processing command: %v", err)
|
log.Printf("Error processing command: %v", err)
|
||||||
}
|
}
|
||||||
@@ -177,16 +193,17 @@ func (c *Client) handleCommand(pkt *protocol.Packet) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// reassembleFragments collects all buffered fragments in order and returns reassembled data
|
// reassembleFragmentsCustom collects all buffered fragments in order from the given queue
|
||||||
func (c *Client) reassembleFragments() ([]byte, bool) {
|
// ending at currentPID.
|
||||||
|
func (c *Client) reassembleFragmentsCustom(queue map[uint16]*protocol.Packet, currentPID uint16) ([]byte, bool) {
|
||||||
var result []byte
|
var result []byte
|
||||||
compressed := false
|
compressed := false
|
||||||
|
|
||||||
// Find the start of the fragment sequence (scan backwards from current)
|
// Find the start of the fragment sequence (scan backwards from current)
|
||||||
startPID := c.ExpectedCommandPID
|
startPID := currentPID
|
||||||
for {
|
for {
|
||||||
prevPID := startPID - 1
|
prevPID := startPID - 1
|
||||||
pkt, ok := c.CommandQueue[prevPID]
|
pkt, ok := queue[prevPID]
|
||||||
if !ok {
|
if !ok {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -198,9 +215,9 @@ func (c *Client) reassembleFragments() ([]byte, bool) {
|
|||||||
startPID = prevPID
|
startPID = prevPID
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now collect from startPID to ExpectedCommandPID (inclusive)
|
// Now collect from startPID to currentPID (inclusive)
|
||||||
for pid := startPID; pid <= c.ExpectedCommandPID; pid++ {
|
for pid := startPID; pid <= currentPID; pid++ {
|
||||||
pkt, ok := c.CommandQueue[pid]
|
pkt, ok := queue[pid]
|
||||||
if !ok {
|
if !ok {
|
||||||
log.Printf("Missing fragment PID=%d during reassembly", pid)
|
log.Printf("Missing fragment PID=%d during reassembly", pid)
|
||||||
return nil, false
|
return nil, false
|
||||||
@@ -212,11 +229,11 @@ func (c *Client) reassembleFragments() ([]byte, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
result = append(result, pkt.Data...)
|
result = append(result, pkt.Data...)
|
||||||
delete(c.CommandQueue, pid)
|
delete(queue, pid)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Reassembled fragments PID %d-%d, total %d bytes, compressed=%v",
|
log.Printf("Reassembled fragments PID %d-%d, total %d bytes, compressed=%v",
|
||||||
startPID, c.ExpectedCommandPID, len(result), compressed)
|
startPID, currentPID, len(result), compressed)
|
||||||
|
|
||||||
return result, compressed
|
return result, compressed
|
||||||
}
|
}
|
||||||
@@ -226,8 +243,8 @@ func (c *Client) processCommand(data []byte, pkt *protocol.Packet) error {
|
|||||||
cmdStr := string(data)
|
cmdStr := string(data)
|
||||||
|
|
||||||
// Debug: Log packet flags and raw command preview (sanitized)
|
// Debug: Log packet flags and raw command preview (sanitized)
|
||||||
log.Printf("Debug Packet: Compressed=%v, Fragmented=%v, RawLen=%d, Preview=%q",
|
log.Printf("Debug Packet: PID=%d, Compressed=%v, Fragmented=%v, RawLen=%d, Preview=%q",
|
||||||
pkt.Header.FlagCompressed(), pkt.Header.FlagFragmented(), len(data),
|
pkt.Header.PacketID, pkt.Header.FlagCompressed(), pkt.Header.FlagFragmented(), len(data),
|
||||||
func() string {
|
func() string {
|
||||||
preview := cmdStr
|
preview := cmdStr
|
||||||
if len(preview) > 100 {
|
if len(preview) > 100 {
|
||||||
@@ -544,6 +561,28 @@ func (c *Client) processCommand(data []byte, pkt *protocol.Packet) error {
|
|||||||
"message": msg,
|
"message": msg,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
case "notifyclientpoke":
|
||||||
|
msg := ""
|
||||||
|
invoker := "Unknown"
|
||||||
|
var invokerID uint16
|
||||||
|
if m, ok := args["msg"]; ok {
|
||||||
|
msg = protocol.Unescape(m)
|
||||||
|
}
|
||||||
|
if name, ok := args["invokername"]; ok {
|
||||||
|
invoker = protocol.Unescape(name)
|
||||||
|
}
|
||||||
|
if iid, ok := args["invokerid"]; ok {
|
||||||
|
var id uint64
|
||||||
|
fmt.Sscanf(iid, "%d", &id)
|
||||||
|
invokerID = uint16(id)
|
||||||
|
}
|
||||||
|
log.Printf("[Poke] %s: %s", invoker, msg)
|
||||||
|
c.emitEvent("client_poke", map[string]any{
|
||||||
|
"senderID": invokerID,
|
||||||
|
"senderName": invoker,
|
||||||
|
"message": msg,
|
||||||
|
})
|
||||||
|
|
||||||
case "notifyservergrouplist", "notifychannelgrouplist", "notifyclientneededpermissions":
|
case "notifyservergrouplist", "notifychannelgrouplist", "notifyclientneededpermissions":
|
||||||
// Ignore verbose noisy setup commands
|
// Ignore verbose noisy setup commands
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -55,6 +55,46 @@ func (c *Client) handlePacket(pkt *protocol.Packet) error {
|
|||||||
|
|
||||||
c.Conn.SendPacket(ack)
|
c.Conn.SendPacket(ack)
|
||||||
|
|
||||||
|
return c.handleCommand(pkt)
|
||||||
|
case protocol.PacketTypeCommandLow:
|
||||||
|
// Send ACK Low
|
||||||
|
ackData := make([]byte, 2)
|
||||||
|
binary.BigEndian.PutUint16(ackData, pkt.Header.PacketID)
|
||||||
|
|
||||||
|
ack := protocol.NewPacket(protocol.PacketTypeAckLow, ackData)
|
||||||
|
// Spec/ts3j: AckLow has its own counter
|
||||||
|
c.AckLowPacketID++
|
||||||
|
ack.Header.PacketID = c.AckLowPacketID
|
||||||
|
ack.Header.ClientID = c.ClientID
|
||||||
|
// ACKs usually don't have NewProtocol flag set in Header byte
|
||||||
|
ack.Header.Type &= ^uint8(protocol.PacketFlagNewProtocol)
|
||||||
|
|
||||||
|
// ACKs for Command packets after handshake must be encrypted
|
||||||
|
key := protocol.HandshakeKey
|
||||||
|
nonce := protocol.HandshakeNonce
|
||||||
|
|
||||||
|
if c.Handshake != nil && c.Handshake.Step >= 6 && len(c.Handshake.SharedIV) > 0 {
|
||||||
|
crypto := &protocol.CryptoState{
|
||||||
|
SharedIV: c.Handshake.SharedIV,
|
||||||
|
SharedMac: c.Handshake.SharedMac,
|
||||||
|
GenerationID: 0,
|
||||||
|
}
|
||||||
|
key, nonce = crypto.GenerateKeyNonce(&ack.Header, true) // Client->Server=true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Meta for Client->Server: PID(2) + CID(2) + PT(1) = 5 bytes
|
||||||
|
meta := make([]byte, 5)
|
||||||
|
binary.BigEndian.PutUint16(meta[0:2], ack.Header.PacketID)
|
||||||
|
binary.BigEndian.PutUint16(meta[2:4], ack.Header.ClientID)
|
||||||
|
meta[4] = ack.Header.Type
|
||||||
|
|
||||||
|
encData, mac, _ := protocol.EncryptEAX(key, nonce, meta, ack.Data)
|
||||||
|
ack.Data = encData
|
||||||
|
copy(ack.Header.MAC[:], mac)
|
||||||
|
// log.Printf("Sending ACK Low for server CommandLow PID=%d", pkt.Header.PacketID)
|
||||||
|
|
||||||
|
c.Conn.SendPacket(ack)
|
||||||
|
|
||||||
return c.handleCommand(pkt)
|
return c.handleCommand(pkt)
|
||||||
case protocol.PacketTypeVoice:
|
case protocol.PacketTypeVoice:
|
||||||
c.handleVoice(pkt)
|
c.handleVoice(pkt)
|
||||||
|
|||||||
135
pkg/audio/biquad.go
Normal file
135
pkg/audio/biquad.go
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
package audio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/moutend/go-equalizer/pkg/equalizer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EQChain manages a cascade of filters using go-equalizer library
|
||||||
|
// Now supports Stereo processing (Left/Right)
|
||||||
|
// EQChain manages a cascade of filters using go-equalizer library
|
||||||
|
// Now supports Stereo processing (Left/Right)
|
||||||
|
type EQChain struct {
|
||||||
|
FiltersLeft []*equalizer.Filter
|
||||||
|
FiltersRight []*equalizer.Filter
|
||||||
|
buffer []float64 // Reusable scratch buffer for processing
|
||||||
|
currentGains []float64 // Cache of current gain values
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewEQChain creates the standard 5-band EQ chain (Stereo)
|
||||||
|
func NewEQChain(sampleRate float64) *EQChain {
|
||||||
|
// Standard bands: 100, 350, 1000, 3000, 8000
|
||||||
|
// Width = 1.0 (approx 1 octave)
|
||||||
|
|
||||||
|
createChain := func() []*equalizer.Filter {
|
||||||
|
f1 := equalizer.NewPeaking(sampleRate, 100, 1.0, 0)
|
||||||
|
f2 := equalizer.NewPeaking(sampleRate, 350, 1.0, 0)
|
||||||
|
f3 := equalizer.NewPeaking(sampleRate, 1000, 1.0, 0)
|
||||||
|
f4 := equalizer.NewPeaking(sampleRate, 3000, 1.0, 0)
|
||||||
|
f5 := equalizer.NewPeaking(sampleRate, 8000, 1.0, 0)
|
||||||
|
return []*equalizer.Filter{f1, f2, f3, f4, f5}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &EQChain{
|
||||||
|
FiltersLeft: createChain(),
|
||||||
|
FiltersRight: createChain(),
|
||||||
|
buffer: make([]float64, 1920), // Pre-allocate for Stereo 20ms frame (960*2)
|
||||||
|
currentGains: make([]float64, 5), // Initialize cache with 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetGain sets the gain for a specific band index (0-4)
|
||||||
|
func (e *EQChain) SetGain(bandIdx int, dbGain float64) {
|
||||||
|
if bandIdx < 0 || bandIdx >= 5 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optimization: If gain hasn't changed, DO NOT recreate filter.
|
||||||
|
// Recreating the filter resets its internal history state (bi-quad delay buffers),
|
||||||
|
// causing audible clicks/pops (discontinuities) at every 20ms frame boundary.
|
||||||
|
const epsilon = 0.001
|
||||||
|
if delta := dbGain - e.currentGains[bandIdx]; delta > -epsilon && delta < epsilon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rate := 48000.0 // Assuming fixed rate for now
|
||||||
|
// Frequencies map to our standard bands
|
||||||
|
freqs := []float64{100, 350, 1000, 3000, 8000}
|
||||||
|
|
||||||
|
// Create new filter with updated gain
|
||||||
|
// We use width=1.0 consistent with constructor
|
||||||
|
// Update BOTH Left and Right to keep balance
|
||||||
|
e.FiltersLeft[bandIdx] = equalizer.NewPeaking(rate, freqs[bandIdx], 1.0, dbGain)
|
||||||
|
e.FiltersRight[bandIdx] = equalizer.NewPeaking(rate, freqs[bandIdx], 1.0, dbGain)
|
||||||
|
|
||||||
|
// Update cache
|
||||||
|
e.currentGains[bandIdx] = dbGain
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset clears history of all filters
|
||||||
|
func (e *EQChain) Reset() {
|
||||||
|
// The library does not expose a Reset method.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process processes a slice of samples (Interleaved Stereo)
|
||||||
|
func (e *EQChain) Process(samples []int16) []int16 {
|
||||||
|
// Grow buffer if needed
|
||||||
|
if cap(e.buffer) < len(samples) {
|
||||||
|
e.buffer = make([]float64, len(samples))
|
||||||
|
}
|
||||||
|
e.buffer = e.buffer[:len(samples)]
|
||||||
|
|
||||||
|
// Float conversion with normalization (-1.0 to 1.0)
|
||||||
|
// We also apply a slight pre-attenuation (Headroom) to avoid clipping when boosting EQ.
|
||||||
|
// -3dB = 0.707
|
||||||
|
const headroom = 0.707
|
||||||
|
const norm = 1.0 / 32768.0
|
||||||
|
|
||||||
|
for i, s := range samples {
|
||||||
|
e.buffer[i] = float64(s) * norm * headroom
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter processing
|
||||||
|
// Input is assumed to be Interleaved Stereo: L, R, L, R...
|
||||||
|
// We iterate by 2 to process pairs.
|
||||||
|
|
||||||
|
for i := 0; i < len(e.buffer); i += 2 {
|
||||||
|
if i+1 >= len(e.buffer) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
valL := e.buffer[i]
|
||||||
|
valR := e.buffer[i+1]
|
||||||
|
|
||||||
|
// Run through LEFT chain
|
||||||
|
for _, f := range e.FiltersLeft {
|
||||||
|
valL = f.Apply(valL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run through RIGHT chain
|
||||||
|
for _, f := range e.FiltersRight {
|
||||||
|
valR = f.Apply(valR)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write back to buffer
|
||||||
|
e.buffer[i] = valL
|
||||||
|
e.buffer[i+1] = valR
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert back to int16
|
||||||
|
for i, val := range e.buffer {
|
||||||
|
// Denormalize
|
||||||
|
val = val * 32767.0
|
||||||
|
|
||||||
|
// Hard clipping
|
||||||
|
if val > 32767 {
|
||||||
|
val = 32767
|
||||||
|
} else if val < -32768 {
|
||||||
|
val = -32768
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write back directly to samples
|
||||||
|
samples[i] = int16(val)
|
||||||
|
}
|
||||||
|
|
||||||
|
return samples
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
package audio
|
package audio
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -11,8 +13,6 @@ import (
|
|||||||
"github.com/moutend/go-wca/pkg/wca"
|
"github.com/moutend/go-wca/pkg/wca"
|
||||||
)
|
)
|
||||||
|
|
||||||
const captureFrameSamples = 960 // 20ms at 48kHz
|
|
||||||
|
|
||||||
// Capturer handles WASAPI audio capture from microphone
|
// Capturer handles WASAPI audio capture from microphone
|
||||||
type Capturer struct {
|
type Capturer struct {
|
||||||
client *wca.IAudioClient
|
client *wca.IAudioClient
|
||||||
@@ -22,6 +22,7 @@ type Capturer struct {
|
|||||||
running bool
|
running bool
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
stopChan chan struct{}
|
stopChan chan struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
|
||||||
// Callback for captured audio (called with 960-sample frames)
|
// Callback for captured audio (called with 960-sample frames)
|
||||||
onAudio func(samples []int16)
|
onAudio func(samples []int16)
|
||||||
@@ -136,6 +137,7 @@ func (c *Capturer) Start() error {
|
|||||||
return fmt.Errorf("failed to start audio client: %w", err)
|
return fmt.Errorf("failed to start audio client: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.wg.Add(1)
|
||||||
go c.captureLoop()
|
go c.captureLoop()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -151,6 +153,7 @@ func (c *Capturer) Stop() {
|
|||||||
c.mu.Unlock()
|
c.mu.Unlock()
|
||||||
|
|
||||||
close(c.stopChan)
|
close(c.stopChan)
|
||||||
|
c.wg.Wait() // Wait for capture loop to finish before proceeding
|
||||||
c.client.Stop()
|
c.client.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,6 +183,7 @@ func (c *Capturer) IsRunning() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Capturer) captureLoop() {
|
func (c *Capturer) captureLoop() {
|
||||||
|
defer c.wg.Done()
|
||||||
ticker := time.NewTicker(10 * time.Millisecond) // Check more often than 20ms
|
ticker := time.NewTicker(10 * time.Millisecond) // Check more often than 20ms
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
|||||||
112
pkg/audio/capture_linux.go
Normal file
112
pkg/audio/capture_linux.go
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package audio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gordonklaus/portaudio"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Capturer handles audio capture using PortAudio
|
||||||
|
type Capturer struct {
|
||||||
|
stream *portaudio.Stream
|
||||||
|
running bool
|
||||||
|
mu sync.Mutex
|
||||||
|
onAudio func(samples []int16)
|
||||||
|
currentLevel int
|
||||||
|
levelMu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCapturer() (*Capturer, error) {
|
||||||
|
if err := initPortAudio(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Capturer{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) SetCallback(fn func(samples []int16)) {
|
||||||
|
c.mu.Lock()
|
||||||
|
c.onAudio = fn
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) Start() error {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if c.running {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
c.stream, err = portaudio.OpenDefaultStream(1, 0, 48000, frameSamples, c.processCapture)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to open portaudio capture stream: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.stream.Start(); err != nil {
|
||||||
|
c.stream.Close()
|
||||||
|
return fmt.Errorf("failed to start portaudio capture stream: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.running = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) Stop() {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if !c.running {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.running = false
|
||||||
|
if c.stream != nil {
|
||||||
|
c.stream.Abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) Close() {
|
||||||
|
c.Stop()
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.stream != nil {
|
||||||
|
c.stream.Close()
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
terminatePortAudio()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) processCapture(in []int16) {
|
||||||
|
c.mu.Lock()
|
||||||
|
callback := c.onAudio
|
||||||
|
running := c.running
|
||||||
|
c.mu.Unlock()
|
||||||
|
|
||||||
|
if !running || callback == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate level
|
||||||
|
level := CalculateRMSLevel(in)
|
||||||
|
c.levelMu.Lock()
|
||||||
|
c.currentLevel = level
|
||||||
|
c.levelMu.Unlock()
|
||||||
|
|
||||||
|
// Clone buffer and send to callback
|
||||||
|
samples := make([]int16, len(in))
|
||||||
|
copy(samples, in)
|
||||||
|
callback(samples)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) GetLevel() int {
|
||||||
|
c.levelMu.RLock()
|
||||||
|
defer c.levelMu.RUnlock()
|
||||||
|
return c.currentLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Capturer) IsRunning() bool {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return c.running
|
||||||
|
}
|
||||||
15
pkg/audio/common.go
Normal file
15
pkg/audio/common.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package audio
|
||||||
|
|
||||||
|
// Shared constants
|
||||||
|
const (
|
||||||
|
frameSamples = 960 // 20ms at 48kHz
|
||||||
|
captureFrameSamples = 960 // 20ms at 48kHz
|
||||||
|
)
|
||||||
|
|
||||||
|
// UserSettings represents per-user audio configuration
|
||||||
|
type UserSettings struct {
|
||||||
|
Volume float32 // 0.0 - 1.0 (or higher for boost)
|
||||||
|
Muted bool
|
||||||
|
Gains []float64 // 5-band Equalizer Gains in dB
|
||||||
|
EQBands []float64
|
||||||
|
}
|
||||||
138
pkg/audio/fft.go
Normal file
138
pkg/audio/fft.go
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
package audio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CalculateEQBands computes frequency magnitudes for 5 EQ bands from PCM samples.
|
||||||
|
// It uses a simplified approach tailored for visualization:
|
||||||
|
// 1. Converts int16 PCM to float64
|
||||||
|
// 2. Applies a Window function (Hanning)
|
||||||
|
// 3. Performs a simple DFT (Discrete Fourier Transform) - sufficient for small N/visualization
|
||||||
|
// 4. Aggregates bins into 5 bands: Bass, Low-Mid, Mid, Hybrid-High, High
|
||||||
|
func CalculateEQBands(samples []int16, sampleRate int) []float64 {
|
||||||
|
// We'll use a relatively small window size for responsiveness and performance
|
||||||
|
// 512 samples at 48kHz is ~10ms, which is very fast.
|
||||||
|
// 1024 samples is ~21ms.
|
||||||
|
|
||||||
|
const windowSize = 1024
|
||||||
|
if len(samples) < windowSize {
|
||||||
|
// Not enough data, return empty or zeroed bands
|
||||||
|
// Pad with zeros if we really wanted to processing, but for vis just return what we have?
|
||||||
|
// Actually, let's just make a copy and pad with zeros to windowSize
|
||||||
|
padded := make([]int16, windowSize)
|
||||||
|
copy(padded, samples)
|
||||||
|
samples = padded
|
||||||
|
} else {
|
||||||
|
// Take the last windowSize samples (most recent audio)
|
||||||
|
samples = samples[len(samples)-windowSize:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare complex input
|
||||||
|
real := make([]float64, windowSize)
|
||||||
|
imag := make([]float64, windowSize)
|
||||||
|
|
||||||
|
// Apply Hanning Window
|
||||||
|
for i := 0; i < windowSize; i++ {
|
||||||
|
val := float64(samples[i]) / 32768.0 // Normalize to -1.0..1.0
|
||||||
|
// Hanning window formula
|
||||||
|
window := 0.5 * (1 - math.Cos(2*math.Pi*float64(i)/float64(windowSize-1)))
|
||||||
|
real[i] = val * window
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perform basic FFT (Cooley-Tukey)
|
||||||
|
// Since windowSize is power of 2 (1024), we can use a recursive or iterative FFT.
|
||||||
|
// For simplicity in a single file without deps, we'll write a small recursive one or iterative.
|
||||||
|
// Given typical Go performance, a simple recursive one is fine for N=1024 per user talk event.
|
||||||
|
fft(real, imag)
|
||||||
|
|
||||||
|
// Calculate magnitudes and bucket into bands
|
||||||
|
// Freq resolution = SampleRate / WindowSize = 48000 / 1024 ~= 46.875 Hz per bin
|
||||||
|
// Nyquist = 24000 Hz (Bin 512)
|
||||||
|
|
||||||
|
// Band definitions (approximate range):
|
||||||
|
// 1. Sub/Bass: 0 - 250 Hz (Bins 0-5)
|
||||||
|
// 2. Low Mids: 250 - 500 Hz (Bins 6-10)
|
||||||
|
// 3. Mids: 500 - 2000 Hz (Bins 11-42)
|
||||||
|
// 4. Upper Mids: 2000 - 4000 Hz (Bins 43-85)
|
||||||
|
// 5. Highs: 4000Hz+ (Bins 86-512)
|
||||||
|
|
||||||
|
bands := make([]float64, 5)
|
||||||
|
|
||||||
|
// Helper to collect energy
|
||||||
|
collectEnergy := func(startBin, endBin int) float64 {
|
||||||
|
sum := 0.0
|
||||||
|
for i := startBin; i <= endBin && i < windowSize/2; i++ {
|
||||||
|
// Magnitude = sqrt(re^2 + im^2)
|
||||||
|
mag := math.Sqrt(real[i]*real[i] + imag[i]*imag[i])
|
||||||
|
sum += mag
|
||||||
|
}
|
||||||
|
// Average
|
||||||
|
count := float64(endBin - startBin + 1)
|
||||||
|
if count > 0 {
|
||||||
|
return sum / count
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
bands[0] = collectEnergy(1, 6) // Skip DC (bin 0)
|
||||||
|
bands[1] = collectEnergy(7, 12)
|
||||||
|
bands[2] = collectEnergy(13, 45)
|
||||||
|
bands[3] = collectEnergy(46, 90)
|
||||||
|
bands[4] = collectEnergy(91, 511)
|
||||||
|
|
||||||
|
// Normalize output for visualization (0.0 to 1.0)
|
||||||
|
// We need some scaling factor. Based on expected signals.
|
||||||
|
const scale = 10.0 // Reduced from 50.0 to fix saturation
|
||||||
|
for i := range bands {
|
||||||
|
bands[i] = bands[i] * scale
|
||||||
|
if bands[i] > 1.0 {
|
||||||
|
bands[i] = 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bands
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple in-place Cooley-Tukey FFT.
|
||||||
|
// n must be power of 2.
|
||||||
|
func fft(real, imag []float64) {
|
||||||
|
n := len(real)
|
||||||
|
if n <= 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split even and odd
|
||||||
|
half := n / 2
|
||||||
|
realEven := make([]float64, half)
|
||||||
|
imagEven := make([]float64, half)
|
||||||
|
realOdd := make([]float64, half)
|
||||||
|
imagOdd := make([]float64, half)
|
||||||
|
|
||||||
|
for i := 0; i < half; i++ {
|
||||||
|
realEven[i] = real[2*i]
|
||||||
|
imagEven[i] = imag[2*i]
|
||||||
|
realOdd[i] = real[2*i+1]
|
||||||
|
imagOdd[i] = imag[2*i+1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursion
|
||||||
|
fft(realEven, imagEven)
|
||||||
|
fft(realOdd, imagOdd)
|
||||||
|
|
||||||
|
// Combine
|
||||||
|
for k := 0; k < half; k++ {
|
||||||
|
tReal := math.Cos(-2 * math.Pi * float64(k) / float64(n))
|
||||||
|
tImag := math.Sin(-2 * math.Pi * float64(k) / float64(n))
|
||||||
|
|
||||||
|
// Multiply odd by twist factor (tReal+itImag) * (oddReal+iOddImag)
|
||||||
|
// (ac - bd) + i(ad + bc)
|
||||||
|
twistReal := tReal*realOdd[k] - tImag*imagOdd[k]
|
||||||
|
twistImag := tReal*imagOdd[k] + tImag*realOdd[k]
|
||||||
|
|
||||||
|
real[k] = realEven[k] + twistReal
|
||||||
|
imag[k] = imagEven[k] + twistImag
|
||||||
|
real[k+half] = realEven[k] - twistReal
|
||||||
|
imag[k+half] = imagEven[k] - twistImag
|
||||||
|
}
|
||||||
|
}
|
||||||
45
pkg/audio/global_linux.go
Normal file
45
pkg/audio/global_linux.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package audio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gordonklaus/portaudio"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
paMu sync.Mutex
|
||||||
|
paRefCount int
|
||||||
|
)
|
||||||
|
|
||||||
|
func initPortAudio() error {
|
||||||
|
paMu.Lock()
|
||||||
|
defer paMu.Unlock()
|
||||||
|
|
||||||
|
if paRefCount == 0 {
|
||||||
|
if err := portaudio.Initialize(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
devices, err := portaudio.Devices()
|
||||||
|
if err == nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "[Audio] Linux/PortAudio initialized globally. Devices found: %d\n", len(devices))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paRefCount++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func terminatePortAudio() {
|
||||||
|
paMu.Lock()
|
||||||
|
defer paMu.Unlock()
|
||||||
|
|
||||||
|
paRefCount--
|
||||||
|
if paRefCount == 0 {
|
||||||
|
fmt.Fprintf(os.Stderr, "[Audio] Linux/PortAudio terminating globally...\n")
|
||||||
|
portaudio.Terminate()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"math"
|
"math"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CalculateRMSLevel calculates the RMS level of PCM samples and returns 0-100
|
// CalculateRMSLevel calculates the RMS level of PCM samples and returns 0-100 (Logarithmic/dB)
|
||||||
func CalculateRMSLevel(samples []int16) int {
|
func CalculateRMSLevel(samples []int16) int {
|
||||||
if len(samples) == 0 {
|
if len(samples) == 0 {
|
||||||
return 0
|
return 0
|
||||||
@@ -16,15 +16,33 @@ func CalculateRMSLevel(samples []int16) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rms := math.Sqrt(sum / float64(len(samples)))
|
rms := math.Sqrt(sum / float64(len(samples)))
|
||||||
// Normalize to 0-100 (max int16 is 32767)
|
|
||||||
level := int(rms / 32767.0 * 100.0)
|
// Normalize to 0.0 - 1.0
|
||||||
|
val := rms / 32768.0
|
||||||
|
if val < 0.000001 { // Avoid log(0)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to dB
|
||||||
|
db := 20 * math.Log10(val)
|
||||||
|
|
||||||
|
// Map -50dB (silence floor) to 0dB (max) to 0-100
|
||||||
|
const minDB = -50.0
|
||||||
|
|
||||||
|
if db < minDB {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scale
|
||||||
|
level := int((db - minDB) * (100.0 / (0 - minDB)))
|
||||||
|
|
||||||
if level > 100 {
|
if level > 100 {
|
||||||
level = 100
|
level = 100
|
||||||
}
|
}
|
||||||
return level
|
return level
|
||||||
}
|
}
|
||||||
|
|
||||||
// CalculatePeakLevel returns the peak level of PCM samples as 0-100
|
// CalculatePeakLevel returns the peak level of PCM samples as 0-100 (Logarithmic/dB)
|
||||||
func CalculatePeakLevel(samples []int16) int {
|
func CalculatePeakLevel(samples []int16) int {
|
||||||
if len(samples) == 0 {
|
if len(samples) == 0 {
|
||||||
return 0
|
return 0
|
||||||
@@ -40,7 +58,26 @@ func CalculatePeakLevel(samples []int16) int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return int(float64(peak) / 32767.0 * 100.0)
|
// Normalize
|
||||||
|
val := float64(peak) / 32768.0
|
||||||
|
if val < 0.000001 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
db := 20 * math.Log10(val)
|
||||||
|
const minDB = -50.0
|
||||||
|
|
||||||
|
if db < minDB {
|
||||||
|
// Linear falloff for very low signals to avoid clutter
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
level := int((db - minDB) * (100.0 / (0 - minDB)))
|
||||||
|
if level > 100 {
|
||||||
|
level = 100
|
||||||
|
}
|
||||||
|
|
||||||
|
return level
|
||||||
}
|
}
|
||||||
|
|
||||||
// LevelToBar converts a 0-100 level to a visual bar string
|
// LevelToBar converts a 0-100 level to a visual bar string
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
package audio
|
package audio
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
@@ -27,24 +30,19 @@ type Player struct {
|
|||||||
// map[SenderID] -> AudioQueue
|
// map[SenderID] -> AudioQueue
|
||||||
userBuffers map[uint16][]int16
|
userBuffers map[uint16][]int16
|
||||||
|
|
||||||
|
// User EQs (DSP Filters)
|
||||||
|
userEQs map[uint16]*EQChain
|
||||||
|
|
||||||
// User settings
|
// User settings
|
||||||
userSettings map[uint16]*UserSettings
|
userSettings map[uint16]*UserSettings
|
||||||
bufferMu sync.Mutex
|
bufferMu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserSettings struct {
|
|
||||||
Volume float32 // 0.0 - 1.0 (or higher for boost)
|
|
||||||
Muted bool
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
frameSamples = 960 // 20ms at 48kHz
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewPlayer creates a new WASAPI audio player
|
// NewPlayer creates a new WASAPI audio player
|
||||||
func NewPlayer() (*Player, error) {
|
func NewPlayer() (*Player, error) {
|
||||||
// Initialize COM
|
// Initialize COM
|
||||||
ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED)
|
ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED)
|
||||||
|
log.Printf("[Audio] Windows/WASAPI initializing...")
|
||||||
|
|
||||||
var deviceEnumerator *wca.IMMDeviceEnumerator
|
var deviceEnumerator *wca.IMMDeviceEnumerator
|
||||||
if err := wca.CoCreateInstance(
|
if err := wca.CoCreateInstance(
|
||||||
@@ -71,11 +69,11 @@ func NewPlayer() (*Player, error) {
|
|||||||
|
|
||||||
waveFormat := &wca.WAVEFORMATEX{
|
waveFormat := &wca.WAVEFORMATEX{
|
||||||
WFormatTag: wca.WAVE_FORMAT_PCM,
|
WFormatTag: wca.WAVE_FORMAT_PCM,
|
||||||
NChannels: 1,
|
NChannels: 2, // STEREO
|
||||||
NSamplesPerSec: 48000,
|
NSamplesPerSec: 48000,
|
||||||
WBitsPerSample: 16,
|
WBitsPerSample: 16,
|
||||||
NBlockAlign: 2,
|
NBlockAlign: 4, // 16bit * 2 channels / 8 = 4 bytes
|
||||||
NAvgBytesPerSec: 96000,
|
NAvgBytesPerSec: 192000, // 48000 * 4
|
||||||
CbSize: 0,
|
CbSize: 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,6 +111,7 @@ func NewPlayer() (*Player, error) {
|
|||||||
muted: false,
|
muted: false,
|
||||||
stopChan: make(chan struct{}),
|
stopChan: make(chan struct{}),
|
||||||
userBuffers: make(map[uint16][]int16),
|
userBuffers: make(map[uint16][]int16),
|
||||||
|
userEQs: make(map[uint16]*EQChain),
|
||||||
userSettings: make(map[uint16]*UserSettings),
|
userSettings: make(map[uint16]*UserSettings),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -168,22 +167,112 @@ func (p *Player) PlayPCM(senderID uint16, samples []int16) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// PHASE 1: Read Configuration (Safe Copy)
|
||||||
|
// ---------------------------------------------------------
|
||||||
p.bufferMu.Lock()
|
p.bufferMu.Lock()
|
||||||
defer p.bufferMu.Unlock()
|
|
||||||
|
|
||||||
// Check per-user mute
|
// Check per-user mute
|
||||||
if settings, ok := p.userSettings[senderID]; ok && settings.Muted {
|
settings, hasSettings := p.userSettings[senderID]
|
||||||
|
if hasSettings && settings.Muted {
|
||||||
|
p.bufferMu.Unlock()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append to user's specific buffer
|
// Get EQ Instance (Create if needed)
|
||||||
// This ensures sequential playback for the same user
|
if _, ok := p.userEQs[senderID]; !ok {
|
||||||
p.userBuffers[senderID] = append(p.userBuffers[senderID], samples...)
|
p.userEQs[senderID] = NewEQChain(48000)
|
||||||
|
}
|
||||||
|
userEQ := p.userEQs[senderID]
|
||||||
|
|
||||||
// Limit buffer size per user to avoid memory leaks if stalled
|
// Check/Copy Gains
|
||||||
if len(p.userBuffers[senderID]) > 48000*2 { // 2 seconds max
|
var gains []float64
|
||||||
|
hasActiveEQ := false
|
||||||
|
if hasSettings && len(settings.Gains) == 5 {
|
||||||
|
// Copy gains to avoid race if UI changes them while we process
|
||||||
|
gains = make([]float64, 5)
|
||||||
|
copy(gains, settings.Gains)
|
||||||
|
|
||||||
|
for _, g := range gains {
|
||||||
|
if g != 0 {
|
||||||
|
hasActiveEQ = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
p.bufferMu.Unlock()
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// END PHASE 1 (Lock Released)
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// PHASE 2: Heavy Processing (Concurrent)
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
|
||||||
|
// Normalize to Stereo (Interleaved)
|
||||||
|
// If input is Mono (960 samples), expand to Stereo (1920 samples)
|
||||||
|
// If input is already Stereo, using it as is.
|
||||||
|
var stereoSamples []int16
|
||||||
|
|
||||||
|
if len(samples) < 1500 { // Heuristic for Mono (960)
|
||||||
|
stereoSamples = make([]int16, len(samples)*2)
|
||||||
|
for i, s := range samples {
|
||||||
|
stereoSamples[i*2] = s
|
||||||
|
stereoSamples[i*2+1] = s
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Already stereo (assumed)
|
||||||
|
stereoSamples = make([]int16, len(samples))
|
||||||
|
copy(stereoSamples, samples)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply EQ Filters if needed
|
||||||
|
if hasActiveEQ {
|
||||||
|
// Update gains on the private EQ instance (Thread-safe per user)
|
||||||
|
for i, g := range gains {
|
||||||
|
userEQ.SetGain(i, g)
|
||||||
|
}
|
||||||
|
// Process Stereo
|
||||||
|
stereoSamples = userEQ.Process(stereoSamples)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate EQ bands for visualization
|
||||||
|
// Downmix to Mono for FFT visualization to save CPU and complexity
|
||||||
|
vizSamples := make([]int16, len(stereoSamples)/2)
|
||||||
|
for i := 0; i < len(vizSamples); i++ {
|
||||||
|
// Average L+R
|
||||||
|
val := (int32(stereoSamples[i*2]) + int32(stereoSamples[i*2+1])) / 2
|
||||||
|
vizSamples[i] = int16(val)
|
||||||
|
}
|
||||||
|
bands := CalculateEQBands(vizSamples, 48000)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// PHASE 3: Write Output (Lock Acquired)
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
// Re-check existence (could have disconnected?)
|
||||||
|
// Update user settings with new bands
|
||||||
|
if _, ok := p.userSettings[senderID]; !ok {
|
||||||
|
p.userSettings[senderID] = &UserSettings{Volume: 1.0, Muted: false}
|
||||||
|
}
|
||||||
|
p.userSettings[senderID].EQBands = bands
|
||||||
|
|
||||||
|
// Append to user's specific buffer
|
||||||
|
p.userBuffers[senderID] = append(p.userBuffers[senderID], stereoSamples...)
|
||||||
|
|
||||||
|
// Limit buffer size per user (Stereo 2sec = 48000*2*2 = 192000 items)
|
||||||
|
// frameSamples is 960 (20ms). 2sec = 100 frames * 960 * 2 = 192000
|
||||||
|
const maxBufferSize = 48000 * 2 * 2 // 2 seconds stereo
|
||||||
|
if len(p.userBuffers[senderID]) > maxBufferSize {
|
||||||
// Drop oldest
|
// Drop oldest
|
||||||
drop := len(p.userBuffers[senderID]) - 48000
|
drop := len(p.userBuffers[senderID]) - maxBufferSize
|
||||||
|
// Ensure we drop aligned to stereo frame (even number)
|
||||||
|
if drop%2 != 0 {
|
||||||
|
drop++
|
||||||
|
}
|
||||||
p.userBuffers[senderID] = p.userBuffers[senderID][drop:]
|
p.userBuffers[senderID] = p.userBuffers[senderID][drop:]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -254,8 +343,68 @@ func (p *Player) GetUserSettings(clientID uint16) (float32, bool) {
|
|||||||
return 1.0, false
|
return 1.0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetEQBands returns the current 5-band EQ values for a user (0.0-1.0)
|
||||||
|
func (p *Player) GetEQBands(clientID uint16) []float64 {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
if settings, ok := p.userSettings[clientID]; ok {
|
||||||
|
return settings.EQBands
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUserGain sets the EQ gain for a specific band (0-4) and user.
|
||||||
|
// Gain is in dB (e.g. -12.0 to +12.0)
|
||||||
|
func (p *Player) SetUserGain(clientID uint16, bandIdx int, gainDb float64) {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
p.ensureUserSettings(clientID)
|
||||||
|
|
||||||
|
// Ensure Gains slice exists
|
||||||
|
if len(p.userSettings[clientID].Gains) != 5 {
|
||||||
|
p.userSettings[clientID].Gains = make([]float64, 5)
|
||||||
|
}
|
||||||
|
|
||||||
|
if bandIdx >= 0 && bandIdx < 5 {
|
||||||
|
p.userSettings[clientID].Gains[bandIdx] = gainDb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserGain returns the gain for a band
|
||||||
|
func (p *Player) GetUserGain(clientID uint16, bandIdx int) float64 {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
if settings, ok := p.userSettings[clientID]; ok {
|
||||||
|
if len(settings.Gains) > bandIdx {
|
||||||
|
return settings.Gains[bandIdx]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0.0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) ensureUserSettings(clientID uint16) {
|
||||||
|
if _, ok := p.userSettings[clientID]; !ok {
|
||||||
|
p.userSettings[clientID] = &UserSettings{
|
||||||
|
Volume: 1.0,
|
||||||
|
Muted: false,
|
||||||
|
Gains: make([]float64, 5),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) ensureEQ(clientID uint16) {
|
||||||
|
if _, ok := p.userEQs[clientID]; !ok {
|
||||||
|
// New EQ chain
|
||||||
|
// Assume 48000 Hz, would be better to pass actual stream rate
|
||||||
|
p.userEQs[clientID] = NewEQChain(48000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (p *Player) playbackLoop() {
|
func (p *Player) playbackLoop() {
|
||||||
ticker := time.NewTicker(20 * time.Millisecond)
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -269,79 +418,107 @@ func (p *Player) playbackLoop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *Player) writeFrame() {
|
func (p *Player) writeFrame() {
|
||||||
var padding uint32
|
for {
|
||||||
if err := p.client.GetCurrentPadding(&padding); err != nil {
|
var padding uint32
|
||||||
return
|
if err := p.client.GetCurrentPadding(&padding); err != nil {
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
available := p.bufferSize - padding
|
available := p.bufferSize - padding
|
||||||
if available < frameSamples {
|
if available < frameSamples {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
p.bufferMu.Lock()
|
p.bufferMu.Lock()
|
||||||
|
|
||||||
// Mix audio from all active user buffers
|
// Mix audio from all active user buffers
|
||||||
mixed := make([]int32, frameSamples)
|
// Stereo mixing: buffer size is frameSamples * 2
|
||||||
activeUsers := 0
|
mixed := make([]int32, frameSamples*2)
|
||||||
|
activeUsers := 0
|
||||||
|
hasAnyAudio := false
|
||||||
|
|
||||||
for id, buf := range p.userBuffers {
|
for id, buf := range p.userBuffers {
|
||||||
if len(buf) > 0 {
|
if len(buf) > 0 {
|
||||||
activeUsers++
|
hasAnyAudio = true
|
||||||
// Take up to frameSamples from this user
|
activeUsers++
|
||||||
toTake := frameSamples
|
// Take up to frameSamples*2 (Stereo) from this user
|
||||||
if len(buf) < frameSamples {
|
toTake := frameSamples * 2
|
||||||
toTake = len(buf)
|
if len(buf) < int(frameSamples)*2 {
|
||||||
}
|
toTake = len(buf)
|
||||||
|
|
||||||
for i := 0; i < toTake; i++ {
|
|
||||||
sample := int32(buf[i])
|
|
||||||
|
|
||||||
// Apply user volume if set
|
|
||||||
if settings, ok := p.userSettings[id]; ok {
|
|
||||||
sample = int32(float32(sample) * settings.Volume)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mixed[i] += sample
|
// Ensure we take pairs (alignment)
|
||||||
}
|
toTake = toTake &^ 1 // clear lowest bit
|
||||||
|
|
||||||
// Advance buffer
|
for i := 0; i < toTake; i++ {
|
||||||
if len(buf) <= frameSamples {
|
sample := int32(buf[i])
|
||||||
delete(p.userBuffers, id)
|
|
||||||
} else {
|
// Apply user volume if set
|
||||||
p.userBuffers[id] = buf[frameSamples:]
|
if settings, ok := p.userSettings[id]; ok {
|
||||||
|
sample = int32(float32(sample) * settings.Volume)
|
||||||
|
}
|
||||||
|
|
||||||
|
mixed[i] += sample
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advance buffer
|
||||||
|
if len(buf) <= toTake {
|
||||||
|
delete(p.userBuffers, id) // Finished this buffer
|
||||||
|
} else {
|
||||||
|
p.userBuffers[id] = buf[toTake:]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
p.bufferMu.Unlock()
|
p.bufferMu.Unlock()
|
||||||
|
|
||||||
// Get WASAPI buffer
|
// If no audio is playing, don't write anything (keep buffer empty for lower latency when audio starts)
|
||||||
var buffer *byte
|
if !hasAnyAudio {
|
||||||
if err := p.renderClient.GetBuffer(uint32(frameSamples), &buffer); err != nil {
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
p.mu.Lock()
|
|
||||||
vol := p.volume
|
|
||||||
p.mu.Unlock()
|
|
||||||
|
|
||||||
// Write mixed samples with clipping protection and volume application
|
|
||||||
bufSlice := unsafe.Slice(buffer, int(frameSamples)*2)
|
|
||||||
for i := 0; i < int(frameSamples); i++ {
|
|
||||||
val := mixed[i]
|
|
||||||
|
|
||||||
// Apply volume
|
|
||||||
val = int32(float32(val) * vol)
|
|
||||||
|
|
||||||
// Hard clipping
|
|
||||||
if val > 32767 {
|
|
||||||
val = 32767
|
|
||||||
} else if val < -32768 {
|
|
||||||
val = -32768
|
|
||||||
}
|
}
|
||||||
binary.LittleEndian.PutUint16(bufSlice[i*2:], uint16(val))
|
|
||||||
}
|
|
||||||
|
|
||||||
p.renderClient.ReleaseBuffer(uint32(frameSamples), 0)
|
// Get WASAPI buffer
|
||||||
|
var buffer *byte
|
||||||
|
if err := p.renderClient.GetBuffer(uint32(frameSamples), &buffer); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
vol := p.volume
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
// Write mixed samples with clipping protection and volume application
|
||||||
|
// Output buffer is for Stereo (frameSamples * 2 channels)
|
||||||
|
bufSlice := unsafe.Slice(buffer, int(frameSamples)*2*2) // *2 channels *2 bytes? No, unsafe.Slice takes count of Type.
|
||||||
|
// If buffer is *byte, we need bytes. frameSamples * 2 channels * 2 bytes/sample.
|
||||||
|
// Wait, GetBuffer returns BYTE pointer.
|
||||||
|
// Let's use uint16 slice.
|
||||||
|
|
||||||
|
// The logic below was: binary.LittleEndian.PutUint16(bufSlice[i*2:], ...)
|
||||||
|
// frameSamples was 960. loop 0..960.
|
||||||
|
// Now we have Stereo mixed buffer. Length = frameSamples * 2.
|
||||||
|
// We need to write frameSamples * 2 samples.
|
||||||
|
|
||||||
|
// Correct loop for Stereo:
|
||||||
|
for i := 0; i < int(frameSamples)*2; i++ { // Iterate over all samples (L, R, L, R...)
|
||||||
|
val := mixed[i]
|
||||||
|
|
||||||
|
// Apply master volume
|
||||||
|
val = int32(float32(val) * vol)
|
||||||
|
|
||||||
|
// Hard clipping
|
||||||
|
if val > 32767 {
|
||||||
|
val = 32767
|
||||||
|
} else if val < -32768 {
|
||||||
|
val = -32768
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map to output byte buffer
|
||||||
|
// i is sample index. Each sample is 2 bytes.
|
||||||
|
// Offset = i * 2.
|
||||||
|
binary.LittleEndian.PutUint16(bufSlice[i*2:], uint16(val))
|
||||||
|
}
|
||||||
|
|
||||||
|
p.renderClient.ReleaseBuffer(uint32(frameSamples), 0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
331
pkg/audio/playback_linux.go
Normal file
331
pkg/audio/playback_linux.go
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package audio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gordonklaus/portaudio"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Player handles audio playback using PortAudio
|
||||||
|
type Player struct {
|
||||||
|
stream *portaudio.Stream
|
||||||
|
volume float32
|
||||||
|
muted bool
|
||||||
|
mu sync.Mutex
|
||||||
|
running bool
|
||||||
|
stopChan chan struct{}
|
||||||
|
|
||||||
|
// User buffers for mixing (Stereo Interleaved)
|
||||||
|
userBuffers map[uint16][]int16
|
||||||
|
|
||||||
|
// User EQs (DSP Filters)
|
||||||
|
userEQs map[uint16]*EQChain
|
||||||
|
|
||||||
|
// User settings
|
||||||
|
userSettings map[uint16]*UserSettings
|
||||||
|
bufferMu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPlayer() (*Player, error) {
|
||||||
|
if err := initPortAudio(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
p := &Player{
|
||||||
|
volume: 1.0,
|
||||||
|
muted: false,
|
||||||
|
stopChan: make(chan struct{}),
|
||||||
|
userBuffers: make(map[uint16][]int16),
|
||||||
|
userEQs: make(map[uint16]*EQChain),
|
||||||
|
userSettings: make(map[uint16]*UserSettings),
|
||||||
|
}
|
||||||
|
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) Start() error {
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.running {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create stream (Stereo, 48kHz, 16-bit)
|
||||||
|
// We'll use a callback-based stream for lower latency
|
||||||
|
var err error
|
||||||
|
p.stream, err = portaudio.OpenDefaultStream(0, 2, 48000, frameSamples, p.processAudio)
|
||||||
|
if err != nil {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return fmt.Errorf("failed to open portaudio stream: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := p.stream.Start(); err != nil {
|
||||||
|
p.stream.Close()
|
||||||
|
p.mu.Unlock()
|
||||||
|
return fmt.Errorf("failed to start portaudio stream: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
p.running = true
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) Stop() {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if !p.running {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.running = false
|
||||||
|
if p.stream != nil {
|
||||||
|
p.stream.Abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) Close() {
|
||||||
|
p.Stop()
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.stream != nil {
|
||||||
|
p.stream.Close()
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
terminatePortAudio()
|
||||||
|
}
|
||||||
|
|
||||||
|
// processAudio is the PortAudio callback
|
||||||
|
func (p *Player) processAudio(out []int16) {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
// Initial silence
|
||||||
|
for i := range out {
|
||||||
|
out[i] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.muted {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
vol := p.volume
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
// Output `out` is Stereo Interleaved (L, R, L, R...)
|
||||||
|
// Its length is frameSamples * 2.
|
||||||
|
mixed := make([]int32, len(out))
|
||||||
|
|
||||||
|
for id, buf := range p.userBuffers {
|
||||||
|
if len(buf) > 0 {
|
||||||
|
toTake := len(out)
|
||||||
|
if len(buf) < toTake {
|
||||||
|
toTake = len(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure pair alignment
|
||||||
|
toTake = toTake &^ 1
|
||||||
|
|
||||||
|
for i := 0; i < toTake; i++ {
|
||||||
|
sample := int32(buf[i])
|
||||||
|
if settings, ok := p.userSettings[id]; ok {
|
||||||
|
sample = int32(float32(sample) * settings.Volume)
|
||||||
|
}
|
||||||
|
mixed[i] += sample
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advance buffer
|
||||||
|
if len(buf) <= toTake {
|
||||||
|
delete(p.userBuffers, id)
|
||||||
|
} else {
|
||||||
|
p.userBuffers[id] = buf[toTake:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply master volume and clip
|
||||||
|
for i := 0; i < len(out); i++ {
|
||||||
|
val := int32(float32(mixed[i]) * vol)
|
||||||
|
if val > 32767 {
|
||||||
|
val = 32767
|
||||||
|
} else if val < -32768 {
|
||||||
|
val = -32768
|
||||||
|
}
|
||||||
|
out[i] = int16(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) PlayPCM(senderID uint16, samples []int16) {
|
||||||
|
if p.muted {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// PHASE 1: Read Configuration (Safe Copy)
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
|
||||||
|
// Check per-user mute
|
||||||
|
settings, hasSettings := p.userSettings[senderID]
|
||||||
|
if hasSettings && settings.Muted {
|
||||||
|
p.bufferMu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get EQ Instance (Create if needed)
|
||||||
|
if _, ok := p.userEQs[senderID]; !ok {
|
||||||
|
p.userEQs[senderID] = NewEQChain(48000)
|
||||||
|
}
|
||||||
|
userEQ := p.userEQs[senderID]
|
||||||
|
|
||||||
|
// Check/Copy Gains
|
||||||
|
var gains []float64
|
||||||
|
hasActiveEQ := false
|
||||||
|
if hasSettings && len(settings.Gains) == 5 {
|
||||||
|
gains = make([]float64, 5)
|
||||||
|
copy(gains, settings.Gains)
|
||||||
|
for _, g := range gains {
|
||||||
|
if g != 0 {
|
||||||
|
hasActiveEQ = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// PHASE 2: Heavy Processing (Concurrent)
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
|
||||||
|
// Normalize to Stereo
|
||||||
|
var stereoSamples []int16
|
||||||
|
if len(samples) < 1500 { // Mono
|
||||||
|
stereoSamples = make([]int16, len(samples)*2)
|
||||||
|
for i, s := range samples {
|
||||||
|
stereoSamples[i*2] = s
|
||||||
|
stereoSamples[i*2+1] = s
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Already stereo
|
||||||
|
stereoSamples = make([]int16, len(samples))
|
||||||
|
copy(stereoSamples, samples)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasActiveEQ {
|
||||||
|
for i, g := range gains {
|
||||||
|
userEQ.SetGain(i, g)
|
||||||
|
}
|
||||||
|
stereoSamples = userEQ.Process(stereoSamples)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate EQ bands (Downmix for visualization)
|
||||||
|
vizSamples := make([]int16, len(stereoSamples)/2)
|
||||||
|
for i := 0; i < len(vizSamples); i++ {
|
||||||
|
val := (int32(stereoSamples[i*2]) + int32(stereoSamples[i*2+1])) / 2
|
||||||
|
vizSamples[i] = int16(val)
|
||||||
|
}
|
||||||
|
bands := CalculateEQBands(vizSamples, 48000)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
// PHASE 3: Write Output (Lock Acquired)
|
||||||
|
// ---------------------------------------------------------
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := p.userSettings[senderID]; !ok {
|
||||||
|
p.userSettings[senderID] = &UserSettings{Volume: 1.0, Muted: false}
|
||||||
|
}
|
||||||
|
p.userSettings[senderID].EQBands = bands
|
||||||
|
|
||||||
|
p.userBuffers[senderID] = append(p.userBuffers[senderID], stereoSamples...)
|
||||||
|
const maxBufferSize = 48000 * 2 * 2 // 2 seconds stereo
|
||||||
|
if len(p.userBuffers[senderID]) > maxBufferSize {
|
||||||
|
drop := len(p.userBuffers[senderID]) - maxBufferSize
|
||||||
|
if drop%2 != 0 {
|
||||||
|
drop++
|
||||||
|
}
|
||||||
|
p.userBuffers[senderID] = p.userBuffers[senderID][drop:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEQBands returns the current 5-band EQ values for a user (0.0-1.0)
|
||||||
|
func (p *Player) GetEQBands(clientID uint16) []float64 {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
if settings, ok := p.userSettings[clientID]; ok {
|
||||||
|
return settings.EQBands
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUserGain sets the EQ gain for a specific band (0-4) and user.
|
||||||
|
func (p *Player) SetUserGain(clientID uint16, bandIdx int, gainDb float64) {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
p.ensureUserSettings(clientID)
|
||||||
|
if len(p.userSettings[clientID].Gains) != 5 {
|
||||||
|
p.userSettings[clientID].Gains = make([]float64, 5)
|
||||||
|
}
|
||||||
|
if bandIdx >= 0 && bandIdx < 5 {
|
||||||
|
p.userSettings[clientID].Gains[bandIdx] = gainDb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserGain returns the gain for a band
|
||||||
|
func (p *Player) GetUserGain(clientID uint16, bandIdx int) float64 {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
if settings, ok := p.userSettings[clientID]; ok {
|
||||||
|
if len(settings.Gains) > bandIdx {
|
||||||
|
return settings.Gains[bandIdx]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0.0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) ensureUserSettings(clientID uint16) {
|
||||||
|
if _, ok := p.userSettings[clientID]; !ok {
|
||||||
|
p.userSettings[clientID] = &UserSettings{
|
||||||
|
Volume: 1.0,
|
||||||
|
Muted: false,
|
||||||
|
Gains: make([]float64, 5),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) SetVolume(vol float32) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
p.volume = vol
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) SetMuted(muted bool) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
p.muted = muted
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) SetUserVolume(clientID uint16, vol float32) {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
p.ensureUserSettings(clientID)
|
||||||
|
p.userSettings[clientID].Volume = vol
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) SetUserMuted(clientID uint16, muted bool) {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
p.ensureUserSettings(clientID)
|
||||||
|
p.userSettings[clientID].Muted = muted
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Player) GetUserSettings(clientID uint16) (float32, bool) {
|
||||||
|
p.bufferMu.Lock()
|
||||||
|
defer p.bufferMu.Unlock()
|
||||||
|
if settings, ok := p.userSettings[clientID]; ok {
|
||||||
|
return settings.Volume, settings.Muted
|
||||||
|
}
|
||||||
|
return 1.0, false
|
||||||
|
}
|
||||||
@@ -124,6 +124,10 @@ func (c *Client) emit(event EventType, data any) {
|
|||||||
if fn, ok := h.(func(*TalkingStatusEvent)); ok {
|
if fn, ok := h.(func(*TalkingStatusEvent)); ok {
|
||||||
fn(data.(*TalkingStatusEvent))
|
fn(data.(*TalkingStatusEvent))
|
||||||
}
|
}
|
||||||
|
case EventPoke:
|
||||||
|
if fn, ok := h.(func(*PokeEvent)); ok {
|
||||||
|
fn(data.(*PokeEvent))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -405,6 +409,13 @@ func (c *Client) handleInternalEvent(eventType string, data map[string]any) {
|
|||||||
Channels: getInt(data, "channels"),
|
Channels: getInt(data, "channels"),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
case "client_poke":
|
||||||
|
c.emit(EventPoke, &PokeEvent{
|
||||||
|
SenderID: getUint16(data, "senderID"),
|
||||||
|
SenderName: getString(data, "senderName"),
|
||||||
|
Message: getString(data, "message"),
|
||||||
|
})
|
||||||
|
|
||||||
case "error":
|
case "error":
|
||||||
c.emit(EventError, &ErrorEvent{
|
c.emit(EventError, &ErrorEvent{
|
||||||
ID: getString(data, "id"),
|
ID: getString(data, "id"),
|
||||||
|
|||||||
@@ -235,6 +235,19 @@ func (c *Client) KickFromServer(clientID uint16, reason string) error {
|
|||||||
return c.internal.SendCommand(cmd)
|
return c.internal.SendCommand(cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Poke sends a poke message to a specific client
|
||||||
|
func (c *Client) Poke(clientID uint16, message string) error {
|
||||||
|
if c.internal == nil {
|
||||||
|
return fmt.Errorf("not connected")
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := protocol.NewCommand("clientpoke")
|
||||||
|
cmd.AddParam("clid", fmt.Sprintf("%d", clientID))
|
||||||
|
cmd.AddParam("msg", message)
|
||||||
|
|
||||||
|
return c.internal.SendCommand(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
// Info Methods
|
// Info Methods
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|||||||
@@ -25,8 +25,18 @@ const (
|
|||||||
|
|
||||||
// Error events
|
// Error events
|
||||||
EventError EventType = "error"
|
EventError EventType = "error"
|
||||||
|
|
||||||
|
// Poke events
|
||||||
|
EventPoke EventType = "poke"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// PokeEvent is emitted when a poke message is received
|
||||||
|
type PokeEvent struct {
|
||||||
|
SenderID uint16
|
||||||
|
SenderName string
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
// ConnectedEvent is emitted when the client successfully connects
|
// ConnectedEvent is emitted when the client successfully connects
|
||||||
type ConnectedEvent struct {
|
type ConnectedEvent struct {
|
||||||
ClientID uint16
|
ClientID uint16
|
||||||
|
|||||||
122
readme.md
Normal file
122
readme.md
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
# TeamSpeak TUI Client
|
||||||
|
|
||||||
|
A modern, fast, and lightweight TeamSpeak 3 client built in Go with a beautiful Terminal User Interface (TUI).
|
||||||
|
|
||||||
|
## 🚀 Features
|
||||||
|
- **Low Latency Audio**: Optimized for both Windows (WASAPI) and Linux (PortAudio).
|
||||||
|
- **Responsive UI**: Built with Bubble Tea for a smooth terminal experience.
|
||||||
|
- **Cross-Platform**: Full support for Windows and Linux (including WSL2).
|
||||||
|
- **Audio Controls**: Per-user volume and mute indicators.
|
||||||
|
|
||||||
|
## 🛠️ Linux Dependencies
|
||||||
|
|
||||||
|
To build the project on Linux (including Ubuntu/WSL2), you need to install the following system libraries:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y \
|
||||||
|
libportaudio2 \
|
||||||
|
portaudio19-dev \
|
||||||
|
libopus-dev \
|
||||||
|
libpulse-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔊 WSL2 Audio Setup
|
||||||
|
|
||||||
|
WSL2 does not have direct access to your Windows audio hardware. To enable audio, we recommend using a PulseAudio network bridge:
|
||||||
|
|
||||||
|
1. **Install PulseAudio on Windows** (e.g., via [portable binaries](https://www.freedesktop.org/wiki/Software/PulseAudio/Ports/Windows/)).
|
||||||
|
2. **Enable TCP**: Edit `default.pa` in PulseAudio and add:
|
||||||
|
`load-module module-native-protocol-tcp auth-anonymous=1 listen=0.0.0.0`
|
||||||
|
3. **Environment Variable**: Set the `PULSE_SERVER` in your WSL2 shell:
|
||||||
|
```bash
|
||||||
|
export PULSE_SERVER=tcp:$(grep nameserver /etc/resolv.conf | awk '{print $2}'):4713
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🏗️ Building
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# General build
|
||||||
|
go build -o ts-tui ./cmd/tui
|
||||||
|
|
||||||
|
# Run with debug logging (highly recommended for audio setup)
|
||||||
|
go run ./cmd/tui --server your-ip:9987 --debug
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⌨️ Common Keys
|
||||||
|
- `q`: Quit cleanly.
|
||||||
|
- `Arrows / hjkl`: Navigate channels and users.
|
||||||
|
- `Enter`: Join channel.
|
||||||
|
- `1`: Poke user (in User View).
|
||||||
|
- `m`: Mute/Unmute audio.
|
||||||
|
## 💻 Development with VS Code
|
||||||
|
|
||||||
|
This project uses Go **build tags** to support multiple platforms from the same codebase. This can sometimes cause "redeclared" errors or "undefined" symbols in VS Code if not configured correctly.
|
||||||
|
|
||||||
|
### Recommended Setup
|
||||||
|
|
||||||
|
1. **Windows + MSYS2**: If you are developing on Windows and have Opus/PortAudio installed via MSYS2, your `.vscode/settings.json` should include the paths to your MinGW64 environment:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"go.toolsEnvVars": {
|
||||||
|
"CGO_ENABLED": "1",
|
||||||
|
"PATH": "C:\\msys64\\mingw64\\bin;${env:PATH}",
|
||||||
|
"PKG_CONFIG_PATH": "C:\\msys64\\mingw64\\lib\\pkgconfig"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
2. **Build Tags**: Do **not** force both tags simultaneously (e.g., `-tags=linux,windows`) as this will cause "redeclared" errors for types defined in both systems (like `Player` or `Capturer`).
|
||||||
|
3. **Switching OS Analysis**: If you are on Windows but want to check for errors in the Linux files, update your settings to:
|
||||||
|
```json
|
||||||
|
"go.toolsEnvVars": { "GOOS": "linux" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pro Tip: VS Code Remote - WSL
|
||||||
|
For the best experience when working on Linux features from Windows, use the **WSL extension**. Open VS Code inside your WSL environment (`code .` from the WSL terminal). This allows `gopls` to run directly in Linux, where all system headers and libraries are natively available.
|
||||||
|
|
||||||
|
## 🤖 Gitea Actions (CI/CD)
|
||||||
|
|
||||||
|
El archivo `.gitea/workflows/build.yml` automatiza la compilación y la creación de Releases.
|
||||||
|
|
||||||
|
1. **Builds automáticas**: Cada `push` a `master` genera artefactos descargables.
|
||||||
|
2. **Releases automáticas**: Al subir un tag (`git tag v*`), se crea una Release con:
|
||||||
|
- `ts3-tui-windows-x86_64.zip` (Portable: exe + dlls).
|
||||||
|
- `ts3-tui-linux-x86_64` (Para PC/WSL2).
|
||||||
|
- `ts3-tui-linux-aarch64` (Para ARM/Raspberry Pi).
|
||||||
|
|
||||||
|
### Cómo usar tu propio Windows como Runner
|
||||||
|
|
||||||
|
Si tu Gitea no tiene runners públicos, puedes convertir tu propia máquina Windows en uno:
|
||||||
|
|
||||||
|
1. **Descarga `act_runner`**: Descarga el binario oficial de [Gitea Actions Runner](https://gitea.com/gitea/act_runner/releases).
|
||||||
|
2. **Registro**:
|
||||||
|
- Ve a tu instancia de Gitea -> Administración del Sitio -> Actions -> Runners.
|
||||||
|
- Copia el **Registration Token**.
|
||||||
|
- Ejecuta: `./act_runner register`
|
||||||
|
- Introduce la URL de tu Gitea y el token.
|
||||||
|
- En **labels**, asegúrate de poner `windows-latest:host`.
|
||||||
|
3. **Ejecución**:
|
||||||
|
- Lanza el runner: `./act_runner daemon`.
|
||||||
|
- Ahora, cualquier push lanzará la build en tu PC de forma automática.
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> El workflow usa **MSYS2** automáticamente para instalar `opus` y `portaudio` en el entorno temporal de la build, así que no necesitas configurar nada extra en el sistema del runner.
|
||||||
|
|
||||||
|
### Cómo añadir un Runner en WSL2 (para x86_64)
|
||||||
|
|
||||||
|
Si tu runner principal es ARM (como una Raspberry Pi) y quieres compilar para tu PC (x86_64), lo mejor es poner un runner dentro de WSL2:
|
||||||
|
|
||||||
|
1. **Entra en WSL2**: Ejecuta `wsl` en tu terminal.
|
||||||
|
2. **Descarga `act_runner`**:
|
||||||
|
```bash
|
||||||
|
curl -L https://gitea.com/gitea/act_runner/releases/download/v0.2.13/act_runner-0.2.13-linux-amd64 -o act_runner
|
||||||
|
chmod +x act_runner
|
||||||
|
```
|
||||||
|
3. **Registro**:
|
||||||
|
- Igual que en Windows, usa `./act_runner register` con el token de tu Gitea.
|
||||||
|
- En **labels**, pon algo como `linux-x86_64:host`.
|
||||||
|
4. **Actualiza el workflow**:
|
||||||
|
- En `.gitea/workflows/build.yml`, cambia `runs-on: ubuntu-latest` por `runs-on: linux-x86_64` en el job `build-linux`.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Al usar el label `:host`, el runner usará las herramientas instaladas en tu Linux de WSL2 sin necesidad de Docker, lo que lo hace mucho más rápido.
|
||||||
@@ -3,4 +3,5 @@ $env:PKG_CONFIG_PATH = "D:\esto_al_path\msys64\mingw64\lib\pkgconfig"
|
|||||||
|
|
||||||
Write-Host "Starting TeamSpeak Client (Windows Native)..." -ForegroundColor Cyan
|
Write-Host "Starting TeamSpeak Client (Windows Native)..." -ForegroundColor Cyan
|
||||||
# go run ./cmd/client/main.go --server localhost:9987
|
# go run ./cmd/client/main.go --server localhost:9987
|
||||||
go run ./cmd/example --server localhost:9987
|
# go run ./cmd/example --server localhost:9987
|
||||||
|
go run ./cmd/tui --server 127.0.0.1:9987 --nickname Adam --debug
|
||||||
11
timestamp.go
11
timestamp.go
@@ -1,11 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
t, _ := time.Parse("2006-01-02 15:04:05", "2023-07-24 10:06:33")
|
|
||||||
fmt.Println(t.Unix())
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user