# S-Live - App Summary for Redesign

## Overview
**S-Live** is a CPU-optimized YouTube livestream application specifically designed for medical consultation and surgery rooms on Windows. The browser serves only as a control interface, while FFmpeg reads cameras directly via Windows DirectShow and pushes RTMP streams to YouTube.

## Target Users
- Medical professionals (doctors, surgeons) conducting telemedicine consultations
- Surgery rooms requiring high-quality live broadcasts
- Healthcare facilities with Windows-based infrastructure
- Users who need CPU-efficient streaming without heavy UI previews

## Current Architecture

### Technology Stack
- **Backend**: Node.js (Express.js) - `server/index.js`
- **Frontend**: Vanilla JavaScript - `public/app.js` + HTML/CSS
- **Streaming Engine**: FFmpeg static binary (spawned as child process)
- **Authentication**: Google OAuth 2.0 (YouTube integration)
- **Environment**: Windows only (DirectShow camera support)

### Backend Components (`server/index.js`)
1. **Express Server** (Port: 8788 default)
   - Static file serving for UI
   - REST API endpoints for device detection, streaming control, OAuth flow
   
2. **FFmpeg Process Management**
   - Spawns FFmpeg child process with custom codec parameters
   - Monitors stream health with frame stall detection (15s watchdog)
   - Auto-restart on failure (max 5 restarts)
   - Startup timeout monitoring (20s)
   - Captures FFmpeg stderr for detailed logging

3. **Device Discovery**
   - Lists available video/audio devices via DirectShow query
   - Caches encoder availability (NVIDIA NVENC, Intel QSV, AMD AMF)
   - GPU detection and fallback to CPU encoder

4. **Streaming Parameters**
   - **Presets**: Consultation (1280x720 30fps), Surgery (1920x1080 60fps)
   - **Bitrate**: 2000 Mbps (consultation), 5000 Mbps (surgery)
   - **Encoders**: NVIDIA NVENC, Intel QSV, AMD AMF, or CPU libx264
   - **RTMP Timeout**: 15 seconds

5. **YouTube OAuth Integration**
   - Generate OAuth authorization URL
   - Callback handling for token exchange
   - Access token refresh and storage
   - Create broadcast metadata (title, description, privacy)
   - Link video source and destination for RTMP ingestion
   - Get live link for sharing

6. **Overlay System**
   - Patient name overlay (configurable)
   - Logo watermark overlay (resizable, configurable position)
   - Font: Arial TTF (configurable via env)

7. **Logging & Diagnostics**
   - Separate log file per stream session: `logs/live-YYYY-MM-DDTHH-mm-ss-sssZ-camera.log`
   - Log size limit: 100MB per session
   - Captures: startup config, FFmpeg stderr, encoder changes, restart/stop/error events

8. **File Storage**
   - `settings.json`: User preferences (resolution, bitrate, devices, etc.)
   - `.tokens.json`: OAuth tokens for YouTube
   - `logo-overlay.png`: Generated overlay with RGBA v2 processing

### Frontend Components (`public/app.js`)

#### UI Sections
1. **Preset Selection**: Quick buttons for Consultation (720p30) or Surgery (1080p60)
2. **Custom Settings**: Manual configuration of resolution, FPS, bitrate, devices, encoder, latency
3. **Device Selection**: Dropdowns for video/audio device selection
4. **Stream Control**: Start/Stop buttons, Status badge, Stream timer
5. **Preview Section**: 
   - Live preview of camera feed (without canvas for CPU optimization)
   - Device info, source/output/encoder stats
   - Video/audio indicator lights
   - Audio level meter with RMS/peak dB display

6. **YouTube Integration Panel**:
   - OAuth login/logout
   - Manual stream key entry (hidden toggle)
   - Live link display with copy button
   - Broadcast creation with title/description modal

7. **Patient Info Panel**: Patient name input for overlay
8. **Logo Upload Panel**: Upload/clear custom logo with preview
9. **Settings Panel**: Collapsible panel with all controls
10. **Logging Panel**: Real-time FFmpeg log display

#### Key Features
- Real-time device refresh
- Stream status monitoring with uptime timer
- FFmpeg log streaming and display
- Patient name input validation modal
- OAuth user profile display (avatar, name, email)
- Bitrate slider with display value
- Latency mode selection
- Logo preview and management
- Stream statistics display (FPS, bitrate, speed, preset, output)

#### State Management
- Settings auto-save to `settings.json`
- OAuth mode vs. manual stream key mode toggle
- Real-time status polling
- Audio level updates
- Stream configuration validation

## Current Features

