1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import logging
import threading
import time
from os import path as osp
from transitions.extensions import LockedMachine as Machine
from transitions import State as State
from blinker import signal
import defaults
import errors
import vs
import utils
import glfw
from algorithm.algorithm_manager import AlgorithmManager
from clientmessenger import CLIENT_MESSENGER
from utils.settings_manager import SETTINGS
from utils import async
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
FAIL_SLEEP = 0.25
class Stitcher(object):
""" Stitcher automaton
- Responsible for the stitching process
- Holds references to streams (preview, broadcast)
- Holds references to recorders (input, output)
"""
def __init__(self, server_instance, stitcher_executor, display_):
"""Init
"""
self.server = server_instance
self.stitcher_executor = stitcher_executor
self.algorithm_manager = None
self.has_audio = None
self.project_manager = self.server.project_manager
self.display = display_
self.old_submit = self.stitcher_executor.submit
self.overlay_window = None
self.overlay_config = None
self.overlay = None
# State Machine
states = [
# The stitcher is waiting for the camera to connect
State(name="WaitingForCamera", ignore_invalid_triggers=True),
# Stitcher running, no errors
State(name="Running", ignore_invalid_triggers=True),
# Stitcher running, but producing errors (EOF, etc..)
State(name="Failing", ignore_invalid_triggers=True),
]
transitions = [
{"source": "WaitingForCamera",
"trigger": "t_camera_connected",
"dest": "Failing"},
{"source": "Running",
"trigger": "t_fail",
"dest": "Failing"},
{"source": "Failing",
"trigger": "t_resume",
"dest": "Running"},
{"source": ["Running", "Failing"],
"trigger": "t_camera_connected",
"conditions": "_ignore",
"dest": "Failing"},
{"source": ["Running", "Failing"],
"trigger": "t_camera_disconnected",
"before": "terminate",
"dest": "WaitingForCamera"},
{"source": ["Running", "Failing"],
"trigger": "t_terminate",
"dest": "WaitingForCamera"},
]
self.machine = Machine(
name="Stitcher", model=self, states=states,
transitions=transitions, initial="WaitingForCamera", async=True)
# Signals
self._connect_signals()
self._load_plugins()
self.run_loop = None
self.native_loop = None
def _connect_signals(self):
signal("camera_connected").connect(self.t_camera_connected)
signal("camera_disconnected").connect(self.t_camera_disconnected)
signal("camera_video_fail").connect(self.t_camera_disconnected)
signal("algorithm_running_success").connect(self._reset_executor)
def _submit(self, fn, *args, **kwargs):
self.native_loop.Lock()
result = self.old_submit(fn, *args, **kwargs)
self.native_loop.Unlock()
return result
def _reset_executor(self, sender, panorama, output):
self.stitcher_executor.submit(self.reset_panorama, sender, panorama, output)
# ------------------------------------------------------------------------
#
# ------------------------------------------------------------------------
def _ignore(self, sender=None):
return False
def on_enter_WaitingForCamera(self, sender=None):
self._cleanup()
def on_exit_WaitingForCamera(self, sender=None):
""" Create stitcher"""
self._create()
def start_streams(self):
signal("stitching_running").send()
def on_enter_Running(self, sender=None):
self.stitcher_executor.submit(self.start_streams).result()
if SETTINGS.enable_ev_compensation:
# Note, if stitcher fails and algorithm won't be completed - it won't be rescheduled
# So we want to start it again when stitcher is running
self.algorithm_manager.start_exposure_compensation()
def on_exit_Running(self, sender=None):
signal("stitching_failing").send(preserve=SETTINGS.output_recovery_enabled)
# ------------------------------------------------------------------------
#
# ------------------------------------------------------------------------
def _load_plugins(self):
if vs.loadPlugins(osp.join(SETTINGS.lib_path, "plugins")) == 0:
raise errors.StitcherError("Parsing: could not load any plugin")
def _create(self):
""" Creates the controller and the stitcher
"""
status = vs.checkDefaultBackendDeviceInitialization()
if not status.ok():
logger.error("CUDA device Initialization failed. Reason {}".format(status.getErrorMessage()))
raise errors.StitcherError("CUDA device Initialization failed")
try:
self.project_manager.create_controller()
except (errors.StitcherError, errors.AudioError, errors.ParserError) as error:
logger.warn("current configuration seems corrupted : {} "
"Switching to default configuration.".format(error))
CLIENT_MESSENGER.send_event(defaults.RESET_TO_DEFAULT_MESSAGE)
utils.async.defer(self.server.reset, True)
return
status = self.project_manager.controller.createStitcher()
if not status.ok():
raise errors.StitcherError("Cannot create stitcher: " + str(status.getErrorMessage()))
self._start_stitching_thread()
self.algorithm_manager = AlgorithmManager(self.project_manager.controller)
self.renderer = None
if self.display.is_active():
self.display.reset_pano()
self.display.open_output_window()
surfaces = self.display.get_surfaces()
if surfaces is None:
raise errors.StitcherError("Error creating destination surface")
self.renderer = self.display.get_renderer()
self.renderer.thisown = 0
self.stitcher_executor.submit = self._submit
#overlay create
self.overlay_config = self.project_manager.project_config.has("overlay")
if self.overlay_config :
glfw.default_window_hints()
glfw.window_hint(glfw.VISIBLE, False)
glfw.window_hint(glfw.CONTEXT_ROBUSTNESS, glfw.NO_RESET_NOTIFICATION)
glfw.window_hint(glfw.CONTEXT_RELEASE_BEHAVIOR, glfw.RELEASE_BEHAVIOR_FLUSH)
self.overlay_window = glfw.create_window(16, 16, "", None, self.display.offscreen_window)
glfw.make_context_current(self.overlay_window)
self.overlay = vs.Compositor(self.display._to_swig(self.overlay_window), self.project_manager.panorama, self.project_manager.controller.getFrameRateFromInputController())
glfw.make_context_current(None)
else:
surfaces = vs.PanoSurfaceVec()
surf = vs.OffscreenAllocator_createPanoSurface(self.project_manager.panorama.width,
self.project_manager.panorama.height,
"StitchOutput")
if not surf.ok():
raise errors.StitcherError("Error creating destination surface " + \
str(surf.status().getErrorMessage()))
dontmemleak = vs.panoSurfaceSharedPtr(surf.release())
# SWIG create a proxy object with an empty deleter
# when passing directly the pointer to the vector object :(
# DON'T TRY TO FACTORIZE THE PREVIOUS LINE OR MEMLEAK
surfaces.push_back(dontmemleak)
self.stitcher_executor.submit = self.old_submit
self.stitch_output = self.project_manager.controller.createAsyncStitchOutput(
surfaces, vs.PanoRendererPtrVector(), vs.OutputWriterPtrVector())
if self.display.is_active():
self.stitch_output.addRenderer(vs.panoRendererSharedPtr(self.renderer))
self.native_loop = vs.StitchLoop(self.display._to_swig(self.display.offscreen_window), self.project_manager.controller, self.stitch_output.object())
if self.overlay:
dontmemleak = vs.overlayerSharedPtr(self.overlay)
# SWIG create a proxy object with an empty deleter
# when passing directly the pointer to the setCompositor function :(
# DON'T TRY TO FACTORIZE THE PREVIOUS LINE OR MEMLEAK
self.stitch_output.setCompositor(dontmemleak)
self.run_loop.set()
# To be deprecated
self.has_audio = False
def _start_stitching_thread(self):
self.run_loop = threading.Event()
self.thread = threading.Thread(target=self._stitch_loop, name="Stitcher")
self.thread.start()
# Stitching process management
def _cleanup(self):
"""Makes sure that all the lib objects are released to prevent assert at exit time
"""
if self.display.is_active():
self.display.close_output_window()
self.stitch_output.removeRenderer("OpenGLRenderer")
self.stitch_output = None
self.algorithm_manager = None
def _check_status(self, status):
current_state = self.state
if status is not None:
if current_state == "WaitingForCamera":
time.sleep(FAIL_SLEEP)
return None
if status.ok():
if current_state == "Failing":
async.defer(self.t_resume)
return status
else:
msg = status.getErrorMessage()
if current_state == "Running":
logger.error("Stitching failed : " + msg)
async.defer(self.t_fail)
return status
# unrecoverable GPU failure. Server need to be resetted
elif self.state == "Failing" and status.getOriginString() == "GPU":
logger.error("Stitching critical failed : " + msg)
CLIENT_MESSENGER.send_error(errors.StitcherError("Internal GPU error: " +
status.getErrorMessage()))
utils.async.defer(self.server.reset)
return status
# No state change
return None
def _stitch_loop(self):
"""Stitcher runner job (blocking while stitcher is starved)
"""
logger.info("starting loop...")
self.run_loop.wait()
if self.display.is_active():
""" When displaying on HDMI, the stitch loop runs in C++.
This loop checks the status of the native loop on a regular basis
"""
self.native_loop.Start()
old_status = None
while self.run_loop.is_set():
algodata = self.algorithm_manager.get_next_algorithm(self.project_manager.panorama)
self.native_loop.setAlgorithm(algodata[0], algodata[1])
status = self.native_loop.StitchStatus()
if old_status is None or old_status.ok() != status.ok():
old_status = self._check_status(status)
time.sleep(1 / 1000.)
self.native_loop.Stop()
else:
""" When not ouptuting to HDMI, the stitcher_executor fires the stitch command
"""
while self.run_loop.is_set():
status = self.stitcher_executor.submit(self._stitch).result()
self._check_status(status)
time.sleep(1 / 1000.)
logger.info("leaving loop...")
def _stitch(self):
"""Stitch the input frames into the output. No python thread blocking.
"""
algodata = self.algorithm_manager.get_next_algorithm(self.project_manager.panorama)
status = None
try:
status = vs.stitchAndExtractNoGIL(
self.project_manager.controller,
self.stitch_output.object(),
algodata[1],
algodata[0],
True)
except Exception as e:
logger.warning(e)
return status
def reset_panorama(self, sender, updater, output):
# Output is passed so that we keep a reference to the underlying object. Please do not remove this unused parameter.
# Get updater function if it's updater, otherwise - pass panorama
updater_param = updater.getCloneUpdater() if isinstance(updater, vs.PanoramaDefinitionUpdater) else updater
status = self.project_manager.controller.updatePanorama(updater_param)
if not status.ok():
CLIENT_MESSENGER.send_error(errors.StitcherError("Cannot update the panorama. Reason: " +
status.getErrorMessage()))
return
self.project_manager.update("pano", self.project_manager.get_save_panorama().serialize())
def terminate(self, sender=None):
if self.run_loop and self.run_loop.is_set():
self.run_loop.clear()
logger.info("Joining run loop...")
self.thread.join()
logger.info("Done")
if self.algorithm_manager is not None:
self.algorithm_manager.cancel_running_algorithms()
self.t_terminate()