lima-plugin-webrtc 0.1.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.
@@ -0,0 +1,1807 @@
1
+ ############################################################################
2
+ # This file is part of LImA, a Library for Image Acquisition
3
+ #
4
+ # Copyright (C) : 2009-2026
5
+ # European Synchrotron Radiation Facility
6
+ # CS40220 38043 Grenoble Cedex 9
7
+ # FRANCE
8
+ #
9
+ # Contact: lima@esrf.fr
10
+ #
11
+ # This is free software; you can redistribute it and/or modify
12
+ # it under the terms of the GNU General Public License as published by
13
+ # the Free Software Foundation; either version 3 of the License, or
14
+ # (at your option) any later version.
15
+ #
16
+ # This software is distributed in the hope that it will be useful,
17
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
18
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
+ # GNU General Public License for more details.
20
+ #
21
+ # You should have received a copy of the GNU General Public License
22
+ # along with this program; if not, see <http://www.gnu.org/licenses/>.
23
+ ############################################################################
24
+ """
25
+ Low-latency H264/WebRTC video streaming plugin for the LimaCCDs device server.
26
+
27
+ This is the Lima-tango-python <= 1.11 compatible copy: that version's Python
28
+ bindings expose `Lima.Core` (not `lima.core`), with VideoMode members and
29
+ DebModApplication flat on `Core` itself (not nested under `Core.VideoMode` /
30
+ `Core.DebModule` as in 1.12+). Everything else is identical to the 1.12+
31
+ version in ../../lima/server/plugins/H264VideoStream.py -- keep both in sync.
32
+
33
+ Install by copying this file to the `Lima/Server/plugins/` directory of your
34
+ Lima-tango-python 1.11 install (e.g.
35
+ `<env>/lib/python3.x/site-packages/Lima/Server/plugins/H264VideoStream.py`).
36
+
37
+ Polls CtVideo's getLastImage()/getLastImageCounter() directly (in-process,
38
+ no Tango round trip) so frames only cross into Tango for the one-shot WebRTC
39
+ SDP signaling handshake, never for the per-frame media path. CtVideo only
40
+ supports a single registered ImageCallback and LimaCCDs.py already occupies
41
+ it for video_last_image push events, so polling the same accessor
42
+ LimaCCDs.py itself uses is what allows this to coexist with it. Frames are
43
+ only available while the main LimaCCDs device has video_live=True, since
44
+ that is what drives the camera's video acquisition in the first place.
45
+
46
+ Requires the optional dependencies ``aiortc``, ``av`` (PyAV) and ``Pillow``.
47
+ """
48
+
49
+ import ast
50
+ import asyncio
51
+ import collections
52
+ import io
53
+ import operator
54
+ import re
55
+ import threading
56
+ import time
57
+ import traceback
58
+ import uuid
59
+ from fractions import Fraction
60
+
61
+ import numpy
62
+ import PyTango
63
+
64
+ from Lima import Core
65
+ from Lima.Server.plugins.Utils import BasePostProcess
66
+
67
+
68
+ def _debug_log(msg):
69
+ # Bypasses Tango's own logging (level, omniORB thread attachment) so the
70
+ # poll loop's behaviour can be observed unambiguously - a single place to
71
+ # disable (e.g. make a no-op) once no longer needed.
72
+ print("H264VideoStream: %s" % msg)
73
+
74
+
75
+ def _diag_log(msg):
76
+ # Callers gate on the DiagLog device property; the diagnostics are off by default.
77
+ _debug_log("DIAG " + msg)
78
+
79
+
80
+ try:
81
+ import av
82
+ except ImportError:
83
+ av = None
84
+
85
+ try:
86
+ from PIL import Image as PILImage
87
+ from PIL import ImageDraw as PILImageDraw
88
+ from PIL import ImageFont as PILImageFont
89
+ except ImportError:
90
+ PILImage = None
91
+ PILImageDraw = None
92
+ PILImageFont = None
93
+
94
+ try:
95
+ from aiortc import (
96
+ MediaStreamTrack,
97
+ RTCConfiguration,
98
+ RTCIceServer,
99
+ RTCPeerConnection,
100
+ RTCSessionDescription,
101
+ )
102
+ except ImportError:
103
+ MediaStreamTrack = object
104
+ RTCConfiguration = RTCIceServer = RTCPeerConnection = RTCSessionDescription = None
105
+
106
+ try:
107
+ import aiortc.codecs.h264 as _aiortc_h264
108
+ except ImportError:
109
+ _aiortc_h264 = None
110
+
111
+ try:
112
+ import aiortc.codecs as _aiortc_codecs
113
+ from aiortc.rtcrtpparameters import RTCRtpCodecParameters as _RTCRtpCodecParameters
114
+ from aiortc.rtcrtpparameters import RTCRtcpFeedback as _RTCRtcpFeedback
115
+ except ImportError:
116
+ _aiortc_codecs = None
117
+ _RTCRtpCodecParameters = None
118
+ _RTCRtcpFeedback = None
119
+
120
+
121
+ # Only the VideoMode values Basler (and video-capable cameras in general) can
122
+ # actually emit are mapped; ffmpeg's native bayer_* pixel formats let
123
+ # libswscale do demosaicing as part of the yuv420p/rgb24 conversion below, so
124
+ # no custom debayering code is needed.
125
+ _VIDEO_MODE_TO_AV_FORMAT_NAMES = {
126
+ "Y8": "gray",
127
+ "Y16": "gray16le",
128
+ "RGB24": "rgb24",
129
+ "BGR24": "bgr24",
130
+ "RGB32": "rgba",
131
+ "BGR32": "bgra",
132
+ "BAYER_RG8": "bayer_rggb8",
133
+ "BAYER_RG16": "bayer_rggb16le",
134
+ "BAYER_BG8": "bayer_bggr8",
135
+ "BAYER_BG16": "bayer_bggr16le",
136
+ "YUV422PACKED": "uyvy422",
137
+ # Scaled to 16 bits by _y32_to_16bit: libswscale has no 32-bit integer
138
+ # gray input format.
139
+ "Y32": "gray16le",
140
+ }
141
+
142
+
143
+ def _build_video_mode_table():
144
+ table = {}
145
+ for mode_name, av_format in _VIDEO_MODE_TO_AV_FORMAT_NAMES.items():
146
+ # VideoMode members are flat on Core itself in <=1.11 (Core.Y8),
147
+ # not nested under Core.VideoMode as in 1.12+.
148
+ mode = getattr(Core, mode_name, None)
149
+ if mode is not None:
150
+ table[mode] = av_format
151
+ return table
152
+
153
+
154
+ _Y32_MODE = getattr(Core, "Y32", None)
155
+
156
+ # 16-bit-container video modes: the camera's actual sensor depth (e.g. a
157
+ # Basler 12-bit sensor reported as BAYER_RG16) can be less than 16 bits, with
158
+ # the raw values left unscaled in the low bits of each 16-bit sample - same
159
+ # issue and fix (data << (16 - bpp)) independently implemented by both
160
+ # daiquiri's parse_video_frame() and video-streamer-mpeg's CameraBase.frame().
161
+ _SIXTEEN_BIT_AV_FORMATS = frozenset({"gray16le", "bayer_rggb16le", "bayer_bggr16le"})
162
+
163
+
164
+ def _build_image_type_to_bpp_table():
165
+ table = {}
166
+ for bpp in (8, 10, 12, 14, 16):
167
+ # ImageType members are flat on Core itself in <=1.11 (Core.Bpp12),
168
+ # not nested under Core.ImageType as in 1.12+.
169
+ image_type = getattr(Core, "Bpp%d" % bpp, None)
170
+ if image_type is not None:
171
+ table[image_type] = bpp
172
+ return table
173
+
174
+
175
+ _NORMALIZE_MODES = ("off", "minmax", "sigma3")
176
+
177
+ # Formats where a global min/max (or mean/stddev) contrast stretch is
178
+ # meaningful. For RGB/BGR/RGBA/BGRA, mono and Bayer (raw mosaic,
179
+ # pre-demosaic), a single flat stretch across every byte is color-neutral:
180
+ # the same vmin/vmax applies identically regardless of channel, so it can't
181
+ # introduce a color cast. YUV422PACKED is handled separately below, since it
182
+ # interleaves luma and chroma - different kinds of value on different
183
+ # scales - which a flat stretch would corrupt rather than just enhance.
184
+ _NORMALIZABLE_AV_FORMATS = frozenset(
185
+ {
186
+ "gray",
187
+ "gray16le",
188
+ "bayer_rggb8",
189
+ "bayer_rggb16le",
190
+ "bayer_bggr8",
191
+ "bayer_bggr16le",
192
+ "rgb24",
193
+ "bgr24",
194
+ "rgba",
195
+ "bgra",
196
+ "uyvy422",
197
+ }
198
+ )
199
+
200
+
201
+ def _stretch_range(data, max_value, vmin, vmax):
202
+ """Linearly map [vmin, vmax] to [0, max_value], clipping outside values."""
203
+ # float64 (not float32) and explicit rounding (astype() truncates, not
204
+ # rounds) - otherwise values meant to land exactly on max_value can come
205
+ # out one short (e.g. 65534 instead of 65535) from rounding error.
206
+ return numpy.clip(
207
+ numpy.round((data.astype(numpy.float64) - vmin) * (max_value / (vmax - vmin))),
208
+ 0,
209
+ max_value,
210
+ )
211
+
212
+
213
+ def _normalize_params(buffer, av_format, is_16bit, mode):
214
+ """The (vmin, vmax) of a contrast stretch, or None if the range is flat."""
215
+ data = numpy.frombuffer(buffer, dtype="<u2" if is_16bit else numpy.uint8)
216
+ if av_format == "uyvy422":
217
+ # UYVY packs U0 Y0 V0 Y1 per 4 bytes: luma is every odd byte,
218
+ # chroma every even byte. Only luma gets stretched; U/V are left
219
+ # untouched since they're not on the same scale as intensity.
220
+ data = data[1::2]
221
+ return _stretch_params(data, mode)
222
+
223
+
224
+ def _stretch_params(data, mode):
225
+ """The (vmin, vmax) of a minmax or sigma3 stretch, or None if the range is flat."""
226
+ if mode == "minmax":
227
+ vmin, vmax = float(data.min()), float(data.max())
228
+ else: # sigma3
229
+ mean, std = float(data.mean()), float(data.std())
230
+ vmin, vmax = mean - 3 * std, mean + 3 * std
231
+ if vmax <= vmin:
232
+ return None
233
+ return vmin, vmax
234
+
235
+
236
+ def _y32_to_16bit(buffer, normalize_mode):
237
+ """Y32 pixels as gray16le bytes, stretched from the frame's own range.
238
+
239
+ A 32-bit container says nothing about the range actually used, so the
240
+ frame is mapped from 0..max (or the normalize range) to the full 16 bits.
241
+ The stretch is computed on the 32-bit values, before any precision is lost.
242
+ """
243
+ data = numpy.frombuffer(buffer, dtype="<u4")
244
+ params = None
245
+ if normalize_mode != "off":
246
+ params = _stretch_params(data, normalize_mode)
247
+ if params is None:
248
+ vmax = float(data.max())
249
+ if vmax == 0:
250
+ return numpy.zeros(data.shape, dtype="<u2").tobytes()
251
+ params = (0.0, vmax)
252
+ return _stretch_range(data, 65535, *params).astype("<u2").tobytes()
253
+
254
+
255
+ def _apply_normalize(buffer, av_format, is_16bit, params):
256
+ if params is None:
257
+ return buffer
258
+ vmin, vmax = params
259
+ dtype = "<u2" if is_16bit else numpy.uint8
260
+ max_value = 65535 if is_16bit else 255
261
+ data = numpy.frombuffer(buffer, dtype=dtype)
262
+
263
+ if av_format == "uyvy422":
264
+ out = data.copy()
265
+ out[1::2] = _stretch_range(data[1::2], max_value, vmin, vmax).astype(dtype)
266
+ return out.tobytes()
267
+
268
+ return _stretch_range(data, max_value, vmin, vmax).astype(dtype).tobytes()
269
+
270
+
271
+ def _normalize_buffer(buffer, av_format, is_16bit, mode):
272
+ return _apply_normalize(
273
+ buffer,
274
+ av_format,
275
+ is_16bit,
276
+ _normalize_params(buffer, av_format, is_16bit, mode),
277
+ )
278
+
279
+
280
+ # Lima's Rotation_90 is clockwise; maps each mode to the counter-clockwise
281
+ # quarter turns numpy.rot90 expects.
282
+ def _build_rotation_table():
283
+ table = {}
284
+ for name, turns in (("Rotation_90", -1), ("Rotation_180", 2), ("Rotation_270", 1)):
285
+ mode = getattr(Core, name, None)
286
+ if mode is not None:
287
+ table[mode] = turns
288
+ return table
289
+
290
+
291
+ def _rotate_yuv420p(frame, turns):
292
+ # Chroma subsampling is symmetric under quarter turns, so each plane
293
+ # rotates independently.
294
+ planes = [
295
+ numpy.ascontiguousarray(
296
+ numpy.rot90(
297
+ numpy.frombuffer(p, numpy.uint8).reshape(p.height, p.line_size)[
298
+ :, : p.width
299
+ ],
300
+ turns,
301
+ )
302
+ )
303
+ for p in frame.planes
304
+ ]
305
+ height, width = planes[0].shape
306
+ rotated = av.VideoFrame(width, height, "yuv420p")
307
+ for plane, data in zip(rotated.planes, planes):
308
+ padded = numpy.zeros((plane.height, plane.line_size), numpy.uint8)
309
+ padded[:, : plane.width] = data
310
+ plane.update(padded.tobytes())
311
+ return rotated
312
+
313
+
314
+ _BYTES_PER_PIXEL = {
315
+ "gray": 1,
316
+ "gray16le": 2,
317
+ "bayer_rggb8": 1,
318
+ "bayer_rggb16le": 2,
319
+ "bayer_bggr8": 1,
320
+ "bayer_bggr16le": 2,
321
+ "rgb24": 3,
322
+ "bgr24": 3,
323
+ "rgba": 4,
324
+ "bgra": 4,
325
+ "uyvy422": 2,
326
+ }
327
+
328
+ _VIEW_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+$")
329
+ _FRACTION_PATTERN = re.compile(r"^\d+(\.\d+)?$")
330
+
331
+ # crop is kept as the four unevaluated w:h:x:y expressions and size as the two
332
+ # unevaluated w:h ones (None when unset); max_w/max_h of 0 mean no limit.
333
+ _View = collections.namedtuple("_View", "name crop max_w max_h size", defaults=(None,))
334
+
335
+
336
+ def _eval_size_expr(expr, in_w, in_h):
337
+ """Evaluate an ffmpeg-style size expression (numbers, in_w, in_h, + - * /)."""
338
+ ops = {
339
+ ast.Add: operator.add,
340
+ ast.Sub: operator.sub,
341
+ ast.Mult: operator.mul,
342
+ ast.Div: operator.truediv,
343
+ }
344
+ names = {"in_w": in_w, "in_h": in_h}
345
+
346
+ def walk(node):
347
+ if isinstance(node, ast.Expression):
348
+ return walk(node.body)
349
+ if (
350
+ isinstance(node, ast.Constant)
351
+ and isinstance(node.value, (int, float))
352
+ and not isinstance(node.value, bool)
353
+ ):
354
+ return node.value
355
+ if isinstance(node, ast.Name) and node.id in names:
356
+ return names[node.id]
357
+ if isinstance(node, ast.BinOp) and type(node.op) in ops:
358
+ return ops[type(node.op)](walk(node.left), walk(node.right))
359
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
360
+ value = walk(node.operand)
361
+ return -value if isinstance(node.op, ast.USub) else value
362
+ raise ValueError("unsupported expression %r" % expr)
363
+
364
+ try:
365
+ tree = ast.parse(expr.strip(), mode="eval")
366
+ return walk(tree)
367
+ except SyntaxError:
368
+ raise ValueError("invalid expression %r" % expr)
369
+ except ZeroDivisionError:
370
+ raise ValueError("division by zero in %r" % expr)
371
+
372
+
373
+ def _parse_views(entries):
374
+ """Parse StreamViews entries ('name; crop=w:h:x:y; size=w:h; max=WxH').
375
+
376
+ The shorthands 'scale/N' (1/N of the frame size) and 'crop/N' (centred crop
377
+ of 1/N of each dimension) expand to the matching size and crop.
378
+
379
+ Returns ({name: _View}, [problem, ...]); bad entries are skipped.
380
+ """
381
+ views, problems = {}, []
382
+ for entry in entries:
383
+ name, *options = [part.strip() for part in entry.split(";")]
384
+ if not _VIEW_NAME_PATTERN.match(name):
385
+ problems.append("invalid view name %r" % name)
386
+ continue
387
+ if name in views:
388
+ problems.append("duplicate view %r" % name)
389
+ continue
390
+ crop, size, max_w, max_h = None, None, 0, 0
391
+ try:
392
+ for option in filter(None, options):
393
+ if "=" not in option and "/" in option:
394
+ key, _, divisor = (part.strip() for part in option.partition("/"))
395
+ key = key.lower()
396
+ if key not in ("crop", "scale"):
397
+ raise ValueError("unknown option %r" % option)
398
+ if not _FRACTION_PATTERN.match(divisor) or float(divisor) < 1:
399
+ raise ValueError("%s/N needs a number N of 1 or more" % key)
400
+ if key == "crop":
401
+ if crop is not None:
402
+ raise ValueError("crop given twice")
403
+ crop = (
404
+ "in_w/%s" % divisor,
405
+ "in_h/%s" % divisor,
406
+ "(in_w-in_w/%s)/2" % divisor,
407
+ "(in_h-in_h/%s)/2" % divisor,
408
+ )
409
+ else:
410
+ if size is not None:
411
+ raise ValueError("size given twice")
412
+ size = ("in_w/%s" % divisor, "in_h/%s" % divisor)
413
+ continue
414
+ key, _, value = option.partition("=")
415
+ key, value = key.strip().lower(), value.strip()
416
+ if key == "crop":
417
+ if crop is not None:
418
+ raise ValueError("crop given twice")
419
+ fields = tuple(f.strip() for f in value.split(":"))
420
+ if len(fields) != 4:
421
+ raise ValueError("crop must be w:h:x:y")
422
+ for field in fields:
423
+ _eval_size_expr(field, 1, 1)
424
+ crop = fields
425
+ elif key == "size":
426
+ if size is not None:
427
+ raise ValueError("size given twice")
428
+ fields = tuple(f.strip() for f in value.split(":"))
429
+ if len(fields) != 2:
430
+ raise ValueError("size must be w:h")
431
+ for field in fields:
432
+ _eval_size_expr(field, 1, 1)
433
+ size = fields
434
+ elif key == "max":
435
+ width, separator, height = value.lower().partition("x")
436
+ max_w, max_h = int(width), int(height)
437
+ if not separator or max_w <= 0 or max_h <= 0:
438
+ raise ValueError("max must be WxH")
439
+ else:
440
+ raise ValueError("unknown option %r" % key)
441
+ except ValueError as e:
442
+ problems.append("view %r: %s" % (name, e))
443
+ continue
444
+ views[name] = _View(name, crop, max_w, max_h, size)
445
+ return views, problems
446
+
447
+
448
+ def _resolve_crop(crop, in_w, in_h):
449
+ """Evaluate a crop to an even-aligned (x, y, w, h) inside an in_w x in_h frame."""
450
+ width, height, x, y = (_eval_size_expr(field, in_w, in_h) for field in crop)
451
+ # Even values keep the Bayer pattern and yuv420p chroma pairs aligned.
452
+ x, y, width, height = (int(round(v)) & ~1 for v in (x, y, width, height))
453
+ if (
454
+ width <= 0
455
+ or height <= 0
456
+ or x < 0
457
+ or y < 0
458
+ or x + width > in_w
459
+ or y + height > in_h
460
+ ):
461
+ raise ValueError(
462
+ "crop %s is outside the %dx%d frame" % (":".join(crop), in_w, in_h)
463
+ )
464
+ return x, y, width, height
465
+
466
+
467
+ def _displayed_to_sensor_rect(rect, turns, sensor_w, sensor_h):
468
+ """Map a rectangle of the rotated (numpy.rot90 by turns) frame to the sensor frame."""
469
+ x, y, w, h = rect
470
+ turns %= 4
471
+ if turns == 1:
472
+ return sensor_w - y - h, x, h, w
473
+ if turns == 2:
474
+ return sensor_w - x - w, sensor_h - y - h, w, h
475
+ if turns == 3:
476
+ return y, sensor_h - x - w, h, w
477
+ return rect
478
+
479
+
480
+ def _fit_size(width, height, max_w, max_h):
481
+ if max_w <= 0 or max_h <= 0 or (width <= max_w and height <= max_h):
482
+ return width, height
483
+ scale = min(max_w / width, max_h / height)
484
+ # even dimensions are required by yuv420p's 2x2 chroma subsampling
485
+ return int(width * scale) & ~1, int(height * scale) & ~1
486
+
487
+
488
+ def _view_output_size(view, displayed_w, displayed_h):
489
+ """The view's displayed crop rectangle (or None) and output size."""
490
+ rect = _resolve_crop(view.crop, displayed_w, displayed_h) if view.crop else None
491
+ out_w, out_h = (rect[2], rect[3]) if rect else (displayed_w, displayed_h)
492
+ if view.size:
493
+ # in_w/in_h are the size of the cropped region, as for ffmpeg's scale.
494
+ out_w, out_h = (
495
+ int(round(_eval_size_expr(f, out_w, out_h))) & ~1 for f in view.size
496
+ )
497
+ if out_w <= 0 or out_h <= 0:
498
+ raise ValueError("size %s is not positive" % ":".join(view.size))
499
+ width, height = _fit_size(out_w, out_h, view.max_w, view.max_h)
500
+ return rect, width, height
501
+
502
+
503
+ def _crop_bytes(buffer, av_format, width, height, x, y, w, h):
504
+ bpp = _BYTES_PER_PIXEL[av_format]
505
+ pixels = numpy.frombuffer(buffer, dtype=numpy.uint8).reshape(height, width * bpp)
506
+ return numpy.ascontiguousarray(pixels[y : y + h, x * bpp : (x + w) * bpp]).tobytes()
507
+
508
+
509
+ def _frame_from_bytes(av_format, width, height, buffer):
510
+ """An av.VideoFrame holding tightly packed pixel bytes.
511
+
512
+ PyAV pads each row to an alignment boundary, so a width whose row size is
513
+ not aligned (typical for a crop) cannot take the bytes as they are.
514
+ """
515
+ frame = av.VideoFrame(width=width, height=height, format=av_format)
516
+ plane = frame.planes[0]
517
+ row_size = width * _BYTES_PER_PIXEL[av_format]
518
+ if plane.line_size == row_size:
519
+ plane.update(buffer)
520
+ else:
521
+ padded = numpy.zeros((height, plane.line_size), dtype=numpy.uint8)
522
+ padded[:, :row_size] = numpy.frombuffer(buffer, dtype=numpy.uint8).reshape(
523
+ height, row_size
524
+ )
525
+ plane.update(padded.tobytes())
526
+ return frame
527
+
528
+
529
+ class _RawFrame:
530
+ """A camera frame from which each view takes its (cropped) region."""
531
+
532
+ def __init__(self, buffer, av_format, width, height, bpp, normalize_mode):
533
+ self.buffer = buffer
534
+ self.av_format = av_format
535
+ self.width = width
536
+ self.height = height
537
+ self.bpp = bpp
538
+ self.normalize_mode = normalize_mode
539
+ self.sixteen_bit = av_format in _SIXTEEN_BIT_AV_FORMATS
540
+ self.__norm_params = None
541
+ self.__norm_ready = False
542
+
543
+ def region(self, rect=None):
544
+ """Pixel bytes of rect (x, y, w, h) with bit depth scaling or normalize applied."""
545
+ buffer = self.buffer
546
+ if rect is not None:
547
+ buffer = _crop_bytes(buffer, self.av_format, self.width, self.height, *rect)
548
+ if self.normalize_mode != "off":
549
+ if not self.__norm_ready:
550
+ # Statistics come from the whole frame, so every view gets the
551
+ # same mapping. Stretching to the observed range already brings
552
+ # values to full scale, making the bpp left-shift redundant.
553
+ self.__norm_params = _normalize_params(
554
+ self.buffer, self.av_format, self.sixteen_bit, self.normalize_mode
555
+ )
556
+ self.__norm_ready = True
557
+ return _apply_normalize(
558
+ buffer, self.av_format, self.sixteen_bit, self.__norm_params
559
+ )
560
+ if self.sixteen_bit and self.bpp is not None and self.bpp < 16:
561
+ # e.g. a 12-bit sensor reported as BAYER_RG16 leaves values
562
+ # unscaled in the low bits of each 16-bit sample, which
563
+ # renders as near-black without this.
564
+ return (
565
+ (numpy.frombuffer(buffer, dtype="<u2") << numpy.uint16(16 - self.bpp))
566
+ .astype("<u2")
567
+ .tobytes()
568
+ )
569
+ return buffer
570
+
571
+
572
+ def _set_result_if_pending(future, value):
573
+ if not future.done():
574
+ future.set_result(value)
575
+
576
+
577
+ def _missing_dependencies(**modules):
578
+ # Reports exactly which import(s) failed, since av/aiortc/Pillow are
579
+ # independent and any one of them can be missing without the others.
580
+ return [name for name, mod in modules.items() if mod is None]
581
+
582
+
583
+ def _filter_sdp_candidates(sdp, keep_address):
584
+ # aioice enumerates every local interface for host candidates (no
585
+ # built-in way to exclude one, e.g. a Docker bridge - see
586
+ # https://github.com/aiortc/aioice/issues/2), so unwanted ones are
587
+ # dropped here instead. No-op when keep_address is unset.
588
+ if not keep_address:
589
+ return sdp
590
+ lines = []
591
+ for line in sdp.split("\r\n"):
592
+ if line.startswith("a=candidate:"):
593
+ fields_ = line.split()
594
+ if len(fields_) > 4 and fields_[4] != keep_address:
595
+ continue
596
+ lines.append(line)
597
+ return "\r\n".join(lines)
598
+
599
+
600
+ def _strip_end_of_candidates(sdp):
601
+ # On a=end-of-candidates, aioice prunes every ICE component for which no
602
+ # remote candidate was added, and the server's own candidates are only
603
+ # gathered afterwards, for the surviving components. Firefox offers
604
+ # mDNS (<uuid>.local) host candidates, which the server cannot resolve,
605
+ # so no remote candidate is added, every component is pruned, and the
606
+ # answer carries zero candidates - aiortc then never starts ICE. Without
607
+ # the line the components are kept, so the answer always carries the
608
+ # server's candidates and the browser can open the connection to it.
609
+ return "\r\n".join(
610
+ line for line in sdp.split("\r\n") if line != "a=end-of-candidates"
611
+ )
612
+
613
+
614
+ # Verified against FFmpeg's libavcodec/h264_levels.c (ITU-T H.264 Annex A
615
+ # Table A-1) - MaxFS (max frame size) in 16x16 macroblocks, per level. aiortc
616
+ # hardcodes level 3.1 (MaxFS 3600) regardless of actual resolution; this is
617
+ # used to only raise it when the camera's real resolution requires more.
618
+ _H264_LEVEL_MAX_MACROBLOCKS = (
619
+ ("31", 3600),
620
+ ("32", 5120),
621
+ ("41", 8192),
622
+ ("42", 8704),
623
+ ("50", 22080),
624
+ ("51", 36864),
625
+ )
626
+
627
+
628
+ def _required_h264_level(width, height):
629
+ macroblocks = ((width + 15) // 16) * ((height + 15) // 16)
630
+ for level, max_macroblocks in _H264_LEVEL_MAX_MACROBLOCKS:
631
+ if macroblocks <= max_macroblocks:
632
+ return level
633
+ return _H264_LEVEL_MAX_MACROBLOCKS[-1][0]
634
+
635
+
636
+ # aiortc's own _encode_frame sets only {"level": "31", "tune": "zerolatency"},
637
+ # leaving every other libx264 option (preset, aq-mode, aq-strength...) at
638
+ # libx264's own built-in defaults. These are that same default preset/aq
639
+ # config, verified against the installed libx264 (ultrafast..veryslow is a
640
+ # pure CPU-vs-compression-efficiency tradeoff, not a latency one - tune
641
+ # zerolatency's bframes=0/rc-lookahead=0 hold regardless of preset); used to
642
+ # detect when every H264 encoder property is at its default, so the encoder
643
+ # patch can be skipped entirely rather than reimplementing aiortc's own
644
+ # method for no behavioral change.
645
+ _H264_DEFAULT_PRESET = "medium"
646
+ _H264_DEFAULT_AQ_MODE = 1
647
+ _H264_DEFAULT_AQ_STRENGTH = 1.0
648
+
649
+
650
+ # Profile name -> (libx264 profile, profile-level-id prefixes). aiortc only
651
+ # negotiates an exactly matching profile, and browsers offer High as either
652
+ # plain High (6400) or Constrained High (640c), so both are registered.
653
+ _H264_PROFILES = {
654
+ "baseline": ("Baseline", ("42e0",)),
655
+ "high": ("High", ("6400", "640c")),
656
+ }
657
+ _H264_DEFAULT_PROFILE = "baseline"
658
+
659
+
660
+ def _make_h264_encode_frame(
661
+ level, preset, aq_mode, aq_strength, profile, threads, diag=False
662
+ ):
663
+ # A copy of aiortc.codecs.h264.H264Encoder._encode_frame (aiortc==1.15.0)
664
+ # with the hardcoded "level": "31" replaced, preset/aq-mode/aq-strength
665
+ # added and the profile parameterised - level/profile are inline literals
666
+ # there, not
667
+ # module constants like MIN_BITRATE/MAX_BITRATE, so there's no way to
668
+ # override just that value without replacing the whole method. This
669
+ # pins to that exact method body: if a future aiortc release changes
670
+ # it, this silently stops reflecting those changes.
671
+ import fractions as _fractions
672
+
673
+ def _encode_frame(self, frame, force_keyframe):
674
+ if self.codec and (
675
+ frame.width != self.codec.width
676
+ or frame.height != self.codec.height
677
+ or abs(self.target_bitrate - self.codec.bit_rate) / self.codec.bit_rate
678
+ > 0.1
679
+ ):
680
+ self.buffer_data = b""
681
+ self.buffer_pts = None
682
+ self.codec = None
683
+
684
+ if force_keyframe:
685
+ frame.pict_type = av.video.frame.PictureType.I
686
+ else:
687
+ frame.pict_type = av.video.frame.PictureType.NONE
688
+
689
+ if self.codec is None:
690
+ self.codec = av.CodecContext.create("libx264", "w")
691
+ self.codec.width = frame.width
692
+ self.codec.height = frame.height
693
+ self.codec.bit_rate = self.target_bitrate
694
+ self.codec.pix_fmt = "yuv420p"
695
+ self.codec.framerate = _fractions.Fraction(_aiortc_h264.MAX_FRAME_RATE, 1)
696
+ self.codec.time_base = _fractions.Fraction(1, _aiortc_h264.MAX_FRAME_RATE)
697
+ self.codec.options = {
698
+ "level": _required_h264_level(frame.width, frame.height),
699
+ "tune": "zerolatency",
700
+ "preset": preset,
701
+ "aq-mode": str(aq_mode),
702
+ "aq-strength": str(aq_strength),
703
+ }
704
+ self.codec.profile = profile
705
+ if threads > 0:
706
+ self.codec.thread_count = threads
707
+ if diag:
708
+ _diag_log(
709
+ "encoder created %dx%d level=%s target=%d kbps"
710
+ % (
711
+ frame.width,
712
+ frame.height,
713
+ self.codec.options["level"],
714
+ self.target_bitrate // 1000,
715
+ )
716
+ )
717
+
718
+ data_to_send = b""
719
+ for package in self.codec.encode(frame):
720
+ data_to_send += bytes(package)
721
+
722
+ if diag:
723
+ if not getattr(self, "_diag_frames", 0):
724
+ self._diag_t0 = time.monotonic()
725
+ self._diag_frames = getattr(self, "_diag_frames", 0) + 1
726
+ self._diag_bytes = getattr(self, "_diag_bytes", 0) + len(data_to_send)
727
+ if self._diag_frames % 120 == 0:
728
+ elapsed = max(time.monotonic() - self._diag_t0, 1e-6)
729
+ _diag_log(
730
+ "encoded 120 frames in %.1f s (%.1f fps): avg %.1f KB/frame, sending %d kbps, target %d kbps"
731
+ % (
732
+ elapsed,
733
+ self._diag_frames / elapsed,
734
+ self._diag_bytes / self._diag_frames / 1000,
735
+ self._diag_bytes * 8 / elapsed / 1000,
736
+ self.target_bitrate // 1000,
737
+ )
738
+ )
739
+ self._diag_frames = self._diag_bytes = 0
740
+
741
+ if data_to_send:
742
+ yield from self._split_bitstream(data_to_send)
743
+
744
+ return _encode_frame
745
+
746
+
747
+ def _register_h264_capability(profile_id_prefix, level):
748
+ # Registers a new H264 capability (so setCodecPreferences can select it)
749
+ # alongside aiortc's hardcoded Baseline Level 3.1 ones - needed whenever
750
+ # the encoder actually encodes a different profile or a level above 3.1,
751
+ # otherwise the declared and actual values would mismatch. Not needed for
752
+ # preset/aq-mode/aq-strength alone, since those aren't declared in SDP.
753
+ # Idempotent: safe to call again (e.g. a Tango Init re-running
754
+ # init_device on the same process) without accumulating duplicates.
755
+ profile_level_id = "%s%02x" % (profile_id_prefix, int(level))
756
+ already_registered = any(
757
+ not _aiortc_codecs.is_rtx(c)
758
+ and c.parameters.get("profile-level-id") == profile_level_id
759
+ for c in _aiortc_codecs.CODECS["video"]
760
+ )
761
+ if not already_registered:
762
+ next_pt = max(c.payloadType for c in _aiortc_codecs.CODECS["video"]) + 1
763
+ _aiortc_codecs.CODECS["video"] += [
764
+ _RTCRtpCodecParameters(
765
+ mimeType="video/H264",
766
+ clockRate=90000,
767
+ payloadType=next_pt,
768
+ rtcpFeedback=[
769
+ _RTCRtcpFeedback(type="nack"),
770
+ _RTCRtcpFeedback(type="nack", parameter="pli"),
771
+ _RTCRtcpFeedback(type="goog-remb"),
772
+ ],
773
+ parameters={
774
+ "level-asymmetry-allowed": "1",
775
+ "packetization-mode": "1",
776
+ "profile-level-id": profile_level_id,
777
+ },
778
+ ),
779
+ _RTCRtpCodecParameters(
780
+ mimeType="video/rtx",
781
+ clockRate=90000,
782
+ payloadType=next_pt + 1,
783
+ parameters={"apt": next_pt},
784
+ ),
785
+ ]
786
+
787
+
788
+ def _restrict_h264_capabilities(profile_id_prefixes):
789
+ # Drops H264 capabilities of any other profile (and their RTX pairs) so
790
+ # the negotiated codec always matches the profile the encoder produces.
791
+ codecs = _aiortc_codecs.CODECS["video"]
792
+ dropped = {
793
+ c.payloadType
794
+ for c in codecs
795
+ if c.mimeType.lower() == "video/h264"
796
+ and c.parameters.get("profile-level-id", "")[:4].lower()
797
+ not in profile_id_prefixes
798
+ }
799
+ codecs[:] = [
800
+ c
801
+ for c in codecs
802
+ if c.payloadType not in dropped
803
+ and not (_aiortc_codecs.is_rtx(c) and c.parameters.get("apt") in dropped)
804
+ ]
805
+
806
+
807
+ def _configure_h264_encoder(
808
+ level, preset, aq_mode, aq_strength, profile_name, threads, diag=False
809
+ ):
810
+ libx264_profile, prefixes = _H264_PROFILES[profile_name]
811
+ if profile_name != _H264_DEFAULT_PROFILE:
812
+ for prefix in prefixes:
813
+ _register_h264_capability(prefix, level)
814
+ _restrict_h264_capabilities(prefixes)
815
+ elif level != "31":
816
+ _register_h264_capability(prefixes[0], level)
817
+ _aiortc_h264.H264Encoder._encode_frame = _make_h264_encode_frame(
818
+ level, preset, aq_mode, aq_strength, libx264_profile, threads, diag
819
+ )
820
+
821
+
822
+ _ICE_GATHERING_TIMEOUT = 3.0
823
+
824
+
825
+ async def _wait_for_ice_gathering_complete(pc, timeout=_ICE_GATHERING_TIMEOUT):
826
+ # JoinStream is a one-shot command with no trickle-ICE channel back to
827
+ # the client, so the answer returned here must already contain every
828
+ # local candidate - same constraint the client-side offer already
829
+ # accounts for (see WebRTCVideoImage.js's own wait). Without this,
830
+ # reading pc.localDescription.sdp races ICE gathering: it can return an
831
+ # answer with zero candidates if gathering (e.g. a STUN round trip)
832
+ # hasn't finished yet, with no way to send the rest afterwards.
833
+ if pc.iceGatheringState == "complete":
834
+ return
835
+ done = asyncio.get_event_loop().create_future()
836
+
837
+ @pc.on("icegatheringstatechange")
838
+ def on_icegatheringstatechange():
839
+ if pc.iceGatheringState == "complete":
840
+ _set_result_if_pending(done, None)
841
+
842
+ try:
843
+ await asyncio.wait_for(done, timeout)
844
+ except asyncio.TimeoutError:
845
+ pass
846
+
847
+
848
+ class _LatestFrameBox:
849
+ """Hands the newest av.VideoFrame from the Lima callback thread to the
850
+ asyncio loop, dropping anything older rather than queueing it."""
851
+
852
+ def __init__(self, loop):
853
+ self.__loop = loop
854
+ self.__lock = threading.Lock()
855
+ self.__frame = None
856
+ self.__waiters = []
857
+
858
+ def publish(self, frame):
859
+ with self.__lock:
860
+ self.__frame = frame
861
+ waiters, self.__waiters = self.__waiters, []
862
+ for future in waiters:
863
+ self.__loop.call_soon_threadsafe(_set_result_if_pending, future, frame)
864
+
865
+ def clear(self):
866
+ with self.__lock:
867
+ self.__frame = None
868
+
869
+ async def wait_for_frame(self):
870
+ with self.__lock:
871
+ if self.__frame is not None:
872
+ return self.__frame
873
+ future = self.__loop.create_future()
874
+ self.__waiters.append(future)
875
+ return await future
876
+
877
+
878
+ class LimaVideoStreamTrack(MediaStreamTrack):
879
+ kind = "video"
880
+
881
+ _CLOCK_RATE = 90000
882
+
883
+ def __init__(self, frame_box, diag=False):
884
+ super().__init__()
885
+ self.__frame_box = frame_box
886
+ self.__diag = diag
887
+ self.__start_time = None
888
+ self.__time_base = Fraction(1, self._CLOCK_RATE)
889
+ self.__logged_first_recv = False
890
+
891
+ async def recv(self):
892
+ frame = await self.__frame_box.wait_for_frame()
893
+ if self.__diag:
894
+ self.__diag_count = (
895
+ getattr(self, "_LimaVideoStreamTrack__diag_count", 0) + 1
896
+ )
897
+ if self.__diag_count % 120 == 1:
898
+ _diag_log(
899
+ "track pulled %d frames, last %dx%d"
900
+ % (self.__diag_count, frame.width, frame.height)
901
+ )
902
+ if self.__start_time is None:
903
+ self.__start_time = time.time()
904
+ frame.pts = int((time.time() - self.__start_time) * self._CLOCK_RATE)
905
+ frame.time_base = self.__time_base
906
+ if not self.__logged_first_recv:
907
+ self.__logged_first_recv = True
908
+ _debug_log(
909
+ "aiortc pulled its first frame from the track (%dx%d)"
910
+ % (frame.width, frame.height)
911
+ )
912
+ return frame
913
+
914
+
915
+ class _ViewState:
916
+ """One stream view: its frame box, shared by the tracks of its viewers."""
917
+
918
+ def __init__(self, spec, loop):
919
+ self.spec = spec
920
+ self.frame_box = _LatestFrameBox(loop)
921
+ self.logged_first_frame = False
922
+ self.logged_problem = False
923
+
924
+
925
+ class H264VideoStreamDeviceServer(BasePostProcess):
926
+ Core.DEB_CLASS(Core.DebModApplication, "H264VideoStreamDeviceServer")
927
+
928
+ VIDEO_MODE_TO_AV_FORMAT = _build_video_mode_table()
929
+ IMAGE_TYPE_TO_BPP = _build_image_type_to_bpp_table()
930
+ ROTATION_TO_TURNS = _build_rotation_table()
931
+
932
+ def __init__(self, cl, name):
933
+ self.__raw_lock = threading.Lock()
934
+ self.__raw_frame = None # (width, height) of the last real frame
935
+ self.__republish = threading.Event()
936
+
937
+ self.__logged_av_format = False
938
+ self.__logged_bpp_scaling = False
939
+ self.__reformat_threads_supported = True
940
+ self.__logged_frame_stats = False
941
+ self.__logged_rotation_turns = None
942
+ self.__normalize = "off"
943
+ self.__logged_normalize_unsupported = False
944
+
945
+ self.__start_lock = threading.Lock()
946
+ self.__peer_connections = {}
947
+ self.__loop = None
948
+ self.__loop_thread = None
949
+ self.__view_specs = {}
950
+ self.__views = {}
951
+ self.__peer_views = {}
952
+ self.__poll_task = None
953
+
954
+ BasePostProcess.__init__(self, cl, name)
955
+ H264VideoStreamDeviceServer.init_device(self)
956
+
957
+ @Core.DEB_MEMBER_FUNCT
958
+ def init_device(self):
959
+ _debug_log("init_device: entered")
960
+ BasePostProcess.init_device(self)
961
+
962
+ ctControl = _control_ref()
963
+ self.__video = ctControl.video()
964
+ self.__image = ctControl.image()
965
+ # Only a camera's own video interface delivers unrotated frames;
966
+ # frames derived from the acquisition pipeline are already rotated.
967
+ # CtVideo reports no auto-gain mode at all without a hardware video
968
+ # interface.
969
+ gain_modes = getattr(Core.CtVideo, "AutoGainMode", Core.CtVideo)
970
+ self.__hw_video = self.__video.checkAutoGainMode(
971
+ gain_modes.OFF
972
+ ) or self.__video.checkAutoGainMode(gain_modes.ON)
973
+ _debug_log("init_device: hardware video interface=%s" % self.__hw_video)
974
+
975
+ self.__stream_max_fps = float(self.StreamMaxFPS)
976
+
977
+ self.__diag = bool(self.DiagLog)
978
+ if self.__diag:
979
+ _debug_log("DiagLog is on: DIAG lines enabled")
980
+
981
+ # The unnamed default view is the full frame under the MaxStream caps.
982
+ named, problems = _parse_views(self.StreamViews)
983
+ for problem in problems:
984
+ self.warn_stream("H264VideoStream: StreamViews: %s, skipped" % problem)
985
+ self.__view_specs = {
986
+ "": _View("", None, self.MaxStreamWidth, self.MaxStreamHeight)
987
+ }
988
+ self.__view_specs.update(named)
989
+
990
+ def __ensure_started(self):
991
+ # Heavy setup (event loop thread, encoder config, poll loop) is
992
+ # deferred to the first JoinStream so an unused device costs nothing.
993
+ with self.__start_lock:
994
+ if self.__poll_task is not None:
995
+ return
996
+ self.__start()
997
+
998
+ def __start(self):
999
+ if _aiortc_h264 is not None:
1000
+ # aiortc's H264 encoder clamps target_bitrate (driven by the
1001
+ # browser's own REMB congestion-control feedback) to this ceiling
1002
+ # regardless of available bandwidth. It's a plain module global,
1003
+ # read by name at call time, so overriding it here - once, for
1004
+ # the whole process - genuinely raises what REMB can push toward
1005
+ # for every connection, with no per-connection API needed.
1006
+ default_max_bitrate = _aiortc_h264.MAX_BITRATE
1007
+ _aiortc_h264.MAX_BITRATE = int(self.StreamMaxBitrate * 1000)
1008
+ if self.StreamMinBitrate > 0:
1009
+ # The browser's own estimate starts low and grows slowly; each
1010
+ # >10% step rebuilds the encoder, restarting from a keyframe
1011
+ # chosen at that low rate. A floor and start value above it
1012
+ # keeps the quality steady.
1013
+ _aiortc_h264.MIN_BITRATE = int(self.StreamMinBitrate * 1000)
1014
+ _aiortc_h264.DEFAULT_BITRATE = _aiortc_h264.MIN_BITRATE
1015
+ _aiortc_h264.MAX_BITRATE = max(
1016
+ _aiortc_h264.MAX_BITRATE, _aiortc_h264.MIN_BITRATE
1017
+ )
1018
+ _debug_log(
1019
+ "StreamMinBitrate override in use: floor and start %d kbps, ceiling %d kbps"
1020
+ % (self.StreamMinBitrate, _aiortc_h264.MAX_BITRATE // 1000)
1021
+ )
1022
+ if _aiortc_h264.MAX_BITRATE != default_max_bitrate:
1023
+ _debug_log(
1024
+ "StreamMaxBitrate override in use: ceiling %d kbps (aiortc default %d kbps)"
1025
+ % (self.StreamMaxBitrate, default_max_bitrate // 1000)
1026
+ )
1027
+
1028
+ self.__loop = asyncio.new_event_loop()
1029
+
1030
+ def _run_loop():
1031
+ _debug_log("loop thread: starting")
1032
+ try:
1033
+ # Tango device methods (warn_stream, push_change_event,
1034
+ # attribute access) silently no-op when called from a thread
1035
+ # never attached to omniORB, so the loop must run inside
1036
+ # EnsureOmniThread.
1037
+ with PyTango.EnsureOmniThread():
1038
+ _debug_log(
1039
+ "loop thread: inside EnsureOmniThread, calling run_forever"
1040
+ )
1041
+ self.__loop.run_forever()
1042
+ _debug_log("loop thread: run_forever returned")
1043
+ except Exception:
1044
+ _debug_log("loop thread: crashed: %s" % traceback.format_exc())
1045
+
1046
+ self.__loop_thread = threading.Thread(target=_run_loop, daemon=True)
1047
+ self.__loop_thread.start()
1048
+
1049
+ self.__views = {
1050
+ name: _ViewState(spec, self.__loop)
1051
+ for name, spec in self.__view_specs.items()
1052
+ }
1053
+
1054
+ if _aiortc_h264 is not None and _aiortc_codecs is not None:
1055
+ size = self.__image.getImageDim().getSize()
1056
+ width, height = size.getWidth(), size.getHeight()
1057
+ level = _required_h264_level(width, height)
1058
+ preset = self.H264Preset
1059
+ aq_mode = self.H264AqMode
1060
+ aq_strength = self.H264AqStrength
1061
+ threads = max(self.H264Threads, 0)
1062
+ profile = self.H264Profile.lower()
1063
+ if profile not in _H264_PROFILES:
1064
+ self.warn_stream(
1065
+ "H264VideoStream: unknown H264Profile %r (expected one of %s), using %s"
1066
+ % (
1067
+ self.H264Profile,
1068
+ ", ".join(_H264_PROFILES),
1069
+ _H264_DEFAULT_PROFILE,
1070
+ )
1071
+ )
1072
+ profile = _H264_DEFAULT_PROFILE
1073
+ if (
1074
+ profile != _H264_DEFAULT_PROFILE
1075
+ or threads != 0
1076
+ or level != "31"
1077
+ or preset != _H264_DEFAULT_PRESET
1078
+ or aq_mode != _H264_DEFAULT_AQ_MODE
1079
+ or aq_strength != _H264_DEFAULT_AQ_STRENGTH
1080
+ or self.__diag
1081
+ ):
1082
+ _debug_log(
1083
+ "non-default H264 encoder settings (resolution %dx%d "
1084
+ "requires level %s, profile=%s, preset=%s, aq-mode=%s, "
1085
+ "aq-strength=%s, threads=%d), applying"
1086
+ % (
1087
+ width,
1088
+ height,
1089
+ level,
1090
+ profile,
1091
+ preset,
1092
+ aq_mode,
1093
+ aq_strength,
1094
+ threads,
1095
+ )
1096
+ )
1097
+ _configure_h264_encoder(
1098
+ level, preset, aq_mode, aq_strength, profile, threads, self.__diag
1099
+ )
1100
+
1101
+ # CtVideo only supports a single registered ImageCallback, and
1102
+ # LimaCCDs.py already occupies it for video_last_image push events,
1103
+ # so new frames are picked up by polling getLastImage()/
1104
+ # getLastImageCounter() instead - the same accessor LimaCCDs.py
1105
+ # itself uses for reading video_last_image, safe for concurrent use.
1106
+ _debug_log("start: scheduling poll task")
1107
+ self.__poll_task = asyncio.run_coroutine_threadsafe(
1108
+ self.__poll_video(), self.__loop
1109
+ )
1110
+ _debug_log("start: poll task scheduled, done=%s" % self.__poll_task.done())
1111
+
1112
+ async def __poll_video(self):
1113
+ _debug_log("poll_video: coroutine entered")
1114
+ self.warn_stream("H264VideoStream: poll loop started")
1115
+ last_counter = -1
1116
+ # True initially so a camera that starts up already non-live still
1117
+ # gets the fallback frame published immediately, rather than a
1118
+ # client being able to join a stream that stays empty until the
1119
+ # camera first goes live. Safe to assume a real frame size is always
1120
+ # available (see _publish_not_live_frame), so this can't repeat the
1121
+ # earlier guessed-size bug that poisoned the encoder's/browser's
1122
+ # locked-in stream resolution.
1123
+ was_live = True
1124
+ while True:
1125
+ # Everything is inside the try, including the sleep/fps setup -
1126
+ # any uncaught exception here previously killed this coroutine
1127
+ # permanently and silently, since self.__poll_task's result is
1128
+ # never awaited/checked anywhere.
1129
+ try:
1130
+ fps = self.__stream_max_fps if self.__stream_max_fps > 0 else 30.0
1131
+ await asyncio.sleep(1.0 / fps)
1132
+ live = self.__video.getLive()
1133
+ if not live:
1134
+ # video_live=False stops frame production entirely, so
1135
+ # getLastImageCounter() just stops advancing - without
1136
+ # this, the stream would silently freeze on the last
1137
+ # live frame forever, indistinguishable from a genuinely
1138
+ # static (but still live) scene.
1139
+ if was_live or self.__republish.is_set():
1140
+ self.__republish.clear()
1141
+ self._publish_not_live_frame()
1142
+ was_live = False
1143
+ continue
1144
+ was_live = True
1145
+ counter = self.__video.getLastImageCounter()
1146
+ # A viewer that just joined needs the current frame even when
1147
+ # the camera has not produced a new one.
1148
+ if counter == last_counter and not self.__republish.is_set():
1149
+ continue
1150
+ self.__republish.clear()
1151
+ last_counter = counter
1152
+ self._on_new_video_image(self.__video.getLastImage())
1153
+ except Exception:
1154
+ _debug_log("poll_video: exception: %s" % traceback.format_exc())
1155
+ self.warn_stream(
1156
+ "H264VideoStream: failed to poll last video image: %s"
1157
+ % traceback.format_exc()
1158
+ )
1159
+
1160
+ @Core.DEB_MEMBER_FUNCT
1161
+ def delete_device(self):
1162
+ _debug_log(
1163
+ "delete_device: entered, call stack:\n%s"
1164
+ % "".join(traceback.format_stack())
1165
+ )
1166
+ if self.__poll_task is not None:
1167
+ self.__poll_task.cancel()
1168
+ if self.__loop is not None:
1169
+ for pc in list(self.__peer_connections.values()):
1170
+ asyncio.run_coroutine_threadsafe(pc.close(), self.__loop)
1171
+ self.__loop.call_soon_threadsafe(self.__loop.stop)
1172
+ self.__loop_thread.join(timeout=5)
1173
+
1174
+ def __run_coroutine(self, coro):
1175
+ return asyncio.run_coroutine_threadsafe(coro, self.__loop).result()
1176
+
1177
+ def __rtc_configuration(self):
1178
+ if RTCIceServer is None or not self.IceServers:
1179
+ return RTCConfiguration(iceServers=[])
1180
+ return RTCConfiguration(
1181
+ iceServers=[RTCIceServer(urls=u) for u in self.IceServers]
1182
+ )
1183
+
1184
+ # ------------------------------------------------------------------
1185
+ # Frame ingestion (called from the Lima video callback thread)
1186
+ # ------------------------------------------------------------------
1187
+ def __make_raw_frame(self, image):
1188
+ av_format = self.VIDEO_MODE_TO_AV_FORMAT.get(image.mode())
1189
+ if not self.__logged_av_format:
1190
+ self.__logged_av_format = True
1191
+ _debug_log(
1192
+ "image.mode()=%s -> av_format=%s, image_type=%s"
1193
+ % (image.mode(), av_format, self.__image.getImageType())
1194
+ )
1195
+ self.warn_stream(
1196
+ "H264VideoStream: image.mode()=%s -> av_format=%s, image_type=%s"
1197
+ % (image.mode(), av_format, self.__image.getImageType())
1198
+ )
1199
+ if av_format is None:
1200
+ self.warn_stream(
1201
+ "H264VideoStream: unsupported video mode %s" % image.mode()
1202
+ )
1203
+ return None
1204
+
1205
+ buffer = image.buffer()
1206
+ if not buffer:
1207
+ return None
1208
+
1209
+ normalize_mode = self.__normalize
1210
+ if normalize_mode != "off" and av_format not in _NORMALIZABLE_AV_FORMATS:
1211
+ if not self.__logged_normalize_unsupported:
1212
+ self.__logged_normalize_unsupported = True
1213
+ self.warn_stream(
1214
+ "H264VideoStream: normalize is not supported for av_format %s, ignoring"
1215
+ % av_format
1216
+ )
1217
+ normalize_mode = "off"
1218
+
1219
+ if image.mode() == _Y32_MODE:
1220
+ # Already stretched to 16 bits, normalize included.
1221
+ buffer = _y32_to_16bit(buffer, normalize_mode)
1222
+ normalize_mode = "off"
1223
+
1224
+ bpp = None
1225
+ if av_format in _SIXTEEN_BIT_AV_FORMATS:
1226
+ bpp = self.IMAGE_TYPE_TO_BPP.get(self.__image.getImageType())
1227
+ if not self.__logged_bpp_scaling:
1228
+ self.__logged_bpp_scaling = True
1229
+ _debug_log(
1230
+ "image_type=%s -> bpp=%s (scaling %s)"
1231
+ % (
1232
+ self.__image.getImageType(),
1233
+ bpp,
1234
+ "applied" if bpp and bpp < 16 else "skipped",
1235
+ )
1236
+ )
1237
+ self.warn_stream(
1238
+ "H264VideoStream: image_type=%s -> bpp=%s (scaling %s)"
1239
+ % (
1240
+ self.__image.getImageType(),
1241
+ bpp,
1242
+ "applied" if bpp and bpp < 16 else "skipped",
1243
+ )
1244
+ )
1245
+ return _RawFrame(
1246
+ buffer, av_format, image.width(), image.height(), bpp, normalize_mode
1247
+ )
1248
+
1249
+ def _on_new_video_image(self, image):
1250
+ raw = self.__make_raw_frame(image)
1251
+ if raw is None:
1252
+ return
1253
+
1254
+ with self.__raw_lock:
1255
+ self.__raw_frame = (raw.width, raw.height)
1256
+
1257
+ # Views nobody is watching cost nothing: no crop, conversion or
1258
+ # normalize statistics. The poll loop's own interval caps how often
1259
+ # this runs.
1260
+ active = set(self.__peer_views.values())
1261
+ if not active:
1262
+ return
1263
+
1264
+ turns = self.__rotation_turns()
1265
+ for name in active:
1266
+ state = self.__views.get(name)
1267
+ if state is None:
1268
+ continue
1269
+ try:
1270
+ frame = self.__render_view(raw, state, turns)
1271
+ except Exception:
1272
+ if not state.logged_problem:
1273
+ state.logged_problem = True
1274
+ self.warn_stream(
1275
+ "H264VideoStream: failed to render view %r: %s"
1276
+ % (name, traceback.format_exc())
1277
+ )
1278
+ continue
1279
+ if not state.logged_first_frame:
1280
+ state.logged_first_frame = True
1281
+ y_arr = numpy.frombuffer(bytes(frame.planes[0]), dtype=numpy.uint8)
1282
+ _debug_log(
1283
+ "view %r first frame %dx%d: yuv Y-plane min=%d max=%d"
1284
+ % (name, frame.width, frame.height, y_arr.min(), y_arr.max())
1285
+ )
1286
+ state.frame_box.publish(frame)
1287
+ if self.__diag:
1288
+ state.diag_count = getattr(state, "diag_count", 0) + 1
1289
+ if state.diag_count % 120 == 1:
1290
+ _diag_log(
1291
+ "view %r published %d frames, last %dx%d from raw %dx%d"
1292
+ % (
1293
+ name,
1294
+ state.diag_count,
1295
+ frame.width,
1296
+ frame.height,
1297
+ raw.width,
1298
+ raw.height,
1299
+ )
1300
+ )
1301
+
1302
+ def __render_view(self, raw, state, turns):
1303
+ # Crop and size limits are defined on the displayed (rotated) frame.
1304
+ displayed_w, displayed_h = (
1305
+ (raw.height, raw.width) if turns % 2 else (raw.width, raw.height)
1306
+ )
1307
+ rect, target_w, target_h = _view_output_size(
1308
+ state.spec, displayed_w, displayed_h
1309
+ )
1310
+ sensor_rect = (
1311
+ _displayed_to_sensor_rect(rect, turns, raw.width, raw.height)
1312
+ if rect
1313
+ else None
1314
+ )
1315
+ src_w, src_h = (
1316
+ (sensor_rect[2], sensor_rect[3]) if sensor_rect else (raw.width, raw.height)
1317
+ )
1318
+
1319
+ src_frame = _frame_from_bytes(
1320
+ raw.av_format, src_w, src_h, raw.region(sensor_rect)
1321
+ )
1322
+ width, height = (target_h, target_w) if turns % 2 else (target_w, target_h)
1323
+ reformat_args = {"width": width, "height": height, "format": "yuv420p"}
1324
+ if self.H264Threads > 0 and self.__reformat_threads_supported:
1325
+ reformat_args["threads"] = self.H264Threads
1326
+ try:
1327
+ frame = src_frame.reformat(**reformat_args)
1328
+ except TypeError:
1329
+ if "threads" not in reformat_args:
1330
+ raise
1331
+ # Older PyAV releases have no threads argument on reformat.
1332
+ self.__reformat_threads_supported = False
1333
+ self.warn_stream(
1334
+ "H264VideoStream: this PyAV does not support threads on reformat, "
1335
+ "H264Threads applies to the encoder only"
1336
+ )
1337
+ del reformat_args["threads"]
1338
+ frame = src_frame.reformat(**reformat_args)
1339
+ if turns:
1340
+ frame = _rotate_yuv420p(frame, turns)
1341
+ return frame
1342
+
1343
+ def __rotation_turns(self):
1344
+ if not self.__hw_video:
1345
+ turns = 0
1346
+ else:
1347
+ turns = self.ROTATION_TO_TURNS.get(self.__image.getRotation(), 0)
1348
+ if turns != self.__logged_rotation_turns:
1349
+ self.__logged_rotation_turns = turns
1350
+ _debug_log(
1351
+ "rotation: hw_video=%s, lima rotation=%s -> %s"
1352
+ % (
1353
+ self.__hw_video,
1354
+ self.__image.getRotation(),
1355
+ (
1356
+ "applying %d counter-clockwise quarter turn(s)" % (turns % 4)
1357
+ if turns
1358
+ else "not applied"
1359
+ ),
1360
+ )
1361
+ )
1362
+ return turns
1363
+
1364
+ # ------------------------------------------------------------------
1365
+ # WebRTC signaling commands
1366
+ # ------------------------------------------------------------------
1367
+ @Core.DEB_MEMBER_FUNCT
1368
+ def JoinStream(self, offer_sdp):
1369
+ return self.__join(offer_sdp, "", "JoinStream")
1370
+
1371
+ @Core.DEB_MEMBER_FUNCT
1372
+ def JoinStreamView(self, argin):
1373
+ if len(argin) != 2:
1374
+ PyTango.Except.throw_exception(
1375
+ "BadArgument", "expected [offer_sdp, view]", "JoinStreamView"
1376
+ )
1377
+ return self.__join(argin[0], argin[1], "JoinStreamView")
1378
+
1379
+ @Core.DEB_MEMBER_FUNCT
1380
+ def ListStreamViews(self):
1381
+ return [name for name in self.__view_specs if name]
1382
+
1383
+ def __join(self, offer_sdp, view, command):
1384
+ missing = _missing_dependencies(aiortc=RTCPeerConnection, av=av)
1385
+ if missing:
1386
+ PyTango.Except.throw_exception(
1387
+ "MissingDependency",
1388
+ "Missing Python package(s) required by H264VideoStream: %s"
1389
+ % ", ".join(missing),
1390
+ command,
1391
+ )
1392
+ if view not in self.__view_specs:
1393
+ PyTango.Except.throw_exception(
1394
+ "UnknownView",
1395
+ "unknown view %r, available: %s"
1396
+ % (view, ", ".join(repr(n) for n in self.__view_specs if n) or "none"),
1397
+ command,
1398
+ )
1399
+
1400
+ self.__ensure_started()
1401
+
1402
+ # uuid4() is plain Python (no event loop needed), safe to call on
1403
+ # this Tango command thread; everything aiortc-related below is not
1404
+ # and must run on self.__loop's own thread instead (see negotiate()).
1405
+ connection_id = str(uuid.uuid4())
1406
+
1407
+ async def negotiate():
1408
+ pc = RTCPeerConnection(configuration=self.__rtc_configuration())
1409
+ pc.addTrack(LimaVideoStreamTrack(self.__views[view].frame_box, self.__diag))
1410
+ self.__peer_connections[connection_id] = pc
1411
+ self.__peer_views[connection_id] = view
1412
+ self.__republish.set()
1413
+
1414
+ # A client is not guaranteed to call LeaveStream (crash, network
1415
+ # drop, ...), so connectionstatechange is the actual source of
1416
+ # truth: closed/failed are terminal, disconnected can recover
1417
+ # from a brief network blip so it only triggers cleanup after it
1418
+ # has stayed disconnected for DisconnectTimeout seconds.
1419
+ @pc.on("connectionstatechange")
1420
+ async def on_connectionstatechange():
1421
+ if pc.connectionState in ("failed", "closed"):
1422
+ await self.__cleanup_connection(connection_id)
1423
+ elif pc.connectionState == "disconnected":
1424
+ await asyncio.sleep(self.DisconnectTimeout)
1425
+ if pc.connectionState == "disconnected":
1426
+ await self.__cleanup_connection(connection_id)
1427
+
1428
+ offer = RTCSessionDescription(
1429
+ sdp=_strip_end_of_candidates(offer_sdp), type="offer"
1430
+ )
1431
+ await pc.setRemoteDescription(offer)
1432
+ answer = await pc.createAnswer()
1433
+ await pc.setLocalDescription(answer)
1434
+ await _wait_for_ice_gathering_complete(pc)
1435
+
1436
+ unfiltered_sdp = pc.localDescription.sdp
1437
+ candidate_lines = [
1438
+ line
1439
+ for line in unfiltered_sdp.split("\r\n")
1440
+ if line.startswith("a=candidate:")
1441
+ ]
1442
+ _debug_log(
1443
+ "iceGatheringState=%s after wait, %d candidate(s) gathered:\n%s"
1444
+ % (
1445
+ pc.iceGatheringState,
1446
+ len(candidate_lines),
1447
+ "\n".join(candidate_lines),
1448
+ )
1449
+ )
1450
+ filtered_sdp = _filter_sdp_candidates(unfiltered_sdp, self.IceHostAddress)
1451
+ filtered_candidate_lines = [
1452
+ line
1453
+ for line in filtered_sdp.split("\r\n")
1454
+ if line.startswith("a=candidate:")
1455
+ ]
1456
+ _debug_log(
1457
+ "after IceHostAddress=%r filtering, %d candidate(s) remain (sent to client):\n%s"
1458
+ % (
1459
+ self.IceHostAddress,
1460
+ len(filtered_candidate_lines),
1461
+ "\n".join(filtered_candidate_lines),
1462
+ )
1463
+ )
1464
+ if self.IceHostAddress:
1465
+ dropped = unfiltered_sdp.count("a=candidate:") - filtered_sdp.count(
1466
+ "a=candidate:"
1467
+ )
1468
+ self.warn_stream(
1469
+ "H264VideoStream: IceHostAddress=%s, dropped %d other ICE candidate(s)"
1470
+ % (self.IceHostAddress, dropped)
1471
+ )
1472
+ return filtered_sdp
1473
+
1474
+ try:
1475
+ answer_sdp = self.__run_coroutine(negotiate())
1476
+ except Exception:
1477
+ self.__peer_connections.pop(connection_id, None)
1478
+ self.__peer_views.pop(connection_id, None)
1479
+ raise
1480
+
1481
+ return [connection_id, answer_sdp]
1482
+
1483
+ @Core.DEB_MEMBER_FUNCT
1484
+ def LeaveStream(self, connection_id):
1485
+ if self.__loop is None:
1486
+ return
1487
+ asyncio.run_coroutine_threadsafe(
1488
+ self.__cleanup_connection(connection_id), self.__loop
1489
+ )
1490
+
1491
+ async def __cleanup_connection(self, connection_id):
1492
+ pc = self.__peer_connections.pop(connection_id, None)
1493
+ view = self.__peer_views.pop(connection_id, None)
1494
+ if view is not None and view not in self.__peer_views.values():
1495
+ # Drop the frame so the next viewer of this view starts on a fresh one.
1496
+ self.__views[view].frame_box.clear()
1497
+ if pc is not None:
1498
+ await pc.close()
1499
+
1500
+ # ------------------------------------------------------------------
1501
+ # Full-size snapshot command
1502
+ # ------------------------------------------------------------------
1503
+ @Core.DEB_MEMBER_FUNCT
1504
+ def SaveLastVideoImage(self, argin):
1505
+ missing = _missing_dependencies(av=av, Pillow=PILImage)
1506
+ if missing:
1507
+ PyTango.Except.throw_exception(
1508
+ "MissingDependency",
1509
+ "Missing Python package(s) required by SaveLastVideoImage: %s"
1510
+ % ", ".join(missing),
1511
+ "SaveLastVideoImage",
1512
+ )
1513
+
1514
+ if not self.__video.getLive():
1515
+ PyTango.Except.throw_exception(
1516
+ "NotLive", "Camera is not live (video_live=False)", "SaveLastVideoImage"
1517
+ )
1518
+
1519
+ image_format = "JPEG"
1520
+ quality = self.JpegQuality
1521
+ if argin:
1522
+ parts = argin.split(":")
1523
+ image_format = parts[0].upper()
1524
+ if len(parts) > 1:
1525
+ quality = int(parts[1])
1526
+ if image_format not in ("JPEG", "PNG"):
1527
+ PyTango.Except.throw_exception(
1528
+ "BadArgument",
1529
+ "format must be 'JPEG', 'PNG' or 'JPEG:<quality>'",
1530
+ "SaveLastVideoImage",
1531
+ )
1532
+
1533
+ t0 = time.perf_counter()
1534
+ raw = self.__make_raw_frame(self.__video.getLastImage())
1535
+ if raw is None:
1536
+ PyTango.Except.throw_exception(
1537
+ "NoImage", "No usable video frame available", "SaveLastVideoImage"
1538
+ )
1539
+ t_raw = time.perf_counter()
1540
+
1541
+ src_frame = _frame_from_bytes(
1542
+ raw.av_format, raw.width, raw.height, raw.region()
1543
+ )
1544
+ rgb_array = src_frame.reformat(format="rgb24").to_ndarray()
1545
+ t_rgb = time.perf_counter()
1546
+ turns = self.__rotation_turns()
1547
+ if turns:
1548
+ rgb_array = numpy.ascontiguousarray(numpy.rot90(rgb_array, turns))
1549
+ t_rot = time.perf_counter()
1550
+
1551
+ out = io.BytesIO()
1552
+ pil_image = PILImage.fromarray(rgb_array)
1553
+ if image_format == "JPEG":
1554
+ pil_image.save(out, format="JPEG", quality=quality)
1555
+ else:
1556
+ pil_image.save(out, format="PNG")
1557
+ t_enc = time.perf_counter()
1558
+
1559
+ data = out.getvalue()
1560
+ if self.__diag:
1561
+ _diag_log(
1562
+ "SaveLastVideoImage %s %dx%d av_format=%s -> %d bytes in %.3fs "
1563
+ "(raw_frame=%.3f rgb_convert=%.3f rotate=%.3f encode=%.3f)"
1564
+ % (
1565
+ image_format,
1566
+ raw.width,
1567
+ raw.height,
1568
+ raw.av_format,
1569
+ len(data),
1570
+ t_enc - t0,
1571
+ t_raw - t0,
1572
+ t_rgb - t_raw,
1573
+ t_rot - t_rgb,
1574
+ t_enc - t_rot,
1575
+ )
1576
+ )
1577
+ return [image_format, data]
1578
+
1579
+ def _publish_not_live_frame(self):
1580
+ # Sized from the last known real frame for consistency. If no real
1581
+ # frame has ever arrived yet (e.g. the camera has never gone live
1582
+ # since this device started), falls back to CtImage's configured
1583
+ # dimensions rather than guessing - video and still image
1584
+ # resolutions are the same here, so this is a real size, not a guess
1585
+ # that could poison the encoder's/browser's locked-in stream
1586
+ # resolution the way an arbitrary default would.
1587
+ missing = _missing_dependencies(av=av, Pillow=PILImage)
1588
+ if missing:
1589
+ return
1590
+ with self.__raw_lock:
1591
+ raw = self.__raw_frame
1592
+ if raw is not None:
1593
+ displayed_w, displayed_h = raw
1594
+ if self.__rotation_turns() % 2:
1595
+ displayed_w, displayed_h = displayed_h, displayed_w
1596
+ else:
1597
+ size = self.__image.getImageDim().getSize()
1598
+ displayed_w, displayed_h = size.getWidth(), size.getHeight()
1599
+
1600
+ for name in set(self.__peer_views.values()):
1601
+ state = self.__views.get(name)
1602
+ if state is None:
1603
+ continue
1604
+ try:
1605
+ _, width, height = _view_output_size(
1606
+ state.spec, displayed_w, displayed_h
1607
+ )
1608
+ except ValueError:
1609
+ width, height = _fit_size(
1610
+ displayed_w, displayed_h, state.spec.max_w, state.spec.max_h
1611
+ )
1612
+ # even dimensions are required by yuv420p's 2x2 chroma subsampling
1613
+ width, height = width & ~1, height & ~1
1614
+ frame = self.__not_live_frame(width, height)
1615
+ if frame is not None:
1616
+ state.frame_box.publish(frame)
1617
+
1618
+ def __not_live_frame(self, width, height):
1619
+ pil_image = PILImage.new("RGB", (width, height), color=(34, 34, 34))
1620
+ text = "Camera not live"
1621
+ draw = PILImageDraw.Draw(pil_image)
1622
+ font_size = max(24, height // 15)
1623
+ try:
1624
+ # load_default() only accepts a size since Pillow 10.1 - falls
1625
+ # back to its fixed (small) size on older Pillow rather than
1626
+ # failing the whole fallback frame over a cosmetic detail.
1627
+ font = PILImageFont.load_default(size=font_size)
1628
+ except TypeError:
1629
+ font = PILImageFont.load_default()
1630
+ left, top, right, bottom = draw.textbbox((0, 0), text, font=font)
1631
+ draw.text(
1632
+ ((width - (right - left)) / 2, (height - (bottom - top)) / 2),
1633
+ text,
1634
+ font=font,
1635
+ fill=(255, 255, 255),
1636
+ )
1637
+
1638
+ try:
1639
+ src_frame = av.VideoFrame.from_ndarray(
1640
+ numpy.array(pil_image), format="rgb24"
1641
+ )
1642
+ return src_frame.reformat(format="yuv420p")
1643
+ except Exception:
1644
+ _debug_log(
1645
+ "failed to build not-live fallback frame: %s" % traceback.format_exc()
1646
+ )
1647
+ return None
1648
+
1649
+ def is_normalize_allowed(self, mode):
1650
+ # Overrides BasePostProcess's generic state-based gate: there is no
1651
+ # real on/off notion for a contrast-stretch mode, so it should not
1652
+ # require Start() first, unlike attributes tied to the base plugin
1653
+ # class's own on/off notion.
1654
+ return True
1655
+
1656
+ def read_normalize(self, attr):
1657
+ attr.set_value(self.__normalize)
1658
+
1659
+ def write_normalize(self, attr):
1660
+ value = attr.get_write_value()
1661
+ if value not in _NORMALIZE_MODES:
1662
+ PyTango.Except.throw_exception(
1663
+ "BadArgument",
1664
+ "normalize must be one of %s" % ", ".join(_NORMALIZE_MODES),
1665
+ "write_normalize",
1666
+ )
1667
+ self.__normalize = value
1668
+
1669
+
1670
+ class H264VideoStreamDeviceServerClass(PyTango.DeviceClass):
1671
+
1672
+ class_property_list = {}
1673
+
1674
+ device_property_list = {
1675
+ "MaxStreamWidth": [
1676
+ PyTango.DevLong,
1677
+ "Downscale streamed frames wider than this (0 = no limit, does not affect SaveLastVideoImage)",
1678
+ [0],
1679
+ ],
1680
+ "MaxStreamHeight": [
1681
+ PyTango.DevLong,
1682
+ "Downscale streamed frames taller than this (0 = no limit, does not affect SaveLastVideoImage)",
1683
+ [0],
1684
+ ],
1685
+ "IceServers": [
1686
+ PyTango.DevVarStringArray,
1687
+ "STUN/TURN server URLs for WebRTC ICE negotiation (empty is fine on a single network segment)",
1688
+ [],
1689
+ ],
1690
+ "JpegQuality": [
1691
+ PyTango.DevShort,
1692
+ "Default JPEG quality (1-100) used by SaveLastVideoImage when none is given",
1693
+ [90],
1694
+ ],
1695
+ "DisconnectTimeout": [
1696
+ PyTango.DevDouble,
1697
+ "Seconds a WebRTC connection may stay in 'disconnected' state before it is force-closed, in case LeaveStream is never called",
1698
+ [30.0],
1699
+ ],
1700
+ "IceHostAddress": [
1701
+ PyTango.DevString,
1702
+ "If set, only advertise this IP as a host ICE candidate to viewers, dropping any others (e.g. a Docker bridge interface also present on this machine)",
1703
+ [""],
1704
+ ],
1705
+ "StreamMaxBitrate": [
1706
+ PyTango.DevLong,
1707
+ "Ceiling (kbps) the H264 encoder's bitrate may reach via WebRTC congestion-control (REMB) feedback (aiortc's own built-in ceiling is 3000)",
1708
+ [3000],
1709
+ ],
1710
+ "StreamMaxFPS": [
1711
+ PyTango.DevDouble,
1712
+ "How often (Hz) the plugin looks for a new camera frame to convert for WebRTC viewers (0 = 30). Frames arriving faster than this are skipped before the pixel conversion; it does not limit how fast the encoder re-sends the latest frame. Read at startup",
1713
+ [10.0],
1714
+ ],
1715
+ "StreamMinBitrate": [
1716
+ PyTango.DevLong,
1717
+ "Floor and starting bitrate (kbps) of the H264 encoder (0 = aiortc's own: 500 kbps floor, 1000 kbps start). Raise it so quality does not depend on the browser's slowly growing bandwidth estimate; the stream then needs at least this much bandwidth",
1718
+ [0],
1719
+ ],
1720
+ "H264Preset": [
1721
+ PyTango.DevString,
1722
+ "libx264 preset (speed/quality tradeoff, e.g. 'ultrafast'..'veryslow'); does not affect latency, only CPU cost and compression efficiency",
1723
+ ["medium"],
1724
+ ],
1725
+ "H264Profile": [
1726
+ PyTango.DevString,
1727
+ "H264 profile: 'baseline' (default, decodes everywhere) or 'high' (better compression; the browser must offer High, otherwise no H264 is negotiated)",
1728
+ ["baseline"],
1729
+ ],
1730
+ "H264Threads": [
1731
+ PyTango.DevLong,
1732
+ "Thread count for the libx264 encoder and the frame conversion (0 = automatic, based on the machine's cores)",
1733
+ [0],
1734
+ ],
1735
+ "H264AqMode": [
1736
+ PyTango.DevLong,
1737
+ "libx264 adaptive quantization mode (0=off, 1=variance, 2=auto-variance)",
1738
+ [1],
1739
+ ],
1740
+ "H264AqStrength": [
1741
+ PyTango.DevDouble,
1742
+ "libx264 adaptive quantization strength",
1743
+ [1.0],
1744
+ ],
1745
+ "DiagLog": [
1746
+ PyTango.DevBoolean,
1747
+ "Print DIAG lines (encoder rebuilds with their target bitrate, measured encode rate and bytes per frame, frame sizes) to the device server's stdout, for diagnosing stream quality",
1748
+ [False],
1749
+ ],
1750
+ "StreamViews": [
1751
+ PyTango.DevVarStringArray,
1752
+ "Named stream views, one 'name; crop=w:h:x:y; size=w:h; max=WxH' per entry (crop and size use in_w/in_h expressions; shorthands: 'scale/N' is 1/N of the frame size, 'crop/N' a centred crop of 1/N of each dimension, e.g. 'overview; scale/2' and 'high-resolution; crop/2'). Clients join one with JoinStreamView; JoinStream gives the full frame",
1753
+ [],
1754
+ ],
1755
+ }
1756
+
1757
+ cmd_list = {
1758
+ "JoinStream": [
1759
+ [PyTango.DevString, "WebRTC SDP offer"],
1760
+ [PyTango.DevVarStringArray, "[connection_id, WebRTC SDP answer]"],
1761
+ ],
1762
+ "JoinStreamView": [
1763
+ [PyTango.DevVarStringArray, "[WebRTC SDP offer, view name]"],
1764
+ [PyTango.DevVarStringArray, "[connection_id, WebRTC SDP answer]"],
1765
+ ],
1766
+ "ListStreamViews": [
1767
+ [PyTango.DevVoid, ""],
1768
+ [PyTango.DevVarStringArray, "Names of the configured stream views"],
1769
+ ],
1770
+ "LeaveStream": [
1771
+ [PyTango.DevString, "connection_id returned by JoinStream"],
1772
+ [PyTango.DevVoid, ""],
1773
+ ],
1774
+ "SaveLastVideoImage": [
1775
+ [PyTango.DevString, "'JPEG', 'PNG' or 'JPEG:<quality>'"],
1776
+ [PyTango.DevEncoded, "The captured frame, as JPEG or PNG bytes"],
1777
+ ],
1778
+ "Start": [[PyTango.DevVoid, ""], [PyTango.DevVoid, ""]],
1779
+ "Stop": [[PyTango.DevVoid, ""], [PyTango.DevVoid, ""]],
1780
+ }
1781
+
1782
+ attr_list = {
1783
+ "RunLevel": [[PyTango.DevLong, PyTango.SCALAR, PyTango.READ_WRITE]],
1784
+ "normalize": [
1785
+ [PyTango.DevString, PyTango.SCALAR, PyTango.READ_WRITE],
1786
+ {
1787
+ "label": "Normalize",
1788
+ "description": "Contrast-stretch frames before streaming/snapshot: 'off', 'minmax', or 'sigma3' (mean +/- 3 standard deviations). For YUV422PACKED, only luma is stretched.",
1789
+ },
1790
+ ],
1791
+ }
1792
+
1793
+ def __init__(self, name):
1794
+ PyTango.DeviceClass.__init__(self, name)
1795
+ self.set_type(name)
1796
+
1797
+
1798
+ _control_ref = None
1799
+
1800
+
1801
+ def set_control_ref(control_class_ref):
1802
+ global _control_ref
1803
+ _control_ref = control_class_ref
1804
+
1805
+
1806
+ def get_tango_specific_class_n_device():
1807
+ return H264VideoStreamDeviceServerClass, H264VideoStreamDeviceServer