Instrument Neutral Distributed Interface INDI 2.2.5
streammanager.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2020 by Pawel Soja <[email protected]>
3 Copyright (C) 2015 by Jasem Mutlaq <[email protected]>
4 Copyright (C) 2014 by geehalel <[email protected]>
5
6 Stream Recorder
7
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
12
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
22*/
23
24#include <config.h>
25#include "streammanager.h"
26#include "streammanager_p.h"
27#include "indiccd.h"
28#include "indisensorinterface.h"
29#include "indilogger.h"
30#include "indiutility.h"
32#include "indielapsedtimer.h"
33
34#include <cerrno>
35#include <sys/stat.h>
36
37#include <algorithm>
38#include <chrono>
39#include <mutex>
40
41static const char * STREAM_TAB = "Streaming";
42
43namespace INDI
44{
45
47 : currentDevice(defaultDevice)
48{
49 FPSAverage.setTimeWindow(1000);
50#ifdef __arm__
51 FPSFast.setTimeWindow(500);
52#else
53 FPSFast.setTimeWindow(100);
54#endif
55
56 recorder = recorderManager.getDefaultRecorder();
57
58 LOGF_DEBUG("Using default recorder (%s)", recorder->getName());
59
60 encoder = encoderManager.getDefaultEncoder();
61
63
64 LOGF_DEBUG("Using default encoder (%s)", encoder->getName());
65
67}
68
70{
71 if (framesThread.joinable())
72 {
74 framesIncoming.abort();
75 framesThread.join();
76 }
77}
78
82
85
87{
88 return currentDevice->getDeviceName();
89}
90
91const char * StreamManager::getDeviceName() const
92{
93 D_PTR(const StreamManager);
94 return d->getDeviceName();
95}
96
98{
99 /* Video Stream */
100 // @INDI_STANDARD_PROPERTY@
101 StreamSP[0].fill("STREAM_ON", "Stream On", ISS_OFF);
102 StreamSP[1].fill("STREAM_OFF", "Stream Off", ISS_ON);
103 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
104 StreamSP.fill(getDeviceName(), "SENSOR_DATA_STREAM", "Video Stream",
105 STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
106 else
107 StreamSP.fill(getDeviceName(), "CCD_VIDEO_STREAM", "Video Stream",
108 STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
109
110 // Full Depth Streaming — right after Video Stream toggle
111 FullDepthSP[FULL_DEPTH_8BIT ].fill("FULL_DEPTH_8BIT", "8-bit", ISS_ON);
112 FullDepthSP[FULL_DEPTH_16BIT].fill("FULL_DEPTH_16BIT", "16-bit", ISS_OFF);
113 FullDepthSP.fill(getDeviceName(), "STREAM_FULL_DEPTH", "Stream Depth", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
114
115 // @INDI_STANDARD_PROPERTY@
116 StreamTimeNP[0].fill("STREAM_DELAY_TIME", "Delay (s)", "%.3f", 0, 60, 0.001, 0);
117 StreamTimeNP.fill(getDeviceName(), "STREAM_DELAY", "Video Stream Delay", STREAM_TAB, IP_RO, 0, IPS_IDLE);
118
119 // @INDI_STANDARD_PROPERTY@
120 StreamExposureNP[STREAM_EXPOSURE].fill("STREAMING_EXPOSURE_VALUE", "Duration (s)", "%.6f", 0.000001, 60, 0.1, 0.1);
121 StreamExposureNP[STREAM_DIVISOR ].fill("STREAMING_DIVISOR_VALUE", "Divisor", "%.f", 1, 15, 1.0, 1.0);
122 StreamExposureNP.fill(getDeviceName(), "STREAMING_EXPOSURE", "Expose", STREAM_TAB, IP_RW, 60, IPS_IDLE);
123
124 /* Measured FPS */
125 // @INDI_STANDARD_PROPERTY@
126 FpsNP[FPS_INSTANT].fill("EST_FPS", "Instant.", "%.2f", 0.0, 999.0, 0.0, 30);
127 FpsNP[FPS_AVERAGE].fill("AVG_FPS", "Average (1 sec.)", "%.2f", 0.0, 999.0, 0.0, 30);
128 FpsNP.fill(getDeviceName(), "FPS", "FPS", STREAM_TAB, IP_RO, 60, IPS_IDLE);
129
130 /* Record Frames */
131 /* File */
132 // @INDI_STANDARD_PROPERTY@
133 std::string defaultDirectory = std::string(getenv("HOME")) + std::string("/Videos/indi__D_");
134 RecordFileTP[0].fill("RECORD_FILE_DIR", "Dir.", defaultDirectory.data());
135 RecordFileTP[1].fill("RECORD_FILE_NAME", "Name", "indi_record__T_");
136 RecordFileTP.fill(getDeviceName(), "RECORD_FILE", "Record File",
137 STREAM_TAB, IP_RW, 0, IPS_IDLE);
138
139 /* Record Options */
140 // @INDI_STANDARD_PROPERTY@
141 RecordOptionsNP[0].fill("RECORD_DURATION", "Duration (sec)", "%.3f", 0.001, 999999.0, 0.0, 1.0);
142 RecordOptionsNP[1].fill("RECORD_FRAME_TOTAL", "Frames", "%.f", 1.0, 999999999.0, 1.0, 30.0);
143 RecordOptionsNP.fill(getDeviceName(), "RECORD_OPTIONS",
144 "Record Options", STREAM_TAB, IP_RW, 60, IPS_IDLE);
145
146 /* Record Switch */
147 // @INDI_STANDARD_PROPERTY@
148 RecordStreamSP[RECORD_ON ].fill("RECORD_ON", "Record On", ISS_OFF);
149 RecordStreamSP[RECORD_TIME ].fill("RECORD_DURATION_ON", "Record (Duration)", ISS_OFF);
150 RecordStreamSP[RECORD_FRAME].fill("RECORD_FRAME_ON", "Record (Frames)", ISS_OFF);
151 RecordStreamSP[RECORD_OFF ].fill("RECORD_OFF", "Record Off", ISS_ON);
152 RecordStreamSP.fill(getDeviceName(), "RECORD_STREAM", "Video Record", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
153
154 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
155 {
156 // CCD Streaming Frame
157 // @INDI_STANDARD_PROPERTY@
158 StreamFrameNP[0].fill("X", "Left", "%.f", 0, 0, 0, 0);
159 StreamFrameNP[1].fill("Y", "Top", "%.f", 0, 0, 0, 0);
160 StreamFrameNP[2].fill("WIDTH", "Width", "%.f", 0, 0, 0, 0);
161 StreamFrameNP[3].fill("HEIGHT", "Height", "%.f", 0, 0, 0, 0);
162 StreamFrameNP.fill(getDeviceName(), "CCD_STREAM_FRAME", "Frame", STREAM_TAB, IP_RW,
163 60, IPS_IDLE);
164 }
165
166 // Encoder Selection
167 // @INDI_STANDARD_PROPERTY@
168 EncoderSP[ENCODER_RAW ].fill("RAW", "RAW", ISS_ON);
169 EncoderSP[ENCODER_MJPEG].fill("MJPEG", "MJPEG", ISS_OFF);
170 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
171 EncoderSP.fill(getDeviceName(), "SENSOR_STREAM_ENCODER", "Encoder", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
172 else
173 EncoderSP.fill(getDeviceName(), "CCD_STREAM_ENCODER", "Encoder", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
174
175 // Recorder Selector
176 // @INDI_STANDARD_PROPERTY@
177 RecorderSP[RECORDER_RAW].fill("SER", "SER", ISS_ON);
178 RecorderSP[RECORDER_OGV].fill("OGV", "OGV", ISS_OFF);
179 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
180 RecorderSP.fill(getDeviceName(), "SENSOR_STREAM_RECORDER", "Recorder", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
181 else
182 RecorderSP.fill(getDeviceName(), "CCD_STREAM_RECORDER", "Recorder", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
183
184 // If we do not have theora installed, let's just define SER default recorder
185#ifndef HAVE_THEORA
186 RecorderSP.resize(1);
187#endif
188
189 // Limits
190 // @INDI_STANDARD_PROPERTY@
191 LimitsNP[LIMITS_BUFFER_MAX ].fill("LIMITS_BUFFER_MAX", "Maximum Buffer Size (MB)", "%.0f", 1, 1024 * 64, 1, 512);
192 LimitsNP[LIMITS_PREVIEW_FPS].fill("LIMITS_PREVIEW_FPS", "Maximum Preview FPS", "%.0f", 1, 120, 1, 10);
193 LimitsNP.fill(getDeviceName(), "LIMITS", "Limits", STREAM_TAB, IP_RW, 0, IPS_IDLE);
194
195 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
196 {
197 // Centroid tracking
198 TrackingSP[TRACKING_ON ].fill("TRACKING_ON", "On", ISS_OFF);
199 TrackingSP[TRACKING_OFF].fill("TRACKING_OFF", "Off", ISS_ON);
200 TrackingSP.fill(getDeviceName(), "STREAM_TRACKING", "Tracking", STREAM_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
201
202 TrackingOffsetNP[TRACKING_CENTROID_X].fill("CENTROID_X", "Centroid X (px)", "%.2f", 0, 65535, 0, 0);
203 TrackingOffsetNP[TRACKING_CENTROID_Y].fill("CENTROID_Y", "Centroid Y (px)", "%.2f", 0, 65535, 0, 0);
204 TrackingOffsetNP[TRACKING_OFFSET_X ].fill("OFFSET_X", "Offset X (px)", "%.2f", -65535, 65535, 0, 0);
205 TrackingOffsetNP[TRACKING_OFFSET_Y ].fill("OFFSET_Y", "Offset Y (px)", "%.2f", -65535, 65535, 0, 0);
206 TrackingOffsetNP[TRACKING_QUALITY ].fill("QUALITY", "Quality", "%.2f", 0, 1, 0, 0);
207 TrackingOffsetNP[TRACKING_SEQUENCE ].fill("SEQUENCE", "Sequence", "%.f", 0, 1e12, 0, 0);
208 // Unix time (s) of the first frame averaged into this report
209 TrackingOffsetNP[TRACKING_TIMESTAMP ].fill("TIMESTAMP", "Timestamp (s)", "%.3f", 0, 1e12, 0, 0);
210 TrackingOffsetNP.fill(getDeviceName(), "STREAM_TRACKING_OFFSET", "Tracking Offset", STREAM_TAB, IP_RO, 60, IPS_IDLE);
211
212 TrackingLockNP[TRACKING_LOCK_X].fill("LOCK_X", "X (px)", "%.2f", 0, 65535, 0, 0);
213 TrackingLockNP[TRACKING_LOCK_Y].fill("LOCK_Y", "Y (px)", "%.2f", 0, 65535, 0, 0);
214 TrackingLockNP.fill(getDeviceName(), "STREAM_TRACKING_LOCK", "Tracking Lock", STREAM_TAB, IP_RW, 60, IPS_IDLE);
215
216 TrackingSettingsNP[TRACKING_AVERAGE].fill("AVERAGE_TIME", "Average (s)", "%.1f", 0.1, 60, 0.5, 1);
217 TrackingSettingsNP[TRACKING_RATE ].fill("MAX_RATE", "Max Rate (Hz)", "%.f", 1, 120, 1, 10);
218 TrackingSettingsNP.fill(getDeviceName(), "STREAM_TRACKING_SETTINGS", "Tracking Settings", STREAM_TAB, IP_RW, 60,
219 IPS_IDLE);
220 }
221
222 return true;
223}
224
226{
227 D_PTR(StreamManager);
228 return d->initProperties();
229}
230
232{
233 if (dev != nullptr && strcmp(getDeviceName(), dev))
234 return;
235
236 if (currentDevice->isConnected())
237 {
238 currentDevice->defineProperty(StreamSP);
239 currentDevice->defineProperty(FullDepthSP);
241 currentDevice->defineProperty(StreamExposureNP);
242 currentDevice->defineProperty(FpsNP);
243 currentDevice->defineProperty(RecordStreamSP);
244 currentDevice->defineProperty(RecordFileTP);
245 currentDevice->defineProperty(RecordOptionsNP);
246 currentDevice->defineProperty(StreamFrameNP);
247 currentDevice->defineProperty(EncoderSP);
248 currentDevice->defineProperty(RecorderSP);
249 currentDevice->defineProperty(LimitsNP);
250 if (currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
251 {
252 currentDevice->defineProperty(TrackingSP);
253 currentDevice->defineProperty(TrackingOffsetNP);
254 currentDevice->defineProperty(TrackingLockNP);
255 currentDevice->defineProperty(TrackingSettingsNP);
256 }
257 }
258}
259
260void StreamManager::ISGetProperties(const char * dev)
261{
262 D_PTR(StreamManager);
263 d->ISGetProperties(dev);
264}
265
267{
268 if (currentDevice->isConnected())
269 {
270 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
271 {
272 imageBP = currentDevice->getBLOB("CCD1");
273 }
274 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
275 {
276 imageBP = currentDevice->getBLOB("SENSOR");
277 }
278
279 currentDevice->defineProperty(StreamSP);
280 currentDevice->defineProperty(FullDepthSP);
281 currentDevice->defineProperty(StreamTimeNP);
283 currentDevice->defineProperty(StreamExposureNP);
284 currentDevice->defineProperty(FpsNP);
285 currentDevice->defineProperty(RecordStreamSP);
286 currentDevice->defineProperty(RecordFileTP);
287 currentDevice->defineProperty(RecordOptionsNP);
288 currentDevice->defineProperty(StreamFrameNP);
289 currentDevice->defineProperty(EncoderSP);
290 currentDevice->defineProperty(RecorderSP);
291 currentDevice->defineProperty(LimitsNP);
292 if (currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
293 {
294 TrackingSettingsNP.load();
295 FPSTracking.setTimeWindow(1000.0 / TrackingSettingsNP[TRACKING_RATE].getValue());
296 currentDevice->defineProperty(TrackingSP);
297 currentDevice->defineProperty(TrackingOffsetNP);
298 currentDevice->defineProperty(TrackingLockNP);
299 currentDevice->defineProperty(TrackingSettingsNP);
300 }
301 }
302 else
303 {
304 if (currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
305 {
306 setTracking(false);
307 currentDevice->deleteProperty(TrackingSP);
308 currentDevice->deleteProperty(TrackingOffsetNP);
309 currentDevice->deleteProperty(TrackingLockNP);
310 currentDevice->deleteProperty(TrackingSettingsNP);
311 }
312 currentDevice->deleteProperty(StreamSP.getName());
313 currentDevice->deleteProperty(StreamTimeNP.getName());
315 currentDevice->deleteProperty(StreamExposureNP.getName());
316 currentDevice->deleteProperty(FpsNP.getName());
317 currentDevice->deleteProperty(RecordFileTP.getName());
318 currentDevice->deleteProperty(RecordStreamSP.getName());
319 currentDevice->deleteProperty(RecordOptionsNP.getName());
320 currentDevice->deleteProperty(StreamFrameNP.getName());
321 currentDevice->deleteProperty(EncoderSP.getName());
322 currentDevice->deleteProperty(RecorderSP.getName());
323 currentDevice->deleteProperty(LimitsNP.getName());
324 currentDevice->deleteProperty(FullDepthSP.getName());
325 }
326
327 return true;
328}
329
331{
332 D_PTR(StreamManager);
333 return d->updateProperties();
334}
335
336/*
337 * The camera driver is expected to send the FULL FRAME of the Camera after BINNING without any subframing at all
338 * Subframing for streaming/recording is done in the stream manager.
339 * Therefore nbytes is expected to be SubW/BinX * SubH/BinY * Bytes_Per_Pixels * Number_Color_Components
340 * Binned frame must be sent from the camera driver for this to work consistentaly for all drivers.*/
341void StreamManagerPrivate::newFrame(const uint8_t * buffer, uint32_t nbytes, uint64_t timestamp)
342{
343 // close the data stream on the same thread as the data stream
344 // manually triggered to stop recording.
346 {
348 return;
349 }
350
351 // Discard every N frame.
352 // do not count it to fps statistics
353 // N is StreamExposureNP[STREAM_DIVISOR].getValue()
355 if (
356 (StreamExposureNP[STREAM_DIVISOR].getValue() > 1) &&
357 (frameCountDivider % static_cast<int>(StreamExposureNP[STREAM_DIVISOR].getValue())) == 0
358 )
359 {
360 return;
361 }
362
363 if (FPSAverage.newFrame())
364 {
365 FpsNP[1].setValue(FPSAverage.framesPerSecond());
366 }
367
368 if (FPSFast.newFrame())
369 {
370 FpsNP[0].setValue(FPSFast.framesPerSecond());
371 if (fastFPSUpdate.try_lock()) // don't block stream thread / record thread
372 std::thread([&]()
373 {
374 FpsNP.apply();
375 fastFPSUpdate.unlock();
376 }).detach();
377 }
378
380 {
381 size_t allocatedSize = nbytes * framesIncoming.size() / 1024 / 1024; // allocated size in MB
382 if (allocatedSize > LimitsNP[LIMITS_BUFFER_MAX].getValue())
383 {
384 LOG_WARN("Frame buffer is full, skipping frame...");
385 return;
386 }
387
388 std::vector<uint8_t> copyBuffer(buffer, buffer + nbytes); // copy the frame
389
390 framesIncoming.push(TimeFrame{FPSFast.deltaTime(), timestamp, std::move(copyBuffer)}); // push it into the queue
391 }
392
394 {
395 FPSRecorder.newFrame(); // count frames and total time
396
397 // captured all frames, stream should be close
398 if (
399 (RecordStreamSP[RECORD_FRAME].getState() == ISS_ON && FPSRecorder.totalFrames() >= (RecordOptionsNP[1].getValue())) ||
400 (RecordStreamSP[RECORD_TIME ].getState() == ISS_ON && FPSRecorder.totalTime() >= (RecordOptionsNP[0].getValue() * 1000.0))
401 )
402 {
403 LOG_INFO("Waiting for all buffered frames to be recorded");
404 framesIncoming.waitForEmpty();
405 // duplicated message
406#if 0
407 LOGF_INFO(
408 "Ending record after %g millisecs and %d frames",
409 FPSRecorder.totalTime(),
410 FPSRecorder.totalFrames()
411 );
412#endif
413 RecordStreamSP.reset();
415 RecordStreamSP.setState(IPS_IDLE);
416 RecordStreamSP.apply();
417
419 }
420 }
421}
422
423void StreamManager::newFrame(const uint8_t * buffer, uint32_t nbytes, uint64_t timestamp)
424{
425 D_PTR(StreamManager);
426 d->newFrame(buffer, nbytes, timestamp);
427}
428
429
431{
432 FrameInfo srcFrameInfo;
433
434 uint8_t components = (PixelFormat == INDI_RGB) ? 3 : 1;
435 uint8_t bytesPerComponent = (PixelDepth + 7) / 8;
436
437 dstFrameInfo.bytesPerColor = components * bytesPerComponent;
438
439 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
440 {
441 srcFrameInfo = FrameInfo(
442 dynamic_cast<const INDI::CCD*>(currentDevice)->PrimaryCCD,
443 components * bytesPerComponent
444 );
445 }
446 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
447 {
448 srcFrameInfo = FrameInfo(
449 *dynamic_cast<const INDI::SensorInterface*>(currentDevice),
450 components * bytesPerComponent
451 );
452 }
453
454 // If stream frame was not yet initialized, let's do that now
455 if (dstFrameInfo.pixels() == 0)
456 {
457 //if (dynamic_cast<INDI::CCD*>(currentDevice)->PrimaryCCD.getNAxis() == 2)
458 // binFactor = dynamic_cast<INDI::CCD*>(currentDevice)->PrimaryCCD.getBinX();
459 dstFrameInfo = srcFrameInfo;
461 StreamFrameNP.setState(IPS_IDLE);
462 StreamFrameNP.apply();
463 }
464
465 return srcFrameInfo;
466}
467
469 const uint8_t *srcBuffer,
470 const FrameInfo &srcFrameInfo,
471 uint8_t *dstBuffer,
473)
474{
475 size_t srcOffset = srcFrameInfo.bytesPerColor * (dstFrameInfo.y * srcFrameInfo.w + dstFrameInfo.x);
476 uint32_t srcStride = srcFrameInfo.lineSize();
477 uint32_t dstStride = dstFrameInfo.lineSize();
478
479 srcBuffer += srcOffset;
480
481 // Copy line-by-line
482 for (size_t i = 0; i < dstFrameInfo.h; ++i)
483 {
484 memcpy(dstBuffer, srcBuffer, dstStride);
485 dstBuffer += dstStride;
486 srcBuffer += srcStride;
487 }
488}
489
491{
492 TimeFrame sourceTimeFrame;
493 sourceTimeFrame.time = 0;
494
495 std::vector<uint8_t> subframeBuffer; // Subframe buffer for recording/streaming
496 std::vector<uint8_t> downscaleBuffer; // Downscale buffer for streaming
497
498 INDI::SingleThreadPool previewThreadPool;
499 INDI::ElapsedTimer previewElapsed;
500
502 {
503 if (framesIncoming.pop(sourceTimeFrame) == false)
504 continue;
505
506 FrameInfo srcFrameInfo = updateSourceFrameInfo();
507
508 std::vector<uint8_t> *sourceBuffer = &sourceTimeFrame.frame;
509
510 // Source buffer size may be equal or larger than frame info size
511 // as some driver still retain full unbinned window size even when binning the output
512 // frame
513 if (PixelFormat != INDI_JPG && sourceBuffer->size() < srcFrameInfo.totalSize())
514 {
515 LOGF_ERROR("Source buffer size %d is less than frame size %d, skipping frame...", sourceBuffer->size(),
516 srcFrameInfo.totalSize());
517 continue;
518 }
519
520 // Check if we need to subframe
521 bool isSubframed = false;
522 if (
524 dstFrameInfo.pixels() != 0 &&
525 dstFrameInfo != srcFrameInfo
526 )
527 {
528 subframeBuffer.resize(dstFrameInfo.totalSize());
529 subframe(sourceBuffer->data(), srcFrameInfo, subframeBuffer.data(), dstFrameInfo);
530
531 sourceBuffer = &subframeBuffer;
532 isSubframed = true;
533 }
534
535 // Measure on the frame as it is recorded, at full bit depth
536 if (isTracking)
537 {
538 const FrameInfo &frameInfo = isSubframed ? dstFrameInfo : srcFrameInfo;
539 processTracking(sourceBuffer->data(), frameInfo.w, frameInfo.h,
540 srcFrameInfo.x + (isSubframed ? dstFrameInfo.x : 0),
541 srcFrameInfo.y + (isSubframed ? dstFrameInfo.y : 0));
542 }
543
544 // For recording, save immediately.
545 {
546 std::lock_guard<std::mutex> lock(recordMutex);
547 if (
549 recordStream(sourceBuffer->data(), sourceBuffer->size(), sourceTimeFrame.time, sourceTimeFrame.timestamp) == false
550 )
551 {
552 LOG_ERROR("Recording failed.");
554 }
555 }
556
557 // For streaming, downscale to 8bit if higher than 8bit to reduce bandwidth
558 // unless Full Depth mode is enabled.
559 // You can reduce the number of frames by setting a frame limit.
560 if (isStreaming && FPSPreview.newFrame())
561 {
562 // Downscale to 8bit for streaming to reduce bandwidth, unless full depth is enabled
563 if (PixelFormat != INDI_JPG && PixelDepth > 8 && FullDepthSP[FULL_DEPTH_16BIT].getState() != ISS_ON)
564 {
565 // Allocale new buffer if size changes
566 downscaleBuffer.resize(dstFrameInfo.pixels());
567
568 // Apply gamma
569 gammaLut16.apply(
570 reinterpret_cast<const uint16_t*>(sourceBuffer->data()),
571 downscaleBuffer.size(),
572 downscaleBuffer.data()
573 );
574
575 sourceBuffer = &downscaleBuffer;
576 }
577
578 //uploadStream(sourceBuffer->data(), sourceBuffer->size());
579 previewThreadPool.start(std::bind([this, &previewElapsed](const std::atomic_bool & isAboutToQuit,
580 std::vector<uint8_t> frame)
581 {
582 INDI_UNUSED(isAboutToQuit);
583 previewElapsed.start();
584 uploadStream(frame.data(), frame.size());
585 StreamTimeNP[0].setValue(previewElapsed.nsecsElapsed() / 1000000000.0);
586 StreamTimeNP.apply();
587
588 }, std::placeholders::_1, std::move(*sourceBuffer)));
589 }
590 }
591}
592
593void StreamManagerPrivate::setSize(uint16_t width, uint16_t height)
594{
595 if (width != StreamFrameNP[CCDChip::FRAME_W].getValue() || height != StreamFrameNP[CCDChip::FRAME_H].getValue())
596 {
597 if (PixelFormat == INDI_JPG)
598 LOG_WARN("Cannot subframe JPEG streams.");
599
600 StreamFrameNP[CCDChip::FRAME_X].setValue(0);
601 StreamFrameNP[CCDChip::FRAME_X].setMax(width - 1);
602 StreamFrameNP[CCDChip::FRAME_Y].setValue(0);
603 StreamFrameNP[CCDChip::FRAME_Y].setMax(height - 1);
604 StreamFrameNP[CCDChip::FRAME_W].setValue(width);
606 StreamFrameNP[CCDChip::FRAME_W].setMax(width);
607 StreamFrameNP[CCDChip::FRAME_H].setValue(height);
609 StreamFrameNP[CCDChip::FRAME_H].setMax(height);
610
611 StreamFrameNP.setState(IPS_OK);
612 StreamFrameNP.updateMinMax();
613 }
614
619
620 // Width & Height are BINNED dimensions.
621 // Since they're the final size to make it to encoders and recorders.
622 rawWidth = width;
623 rawHeight = height;
624
625 for (EncoderInterface * oneEncoder : encoderManager.getEncoderList())
626 oneEncoder->setSize(rawWidth, rawHeight);
627 for (RecorderInterface * oneRecorder : recorderManager.getRecorderList())
628 oneRecorder->setSize(rawWidth, rawHeight);
629}
630
632{
633 D_PTR(StreamManager);
634 std::lock_guard<std::mutex> lock(d->recordMutex);
635 return d->recorder->close();
636}
637
638bool StreamManagerPrivate::setPixelFormat(INDI_PIXEL_FORMAT pixelFormat, uint8_t pixelDepth)
639{
640 if (pixelFormat == PixelFormat && pixelDepth == PixelDepth)
641 return true;
642
643 bool recorderOK = recorder->setPixelFormat(pixelFormat, pixelDepth);
644 if (recorderOK == false)
645 {
646 LOGF_ERROR("Pixel format %d is not supported by %s recorder.", pixelFormat, recorder->getName());
647 }
648 else
649 {
650 LOGF_DEBUG("Pixel format %d is supported by %s recorder.", pixelFormat, recorder->getName());
651 }
652 bool encoderOK = encoder->setPixelFormat(pixelFormat, pixelDepth);
653 if (encoderOK == false)
654 {
655 LOGF_ERROR("Pixel format %d is not supported by %s encoder.", pixelFormat, encoder->getName());
656 }
657 else
658 {
659 LOGF_DEBUG("Pixel format %d is supported by %s encoder.", pixelFormat, encoder->getName());
660 }
661
662 PixelFormat = pixelFormat;
663 PixelDepth = pixelDepth;
664 return true;
665}
666
667bool StreamManager::setPixelFormat(INDI_PIXEL_FORMAT pixelFormat, uint8_t pixelDepth)
668{
669 D_PTR(StreamManager);
670 return d->setPixelFormat(pixelFormat, pixelDepth);
671}
672
673
674void StreamManager::setSize(uint16_t width, uint16_t height)
675{
676 D_PTR(StreamManager);
677 d->setSize(width, height);
678}
679
680bool StreamManagerPrivate::recordStream(const uint8_t * buffer, uint32_t nbytes, double deltams, uint64_t timestamp)
681{
682 INDI_UNUSED(deltams);
683 if (!isRecording)
684 return false;
685
686 return recorder->writeFrame(buffer, nbytes, timestamp);
687}
688
689std::string StreamManagerPrivate::expand(const std::string &fname, const std::map<std::string, std::string> &patterns)
690{
691 std::string result = fname;
692
693 std::time_t t = std::time(nullptr);
694 std::tm tm = *std::gmtime(&t);
695
696 auto extendedPatterns = patterns;
697 extendedPatterns["_D_"] = format_time(tm, "%Y-%m-%d");
698 extendedPatterns["_H_"] = format_time(tm, "%H-%M-%S");
699 extendedPatterns["_T_"] = format_time(tm, "%Y-%m-%d" "@" "%H-%M-%S");
700
701 for(const auto &pattern : extendedPatterns)
702 {
703 replace_all(result, pattern.first, pattern.second);
704 }
705
706 // Replace all : to - to be valid filename on Windows
707 std::replace(result.begin(), result.end(), ':', '-'); // it's really needed now?
708
709 return result;
710}
711
713{
714 char errmsg[MAXRBUF];
715 std::string filename, expfilename, expfiledir;
716 std::string filtername;
717 std::map<std::string, std::string> patterns;
718 if (isRecording)
719 return true;
720
721 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
722 {
723 /* get filter name for pattern substitution */
724 if (dynamic_cast<INDI::CCD * >(currentDevice)->CurrentFilterSlot != -1
725 && dynamic_cast<INDI::CCD * >(currentDevice)->CurrentFilterSlot <= static_cast<int>(dynamic_cast<INDI::CCD * >
726 (currentDevice)->FilterNames.size()))
727 {
728 filtername = dynamic_cast<INDI::CCD*>(currentDevice)->FilterNames.at(dynamic_cast<INDI::CCD*>
730 patterns["_F_"] = filtername;
731 LOGF_DEBUG("Adding filter pattern %s", filtername.c_str());
732 }
733 }
734
735 recorder->setFPS(FpsNP[FPS_AVERAGE].getValue());
736
737 // _HOME_ expands to this machine's home directory. Clients (e.g. Ekos) cannot know
738 // in advance what the home directory of a remote INDI server is, so they send the
739 // _HOME_ token literally and let the driver resolve it locally.
740 if (const char * home = getenv("HOME"))
741 patterns["_HOME_"] = home;
742
743 /* pattern substitution */
744 recordfiledir.assign(RecordFileTP[0].getText());
745 expfiledir = expand(recordfiledir, patterns);
746 if (expfiledir.at(expfiledir.size() - 1) != '/')
747 expfiledir += '/';
748 recordfilename.assign(RecordFileTP[1].getText());
749 expfilename = expand(recordfilename, patterns);
750 if (expfilename.size() < 4 || expfilename.substr(expfilename.size() - 4, 4) != recorder->getExtension())
751 expfilename += recorder->getExtension();
752
753 filename = expfiledir + expfilename;
754 //LOGF_INFO("Expanded file is %s", filename.c_str());
755 //filename=recordfiledir+recordfilename;
756 LOGF_INFO("Record file is %s", filename.c_str());
757 /* Create/open file/dir */
758 if (mkpath(expfiledir, 0755))
759 {
760 LOGF_WARN("Can not create record directory %s: %s", expfiledir.c_str(),
761 strerror(errno));
762 return false;
763 }
764 if (!recorder->open(filename.c_str(), errmsg))
765 {
766 RecordStreamSP.setState(IPS_ALERT);
767 RecordStreamSP.apply();
768 LOGF_WARN("Can not open record file: %s", errmsg);
769 return false;
770 }
771
772#if 0
773 /* start capture */
774 // TODO direct recording should this be part of StreamManager?
775 if (direct_record)
776 {
777 LOG_INFO("Using direct recording (no software cropping).");
778 //v4l_base->doDecode(false);
779 //v4l_base->doRecord(true);
780 }
781 else
782 {
783 //if (ImageColorS[IMAGE_GRAYSCALE].s == ISS_ON)
784 if (dynamic_cast<INDI::CCD * >(currentDevice)->PrimaryCCD.getNAxis() == 2)
785 recorder->setDefaultMono();
786 else
787 recorder->setDefaultColor();
788 }
789#endif
790 FPSRecorder.reset();
792
793 if (isStreaming == false)
794 {
795 FPSAverage.reset();
796 FPSFast.reset();
797 }
798
799 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
800 {
801 if (isStreaming == false && dynamic_cast<INDI::CCD * >(currentDevice)->StartStreaming() == false)
802 {
803 LOG_ERROR("Failed to start recording.");
804 RecordStreamSP.setState(IPS_ALERT);
805 RecordStreamSP.reset();
807 RecordStreamSP.apply();
808 }
809 }
810 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
811 {
812 if (isStreaming == false && dynamic_cast<INDI::SensorInterface * >(currentDevice)->StartStreaming() == false)
813 {
814 LOG_ERROR("Failed to start recording.");
815 RecordStreamSP.setState(IPS_ALERT);
816 RecordStreamSP.reset();
818 RecordStreamSP.apply();
819 }
820 }
821 isRecording = true;
822 return true;
823}
824
826{
827 if (!isRecording && force == false)
828 return true;
829
830 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
831 {
832 if (!isStreaming)
833 dynamic_cast<INDI::CCD * >(currentDevice)->StopStreaming();
834 }
835 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
836 {
837 if (!isStreaming)
838 dynamic_cast<INDI::SensorInterface * >(currentDevice)->StopStreaming();
839
840 }
841
842 isRecording = false;
844
845 {
846 std::lock_guard<std::mutex> lock(recordMutex);
847 recorder->close();
848 }
849
850 if (force)
851 return false;
852
853 LOGF_INFO(
854 "Record Duration: %g millisec / %d frames",
855 FPSRecorder.totalTime(),
856 FPSRecorder.totalFrames()
857 );
858
859 return true;
860}
861
862bool StreamManagerPrivate::ISNewSwitch(const char * dev, const char * name, ISState * states, char * names[], int n)
863{
864 /* ignore if not ours */
865 if (dev != nullptr && strcmp(getDeviceName(), dev))
866 return false;
867
868 /* Video Stream */
869 if (StreamSP.isNameMatch(name))
870 {
871 for (int i = 0; i < n; i++)
872 {
873 if (!strcmp(names[i], "STREAM_ON") && states[i] == ISS_ON)
874 {
875 setStream(true);
876 break;
877 }
878 else if (!strcmp(names[i], "STREAM_OFF") && states[i] == ISS_ON)
879 {
880 setStream(false);
881 break;
882 }
883 }
884 return true;
885 }
886
887 // Record Stream
888 if (RecordStreamSP.isNameMatch(name))
889 {
890 int prevSwitch = RecordStreamSP.findOnSwitchIndex();
891 RecordStreamSP.update(states, names, n);
892
893 if (isRecording && RecordStreamSP[RECORD_OFF].getState() != ISS_ON)
894 {
895 RecordStreamSP.reset();
896 RecordStreamSP[prevSwitch].setState(ISS_ON);
897 RecordStreamSP.apply();
898 LOG_WARN("Recording device is busy.");
899 return true;
900 }
901
902 if (
903 RecordStreamSP[RECORD_ON ].getState() == ISS_ON ||
904 RecordStreamSP[RECORD_TIME ].getState() == ISS_ON ||
905 RecordStreamSP[RECORD_FRAME].getState() == ISS_ON
906 )
907 {
908 if (!isRecording)
909 {
910 RecordStreamSP.setState(IPS_BUSY);
911 if (RecordStreamSP[RECORD_TIME].getState() == ISS_ON)
912 LOGF_INFO("Starting video record (Duration): %g secs.", RecordOptionsNP[0].getValue());
913 else if (RecordStreamSP[RECORD_FRAME].getState() == ISS_ON)
914 LOGF_INFO("Starting video record (Frame count): %d.", static_cast<int>(RecordOptionsNP[1].getValue()));
915 else
916 LOG_INFO("Starting video record.");
917
918 if (!startRecording())
919 {
920 RecordStreamSP.reset();
922 RecordStreamSP.setState(IPS_ALERT);
923 }
924 }
925 }
926 else
927 {
928 RecordStreamSP.setState(IPS_IDLE);
929 Format.clear();
930 FpsNP[FPS_INSTANT].setValue(0);
931 FpsNP[FPS_AVERAGE].setValue(0);
932 if (isRecording)
933 {
934 LOG_INFO("Recording stream has been disabled. Closing the stream...");
936 }
937 }
938
939 RecordStreamSP.apply();
940 return true;
941 }
942
943 // Encoder Selection
944 if (EncoderSP.isNameMatch(name))
945 {
946 EncoderSP.update(states, names, n);
947 EncoderSP.setState(IPS_ALERT);
948
949 const char * selectedEncoder = EncoderSP.findOnSwitch()->getName();
950
951 for (EncoderInterface * oneEncoder : encoderManager.getEncoderList())
952 {
953 if (!strcmp(selectedEncoder, oneEncoder->getName()))
954 {
955 encoderManager.setEncoder(oneEncoder);
956
957 oneEncoder->setPixelFormat(PixelFormat, PixelDepth);
958
959 encoder = oneEncoder;
960
961 EncoderSP.setState(IPS_OK);
962 }
963 }
964 EncoderSP.apply();
965 return true;
966 }
967
968 // Recorder Selection
969 if (RecorderSP.isNameMatch(name))
970 {
971 RecorderSP.update(states, names, n);
972 RecorderSP.setState(IPS_ALERT);
973
974 const char * selectedRecorder = RecorderSP.findOnSwitch()->getName();
975
976 for (RecorderInterface * oneRecorder : recorderManager.getRecorderList())
977 {
978 if (!strcmp(selectedRecorder, oneRecorder->getName()))
979 {
980 recorderManager.setRecorder(oneRecorder);
981
982 oneRecorder->setPixelFormat(PixelFormat, PixelDepth);
983
984 recorder = oneRecorder;
985
986 RecorderSP.setState(IPS_OK);
987 }
988 }
989 RecorderSP.apply();
990 return true;
991 }
992
993 // Centroid Tracking
994 if (TrackingSP.isNameMatch(name))
995 {
996 TrackingSP.update(states, names, n);
998 return true;
999 }
1000
1001 // Full Depth Streaming
1002 if (FullDepthSP.isNameMatch(name))
1003 {
1004 currentDevice->updateProperty(FullDepthSP, states, names, n, [this, names]()
1005 {
1006 LOGF_INFO("Stream depth set to %s.", FullDepthSP[FULL_DEPTH_16BIT].isNameMatch(names[0]) == ISS_ON ? "16-bit" : "8-bit");
1007 return true;
1008 }, true);
1009 return true;
1010 }
1011
1012 // No properties were processed
1013 return false;
1014}
1015
1016bool StreamManager::ISNewSwitch(const char * dev, const char * name, ISState * states, char * names[], int n)
1017{
1018 D_PTR(StreamManager);
1019 return d->ISNewSwitch(dev, name, states, names, n);
1020}
1021
1022bool StreamManagerPrivate::ISNewText(const char * dev, const char * name, char * texts[], char * names[], int n)
1023{
1024 /* ignore if not ours */
1025 if (dev != nullptr && strcmp(getDeviceName(), dev))
1026 return false;
1027
1028 if (RecordFileTP.isNameMatch(name))
1029 {
1030 auto tp = RecordFileTP.findWidgetByName("RECORD_FILE_NAME");
1031 if (strchr(tp->getText(), '/'))
1032 {
1033 LOG_WARN("Dir. separator (/) not allowed in filename.");
1034 return true;
1035 }
1036
1037 RecordFileTP.update(texts, names, n);
1038 RecordFileTP.apply();
1039 return true;
1040 }
1041
1042 // No Properties were processed.
1043 return false;
1044}
1045
1046bool StreamManager::ISNewText(const char * dev, const char * name, char * texts[], char * names[], int n)
1047{
1048 D_PTR(StreamManager);
1049 return d->ISNewText(dev, name, texts, names, n);
1050}
1051
1052bool StreamManagerPrivate::ISNewNumber(const char * dev, const char * name, double values[], char * names[], int n)
1053{
1054 /* ignore if not ours */
1055 if (dev != nullptr && strcmp(getDeviceName(), dev))
1056 return false;
1057
1058 if (StreamExposureNP.isNameMatch(name))
1059 {
1060 StreamExposureNP.update(values, names, n);
1061 StreamExposureNP.setState(IPS_OK);
1062 StreamExposureNP.apply();
1063 return true;
1064 }
1065
1066 /* Limits */
1067 if (LimitsNP.isNameMatch(name))
1068 {
1069 LimitsNP.update(values, names, n);
1070
1071 FPSPreview.setTimeWindow(1000.0 / LimitsNP[LIMITS_PREVIEW_FPS].getValue());
1072 FPSPreview.reset();
1073
1074 LimitsNP.setState(IPS_OK);
1075 LimitsNP.apply();
1076 return true;
1077 }
1078
1079 /* Record Options */
1080 if (RecordOptionsNP.isNameMatch(name))
1081 {
1082 if (isRecording)
1083 {
1084 LOG_WARN("Recording device is busy");
1085 return true;
1086 }
1087
1088 RecordOptionsNP.update(values, names, n);
1089 RecordOptionsNP.setState(IPS_OK);
1090 RecordOptionsNP.apply();
1091 return true;
1092 }
1093
1094 /* Stream Frame */
1095 if (StreamFrameNP.isNameMatch(name))
1096 {
1097 if (isRecording)
1098 {
1099 LOG_WARN("Recording device is busy");
1100 return true;
1101 }
1102
1103 FrameInfo srcFrameInfo;
1104
1105 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
1106 {
1107 srcFrameInfo = FrameInfo(dynamic_cast<const INDI::CCD*>(currentDevice)->PrimaryCCD);
1108 }
1109 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
1110 {
1111 srcFrameInfo = FrameInfo(*dynamic_cast<const INDI::SensorInterface*>(currentDevice));
1112 }
1113
1114 StreamFrameNP.update(values, names, n);
1115 StreamFrameNP.setState(IPS_OK);
1116
1117 double subW = srcFrameInfo.w - StreamFrameNP[CCDChip::FRAME_X].getValue();
1118 double subH = srcFrameInfo.h - StreamFrameNP[CCDChip::FRAME_Y].getValue();
1119
1120 StreamFrameNP[CCDChip::FRAME_W].setValue(std::min(StreamFrameNP[CCDChip::FRAME_W].getValue(), subW));
1121 StreamFrameNP[CCDChip::FRAME_H].setValue(std::min(StreamFrameNP[CCDChip::FRAME_H].getValue(), subH));
1122
1124
1125 StreamFrameNP.apply();
1126 return true;
1127 }
1128
1129 /* Tracking Lock */
1130 if (TrackingLockNP.isNameMatch(name))
1131 {
1132 std::lock_guard<std::mutex> lock(trackingMutex);
1133 if (!isTracking)
1134 {
1135 LOG_WARN("Turn tracking on before setting the lock point.");
1136 TrackingLockNP.setState(IPS_ALERT);
1137 TrackingLockNP.apply();
1138 return true;
1139 }
1140
1141 TrackingLockNP.update(values, names, n);
1143 TrackingLockNP.setState(IPS_OK);
1144 TrackingLockNP.apply();
1145 LOGF_INFO("Tracking lock set to (%.1f, %.1f).", TrackingLockNP[TRACKING_LOCK_X].getValue(),
1146 TrackingLockNP[TRACKING_LOCK_Y].getValue());
1147 return true;
1148 }
1149
1150 /* Tracking Settings */
1151 if (TrackingSettingsNP.isNameMatch(name))
1152 {
1153 std::lock_guard<std::mutex> lock(trackingMutex);
1154 TrackingSettingsNP.update(values, names, n);
1155 FPSTracking.setTimeWindow(1000.0 / TrackingSettingsNP[TRACKING_RATE].getValue());
1156 FPSTracking.reset();
1157 TrackingSettingsNP.setState(IPS_OK);
1158 TrackingSettingsNP.apply();
1159 return true;
1160 }
1161
1162 // No properties were processed
1163 return false;
1164}
1165
1166bool StreamManager::ISNewNumber(const char * dev, const char * name, double values[], char * names[], int n)
1167{
1168 D_PTR(StreamManager);
1169 return d->ISNewNumber(dev, name, values, names, n);
1170}
1171
1173{
1174 if (enable)
1175 {
1176 if (!isStreaming)
1177 {
1178 StreamSP.setState(IPS_BUSY);
1179#if 0
1180 if (StreamOptionsN[OPTION_RATE_DIVISOR].value > 0)
1182 "Starting the video stream with target FPS %.f and rate divisor of %.f",
1183 StreamOptionsN[OPTION_TARGET_FPS].value, StreamOptionsN[OPTION_RATE_DIVISOR].value);
1184 else
1185 LOGF_INFO("Starting the video stream with target FPS %.f", StreamOptionsN[OPTION_TARGET_FPS].value);
1186#endif
1187 LOGF_INFO("Starting the video stream with target exposure %.6f s (Max theoretical FPS %.f)",
1188 StreamExposureNP[0].getValue(), 1 / StreamExposureNP[0].getValue());
1189
1190 FPSAverage.reset();
1191 FPSFast.reset();
1192 FPSPreview.reset();
1193 FPSPreview.setTimeWindow(1000.0 / LimitsNP[LIMITS_PREVIEW_FPS].getValue());
1195
1196 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
1197 {
1198 if (dynamic_cast<INDI::CCD * >(currentDevice)->StartStreaming() == false)
1199 {
1200 StreamSP.reset();
1201 StreamSP[1].setState(ISS_ON);
1202 StreamSP.setState(IPS_ALERT);
1203 LOG_ERROR("Failed to start streaming.");
1204 StreamSP.apply();
1205 return false;
1206 }
1207 }
1208 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
1209 {
1210 if (dynamic_cast<INDI::SensorInterface * >(currentDevice)->StartStreaming() == false)
1211 {
1212 StreamSP.reset();
1213 StreamSP[1].setState(ISS_ON);
1214 StreamSP.setState(IPS_ALERT);
1215 LOG_ERROR("Failed to start streaming.");
1216 StreamSP.apply();
1217 return false;
1218 }
1219 }
1220 isStreaming = true;
1221 Format.clear();
1222 FpsNP[FPS_INSTANT].setValue(0);
1223 FpsNP[FPS_AVERAGE].setValue(0);
1224 StreamSP.reset();
1225 StreamSP[0].setState(ISS_ON);
1226 recorder->setStreamEnabled(true);
1227 }
1228 }
1229 else
1230 {
1231 StreamSP.setState(IPS_IDLE);
1232 Format.clear();
1233 FpsNP[FPS_INSTANT].setValue(0);
1234 FpsNP[FPS_AVERAGE].setValue(0);
1235 if (isStreaming)
1236 {
1237 if (!isRecording)
1238 {
1239 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
1240 {
1241 if (dynamic_cast<INDI::CCD * >(currentDevice)->StopStreaming() == false)
1242 {
1243 StreamSP.setState(IPS_ALERT);
1244 LOG_ERROR("Failed to stop streaming.");
1245 StreamSP.apply();
1246 return false;
1247 }
1248 }
1249 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
1250 {
1251 if (dynamic_cast<INDI::SensorInterface * >(currentDevice)->StopStreaming() == false)
1252 {
1253 StreamSP.setState(IPS_ALERT);
1254 LOG_ERROR("Failed to stop streaming.");
1255 StreamSP.apply();
1256 return false;
1257 }
1258 }
1259 }
1260
1261 StreamSP.reset();
1262 StreamSP[1].setState(ISS_ON);
1263 isStreaming = false;
1264 Format.clear();
1265 FpsNP[FPS_INSTANT].setValue(0);
1266 FpsNP[FPS_AVERAGE].setValue(0);
1267
1268 recorder->setStreamEnabled(false);
1269 }
1270 }
1271
1272 StreamSP.apply();
1273 return true;
1274}
1275
1277{
1278 D_PTR(StreamManager);
1279 return d->setStream(enable);
1280}
1281
1283{
1284 D_PTR(StreamManager);
1285 d->EncoderSP.save(fp);
1286 d->RecordFileTP.save(fp);
1287 d->RecordOptionsNP.save(fp);
1288 d->RecorderSP.save(fp);
1289 d->LimitsNP.save(fp);
1290 d->FullDepthSP.save(fp);
1291 if (d->currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
1292 d->TrackingSettingsNP.save(fp);
1293 return true;
1294}
1295
1297{
1298 std::lock_guard<std::mutex> lock(trackingMutex);
1299
1300 if (enable == isTracking)
1301 return;
1302
1303 TrackingSP.reset();
1304 TrackingSP[enable ? TRACKING_ON : TRACKING_OFF].setState(ISS_ON);
1305
1306 if (enable)
1307 {
1308 frameTracker.reset();
1309 FPSTracking.reset();
1310 trackingFormatWarned = false;
1311 TrackingSP.setState(IPS_OK);
1312 // Busy until the first valid measurement acquires the lock
1313 TrackingOffsetNP.setState(IPS_BUSY);
1314 TrackingLockNP.setState(IPS_BUSY);
1315 LOG_INFO("Tracking enabled. The target position is measured while streaming or recording.");
1316 }
1317 else
1318 {
1319 TrackingSP.setState(IPS_IDLE);
1320 TrackingOffsetNP.setState(IPS_IDLE);
1321 TrackingLockNP.setState(IPS_IDLE);
1322 LOG_INFO("Tracking disabled.");
1323 }
1324
1325 isTracking = enable;
1326 TrackingSP.apply();
1327 TrackingOffsetNP.apply();
1328 TrackingLockNP.apply();
1329}
1330
1331void StreamManagerPrivate::processTracking(const uint8_t *buffer, size_t width, size_t height, size_t originX,
1332 size_t originY)
1333{
1334 std::lock_guard<std::mutex> lock(trackingMutex);
1335
1336 if (!isTracking || FPSTracking.newFrame() == false)
1337 return;
1338
1339 FrameTracker::Image image;
1340 image.data = buffer;
1341 image.width = width;
1342 image.height = height;
1343 image.bytesPerComponent = (PixelDepth + 7) / 8;
1344 switch (PixelFormat)
1345 {
1346 case INDI_MONO:
1347 break;
1348 case INDI_RGB:
1349 image.components = 3;
1350 break;
1351 case INDI_BAYER_GRBG:
1352 case INDI_BAYER_GBRG:
1353 case INDI_BAYER_RGGB:
1354 case INDI_BAYER_BGGR:
1355 image.bayer = true;
1356 break;
1357 default:
1359 {
1360 LOG_ERROR("Tracking is not supported for compressed (JPEG) streams.");
1361 trackingFormatWarned = true;
1362 TrackingOffsetNP.setState(IPS_ALERT);
1363 TrackingOffsetNP.apply();
1364 }
1365 return;
1366 }
1367
1368 FrameTracker::Measurement measurement = FrameTracker::measure(image, frameTracker.lockArea());
1369 // Report in sensor coordinates so changing the stream frame does not move the lock point
1370 measurement.x += originX;
1371 measurement.y += originY;
1372
1373 const bool hadLock = frameTracker.hasLock();
1374 const double now = std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count();
1375
1376 FrameTracker::Report report;
1377 const bool hasReport = frameTracker.addMeasurement(measurement, now, TrackingSettingsNP[TRACKING_AVERAGE].getValue(),
1378 report);
1379
1380 if (!hadLock && frameTracker.hasLock())
1381 {
1382 TrackingLockNP[TRACKING_LOCK_X].setValue(frameTracker.lockX());
1383 TrackingLockNP[TRACKING_LOCK_Y].setValue(frameTracker.lockY());
1384 TrackingLockNP.setState(IPS_OK);
1385 TrackingLockNP.apply();
1386 LOGF_INFO("Tracking locked at (%.1f, %.1f).", frameTracker.lockX(), frameTracker.lockY());
1387 }
1388
1389 if (!hasReport)
1390 return;
1391
1394 TrackingOffsetNP[TRACKING_QUALITY].setValue(report.quality);
1395 if (report.valid)
1396 {
1397 TrackingOffsetNP[TRACKING_CENTROID_X].setValue(report.x);
1398 TrackingOffsetNP[TRACKING_CENTROID_Y].setValue(report.y);
1399 TrackingOffsetNP[TRACKING_OFFSET_X].setValue(report.offsetX);
1400 TrackingOffsetNP[TRACKING_OFFSET_Y].setValue(report.offsetY);
1401 TrackingOffsetNP.setState(IPS_OK);
1402 }
1403 else
1404 TrackingOffsetNP.setState(IPS_ALERT);
1405 TrackingOffsetNP.apply();
1406}
1407
1408void StreamManagerPrivate::getStreamFrame(uint16_t * x, uint16_t * y, uint16_t * w, uint16_t * h) const
1409{
1410 *x = StreamFrameNP[CCDChip::FRAME_X].getValue();
1411 *y = StreamFrameNP[CCDChip::FRAME_Y].getValue();
1412 *w = StreamFrameNP[CCDChip::FRAME_W].getValue();
1413 *h = StreamFrameNP[CCDChip::FRAME_H].getValue();
1414}
1415
1416void StreamManagerPrivate::setStreamFrame(uint16_t x, uint16_t y, uint16_t w, uint16_t h)
1417{
1418 StreamFrameNP[CCDChip::FRAME_X].setValue(x);
1419 StreamFrameNP[CCDChip::FRAME_Y].setValue(y);
1420 StreamFrameNP[CCDChip::FRAME_W].setValue(w);
1421 StreamFrameNP[CCDChip::FRAME_H].setValue(h);
1422}
1423
1425{
1426 setStreamFrame(frameInfo.x, frameInfo.y, frameInfo.w, frameInfo.h);
1427}
1428
1429void StreamManager::getStreamFrame(uint16_t * x, uint16_t * y, uint16_t * w, uint16_t * h) const
1430{
1431 D_PTR(const StreamManager);
1432 d->getStreamFrame(x, y, w, h);
1433}
1434
1435bool StreamManagerPrivate::uploadStream(const uint8_t * buffer, uint32_t nbytes)
1436{
1437 // Send as is, already encoded.
1438 if (PixelFormat == INDI_JPG)
1439 {
1440 imageBP[0].setBlob(const_cast<uint8_t *>(buffer));
1441 imageBP[0].setBlobLen(nbytes);
1442 imageBP[0].setSize(nbytes);
1443 imageBP[0].setFormat(".stream_jpg");
1444 imageBP.setState(IPS_OK);
1445 imageBP.apply();
1446 return true;
1447 }
1448
1449 // Binning for grayscale frames only for now - REMOVE ME
1450#if 0
1451 if (dynamic_cast<INDI::CCD * >(currentDevice)->PrimaryCCD.getNAxis() == 2)
1452 {
1453 dynamic_cast<INDI::CCD*>(currentDevice)->PrimaryCCD.binFrame();
1454 nbytes /= dynamic_cast<INDI::CCD*>(currentDevice)->PrimaryCCD.getBinX() * dynamic_cast<INDI::CCD*>
1455 (currentDevice)->PrimaryCCD.getBinY();
1456 }
1457#endif
1458
1459 if(currentDevice->getDriverInterface() & INDI::DefaultDevice::CCD_INTERFACE)
1460 {
1461 if (encoder->upload(&imageBP[0], buffer, nbytes, dynamic_cast<INDI::CCD * >(currentDevice)->PrimaryCCD.isCompressed()))
1462 {
1463 // Upload to client now
1464 imageBP.setState(IPS_OK);
1465 imageBP.apply();
1466 return true;
1467 }
1468 }
1469 else if(currentDevice->getDriverInterface() & INDI::DefaultDevice::SENSOR_INTERFACE)
1470 {
1471 if (encoder->upload(&imageBP[0], buffer, nbytes,
1472 false))//dynamic_cast<INDI::SensorInterface*>(currentDevice)->isCompressed()))
1473 {
1474 // Upload to client now
1475 imageBP.setState(IPS_OK);
1476 imageBP.apply();
1477 return true;
1478 }
1479 }
1480
1481 return false;
1482}
1483
1485{
1486 D_PTR(const StreamManager);
1487 return d->recorder;
1488}
1489
1491{
1492 D_PTR(const StreamManager);
1493 return d->direct_record;
1494}
1495
1497{
1498 D_PTR(const StreamManager);
1499 return d->isStreaming;
1500}
1501
1503{
1504 D_PTR(const StreamManager);
1505 return d->isRecording && !d->isRecordingAboutToClose;
1506}
1507
1509{
1510 D_PTR(const StreamManager);
1511 return (d->isStreaming || d->isRecording);
1512}
1513
1515{
1516 D_PTR(const StreamManager);
1517 return 1.0 / d->StreamExposureNP[0].getValue();
1518}
1520{
1521 D_PTR(const StreamManager);
1522 return d->StreamExposureNP[0].getValue();
1523}
1524
1526{
1527 D_PTR(StreamManager);
1528 d->hasStreamingExposure = enable;
1529}
1530
1531}
bool isCompressed() const
isCompressed
Class to provide general functionality of CCD cameras with a single CCD sensor, or a primary CCD sens...
Definition indiccd.h:108
CCDChip PrimaryCCD
Definition indiccd.h:624
int CurrentFilterSlot
Definition indiccd.h:618
Class to provide extended functionality for devices in addition to the functionality provided by INDI...
The ElapsedTimer class provides a fast way to calculate elapsed times.
int64_t nsecsElapsed() const
Returns the number of nanoseconds since this ElapsedTimer was last started.
void start()
Starts this timer. Once started, a timer value can be checked with elapsed().
The EncoderInterface class is the base class for video streaming encoders.
static Measurement measure(const Image &image, double referenceArea=0)
measure Find the target in a single frame.
The RecorderInterface class is the base class for recorders.
The SensorDevice class provides functionality of a Sensor Device within a Sensor.
void start(const std::function< void(const std::atomic_bool &isAboutToClose)> &functionToRun)
Reserves a thread and uses it to run functionToRun. A running function can check the 'isAboutToClose'...
bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
std::atomic< bool > isRecording
bool setPixelFormat(INDI_PIXEL_FORMAT pixelFormat, uint8_t pixelDepth)
INDI::PropertyNumber TrackingSettingsNP
INDI::PropertySwitch RecordStreamSP
static std::string expand(const std::string &fname, const std::map< std::string, std::string > &patterns)
void setStreamFrame(uint16_t x, uint16_t y, uint16_t w, uint16_t h)
INDI::PropertySwitch EncoderSP
std::atomic< bool > isStreaming
std::atomic< bool > isTracking
INDI::PropertySwitch StreamSP
static void subframe(const uint8_t *srcBuffer, const FrameInfo &srcFrameInfo, uint8_t *dstBuffer, const FrameInfo &dstFrameInfo)
void newFrame(const uint8_t *buffer, uint32_t nbytes, uint64_t timestamp)
std::atomic< bool > isRecordingAboutToClose
bool stopRecording(bool force=false)
UniqueQueue< TimeFrame > framesIncoming
INDI::PropertySwitch FullDepthSP
void processTracking(const uint8_t *buffer, size_t width, size_t height, size_t originX, size_t originY)
processTracking Measure the target in a frame and publish the averaged offset.
std::atomic< bool > framesThreadTerminate
INDI::PropertyNumber RecordOptionsNP
const char * getDeviceName() const
INDI::PropertyNumber TrackingOffsetNP
INDI::PropertyNumber StreamTimeNP
INDI::PropertyNumber FpsNP
void setSize(uint16_t width, uint16_t height)
bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
INDI::PropertyNumber TrackingLockNP
bool uploadStream(const uint8_t *buffer, uint32_t nbytes)
uploadStream Upload frame to client using the selected encoder
INDI_PIXEL_FORMAT PixelFormat
INDI::PropertySwitch TrackingSP
bool recordStream(const uint8_t *buffer, uint32_t nbytes, double deltams, uint64_t timestamp)
recordStream Calls the backend recorder to record a single frame.
RecorderInterface * recorder
INDI::PropertyText RecordFileTP
INDI::PropertyNumber StreamFrameNP
INDI::PropertyNumber LimitsNP
StreamManagerPrivate(DefaultDevice *defaultDevice)
void getStreamFrame(uint16_t *x, uint16_t *y, uint16_t *w, uint16_t *h) const
void asyncStreamThread()
Thread processing frames and forwarding to recording and preview.
void ISGetProperties(const char *dev)
bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
INDI::PropertyNumber StreamExposureNP
INDI::PropertySwitch RecorderSP
void setSize(uint16_t width, uint16_t height=1)
bool isDirectRecording() const
void getStreamFrame(uint16_t *x, uint16_t *y, uint16_t *w, uint16_t *h) const
void newFrame(const uint8_t *buffer, uint32_t nbytes, uint64_t timestamp=0)
newFrame CCD drivers call this function when a new frame is received. It is then streamed,...
void setStreamingExposureEnabled(bool enable)
setStreamingExposureEnabled Can stream exposure time be changed?
std::shared_ptr< StreamManagerPrivate > d_ptr
bool setPixelFormat(INDI_PIXEL_FORMAT pixelFormat, uint8_t pixelDepth=8)
double getTargetExposure() const
bool setStream(bool enable)
setStream Enables (starts) or disables (stops) streaming.
double getTargetFPS() const
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
virtual void ISGetProperties(const char *dev)
virtual bool initProperties()
StreamManager(DefaultDevice *currentDevice)
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
virtual bool saveConfigItems(FILE *fp)
RecorderInterface * getRecorder() const
virtual bool updateProperties()
const char * getDeviceName() const
int errno
ISState
Switch state.
Definition indiapi.h:148
@ ISS_OFF
Definition indiapi.h:149
@ ISS_ON
Definition indiapi.h:150
@ IP_RW
Definition indiapi.h:184
@ IP_RO
Definition indiapi.h:182
@ IPS_BUSY
Definition indiapi.h:161
@ IPS_ALERT
Definition indiapi.h:162
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
@ ISR_1OFMANY
Definition indiapi.h:171
INDI_PIXEL_FORMAT
@ INDI_BAYER_GRBG
@ INDI_MONO
@ INDI_BAYER_GBRG
@ INDI_BAYER_BGGR
@ INDI_RGB
@ INDI_JPG
@ INDI_BAYER_RGGB
#define INDI_UNUSED(x)
Definition indidevapi.h:132
#define MAXRBUF
Definition indidriver.c:52
*brief user defined string literal for JSON values *sa std::size_t n
#define LOGF_INFO(fmt,...)
Definition indilogger.h:82
#define LOGF_WARN(fmt,...)
Definition indilogger.h:81
#define LOG_WARN(txt)
Definition indilogger.h:73
#define LOGF_DEBUG(fmt,...)
Definition indilogger.h:83
#define LOG_ERROR(txt)
Shorter logging macros. In order to use these macros, the function (or method) "getDeviceName()" must...
Definition indilogger.h:72
#define LOGF_ERROR(fmt,...)
Definition indilogger.h:80
#define LOG_INFO(txt)
Definition indilogger.h:74
#define DEBUGF(priority, msg,...)
Definition indilogger.h:57
Namespace to encapsulate INDI client, drivers, and mediator classes.
std::string format_time(const std::tm &tm, const char *format)
void replace_all(std::string &subject, const std::string &search, const std::string &replace)
int mkpath(std::string s, mode_t mode)
bool bayer
Raw Bayer mosaic: binning is kept even so each bin averages whole CFA cells.
size_t bytesPerComponent
1 for 8-bit, 2 for 16-bit (native endian) samples
size_t components
1 for mono or Bayer, 3 for interleaved RGB
double x
Centroid in frame pixels.
double offsetX
Averaged centroid minus lock point.
double quality
Mean quality of the valid samples, scaled by the fraction of samples that were valid.
double windowStart
Time of the first sample in the window.
bool valid
False if no sample in the window was valid (target lost).
double x
Averaged centroid in frame pixels.