### Core Functionality
1. **Streaming Control**: Start/stop live streams to YouTube
2. **Camera Management**: DirectShow camera selection with resolution/FPS/bitrate control
3. **Encoder Selection**: Auto GPU detection or manual encoder choice
4. **OAuth Integration**: Google authentication with YouTube broadcast creation
5. **Manual Stream Key**: Option to input RTMP URL + key directly
6. **Overlay Graphics**: Patient name and logo watermarks
7. **Health Monitoring**: Frame stall detection, auto-restart on failure
8. **Logging**: Per-session FFmpeg debug logs with configurable retention
9. **Device Discovery**: Real-time detection of video/audio devices
10. **Audio Monitoring**: Live audio level meter with RMS/peak indicators

### Performance Optimizations
- No canvas preview (browser-side rendering) to minimize CPU usage
- Direct camera reading via DirectShow (not through browser)
- GPU encoder priority (NVENC > QSV > AMF > CPU fallback)
- RTMP watchdog for connection health
- Frame stall detection with automatic restart

## Design Constraints & Goals

### Constraints
- **Windows-only**: Requires DirectShow camera API
- **CPU Optimization**: Medical use case demands minimal CPU overhead
- **No Web Preview**: Canvas rendering disabled to save CPU
- **Single Broadcast**: Handles one stream at a time
- **Manual Installation**: PowerShell scripts for setup; not distributed on app stores

### Design Goals
- Simplicity: Single-purpose tool (no social features, playlists, etc.)
- Reliability: Auto-recovery from encoder/camera failures
- Transparency: Full FFmpeg logs accessible for debugging
- Quick Presets: One-click setup for common medical scenarios
- Professional Feel: Minimal UI, clinical focus

## Deployment Model

### Installation Methods
1. **Quick Install Script**: One-line PowerShell command from GitHub
2. **End-User Package**: Self-contained ZIP with `node_modules` included
3. **Manual Setup**: Clone repo, run installer, or start directly with `start.bat`

### Configuration
- **Environment Variables** (`.env`):
  - `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_REDIRECT_URI`
  - `PORT` (default 8788)
  - `FFMPEG_PATH` (custom FFmpeg binary)
  - `LOGO_PATH` (custom logo image)
  - `LOGO_WIDTH` (overlay size, default 120px)
  - `OVERLAY_FONT` (TTF path, default Arial)

## Current Pain Points / Future Considerations
1. No canvas preview limits real-time visual feedback
2. Manual device/encoder configuration could be more intuitive
3. FFmpeg log is text-only; no visual error indicators
4. Limited customization for overlay positioning/size in UI
5. OAuth setup complexity for end users
6. No multi-camera support
7. No recording capability (only streaming)

## File Structure
```
sanglive/
├── server/
│   └── index.js              # Backend: FFmpeg control, OAuth, API
├── public/
│   ├── app.js                # Frontend: UI logic, state management
│   ├── index.html            # HTML structure
│   ├── style.css             # Styling
│   ├── logo.png              # Default logo
│   └── sanglive.ico          # App icon
├── scripts/
│   └── build-enduser-package.ps1  # Packaging script
├── .runtime/                 # Runtime directory (settings, logos, overlays)
├── logs/                     # FFmpeg session logs
├── package.json              # Dependencies
├── .env.example              # Environment template
└── README.md                 # User documentation
```

## Key Dependencies
- **express**: HTTP server
- **ffmpeg-static**: Bundled FFmpeg binary
- **googleapis**: Google API client for OAuth and YouTube integration
- **dotenv**: Environment variable loading

## API Endpoints (Summary)
- `GET /api/devices` - List available video/audio devices
- `GET /api/status` - Get current stream status
- `POST /api/start` - Start streaming with config
- `POST /api/stop` - Stop streaming
- `POST /api/upload-logo` - Upload custom logo
- `GET /api/auth/url` - Get OAuth authorization URL
- `GET /auth/callback` - Handle OAuth callback
- `GET /api/user` - Get current OAuth user info
- `POST /api/logout` - Logout and clear tokens
- `POST /api/create-broadcast` - Create YouTube broadcast
- `GET /api/logs` - Stream FFmpeg logs in real-time
- `GET /api/settings` - Get saved settings
- `POST /api/settings` - Save settings

## Summary for Redesign Purposes
This is a **focused, single-purpose medical streaming tool** with:
- Deep integration with Windows DirectShow cameras
- Heavy reliance on FFmpeg child process orchestration
- Minimal UI philosophy (clinical focus, not eye candy)
- OAuth complexity hidden from casual users (manual key option available)
- Strong logging/debugging focus for troubleshooting live medical scenarios

**Key design principle**: CPU efficiency over feature richness. The current implementation avoids any unnecessary browser-side processing that would add overhead to medical workflows.
