ScreenSync MCP guide

High-Speed 15 FPS Screen Mirroring: Building Real-Time MJPEG Streaming Pipelines for Mobile AI Vision

Learn how to build a high-speed 15 FPS MJPEG screen streaming pipeline for mobile AI vision. Complete engineering guide covering MediaProjection, multipart boundaries, and zero-latency agent loops.

A developer working on mobile screen mirroring with a laptop and smartphone on a sunlit outdoor cafe terrace.

Yes, achieving real-time 10 to 15 frames per second (FPS) screen mirroring for autonomous mobile AI vision is fully practical today using a continuous Motion JPEG (MJPEG) multipart streaming pipeline. By shifting from legacy static screenshot polling to an optimized binary HTTP stream powered by Android's native MediaProjection API and Node.js stream compositors, multi-modal AI agents like Claude Desktop, Claude Code, and GPT-4o vision can perceive mobile animations, page transitions, and dynamic touch responses in near real-time with sub-100 millisecond latency.

This comprehensive architectural guide explains how the ScreenSync MCP live streaming engine eliminates frame stutter, avoids garbage collection memory leaks, and delivers seamless continuous visual telemetry to autonomous AI agent workflows.


Key Takeaways

  • From Static Polling to Continuous Streams: Replaces high-overhead Base64 JSON polling (0.5 FPS) with an RFC 2046 compliant multipart MJPEG stream (/api/screens/stream.mjpg) delivering 10 to 15 FPS.
  • Hardware-Accelerated Display Capture: Uses Android's MediaProjectionManager and VirtualDisplay to stream compressed JPEG surfaces directly from GPU frame buffers.
  • Sub-100 ms Local Latency: Bypasses external cloud relays, transmitting raw visual frames directly over the local Wi-Fi subnet with a median transmission latency of ~84 ms.
  • Zero-Copy Memory Hygiene: Implements ring-buffer frame dropping policies on the Node.js desktop hub to prevent backpressure stalls and socket buffer bloat during heavy AI inference.
  • Multi-Modal Agent Integration: Bridges continuous visual streams into Model Context Protocol (MCP) clients, enabling tools like get_latest_screenshot to serve instant pre-cached frames in 12 ms.
  • Universal Android Compatibility: Functions across physical hardware devices running Android 7.0 (Nougat) through Android 15 without requiring root access or ADB debugging.

What It Is and Why It Matters

The Fundamental Flaw of Static Screenshot Polling

The standard approach to giving an AI agent "eyes" on a mobile device has historically relied on discrete screenshot capture. When an AI agent decides it needs to inspect the phone's state, it invokes a tool such as take_screenshot. Behind the scenes, the testing framework initiates a synchronous capture request:

  1. The host invokes an ADB command: adb exec-out screencap -p > screen.png.
  2. The phone halts screen compositing, encodes the display surface into uncompressed PNG bytes, and transmits the payload across USB or wireless ADB.
  3. The host tool parses the binary stream, converts it into a Base64 string, and injects it into the LLM context window.

This request-response paradigm introduces severe operational friction. An uncompressed 1080x2400 PNG file typically spans 2.5 to 4.5 megabytes. Encoding and transmitting this payload over ADB takes between 1.2 and 3.5 seconds. If an AI agent attempts to monitor a smooth scroll, a screen transition, or a loading progress bar, it is effectively blind between captures. Capturing just one frame every two seconds produces severe "temporal blindness"—the agent cannot verify if a button clicked, whether an intermediate animation stuttered, or if an ephemeral error toast flashed and vanished.

The Rise of Multi-Modal Video-Rate Perception

Modern multi-modal frontier models (such as Anthropic Claude 3.5 Sonnet, Google Gemini 1.5 Pro, and OpenAI GPT-4o) possess vision encoders capable of processing continuous visual sequences. When provided with a consistent visual feed, these models can:

  • Detect UI layout shifts and frame drops during navigation transitions.
  • Validate that micro-interactions (e.g., button ripples, skeleton loaders, pull-to-refresh spinners) render correctly.
  • Identify transient state anomalies, such as validation snackbars that dismiss after 1,500 milliseconds.
  • Verify video playback, animated banners, and complex canvas rendering.

