# Xtream Codes - IPTV Patterns & Integrations ## 1. Stream URL Patterns ### Live TV URL Structure ``` http://{server}:{port}/live/{username}/{password}/{stream_id}.{extension} ``` | Extension | Use Case | Content-Type | |-----------|----------|--------------| | .ts | MPEG Transport Stream (most compatible) | video/mp2t | | .m3u8 | HLS Adaptive Streaming | application/x-mpegurl | ### VOD URL Structure ``` http://{server}:{port}/movie/{username}/{password}/{stream_id}.{extension} ``` Container extensions: mp4, mkv, avi, 3gp, flv, wmv, mov, ts ### Series URL Structure ``` http://{server}:{port}/series/{username}/{password}/{episode_stream_id}.{extension} ``` ### Timeshift/Catchup URL Structure ``` http://{server}:{port}/timeshift/{username}/{password}/{duration_minutes}/{start_time}/{stream_id} ``` Start time formats: - `YYYY-MM-DD:HH-MM` (e.g., `2025-12-24:10-00`) - `YYYYMMDD-HH` (e.g., `20251224-10`) --- ## 2. M3U Playlist Format ### Standard M3U Plus Format ```m3u #EXTM3U #EXTINF:-1 tvg-id="channel.epg" tvg-name="Channel Name" tvg-logo="http://icon.url" group-title="Category",Channel Name http://server:25461/live/user/pass/123.ts ``` ### Extended Attributes | Attribute | Description | |-----------|-------------| | tvg-id | EPG channel identifier | | tvg-name | Display name | | tvg-logo | Channel icon URL | | group-title | Category name | | tvg-chno | Channel number | | radio | "true" for radio streams | ### Catchup Support Tags ```m3u #EXTINF:-1 tvg-id="channel.epg" catchup="default" catchup-source="http://server:25461/timeshift/user/pass/{duration:60}/{start}/123.ts" catchup-days="7",Channel Name ``` --- ## 3. EPG/XMLTV Integration ### XMLTV Format ```xml Channel Name Program Title Description News ``` ### EPG URL ``` http://server:25461/xmltv.php?username={user}&password={pass} ``` ### EPG Mapping The `tvg-id` attribute in M3U must match the `channel id` in XMLTV. --- ## 4. MAG/Stalker Portal Integration ### Authentication Flow 1. Device sends handshake with MAC address 2. Server returns token 3. Device includes token in all subsequent requests 4. Watchdog keeps session alive ### Required Headers ``` Authorization: Bearer {token} Cookie: mac={mac_address}; timezone={timezone}; locale={locale} X-User-Agent: Model: MAG254; Link: WiFi ``` ### Stalker URL Encryption For secure streaming, URLs are encrypted: ```php $stalker_key = base64_encode(mc_encrypt("{$mac}={$ip}={$stream_id}={$expire_time}", $secret)); ``` ### Event Types | Event | Description | |-------|-------------| | send_msg | Display message | | reboot | Reboot device | | reload_portal | Reload portal | | play_channel | Auto-tune to channel | | cut_off | Disconnect device | --- ## 5. Enigma2 Integration ### Service Reference Format Enigma2 uses service references for channels: ``` #SERVICE 4097:0:1:0:0:0:0:0:0:0:http://server:25461/live/user/pass/123.ts:Channel Name #DESCRIPTION Channel Name ``` ### Bouquet File Format ``` #NAME Provider Bouquet #SERVICE 4097:0:1:0:0:0:0:0:0:0:http://server:25461/live/user/pass/123.ts:Channel 1 #DESCRIPTION Channel 1 #SERVICE 4097:0:1:0:0:0:0:0:0:0:http://server:25461/live/user/pass/124.ts:Channel 2 #DESCRIPTION Channel 2 ``` ### XML Response Format All Enigma2 API responses use XML with Base64-encoded text: ```xml Q2hhbm5lbCBOYW1l RGVzY3JpcHRpb24= ``` --- ## 6. HLS Streaming ### Playlist Structure ```m3u #EXTM3U #EXT-X-VERSION:3 #EXT-X-TARGETDURATION:3 #EXT-X-MEDIA-SEQUENCE:1000 #EXTINF:3.0, 123_1000.ts?token=abc123 #EXTINF:3.0, 123_1001.ts?token=def456 #EXTINF:3.0, 123_1002.ts?token=ghi789 ``` ### Segment Token Validation Each segment URL includes a token: ``` token = md5(segment_name + username + crypt_key + filesize) ``` ### Connection Tracking - HLS connections tracked via `user_activity_now` table - `hls_last_read` timestamp updated per segment request - Inactive HLS connections cleaned up by cron --- ## 7. Load Balancing ### Server Selection Load balancer selects optimal server based on: - Server load (active connections) - Geographic proximity - Server status (online/offline) - Stream availability ### Redirect Mechanism ```nginx location /live/ { proxy_pass http://load_balancer; } ``` ### Balance Configuration `nginx/conf/balance.conf`: ```nginx upstream streaming_servers { server 192.168.1.1:25461 weight=5; server 192.168.1.2:25461 weight=3; server 192.168.1.3:25461 backup; } ``` --- ## 8. TV Archive/Catchup ### Archive Storage ``` /home/xtreamcodes/iptv_xtream_codes/tv_archive/{stream_id}/YYYY-MM-DD:HH-MM.ts ``` ### Archive Duration Configured per-stream via `tv_archive_duration` (days). ### Timeshift Playback ```bash # Last 60 minutes from channel 123 curl "http://server/timeshift/user/pass/60/2025-12-24:10-00/123" # HLS format for player apps curl "http://server/timeshift/user/pass/60/2025-12-24:10-00/123.m3u8" ``` --- ## 9. Multi-Server Architecture ### Server Roles | Role | Description | |------|-------------| | Main | Database, panel, management | | Load Balancer | Traffic distribution | | Streaming | Stream transcoding/delivery | ### Inter-Server Communication Via `system_api.php`: - Connection state synchronization - Stream start/stop commands - User activity tracking ### Server Registration Each server has unique `SERVER_ID` from config file. --- ## 10. Authentication & Security ### User Authentication Checks (in order) 1. Username/password validation 2. Account expiration check 3. Admin enabled check 4. User enabled check 5. IP whitelist check 6. Country restriction check 7. User agent validation 8. ISP restriction check 9. Max connections check 10. Bouquet access check ### Security Features | Feature | Description | |---------|-------------| | GeoIP | Country-based restrictions | | ISP Lock | Restrict to specific ISPs | | IP Whitelist | Per-user allowed IPs | | UA Whitelist | Per-user allowed user agents | | Max Connections | Concurrent connection limit | | Flood Protection | Rate limiting failed auth | ### Play Token System For MAG devices: ``` play_token = random_string:expire_timestamp:stream_id ``` Validated before streaming to prevent URL sharing. --- ## 11. Bouquet System ### Bouquet Structure Bouquets group streams and categories for user access control. ```json { "bouquet_id": 1, "bouquet_name": "Basic Package", "bouquet_channels": [1, 2, 3, 4, 5], "bouquet_series": [10, 11, 12], "bouquet_movies": [100, 101, 102] } ``` ### User Bouquet Assignment ```json { "user_id": 100, "bouquet": [1, 2, 3] // User has access to bouquets 1, 2, and 3 } ``` ### Category-Based Access Categories can be assigned to bouquets for bulk access control. --- ## 12. Reseller System ### Reseller Hierarchy ``` Admin ├── Reseller 1 │ ├── User A │ ├── User B │ └── Sub-reseller 1.1 │ └── User C └── Reseller 2 └── User D ``` ### Credit System Resellers have credits to create/extend users: - 1 credit = 1 month subscription - Credits deducted on user creation/extension - Admin can add credits to resellers ### Reseller Permissions | Permission | Description | |------------|-------------| | add_user | Can create users | | edit_user | Can modify own users | | delete_user | Can delete own users | | add_mag | Can register MAG devices | | add_e2 | Can register Enigma2 | | allowed_ips | Restrict reseller panel access | --- ## 13. Output Formats ### User-Allowed Formats ```json { "allowed_output_formats": ["ts", "m3u8", "rtmp"] } ``` ### Format Handling | Format | Handler | Use Case | |--------|---------|----------| | ts | clients_live.php | Direct streaming | | m3u8 | clients_live.php | HLS adaptive | | rtmp | rtmp handler | Flash players | ### Container Mapping ```php $containers = [ 'ts' => 'video/mp2t', 'm3u8' => 'application/x-mpegurl', 'mp4' => 'video/mp4', 'mkv' => 'video/x-matroska', 'avi' => 'video/x-msvideo' ]; ``` --- ## 14. Client Activity Tracking ### Activity Table Structure ```sql user_activity_now ( activity_id INT PRIMARY KEY, user_id INT, stream_id INT, server_id INT, user_agent VARCHAR, user_ip VARCHAR, container VARCHAR, pid INT, date_start INT, geoip_country_code VARCHAR, isp VARCHAR, external_device VARCHAR, hls_last_read INT, hls_end TINYINT ) ``` ### Connection Lifecycle 1. INSERT on stream start 2. UPDATE `hls_last_read` for HLS 3. DELETE on stream end 4. Archive to `user_activity` for history --- ## 15. Error Handling Patterns ### Graceful Degradation ```php // Show alternative video on errors ipTV_streaming::ShowVideo($is_restreamer, 'show_not_on_air_video', 'not_on_air_video_path', $extension); ``` ### Video Placeholders | Setting | Description | |---------|-------------| | show_expired_video | Show when user expired | | show_banned_video | Show when user banned | | show_not_on_air_video | Show when stream offline | ### Client Logging All access attempts logged for debugging: ```php ipTV_streaming::ClientLog($stream_id, $user_id, 'ERROR_CODE', $user_ip, $extra_data); ```