Files
go-mxl-player/cmd/mxl-player/main.go
T
2026-09-02 01:06:40 +03:00

1124 lines
31 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"mxl-player/internal/imgui"
"mxl-player/internal/playback"
"mxl-player/internal/renderer"
"mxl-player/internal/sdl"
"os"
"runtime"
"time"
"unsafe"
cimgui "github.com/AllenDang/cimgui-go/imgui"
vk "github.com/christerso/vulkan-go/vk"
pflag "github.com/spf13/pflag"
)
const (
APP_NAME = "MXL Player"
APP_VER = "1.0.0"
WIN_WIDTH int32 = 1280
WIN_HEIGHT int32 = 720
)
const (
placeholderWidth uint32 = 1
placeholderHeight uint32 = 1
placeholderStride uint32 = 4
)
const (
initialRetryDelay = 500 * time.Millisecond
maxRetryDelay = 5 * time.Second
)
type appArgs struct {
ShowHelp bool
Domain string
VideoDomain string
AudioDomain string
VideoFlowId string
AudioFlowId string
IsFullscreen bool
PlaybackId uint32
GpuId uint32
IsVerbose bool
ListAudio bool
ListGPU bool
SyncRequested bool
MaxAttempts int
PlaylistPath string
}
func printCliHelp(fs *pflag.FlagSet) {
fmt.Printf("%s %s\n", APP_NAME, APP_VER)
fmt.Println("Usage: mxl-player [-d <domain>] [-v <uuid>] [-a <uuid>] [options]")
fmt.Println(" [-g <gpu-id>] [-p <playback-id>] [--verbose]")
fmt.Println(" or: mxl-player [--playlist <playlist.json]")
fmt.Println(" or: mxl-player [--list-playback] [--list-gpu]")
fmt.Println(" or: mxl-player (and set everything in GUI)")
fmt.Println()
fs.PrintDefaults()
}
func printUsage(w io.Writer) {
fmt.Fprintln(w, "Usage: mxl-player [-d <domain>] [-v <uuid>] [-a <uuid>] [options]")
fmt.Fprintln(w, "Try 'mxl-player -h' for more information.")
}
func checkMXLargs(args appArgs) {
checkDomain := func(label, domain string) {
if domain == "" {
fmt.Fprintf(os.Stderr, "%s domain is required when its UUID is configured\n", label)
printUsage(os.Stderr)
os.Exit(2)
}
info, err := os.Stat(domain)
if err != nil || !info.IsDir() {
fmt.Fprintf(os.Stderr, "Invalid %s MXL domain: %s\n", label, domain)
fmt.Fprintln(os.Stderr, "Domain must be a directory in tmpfs")
printUsage(os.Stderr)
os.Exit(2)
}
}
if args.VideoFlowId != "" {
checkDomain("video", args.VideoDomain)
}
if args.AudioFlowId != "" {
checkDomain("audio", args.AudioDomain)
}
}
func main() {
var args appArgs
flagSet := pflag.NewFlagSet(APP_NAME, pflag.ContinueOnError)
flagSet.SortFlags = false
flagSet.Usage = func() { printUsage(os.Stderr) }
flagSet.BoolVarP(&args.ShowHelp, "help", "h", false, "Show help message and exit")
flagSet.StringVarP(
&args.Domain,
"domain",
"d",
"",
"Default MXL domain for feeds without a specific domain",
)
flagSet.StringVar(&args.VideoDomain, "video-domain", "", "MXL domain for the video feed")
flagSet.StringVar(&args.AudioDomain, "audio-domain", "", "MXL domain for the audio feed")
flagSet.StringVarP(&args.VideoFlowId, "video", "v", "", "Video flow UUID")
flagSet.StringVarP(&args.AudioFlowId, "audio", "a", "", "Audio flow UUID")
flagSet.BoolVarP(
&args.SyncRequested,
"sync", "s",
false,
"Start configured audio and video as a synchronized group",
)
flagSet.IntVar(
&args.MaxAttempts,
"max-attempts",
0,
"Maximum connection attempts per playback lifecycle; 0 retries indefinitely",
)
flagSet.StringVar(
&args.PlaylistPath,
"playlist",
"",
"Load playlist from a JSON file",
)
flagSet.BoolVarP(&args.IsFullscreen, "fullscreen", "f", false, "Run app in fullscreen mode")
flagSet.Uint32VarP(&args.GpuId, "gpu-id", "g", 0, "GPU id [TODO]")
flagSet.Uint32VarP(&args.PlaybackId, "playback-id", "p", 0, "Playback audio device id")
flagSet.BoolVar(&args.IsVerbose, "verbose", false, "Verbose output [TODO]")
flagSet.BoolVar(&args.ListAudio, "list-playback", false, "List audio playback devices and exit")
flagSet.BoolVar(&args.ListGPU, "list-gpu", false, "List GPUs and exit")
if err := flagSet.Parse(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
printUsage(os.Stderr)
os.Exit(2)
}
if args.ShowHelp {
printCliHelp(flagSet)
return
}
if args.MaxAttempts < 0 {
fmt.Fprintln(os.Stderr, "--max-attempts cannot be negative")
printUsage(os.Stderr)
os.Exit(2)
}
retryPolicy := playback.RetryPolicy{
MaxAttempts: args.MaxAttempts,
InitialDelay: initialRetryDelay,
MaxDelay: maxRetryDelay,
}
if err := retryPolicy.Validate(); err != nil {
fmt.Fprintln(os.Stderr, "invalid retry configuration:", err)
os.Exit(2)
}
configuredPlaylist := playback.Playlist{}
hasPlaylist := args.PlaylistPath != ""
if hasPlaylist {
playlist, err := loadPlaylistFile(args.PlaylistPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
configuredPlaylist = playlist
retryPolicy = resolveRetryPolicy(
retryPolicy,
flagSet.Changed("max-attempts"),
configuredPlaylist,
)
}
if args.VideoDomain == "" {
args.VideoDomain = args.Domain
}
if args.AudioDomain == "" {
args.AudioDomain = args.Domain
}
if !args.ListAudio && !args.ListGPU {
checkMXLargs(args)
}
runtime.LockOSThread()
if err := sdl.Load(); err != nil {
panic(err)
}
if !sdl.Init(sdl.InitVideo | sdl.InitAudio) {
log.Fatalf("SDL_Init: %s", sdl.GetError())
return
}
sdlAudioDevice := sdl.AudioDeviceDefaultPlayback
if args.PlaybackId != 0 {
sdlAudioDevice = args.PlaybackId
}
// List audio playback devices and exit
if args.ListAudio {
devs := sdl.GetAudioPlaybackDevices()
fmt.Println("Available playback audio devices")
fmt.Println("id name")
for _, d := range devs {
fmt.Println(d.ID, d.Name)
}
return
}
windowHandler := sdl.CreateWindow(fmt.Sprintf("%s %s", APP_NAME, APP_VER), WIN_WIDTH, WIN_HEIGHT, sdl.WindowVulkan|sdl.WindowResizable)
if windowHandler == 0 {
sdl.Quit()
log.Fatalf("SDL_CreateWindow: %s", sdl.GetError())
return
}
// ImGui init
gui := imgui.New()
defer gui.Destroy()
fontConfig := cimgui.NewFontConfig()
font := gui.IO().Fonts().AddFontFromFileTTFV(
"/home/itten/Downloads/JetBrainsMono/JetBrainsMonoNLNerdFontMono-Regular.ttf",
18,
fontConfig,
nil,
)
fontConfig.Destroy()
if font == nil || font.CData == nil {
log.Fatal("failed to load ImGui font")
}
gui.IO().SetFontDefault(font)
// sdl keys handler
sdl.StartTextInput(windowHandler)
defer sdl.StopTextInput(windowHandler)
// fin on ImGui init
if err := vk.Load(); err != nil {
panic(err)
}
sdlExtensions := sdl.VulkanGetInstanceExtensions()
if len(sdlExtensions) == 0 {
log.Fatal("sdlVulkanGetInstanceExtensions is 0")
return
}
var vkLayers []string
vkExtensions := append(sdlExtensions, vk.ExtDebugUtils)
vkInstance, err := vk.CreateInstance(vk.InstanceConfig{
ApplicationName: APP_NAME,
EngineName: "no engine",
Extensions: vkExtensions,
Layers: vkLayers,
})
if err != nil {
log.Fatalf("%s", err)
panic(err)
}
defer vkInstance.Destroy()
var vkSurface uint64
if !sdl.VulkanCreateSurface(windowHandler, uintptr(vkInstance), 0, &vkSurface) {
log.Fatalf("SDL_Vulkan_CreateSurface: %s", sdl.GetError())
return
}
vkSurf := vk.SurfaceKHR(vkSurface)
defer vkInstance.DestroySurface(vkSurf)
devices, err := vkInstance.EnumeratePhysicalDevices()
if err != nil || len(devices) == 0 {
panic("No Vulkan devices")
}
// List GPU's and exit
if args.ListGPU {
fmt.Println("Available Vulkan physical devices:")
fmt.Println("id name (type)")
for i, pd := range devices {
info := pd.Info()
fmt.Printf("%2d %s (%s)\n", i, info.Name, info.Type)
}
return
}
vkPhysDevice := devices[0]
gfx, err := vkPhysDevice.GraphicsFamily()
if err != nil {
panic(err.Error())
}
if !vkPhysDevice.SurfaceSupport(gfx, vkSurf) {
log.Fatalf("graphics queue cannot present")
return
}
vkDevice, vkQueue, err := vkPhysDevice.CreateDevice(vk.DeviceConfig{
GraphicsFamily: gfx,
Extensions: []string{"VK_KHR_swapchain"},
})
if err != nil {
panic(err)
}
defer vkDevice.Destroy()
// Create renderer
r, err := renderer.New(renderer.Config{
PhysDevice: vkPhysDevice,
Device: vkDevice,
Queue: vkQueue,
Surface: vkSurf,
Window: windowHandler,
GraphicsFamily: gfx,
VideoWidth: placeholderWidth,
VideoHeight: placeholderHeight,
VideoStride: placeholderStride,
})
if err != nil {
panic(err)
}
defer r.Destroy()
// Create GUI backend
guiBackend, err := imgui.NewVulkanBackend(
vkPhysDevice,
vkDevice,
vkQueue,
r.CmdPool(),
r.RenderPass(),
)
if err != nil {
panic(err)
}
defer guiBackend.Destroy()
r.ImGuiDraw = func(cmd vk.CommandBuffer) {
guiBackend.RecordDraw(cmd, gui.LastDrawData())
}
if err := r.StageFrame(
[]byte{0, 0, 0, 255},
placeholderWidth,
placeholderHeight,
placeholderStride,
); err != nil {
panic(err)
}
defer vkDevice.WaitIdle()
// GUI state (accessible from doReconnect + goroutine)
var (
videoDomainStr string = args.VideoDomain
audioDomainStr string = args.AudioDomain
videoStr string = args.VideoFlowId
audioStr string = args.AudioFlowId
showStats bool = false
)
videoActive := args.VideoFlowId != ""
audioActive := args.AudioFlowId != ""
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
player, err := newPlayerPlayback(sdlAudioDevice, retryPolicy)
if err != nil {
panic(err)
}
videoBridge := player.Video
statusStore := player.Status
syncRequested := args.SyncRequested
enqueueCommand := func(command playback.SessionCommand) {
select {
case player.Commands <- command:
default:
log.Printf("playback command queue is full; ignoring command %d", command.Kind)
}
}
doReconnect := func() {
videoDomainStr, videoStr = normalizeFeedInput(videoDomainStr, videoStr)
audioDomainStr, audioStr = normalizeFeedInput(audioDomainStr, audioStr)
videoActive = videoStr != ""
audioActive = audioStr != ""
videoConfig := playback.FeedConfig{}
if videoActive {
videoConfig = playback.FeedConfig{
Domain: videoDomainStr,
UUID: videoStr,
Active: true,
}
}
audioConfig := playback.FeedConfig{}
if audioActive {
audioConfig = playback.FeedConfig{
Domain: audioDomainStr,
UUID: audioStr,
Active: true,
}
}
enqueueCommand(playback.SessionCommand{
Kind: playback.CommandSetSession,
Session: playback.SessionConfig{
Video: videoConfig,
Audio: audioConfig,
SyncRequested: syncRequested,
},
})
}
drawUnitStatus := func(label string, unit playback.Unit) {
status, ok := statusStore.Snapshot(unit)
if !ok {
cimgui.Text(fmt.Sprintf("%s: not started", label))
return
}
cimgui.Text(fmt.Sprintf("%s: %s", label, status.State))
cimgui.Text(fmt.Sprintf(
"Attempt: %d, failed: %d",
status.Attempt,
status.FailedAttempts,
))
if status.RetryIn > 0 {
cimgui.Text(fmt.Sprintf(
"Retry in: %s",
status.RetryIn.Round(time.Millisecond),
))
}
if status.Err != nil {
cimgui.TextWrapped(status.Err.Error())
}
}
playbackDone := make(chan error, 1)
go func() {
playbackDone <- player.Controller.Run(
ctx,
args.playbackConfig(),
player.Commands,
)
}()
var playlistRuntime *playerPlaylist
var playlistDone chan error
if hasPlaylist {
playlistRuntime, err = newPlayerPlaylist(
configuredPlaylist,
retryPolicy,
player,
)
if err != nil {
panic(err)
}
playlistDone = make(chan error, 1)
go func() {
playlistDone <- playlistRuntime.Run(ctx)
}()
if shouldAutoStartPlaylist(args, configuredPlaylist) &&
!playlistRuntime.Select(0) {
log.Print("playlist command queue is full")
}
}
running := true
resized := false
fullscreen := args.IsFullscreen
if fullscreen {
sdl.SetWindowFullscreen(windowHandler, true)
}
var (
displayedVideoWidth uint32 = placeholderWidth
displayedVideoHeight uint32 = placeholderHeight
displayedVideoStride uint32 = placeholderStride
displayedVideoSource playback.FeedConfig
hasDisplayedVideo bool
fps float64
dropTracker videoDropTracker
dropped uint64
droppedTotal uint64
frameCount uint64
lastReport time.Time
lastFrame time.Time
renderLoopDT time.Duration
)
lastFrame = time.Now()
lastReport = lastFrame
// ImGui
var (
statsWindowWidth float32 = 460
statsWindowHeight float32 = 510
settingWindowWidth float32 = 700
settingsWindowState bool = true
)
for running {
frameStart := time.Now()
var event [128]byte
for sdl.PollEvent(unsafe.Pointer(&event[0])) {
eventType := *(*uint32)(unsafe.Pointer(&event[0]))
switch eventType {
case sdl.EventQuit:
running = false
case sdl.EventWindowResized, sdl.EventPixelSizeChanged:
resized = true
case sdl.EventKeyDown:
if gui.IO().WantCaptureKeyboard() {
break
}
key := *(*int32)(unsafe.Pointer(&event[28]))
switch uint32(key) {
case sdl.KeyQ:
fallthrough
case sdl.KeyEscape:
running = false
case sdl.KeyF:
fullscreen = !fullscreen
sdl.SetWindowFullscreen(windowHandler, fullscreen)
resized = true
case sdl.KeyF1:
settingsWindowState = !settingsWindowState
case sdl.KeyF2:
showStats = !showStats
}
}
gui.ProcessEvent(&event)
}
if !running {
break
}
if resized && r != nil {
if err := r.RecreateSwapchain(); err != nil {
if errors.Is(err, renderer.ErrMinimized) {
resized = true
paceFrame(frameStart)
continue
}
panic(err)
}
resized = false
}
var shownIndex uint64
var shownGeneration uint64
var shownSource playback.FeedConfig
hasFrame := false
frameCtx, frameCancel := context.WithTimeout(ctx, videoPollInterval)
pendingFrame, frameErr := videoBridge.Next(frameCtx)
frameCancel()
if pendingFrame != nil {
var stageErr error
if r != nil {
stageErr = r.StageFrame(
pendingFrame.Frame.Payload,
pendingFrame.Frame.Width,
pendingFrame.Frame.Height,
pendingFrame.Frame.Stride,
)
}
// Release the borrowed payload before reacting to a staging error
pendingFrame.Complete(stageErr)
if stageErr != nil {
panic(stageErr)
}
shownIndex = pendingFrame.Frame.Index
shownGeneration = pendingFrame.Generation
shownSource = pendingFrame.Source
displayedVideoWidth = pendingFrame.Frame.Width
displayedVideoHeight = pendingFrame.Frame.Height
displayedVideoStride = pendingFrame.Frame.Stride
hasFrame = true
} else if frameErr != nil &&
!errors.Is(frameErr, context.DeadlineExceeded) &&
!errors.Is(frameErr, context.Canceled) {
panic(frameErr)
}
snapshot, hasSnapshot := player.Controller.Snapshot()
desiredVideo := desiredVideoFeed(snapshot, hasSnapshot)
if !desiredVideo.Active ||
desiredVideo.Domain != displayedVideoSource.Domain ||
desiredVideo.UUID != displayedVideoSource.UUID {
hasDisplayedVideo = false
}
if hasFrame {
displayedVideoSource = shownSource
hasDisplayedVideo = shouldShowVideo(desiredVideo, shownSource)
}
// stats
if hasFrame {
if gap := dropTracker.Observe(shownGeneration, shownSource, shownIndex); gap > 0 {
dropped += gap
droppedTotal += gap
}
frameCount++
if now := time.Now(); now.Sub(lastReport) >= time.Second {
dt := now.Sub(lastReport).Seconds()
fps = float64(frameCount) / dt
fmt.Printf("fps=%.1f dropped=%d idx=%d frameTime=%.2fms\n",
fps, dropped, shownIndex, float64(now.Sub(frameStart).Microseconds())/1000.0)
frameCount = 0
dropped = 0
lastReport = now
}
}
// end of stats
if r != nil {
gui.BeginFrame(time.Since(lastFrame), int32(r.Extent().Width), int32(r.Extent().Height))
if showStats {
cimgui.SetNextWindowPos(cimgui.Vec2{X: float32(r.Extent().Width) - statsWindowWidth, Y: 0})
cimgui.SetNextWindowSize(cimgui.Vec2{X: statsWindowWidth, Y: statsWindowHeight})
cimgui.BeginV("Stats", &showStats, cimgui.WindowFlagsNoResize|cimgui.WindowFlagsNoScrollbar)
mediaStats := player.MediaStats.Snapshot()
cimgui.SeparatorText("Video")
if mediaStats.Video.Available {
label := mediaStats.Video.Label
if label == "" {
label = "(no label)"
}
cimgui.TextWrapped(fmt.Sprintf("Label: %s", label))
if hasSnapshot && snapshot.Desired.Video.IsConfigured() {
cimgui.TextWrapped(fmt.Sprintf("Domain: %s", snapshot.Desired.Video.Domain))
cimgui.TextWrapped(fmt.Sprintf("UUID: %s", snapshot.Desired.Video.UUID))
}
cimgui.Text(fmt.Sprintf(
"Resolution: %dx%d (stride %d)",
mediaStats.Video.Width,
mediaStats.Video.Height,
mediaStats.Video.Stride,
))
cimgui.Text(fmt.Sprintf(
"FPS: flow %.2f | received %.1f | displayed %.1f",
mediaStats.Video.DeclaredFPS,
mediaStats.Video.ReceivedFPS,
fps,
))
cimgui.Text(fmt.Sprintf(
"Frame dt: source %.1f ms | render loop %.1f ms",
float64(mediaStats.Video.FrameDT.Microseconds())/1000,
float64(renderLoopDT.Microseconds())/1000,
))
cimgui.Text(fmt.Sprintf(
"Index: %d | payload: %d bytes",
mediaStats.Video.Index,
mediaStats.Video.PayloadSize,
))
cimgui.Text(fmt.Sprintf(
"Dropped: %d | invalid: %d",
droppedTotal,
mediaStats.Video.Invalid,
))
} else {
cimgui.Text("No video frames received")
}
cimgui.SeparatorText("Audio")
if mediaStats.Audio.Available {
label := mediaStats.Audio.Label
if label == "" {
label = "(no label)"
}
cimgui.TextWrapped(fmt.Sprintf("Label: %s", label))
if hasSnapshot && snapshot.Desired.Audio.IsConfigured() {
cimgui.TextWrapped(fmt.Sprintf("Domain: %s", snapshot.Desired.Audio.Domain))
cimgui.TextWrapped(fmt.Sprintf("UUID: %s", snapshot.Desired.Audio.UUID))
}
cimgui.Text(fmt.Sprintf(
"Format: %.3f kHz, %d channels",
mediaStats.Audio.SampleRateHz/1000,
mediaStats.Audio.Channels,
))
cimgui.Text(fmt.Sprintf(
"Batch: %d samples (%.3f ms)",
mediaStats.Audio.SampleCount,
float64(mediaStats.Audio.BatchDuration.Microseconds())/1000,
))
cimgui.Text(fmt.Sprintf("Index: %d", mediaStats.Audio.Index))
} else {
cimgui.Text("No audio batches received")
}
cimgui.SeparatorText("Runtime")
if hasSnapshot {
cimgui.Text(fmt.Sprintf(
"Topology: %s | generation %d",
snapshot.Plan.Topology,
snapshot.Generation,
))
drawCompactStatus := func(label string, unit playback.Unit) {
status, ok := statusStore.Snapshot(unit)
if !ok {
cimgui.Text(fmt.Sprintf("%s: not started", label))
return
}
cimgui.Text(fmt.Sprintf(
"%s: %s (attempt %d, failed %d)",
label,
status.State,
status.Attempt,
status.FailedAttempts,
))
}
switch snapshot.Plan.Topology {
case playback.TopologySynchronized:
drawCompactStatus("Sync", playback.UnitSync)
case playback.TopologyIndependent:
if snapshot.Plan.Video.Active {
drawCompactStatus("Video", playback.UnitVideo)
}
if snapshot.Plan.Audio.Active {
drawCompactStatus("Audio", playback.UnitAudio)
}
}
} else {
cimgui.Text("Playback controller is starting")
}
cimgui.End()
}
// settings & info window
videoConfigured := videoStr != ""
audioConfigured := audioStr != ""
if hasSnapshot {
videoActive = snapshot.Desired.Video.Active
audioActive = snapshot.Desired.Audio.Active
videoConfigured = snapshot.Desired.Video.IsConfigured()
audioConfigured = snapshot.Desired.Audio.IsConfigured()
syncRequested = snapshot.Desired.SyncRequested
}
drawSettingsContents := func() {
var collapsingHeaderFlags cimgui.TreeNodeFlags = cimgui.TreeNodeFlagsDefaultOpen
drawFeedsSections := func() {
cimgui.SeparatorText("Video")
cimgui.InputTextWithHint("Video domain", "/dev/shm/mxl", &videoDomainStr, 0, nil)
if cimgui.IsItemDeactivatedAfterEdit() {
videoDomainStr, _ = normalizeFeedInput(videoDomainStr, "")
}
cimgui.InputTextWithHint("Video UUID", "", &videoStr, 0, nil)
if cimgui.IsItemDeactivatedAfterEdit() {
_, videoStr = normalizeFeedInput("", videoStr)
}
if videoActive {
cimgui.SameLine()
if cimgui.Button("Stop##video") {
videoActive = false
enqueueCommand(playback.SessionCommand{Kind: playback.CommandStopVideo})
}
}
if !videoActive && videoConfigured {
cimgui.SameLine()
if cimgui.Button("Resume##video") {
videoActive = true
enqueueCommand(playback.SessionCommand{Kind: playback.CommandResumeVideo})
}
}
if videoConfigured {
cimgui.SameLine()
if cimgui.Button("Remove##video") {
videoActive = false
videoStr = ""
enqueueCommand(playback.SessionCommand{Kind: playback.CommandRemoveVideo})
}
}
cimgui.SeparatorText("Audio")
cimgui.InputTextWithHint("Audio domain", "/dev/shm/mxl", &audioDomainStr, 0, nil)
if cimgui.IsItemDeactivatedAfterEdit() {
audioDomainStr, _ = normalizeFeedInput(audioDomainStr, "")
}
cimgui.InputTextWithHint("Audio UUID", "", &audioStr, 0, nil)
if cimgui.IsItemDeactivatedAfterEdit() {
_, audioStr = normalizeFeedInput("", audioStr)
}
if audioActive {
cimgui.SameLine()
if cimgui.Button("Stop##audio") {
audioActive = false
enqueueCommand(playback.SessionCommand{Kind: playback.CommandStopAudio})
}
}
if !audioActive && audioConfigured {
cimgui.SameLine()
if cimgui.Button("Resume##audio") {
audioActive = true
enqueueCommand(playback.SessionCommand{Kind: playback.CommandResumeAudio})
}
}
if audioConfigured {
cimgui.SameLine()
if cimgui.Button("Remove##audio") {
audioActive = false
audioStr = ""
enqueueCommand(playback.SessionCommand{Kind: playback.CommandRemoveAudio})
}
}
cimgui.SeparatorText("Controls")
if cimgui.Button("Apply feeds") {
doReconnect()
}
cimgui.SameLine()
if videoActive || audioActive {
if cimgui.Button("Stop all") {
enqueueCommand(playback.SessionCommand{Kind: playback.CommandStopAll})
}
}
if (videoConfigured && !videoActive) || (audioConfigured && !audioActive) {
if videoActive || audioActive {
cimgui.SameLine()
}
if cimgui.Button("Resume all") {
enqueueCommand(playback.SessionCommand{Kind: playback.CommandResumeAll})
}
}
cimgui.SameLine()
if cimgui.Checkbox("Synchronize", &syncRequested) {
kind := playback.CommandDisableSync
if syncRequested {
kind = playback.CommandEnableSync
}
enqueueCommand(playback.SessionCommand{Kind: kind})
}
cimgui.SeparatorText("Feeds stats")
cimgui.Checkbox("Show stats", &showStats)
}
if cimgui.CollapsingHeaderTreeNodeFlagsV("Feeds", collapsingHeaderFlags) {
drawFeedsSections()
}
if playlistRuntime != nil &&
cimgui.CollapsingHeaderTreeNodeFlagsV("Playlist", collapsingHeaderFlags) {
playlistSnapshot, hasPlaylistSnapshot :=
playlistRuntime.Controller.Snapshot()
cimgui.TextWrapped(fmt.Sprintf("File: %s", args.PlaylistPath))
cimgui.Text(fmt.Sprintf("Entries: %d", len(configuredPlaylist.Entries)))
if configuredPlaylist.Loop {
cimgui.Text("End behavior: loop")
} else {
cimgui.Text("End behavior: stop")
}
cimgui.Text(fmt.Sprintf(
"Failure behavior: %s",
configuredPlaylist.OnFailure,
))
if retryPolicy.MaxAttempts == 0 {
cimgui.Text("Retries: infinite")
} else {
cimgui.Text(fmt.Sprintf(
"Attempts per entry: %d",
retryPolicy.MaxAttempts,
))
}
cimgui.Text(fmt.Sprintf(
"Retry delay: %s to %s",
retryPolicy.InitialDelay,
retryPolicy.MaxDelay,
))
if hasPlaylistSnapshot && playlistSnapshot.HasFailure {
failure := playlistSnapshot.Failure
name := failure.EntryName
if name == "" {
name = fmt.Sprintf("Entry %d", failure.EntryIndex+1)
}
cimgui.SeparatorText("Last failure")
cimgui.TextWrapped(fmt.Sprintf(
"%s: %s failed",
name,
failure.Status.Unit,
))
cimgui.Text(fmt.Sprintf(
"Attempts: %d | failed attempts: %d",
failure.Status.Attempt,
failure.Status.FailedAttempts,
))
cimgui.Text(fmt.Sprintf("Policy: %s", failure.Policy))
if failure.Status.Err != nil {
cimgui.TextWrapped(failure.Status.Err.Error())
}
}
preview := "No entry selected"
if hasPlaylistSnapshot && playlistSnapshot.State.HasSelection {
preview = playlistEntryDisplayName(
playlistSnapshot.Entry,
playlistSnapshot.State.CurrentIndex,
)
}
if cimgui.BeginCombo("Entry##playlist", preview) {
for index, entry := range configuredPlaylist.Entries {
selected := hasPlaylistSnapshot &&
playlistSnapshot.State.HasSelection &&
playlistSnapshot.State.CurrentIndex == index
label := fmt.Sprintf(
"%s##playlist-entry-%d",
playlistEntryDisplayName(entry, index),
index,
)
if cimgui.SelectableBoolV(
label,
selected,
cimgui.SelectableFlagsNone,
cimgui.Vec2{},
) && !playlistRuntime.Select(index) {
log.Print("playlist command queue is full")
}
if selected {
cimgui.SetItemDefaultFocus()
}
}
cimgui.EndCombo()
}
if cimgui.Button("Previous##playlist") && !playlistRuntime.Previous() {
log.Print("playlist command queue is full")
}
cimgui.SameLine()
if cimgui.Button("Next##playlist") && !playlistRuntime.Next() {
log.Print("playlist command queue is full")
}
if hasPlaylistSnapshot &&
playlistSnapshot.State.HasSelection &&
playlistSnapshot.Entry.Duration > 0 &&
!playlistSnapshot.Timing.Expired {
cimgui.SameLine()
if playlistSnapshot.Timing.Paused {
if cimgui.Button("Resume timer##playlist") &&
!playlistRuntime.Resume() {
log.Print("playlist command queue is full")
}
} else if cimgui.Button("Pause timer##playlist") &&
!playlistRuntime.Pause() {
log.Print("playlist command queue is full")
}
}
if hasPlaylistSnapshot && playlistSnapshot.State.HasSelection {
entry := playlistSnapshot.Entry
cimgui.SeparatorText("Current entry")
cimgui.Text(fmt.Sprintf(
"%d of %d: %s",
playlistSnapshot.State.CurrentIndex+1,
len(configuredPlaylist.Entries),
playlistEntryDisplayName(entry, playlistSnapshot.State.CurrentIndex),
))
if entry.Video.IsConfigured() {
cimgui.TextWrapped(fmt.Sprintf(
"Video: %s (%s)",
entry.Video.UUID,
entry.Video.Domain,
))
}
if entry.Audio.IsConfigured() {
cimgui.TextWrapped(fmt.Sprintf(
"Audio: %s (%s)",
entry.Audio.UUID,
entry.Audio.Domain,
))
}
if entry.SyncRequested {
cimgui.Text("Synchronization: requested")
} else {
cimgui.Text("Synchronization: independent")
}
switch {
case entry.Duration == 0:
cimgui.Text("Timing: manual advance")
case playlistSnapshot.Timing.Paused:
fraction, remaining := playlistTimingProgress(
playlistSnapshot.Timing,
time.Now(),
)
cimgui.Text("Timing: paused")
cimgui.ProgressBarV(
fraction,
cimgui.Vec2{X: -1, Y: 0},
remaining.Round(time.Second).String(),
)
case playlistSnapshot.Timing.Started:
fraction, remaining := playlistTimingProgress(
playlistSnapshot.Timing,
time.Now(),
)
cimgui.Text(fmt.Sprintf("Duration: %s", entry.Duration))
cimgui.ProgressBarV(
fraction,
cimgui.Vec2{X: -1, Y: 0},
remaining.Round(time.Second).String(),
)
case playlistSnapshot.Timing.Expired:
cimgui.Text("Timing: finished")
default:
cimgui.Text("Timing: waiting for playback")
}
}
}
drawHotkeysSection := func() {
cimgui.Text("F1 - show/hide settings")
cimgui.Text("F2 - show/hide stats")
cimgui.Text("F - toggle fullscreen")
cimgui.Text("Q or Esc - quit")
}
if cimgui.CollapsingHeaderTreeNodeFlagsV("Hotkeys", collapsingHeaderFlags) {
drawHotkeysSection()
}
drawDebugSection := func() {
if hasSnapshot {
cimgui.Text(fmt.Sprintf(
"Topology: %s (generation %d)",
snapshot.Plan.Topology,
snapshot.Generation,
))
} else {
cimgui.Text("Topology: starting")
}
if hasSnapshot && syncRequested && snapshot.Plan.Topology != playback.TopologySynchronized {
switch {
case !videoConfigured || !audioConfigured:
cimgui.TextWrapped("Sync requested: waiting for both feeds to be configured.")
case !videoActive || !audioActive:
cimgui.TextWrapped("Sync requested: waiting for both feeds to be active.")
case snapshot.Desired.Video.Domain != snapshot.Desired.Audio.Domain:
cimgui.TextWrapped("Sync requested, but native MXL sync requires matching domains. Playing independently.")
default:
cimgui.TextWrapped("Sync requested but currently unavailable. Playing independently.")
}
}
cimgui.Separator()
cimgui.Text("Current playback")
if hasSnapshot {
switch snapshot.Plan.Topology {
case playback.TopologySynchronized:
drawUnitStatus("Synchronized group", playback.UnitSync)
case playback.TopologyIndependent:
if snapshot.Plan.Video.Active {
drawUnitStatus("Video", playback.UnitVideo)
}
if snapshot.Plan.Audio.Active {
drawUnitStatus("Audio", playback.UnitAudio)
}
case playback.TopologyIdle:
cimgui.Text("No active feeds")
}
} else {
cimgui.Text("Playback controller is starting")
}
cimgui.Separator()
if videoActive {
cimgui.Text("Video desired: active")
} else if videoConfigured {
cimgui.Text("Video desired: stopped")
} else {
cimgui.Text("Video desired: not configured")
}
if audioActive {
cimgui.Text("Audio desired: active")
} else if audioConfigured {
cimgui.Text("Audio desired: stopped")
} else {
cimgui.Text("Audio desired: not configured")
}
}
if cimgui.CollapsingHeaderTreeNodeFlagsV("Debug Info", cimgui.TreeNodeFlagsNone) {
drawDebugSection()
}
}
if settingsWindowState {
cimgui.SetNextWindowPos(cimgui.Vec2{X: 0, Y: 0})
cimgui.SetNextWindowSize(cimgui.Vec2{X: settingWindowWidth, Y: float32(r.Extent().Height)})
if cimgui.BeginV("Settings & Info", &settingsWindowState, cimgui.WindowFlagsNone) {
drawSettingsContents()
}
cimgui.End()
}
gui.EndFrame()
lastFrame = time.Now()
// end of test widget
err := r.DrawFrame(
displayedVideoWidth,
displayedVideoHeight,
displayedVideoStride,
hasDisplayedVideo,
)
if errors.Is(err, renderer.ErrOutOfDate) {
if rerr := r.RecreateSwapchain(); rerr != nil {
if errors.Is(rerr, renderer.ErrMinimized) {
resized = true
paceFrame(frameStart)
continue
}
panic(rerr)
}
continue
}
if err != nil {
panic(err)
}
renderLoopDT = time.Since(frameStart)
} else {
time.Sleep(10 * time.Millisecond)
}
}
cancel()
if err := <-playbackDone; err != nil && !errors.Is(err, context.Canceled) {
log.Printf("playback controller: %v", err)
}
if playlistDone != nil {
if err := <-playlistDone; err != nil && !errors.Is(err, context.Canceled) {
log.Printf("playlist runtime: %v", err)
}
}
if err := player.Close(); err != nil {
log.Printf("close playback: %v", err)
}
}