File size: 7,828 Bytes
54b22e0
 
 
9c0765b
a6d1e63
54b22e0
 
 
6daf6f5
54b22e0
e98caa2
54b22e0
3a405e3
6daf6f5
 
 
54b22e0
 
3a405e3
6daf6f5
3a405e3
6daf6f5
3a405e3
3b4d4ac
6daf6f5
3a405e3
 
 
 
 
 
6daf6f5
3a405e3
6daf6f5
 
3a405e3
6daf6f5
 
 
c1ecc31
3a405e3
6daf6f5
 
c1ecc31
3a405e3
6daf6f5
 
3a405e3
 
54b22e0
 
 
6daf6f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b4d4ac
6daf6f5
3b4d4ac
6daf6f5
 
 
 
 
 
 
 
3b4d4ac
54b22e0
 
6daf6f5
 
 
c1ecc31
6daf6f5
 
 
3b4d4ac
6daf6f5
 
 
c1ecc31
6daf6f5
 
 
 
 
c1ecc31
6daf6f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1ecc31
6daf6f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b4d4ac
 
6daf6f5
 
c1ecc31
6daf6f5
 
 
 
c1ecc31
 
6daf6f5
54b22e0
 
 
 
 
 
 
 
6daf6f5
 
 
 
 
3b4d4ac
6daf6f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b4d4ac
6daf6f5
 
 
 
 
 
 
 
 
54b22e0
 
6daf6f5
 
c1ecc31
3a405e3
 
 
 
6daf6f5
bfa811a
6daf6f5
c1ecc31
 
 
6daf6f5
c1ecc31
bfa811a
54b22e0
c1ecc31
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import pygame
import time
import threading
import os
from flask import Flask, Response, render_template_string

os.environ['SDL_VIDEODRIVER'] = 'dummy'
pygame.init()
print("✅ PyGame initialized")

WIDTH, HEIGHT = 400, 300
shared = {
    "streaming": True,
    "x": 200,
    "y": 150,
    "frame_count": 0
}

def game_loop():
    """Generate frames continuously"""
    screen = pygame.Surface((WIDTH, HEIGHT))
    x, speed = 200, 5
    
    while shared["streaming"]:
        start_time = time.time()
        
        # Update position
        x += speed
        if x < 30 or x > WIDTH-30:
            speed *= -1
        
        # Draw frame
        screen.fill((25, 25, 45))
        pygame.draw.circle(screen, (255, 80, 80), (int(x), int(shared["y"])), 20)
        pygame.draw.circle(screen, (255, 255, 255), (int(x), int(shared["y"])), 20, 2)
        
        # Store latest frame as RGB bytes
        shared["current_frame"] = pygame.image.tostring(screen, 'RGB')
        shared["x"] = x
        shared["frame_count"] += 1
        
        # Log every 30 frames
        if shared["frame_count"] % 30 == 0:
            print(f"Frame {shared['frame_count']}: X={x}")
        
        # Maintain 30 FPS
        elapsed = time.time() - start_time
        if elapsed < 1.0/30:
            time.sleep(1.0/30 - elapsed)

app = Flask(__name__)