To empower multi-modal agents with this level of scrutiny, the underlying capture pipeline must transition from discrete request-driven snapshots to continuous, push-driven video streaming.

Why MJPEG Over WebRTC for Local AI Hubs

When engineering a real-time streaming pipeline, developers typically evaluate three protocols: H.264/H.265 via WebRTC, raw binary WebSocket streams, and Motion JPEG over HTTP multipart.

While WebRTC offers high compression efficiency for WAN connections, it introduces substantial architectural overhead for local machine automation:

  • ICE Candidate Exchange & STUN/TURN: Requires complex signaling servers and SDP negotiation handshakes that complicate local CLI environments.
  • Codec Licensing & Transcoding: Decoding H.264 video inside a lightweight Node.js MCP hub requires native binary bindings (e.g., ffmpeg or webrtc-native), increasing package footprint and cross-platform installation failure rates.
  • Keyframe Latency (GOP Intervals): When an AI agent requests an immediate frame capture at arbitrary timestamp $T$, an H.264 stream requires decoding preceding I-frames and P-frames, introducing seek latency.

Motion JPEG (MJPEG) over HTTP multipart strikes the optimal balance for local AI automation:

  • Every frame is an independent, self-contained JPEG keyframe. The desktop hub or AI vision client can extract any frame instantaneously without decoding historical frames.
  • Standard HTTP multipart/x-mixed-replace is natively supported by all browsers, image decoders, and HTTP libraries without external dependencies.
  • CPU encoding overhead on mobile hardware is minimal when offloaded to Android's hardware JPEG compressor.

Architectural Comparison Matrix

Streaming Architecture Target Frame Rate Transmission Latency Bandwidth (1080p) Host CPU Overhead Client Complexity
ScreenSync MJPEG (v2.5+) 10 - 15 FPS ~84 ms 1.2 - 2.8 Mbps < 2.5% (Node.js Stream) Universal HTTP / MCP
Legacy ADB screencap 0.3 - 0.7 FPS 1,800 - 3,200 ms Burst (35 Mbps peak) High (Process forking) Low (CLI command)
WebRTC H.264 30 - 60 FPS 45 - 80 ms 1.5 - 4.0 Mbps High (Hardware Transcode) High (SDP / ICE negotiation)
Scrcpy Video Mirror 30 - 60 FPS 35 - 70 ms 4.0 - 8.0 Mbps Moderate (C++ Native) Moderate (Requires desktop UI)
WebSocket Base64 2 - 4 FPS 350 - 650 ms 6.0 - 12.0 Mbps Moderate (String parsing) Moderate (Custom binary parser)

How It Works: Pipeline Engineering Deep Dive

High-Throughput Stream Topology

The ScreenSync MCP high-speed streaming architecture connects Android's MediaProjection graphics subsystem to the Node.js MCP Hub over an authenticated local socket:

+-----------------------------------------------------------------------------------------+
|                                ANDROID SYSTEM COMPOSITOR                                |
|                                                                                         |
|   +-----------------------+     Hardware Surface      +------------------------------+  |
|   |   Android SurfaceFlinger| ----------------------> |   VirtualDisplay             |  |
|   |   (GPU FrameBuffer)   |                           |   (MediaProjection Session)  |  |
|   +-----------------------+                           +--------------|---------------+  |
|                                                                      |                  |
|                                                     Surface Frames   | YUV420 / RGBA    |
|                                                                      v                  |
|   +---------------------------------------------------------------------------------+   |
|   |   ScreenSync Android Core Engine (Flutter / Kotlin)                             |   |
|   |   * ImageReader listener receives hardware frame buffers                        |   |
|   |   * Hardware JPEG compressor downsamples & compresses frame (Quality: 65%)      |   |
|   |   * Dynamic throttling loop clamps cadence to 66 ms (15 FPS target)             |   |
|   |   * Streaming binary HTTP POST /chunk socket to desktop Hub                     |   |
|   +------------------------------------------------------------------|--------------+   |
+----------------------------------------------------------------------|------------------+
                                                                       | Local Wi-Fi Subnet
                                                      Raw Binary JPEGs | (HTTP Keep-Alive)
                                                                       v
+-----------------------------------------------------------------------------------------+
|                                DESKTOP MCP HUB (Node.js 18+)                            |
|                                                                                         |
|   +---------------------------------------------------------------------------------+   |
|   |   Hub Phone Bridge (hub-phone-bridge.ts)                                        |   |
|   |   * Ingests incoming binary JPEG chunks                                         |   |
|   |   * Updates atomic L1 in-memory latestFrameBuffer (12 ms cache retrieval)       |   |
|   |   * Fan-out router dispatches to active MJPEG socket subscribers                |   |
|   |   * Backpressure Drop Policy: Discards frames for slow consumers                |   |
|   +------------------------------------------------------------------|--------------+   |
|                                                                      |                  |
|                                     multipart/x-mixed-replace        | stdio JSON-RPC   |
|                                     HTTP Stream                      | Base64 Frame     |
|                                     v                                v                  |
|   +---------------------------------------+       +---------------------------------+   |
|   |   Live Web Viewer / Monitor Dashboard |       |   Claude Desktop / Claude Code  |   |
|   |   http://localhost:3000/stream.mjpg   |       |   (get_latest_screenshot)      |   |
|   +---------------------------------------+       +---------------------------------+   |
+-----------------------------------------------------------------------------------------+

1. Android MediaProjection & Surface Capture

In Android, the MediaProjection API captures screen contents by projecting the system display onto a virtual target surface. In Kotlin, ScreenSync MCP initializes an ImageReader configured with a private ImageFormat:

package com.screensync.mcp

import android.content.Context
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.ImageReader
import android.media.projection.MediaProjection
import java.io.ByteArrayOutputStream

class ScreenCaptureEngine(
    private val mediaProjection: MediaProjection,
    private val width: Int,
    private val height: Int,
    private val densityDpi: Int
) {
    private var imageReader: ImageReader? = null
    private var virtualDisplay: VirtualDisplay? = null
    private var isStreaming = false

    fun startStreaming(onFrameReady: (ByteArray) -> Unit) {
        // Allocate an ImageReader with maxImages = 2 to prevent buffer starvation
        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)

        virtualDisplay = mediaProjection.createVirtualDisplay(
            "ScreenSyncStream",
            width,
            height,
            densityDpi,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader!!.surface,
            null,
            null
        )

        isStreaming = true

        imageReader!!.setOnImageAvailableListener({ reader ->
            val image = reader.acquireLatestImage() ?: return@setOnImageAvailableListener
            try {
                val planes = image.planes
                val buffer = planes[0].buffer
                val pixelStride = planes[0].pixelStride
                val rowStride = planes[0].rowStride
                val rowPadding = rowStride - pixelStride * width

                val bitmap = Bitmap.createBitmap(
                    width + rowPadding / pixelStride,
                    height,
                    Bitmap.Config.ARGB_8888
                )
                bitmap.copyPixelsFromBuffer(buffer)

                // Crop out row padding to preserve accurate aspect ratio
                val cropped = if (rowPadding > 0) {
                    Bitmap.createBitmap(bitmap, 0, 0, width, height)
                } else {
                    bitmap
                }

                // Compress to JPEG with 65% quality for optimal bandwidth/fidelity ratio
                val outStream = ByteArrayOutputStream()
                cropped.compress(Bitmap.CompressFormat.JPEG, 65, outStream)
                val jpegBytes = outStream.toByteArray()

                onFrameReady(jpegBytes)

                if (cropped !== bitmap) cropped.recycle()
                bitmap.recycle()
            } finally {
                image.close()
            }
        }, null)
    }

    fun stopStreaming() {
        isStreaming = false
        virtualDisplay?.release()
        imageReader?.close()
    }
}

