atv-core README

The project's README from github.com/corvofeng/atv-core. As one markdown file: README.md.

Fake Apple TV (atv-core) 📺

English Version | 中文版本

High-performance Rust implementation of the Apple TV Companion Link and MediaRemote (MRP) protocols. Discover, pair, and control targets directly using the native Apple TV Remote widget in iOS / iPadOS Control Center without jailbreak or dedicated hardware:

  1. macOS (Mac mini / MacBook / iMac):
    • Native Swift menu bar app (AppleTVRemote.app) and cross-platform CLI.
    • Ultra-smooth adaptive dynamic acceleration mouse cursor and D-pad dual-mode seamless switching, with native hardware media key and volume control integration.
    • Built-in Web Inspector and Swift Host Diagnostics dashboards, delivering real-time visualization of touchpad gestures, hardware volume levels, and millisecond-level protocol events.
  2. Android TV / Google TV / TV Boxes / Emulators:
    • Native Standalone APK: Driven by JNI + embedded ADB (dadb) + Android Accessibility Service (AtvAccessibilityService), auto-starts on boot with independent mDNS broadcasting.
    • Remote Network ADB Mode: Run the daemon on a Mac mini or PC, forwarding remote keys and swipes over TCP ADB in real time.

Table of Contents


I. Live Interfaces & Real-World Showcase

1. macOS & iOS Interactive Interfaces

① iOS Remote Directly Controlling macOS

No third-party iOS app required. Simply pull down the iOS Control Center and tap the native Apple TV Remote icon to immediately discover the host Mac (as shown below, connected directly to Yuhao's MacBook (2)):

Native iOS Apple TV Remote Connected to Mac

② macOS Web Inspector (Port 8765)

When running the daemon or menu bar app on macOS, visit http://127.0.0.1:8765 in your browser to open the interactive inspection console (captured live with active finger swipe vectors and event logs):

macOS Browser Web Inspector UI


③ macOS Swift Host Diagnostics & Runtime Logs (Port 8766)

Navigate to http://127.0.0.1:8766 to inspect the Swift host process health, active port bindings, and live protocol handshakes:

macOS Swift Host Diagnostics


④ macOS Native Menu Bar App & Key Features

Running AppleTVRemote.app places a lightweight native Swift icon in the macOS menu bar, consuming as little as 18MB of RAM:


2. Android TV Interfaces & Remote Navigation

① Control Dashboard & Configuration Dialogs

Launch the app on Android TV to monitor driver status and customize key bindings:

Main Dashboard Input Injection Mode Menu Key Binding
Main Dashboard Injection Mode Menu Key Binding

② Android TV Launcher Gesture & Focus Movement

Swiping on the iPhone touchpad smoothly shifts the TV focus highlight across the UI grid:

[Top Navigation Tabs (For you / Apps)]
              ↕ (Swipe Down)
[Featured Hero Banner Focus]
              ↕ (Swipe Down)
[Application Row (YouTube / VLC / Settings)]
1. Top Navigation Focus 2. Hero Banner Focus 3. App Card Row Focus
Top Navigation Hero Focus App Row Focus

II. Prerequisites & Permissions Checklist (Essential)

Review the following system requirements before initial launch:

Prerequisites & Permissions Guide

1. macOS Prerequisites & Gatekeeper Clearance

① Gatekeeper & Self-Signed Certificate

Release builds are signed with a dedicated developer certificate (Corvo Development). On macOS, Gatekeeper may flag untrusted apps:

② Accessibility Permission

Simulating keyboard strokes and smooth mouse cursor movements requires macOS Accessibility permissions:

  1. Navigate to System Settings -> Privacy & Security -> Accessibility.
  2. Enable AppleTVRemote (or your terminal application like Terminal / iTerm if running via CLI).

2. Android TV Prerequisites & Critical Permissions

① Enable Network ADB & USB Debugging

② Accept ADB RSA Fingerprint Authorization

When the app initializes the local Dadb connection, an Android system security prompt will appear:

⚠️ CRITICAL: Using your physical TV remote, check "Always allow from this computer" and click "Allow / OK". Rejecting this prompt will cause Unauthorized connection errors and prevent remote input.

③ Enable Accessibility Service

Step 1: Accessibility List Step 2: Confirmation Dialog Step 3: Service Ready
Service List Permission Dialog Ready Status

3. LAN & Network Pairing Requirements

  1. Same Wi-Fi Subnet: The iPhone and TV / Mac must share the same local router subnet (2.4G and 5G bands are compatible).
  2. Disable AP Isolation: Commercial routers with "AP Isolation" or "Guest Mode" block UDP 5353 Bonjour multicast packets. Ensure client-to-client communication is permitted.
  3. Initial Pairing PIN: When connecting from the iPhone Control Center, enter the default PIN 1111 to complete the SRP cryptographic handshake.

III. Quick Start & Operational Guides

1. Running on macOS

# Build standalone DMG package
./scripts/build_dmg.sh

Mount build/AppleTVRemote-arm64.dmg and drag the application to /Applications. Launch the app and access controls via the menu bar icon.


2. Running on Android TV

# Build and install APK
./scripts/build_android.sh
adb install -r android-tv/app/build/outputs/apk/debug/app-debug.apk

# Launch app
adb shell am start -n com.corvofeng.fakeatv/.MainActivity

3. Android Emulator Bridge Setup

For testing inside Android Studio's Android TV Virtual Devices (AVD):

Step 1: Launch Emulator

Start an Android TV AVD (API 30+ recommended). Run adb devices to verify emulator-5554 is online.

Step 2: Install and Launch Receiver

./scripts/build_android.sh
adb -s emulator-5554 install -r android-tv/app/build/outputs/apk/debug/app-debug.apk
adb -s emulator-5554 shell am start -n com.corvofeng.fakeatv/.MainActivity

Step 3: Start Bridge Daemon

# Start background daemon
python3 scripts/bridge_emulator.py start

# Or run foreground with live logs
python3 scripts/bridge_emulator.py start -f

Step 4: Pair from iPhone

  1. Connect iPhone to the same Wi-Fi as your Mac.
  2. Open iOS Control Center -> Apple TV Remote.
  3. Select Android TV Emulator.
  4. Enter default PIN 1111 to start controlling the emulator!

IV. Implementation Principles & Architecture

1. Touchpad Gestures & Focus Accumulation Algorithm

When swiping on the iPhone touchpad, the Companion Link protocol streams high-frequency differential delta coordinates. atv-core converts these inputs into smooth grid focus shifts on Android TV and ergonomic cursor acceleration on macOS:

Remote Swipe & Navigation Flow

  1. Delta Accumulator: Aggregates continuous micro-displacements to prevent jitter and accidental touches.
  2. Direction Deadzone & Thresholds: Determines primary intent (horizontal vs. vertical) while filtering diagonal noise.
  3. Platform Dispatch:
    • Android TV: Emits KEYCODE_DPAD_UP/DOWN/LEFT/RIGHT focus events.
    • macOS: Computes velocity-based ballistics curves and emits smooth cursor motion via CGEvent.

2. Emulator Bridge Architecture & mDNS Topology

Because the Android emulator runs within an isolated host NAT subnet (fixed virtual IP 10.0.2.15), local physical devices cannot discover it directly:

Emulator Bridge Workflow

  1. ADB Port Forwarding: Ports 49152, 49153, and 49154 are forwarded directly into the emulator guest OS via adb forward.
  2. mDNS Host Proxy: The host proxies Bonjour records (_mediaremotetv._tcp and _companion-link._tcp) onto the physical Wi-Fi network.
  3. Transparent Connection: The iPhone connects directly to the host's LAN IP, seamlessly routed to the emulator.

3. Driver Dispatch Hierarchy & Security Sandboxing

atv-core uses a layered driver strategy to ensure lowest possible latency and dependable fallback:

Driver Hierarchy & Permissions


V. Key & Gesture Mapping Reference

Apple TV Remote Action Android TV (Device / Emulator) macOS (Mac mini / MacBook)
Touch Surface Swipe (D-pad) KEYCODE_DPAD_UP / DOWN / LEFT / RIGHT Arrow keys ↑ ↓ ← →
Touch Surface Swipe (Cursor) Touch drag / cursor simulation Smooth cursor movement via CGEvent
Tap / Click SELECT KEYCODE_DPAD_CENTER / Select Enter key / Left Mouse Click
Back Chevron (<) GLOBAL_ACTION_BACK Escape key
TV Icon (Home) GLOBAL_ACTION_HOME Desktop / Configurable shortcut
Single Click ⏯ KEYCODE_MEDIA_PLAY_PAUSE Native Play / Pause (NX_KEYTYPE_PLAY)
Double Click ⏯ Fast forward / Next episode Next Track (⏭)
Triple Click ⏯ Rewind / Previous episode Previous Track (⏮)
Volume Up / Down (+/-) KEYCODE_VOLUME_UP / DOWN Hardware master volume + native HUD
Mute (Mute) KEYCODE_VOLUME_MUTE System master mute
Side Siri Key Voice search (KEYCODE_SEARCH) Mode toggle (Mouse ⇄ D-Pad) or Siri
Power (Power) Power dialog (GLOBAL_ACTION_POWER_DIALOG) Display sleep / wake

VI. Troubleshooting & FAQ

Q1: Device does not appear in iOS Control Center?

  1. Ensure both iPhone and target device are on the exact same Wi-Fi subnet (disable router AP Isolation / Guest Mode).
  2. On macOS, run dns-sd -B _mediaremotetv._tcp to verify local Bonjour advertisement.
  3. For Android emulator, verify the bridge is running via python3 scripts/bridge_emulator.py status.

Q2: Remote keys don't respond on TV; ADB shows connection error?

  1. Open TV Developer Options and verify both "Network ADB" and "USB Debugging" are enabled.
  2. Relaunch the app and look for the system RSA key dialog on screen. Check "Always allow" and click "Allow".
  3. If no prompt appears, execute adb connect <TV_IP>:5555 from your computer to trigger initial trust.

Q3: Cannot find Accessibility settings on Android TV?

Certain customized Android TV skins hide standard accessibility menus. Click the "ACCESSIBILITY SETTINGS" dialog in the app to view terminal activation commands, or run:

adb shell settings put secure enabled_accessibility_services com.corvofeng.fakeatv/.AtvAccessibilityService
adb shell settings put secure accessibility_enabled 1

Q4: macOS reports damaged application or unidentified developer?

Strip the Gatekeeper quarantine attribute:

xattr -dr com.apple.quarantine /Applications/AppleTVRemote.app

Or import the repository self-signed certificate:

./scripts/import_certificate.sh Corvo_Development.p12

License

This project is licensed under the MIT License. Intended for educational and local device interoperability research.

atv-core (corvofeng/atv-core)

Searching Database…

Что это?atv-core — это высокопроизводительная реализация на Rust протоколов Apple TV Companion Link и MediaRemote (MRP), которая позволяет находить, сопрягать и управлять целями Apple TV через штатный виджет Apple TV Remote в Пункте управления iOS/iPadOS, без джейлбрейка и специального железа.
Это одно приложение или несколько отдельных частей?Он разделён на основную библиотеку/CLI на Rust, нативное приложение в строке меню на Swift (AppleTVRemote.app) для macOS и отдельный Android APK для Android TV/Google TV, который управляет вводом через JNI плюс встроенный ADB-клиент (dadb) и Accessibility Service.
Как запустить его на macOS и Android TV?На macOS смонтируйте build/AppleTVRemote-arm64.dmg и перетащите приложение в /Applications, затем управляйте им из строки меню; на Android TV установите отдельный APK, включите отладку ADB по сети/USB, примите запрос на встроенный RSA-отпечаток ADB и включите Accessibility Service «Apple TV Remote Receiver».
Нужно ли включать ADB и режим разработчика на ТВ?Да — на Android TV нужно включить параметры разработчика, отладку по USB и отладку по сети, а затем принять запрос на RSA-отпечаток встроенного Dadb; приложению также нужно включить собственный Accessibility Service как резервный канал ввода.
Есть ли подводные камни, о которых стоит знать перед сопряжением?macOS Gatekeeper может пометить неподписанное приложение как «повреждённое» или от неустановленного разработчика, из-за чего придётся снять атрибут карантина или импортировать самоподписанный сертификат из репозитория; кроме того, роутеры с AP Isolation или гостевым режимом блокируют обнаружение Bonjour (UDP 5353), от которого зависит сопряжение.
Нужен ли Android-приложению глубокий доступ к системе?Да, приложение для Android TV опирается на Accessibility Service, чтобы внедрять глобальные действия D-pad/Select/Back/Home, и использует локальное ADB-соединение для отправки кодов клавиш, поскольку обычные приложения не могут внедрять ввод в сторонние стриминговые приложения.
Какой PIN-код сопряжения по умолчанию?Это 1111 — вводится на iPhone во время криптографического рукопожатия SRP при первом подключении к Mac или цели Android TV.
Можно ли протестировать это без настоящей Apple TV или приставки Android TV?Да — atv-core поддерживает настройку с эмулятором Android TV: пробрасываются ADB-порты, а mDNS-записи Bonjour проксируются в локальную сеть, так что iPhone может напрямую находить эмулятор и управлять им.
Что показывают встроенные диагностические дашборды?Приложение для macOS открывает Web Inspector на порту 8765 и дашборд Swift Host Diagnostics на порту 8766, визуализируя жесты тачпада, уровни аппаратной громкости и события протокола с точностью до миллисекунд в реальном времени.
Как он превращает свайпы iPhone в навигацию по ТВ?Он накапливает высокочастотные дельта-координаты из потока касаний Companion Link, фильтрует шум с помощью мёртвой зоны по направлению, а затем отправляет события фокуса D-pad Android или движение курсора с учётом скорости через CGEvent на macOS.
Creator
corvofeng
Size
9.4 MB
Stars
380
Age
22d
Commits · 90 Days