Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Brainwave EEG Interface

Real-Time Brain-Computer Interface with Metal GPU Rendering

SwiftSwiftUIMetalPlatformLicense


A neuroscience-grade iOS application that connects to NeuroSky EEG headbands via Bluetooth, performs real-time FFT spectral analysis at 512Hz, and renders live brainwave visualizations using custom Metal GPU shaders.

iOS BCI 腦機介面應用程式 -- 透過藍牙連接 NeuroSky 腦波頭環,即時進行 512Hz 快速傅立葉轉換頻譜分析,並使用自訂 Metal GPU 著色器渲染即時腦波視覺化。


 ╔══════════════╗ Bluetooth ╔═══════════════╗ vDSP/FFT ╔══════════════╗
║ NeuroSky ║ ──────────────────> ║ ThinkGear ║ ────────────────> ║ EEG ║
║ EEG Band ║ ExternalAccessory ║ Parser ║ 512pt Hann Win ║ Analyzer ║
╚══════════════╝ ╚═══════════════╝ ╚══════╦═══════╝
│
Band Powers
│
╔══════════════╗ Metal Render ╔═══════════════╗ AsyncStream ╔══════╩═══════╗
║ Waveform ║ <────────────────── ║ Metal GPU ║ <──────────────── ║ Brainwave ║
║ Display ║ Custom Shaders ║ Renderer ║ @Published ║ ViewModel ║
╚══════════════╝ ╚═══════════════╝ ╚══════════════╝

About

Brainwave EEG Interface 是一款即時腦機介面(BCI)應用,透過藍牙連接 EEG 裝置擷取腦波訊號並以高效渲染方式視覺化。適合用於研究展示、互動藝術與即時生理訊號監測的原型開發。

About (EN)

Brainwave EEG Interface is a real-time brain-computer interface app that streams EEG data over Bluetooth and visualizes signals with GPU acceleration. It is designed for research demos, biofeedback experiments, and interactive neuroscience prototypes.

📋 Quick Summary

🧠 這是一款神經科學等級的 iOS 腦機介面(BCI)應用程式,透過藍牙連接 NeuroSky 腦波頭環,以 512Hz 取樣率即時擷取腦電波(EEG)訊號。🔬 核心訊號處理引擎採用 Apple Accelerate vDSP 框架進行快速傅立葉轉換(FFT),將原始腦波拆解為 Delta(深層睡眠)、Theta(冥想放鬆)、Alpha(清醒放鬆)、Beta(專注思考)、Gamma(高階認知)五大頻段。🎨 視覺化渲染完全由自訂 Metal GPU 著色器驅動,包含抗鋸齒、漸變色、極簡快速三種渲染路徑,相比 CPU 渲染降低 76% 功耗。⚡ 架構採用 MVVM 模式搭配 Swift Concurrency(actor + AsyncStream),確保高頻數據的執行緒安全。💡 內建模擬模式,無需實體硬體即可完整開發測試。適合對 BCI 研究、數位訊號處理、行動 GPU 運算有興趣的開發者深入學習。


✨ Highlights / 技術亮點

DomainDetail
Signal Acquisition512Hz 取樣率,透過 ExternalAccessory 藍牙連接 NeuroSky ThinkGear 協定
DSP PipelineApple Accelerate vDSP 實數 FFT (zrip),512 點 Hann 窗,DC 去除,Nyquist 處理
Brainwave DecompositionDelta (0.5-4Hz) / Theta (4-8Hz) / Alpha (8-13Hz) / Beta (13-30Hz) / Gamma (30-100Hz) 五頻段分解
GPU Rendering自訂 Metal vertex & fragment shaders,含抗鋸齒、漸變色、極簡快速路徑三種變體
ArchitectureMVVM 架構搭配 Swift Concurrency (actorAsyncStream) 與 Combine 綁定
Power Optimization動態 FPS 節流、packed vertex buffers、低功耗 Metal 渲染模式(目標降低 76% 功耗)

🏗️ Architecture / 系統架構

Signal Processing Pipeline / 訊號處理流程

Raw EEG (512 Hz)
│
├── DC Removal 去直流(移除平均值)
│
├── Hann Window 512 點漢寧窗加權
│
├── Real FFT Accelerate vDSP_fft_zrip 實數快速傅立葉轉換
│
├── Power Spectrum 功率頻譜密度計算
│
├── ENBW Correction 等效雜訊頻寬校正 (factor = 1.5)
│
├── Band Integration 頻段能量積分
│ ├── Delta δ : 0.5 – 4 Hz 深層睡眠波
│ ├── Theta θ : 4 – 8 Hz 冥想放鬆波
│ ├── Alpha α : 8 – 13 Hz 清醒放鬆波
│ ├── Beta β : 13 – 30 Hz 專注思考波
│ └── Gamma γ : 30 – 100 Hz 高階認知波
│
├── log10 Scaling 可選對數縮放
│
└── EMA Smoothing 指數移動平均平滑 (α = 0.2)

Metal GPU Rendering / Metal GPU 渲染管線

應用程式包含四種著色器變體,針對不同場景優化:

ShaderPurpose / 用途
vertex_waveform + fragment_waveform標準波形渲染,剪裁空間座標直接映射
fragment_waveform_antialiased距離場抗鋸齒,smoothstep 實現平滑邊緣
vertex_waveform_gradient + fragment_waveform_gradient多頻帶漸變色顯示,頂點間顏色插值
vertex_waveform_fast + fragment_waveform_fastpacked_float2 極簡路徑,最低 GPU 開銷

📁 Project Structure / 專案結構

brainwave-eeg-interface/
├── Aura/
│ ├── AuraApp.swift # App entry point / 應用程式進入點
│ ├── BrainwaveViewModel.swift # MVVM core (450 lines) / MVVM 核心協調器
│ ├── EEGAnalyzer.swift # DSP engine (407 lines) / Accelerate FFT 訊號處理
│ ├── MetalWaveformRenderer.swift # GPU renderer (271 lines) / Metal 渲染管線
│ ├── Shaders.metal # Custom Metal shaders / 自訂 GPU 著色器
│ ├── MetalWaveformView.swift # MetalKit view integration / Metal 視圖橋接
│ ├── BluetoothManager.swift # CoreBluetooth BLE scanning / 藍牙裝置掃描
│ ├── MindLinkManager.swift # NeuroSky ExternalAccessory / NeuroSky 協定連接
│ ├── ThinkGearParser.swift # ThinkGear packet parser / 0xAA 封包解析
│ ├── DataParser.swift # Raw data parsing / 原始資料解析
│ ├── WaveformBuffer.swift # Ring buffer (2000 samples) / 環形緩衝區
│ ├── WaveformView.swift # SwiftUI waveform view / SwiftUI 波形視圖
│ ├── ContentView.swift # Main TabView UI / 主介面 TabView
│ ├── DeviceListView.swift # BLE device scanner UI / 裝置掃描列表
│ ├── DataDisplayView.swift # Real-time data dashboard / 即時數據儀表板
│ ├── SimulatedDataSource.swift # Debug signal generator / 模擬訊號產生器
│ ├── SessionModels.swift # Data models / 會話資料模型
│ ├── SessionStore.swift # JSON persistence / JSON 持久化儲存
│ ├── EEGBandReference.swift # Band definitions / 頻段定義參考
│ └── Theme.swift # UI theming / 主題配色
├── Aura.xcodeproj/ # Xcode project configuration
├── AuraTests/ # Unit tests / 單元測試
├── AuraUITests/ # UI tests / UI 自動化測試
└── docs/ # Technical documentation / 技術文件

🛠️ Tech Stack / 技術棧

LayerTechnology
UI FrameworkSwiftUI, MetalKit
GPU ComputingMetal Shading Language (MSL) -- custom vertex/fragment shaders
Digital Signal ProcessingApple Accelerate / vDSP -- hardware-accelerated FFT, windowing, vector ops
BluetoothExternalAccessory (NeuroSky ThinkGear), CoreBluetooth (BLE scanning)
ConcurrencySwift actor (EEGAnalyzer), AsyncStream (band/eSense streams), Combine
ArchitectureMVVM -- BrainwaveViewModel as single source of truth
PersistenceFile-based JSON session index + per-session data files

🔑 Key Implementation Details / 關鍵實作細節

EEG Analyzer (EEGAnalyzer.swift -- 407 lines)

  • Actor-based thread safety -- 整個 DSP 引擎使用 Swift actor 模型,確保 512Hz 高頻數據的執行緒安全
  • Accelerate vDSP FFT -- 使用 vDSP_fft_zrip 實數到複數轉換,radix-2 演算法
  • Hann windowing -- ENBW 校正係數 1.5,功率增益校正 0.375
  • NeuroSky ADC alignment -- 12-bit ADC 歸一化 (±2048 範圍),非 Int16 全範圍
  • Dual output streams -- AsyncStream<BandFrame> 輸出五頻段能量,AsyncStream<ESenseFrame> 輸出注意力/冥想指標
  • Configurable pipeline -- 可選 log10 縮放、相對能量模式、EMA 平滑、增益校正

Metal Renderer (MetalWaveformRenderer.swift -- 271 lines)

  • 完整 Metal 渲染管線:device -> commandQueue -> pipelineState -> vertexBuffer -> uniformBuffer
  • 動態 FPS 控制 -- 預設 60fps,可降頻至 30fps 省電模式
  • 四種 shader 路徑 -- 標準 / 抗鋸齒 / 漸變色 / 極簡快速,根據場景自動切換
  • 功耗目標 -- 相比 CPU 渲染降低 76% 電力消耗

ViewModel (BrainwaveViewModel.swift -- 450 lines)

  • 中央協調器,綁定 Bluetooth、Parser、Analyzer、UI 四層
  • Session recording -- 持久化會話索引,支援歷史回顧與匯出
  • EEG watchdog timer -- 連接健康狀態監控,自動偵測訊號中斷
  • Simulation mode -- 無需硬體即可開發測試,產生符合 NeuroSky 規格的模擬數據

⚡ Performance / 效能指標

MetricValue
Sampling Rate512 Hz
FFT Resolution1 Hz (512-point window)
Waveform Refresh~60 FPS (Metal GPU)
Power Reduction76% vs CPU rendering
Memory Footprint< 60 MB
Hardware Alignment< 5% deviation from NeuroSky ASIC
Parseval Theorem Error< 1%

🏁 Getting Started / 開始使用

Prerequisites / 前置需求

  • Xcode 15+ with iOS 17 SDK
  • NeuroSky MindWave Mobile or compatible EEG headband
  • Physical iOS device (Metal requires real hardware / Metal 需要實機)

Build & Run / 建置與執行

# Clone the repository
git clone <repo-url>cd brainwave-eeg-interface
# Open in Xcode
open Aura.xcodeproj
# Select your iOS device target, then Build & Run (Cmd+R)

Using Simulation Mode / 使用模擬模式

無需實體 EEG 頭環即可體驗完整功能。在 App 設定中開啟「模擬數據」,系統會透過 SimulatedDataSource.swift 產生符合 NeuroSky 規格的合成腦波訊號,FFT 分析結果與硬體輸出一致性 < 5%。


🏷️ Category / 分類

Human-Machine Interaction / 人機互動

本專案位於神經科學、數位訊號處理、行動 GPU 運算的交匯點 -- 將大腦原始電位活動轉化為即時互動的視覺體驗。從 512Hz 原始 EEG 訊號到 Metal 著色器渲染的腦波圖,完整展示了 BCI 腦機介面從硬體協定到 GPU 管線的全棧實作。


Built with Swift, Metal, and Accelerate

用 Swift、Metal 和 Accelerate 打造的即時腦機介面

About

Real-time iOS brain-computer interface that streams EEG over Bluetooth and renders signals with GPU acceleration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages