### Centralized Configuration Management with Singleton (Python) Source: https://context7.com/muhammetssen/videosync/llms.txt The `Config` class implements a singleton pattern for centralized configuration. It manages network ports, video parameters, codec settings, and node identification. It automatically detects the local IP address and creates necessary temporary directories. ```python from config import Config import cv2 # Access singleton instance config = Config() # Network configuration print(f"My IP: {config.MY_IP}") print(f"Control Port: {config.CONTROL_PORT}") print(f"Data Port: {config.DATA_PORT}") # Output: # My IP: 192.168.1.101 # Control Port: 12345 # Data Port: 12346 # Video configuration config.VIDEO_RESOLUTION = (1280, 720) config.VIDEO_FPS = 24 config.VIDEO_DURATION = 1 config.SCREENSHOT_RESOLUTION = (1920, 1080) print(f"Recording {config.VIDEO_FPS} FPS at {config.VIDEO_RESOLUTION}") # Codec settings config.VIDEO_CODEC = cv2.VideoWriter_fourcc(*"avc1") config.FILE_EXTENSION = ".mp4" config.COMPRESSION_ENABLED = True # Node identification config.WHAT_AM_I = "server" # or "client" config.NAME = "server" # or "c1", "c2", etc. # Temporary file storage print(f"Temp directory: {config.TEMP_DIR}") # Output: Temp directory: temp # Directory is automatically created if it doesn't exist ``` -------------------------------- ### Command Line Input Listener Source: https://context7.com/muhammetssen/videosync/llms.txt The `input_listener` module provides a command-line interface for interacting with the running application. It supports commands like 'list' to trigger peer discovery and display current connections. Invalid commands are handled with an error message. ```python from input_listener import startup from connection import Connection from communication import udp_broadcast # Start input listener in background thread startup() # Available commands (type in terminal while app is running): # # Command: list # Action: Broadcasts UDP hello message and displays current connections # Output: Current addresses: {'192.168.1.100': 'server', '192.168.1.102': 'c2'} # Programmatic equivalent: udp_broadcast() print("Current addresses:", Connection().connected_ips) # Invalid commands produce error message: # Input: status # Output: Invalid command! # The listener runs continuously in a separate thread # allowing users to query connection state at any time ``` -------------------------------- ### Network Communication and Peer Discovery Source: https://context7.com/muhammetssen/videosync/llms.txt Handles UDP broadcasting for peer discovery and TCP listening for control messages and delay probes. It implements a handshake protocol where nodes broadcast 'hello' and respond with 'aleykumselam' to establish connections. Dependencies include 'communication', 'connection', and 'config' modules. ```python from communication import startup, udp_broadcast, send_probe from connection import Connection from config import Config import json import time # Start all communication threads (UDP/TCP listeners, broadcaster, sync) startup() # Manual peer discovery broadcast udp_broadcast() # Sends: {"type": "hello", "myname": "c1"} to 192.168.1.255:12345 # Wait for connections to establish time.sleep(2) # Check connected peers print(Connection().connected_ips) # Output: {'192.168.1.100': 'server', '192.168.1.102': 'c2'} # Measure network delay to a specific client client_ip = "192.168.1.102" delay = send_probe(client_ip) print(f"Round-trip time: {delay*1000:.2f} ms") # Performs 3 TCP probes, sends "_" and waits for response # Example output: Round-trip time: 3.24 ms # Access bidirectional mapping server_ip = Connection().connected_ips.inv['server'] print(f"Server IP: {server_ip}") # Output: Server IP: 192.168.1.100 ``` -------------------------------- ### Server-Side Screen Recording and Distribution Source: https://context7.com/muhammetssen/videosync/llms.txt Manages screen recording, encoding, and synchronized video distribution to clients. It captures screen content, encodes video chunks, and sends them with calculated delays to maintain synchronization. The recording loop runs in a thread and pauses when no clients are connected. Dependencies include 'server', 'config', and 'communication' modules. ```python from server import Server from config import Config from communication import startup as communication_startup # Configure video parameters Config().VIDEO_RESOLUTION = (854, 480) Config().VIDEO_FPS = 30 Config().VIDEO_DURATION = 1 Config().COMPRESSION_ENABLED = False # Initialize communication layer (UDP/TCP listeners, sync threads) communication_startup() # Start server instance (begins recording automatically) server = Server() # Server continuously records screen in 1-second chunks # Each chunk is distributed to clients with calculated sync delays # Example internal flow: # 1. Screen captured at 30 FPS for 1 second (30 frames) # 2. Video encoded to temp/1698765432.mp4 # 3. SyncManager provides delays: {'server': 0, 'c1': 15.2, 'c2': 23.7} # 4. Video sent to c1 immediately, to c2 after 8.5ms delay # Stop recording when needed server.stop_recording() ``` -------------------------------- ### Client-Side Video Reception and Playback Source: https://context7.com/muhammetssen/videosync/llms.txt Listens for incoming video chunks, saves them to temporary files, and plays them using VLC media player in fullscreen. It maintains a persistent TCP connection for video data and handles continuous playback of received segments. Dependencies include 'client', 'config', 'communication', and 'vlc'. ```python from client import Client from config import Config from communication import startup as communication_startup import vlc # Configure client settings Config().MY_IP = "192.168.1.101" Config().DATA_PORT = 12346 Config().TEMP_DIR = "temp" # Start communication layer to discover and connect to server communication_startup() # Initialize client (starts listening and VLC player) client = Client() # Client internal flow: # 1. Listens on DATA_PORT (12346) # 2. Receives video chunk bytes via TCP # 3. Saves to temp/1698765432.0.mp4 # 4. Plays video with VLC: client.media_player.set_mrl(filename) # 5. Repeats for continuous streaming # Client runs indefinitely until process termination ``` -------------------------------- ### Video Compression Utility using FFmpeg Source: https://context7.com/muhammetssen/videosync/llms.txt The `compress_video` module leverages FFmpeg to compress video files, reducing their size for efficient network transmission. It uses H.264 encoding with a `superfast` preset and a configurable CRF value for quality control. ```python from utils.compress_video import compress, get_compress_name from config import Config import os # Configure compression Config().FILE_EXTENSION = ".mp4" # Get compressed filename without processing original = "temp/1698765432.5.mp4" compressed_name = get_compress_name(original) print(compressed_name) # Output: temp/1698765432.5_comp.mp4 # Compress video file result = compress(original) print(f"Compressed: {result}") # Compare file sizes original_size = os.path.getsize(original) compressed_size = os.path.getsize(result) ratio = (1 - compressed_size/original_size) * 100 print(f"Original: {original_size/1024:.2f} KB") print(f"Compressed: {compressed_size/1024:.2f} KB") print(f"Reduction: {ratio:.1f}%") # Example output: # Original: 2847.32 KB # Compressed: 892.15 KB # Reduction: 68.7% # Compression settings used: # - crf=35 (quality factor, higher=smaller/lower quality) # - vcodec=libx264 (H.264 encoding) # - preset=superfast (fast encoding, larger files than slower presets) # - loglevel=quiet (suppress ffmpeg output) ``` -------------------------------- ### Record Screen Content with Compression (Python) Source: https://context7.com/muhammetssen/videosync/llms.txt The `video_recorder` utility captures screen content using `mss`, encodes frames with OpenCV, and supports optional compression using ffmpeg. Recording runs in a separate thread with precise frame timing using busy-wait sleep. It returns the filename of the recorded video. ```python from utils import video_recorder from config import Config import time # Configure recording parameters Config().VIDEO_RESOLUTION = (1280, 720) Config().SCREENSHOT_RESOLUTION = (1920, 1080) Config().VIDEO_FPS = 30 Config().VIDEO_DURATION = 2 # seconds Config().COMPRESSION_ENABLED = True # Record screen for specified duration start = time.time() video_file = video_recorder.record() print(f"Recording completed: {video_file}") # Output: Recording completed: temp/1698765432.5.mp4 # Total time elapsed: 2.003 seconds # Internal process: # 1. Creates VideoWriter with H.264 codec (avc1) # 2. Captures 60 frames (30 FPS × 2 seconds) # 3. Each frame: grab 1920x1080, convert BGRA→BGR, resize to 1280x720 # 4. Writes frames to file using separate saver thread # 5. If compression enabled: runs ffmpeg with crf=35, libx264, superfast # 6. Returns compressed filename: temp/1698765432.5_comp.mp4 # Read and use the video file with open(video_file, 'rb') as f: video_bytes = f.read() print(f"Video size: {len(video_bytes)/1024:.2f} KB") ``` -------------------------------- ### Manage Synchronization with Linear Equations (Python) Source: https://context7.com/muhammetssen/videosync/llms.txt The SyncManager calculates optimal delays for clients using linear equations derived from network latency measurements. It continuously receives round-trip delay data and solves for absolute delays relative to a reference point. Results are stored in `current_delays`. ```python from server import SyncManager from sympy import symbols, Eq, solve # SyncManager is instantiated within Server sync_manager = SyncManager() # Simulate delay measurements between nodes # Format: sender_name, receiver_name, round_trip_delay_ms sync_manager.update('server', 'c1', 15.4) sync_manager.update('server', 'c2', 23.8) sync_manager.update('c1', 'c2', 18.6) # Additional measurements accumulate sync_manager.update('server', 'c1', 14.8) sync_manager.update('server', 'c2', 24.2) sync_manager.update('c1', 'c2', 19.1) # Solve the equation system (automatically called every 5 seconds) sync_manager.solve() # Result stored in current_delays print(sync_manager.current_delays) # Output: {'c2': 23.5, 'c1': 15.1, 'server': 0.0} # Interpretation: c2 has highest latency, send videos to c2 first, # then wait 8.4ms before sending to c1, then 15.1ms to server (if needed) # Mathematical model: # Let s = server delay, c1 = client1 delay, c2 = client2 delay # Equations: s + c1 = 15.1, s + c2 = 23.5, c1 + c2 = 18.6 # Solve and normalize to min=0: {s: 0, c1: 15.1, c2: 23.5} ``` -------------------------------- ### Precise Sleep Utility using Busy-Waiting Source: https://context7.com/muhammetssen/videosync/llms.txt The `perfect_sleep` function achieves high-precision sleep by using busy-waiting, essential for accurate frame timing in video recording. It offers significantly less overshoot compared to `time.sleep()` and is demonstrated with frame rate maintenance. ```python from utils.perfect_sleep import perfect_sleep import time # Standard sleep vs perfect sleep comparison start = time.perf_counter() time.sleep(0.001) # Request 1ms sleep elapsed = time.perf_counter() - start print(f"time.sleep(0.001): {elapsed*1000:.3f} ms") # Output: time.sleep(0.001): 1.523 ms (varies, often overshoots) start = time.perf_counter() perfect_sleep(0.001) # Request 1ms sleep elapsed = time.perf_counter() - start print(f"perfect_sleep(0.001): {elapsed*1000:.3f} ms") # Output: perfect_sleep(0.001): 1.001 ms (precise, minimal overshoot) # Use case: maintaining exact frame rate fps = 30 frame_interval = 1.0 / fps # 33.333ms per frame for frame_num in range(30): frame_start = time.perf_counter() # Simulate frame processing (capture, encode) time.sleep(0.020) # 20ms processing time # Sleep for remaining time to maintain FPS processing_time = time.perf_counter() - frame_start perfect_sleep(frame_interval - processing_time) # Result: consistent 30 FPS without drift ``` -------------------------------- ### Send TCP Packets with Timeout (Python) Source: https://context7.com/muhammetssen/videosync/llms.txt The `send_packet` utility facilitates TCP-based network communication. It handles connection establishment, message transmission, and socket closure, including automatic timeout handling. This function can send both binary data and JSON messages. ```python from utils.send_packet import send_packet import json # Send JSON control message target_ip = "192.168.1.102" control_port = 12345 message = json.dumps({"type": "aleykumselam", "myname": "c1"}) send_packet(target_ip, control_port, message.encode('utf-8')) # Send binary video data data_port = 12346 with open('temp/video.mp4', 'rb') as f: video_bytes = f.read() send_packet(target_ip, data_port, video_bytes, timeout=10) # Sends entire video file in one TCP transmission # Error handling is automatic send_packet("192.168.1.999", control_port, b"test") # Output: Connection refused [Errno 113] No route to host 192.168.1.999 ``` -------------------------------- ### Invertible Dictionary Data Structure Source: https://context7.com/muhammetssen/videosync/llms.txt The `InvertibleDict` class implements a bidirectional mapping, allowing lookups using either keys or values via the `inv` property. It enforces that mappings are invertible and prevents duplicate values from being mapped by different keys. ```python from utils.invertible_dict import InvertibleDict # Create bidirectional mapping of IPs to client names connections = InvertibleDict() connections['192.168.1.100'] = 'server' connections['192.168.1.101'] = 'c1' connections['192.168.1.102'] = 'c2' # Forward lookup: IP → name print(connections['192.168.1.101']) # Output: c1 # Reverse lookup: name → IP print(connections.inv['server']) # Output: 192.168.1.100 # Bidirectional updates connections.inv['c3'] = '192.168.1.103' print(connections['192.168.1.103']) # Output: c3 # Iteration and membership for ip in connections: print(f"{ip} → {connections[ip]}") # Output: # 192.168.1.100 → server # 192.168.1.101 → c1 # 192.168.1.102 → c2 # 192.168.1.103 → c3 print('server' in connections.inv) # Output: True # Non-invertible mapping prevention try: connections['192.168.1.104'] = 'c1' # 'c1' already mapped to .101 except ValueError as e: print(e) # Output: non-invertible: 192.168.1.101, 192.168.1.104 both map to: c1 # Clear all mappings connections.clear() print(len(connections)) # Output: 0 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.