Skip to content

Repository files navigation

broadcast-hls

License Next.js TypeScript HLS.js Tailwind CSS

broadcast-hls is a professional HTTP Live Streaming (HLS .m3u8) and IPTV (.m3u) web platform engineered for live stream playback, real-time telemetry analytics, multi-stream monitoring, IPTV playlist management, channel zapping, and zero-copy CORS/Mixed-Content proxying.


Table of Contents


Application Purpose

Testing, monitoring, and playing live HLS streams over the open web introduces technical challenges:

  1. CORS Restrictions: Many IPTV, sports, and live broadcast streams block browser playback due to missing Cross-Origin Resource Sharing (Access-Control-Allow-Origin) response headers.
  2. Mixed Content Blocking: Web Browsers block unencrypted http:// streams when hosted on secure https:// origins.
  3. Lack of Diagnostics: Default HTML5 video elements do not expose real-time metrics such as buffer length, latency to live edge, dropped frames, or active ABR variant bitrates.
  4. IPTV Playlist Parsing: Public and commercial IPTV playlists (.m3u) contain thousands of channels with logos, categories, and custom HTTP headers (#EXTVLCOPT:http-user-agent).
  5. Multi-View Requirements: Broadcast engineers and sports operators often need to monitor multiple live feeds simultaneously in a synchronized layout.

broadcast-hls resolves these challenges in a unified web application styled after modern broadcast software and developer dashboards.


Audit & Architectural Improvements

Following an in-depth codebase audit and refactoring process, the following technical enhancements were implemented across the architecture:

1. Media Engine Resilience & Auto-Recovery

  • 2-Stage Media Error Handling: Implemented multi-tier media error recovery inside hooks/useHlsPlayer.ts. On first media error, the engine executes recoverMediaError(). On second consecutive failure, it calls swapAudioCodec() to switch audio demuxers before retrying media decoding.
  • Exponential Backoff Reconnecting: Added retry attempt tracking with exponential delays (1s, 2s, 4s, 8s, 16s) for non-fatal network interruptions before raising a fatal offline error state.
  • Memory Leak Protection: Enhanced component unmount logic by detaching media (hls.detachMedia()), stopping segment loading (hls.stopLoad()), destroying instances (hls.destroy()), and resetting video source attributes (video.removeAttribute('src'); video.load()).

2. High-Throughput Zero-Copy Stream Proxy

  • Zero-Copy Streaming: Refactored /api/stream/proxy to pipe binary media chunks (.ts, .m4s, .mp4, .aac) directly using Web ReadableStream instead of buffering payloads into server RAM via ArrayBuffer or inspecting text, resolving Node fetch stream locking 500 Internal Server Errors.
  • Custom Header Passthrough: Added support for ua (User-Agent) and referer search parameters to forward custom headers required by strict IPTV servers.
  • Proxy Unwrapping Helper: Added cleanStreamUrl to unwrap nested proxy paths and extract clean target stream URLs.

3. IPTV Playlist Engine & Default Auto-Seeding

  • Default 12,000+ All Channels Index: Updated default IPTV channel guide auto-seed to the main All Channels Index (index.m3u).
  • M3U Metadata Parser (utils/m3uParser.ts): Parses #EXTINF metadata (tvg-logo, group-title, tvg-country, tvg-language) and #EXTVLCOPT custom headers.
  • Local Storage State Store (hooks/useIptvStore.ts): Saves imported playlists, active selection, and starred favorite channels (⭐) across browser sessions.
  • Disk File Upload: Direct .m3u and .m3u8 file disk parsing.

4. Player Controls & Settings Popover Redesign

  • Top-Left Video Overlay LIVE Badge: Relocated the LIVE sync indicator ([πŸ”΄ LIVE]) to a sleek top-left video stage overlay alongside the channel title, freeing up bottom control bar real estate.
  • Hierarchical Settings Menu: Created a macOS/iOS style flyout menu (components/player/menu/) with submenus for Quality (QualityMenu.tsx), Audio Tracks (AudioMenu.tsx), Subtitles (SubtitleMenu.tsx), Playback Speed (SpeedMenu.tsx), and Low Latency mode.
  • Auto-Hide Freeze State: Automatically freezes the 2.5s auto-hide timer whenever Settings or diagnostic modals are open.
  • TV Zapping Pill: Added explicit ChannelZapButtons.tsx component with channel counter and hotkeys (N / P).

5. Component Modularization & Sub-Directories

  • Clean Component Separation: Extracted component sub-domains:
    • components/common/: StreamInput.tsx, StreamUrlForm.tsx, StreamSamplePresets.tsx, StreamValidationBadge.tsx, ProxyToggle.tsx, Footer.tsx.
    • components/iptv/: IptvPresetGrid.tsx, IptvImportBar.tsx, IptvViewControls.tsx, IptvCategoryPills.tsx, IptvChannelCard.tsx.
    • components/player/menu/: QualityMenu.tsx, AudioMenu.tsx, SubtitleMenu.tsx, SpeedMenu.tsx.
    • hooks/: Extracted state & event handlers into useMainApp.ts, useHlsPlayer.ts, useIptvStore.ts, useKeyboardShortcuts.ts, and useStreamHistory.ts.

6. Mobile-First Responsive Design

  • Responsive Navigation Header: Designed a collapsible mobile navigation drawer with touch-optimized buttons and hamburger toggle (Menu / X).
  • Touch Gesture Overlay: Large centered play/pause and Β±10s seek buttons overlayed on video stage for mobile tap interaction.

7. Framework Alignment & CSS Architecture

  • Next.js Font Optimization: Configured Google Fonts (Inter and JetBrains Mono) using next/font/google in app/layout.tsx for zero Cumulative Layout Shift (CLS).
  • Tailwind CSS Directive Ordering: Cleaned app/globals.css to begin directly with @tailwind base; @tailwind components; @tailwind utilities; in accordance with Next.js framework setup guides.

Understanding HLS & IPTV Playlists

What is HLS?

Developed by Apple Inc. in 2009 (IETF RFC 8216), HTTP Live Streaming (HLS) is an HTTP-based adaptive bitrate streaming protocol. It splits video content into small media segments (.ts, .m4s, or .aac) and delivers them over standard HTTP web servers.

What is an IPTV M3U Playlist?

An IPTV M3U Playlist is a text file listing channels, logos, categories, and stream URIs:

#EXTM3U
#EXTINF:-1 tvg-id="ESPN.us" tvg-logo="https://..." group-title="Sports", ESPN HD
http://example.com/live/espn.m3u8

Curated IPTV Categories Included

The application includes 8 pre-configured global IPTV playlist presets:

  1. All Channels (12,000+ Default Index): https://iptv-org.github.io/iptv/index.m3u
  2. Grouped by Category: https://iptv-org.github.io/iptv/index.category.m3u
  3. News Channels (930+): https://iptv-org.github.io/iptv/categories/news.m3u
  4. Sports Channels (320+): https://iptv-org.github.io/iptv/categories/sports.m3u
  5. Movies & Cinema (350+): https://iptv-org.github.io/iptv/categories/movies.m3u
  6. Music & Hits (650+): https://iptv-org.github.io/iptv/categories/music.m3u
  7. Grouped by Country: https://iptv-org.github.io/iptv/index.country.m3u
  8. Grouped by Language: https://iptv-org.github.io/iptv/index.language.m3u

Why Proxy HLS? (CORS & Mixed Content)

Loading a remote .m3u8 link from a third-party server directly in a client browser can trigger:

  • CORS Errors: Browsers reject cross-origin requests if the remote server omits Access-Control-Allow-Origin: *.
  • Mixed Content Errors: Attempting to load http://stream.m3u8 from an https:// origin triggers security blocks.

The broadcast-hls Proxy Architecture

The serverless proxy route (/api/stream/proxy):

  1. Requests the remote .m3u8 playlist server-side.
  2. Rewrites relative segment URIs into fully-qualified proxied endpoints.
  3. Streams segment byte data back to the browser with explicit Access-Control-Allow-Origin: * headers and zero-copy streaming.

Key Features

  • Hero Video Player: Built on hls.js with top-left overlay LIVE badge, space-saving controls, and auto-hide freeze state.
  • IPTV Playlist Manager: Full IPTV tab with LocalStorage persistence, disk upload, and search across 12,000+ streams.
  • TV Zapping: Next/Previous channel flipping via control bar buttons or keyboard shortcuts (N / P).
  • Starred Favorites: Star favorite channels (⭐) for instant access across sessions.
  • 4K UHD & Multi-Quality Selector: Supports adaptive Auto mode or forced quality levels (4K 2160p, 1440p, 1080p, 720p).
  • 10s Seek Controls & Live Edge Sync: Quick -10s and +10s seek buttons alongside top-left LIVE edge synchronization.
  • Multi-Audio Track & WebVTT Subtitles: Switch multi-language audio tracks and toggle closed captions.
  • CORS & HTTP Proxy Engine: Toggleable zero-copy proxying for seamless playback of restricted or HTTP streams.
  • Real-time Telemetry & Health Panel: Live monitoring of buffer length, latency to live edge, FPS, dropped frames, and download speed.
  • Multi-Stream Grid: View up to 4 concurrent live streams in a 2x2 multi-view layout with independent volume and fullscreen controls.
  • Stream History: Persists recent stream URLs in browser localStorage.
  • Shareable Direct Links: Share links pre-configured with query parameters (/?url=...&proxy=true).
  • Mobile & Touch Optimization: Responsive layouts tailored for smartphones, tablets, and desktop displays.

Project Architecture

broadcast-hls/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/stream/
β”‚   β”‚   β”œβ”€β”€ proxy/route.ts            # Serverless zero-copy CORS & HTTP proxy
β”‚   β”‚   β”œβ”€β”€ validate/route.ts         # Stream manifest & header validator
β”‚   β”‚   β”œβ”€β”€ health/route.ts           # Latency & ping health probe
β”‚   β”‚   └── history/route.ts          # Server-side history endpoint
β”‚   β”œβ”€β”€ globals.css                   # CSS design system tokens & utilities
β”‚   β”œβ”€β”€ layout.tsx                    # Root layout, next/font optimization & meta tags
β”‚   └── page.tsx                      # Main app container & tab router
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ common/
β”‚   β”‚   β”œβ”€β”€ Footer.tsx                # Application footer component
β”‚   β”‚   β”œβ”€β”€ ProxyToggle.tsx           # CORS Proxy toggle switch
β”‚   β”‚   β”œβ”€β”€ StreamInput.tsx           # Stream URL input bar
β”‚   β”‚   β”œβ”€β”€ StreamSamplePresets.tsx   # Quick stream sample preset chips
β”‚   β”‚   β”œβ”€β”€ StreamUrlForm.tsx         # Main URL form input
β”‚   β”‚   └── StreamValidationBadge.tsx # Stream validation status badge
β”‚   β”œβ”€β”€ iptv/
β”‚   β”‚   β”œβ”€β”€ IptvCategoryPills.tsx     # Category filter pills
β”‚   β”‚   β”œβ”€β”€ IptvChannelCard.tsx       # Channel card item
β”‚   β”‚   β”œβ”€β”€ IptvImportBar.tsx         # Playlist import & file upload bar
β”‚   β”‚   β”œβ”€β”€ IptvPresetGrid.tsx        # Preset playlist cards
β”‚   β”‚   └── IptvViewControls.tsx      # Search & grid/list layout controls
β”‚   β”œβ”€β”€ player/
β”‚   β”‚   β”œβ”€β”€ menu/
β”‚   β”‚   β”‚   β”œβ”€β”€ AudioMenu.tsx         # Multi-audio track selector
β”‚   β”‚   β”‚   β”œβ”€β”€ QualityMenu.tsx       # 4K UHD / HD video quality menu
β”‚   β”‚   β”‚   β”œβ”€β”€ SpeedMenu.tsx         # Playback speed menu
β”‚   β”‚   β”‚   └── SubtitleMenu.tsx      # Closed caption subtitles menu
β”‚   β”‚   β”œβ”€β”€ ChannelZapButtons.tsx     # TV Zapping channel buttons
β”‚   β”‚   β”œβ”€β”€ KeyboardShortcutsModal.tsx# Hotkeys documentation modal
β”‚   β”‚   β”œβ”€β”€ PlayerControls.tsx        # Bottom playback control bar
β”‚   β”‚   β”œβ”€β”€ PlayerOverlayMessages.tsx # Error & loading status overlay
β”‚   β”‚   β”œβ”€β”€ PlayerSkeleton.tsx        # Video player skeleton loader
β”‚   β”‚   β”œβ”€β”€ ProgressBar.tsx           # Timeline buffer progress bar
β”‚   β”‚   β”œβ”€β”€ SettingsMenu.tsx          # Hierarchical settings popover
β”‚   β”‚   β”œβ”€β”€ StreamInfoModal.tsx       # Diagnostic telemetry modal
β”‚   β”‚   β”œβ”€β”€ VideoPlayer.tsx           # Core video player & stage overlay
β”‚   β”‚   └── VolumeControl.tsx         # Mute & volume slider
β”‚   β”œβ”€β”€ telemetry/
β”‚   β”‚   └── StreamHealthPanel.tsx     # Diagnostic health panel & metrics
β”‚   β”œβ”€β”€ IptvChannelGuide.tsx          # Responsive IPTV channel drawer
β”‚   β”œβ”€β”€ IptvPlaylistTab.tsx           # Full IPTV channel guide tab
β”‚   β”œβ”€β”€ MultiView.tsx                 # 2x2 multi-stream grid player
β”‚   β”œβ”€β”€ Navbar.tsx                    # Responsive navigation header
β”‚   └── RecentStreams.tsx             # Stream history list
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ useHlsPlayer.ts               # hls.js lifecycle & auto-recovery hook
β”‚   β”œβ”€β”€ useIptvStore.ts               # LocalStorage IPTV store (Default: index.m3u)
β”‚   β”œβ”€β”€ useKeyboardShortcuts.ts       # Keyboard shortcuts listener
β”‚   β”œβ”€β”€ useMainApp.ts                 # Main page state container hook
β”‚   └── useStreamHistory.ts           # LocalStorage stream history hook
β”œβ”€β”€ utils/
β”‚   └── m3uParser.ts                  # M3U IPTV parser & URL unwrapper utility
β”œβ”€β”€ types/
β”‚   └── stream.ts                     # TypeScript interfaces
β”œβ”€β”€ package.json
└── README.md

API Endpoints

1. CORS Stream Proxy

GET /api/stream/proxy?url=<ENCODED_M3U8_URL>&ua=<USER_AGENT>&referer=<REFERER>

  • Fetches target .m3u8 manifest or segment byte data.
  • Forwards optional custom User-Agent and Referer headers.
  • Rewrites internal segment URIs to route through the proxy.
  • Returns payload with Access-Control-Allow-Origin: * and zero-copy streaming.

2. Stream Validator

POST /api/stream/validate

  • Body: { "url": "https://example.com/stream.m3u8" }
  • Response: Returns stream validity, content-type (application/x-mpegURL), resolution, and codecs.

Quick Start & Local Setup

Prerequisites

  • Node.js 18.x or higher
  • npm or pnpm

1. Clone & Install Dependencies

git clone https://github.com/Muhammed-Rizin/broadcast-hls.git
cd broadcast-hls
npm install

2. Run Development Server

npm run dev

Open http://localhost:3000 in your web browser.

3. Linting & Production Build

# Run ESLint check
npm run lint

# Compile Next.js production build
npm run build

# Start production server
npm run start

Keyboard Shortcuts

Shortcut Action
Space / K Toggle Play / Pause
F Toggle Fullscreen
M Toggle Mute
J / ← Seek 10 seconds backward
L / β†’ Seek 10 seconds forward
N / PageDown Next IPTV Channel
P / PageUp Previous IPTV Channel
0 Jump to Live edge

License

Distributed under the MIT License. See LICENSE for details.

About

All-in-one HLS stream analyzer and global IPTV playlist manager with 12,000+ live channels (News, Sports, Movies, Music), 4K UHD playback, multi-channel grid monitoring, custom HTTP header proxying, and channel zapping.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages