10 KiB
Context Document: Radar and Video Synchronizer Application
1. High-Level Overview
Core Purpose: A high-precision, browser-based tool for visualizing and synchronizing radar sensor data (JSON) with a corresponding video file. It allows for detailed analysis of object tracks, point clouds, and vehicle dynamics.
Core Technologies:
- Frontend: HTML5, Tailwind CSS
- Logic: Modular JavaScript (ES6 Modules)
- Visualization:
p5.jsfor the main radar plot, a zoomed-in "god mode" view, and a time-series speed graph. - Data Handling:
- Web Workers (
parser.worker.js) with theClarinet.jsstreaming library to parse large JSON files off the main thread, preventing UI freezes. Oboe.jsis included in vendor files butClarinet.jsis the active parser.
- Web Workers (
- Data Exploration:
AG-Gridfor tabular data view andChart.jsfor plotting data from the grid. - Persistence:
IndexedDBfor caching large files (JSON, Video) andlocalStoragefor user settings (UI state, theme, file references).
2. Project Architecture & File Structure
The application uses a modular ES6 structure. All source code resides in the /src directory.
index.html: The main HTML shell. Defines the DOM structure, including the main layout, collapsible sidebar, data explorer panel, and documentation modals (User Manual, Shortcuts, Codebase Overview, Changelog). It loads all necessary CDN libraries and the main JS module.
...
-
/annex/: Supplementary Documentation. Contains HTML files for the User Manual, Keyboard Shortcuts, Codebase Overview, and Changelog, as well as the progress log (Improvements.txt). -
/intel/: Project Intelligence. Contains documentation and AI-specific context files (readme.md,GEMINI.md,context.md). -
/src/main.js: The Orchestrator. This is the application's entry point. It initializes the database, theme, and data explorer. It sets up the initial event listeners for the UI and delegates specialized tasks to other modules (fileLoader.js,keyboard.js,sync.js,ui.js). -
/src/state.js: The Single Source of Truth. Exports a single globalappStateobject that holds all dynamic data (e.g.,vizData,isPlaying,currentFrame). All modules import from this file. -
/src/fileLoader.js: File Management. Handles the file loading pipeline. It manages drag-and-drop interactions, file input changes, and the unified processing of JSON and Video files. It handles caching logic (saving/loading fromIndexedDB) and triggers the parsing worker. -
/src/keyboard.js: Input Handling. Manages all keyboard shortcuts. It creates a centralizedkeydownlistener that triggers UI actions (play/pause, seeking, toggles) and prevents interference with input fields. -
/src/sync.js: The Heartbeat & Controller. Contains the core logic for playback and synchronization.animationLoop(): The main render loop that keeps the UI updated.videoFrameCallback(): The high-precision video timing loop.updateFrame(): The central function that updates the current frame index, synchronizes the video (handling drift), and updates UI elements (sliders, counters, overlays).resetVisualization(): Resets the playback state.- Handles timeline interactions (input, scroll wheel) and video panel scrolling.
-
/src/dom.js: The UI Interface. Exports constants for every key DOM element. It contains functions to update specific UI components like persistent overlays (updatePersistentOverlays), debug overlays (updateDebugOverlay), and custom TTC scheme inputs. Note: Core playback-driven UI updates have moved tosync.js. -
/src/fileParsers.js: The Data Processor. ContainsparseVisualizationJson(), which takes the raw parsed JSON object and enriches it with calculatedtimestampMsvalues relative to the video start time and determines global SNR ranges. -
/src/parser.worker.js: The Heavy Lifter. A Web Worker that usesClarinet.jsto stream-parse the JSON file, preventing the main thread from freezing. It posts progress updates and the final parsed object back tomain.js(viafileLoader.js). -
/src/db.js: The Caching Layer. Manages all interactions withIndexedDBto save and load file blobs and their metadata, enabling fast session reloads. -
/src/dataExplorer.js: The Inspector. Manages the "Data Explorer" panel. It uses AG-Grid to display data in a table and Chart.js to plot selected columns. It includesthrottledUpdateExplorerto efficiently update the view during playback. -
/src/ui.js: The UI Engine. Manages all advanced interface interactions.makeDraggableAndResizable(): A unified utility that transforms any DOM element into a floating window with persistent memory.- Memory & Persistence: Saves/Loads panel coordinates and GridStack layouts to
localStorage. - Viewport Rescue: Automatically recovers off-screen windows during browser resizing.
- Auto-Focus: Dynamically manages
z-indexto bring active windows to the front on click.
-
/src/debug.js: Debug Configuration. ExportsdebugFlagsto toggle logging for various subsystems (sync, drawing, file loading) and configure constants like video load timeouts. -
/src/utils.js: Toolbox. A collection of pure, reusable helper functions (e.g.,findRadarFrameIndexForTime(binary search), timestamp parsers,throttle,precomputeRadarVideoSync). -
/src/modal.js: User Feedback. Manages the logic for pop-up modal dialogs, including notifications, confirmations, and loading progress bars. -
/src/theme.js: Styling. Handles the dark/light mode theme switching. -
/src/constants.js: Configuration. Stores shared, static values likeVIDEO_FPSand radar plot boundaries. -
/src/p5/: Visualization Modules.radarSketch.js: Master timer for God Mode auto-visibility (5s delay). Hardened with guards against 0-width crashes.zoomSketch.js: "GOD MODE" view. Includes the "Closing in..." countdown (3s) and "Out of Bounds" safety indicators.speedGraphSketch.js: Refined with initialization guards to handle rapid layout shifts.
-
/src/drawUtils.js: The Artist's Toolkit. Contains pure drawing functions called by the p5 sketches (e.g.,drawPointCloud,drawTrajectories). This is where the visual appearance of radar objects is defined.
3. Data Flow & State Management
File Loading Pipeline (fileLoader.js):
- Input: User drops files or clicks load buttons.
handleFiles()identifies the file types. - Processing (
processFilePipeline): A loading modal is shown. - Caching: Files are saved to
IndexedDB(non-blocking). - Offset: Timestamp offset is calculated from filenames.
- JSON Parsing: JSON is sent to
parser.worker.js. The worker streams the file and returns the object. - Post-Processing:
parseVisualizationJson()(infileParsers.js) enriches the data.precomputeRadarVideoSync()(inutils.js) bakes sync times. - Video Loading: The video is loaded into the player.
- Finalization:
finalizeSetup()(infileLoader.js) resets the visualization, creates/updates p5 sketches, and updates the UI.
Playback & Synchronization (sync.js):
- Video Master: The video element's time is the source of truth when playing.
videoFrameCallback: Runs on every video frame, finds the corresponding radar frame index, and updatesappState.currentFrame.animationLoop: Runs onrequestAnimationFrame(~60Hz). It callsupdateFrame()to reflect the state on the screen.updateFrame():- Updates UI (slider, counter).
- Updates overlays (Ego speed, CAN speed).
- Calls
throttledUpdateExplorer. - Handles Video Seek: If
forceVideoSeekis true (e.g., user scrubbed the timeline), it setsvideoPlayer.currentTime.
- Drift Correction: If the video drifts significantly from the target radar frame time,
updateFrameforces a seek to resync.
State Management (appState):
The appState object in state.js is the central hub. Key properties include:
vizData: The large object containing all radar frames and track data.isPlaying: Boolean controlling the loop.currentFrame: Integer index of the currently displayed radar frame.offset: Manual or auto-calculated time offset (ms).videoStartDate,radarStartTimeMs: Timestamps for absolute time calculation.p5_instance,speedGraphInstance: References to active sketches.videoMissing: Flag for JSON-only mode.
4. Key Interaction Flows
Timeline Scrubbing (sync.js):
- Drag:
handleTimelineInputupdates the UI immediately for responsiveness but debounces the expensive video seek until the user stops dragging. - Scroll Wheel:
handleTimelineWheelallows frame-by-frame or accelerated seeking. It also updates UI immediately and debounces the video seek.
Data Explorer (dataExplorer.js):
- Activated by
Ikey or canvas click. - Shows Tree, Grid, and Plot views.
- Updates are throttled to prevent performance degradation during playback.
God Mode Auto-Hide (p5/*.js):
- Sequence: The panel appears on hover. If the mouse stops moving over a relevant point, a 5-second "Analysis Period" begins. After 5s, a visual 3-second countdown appears. Total 8s before hiding.
- Override: Any new interaction or mouse movement resets the full 8-second timer.
Layout Persistence (ui.js & main.js):
- GridStack: Uses a "Soft Restore" loop to update panel positions by ID, ensuring p5 canvases and Video elements are not destroyed during layout changes.
- Floating Panels: Tracks
top/left/width/heightindividually per panel ID. - Nuclear Reset: The "Clear Cache and Reload" button wipes all UI memory, returning the app to factory defaults.
Session Management (main.js & db.js):
saveSessionBtnsaves current filenames, offset, and toggles to a JSON file.loadSessionBtnreads the session file. It verifies that the referenced files exist inIndexedDB(vialoadFreshFileFromDB) before applying settings and reloading the page.
Keyboard Shortcuts (keyboard.js):
- Centralized handler for
Play/Pause(Space),Seek(Arrows),Toggle Views(1-4, T, D, G, P, C),Debug(A),Theme(Q). - Smartly ignores shortcuts when input fields are focused.