Notice the critical buffer safety rules:

  1. maxImages = 2: Android's hardware surface compositor operates on a double-buffered queue. Allocating more than 2 frames causes memory bloat; allocating 1 frame causes frame drops if processing takes longer than a single vertical sync (VSYNC) pulse.
  2. acquireLatestImage(): If the network socket is temporarily congested, acquireLatestImage() automatically drops intermediate frames and acquires only the most current frame, ensuring latency never accumulates.
  3. image.close(): Failing to invoke image.close() within the finally block locks the graphics pipe, freezing display capture completely.

2. Node.js Multipart MJPEG Ingestion and Fan-Out

On the desktop host workstation, the ScreenSync MCP Hub (hub-phone-bridge.ts) implements an HTTP multipart streaming endpoint adhering to RFC 2046:

import { Request, Response } from 'express';
import EventEmitter from 'events';

class MjpegStreamHub extends EventEmitter {
  private activeSubscribers: Set<Response> = new Set();
  private latestFrame: Buffer | null = null;
  private lastFrameTimestamp: number = 0;

  public handleStreamRequest(req: Request, res: Response): void {
    // Set headers for multipart MIME stream
    res.writeHead(200, {
      'Content-Type': 'multipart/x-mixed-replace; boundary=frame',
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Connection': 'keep-alive',
      'Pragma': 'no-cache',
      'Expires': '0',
    });

    this.activeSubscribers.add(res);

    // If we have an existing cached frame, transmit immediately
    if (this.latestFrame) {
      this.writeFrame(res, this.latestFrame);
    }

    // Clean up when client disconnects
    const cleanup = () => {
      this.activeSubscribers.delete(res);
      res.end();
    };

    req.on('close', cleanup);
    req.on('end', cleanup);
    res.on('error', cleanup);
  }

  public pushNewFrame(jpegBuffer: Buffer): void {
    this.latestFrame = jpegBuffer;
    this.lastFrameTimestamp = Date.now();

    for (const client of this.activeSubscribers) {
      // Backpressure check: If the socket buffer is backed up, skip this frame
      if (client.writableNeedDrain) {
        continue;
      }
      this.writeFrame(client, jpegBuffer);
    }
  }

  private writeFrame(res: Response, buffer: Buffer): void {
    try {
      res.write(`--frame
`);
      res.write(`Content-Type: image/jpeg
`);
      res.write(`Content-Length: ${buffer.length}

`);
      res.write(buffer);
      res.write(`
`);
    } catch (err) {
      this.activeSubscribers.delete(res);
    }
  }

  public getLatestFrame(): { buffer: Buffer; timestamp: number } | null {
    if (!this.latestFrame) return null;
    return { buffer: this.latestFrame, timestamp: this.lastFrameTimestamp };
  }
}

export const mjpegHub = new MjpegStreamHub();

The multipart formatting string `--frame
Content-Type: image/jpeg
Content-Length: ...

` tells client software (whether a Chrome browser tab, VLC, Python OpenCV, or an MCP agent) that a new self-contained JPEG frame has arrived. Because each frame boundary replaces the previous frame in the rendering context, memory consumption remains constant regardless of how long the stream runs.


Step-by-Step Production Setup Guide

1. Configuring Real-Time Streaming on Android

  1. Download and launch ScreenSync MCP from Google Play.
  2. On the main home view, navigate to Settings > Mirror Quality.
  3. Set Frame Rate Target to 15 FPS (or Dynamic Auto).
  4. Set Compression Quality to 65% (optimal balance between text sharpness and bandwidth).
  5. Grant the MediaProjection system consent prompt: "Start recording or casting with ScreenSync MCP?". Check "Don't ask again" if supported by your OEM firmware.

2. Verifying the Local Stream

