from __future__ import annotations
import argparse
import logging
import os
import threading
import time
from operator import index
from typing import Optional, Sequence
import numpy as np
from pylsl import StreamInfo, StreamOutlet, local_clock
from pyoephys.io import load_open_ephys_session, find_oebin_files
log = logging.getLogger(__name__)
[docs]
class OEBinPlaybackClient:
"""
Realtime playback of Open Ephys .oebin recordings with clean LSL timestamps.
Publishes chunks as (n_samples, n_channels) using recorded or LSL clock timestamps.
Parameters
----------
oebin_path : str
Path to a single .oebin file or a directory containing one.
stream_name : str
LSL stream name to publish.
block_size : int
Samples per chunk (controls latency).
loopback : bool
If True, after the last sample is sent, restart from the beginning.
enable_lsl : bool
Whether to publish over LSL. If False, only loop internally (for tests).
use_recorded_timestamps : bool
If True, publish recorded timestamps instead of local_clock().
speed_factor : float
1.0 = real time. >1.0 faster, <1.0 slower (wall-time playback).
verbose : bool
If True, emit INFO logs from this client.
channels : sequence of int or None
Zero-based channel indices in output order. None plays all channels.
stream_type : str
LSL stream type to publish.
"""
def __init__(
self,
oebin_path: str,
stream_name: str = "EMG",
block_size: int = 128,
loopback: bool = False,
enable_lsl: bool = True,
use_recorded_timestamps: bool = True,
speed_factor: float = 1.0,
verbose: bool = False,
*,
channels: Sequence[int] | None = None,
stream_type: str = "EMG",
) -> None:
self.stream_name = str(stream_name)
self.verbose = bool(verbose)
self.loopback = bool(loopback)
self.block_size = int(block_size)
self.enable_lsl = bool(enable_lsl)
self.use_recorded_timestamps = bool(use_recorded_timestamps)
self.speed_factor = float(speed_factor)
# Resolve .oebin path (file or directory)
if os.path.isdir(oebin_path):
if self.verbose:
log.info("Searching for OEBIN files in: %s", oebin_path)
oebin_files = find_oebin_files(oebin_path)
if not oebin_files:
raise FileNotFoundError(f"No .oebin in {oebin_path}")
oebin_file = oebin_files[0]
else:
oebin_file = oebin_path
if not os.path.isfile(oebin_file):
raise FileNotFoundError(oebin_file)
self.oebin_file = oebin_file
# Threading
self._thread: Optional[threading.Thread] = None
self._stop = threading.Event()
self._lock = threading.Lock()
# Load entire session to memory (defer to your IO util)
data = load_open_ephys_session(oebin_file)
# Expecting keys: 'amplifier_data' -> (n_channels, n_samples), 't_amplifier', 'sample_rate', etc.
self._y = np.asarray(data["amplifier_data"]) # (C, S)
self._t = np.asarray(data["t_amplifier"]) # (S,)
self.fs = float(data["sample_rate"])
self.channel_names = list(data["channel_names"]) # list of channel names
if channels is not None:
indices = [index(channel) for channel in channels]
if not indices or min(indices) < 0 or max(indices) >= self._y.shape[0]:
raise ValueError("Select one or more channels within the recording's channel range.")
self._y = self._y[indices]
self.channel_names = [self.channel_names[index] for index in indices]
# Maintain compatibility for some older scripts
self.sampling_rate = self.fs
self.n_channels, self.n_samples = self._y.shape
self.t_file = self._t
if self.n_samples == 0 or self.block_size < 1 or not np.isfinite(self.speed_factor) or self.speed_factor <= 0:
raise ValueError("Playback requires samples, a positive block size, and a positive finite speed.")
self.total_samples = 0
self.current_index = 0
if self.verbose:
log.info(
"Loaded %s: channels=%d, samples=%d, fs=%.2f Hz",
os.path.basename(oebin_file),
self._y.shape[0],
self._y.shape[1],
self.fs,
)
# Prepare LSL outlet if enabled
self._outlet: Optional[StreamOutlet] = None
if self.enable_lsl:
n_channels = int(self._y.shape[0])
info = StreamInfo(
name=self.stream_name,
type=stream_type,
channel_count=n_channels,
nominal_srate=self.fs,
channel_format="float32",
source_id=f"pyoephys.playback.{os.path.basename(oebin_file)}",
)
self._outlet = StreamOutlet(info)
[docs]
def start(self) -> None:
if self._thread and self._thread.is_alive():
return
self._stop.clear()
self._thread = threading.Thread(target=self._run_loop, name="OEBinPlayback", daemon=True)
self._thread.start()
if self.verbose:
log.info("Playback started.")
[docs]
def stop(self, timeout: Optional[float] = 2.0) -> None:
self._stop.set()
if self._thread and self._thread.is_alive():
self._thread.join(timeout=timeout)
if self.verbose:
log.info("Playback stopped.")
[docs]
def close(self) -> None:
"""Stop playback and release resources."""
self.stop()
self._thread = None
self._outlet = None
if self.verbose:
log.info("Playback client closed.")
[docs]
def is_done(self) -> bool:
"""Check if playback has reached the end of the recording, and not loopback."""
return self._stop.is_set() or (not self.loopback) and (self.current_index >= self.n_samples)
def _run_loop(self) -> None:
i0 = self.current_index
start_index = min(i0, self.n_samples - 1)
start_wall = time.perf_counter()
while not self._stop.is_set():
if i0 >= self.n_samples:
if not self.loopback:
if self.verbose:
log.info("Reached end of recording.")
break
i0 = start_index = 0
start_wall = time.perf_counter()
i1 = min(i0 + self.block_size, self.n_samples)
if self.use_recorded_timestamps:
elapsed = self._t[i0] - self._t[start_index]
else:
elapsed = (i0 - start_index) / self.fs
delay = start_wall + elapsed / self.speed_factor - time.perf_counter()
if self._stop.wait(max(0.0, delay)):
break
if self._outlet is not None:
chunk = self._y[:, i0:i1]
if self.use_recorded_timestamps:
timestamp = self._t[i0:i1].tolist()
else:
# For regular-rate streams LSL derives the earlier timestamps
# in a chunk from the timestamp of its final sample.
timestamp = local_clock() + (i1 - i0 - 1) / self.fs
chunk_sc = np.ascontiguousarray(chunk.T, dtype=np.float32) # shape (B, C), C-order
self._outlet.push_chunk(chunk_sc, timestamp)
with self._lock:
self.total_samples = self.current_index = i1
i0 = i1
[docs]
def is_running(self) -> bool:
return self._thread is not None and self._thread.is_alive()
[docs]
def get_latest_window(self, window_ms: int = 500) -> np.ndarray:
"""
Return the most recent played window as (C, Nwin).
"""
nwin = int(max(1, round(window_ms / 1000.0 * self.fs)))
with self._lock:
end = self.total_samples
beg = max(0, end - nwin)
return self._y[:, beg:end].astype(np.float32, copy=True)
# ---------------- CLI entry -----------------
def _add_common_args(ap: argparse.ArgumentParser) -> None:
ap.add_argument("--oebin", dest="oebin", required=True, help="Path to .oebin file or its parent folder")
ap.add_argument("--stream_name", default="EMG", help="LSL stream name")
ap.add_argument("--stream_type", default="EMG", help="LSL stream type")
ap.add_argument("--channels", type=int, nargs="+", help="Zero-based channels in output order")
ap.add_argument("--block_size", type=int, default=128, help="Samples per push")
ap.add_argument("--loop", action="store_true", help="Loop playback when the end is reached")
ap.add_argument("--no_lsl", action="store_true", help="Disable LSL publishing (dry run)")
ap.add_argument("--recorded_ts", action="store_true", help="Publish recorded timestamps")
ap.add_argument("--speed", type=float, default=1.0, help="Playback speed factor (1.0 = realtime)")
ap.add_argument("--verbose", action="store_true", help="Enable INFO logs for playback")
[docs]
def playback_cli(argv: Optional[Sequence[str]] = None) -> None:
from pyoephys.logging import configure
ap = argparse.ArgumentParser(prog="pyoephys-playback", description="Play back .oebin over LSL")
_add_common_args(ap)
args = ap.parse_args(argv)
configure("INFO" if args.verbose else "WARNING")
client = OEBinPlaybackClient(
oebin_path=args.oebin,
stream_name=args.stream_name,
block_size=args.block_size,
loopback=args.loop,
enable_lsl=not args.no_lsl,
use_recorded_timestamps=args.recorded_ts,
speed_factor=args.speed,
verbose=args.verbose,
channels=args.channels,
stream_type=args.stream_type,
)
client.start()
try:
while client.is_running():
time.sleep(0.25)
except KeyboardInterrupt:
pass
finally:
client.stop()