package main import ( "context" "fmt" "io" "log" "net/http" "net/http/httputil" "net/url" "os" "os/signal" "strings" "syscall" "time" "tuner/api" "tuner/m3u" "tuner/process" ) func getEnv(key, fallback string) string { if v := os.Getenv(key); v != "" { return v } return fallback } // normalizePlaybackMode validates the PLAYBACK_MODE value. Accepts "standard", // "fmp4", or "llhls" (case-insensitive); anything else falls back to "standard". func normalizePlaybackMode(mode string) string { switch strings.ToLower(strings.TrimSpace(mode)) { case "llhls", "lowlatency", "low-latency": return "llhls" case "fmp4", "mp4", "fragmented-mp4", "fragmented_mp4": return "fmp4" default: return "standard" } } func normalizeIngestMode(mode string) string { switch strings.ToLower(strings.TrimSpace(mode)) { case "rtsp": return "rtsp" default: return "rtmp" } } func normalizeIngestAudioMode(mode string) string { switch strings.ToLower(strings.TrimSpace(mode)) { case "copy": return "copy" default: return "aac" } } // mediamtxEnvForMode returns the MTX_* environment variable overrides for the // given playback mode. func mediamtxEnvForMode(mode string) []string { if mode == "llhls" { // Low-Latency HLS: minimal latency, more sensitive to upstream jitter. return []string{ "MTX_HLSVARIANT=lowLatency", "MTX_HLSSEGMENTCOUNT=7", "MTX_HLSSEGMENTDURATION=1s", "MTX_HLSPARTDURATION=200ms", } } if mode == "fmp4" { // Fragmented MP4 HLS: smooth standard HLS with HEVC/H.265 support. return []string{ "MTX_HLSVARIANT=fmp4", "MTX_HLSSEGMENTCOUNT=7", "MTX_HLSSEGMENTDURATION=2s", } } // Standard HLS (mpegts): smooth, resilient, universally compatible (including iOS Safari). return []string{ "MTX_HLSVARIANT=mpegts", "MTX_HLSSEGMENTCOUNT=7", "MTX_HLSSEGMENTDURATION=2s", } } func parseRefreshInterval(value string) time.Duration { v := strings.ToLower(strings.TrimSpace(value)) if v == "" || v == "0" || v == "off" || v == "false" || v == "disabled" { return 0 } d, err := time.ParseDuration(v) if err != nil { log.Printf("[startup] warning: invalid PLAYLIST_AUTO_REFRESH_INTERVAL=%q, using 1h", value) return time.Hour } return d } // copyFile copies src to dst, creating dst if it doesn't exist. func copyFile(src, dst string) error { in, err := os.Open(src) if err != nil { return fmt.Errorf("open source: %w", err) } defer in.Close() if err := os.MkdirAll("/data", 0o755); err != nil { return fmt.Errorf("mkdir /data: %w", err) } out, err := os.Create(dst) if err != nil { return fmt.Errorf("create dest: %w", err) } defer out.Close() if _, err := io.Copy(out, in); err != nil { return fmt.Errorf("copy: %w", err) } return nil } func main() { playlistPath := getEnv("PLAYLIST_PATH", "/data/playlist.m3u") mediamtxBin := getEnv("MEDIAMTX_PATH", "mediamtx") mediamtxCfg := getEnv("MEDIAMTX_CONFIG", "mediamtx.yml") port := getEnv("RESTREAMER_PORT", "8080") playlistURL := getEnv("PLAYLIST_URL", "") useLocal := getEnv("PLAYLIST_USE_LOCAL", "false") == "true" playbackMode := normalizePlaybackMode(getEnv("PLAYBACK_MODE", "standard")) ingestMode := normalizeIngestMode(getEnv("INGEST_MODE", "rtmp")) ingestAudioMode := normalizeIngestAudioMode(getEnv("INGEST_AUDIO_MODE", "aac")) playlistRefreshInterval := parseRefreshInterval(getEnv("PLAYLIST_AUTO_REFRESH_INTERVAL", "1h")) localSrcPath := getEnv("PLAYLIST_LOCAL_SRC", "/data/playlist.m3u.local") // Fetch playlist from URL unless PLAYLIST_USE_LOCAL=true if !useLocal && playlistURL != "" { if err := api.FetchPlaylist(playlistURL, playlistPath); err != nil { log.Printf("[startup] warning: could not fetch playlist from URL: %v", err) } } else if useLocal { log.Printf("[startup] PLAYLIST_USE_LOCAL=true, copying %s -> %s", localSrcPath, playlistPath) if err := copyFile(localSrcPath, playlistPath); err != nil { log.Printf("[startup] warning: could not copy local playlist: %v", err) } } // Initialize process managers mtxManager := process.NewMediaMTXManager(mediamtxBin, mediamtxCfg) mtxManager.SetEnv(mediamtxEnvForMode(playbackMode)) ffmpegManager := process.NewFFmpegManager(ingestMode, ingestAudioMode) log.Printf("[startup] playback mode: %s", playbackMode) log.Printf("[startup] ingest mode: %s", ingestMode) log.Printf("[startup] ingest audio mode: %s", ingestAudioMode) // Build shared app state app := &api.App{ PlaylistPath: playlistPath, PlaybackMode: playbackMode, MediaMTX: mtxManager, FFmpeg: ffmpegManager, } // Only expose the URL for reloads when we're in URL mode if !useLocal && playlistURL != "" { app.PlaylistURL = playlistURL } // Load playlist (warn but don't crash if missing) channels, err := m3u.ParseFile(playlistPath) if err != nil { log.Printf("[startup] warning: could not load playlist %s: %v", playlistPath, err) } else { app.Channels = channels app.PlaylistVersion = 1 app.Status.PlaylistVersion = app.PlaylistVersion log.Printf("[startup] loaded %d channels from %s", len(channels), playlistPath) } if playlistRefreshInterval > 0 { log.Printf("[startup] playlist auto-refresh enabled: %s", playlistRefreshInterval) go func() { ticker := time.NewTicker(playlistRefreshInterval) defer ticker.Stop() for range ticker.C { count, err := app.ReloadPlaylist() if err != nil { log.Printf("[playlist] auto-refresh failed: %v", err) continue } log.Printf("[playlist] auto-refreshed: %d channels", count) } }() } else { log.Printf("[startup] playlist auto-refresh disabled") } // Start MediaMTX (warn but don't crash if binary not found) if err := mtxManager.Start(); err != nil { log.Printf("[startup] warning: could not start mediamtx: %v", err) } // Register routes mux := http.NewServeMux() // API routes mux.HandleFunc("/api/config", app.HandleConfig) mux.HandleFunc("/api/status", app.HandleStatus) mux.HandleFunc("/api/admin/channels", app.HandleChannels) mux.HandleFunc("/api/admin/groups", app.HandleGroups) mux.HandleFunc("/api/admin/source", app.HandleSetSource) mux.HandleFunc("/api/admin/channel", app.HandleSetChannel) mux.HandleFunc("/api/admin/playlist/reload", app.HandleReloadPlaylist) mux.HandleFunc("/api/admin/process/status", app.HandleProcessStatus) // Proxy HLS through the main app origin so HTTPS deployments avoid mixed content. hlsURL, err := url.Parse("http://127.0.0.1:8888") if err != nil { log.Printf("[startup] warning: invalid HLS proxy URL: %v", err) } else { mux.Handle("/live/", httputil.NewSingleHostReverseProxy(hlsURL)) } // Serve frontend static files (falls back to index.html for SPA routing) frontendDir := getEnv("FRONTEND_DIR", "frontend/dist") if info, err := os.Stat(frontendDir); err == nil && info.IsDir() { fs := http.FileServer(http.Dir(frontendDir)) mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Try to serve the file; if it doesn't exist, serve index.html (SPA fallback) path := frontendDir + r.URL.Path if _, err := os.Stat(path); os.IsNotExist(err) && r.URL.Path != "/" { http.ServeFile(w, r, frontendDir+"/index.html") return } fs.ServeHTTP(w, r) })) log.Printf("[startup] serving frontend from %s", frontendDir) } else { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("Tuner backend running. Frontend not found.")) }) log.Printf("[startup] frontend dir %s not found, serving placeholder", frontendDir) } // Wrap with middleware handler := api.Logging(api.CORS(mux)) server := &http.Server{ Addr: ":" + port, Handler: handler, } // Graceful shutdown go func() { sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) sig := <-sigCh log.Printf("[shutdown] received %v, shutting down...", sig) // Stop child processes if err := ffmpegManager.Stop(); err != nil { log.Printf("[shutdown] error stopping ffmpeg: %v", err) } if err := mtxManager.Stop(); err != nil { log.Printf("[shutdown] error stopping mediamtx: %v", err) } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := server.Shutdown(ctx); err != nil { log.Printf("[shutdown] http server shutdown error: %v", err) } }() log.Printf("[startup] listening on :%s", port) if err := server.ListenAndServe(); err != http.ErrServerClosed { log.Fatalf("[fatal] server error: %v", err) } log.Println("[shutdown] complete") }