Once connected to the desktop hub, you can verify the live video stream directly in any web browser without starting an AI agent:

  1. Open your browser and navigate to: http://localhost:3000/api/screens/stream.mjpg
  2. You should observe a fluid, real-time mirror of your phone display updating at 15 FPS.
  3. Move your finger across the physical screen; the browser mirror reflects the motion with zero perceptible delay (< 90 ms).

3. Integrating with AI Agents (Claude Desktop & Claude Code)

When multi-modal AI agents connect via MCP, they do not need to pull the full 15 FPS video stream over stdio (which would overflow LLM token limits). Instead, they invoke get_latest_screenshot:

{
  "name": "get_latest_screenshot",
  "arguments": {}
}

Because the hub continuously ingests the 15 FPS MJPEG stream in the background, get_latest_screenshot never has to wait for a round-trip capture handshake. It instantly reads the in-memory latestFrame buffer and returns the image in 12 milliseconds.


Real-World Production Test Scenarios

Scenario 1: Monitoring a Multi-Step Mobile Onboarding Carousel

In this scenario, an AI QA agent tests an onboarding carousel that features fluid swipe animations, animated transition banners, and page dots.

User Prompt:

"Swipe through all 3 onboarding slides on the mobile app. Verify that the transition animation completes smoothly, the page indicator updates from dot 1 to dot 3, and the 'Get Started' button appears on the final slide."

Execution Trace:

  1. Initial Frame Check: Agent calls get_latest_screenshot. The hub returns the current cached frame in 14 ms.
  2. First Swipe: Agent invokes control_swipe with parameters startX: 850, startY: 1200, endX: 150, endY: 1200, durationMs: 250.
  3. Mid-Transition Telemetry: The agent captures an intermediate frame after 300 ms. Because of the 15 FPS pipeline, the captured frame catches the exact state of the carousel midway through its deceleration curve.
  4. Final Assertion: The agent captures the final frame, verifies the "Get Started" button text via multi-modal vision, and confirms the test passed.
{
  "name": "control_swipe",
  "arguments": {
    "startX": 850,
    "startY": 1200,
    "endX": 150,
    "endY": 1200,
    "durationMs": 250
  }
}
{
  "name": "get_latest_screenshot",
  "arguments": {}
}

Empirical Network & Thermal Benchmarks

Our engineering team conducted rigorous 8-hour continuous streaming benchmarks across three hardware tiers:

  • Tier 1 (Flagship): Google Pixel 8 Pro (Tensor G3, 12GB RAM, Android 14)
  • Tier 2 (Mid-Range): Samsung Galaxy A54 (Exynos 1380, 8GB RAM, Android 14)
  • Tier 3 (Budget): Motorola Moto G Stylus (Snapdragon 6 Gen 1, 6GB RAM, Android 13)

Streaming Benchmark Results (8-Hour Continuous Run)

Performance Metric Google Pixel 8 Pro Samsung Galaxy A54 Moto G Stylus
Achieved Frame Rate 14.8 FPS 13.6 FPS 11.2 FPS
Median Network Latency 78 ms 92 ms 114 ms
Bandwidth Consumption 1.85 Mbps 1.72 Mbps 1.45 Mbps
Device Battery Drain 6.2% / hour 7.4% / hour 8.1% / hour
Temperature Rise (ΔT) +2.1°C +3.4°C +3.8°C
Frame Loss Rate 0.02% 0.14% 0.38%

The benchmark confirms that hardware-accelerated JPEG compression and lightweight multipart streaming impose negligible thermal impact, enabling unattended multi-hour automated test runs without device throttling or thermal shutdowns.


Failure Modes, Edge Cases & Troubleshooting

1. Wi-Fi Power Save Mode Causing Frame Jitter

On certain Android handsets, the Wi-Fi chipset automatically enters Power Save Polling (PSP) mode when high-bandwidth data transfers pause briefly. This introduces sudden 200 ms latency spikes between frames.

  • Resolution: In the ScreenSync mobile app, ensure High Performance Wi-Fi Lock (WifiManager.WIFI_MODE_FULL_HIGH_PERF) is enabled in Settings. This keeps the Wi-Fi MAC layer active at low power.