HTML = '''<!DOCTYPE html>
<html>
<head>
    <style>
        body { 
            background: #0f172a; 
            color: white; 
            text-align: center; 
            padding: 20px;
            font-family: monospace;
            margin: 0;
            overflow: hidden;
        }
        canvas { 
            border: 3px solid #60a5fa; 
            image-rendering: pixelated;
            background: black;
        }
        .stats {
            background: #1e293b;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            display: inline-block;
        }
    </style>
</head>
<body>
    <h1>🎮 Binary Stream</h1>
    
    <canvas id="canvas" width="400" height="300"></canvas>
    
    <div class="stats">
        Frame: <span id="counter">0</span> | 
        Position: X=<span id="pos">200</span> |
        FPS: <span id="fps">0</span>
    </div>
    
    <div style="margin-top: 10px; color: #94a3b8;">
        Streaming raw RGB data • 30 FPS • No caching
    </div>
    
    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        
        let frameCounter = 0;
        let fpsCounter = 0;
        let lastFpsUpdate = Date.now();
        let connectionActive = false;
        
        // Connect to binary stream
        function connectStream() {
            const eventSource = new EventSource('/stream');
            
            eventSource.onopen = () => {
                console.log('✅ Connected to stream');
                connectionActive = true;
                document.title = '🎮 Stream • Connected';
            };
            
            eventSource.onmessage = (event) => {
                if (!connectionActive) return;
                
                try {
                    // Parse the binary frame data
                    const data = JSON.parse(event.data);
                    
                    // Convert base64 to binary
                    const binaryString = atob(data.frame);
                    const bytes = new Uint8Array(binaryString.length);
                    for (let i = 0; i < binaryString.length; i++) {
                        bytes[i] = binaryString.charCodeAt(i);
                    }
                    
                    // Create ImageData from RGB bytes
                    const imageData = new ImageData(400, 300);
                    for (let i = 0; i < bytes.length; i++) {
                        imageData.data[i] = bytes[i];
                    }
                    
                    // Draw to canvas
                    ctx.putImageData(imageData, 0, 0);
                    
                    // Update stats
                    frameCounter++;
                    fpsCounter++;
                    document.getElementById('counter').textContent = data.frame_count;
                    document.getElementById('pos').textContent = data.x;
                    
                    // Calculate FPS
                    const now = Date.now();
                    if (now - lastFpsUpdate >= 1000) {
                        const fps = fpsCounter / ((now - lastFpsUpdate) / 1000);
                        document.getElementById('fps').textContent = fps.toFixed(1);
                        fpsCounter = 0;
                        lastFpsUpdate = now;
                    }
                    
                } catch (err) {
                    console.error('Frame error:', err);
                }
            };
            
            eventSource.onerror = (err) => {
                console.log('❌ Stream error, reconnecting...');
                connectionActive = false;
                document.title = '🎮 Stream • Reconnecting...';
                eventSource.close();
                
                // Show error on canvas
                ctx.fillStyle = '#5c1a1a';
                ctx.fillRect(0, 0, 400, 300);
                ctx.fillStyle = 'white';
                ctx.font = '20px monospace';
                ctx.fillText('Reconnecting...', 120, 150);
                
                // Reconnect after 1 second
                setTimeout(connectStream, 1000);
            };
            
            return eventSource;
        }
        
        // Start connection
        let streamConnection = connectStream();
        
        // Manual reconnect button (optional)
        window.reconnect = function() {
            if (streamConnection) streamConnection.close();
            streamConnection = connectStream();
        };
        
        console.log('Binary stream client started');
    </script>
</body>
</html>'''

@app.route('/')
def index():
    return render_template_string(HTML)

@app.route('/stream')
def stream():
    """Server-Sent Events stream with base64 encoded frames"""
    import json
    import base64
    
    def generate():
        last_sent = 0
        while shared.get("streaming", True):
            # Only send if frame has updated
            if shared.get("frame_count", 0) > last_sent and "current_frame" in shared:
                frame_data = {
                    'frame': base64.b64encode(shared["current_frame"]).decode('utf-8'),
                    'frame_count': shared["frame_count"],
                    'x': shared["x"],
                    'timestamp': time.time()
                }
                yield f"data: {json.dumps(frame_data)}\n\n"
                last_sent = shared["frame_count"]
            
            # Check for updates 30 times per second
            time.sleep(1.0/30)
    
    return Response(
        generate(),
        mimetype='text/event-stream',
        headers={
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'X-Accel-Buffering': 'no'
        }
    )

if __name__ == "__main__":
    print("🚀 Starting binary stream server...")
    print("Expecting 30 FPS updates via SSE")
    
    # Create initial frame
    screen = pygame.Surface((WIDTH, HEIGHT))
    screen.fill((25, 25, 45))
    pygame.draw.circle(screen, (255, 80, 80), (200, 150), 20)
    shared["current_frame"] = pygame.image.tostring(screen, 'RGB')
    
    # Start game thread
    thread = threading.Thread(target=game_loop, daemon=True)
    thread.start()
    
    # Give it a moment
    time.sleep(0.5)
    
    # Start server
    app.run(
        host='0.0.0.0', 
        port=int(os.environ.get('PORT', 7860)), 
        debug=False, 
        threaded=True
    )