talksign 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
talksign/video.py ADDED
@@ -0,0 +1,625 @@
1
+ """Steady RGB frames from an :class:`~talksign.EchoStream` (``pip install "talksign[video]"``).
2
+
3
+ :class:`EchoFrameSource` is the building block of the voice-agent plugins: push text in, read
4
+ ``numpy`` frames (``height x width x 3``, ``uint8``, RGB) out at a fixed frame rate. It loops the
5
+ avatar's idle clip when nothing is being signed, crossfades between clips, downloads clips with
6
+ bounded concurrency and a small LRU cache, and decodes video in a worker thread so the event loop
7
+ never blocks.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import contextlib
14
+ import io
15
+ from collections import OrderedDict, deque
16
+ from collections.abc import Iterator
17
+ from dataclasses import dataclass, field
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ import httpx
21
+
22
+ try:
23
+ import av
24
+ import numpy as np
25
+ except ImportError as e: # pragma: no cover - exercised only without the extra
26
+ raise ImportError('talksign.video needs the "video" extra: pip install "talksign[video]"') from e
27
+
28
+ from ._echo import ClipEvent, DoneEvent, EchoStream, IdleEvent, SentenceEvent
29
+ from .types import Clip
30
+
31
+ if TYPE_CHECKING:
32
+ from numpy.typing import NDArray
33
+
34
+ from ._client import AsyncTalksign
35
+
36
+ Frame = NDArray[np.uint8]
37
+ else:
38
+ Frame = Any
39
+
40
+ __all__ = ["ClipCache", "EchoFrameSource", "Frame", "decode_clip"]
41
+
42
+ _EPS = 1e-6
43
+ _BATCH = 6
44
+
45
+
46
+ # ----------------------------------------------------------------------------
47
+ # Decoding (runs in a worker thread)
48
+ # ----------------------------------------------------------------------------
49
+ def _fit(frame: Any, width: int, height: int, background: tuple[int, int, int]) -> Frame:
50
+ fw, fh = frame.width, frame.height
51
+ scale = min(width / fw, height / fh)
52
+ nw, nh = max(2, int(round(fw * scale))), max(2, int(round(fh * scale)))
53
+ nw, nh = min(nw, width), min(nh, height)
54
+ arr: Frame = frame.reformat(width=nw, height=nh, format="rgb24").to_ndarray()
55
+ if nw == width and nh == height:
56
+ return arr
57
+ canvas: Frame = np.empty((height, width, 3), dtype=np.uint8)
58
+ canvas[:, :] = background
59
+ x, y = (width - nw) // 2, (height - nh) // 2
60
+ canvas[y : y + nh, x : x + nw] = arr
61
+ return canvas
62
+
63
+
64
+ def decode_clip(
65
+ data: bytes,
66
+ *,
67
+ width: int,
68
+ height: int,
69
+ fps: float,
70
+ start_s: float | None = None,
71
+ end_s: float | None = None,
72
+ speed: float = 1.0,
73
+ background: tuple[int, int, int] = (255, 255, 255),
74
+ ) -> Iterator[Frame]:
75
+ """Yields the clip's frames resampled to ``fps`` (played at ``speed``) and fitted into ``width x height``.
76
+
77
+ Only ``[start_s, end_s]`` of the source is used. Blocking: run it in a thread.
78
+ """
79
+ step = max(speed, 0.05) / fps
80
+ target = max(0.0, start_s or 0.0)
81
+ container = av.open(io.BytesIO(data), mode="r")
82
+ try:
83
+ stream = container.streams.video[0]
84
+ rate = float(stream.average_rate or stream.guessed_rate or 30)
85
+ prev: Any = None
86
+ prev_t = 0.0
87
+ prev_rgb: Frame | None = None
88
+ index = 0
89
+ for fr in container.decode(stream):
90
+ t = float(fr.time) if fr.time is not None else index / rate
91
+ index += 1
92
+ if end_s is not None and t > end_s + _EPS:
93
+ break
94
+ while prev is not None and t > target + _EPS:
95
+ if prev_rgb is None:
96
+ prev_rgb = _fit(prev, width, height, background)
97
+ yield prev_rgb
98
+ target += step
99
+ prev, prev_rgb, prev_t = fr, None, t
100
+ if prev is not None:
101
+ last_end = end_s if end_s is not None else prev_t + 1.0 / rate
102
+ while target < last_end - _EPS:
103
+ if prev_rgb is None:
104
+ prev_rgb = _fit(prev, width, height, background)
105
+ yield prev_rgb
106
+ target += step
107
+ finally:
108
+ container.close()
109
+
110
+
111
+ def _next_batch(it: Iterator[Frame], n: int) -> list[Frame]:
112
+ out: list[Frame] = []
113
+ for frame in it:
114
+ out.append(frame)
115
+ if len(out) >= n:
116
+ break
117
+ return out
118
+
119
+
120
+ class _Reader:
121
+ """Pulls decoded frames from a clip, a few at a time, in a worker thread (always one batch ahead)."""
122
+
123
+ def __init__(
124
+ self, data: bytes, opts: dict[str, Any], *, start_s: float | None, end_s: float | None, speed: float
125
+ ) -> None:
126
+ self._it = decode_clip(data, start_s=start_s, end_s=end_s, speed=speed, **opts)
127
+ self._buf: deque[Frame] = deque()
128
+ self._task: asyncio.Task[list[Frame]] | None = None
129
+ self._done = False
130
+
131
+ def prime(self) -> None:
132
+ if self._task is None and not self._done:
133
+ self._task = asyncio.get_running_loop().create_task(asyncio.to_thread(_next_batch, self._it, _BATCH))
134
+
135
+ async def next(self) -> Frame | None:
136
+ while not self._buf:
137
+ if self._done:
138
+ return None
139
+ self.prime()
140
+ assert self._task is not None
141
+ batch = await self._task
142
+ self._task = None
143
+ if len(batch) < _BATCH:
144
+ self._done = True
145
+ self._buf.extend(batch)
146
+ frame = self._buf.popleft()
147
+ if len(self._buf) < _BATCH // 2:
148
+ self.prime()
149
+ return frame
150
+
151
+ def close(self) -> None:
152
+ self._done = True
153
+ self._buf.clear()
154
+ task, self._task = self._task, None
155
+ it = self._it
156
+
157
+ def _close() -> None:
158
+ with contextlib.suppress(Exception):
159
+ it.close() # type: ignore[attr-defined]
160
+
161
+ if task is not None and not task.done():
162
+ task.add_done_callback(lambda _t: asyncio.get_running_loop().run_in_executor(None, _close))
163
+ else:
164
+ with contextlib.suppress(RuntimeError):
165
+ asyncio.get_running_loop().run_in_executor(None, _close)
166
+
167
+
168
+ # ----------------------------------------------------------------------------
169
+ # Downloads
170
+ # ----------------------------------------------------------------------------
171
+ def _consume_exception(fut: asyncio.Future[Any]) -> None:
172
+ if not fut.cancelled():
173
+ fut.exception()
174
+
175
+
176
+ class ClipCache:
177
+ """Downloads clip URLs with bounded concurrency into a small LRU cache.
178
+
179
+ Signed URLs change per call while the clip stays the same, so the cache key ignores the query string.
180
+ """
181
+
182
+ def __init__(
183
+ self,
184
+ http: httpx.AsyncClient,
185
+ *,
186
+ max_concurrency: int = 3,
187
+ max_items: int = 32,
188
+ max_bytes: int = 128 * 1024 * 1024,
189
+ ) -> None:
190
+ self._http = http
191
+ self._sem = asyncio.Semaphore(max(1, max_concurrency))
192
+ self._lru: OrderedDict[str, bytes] = OrderedDict()
193
+ self._inflight: dict[str, asyncio.Future[bytes]] = {}
194
+ self.max_items = max_items
195
+ self.max_bytes = max_bytes
196
+ self._bytes = 0
197
+
198
+ @staticmethod
199
+ def key(url: str) -> str:
200
+ return url.split("?", 1)[0]
201
+
202
+ def __contains__(self, url: str) -> bool:
203
+ return self.key(url) in self._lru
204
+
205
+ def __len__(self) -> int:
206
+ return len(self._lru)
207
+
208
+ async def get(self, url: str) -> bytes:
209
+ k = self.key(url)
210
+ if k in self._lru:
211
+ self._lru.move_to_end(k)
212
+ return self._lru[k]
213
+ fut = self._inflight.get(k)
214
+ if fut is None:
215
+ fut = asyncio.get_running_loop().create_task(self._download(url, k))
216
+ fut.add_done_callback(_consume_exception) # a prefetch nobody awaits (e.g. after interrupt) stays quiet
217
+ self._inflight[k] = fut
218
+ return await asyncio.shield(fut)
219
+
220
+ async def aclose(self) -> None:
221
+ """Cancels downloads still in flight (call before closing the HTTP client)."""
222
+ pending = list(self._inflight.values())
223
+ for fut in pending:
224
+ fut.cancel()
225
+ if pending:
226
+ await asyncio.gather(*pending, return_exceptions=True)
227
+
228
+ async def _download(self, url: str, k: str) -> bytes:
229
+ try:
230
+ async with self._sem:
231
+ resp = await self._http.get(url)
232
+ resp.raise_for_status()
233
+ data = resp.content
234
+ self._put(k, data)
235
+ return data
236
+ finally:
237
+ self._inflight.pop(k, None)
238
+
239
+ def _put(self, k: str, data: bytes) -> None:
240
+ if len(data) > self.max_bytes:
241
+ return
242
+ self._lru[k] = data
243
+ self._bytes += len(data)
244
+ while self._lru and (len(self._lru) > self.max_items or self._bytes > self.max_bytes):
245
+ _, old = self._lru.popitem(last=False)
246
+ self._bytes -= len(old)
247
+
248
+
249
+ # ----------------------------------------------------------------------------
250
+ # Frame source
251
+ # ----------------------------------------------------------------------------
252
+ @dataclass
253
+ class _Segment:
254
+ url: str
255
+ start_s: float | None = None
256
+ end_s: float | None = None
257
+ speed: float = 1.0
258
+ task: asyncio.Task[bytes] | None = None
259
+ reader: _Reader | None = None
260
+
261
+
262
+ @dataclass
263
+ class _Word:
264
+ clip: Clip
265
+ segments: list[_Segment]
266
+ seamless: bool # has neutral-pose in/out clips: no crossfade needed
267
+ pos: int = 0
268
+ started: bool = field(default=False)
269
+
270
+
271
+ def _word_from_clip(clip: Clip) -> _Word:
272
+ url = clip.get("url")
273
+ assert url
274
+ in_url, out_url = clip.get("in_url"), clip.get("out_url")
275
+ if in_url and out_url:
276
+ speed = float(clip.get("in_out_speed") or 1.0)
277
+ segs = [
278
+ _Segment(in_url, speed=speed),
279
+ _Segment(url, start_s=clip.get("active_start_s"), end_s=clip.get("active_end_s")),
280
+ _Segment(out_url, speed=speed),
281
+ ]
282
+ return _Word(clip, segs, seamless=True)
283
+ return _Word(clip, [_Segment(url)], seamless=False)
284
+
285
+
286
+ class EchoFrameSource:
287
+ """A steady stream of RGB frames for an :class:`~talksign.EchoStream`.
288
+
289
+ ``async for frame in source`` yields one ``numpy`` array per frame (``height x width x 3`` ``uint8``) at
290
+ ``fps`` frames per second (paced in real time when ``realtime=True``; as fast as possible otherwise).
291
+ Text goes in with :meth:`push_text` / :meth:`flush`; :meth:`interrupt` stops signing at once and
292
+ crossfades back to the idle loop. Before the avatar's idle clip is known, frames show ``background``.
293
+ """
294
+
295
+ def __init__(
296
+ self,
297
+ stream: EchoStream,
298
+ *,
299
+ width: int = 1280,
300
+ height: int = 720,
301
+ fps: float = 30.0,
302
+ crossfade_ms: float = 150.0,
303
+ background: tuple[int, int, int] = (255, 255, 255),
304
+ realtime: bool = True,
305
+ max_downloads: int = 3,
306
+ cache_items: int = 32,
307
+ cache_bytes: int = 128 * 1024 * 1024,
308
+ idle_url: str | None = None,
309
+ http_client: httpx.AsyncClient | None = None,
310
+ ) -> None:
311
+ if width < 2 or height < 2 or fps <= 0:
312
+ raise ValueError("width/height must be >= 2 and fps > 0")
313
+ self.stream = stream
314
+ self.width, self.height, self.fps = int(width), int(height), float(fps)
315
+ self.background = background
316
+ self.realtime = realtime
317
+ self.crossfade_frames = max(0, int(round(crossfade_ms * self.fps / 1000.0)))
318
+ self._own_http = http_client is None
319
+ self._http = http_client or httpx.AsyncClient(timeout=30.0, follow_redirects=True)
320
+ self.cache = ClipCache(self._http, max_concurrency=max_downloads, max_items=cache_items, max_bytes=cache_bytes)
321
+ self._opts: dict[str, Any] = {
322
+ "width": self.width,
323
+ "height": self.height,
324
+ "fps": self.fps,
325
+ "background": background,
326
+ }
327
+ self._queue: deque[_Word] = deque()
328
+ self._word: _Word | None = None
329
+ self._idle_url: str | None = idle_url
330
+ self._idle_task: asyncio.Task[bytes] | None = None
331
+ self._idle_reader: _Reader | None = None
332
+ self._blank: Frame = np.empty((self.height, self.width, 3), dtype=np.uint8)
333
+ self._blank[:, :] = background
334
+ self._last: Frame = self._blank
335
+ self._fade_from: Frame | None = None
336
+ self._fade_left = 0
337
+ self._hold = 0
338
+ self._events_task: asyncio.Task[None] | None = None
339
+ self._stream_done = False
340
+ self._closed = False
341
+ self._t0: float | None = None
342
+ self._n = 0
343
+
344
+ @classmethod
345
+ def from_client(
346
+ cls, client: AsyncTalksign, *, avatar: str = "arthur", language: str = "asl", **kwargs: Any
347
+ ) -> EchoFrameSource:
348
+ """Shortcut: ``EchoFrameSource(client.echo.stream(avatar=..., language=...), **kwargs)``."""
349
+ return cls(client.echo.stream(avatar=avatar, language=language), **kwargs)
350
+
351
+ # -- control ---------------------------------------------------------------
352
+ @property
353
+ def is_signing(self) -> bool:
354
+ """True while a word is playing or queued."""
355
+ return self._word is not None or bool(self._queue)
356
+
357
+ def push_text(self, chunk: str) -> None:
358
+ self._ensure_events()
359
+ self.stream.push_text(chunk)
360
+
361
+ def flush(self) -> None:
362
+ self._ensure_events()
363
+ self.stream.flush()
364
+
365
+ def interrupt(self) -> None:
366
+ """Stops signing now and crossfades back to the idle loop."""
367
+ self.stream.interrupt()
368
+ self._drop_words()
369
+ if self._word is not None:
370
+ self._close_word(self._word)
371
+ self._word = None
372
+ self._start_fade()
373
+
374
+ async def aclose(self) -> None:
375
+ if self._closed:
376
+ return
377
+ self._closed = True
378
+ self.stream.interrupt()
379
+ await self.stream.aclose()
380
+ if self._events_task is not None:
381
+ self._events_task.cancel()
382
+ with contextlib.suppress(asyncio.CancelledError):
383
+ await self._events_task
384
+ self._drop_words()
385
+ if self._word is not None:
386
+ self._close_word(self._word)
387
+ self._word = None
388
+ if self._idle_reader is not None:
389
+ self._idle_reader.close()
390
+ if self._idle_task is not None:
391
+ self._idle_task.cancel()
392
+ await self.cache.aclose()
393
+ if self._own_http:
394
+ await self._http.aclose()
395
+
396
+ async def __aenter__(self) -> EchoFrameSource:
397
+ return self
398
+
399
+ async def __aexit__(self, *exc: object) -> None:
400
+ await self.aclose()
401
+
402
+ # -- iteration -------------------------------------------------------------
403
+ def __aiter__(self) -> EchoFrameSource:
404
+ return self
405
+
406
+ async def __anext__(self) -> Frame:
407
+ if self._closed:
408
+ raise StopAsyncIteration
409
+ self._ensure_events()
410
+ if self.realtime:
411
+ await self._pace()
412
+ frame = await self._next_frame()
413
+ if self._fade_left > 0 and self._fade_from is not None:
414
+ a = 1.0 - self._fade_left / (self.crossfade_frames + 1)
415
+ frame = (self._fade_from.astype(np.float32) * (1.0 - a) + frame.astype(np.float32) * a).astype(np.uint8)
416
+ self._fade_left -= 1
417
+ if self._fade_left == 0:
418
+ self._fade_from = None
419
+ self._last = frame
420
+ return frame
421
+
422
+ async def _pace(self) -> None:
423
+ loop = asyncio.get_running_loop()
424
+ now = loop.time()
425
+ if self._t0 is None:
426
+ self._t0, self._n = now, 0
427
+ target = self._t0 + self._n / self.fps
428
+ if target > now:
429
+ await asyncio.sleep(target - now)
430
+ elif now - target > 0.25: # fell behind (slow consumer): resync instead of bursting
431
+ self._t0, self._n = now, 0
432
+ self._n += 1
433
+
434
+ # -- internals ---------------------------------------------------------------
435
+ def _ensure_events(self) -> None:
436
+ if self._events_task is None and not self._closed:
437
+ self._events_task = asyncio.get_running_loop().create_task(self._consume())
438
+
439
+ async def _consume(self) -> None:
440
+ async for ev in self.stream:
441
+ if isinstance(ev, SentenceEvent):
442
+ idle = ev.idle
443
+ if idle and idle.get("url"):
444
+ self._set_idle(idle["url"])
445
+ elif isinstance(ev, ClipEvent):
446
+ word = _word_from_clip(ev.clip)
447
+ for seg in word.segments:
448
+ seg.task = asyncio.get_running_loop().create_task(self.cache.get(seg.url))
449
+ self._queue.append(word)
450
+ elif isinstance(ev, IdleEvent):
451
+ if ev.idle and ev.idle.get("url"):
452
+ self._set_idle(ev.idle["url"])
453
+ elif isinstance(ev, DoneEvent):
454
+ self._stream_done = True
455
+
456
+ def _set_idle(self, url: str) -> None:
457
+ if self._idle_url is not None and ClipCache.key(self._idle_url) == ClipCache.key(url):
458
+ self._idle_url = url # fresh signature, same clip
459
+ return
460
+ self._idle_url = url
461
+ if self._idle_task is not None:
462
+ self._idle_task.cancel()
463
+ self._idle_task = None
464
+ if self._idle_reader is not None:
465
+ self._idle_reader.close()
466
+ self._idle_reader = None
467
+
468
+ def _drop_words(self) -> None:
469
+ while self._queue:
470
+ self._close_word(self._queue.popleft())
471
+
472
+ @staticmethod
473
+ def _close_word(word: _Word) -> None:
474
+ for seg in word.segments:
475
+ if seg.reader is not None:
476
+ seg.reader.close()
477
+ seg.reader = None
478
+ if seg.task is not None and not seg.task.done():
479
+ seg.task.cancel()
480
+
481
+ def _start_fade(self) -> None:
482
+ if self.crossfade_frames > 0:
483
+ self._fade_from = self._last
484
+ self._fade_left = self.crossfade_frames
485
+
486
+ @staticmethod
487
+ def _ready(seg: _Segment) -> bool | None:
488
+ """True when downloaded, False while downloading, None when the download failed."""
489
+ if seg.task is None or not seg.task.done():
490
+ return False
491
+ if seg.task.cancelled() or seg.task.exception() is not None:
492
+ return None
493
+ return True
494
+
495
+ def _reader_for(self, seg: _Segment) -> _Reader:
496
+ if seg.reader is None:
497
+ assert seg.task is not None
498
+ seg.reader = _Reader(seg.task.result(), self._opts, start_s=seg.start_s, end_s=seg.end_s, speed=seg.speed)
499
+ seg.reader.prime()
500
+ return seg.reader
501
+
502
+ def _head_ready(self) -> bool:
503
+ """Drops failed words at the head of the queue; True when the head word can start."""
504
+ while self._queue:
505
+ state = self._ready(self._queue[0].segments[0])
506
+ if state is None:
507
+ self._close_word(self._queue.popleft())
508
+ continue
509
+ return state
510
+ return False
511
+
512
+ def _prime_next(self) -> None:
513
+ """Opens the decoder of what plays next, so switching never waits on a cold decoder."""
514
+ nxt: _Segment | None = None
515
+ if self._word is not None and self._word.pos + 1 < len(self._word.segments):
516
+ nxt = self._word.segments[self._word.pos + 1]
517
+ elif self._queue:
518
+ nxt = self._queue[0].segments[0]
519
+ if nxt is not None and self._ready(nxt):
520
+ self._reader_for(nxt)
521
+
522
+ async def _next_frame(self) -> Frame:
523
+ for _ in range(64): # bounded: each pass either returns a frame or advances state
524
+ if self._word is None:
525
+ if not self.realtime and not self._head_ready() and await self._wait_for_work():
526
+ continue
527
+ if self._head_ready():
528
+ self._word = self._queue.popleft()
529
+ self._start_fade() # idle -> signing
530
+ self._hold = 0
531
+ elif self._queue and self._hold < self.fps:
532
+ # next word still downloading right after signing: hold the last frame briefly
533
+ if self._last is not self._blank and self._hold > 0:
534
+ self._hold += 1
535
+ return self._last
536
+ return await self._idle_frame()
537
+ else:
538
+ return await self._idle_frame()
539
+ word = self._word
540
+ seg = word.segments[word.pos]
541
+ state = self._ready(seg)
542
+ if state is None: # failed download: skip the word
543
+ self._close_word(word)
544
+ self._word = None
545
+ continue
546
+ if state is False:
547
+ if not self.realtime: # offline: wait for the download, never pad with filler
548
+ await self._await_seg(seg)
549
+ continue
550
+ self._hold += 1
551
+ return self._last
552
+ reader = self._reader_for(seg)
553
+ self._prime_next()
554
+ frame = await reader.next()
555
+ if frame is not None:
556
+ return frame
557
+ reader.close()
558
+ seg.reader = None
559
+ word.pos += 1
560
+ if word.pos < len(word.segments):
561
+ continue
562
+ # word finished
563
+ self._word = None
564
+ if self._queue and self._head_ready():
565
+ nxt = self._queue[0]
566
+ self._word = self._queue.popleft()
567
+ if not (word.seamless and nxt.seamless):
568
+ self._start_fade()
569
+ continue
570
+ if self._queue:
571
+ if not self.realtime:
572
+ await self._await_seg(self._queue[0].segments[0])
573
+ continue
574
+ self._hold = 1 # next word is downloading: hold
575
+ return self._last
576
+ self._start_fade() # signing -> idle
577
+ self._hold = 0
578
+ continue
579
+ return self._last
580
+
581
+ @staticmethod
582
+ async def _await_seg(seg: _Segment) -> None:
583
+ if seg.task is not None and not seg.task.done():
584
+ await asyncio.wait({seg.task})
585
+
586
+ async def _wait_for_work(self) -> bool:
587
+ """Offline mode: waits while sentences are in flight or the head word downloads.
588
+
589
+ Returns True when there is a word to play (or a failed one to drop), False when nothing is pending."""
590
+ while not self._closed:
591
+ if self._queue:
592
+ await self._await_seg(self._queue[0].segments[0])
593
+ return True
594
+ if self._stream_done or not self.stream.busy:
595
+ return False
596
+ await asyncio.sleep(0.005) # the event consumer is turning responses into words
597
+ return False
598
+
599
+ async def _idle_frame(self) -> Frame:
600
+ if self._idle_url is None and not self.realtime:
601
+ idle = await self.stream.wait_idle_fetched() # offline: show the avatar, not a blank, from frame 1
602
+ if idle and idle.get("url") and self._idle_url is None:
603
+ self._set_idle(idle["url"])
604
+ if self._idle_url is None:
605
+ return self._last if self._last is not self._blank else self._blank
606
+ if self._idle_task is None:
607
+ self._idle_task = asyncio.get_running_loop().create_task(self.cache.get(self._idle_url))
608
+ if not self._idle_task.done():
609
+ if not self.realtime:
610
+ await asyncio.wait({self._idle_task})
611
+ return await self._idle_frame()
612
+ return self._last
613
+ if self._idle_task.cancelled() or self._idle_task.exception() is not None:
614
+ self._idle_task = None
615
+ self._idle_url = None
616
+ return self._last
617
+ for _ in range(2):
618
+ if self._idle_reader is None:
619
+ self._idle_reader = _Reader(self._idle_task.result(), self._opts, start_s=None, end_s=None, speed=1.0)
620
+ frame = await self._idle_reader.next()
621
+ if frame is not None:
622
+ return frame
623
+ self._idle_reader.close()
624
+ self._idle_reader = None # loop the idle clip
625
+ return self._last