2. Backpressure Memory Accumulation on Slow Hosts

If an AI agent host machine is heavily constrained by concurrent local LLM inference, it may fail to read socket buffers fast enough.

  • Resolution: The ScreenSync desktop hub checks res.writableNeedDrain before writing each frame. If a client's TCP send window is full, the frame is discarded immediately. This ensures the hub's RAM usage remains strictly capped under 45 MB regardless of client congestion.

3. Blank Screen on Secure Windows

When an application displays views with FLAG_SECURE (such as password inputs or banking dashboards), Android's hardware compositor intentionally replaces the surface output with solid black pixels.

  • Resolution: Combine visual streaming with get_ui_hierarchy. Even when visual frames are blacked out by OS security, structural view attributes remain fully inspectable for authorized accessibility services.

Frequently Asked Questions

What network bandwidth does 15 FPS screen streaming require?

At 1080x2400 resolution with 65% JPEG quality, the stream consumes between 1.2 and 2.8 megabits per second (Mbps). On standard local 5 GHz Wi-Fi networks (which provide 300+ Mbps throughput), this represents less than 1% of available local bandwidth.

Does ScreenSync MCP transmit video frames to external cloud servers?

No. All video streaming operates strictly over your local area network (LAN) directly between your physical Android handset and your local desktop hub. No video data or screenshot frames are ever routed through EpsolDev cloud infrastructure.

Can I record the stream to an MP4 video file during automated test runs?

Yes. The ScreenSync MCP desktop hub includes a built-in record_screen tool that packages the incoming frame stream into standardized MP4 recordings with timestamp overlays for test reporting.

How does this compare to Scrcpy?

Scrcpy is an exceptional display mirroring tool designed primarily for human visual inspection via a desktop GUI window. ScreenSync MCP is purpose-built for autonomous AI agents, exposing continuous video streams, atomic L1 frame buffers, and Model Context Protocol tool contracts over stdio and HTTP.

Does 15 FPS streaming work on older Android versions?

Yes. ScreenSync MCP supports all physical devices and emulators running Android 7.0 (API Level 24) or higher, covering over 96% of active Android devices worldwide.


Conclusion & Strategic Roadmap

Transitioning from sluggish static screenshot polling to high-speed 15 FPS MJPEG streaming unlocks a new frontier for autonomous mobile AI agents. By providing multi-modal models with a fluid, continuous visual telemetry feed at sub-100 millisecond latency, engineering teams can automate complex visual QA, verify fluid UI animations, and catch fleeting transient bugs with unprecedented accuracy.

Explore the complete open-source documentation at www.screensyncmcp.tech or download the ScreenSync MCP mobile application directly from the Google Play Store. For technical support and enterprise integration runbooks, contact [email protected].

FAQ

Questions, answered

What network bandwidth does 15 FPS screen streaming require?

At 1080p resolution with 65% JPEG quality, the stream consumes between 1.2 and 2.8 Mbps over your local network.

Does ScreenSync MCP transmit video frames to external cloud servers?

No. All video streaming operates strictly over your local area network directly between your physical handset and your local desktop hub.

Can I record the stream to an MP4 video file during automated test runs?

Yes. ScreenSync MCP includes a record_screen tool that captures the incoming frame stream into standardized MP4 recordings.

How does this compare to Scrcpy?

While Scrcpy is built for human desktop viewing, ScreenSync MCP is purpose-built for AI agents with native Model Context Protocol tool bindings.

Does 15 FPS streaming work on older Android versions?

Yes. ScreenSync MCP supports all physical devices running Android 7.0 (API Level 24) or higher.

Written by

ScreenSync MCP team

The ScreenSync MCP team at EpsolDev builds the Android app, the desktop MCP hub and the browser extension that let AI agents see and control a real phone. These guides come out of that work.