Release 0.8.1 camera, browser audio and compact controls
Offline project checks / check (push) Canceled after 0s
Offline project checks / check (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
From: Samuel LEGROS <sam.legros@gmail.com>
|
||||
Subject: [PATCH] libcamera: add Sony IMX363 properties and gain helper
|
||||
|
||||
Adapted to libcamera 0.7.1 from the proposed upstream patch:
|
||||
https://patchwork.libcamera.org/patch/28201/
|
||||
Original Signed-off-by: Samuel LEGROS <sam.legros@gmail.com>
|
||||
The same 0..480 analogue gain code and 0x40 black level are exposed by
|
||||
our imported IMX363 kernel driver. Keep the Sony non-linear gain model
|
||||
so the software IPA does not treat a register code as a linear multiplier.
|
||||
|
||||
--- a/src/ipa/libipa/camera_sensor_helper.cpp
|
||||
+++ b/src/ipa/libipa/camera_sensor_helper.cpp
|
||||
@@ -617,6 +617,18 @@
|
||||
};
|
||||
REGISTER_CAMERA_SENSOR_HELPER("imx335", CameraSensorHelperImx335)
|
||||
|
||||
+class CameraSensorHelperImx363 : public CameraSensorHelper
|
||||
+{
|
||||
+public:
|
||||
+ CameraSensorHelperImx363()
|
||||
+ {
|
||||
+ /* 0x40 at 10 bits; Sony gain = 512 / (512 - code). */
|
||||
+ blackLevel_ = 4096;
|
||||
+ gain_ = AnalogueGainLinear{ 0, 512, -1, 512 };
|
||||
+ }
|
||||
+};
|
||||
+REGISTER_CAMERA_SENSOR_HELPER("imx363", CameraSensorHelperImx363)
|
||||
+
|
||||
class CameraSensorHelperImx415 : public CameraSensorHelper
|
||||
{
|
||||
public:
|
||||
--- a/src/libcamera/sensor/camera_sensor_properties.cpp
|
||||
+++ b/src/libcamera/sensor/camera_sensor_properties.cpp
|
||||
@@ -261,6 +261,22 @@
|
||||
.testPatternModes = {},
|
||||
.sensorDelays = { },
|
||||
} },
|
||||
+ { "imx363", {
|
||||
+ .unitCellSize = { 1400, 1400 },
|
||||
+ .testPatternModes = {
|
||||
+ { controls::draft::TestPatternModeOff, 0 },
|
||||
+ { controls::draft::TestPatternModeSolidColor, 1 },
|
||||
+ { controls::draft::TestPatternModeColorBars, 2 },
|
||||
+ { controls::draft::TestPatternModeColorBarsFadeToGray, 3 },
|
||||
+ { controls::draft::TestPatternModePn9, 4 },
|
||||
+ },
|
||||
+ .sensorDelays = {
|
||||
+ .exposureDelay = 2,
|
||||
+ .gainDelay = 2,
|
||||
+ .vblankDelay = 2,
|
||||
+ .hblankDelay = 2
|
||||
+ },
|
||||
+ } },
|
||||
{ "imx415", {
|
||||
.unitCellSize = { 1450, 1450 },
|
||||
.testPatternModes = {},
|
||||
@@ -0,0 +1,80 @@
|
||||
From: Platina Linux contributors
|
||||
Subject: [PATCH] ipa: simple: expose manual white balance alongside AWB
|
||||
|
||||
Use the public AwbEnable and ColourGains controls already used by other
|
||||
libcamera IPAs. Preserve automatic grey-world behaviour by default, and
|
||||
apply manual gains in linear sensor space before CCM and gamma. This
|
||||
allows live manual adjustment without changing recorded pixels afterward.
|
||||
|
||||
--- a/src/ipa/simple/algorithms/awb.h
|
||||
+++ b/src/ipa/simple/algorithms/awb.h
|
||||
@@ -19,6 +19,9 @@
|
||||
Awb() = default;
|
||||
~Awb() = default;
|
||||
|
||||
+ int init(IPAContext &context, const ValueNode &tuningData) override;
|
||||
+ void queueRequest(IPAContext &context, const uint32_t frame,
|
||||
+ IPAFrameContext &frameContext, const ControlList &controls) override;
|
||||
int configure(IPAContext &context, const IPAConfigInfo &configInfo) override;
|
||||
void prepare(IPAContext &context,
|
||||
const uint32_t frame,
|
||||
@@ -29,6 +32,9 @@
|
||||
IPAFrameContext &frameContext,
|
||||
const SwIspStats *stats,
|
||||
ControlList &metadata) override;
|
||||
+
|
||||
+private:
|
||||
+ bool enabled_ = true;
|
||||
};
|
||||
|
||||
} /* namespace ipa::soft::algorithms */
|
||||
--- a/src/ipa/simple/algorithms/awb.cpp
|
||||
+++ b/src/ipa/simple/algorithms/awb.cpp
|
||||
@@ -23,9 +23,35 @@
|
||||
|
||||
namespace ipa::soft::algorithms {
|
||||
|
||||
+int Awb::init(IPAContext &context, [[maybe_unused]] const ValueNode &tuningData)
|
||||
+{
|
||||
+ context.ctrlMap[&controls::AwbEnable] = ControlInfo(false, true, true);
|
||||
+ context.ctrlMap[&controls::ColourGains] =
|
||||
+ ControlInfo(0.25f, 4.0f, Span<const float, 2>{ { 1.0f, 1.0f } });
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+void Awb::queueRequest(IPAContext &context,
|
||||
+ [[maybe_unused]] const uint32_t frame,
|
||||
+ [[maybe_unused]] IPAFrameContext &frameContext,
|
||||
+ const ControlList &controls)
|
||||
+{
|
||||
+ if (const auto enabled = controls.get(controls::AwbEnable))
|
||||
+ enabled_ = *enabled;
|
||||
+ if (!enabled_) {
|
||||
+ if (const auto manual = controls.get(controls::ColourGains)) {
|
||||
+ auto &gains = context.activeState.awb.gains;
|
||||
+ gains = { { (*manual)[0], 1.0f, (*manual)[1] } };
|
||||
+ RGB<double> rgb{ { 1 / gains.r(), 1.0, 1 / gains.b() } };
|
||||
+ context.activeState.awb.temperatureK = estimateCCT(rgb);
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
int Awb::configure(IPAContext &context,
|
||||
[[maybe_unused]] const IPAConfigInfo &configInfo)
|
||||
{
|
||||
+ enabled_ = true;
|
||||
auto &gains = context.activeState.awb.gains;
|
||||
gains = { { 1.0, 1.0, 1.0 } };
|
||||
|
||||
@@ -64,6 +90,11 @@
|
||||
static_cast<float>(frameContext.gains.blue)
|
||||
};
|
||||
metadata.set(controls::ColourGains, mdGains);
|
||||
+ metadata.set(controls::AwbEnable, enabled_);
|
||||
+ if (!enabled_) {
|
||||
+ metadata.set(controls::ColourTemperature, context.activeState.awb.temperatureK);
|
||||
+ return;
|
||||
+ }
|
||||
|
||||
if (!stats->valid)
|
||||
return;
|
||||
@@ -0,0 +1,47 @@
|
||||
--- a/src/libcamera/pipeline/simple/simple.cpp
|
||||
+++ b/src/libcamera/pipeline/simple/simple.cpp
|
||||
@@ -692,6 +692,10 @@
|
||||
*/
|
||||
void SimpleCameraData::tryPipeline(unsigned int code, const Size &size)
|
||||
{
|
||||
+ /* Platina: retain the full sensor field of view at every output size. */
|
||||
+ if (sensor_->model() == "imx363" && size != Size(4032, 3024))
|
||||
+ return;
|
||||
+
|
||||
/*
|
||||
* Propagate the format through the pipeline, and enumerate the
|
||||
* corresponding possible V4L2 pixel formats on the video node.
|
||||
--- a/src/libcamera/software_isp/debayer_egl.cpp
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.cpp
|
||||
@@ -326,8 +326,10 @@
|
||||
~(inputConfig_.patternSize.width - 1);
|
||||
window_.y = ((inputCfg.size.height - outputCfg.size.height) / 2) &
|
||||
~(inputConfig_.patternSize.height - 1);
|
||||
- window_.width = outputCfg.size.width;
|
||||
- window_.height = outputCfg.size.height;
|
||||
+ window_.width = inputCfg.size.width;
|
||||
+ window_.height = inputCfg.size.height;
|
||||
+ window_.x = 0;
|
||||
+ window_.y = 0;
|
||||
|
||||
/*
|
||||
* Don't pass x,y from window_ since process() already adjusts for it.
|
||||
@@ -389,8 +391,7 @@
|
||||
* Scale input to output size, keeping the aspect ratio and preferring
|
||||
* cropping over black bars.
|
||||
*/
|
||||
- GLfloat scale = std::max((GLfloat)window_.width / width_,
|
||||
- (GLfloat)window_.height / height_);
|
||||
+ GLfloat scale = 1.0f;
|
||||
GLfloat trans = -(1.0f - scale);
|
||||
GLfloat projMatrix[] = {
|
||||
scale, 0, 0, 0,
|
||||
@@ -507,7 +508,7 @@
|
||||
egl_.createOutputDMABufTexture2D(*eglImageBayerOut_, out_fd);
|
||||
|
||||
setShaderVariableValues(params);
|
||||
- glViewport(0, 0, width_, height_);
|
||||
+ glViewport(0, 0, outputSize_.width, outputSize_.height);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
glDrawArrays(GL_TRIANGLE_FAN, 0, DEBAYER_OPENGL_COORDS);
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
--- a/include/libcamera/internal/egl.h
|
||||
+++ b/include/libcamera/internal/egl.h
|
||||
@@ -119,6 +119,7 @@
|
||||
void useProgram(GLuint programId);
|
||||
void deleteProgram(GLuint programId);
|
||||
void syncOutput();
|
||||
+ void flushOutput();
|
||||
|
||||
private:
|
||||
LIBCAMERA_DISABLE_COPY_AND_MOVE(eGL)
|
||||
--- a/src/libcamera/egl.cpp
|
||||
+++ b/src/libcamera/egl.cpp
|
||||
@@ -96,6 +96,15 @@
|
||||
ASSERT(tid_ == Thread::currentId());
|
||||
|
||||
glFinish();
|
||||
+}
|
||||
+
|
||||
+/**
|
||||
+ * \brief Submit GPU work without waiting, so CPU statistics can overlap it.
|
||||
+ */
|
||||
+void eGL::flushOutput()
|
||||
+{
|
||||
+ ASSERT(tid_ == Thread::currentId());
|
||||
+ glFlush();
|
||||
}
|
||||
|
||||
/**
|
||||
--- a/src/libcamera/software_isp/debayer_egl.cpp
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.cpp
|
||||
@@ -516,7 +516,7 @@
|
||||
LOG(eGL, Error) << "Drawing scene fail " << err;
|
||||
return -ENODEV;
|
||||
} else {
|
||||
- egl_.syncOutput();
|
||||
+ egl_.flushOutput();
|
||||
}
|
||||
|
||||
return 0;
|
||||
@@ -547,13 +547,14 @@
|
||||
goto error;
|
||||
}
|
||||
|
||||
- bench_.finishFrame();
|
||||
-
|
||||
metadata.planes()[0].bytesused = output->planes()[0].length;
|
||||
|
||||
/* Calculate stats for the whole frame */
|
||||
stats_->processFrame(frame, 0, input);
|
||||
dmaSyncers.clear();
|
||||
+
|
||||
+ egl_.syncOutput();
|
||||
+ bench_.finishFrame();
|
||||
|
||||
outputBufferReady.emit(output);
|
||||
inputBufferReady.emit(input);
|
||||
@@ -0,0 +1,160 @@
|
||||
--- a/src/libcamera/egl.cpp
|
||||
+++ b/src/libcamera/egl.cpp
|
||||
@@ -127,7 +127,7 @@
|
||||
EGLint image_attrs[] = {
|
||||
EGL_WIDTH, (EGLint)eglImage.width_,
|
||||
EGL_HEIGHT, (EGLint)eglImage.height_,
|
||||
- EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_ARGB8888,
|
||||
+ EGL_LINUX_DRM_FOURCC_EXT, output ? DRM_FORMAT_ARGB8888 : DRM_FORMAT_R8,
|
||||
EGL_DMA_BUF_PLANE0_FD_EXT, fd,
|
||||
EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0,
|
||||
EGL_DMA_BUF_PLANE0_PITCH_EXT, (EGLint)eglImage.stride_,
|
||||
@@ -153,6 +153,8 @@
|
||||
// Generate texture with filter semantics
|
||||
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
|
||||
eglDestroyImageKHR(display_, image);
|
||||
+ if (glGetError() != GL_NO_ERROR)
|
||||
+ return -ENODEV;
|
||||
|
||||
// Nearest filtering
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||
--- a/src/libcamera/software_isp/debayer_egl.cpp
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.cpp
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "debayer_egl.h"
|
||||
|
||||
#include <cmath>
|
||||
+#include <chrono>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
@@ -20,6 +21,13 @@
|
||||
#include "../glsl_shaders.h"
|
||||
|
||||
namespace libcamera {
|
||||
+
|
||||
+using ProfileClock = std::chrono::steady_clock;
|
||||
+static double milliseconds(ProfileClock::time_point a, ProfileClock::time_point b)
|
||||
+{
|
||||
+ return std::chrono::duration<double, std::milli>(b - a).count();
|
||||
+}
|
||||
+
|
||||
|
||||
/**
|
||||
* \class DebayerEGL
|
||||
@@ -36,6 +44,8 @@
|
||||
DebayerEGL::DebayerEGL(std::unique_ptr<SwStatsCpu> stats, const CameraManager &cm)
|
||||
: Debayer(cm), stats_(std::move(stats))
|
||||
{
|
||||
+ profile_ = utils::secure_getenv("PLATINA_GPU_PROFILE");
|
||||
+ inputDmabuf_ = utils::secure_getenv("PLATINA_GPU_INPUT_DMABUF");
|
||||
}
|
||||
|
||||
DebayerEGL::~DebayerEGL()
|
||||
@@ -496,13 +506,21 @@
|
||||
return;
|
||||
}
|
||||
|
||||
-int DebayerEGL::debayerGPU(MappedFrameBuffer &in, int out_fd, const DebayerParams ¶ms)
|
||||
+int DebayerEGL::debayerGPU(MappedFrameBuffer &in, int in_fd, int out_fd, const DebayerParams ¶ms)
|
||||
{
|
||||
/* eGL context switch */
|
||||
egl_.makeCurrent();
|
||||
|
||||
/* Create a standard texture input */
|
||||
- egl_.createTexture2D(*eglImageBayerIn_, glFormat_, inputConfig_.stride / bytesPerPixel_, height_, in.planes()[0].data());
|
||||
+ auto started = ProfileClock::now();
|
||||
+ if (inputDmabuf_ && egl_.createInputDMABufTexture2D(*eglImageBayerIn_, in_fd)) {
|
||||
+ inputDmabuf_ = false;
|
||||
+ LOG(Debayer, Warning) << "R8 DMA import unavailable; using texture upload";
|
||||
+ }
|
||||
+ if (!inputDmabuf_)
|
||||
+ egl_.createTexture2D(*eglImageBayerIn_, glFormat_, inputConfig_.stride / bytesPerPixel_, height_, in.planes()[0].data());
|
||||
+ auto uploaded = ProfileClock::now();
|
||||
+ inputMs_ = milliseconds(started, uploaded);
|
||||
|
||||
/* Generate the output render framebuffer as render to texture */
|
||||
egl_.createOutputDMABufTexture2D(*eglImageBayerOut_, out_fd);
|
||||
@@ -519,6 +537,7 @@
|
||||
} else {
|
||||
egl_.flushOutput();
|
||||
}
|
||||
+ submitMs_ = milliseconds(uploaded, ProfileClock::now());
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -526,6 +545,8 @@
|
||||
void DebayerEGL::process(uint32_t frame, FrameBuffer *input, FrameBuffer *output, const DebayerParams ¶ms)
|
||||
{
|
||||
bench_.startFrame();
|
||||
+ auto started = ProfileClock::now();
|
||||
+ ProfileClock::time_point statsStart, statsEnd, finished;
|
||||
|
||||
std::vector<DmaSyncer> dmaSyncers;
|
||||
|
||||
@@ -543,7 +564,7 @@
|
||||
goto error;
|
||||
}
|
||||
|
||||
- if (debayerGPU(in, output->planes()[0].fd.get(), params)) {
|
||||
+ if (debayerGPU(in, input->planes()[0].fd.get(), output->planes()[0].fd.get(), params)) {
|
||||
LOG(Debayer, Error) << "debayerGPU failed";
|
||||
goto error;
|
||||
}
|
||||
@@ -551,10 +572,25 @@
|
||||
metadata.planes()[0].bytesused = output->planes()[0].length;
|
||||
|
||||
/* Calculate stats for the whole frame */
|
||||
+ statsStart = ProfileClock::now();
|
||||
stats_->processFrame(frame, 0, input);
|
||||
+ statsEnd = ProfileClock::now();
|
||||
dmaSyncers.clear();
|
||||
|
||||
egl_.syncOutput();
|
||||
+ finished = ProfileClock::now();
|
||||
+ if (profile_) {
|
||||
+ const double values[] = {milliseconds(started, finished), inputMs_, submitMs_, milliseconds(statsStart, statsEnd), milliseconds(statsEnd, finished)};
|
||||
+ for (unsigned i = 0; i < 5; ++i) profileTotals_[i] += values[i];
|
||||
+ if (++profileFrames_ == 60) {
|
||||
+ LOG(Debayer, Info) << "PlatinaGPU total_ms=" << profileTotals_[0] / 60
|
||||
+ << " input_ms=" << profileTotals_[1] / 60 << " submit_ms=" << profileTotals_[2] / 60
|
||||
+ << " stats_ms=" << profileTotals_[3] / 60 << " wait_ms=" << profileTotals_[4] / 60
|
||||
+ << " input_dmabuf=" << inputDmabuf_;
|
||||
+ profileFrames_ = 0;
|
||||
+ for (double &value : profileTotals_) value = 0;
|
||||
+ }
|
||||
+ }
|
||||
bench_.finishFrame();
|
||||
|
||||
outputBufferReady.emit(output);
|
||||
@@ -580,7 +616,7 @@
|
||||
LOG(Debayer, Debug) << "Available fragment shader texture units " << maxTextureImageUnits;
|
||||
|
||||
/* Raw bayer input as texture */
|
||||
- eglImageBayerIn_ = std::make_unique<eGLImage>(width_, height_, inputConfig_.stride, GL_TEXTURE0, 0);
|
||||
+ eglImageBayerIn_ = std::make_unique<eGLImage>(inputConfig_.stride / bytesPerPixel_, height_, inputConfig_.stride, GL_TEXTURE0, 0);
|
||||
|
||||
/* Texture we will render to */
|
||||
eglImageBayerOut_ = std::make_unique<eGLImage>(outputSize_.width, outputSize_.height, outputConfig_.stride, GL_TEXTURE1, 1);
|
||||
--- a/src/libcamera/software_isp/debayer_egl.h
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.h
|
||||
@@ -66,7 +66,7 @@
|
||||
int initBayerShaders(PixelFormat inputFormat, PixelFormat outputFormat);
|
||||
int getShaderVariableLocations();
|
||||
void setShaderVariableValues(const DebayerParams ¶ms);
|
||||
- int debayerGPU(MappedFrameBuffer &in, int out_fd, const DebayerParams ¶ms);
|
||||
+ int debayerGPU(MappedFrameBuffer &in, int in_fd, int out_fd, const DebayerParams ¶ms);
|
||||
|
||||
/* Shader program identifiers */
|
||||
GLuint vertexShaderId_ = 0;
|
||||
@@ -107,6 +107,10 @@
|
||||
eGL egl_;
|
||||
uint32_t width_;
|
||||
uint32_t height_;
|
||||
+ bool profile_ = false;
|
||||
+ bool inputDmabuf_ = false;
|
||||
+ double inputMs_ = 0, submitMs_ = 0, profileTotals_[5] = {};
|
||||
+ unsigned int profileFrames_ = 0;
|
||||
GLint glFormat_;
|
||||
unsigned int bytesPerPixel_;
|
||||
uint32_t shaderStridePixels_;
|
||||
@@ -0,0 +1,99 @@
|
||||
--- a/src/libcamera/software_isp/debayer_egl.cpp
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.cpp
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
#include <cmath>
|
||||
#include <chrono>
|
||||
+#include <fstream>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
@@ -45,6 +46,8 @@
|
||||
: Debayer(cm), stats_(std::move(stats))
|
||||
{
|
||||
profile_ = utils::secure_getenv("PLATINA_GPU_PROFILE");
|
||||
+ if (const char *r = utils::secure_getenv("PLATINA_GPU_ROTATION"))
|
||||
+ rotation_ = std::atoi(r);
|
||||
inputDmabuf_ = utils::secure_getenv("PLATINA_GPU_INPUT_DMABUF");
|
||||
}
|
||||
|
||||
@@ -112,6 +115,7 @@
|
||||
ccmUniformDataIn_ = glGetUniformLocation(programId_, "ccm");
|
||||
blackLevelUniformDataIn_ = glGetUniformLocation(programId_, "blacklevel");
|
||||
gammaUniformDataIn_ = glGetUniformLocation(programId_, "gamma");
|
||||
+ saturationUniformDataIn_ = glGetUniformLocation(programId_, "platinaSaturation");
|
||||
contrastExpUniformDataIn_ = glGetUniformLocation(programId_, "contrastExp");
|
||||
|
||||
textureUniformStep_ = glGetUniformLocation(programId_, "tex_step");
|
||||
@@ -416,12 +420,24 @@
|
||||
{ +1.0f, +1.0f },
|
||||
{ +1.0f, -1.0f },
|
||||
};
|
||||
- static const GLfloat tcoordinates[4][2] = {
|
||||
+ const GLfloat baseCoordinates[4][2] = {
|
||||
{ 0.0f, 0.0f },
|
||||
{ 0.0f, 1.0f },
|
||||
{ 1.0f, 1.0f },
|
||||
{ 1.0f, 0.0f },
|
||||
};
|
||||
+
|
||||
+ auto &tcoordinates = textureCoordinates_;
|
||||
+ for (unsigned i = 0; i < 4; ++i) {
|
||||
+ tcoordinates[i][0] = baseCoordinates[i][0];
|
||||
+ tcoordinates[i][1] = baseCoordinates[i][1];
|
||||
+ }
|
||||
+ for (auto &coordinate : tcoordinates) {
|
||||
+ const GLfloat x = coordinate[0], y = coordinate[1];
|
||||
+ if (rotation_ == 90) { coordinate[0] = y; coordinate[1] = 1 - x; }
|
||||
+ else if (rotation_ == 180) { coordinate[0] = 1 - x; coordinate[1] = 1 - y; }
|
||||
+ else if (rotation_ == 270) { coordinate[0] = 1 - y; coordinate[1] = x; }
|
||||
+ }
|
||||
|
||||
/* vertexIn - bayer_8.vert */
|
||||
glEnableVertexAttribArray(attributeVertex_);
|
||||
@@ -495,6 +511,14 @@
|
||||
* Gamma
|
||||
*/
|
||||
glUniform1f(gammaUniformDataIn_, params.gamma);
|
||||
+ float saturation = 1.0f;
|
||||
+ if (const char *path = utils::secure_getenv("PLATINA_CAMERA_CONTROLS")) {
|
||||
+ std::ifstream controls(path);
|
||||
+ float gamma, contrast, value;
|
||||
+ if (controls >> gamma >> contrast >> value && std::isfinite(value) && value >= 0 && value <= 2)
|
||||
+ saturation = value;
|
||||
+ }
|
||||
+ glUniform1f(saturationUniformDataIn_, saturation);
|
||||
LOG(Debayer, Debug) << " gammaUniformDataIn_ " << gammaUniformDataIn_ << " data " << params.gamma;
|
||||
|
||||
/*
|
||||
--- a/src/libcamera/software_isp/debayer_egl.h
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.h
|
||||
@@ -98,6 +98,9 @@
|
||||
|
||||
/* Gamma */
|
||||
GLint gammaUniformDataIn_;
|
||||
+ GLint saturationUniformDataIn_ = -1;
|
||||
+ int rotation_ = 0;
|
||||
+ GLfloat textureCoordinates_[4][2] = {};
|
||||
|
||||
/* Contrast */
|
||||
GLint contrastExpUniformDataIn_;
|
||||
--- a/src/libcamera/shaders/bayer_1x_packed.frag
|
||||
+++ b/src/libcamera/shaders/bayer_1x_packed.frag
|
||||
@@ -69,6 +69,7 @@
|
||||
uniform vec3 blacklevel;
|
||||
uniform float gamma;
|
||||
uniform float contrastExp;
|
||||
+uniform float platinaSaturation;
|
||||
|
||||
float apply_contrast(float value)
|
||||
{
|
||||
@@ -282,6 +283,8 @@
|
||||
|
||||
/* Apply gamma after colour correction */
|
||||
rgb = pow(rgb, vec3(gamma));
|
||||
+ float luma = dot(rgb, vec3(0.299, 0.587, 0.114));
|
||||
+ rgb = clamp(mix(vec3(luma), rgb, platinaSaturation), 0.0, 1.0);
|
||||
|
||||
#if defined (SWAP_BLUE)
|
||||
gl_FragColor = vec4(rgb.bgr, 1.0);
|
||||
@@ -0,0 +1,110 @@
|
||||
From: Platina Linux contributors
|
||||
Subject: [PATCH] ipa: simple: add per-request manual exposure and gain
|
||||
|
||||
Keep the default AGC algorithm unchanged. AeEnable false applies bounded
|
||||
sensor time/gain after reporting actual delayed sensor metadata. Snapshot
|
||||
controls per frame so queued requests cannot change older statistics.
|
||||
platina_exposure.h is supplied by the device integration recipe.
|
||||
|
||||
--- a/src/ipa/simple/algorithms/agc.h
|
||||
+++ b/src/ipa/simple/algorithms/agc.h
|
||||
@@ -19,12 +19,18 @@
|
||||
Agc();
|
||||
~Agc() = default;
|
||||
|
||||
+ int init(IPAContext &context, const ValueNode &tuningData) override;
|
||||
+ int configure(IPAContext &context, const IPAConfigInfo &configInfo) override;
|
||||
+ void queueRequest(IPAContext &context, const uint32_t frame,
|
||||
+ IPAFrameContext &frameContext, const ControlList &controls) override;
|
||||
+
|
||||
void process(IPAContext &context, const uint32_t frame,
|
||||
IPAFrameContext &frameContext,
|
||||
const SwIspStats *stats,
|
||||
ControlList &metadata) override;
|
||||
|
||||
private:
|
||||
+ platina::ExposureSettings settings_;
|
||||
void updateExposure(IPAContext &context, IPAFrameContext &frameContext, double exposureMSV);
|
||||
};
|
||||
|
||||
--- a/src/ipa/simple/algorithms/agc.cpp
|
||||
+++ b/src/ipa/simple/algorithms/agc.cpp
|
||||
@@ -39,6 +39,40 @@
|
||||
|
||||
Agc::Agc()
|
||||
{
|
||||
+}
|
||||
+
|
||||
+int Agc::init(IPAContext &context, [[maybe_unused]] const ValueNode &tuningData)
|
||||
+{
|
||||
+ context.ctrlMap[&controls::AeEnable] = ControlInfo(false, true, true);
|
||||
+ /* Public request envelope; configured sensor limits are enforced below. */
|
||||
+ context.ctrlMap[&controls::ExposureTime] = ControlInfo(int32_t(100), int32_t(100000), int32_t(10000));
|
||||
+ context.ctrlMap[&controls::AnalogueGain] = ControlInfo(1.0f, 8.0f, 1.0f);
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+int Agc::configure([[maybe_unused]] IPAContext &context,
|
||||
+ [[maybe_unused]] const IPAConfigInfo &configInfo)
|
||||
+{
|
||||
+ settings_ = {};
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+void Agc::queueRequest([[maybe_unused]] IPAContext &context,
|
||||
+ [[maybe_unused]] const uint32_t frame,
|
||||
+ IPAFrameContext &frameContext, const ControlList &controls)
|
||||
+{
|
||||
+ if (const auto enabled = controls.get(controls::AeEnable))
|
||||
+ settings_.automatic = *enabled;
|
||||
+ /* Ignore manual values while automatic, as required by AeEnable. */
|
||||
+ if (!settings_.automatic) {
|
||||
+ if (const auto exposure = controls.get(controls::ExposureTime))
|
||||
+ settings_.exposureUs = std::clamp(*exposure, int32_t(100), int32_t(100000));
|
||||
+ if (const auto gain = controls.get(controls::AnalogueGain))
|
||||
+ settings_.gain = platina::sensorGain(*gain, 1.0, 8.0);
|
||||
+ }
|
||||
+ /* Snapshot the mode and values: another queued request must not alter
|
||||
+ * how statistics from this frame are processed. */
|
||||
+ frameContext.exposureControl = settings_;
|
||||
}
|
||||
|
||||
void Agc::updateExposure(IPAContext &context, IPAFrameContext &frameContext, double exposureMSV)
|
||||
@@ -109,6 +143,19 @@
|
||||
context.configuration.agc.lineDuration * frameContext.sensor.exposure;
|
||||
metadata.set(controls::ExposureTime, exposureTime.get<std::micro>());
|
||||
metadata.set(controls::AnalogueGain, frameContext.sensor.gain);
|
||||
+
|
||||
+ if (!frameContext.exposureControl.automatic) {
|
||||
+ const auto &limits = context.configuration.agc;
|
||||
+ frameContext.sensor.exposure = platina::exposureLines(
|
||||
+ frameContext.exposureControl.exposureUs,
|
||||
+ limits.lineDuration.get<std::micro>(), limits.exposureMin, limits.exposureMax);
|
||||
+ frameContext.sensor.gain = platina::sensorGain(
|
||||
+ frameContext.exposureControl.gain, limits.againMin, limits.againMax);
|
||||
+ context.activeState.agc.exposure = frameContext.sensor.exposure;
|
||||
+ context.activeState.agc.again = frameContext.sensor.gain;
|
||||
+ context.activeState.agc.valid = true;
|
||||
+ return;
|
||||
+ }
|
||||
|
||||
if (!context.activeState.agc.valid) {
|
||||
/*
|
||||
--- a/src/ipa/simple/ipa_context.h
|
||||
+++ b/src/ipa/simple/ipa_context.h
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <libipa/fc_queue.h>
|
||||
|
||||
#include "core_ipa_interface.h"
|
||||
+#include "algorithms/platina_exposure.h"
|
||||
|
||||
namespace libcamera {
|
||||
|
||||
@@ -64,6 +65,7 @@
|
||||
};
|
||||
|
||||
struct IPAFrameContext : public FrameContext {
|
||||
+ platina::ExposureSettings exposureControl;
|
||||
Matrix<float, 3, 3> ccm;
|
||||
|
||||
struct {
|
||||
@@ -0,0 +1,37 @@
|
||||
From: Platina Linux contributors
|
||||
Subject: [PATCH] software ISP: centered live digital zoom on GPU
|
||||
|
||||
Read the appended zoom control from the atomically replaced controls file.
|
||||
Crop normalized input coordinates after rotation, before debayering/scaling.
|
||||
Keep the output viewport, packed RAW addressing and Bayer parity unchanged.
|
||||
platina_zoom.h is provided by the device integration recipe.
|
||||
|
||||
--- a/src/libcamera/software_isp/debayer_egl.cpp
|
||||
+++ b/src/libcamera/software_isp/debayer_egl.cpp
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <cmath>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
+#include "platina_zoom.h"
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
@@ -432,11 +433,18 @@
|
||||
tcoordinates[i][0] = baseCoordinates[i][0];
|
||||
tcoordinates[i][1] = baseCoordinates[i][1];
|
||||
}
|
||||
+ float zoom = 1.0f;
|
||||
+ if (const char *path = utils::secure_getenv("PLATINA_CAMERA_CONTROLS")) {
|
||||
+ std::ifstream controls(path);
|
||||
+ zoom = platina::zoomFromControls(controls);
|
||||
+ }
|
||||
for (auto &coordinate : tcoordinates) {
|
||||
const GLfloat x = coordinate[0], y = coordinate[1];
|
||||
if (rotation_ == 90) { coordinate[0] = y; coordinate[1] = 1 - x; }
|
||||
else if (rotation_ == 180) { coordinate[0] = 1 - x; coordinate[1] = 1 - y; }
|
||||
else if (rotation_ == 270) { coordinate[0] = 1 - y; coordinate[1] = x; }
|
||||
+ coordinate[0] = platina::zoomCoordinate(coordinate[0], zoom);
|
||||
+ coordinate[1] = platina::zoomCoordinate(coordinate[1], zoom);
|
||||
}
|
||||
|
||||
/* vertexIn - bayer_8.vert */
|
||||
@@ -0,0 +1,91 @@
|
||||
# Headless GPU-enabled camera development build for Platina.
|
||||
pkgname=platina-libcamera
|
||||
pkgver=0.7.1
|
||||
pkgrel=31
|
||||
pkgdesc="Headless libcamera with GPU/CPU software ISP for Platina"
|
||||
url="https://libcamera.org/"
|
||||
arch="aarch64"
|
||||
license="LGPL-2.1-or-later AND GPL-2.0-or-later AND CC0-1.0"
|
||||
depends="alsa-utils python3 py3-paho-mqtt v4l-utils platina-mesa-freedreno"
|
||||
sonameprefix="platina-"
|
||||
makedepends="platina-mesa-freedreno coreutils eudev-dev gnutls-dev libevent-dev libjpeg-turbo-dev libyuv libyuv-dev linux-headers meson py3-jinja2 py3-ply py3-yaml python3-dev yaml-dev"
|
||||
source="https://gitlab.freedesktop.org/camera/libcamera/-/archive/v$pkgver/libcamera-v$pkgver.tar.gz
|
||||
imx363.yaml
|
||||
0001-imx363-properties.patch
|
||||
0002-simple-manual-white-balance.patch
|
||||
0003-platina-full-field-gpu-scale.patch
|
||||
0004-overlap-gpu-statistics.patch
|
||||
0005-platina-gpu-profile-dmabuf.patch
|
||||
0006-platina-gpu-rotation-saturation.patch
|
||||
0011-simple-manual-exposure.patch
|
||||
0012-platina-gpu-zoom.patch
|
||||
platina_exposure.h
|
||||
platina_zoom.h
|
||||
capture.cpp
|
||||
serve.py
|
||||
camera_mqtt.py
|
||||
platina-camera.openrc
|
||||
preview.html
|
||||
configuration.yaml"
|
||||
builddir="$srcdir/libcamera-v$pkgver"
|
||||
options="!strip !check"
|
||||
ldpath="/usr/lib/platina-camera/lib"
|
||||
|
||||
prepare() {
|
||||
default_prepare
|
||||
cp "$srcdir/platina_exposure.h" "$builddir/src/ipa/simple/algorithms/platina_exposure.h"
|
||||
cp "$srcdir/platina_zoom.h" "$builddir/src/libcamera/software_isp/platina_zoom.h"
|
||||
}
|
||||
|
||||
build() {
|
||||
export LDFLAGS="$LDFLAGS -Wl,-rpath,/usr/lib/platina-camera/gpu/lib -Wl,-rpath,/usr/lib/platina-camera/gpu/lib/dri"
|
||||
export PKG_CONFIG_PATH=/usr/lib/platina-camera/gpu/lib/pkgconfig
|
||||
abuild-meson --prefix=/usr/lib/platina-camera \
|
||||
--bindir=/usr/lib/platina-camera/bin --libdir=/usr/lib/platina-camera/lib \
|
||||
--libexecdir=/usr/lib/platina-camera/libexec --datadir=/usr/lib/platina-camera/share \
|
||||
--includedir=/usr/lib/platina-camera/include \
|
||||
-Dpipelines=simple -Dipas=simple -Dsoftisp-gpu=enabled \
|
||||
-Dcam=enabled -Dcam-jpeg=enabled -Dcam-output-kms=disabled -Dcam-output-sdl2=disabled \
|
||||
-Dqcam=disabled -Dgstreamer=disabled -Dpycamera=disabled -Dlc-compliance=disabled \
|
||||
-Ddocumentation=disabled -Dapps-output-dng=disabled -Dlibdw=disabled -Dlibunwind=disabled \
|
||||
-Dtracing=disabled -Dv4l2=disabled -Dtest=false -Dwerror=false . output
|
||||
meson compile -C output -j 2
|
||||
$CXX -std=c++17 -O2 -pthread -Iinclude -Ioutput/include "$srcdir/capture.cpp" \
|
||||
-Loutput/src/libcamera -Loutput/src/libcamera/base \
|
||||
-Wl,-rpath,/usr/lib/platina-camera/lib -Wl,-rpath-link,output/src/libcamera/base \
|
||||
-Wl,-rpath-link,/usr/lib/platina-camera/gpu/lib -Wl,-rpath-link,/usr/lib/platina-camera/gpu/lib/dri \
|
||||
-lcamera -lcamera-base -ljpeg -lyuv -o output/platina-camera-capture
|
||||
}
|
||||
|
||||
package() {
|
||||
DESTDIR="$pkgdir" meson install --no-rebuild -C output
|
||||
install -Dm755 output/platina-camera-capture "$pkgdir/usr/lib/platina-camera/bin/platina-camera-capture"
|
||||
install -Dm755 "$srcdir/serve.py" "$pkgdir/usr/lib/platina-camera/bin/serve.py"
|
||||
install -Dm644 "$srcdir/camera_mqtt.py" "$pkgdir/usr/lib/platina-camera/bin/camera_mqtt.py"
|
||||
install -Dm755 "$srcdir/platina-camera.openrc" "$pkgdir/etc/init.d/platina-camera"
|
||||
install -Dm644 "$srcdir/preview.html" "$pkgdir/usr/lib/platina-camera/bin/preview.html"
|
||||
install -Dm644 "$srcdir/configuration.yaml" "$pkgdir/usr/lib/platina-camera/share/libcamera/configuration.yaml"
|
||||
install -Dm644 "$srcdir/imx363.yaml" "$pkgdir/usr/lib/platina-camera/share/libcamera/ipa/simple/imx363.yaml"
|
||||
|
||||
}
|
||||
|
||||
sha512sums="
|
||||
0e886021a3bbd668184b581248b9d89a8e909360a7f138237a2c03b41b477cb255bd6daf4932fdebf86c3410b4deccc4c5db93264ed0c6c9969076cdbae8a77b libcamera-v0.7.1.tar.gz
|
||||
57c812b5666ebbe1f2a56e1469ad2233925064b4ed7d132b72e4913e24499eb5975f0a4cbe0941754f0a60b35313e19f27193ad1e458848519e5f826ca4c5e37 imx363.yaml
|
||||
6af6d7712077367f02a48988af33d22b50d4f2ea253463786ffc3b06e3150a7c6b0455f83e5cbd59388d5a76f8bca77d8a804de9452e0d747a1595501faf8d1c 0001-imx363-properties.patch
|
||||
cdb6f50dfc725b7266eac7feb7d880e2915d0e7872c88f522f3cd4f2a80dcd150ecde1a40c1dcfd054693f8028216841ca2c84e85525592aa067571d3c247755 0002-simple-manual-white-balance.patch
|
||||
2d84217307a09398767810e5a20bf1489dde38dbf3c19675ff4d90b44996fb486aa29aa096b4e6accba53d80c34dc5a8475f62939e37a63754cac2dc51f415c4 0003-platina-full-field-gpu-scale.patch
|
||||
e5a6e44e6243029038215e198259a4f213feceeb56ce0c71525edaaf3f350a2c0feaf8c14e2e69cd3501b80351b71b7ce69f9618ae776ed572c94b3970493c9d 0004-overlap-gpu-statistics.patch
|
||||
5756fc1de6f2de7db742d5be9fa01f91bdaa71a44b0cb7efcfb4572b464ba912f49795d85576b9b4b2bcedd7a99417c31984c54cb136456479b70f98bdb4ea05 0005-platina-gpu-profile-dmabuf.patch
|
||||
24f343ee9afc89503e0d3cddf736e06e7b27fe7d2d42552dfb49e8165c59cb11d48f55e8b38252a1ba54d7ad7189faf7510111d4fe7923e773f7d0774212b4b1 0006-platina-gpu-rotation-saturation.patch
|
||||
d4efc6815992d7e79b12583839f5394700c06f26c057feb2027391cfa9e12fe3bdeb4a7279dea4b1d76f45cd0372b5d5bb0d056781aaea5d762c4fb0f33e273b 0011-simple-manual-exposure.patch
|
||||
1cfd41c80346d90232aa842f71f1ceeb9e1322b0dc100dfa61964ee45c1551ed2f0b73211ae9abb94969d871b9b1a1ed3fa14bfc6b0c30dbcdbb436a8ff1ee15 0012-platina-gpu-zoom.patch
|
||||
8938ab20e273c06ab284f825b248e0190167165290d3f54dfdeba3066754dcbca0bde16ed6e29e455e1657fea44bf3fb2e962cdc9e2e3aad0fab214fc09b339b platina_exposure.h
|
||||
d083da94fbd1dd6e7d2e41ea22767e90e9fe8fcba9c4708676683e248c4131d5fbe45a6e4fc0d84680e2f17dbf9ebda75f99dc64e45172138cacb8c24b52de71 platina_zoom.h
|
||||
c28e44e939b3f212fd275967762f67e41a831b52a82a2a512ca21f1d77093ab8a2b1e926b55f775aa42b19e4339ffcf9d66d0223106e0ed41722828c01441441 capture.cpp
|
||||
4c5a42e531579783f03cd06d444e53ca159ef7ad043aafe8b6f9344e7f347e45d6fcf52600a2c0fec71921d4ccb39ab5f66f865ee9f804a897273859fa9ea615 serve.py
|
||||
8c8951b57b88f7e0a24d2f9f2fd9a2aaf0a717c2069e4b44a89c09e4c4891d10d7ff1732b3f3ba3a71e376c30738698a25ffb37949cedb515726aedbf6477cf5 camera_mqtt.py
|
||||
19550862ce07ec281021923a22d5149d582126bf202a7b4a7214d4cd5001c8ceadc351ddcc2fe7cf7909db53e2a6e77304fc7e7c514b174b49fd6ba5843ebf79 platina-camera.openrc
|
||||
3a89c3955e01ab24478f0806df294d40cced80b8b17b9421727a176449908da38d7c1f4f9fb61d8ba193fc58b303b0665b996014ab446fab18994c1f97c486ed preview.html
|
||||
1ed1a8976f5379216dff442ca9f5c849a5cde1c0a02fe8b07c8eb66d4058cc985f98d91e83cb144a740653577de2f7cd79e84552289411a630510926f237395a configuration.yaml
|
||||
"
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Home Assistant discovery and acknowledged controls; never restores ON at boot."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import queue
|
||||
import time
|
||||
|
||||
RESOLUTIONS = {'12 MP': 1, '5,4 MP': 1.5, '3 MP': 2, '1,3 MP': 3, '0,75 MP': 4, '0,33 MP': 6}
|
||||
NUMBERS = {
|
||||
'focus': ('Ostření', 0, 1023, 1, 'mdi:camera-iris'),
|
||||
'quality': ('Kvalita JPEG', 10, 95, 1, 'mdi:image'),
|
||||
'fps': ('Cílové FPS', 10, 30, 1, 'mdi:play-speed'),
|
||||
'gamma': ('Gama', .5, 4, .05, 'mdi:brightness-6'),
|
||||
'contrast': ('Kontrast', .5, 1.8, .02, 'mdi:contrast'),
|
||||
'saturation': ('Sytost', 0, 2, .02, 'mdi:palette'),
|
||||
'exposure_us': ('Expoziční čas (µs)', 100, 100000, 100, 'mdi:camera-timer'),
|
||||
'analogue_gain': ('Analogové zesílení', 1, 8, .1, 'mdi:brightness-6'),
|
||||
'zoom': ('Digitální zoom', 1, 10, .1, 'mdi:magnify-plus'),
|
||||
}
|
||||
|
||||
|
||||
def discovery(config):
|
||||
base = config['topic']
|
||||
uid = config['device_id']
|
||||
device = dict(identifiers=[uid], name='Platina kamera', manufacturer='Xiaomi',
|
||||
model='Mi 8 Lite / IMX363', sw_version='Platina Linux 0.8.1',
|
||||
configuration_url=config['web_url'])
|
||||
common = dict(device=device, availability_topic=base + '/availability',
|
||||
state_topic=base + '/state', origin=dict(name='Platina Linux', sw_version='0.8.1',
|
||||
support_url='https://github.com/Sukecz/platina-linux'))
|
||||
entities = []
|
||||
|
||||
def add(domain, key, **fields):
|
||||
payload = dict(common, unique_id=uid + '_' + key, **fields)
|
||||
entities.append((f'homeassistant/{domain}/{uid}/{key}/config', payload))
|
||||
|
||||
add('switch', 'stream', name='Kamera', icon='mdi:video',
|
||||
command_topic=base + '/set/enabled', value_template="{{ 'ON' if value_json.enabled else 'OFF' }}",
|
||||
payload_on='ON', payload_off='OFF', optimistic=False, retain=False, qos=1)
|
||||
for key, (name, low, high, step, icon) in NUMBERS.items():
|
||||
add('number', key, name=name, min=low, max=high, step=step, mode='slider', icon=icon,
|
||||
command_topic=base + '/set/' + key, value_template='{{ value_json.settings.' + key + ' }}',
|
||||
optimistic=False, retain=False, qos=1)
|
||||
add('switch', 'white_balance', name='Automatické vyvážení bílé', icon='mdi:white-balance-auto',
|
||||
command_topic=base + '/set/automatic',
|
||||
value_template="{{ 'ON' if value_json.settings.automatic else 'OFF' }}",
|
||||
payload_on='ON', payload_off='OFF', optimistic=False, retain=False, qos=1)
|
||||
add('switch', 'exposure_auto', name='Automatická expozice', icon='mdi:camera-auto',
|
||||
command_topic=base + '/set/exposure_auto',
|
||||
value_template="{{ 'ON' if value_json.settings.exposure_auto else 'OFF' }}",
|
||||
payload_on='ON', payload_off='OFF', optimistic=False, retain=False, qos=1)
|
||||
for key, name, unit in (('exposure_us_actual', 'Skutečný expoziční čas', 'µs'),
|
||||
('analogue_gain_actual', 'Skutečné analogové zesílení', '×')):
|
||||
add('sensor', key, name=name, unit_of_measurement=unit, state_class='measurement',
|
||||
availability=[dict(topic=base + '/availability'),
|
||||
dict(topic=base + '/state', value_template="{{ 'online' if value_json.state == 'on' and value_json." + key + " is number else 'offline' }}")],
|
||||
availability_mode='all', value_template='{{ value_json.' + key + ' | default(none) }}')
|
||||
entities[-1][1].pop('availability_topic', None)
|
||||
choices = json.dumps({str(v): k for k, v in RESOLUTIONS.items()}, ensure_ascii=False)
|
||||
add('select', 'resolution', name='Rozlišení', icon='mdi:aspect-ratio', options=list(RESOLUTIONS),
|
||||
command_topic=base + '/set/resolution',
|
||||
value_template='{{ (' + choices + ')[value_json.settings.scale | string] }}',
|
||||
optimistic=False, retain=False, qos=1)
|
||||
add('sensor', 'status', name='Stav kamery', icon='mdi:video-check', value_template='{{ value_json.state }}')
|
||||
add('sensor', 'fps', name='Skutečné FPS', icon='mdi:play-speed',
|
||||
value_template='{{ value_json.fps | default(0) | round(1) }}', state_class='measurement')
|
||||
add('button', 'save', name='Uložit nastavení', icon='mdi:content-save',
|
||||
command_topic=base + '/set/save', payload_press='PRESS', retain=False, qos=1)
|
||||
# Buttons do not consume a state topic.
|
||||
entities[-1][1].pop('state_topic', None)
|
||||
return entities
|
||||
|
||||
|
||||
class Bridge:
|
||||
def __init__(self, camera, path):
|
||||
import paho.mqtt.client as mqtt
|
||||
self.camera = camera
|
||||
self.config = json.loads(Path(path).read_text())
|
||||
self.topic = self.config['topic']
|
||||
self.commands = queue.Queue(maxsize=16)
|
||||
self.connected = False
|
||||
self.last_state = None
|
||||
self.last_publish = 0
|
||||
self.refresh = False
|
||||
if hasattr(mqtt, 'CallbackAPIVersion'):
|
||||
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,
|
||||
client_id=self.config['device_id'] + '_camera')
|
||||
else:
|
||||
self.client = mqtt.Client(client_id=self.config['device_id'] + '_camera')
|
||||
self.client.username_pw_set(self.config['username'], self.config['password'])
|
||||
self.client.will_set(self.topic + '/availability', 'offline', qos=1, retain=True)
|
||||
self.client.reconnect_delay_set(1, 30)
|
||||
self.client.max_queued_messages_set(64)
|
||||
self.client.on_connect = self.on_connect
|
||||
self.client.on_disconnect = self.on_disconnect
|
||||
self.client.on_message = self.on_message
|
||||
|
||||
def start(self):
|
||||
self.client.connect_async(self.config['host'], self.config.get('port', 1883), 30)
|
||||
self.client.loop_start()
|
||||
|
||||
def on_connect(self, client, userdata, flags, reason, properties=None):
|
||||
self.connected = reason == 0
|
||||
if self.connected:
|
||||
client.subscribe([(self.topic + '/set/+', 1), ('homeassistant/status', 1)])
|
||||
self.publish_discovery()
|
||||
client.publish(self.topic + '/availability', 'online', qos=1, retain=True)
|
||||
self.refresh = True
|
||||
|
||||
def on_disconnect(self, client, userdata, *args):
|
||||
self.connected = False
|
||||
|
||||
def publish_discovery(self):
|
||||
for topic, payload in discovery(self.config):
|
||||
self.client.publish(topic, json.dumps(payload, ensure_ascii=False), qos=1, retain=True)
|
||||
|
||||
def on_message(self, client, userdata, message):
|
||||
if message.topic == 'homeassistant/status':
|
||||
if message.payload == b'online':
|
||||
self.publish_discovery()
|
||||
self.refresh = True
|
||||
return
|
||||
# Retained commands must never turn the sensor on after startup/reconnect.
|
||||
if message.retain or len(message.payload) > 128:
|
||||
return
|
||||
try:
|
||||
self.commands.put_nowait((message.topic.rsplit('/', 1)[-1], message.payload.decode('utf-8')))
|
||||
except (queue.Full, UnicodeError):
|
||||
pass
|
||||
|
||||
def command(self, key, payload):
|
||||
if key in ('enabled', 'automatic', 'exposure_auto'):
|
||||
if payload not in ('ON', 'OFF'):
|
||||
raise ValueError('Invalid switch command')
|
||||
if key == 'enabled':
|
||||
self.camera.set_enabled(payload == 'ON')
|
||||
else:
|
||||
self.camera.configure({key: payload == 'ON'}, save=True)
|
||||
elif key == 'resolution':
|
||||
self.camera.configure({'scale': RESOLUTIONS[payload]}, save=True)
|
||||
elif key in NUMBERS:
|
||||
value = float(payload)
|
||||
if key in ('focus', 'quality', 'fps', 'exposure_us'):
|
||||
if not value.is_integer():
|
||||
raise ValueError('Expected integer')
|
||||
value = int(value)
|
||||
self.camera.configure({key: value}, save=True)
|
||||
elif key == 'save' and payload == 'PRESS':
|
||||
self.camera.configure({}, save=True)
|
||||
else:
|
||||
raise ValueError('Unknown command')
|
||||
|
||||
def tick(self):
|
||||
try:
|
||||
key, payload = self.commands.get_nowait()
|
||||
try:
|
||||
self.command(key, payload)
|
||||
except (ValueError, KeyError, OSError):
|
||||
print('Camera MQTT command rejected', flush=True)
|
||||
self.refresh = True
|
||||
except queue.Empty:
|
||||
pass
|
||||
if not self.connected:
|
||||
return
|
||||
now = time.monotonic()
|
||||
# Read image metadata at most once a second, even with no commands.
|
||||
if not self.refresh and now - self.last_publish < 1:
|
||||
return
|
||||
state = json.dumps(self.camera.status(), sort_keys=True)
|
||||
if self.refresh or state != self.last_state or now - self.last_publish >= 5:
|
||||
self.client.publish(self.topic + '/state', state, qos=1, retain=True)
|
||||
self.last_state = state
|
||||
self.last_publish = now
|
||||
self.refresh = False
|
||||
|
||||
def close(self):
|
||||
if self.connected:
|
||||
self.client.publish(self.topic + '/state', json.dumps(self.camera.status()), qos=1, retain=True)
|
||||
pending = self.client.publish(self.topic + '/availability', 'offline', qos=1, retain=True)
|
||||
pending.wait_for_publish(timeout=2)
|
||||
self.client.disconnect()
|
||||
self.client.loop_stop()
|
||||
@@ -0,0 +1,389 @@
|
||||
// SPDX-License-Identifier: GPL-2.0-only
|
||||
// Headless camera consumer. Bounded ISP requests and one latest JPEG job, no FIFO.
|
||||
#include <libcamera/camera.h>
|
||||
#include <libcamera/camera_manager.h>
|
||||
#include <libcamera/control_ids.h>
|
||||
#include <libcamera/formats.h>
|
||||
#include <libcamera/framebuffer_allocator.h>
|
||||
#include <libcamera/request.h>
|
||||
#include <cstdio>
|
||||
#include <jpeglib.h>
|
||||
#include <libyuv.h>
|
||||
#include <sys/mman.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include "platina_exposure.h"
|
||||
#include "platina_zoom.h"
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
static std::atomic<bool> stopping{false};
|
||||
static_assert(std::atomic<bool>::is_always_lock_free);
|
||||
static void stop(int) { stopping = true; }
|
||||
static int64_t monotonicNs() {
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count();
|
||||
}
|
||||
struct Settings {
|
||||
float gamma = 2.2f, contrast = 1.0f, saturation = 1.0f, red = 1.0f, blue = 1.0f;
|
||||
float scale = 2.0f;
|
||||
int automatic = 1, rotation = 90, quality = 50, fps = 30;
|
||||
int exposureAuto = 1, exposureUs = 10000;
|
||||
float analogueGain = 1.0f;
|
||||
float zoom = 1.0f;
|
||||
};
|
||||
class Capture {
|
||||
public:
|
||||
std::shared_ptr<libcamera::Camera> camera;
|
||||
libcamera::Stream *stream = nullptr;
|
||||
unsigned width = 0, height = 0, stride = 0;
|
||||
double ispScale = 1;
|
||||
int ispRotation = 0;
|
||||
bool ispSaturation = false;
|
||||
bool ispZoom = false;
|
||||
unsigned inFlight = 0, maxInFlight = 1;
|
||||
struct EncoderBuffers { std::vector<uint8_t> scaled, rotated, colored, packed; };
|
||||
std::mutex publishMutex;
|
||||
int64_t lastPublished = 0;
|
||||
Clock::time_point fpsStarted = Clock::now();
|
||||
unsigned fpsFrames = 0;
|
||||
double recentFps = 0;
|
||||
std::string output;
|
||||
Settings defaults;
|
||||
struct Mapping { void *base; size_t size; uint8_t *pixels; };
|
||||
std::map<libcamera::FrameBuffer *, Mapping> maps;
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
std::deque<libcamera::Request *> ready;
|
||||
libcamera::Request *latest = nullptr;
|
||||
std::atomic<uint64_t> captured{0}, encoded{0};
|
||||
std::vector<std::thread> encoders;
|
||||
Clock::time_point started = Clock::now();
|
||||
|
||||
Settings settings() const {
|
||||
Settings s = defaults;
|
||||
std::ifstream file(output + ".controls");
|
||||
Settings candidate;
|
||||
if (file >> candidate.gamma >> candidate.contrast >> candidate.saturation >>
|
||||
candidate.automatic >> candidate.red >> candidate.blue >> candidate.rotation >>
|
||||
candidate.scale >> candidate.quality >> candidate.fps >>
|
||||
candidate.exposureAuto >> candidate.exposureUs >> candidate.analogueGain >> candidate.zoom) {
|
||||
if (std::isfinite(candidate.gamma) && candidate.gamma >= .5f && candidate.gamma <= 4 &&
|
||||
std::isfinite(candidate.contrast) && candidate.contrast >= .5f && candidate.contrast <= 1.8f &&
|
||||
std::isfinite(candidate.saturation) && candidate.saturation >= 0 && candidate.saturation <= 2 &&
|
||||
std::isfinite(candidate.red) && candidate.red >= .25f && candidate.red <= 4 &&
|
||||
std::isfinite(candidate.blue) && candidate.blue >= .25f && candidate.blue <= 4 &&
|
||||
(candidate.automatic == 0 || candidate.automatic == 1) &&
|
||||
(candidate.rotation == 0 || candidate.rotation == 90 || candidate.rotation == 180 || candidate.rotation == 270) &&
|
||||
(candidate.scale == 1 || candidate.scale == 1.5f || candidate.scale == 2 || candidate.scale == 3 || candidate.scale == 4 || candidate.scale == 6) && candidate.quality >= 10 && candidate.quality <= 95 &&
|
||||
candidate.fps >= 10 && candidate.fps <= 30 &&
|
||||
(candidate.exposureAuto == 0 || candidate.exposureAuto == 1) &&
|
||||
candidate.exposureUs >= 100 && candidate.exposureUs <= 100000 &&
|
||||
std::isfinite(candidate.analogueGain) && candidate.analogueGain >= 1 && candidate.analogueGain <= 8 &&
|
||||
std::isfinite(candidate.zoom) && candidate.zoom >= 1 && candidate.zoom <= 10)
|
||||
{ candidate.fps = 30; s = candidate; }
|
||||
}
|
||||
return s;
|
||||
}
|
||||
void recycle(libcamera::Request *request) {
|
||||
request->reuse(libcamera::Request::ReuseBuffers);
|
||||
ready.push_back(request);
|
||||
}
|
||||
void complete(libcamera::Request *request) {
|
||||
if (request->status() == libcamera::Request::RequestCancelled || stopping) return;
|
||||
auto *buffer = request->findBuffer(stream);
|
||||
if (!buffer || buffer->metadata().status != libcamera::FrameMetadata::FrameSuccess) {
|
||||
std::cerr << "Camera buffer failed\n"; stopping = true; changed.notify_all(); return;
|
||||
}
|
||||
captured++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
// Drop an obsolete job before it enters the encoder.
|
||||
if (latest) recycle(latest);
|
||||
latest = request;
|
||||
if (inFlight) --inFlight;
|
||||
}
|
||||
changed.notify_all();
|
||||
}
|
||||
bool encode(libcamera::Request *request, EncoderBuffers &storage) {
|
||||
auto &scaledPixels = storage.scaled;
|
||||
auto &rotatedPixels = storage.rotated;
|
||||
auto &coloredPixels = storage.colored;
|
||||
const Settings s = settings();
|
||||
const int rotation = (s.rotation - ispRotation + 360) % 360;
|
||||
const float saturation = ispSaturation ? 1.0f : s.saturation;
|
||||
auto *buffer = request->findBuffer(stream);
|
||||
const auto &m = maps.at(buffer);
|
||||
struct jpeg_compress_struct jpeg{};
|
||||
struct jpeg_error_mgr error{};
|
||||
jpeg.err = jpeg_std_error(&error);
|
||||
jpeg_create_compress(&jpeg);
|
||||
unsigned char *data = nullptr;
|
||||
unsigned long length = 0;
|
||||
jpeg_mem_dest(&jpeg, &data, &length);
|
||||
const double scale = std::max(1.0, double(s.scale) / ispScale);
|
||||
const unsigned sampleWidth = static_cast<unsigned>(width / scale) & ~3U, sampleHeight = static_cast<unsigned>(height / scale) & ~3U;
|
||||
const bool portrait = rotation == 90 || rotation == 270;
|
||||
jpeg.image_width = portrait ? sampleHeight : sampleWidth;
|
||||
jpeg.image_height = portrait ? sampleWidth : sampleHeight;
|
||||
jpeg.input_components = 4;
|
||||
jpeg.in_color_space = JCS_EXT_BGRX;
|
||||
jpeg_set_defaults(&jpeg);
|
||||
jpeg_set_quality(&jpeg, s.quality, TRUE);
|
||||
jpeg_start_compress(&jpeg, TRUE);
|
||||
const auto sensorTime = request->metadata().get(libcamera::controls::SensorTimestamp).value_or(monotonicNs());
|
||||
char marker[80];
|
||||
int markerLength = snprintf(marker, sizeof(marker), "platina_capture_ns=%lld", static_cast<long long>(sensorTime));
|
||||
jpeg_write_marker(&jpeg, JPEG_COM, reinterpret_cast<const JOCTET *>(marker), markerLength);
|
||||
const int64_t encodingStart = monotonicNs();
|
||||
const uint8_t *pixels = m.pixels;
|
||||
unsigned pixelStride = stride;
|
||||
// GPU stride 8192 causes severe cache-set conflicts during transposition.
|
||||
// Copy rows once into a tightly packed cached buffer before rotation.
|
||||
if (rotation && scale == 1 && stride % 4096 == 0) {
|
||||
storage.packed.resize(width * height * 4);
|
||||
for (unsigned y = 0; y < height; ++y)
|
||||
std::memcpy(storage.packed.data() + y * width * 4,
|
||||
pixels + y * stride, width * 4);
|
||||
pixels = storage.packed.data(); pixelStride = width * 4;
|
||||
}
|
||||
const auto crop = platina::centerCrop(width, height, ispZoom ? 1.0f : s.zoom);
|
||||
if (scale > 1 || (!ispZoom && s.zoom > 1)) {
|
||||
scaledPixels.resize(sampleWidth * sampleHeight * 4);
|
||||
if (libyuv::ARGBScale(pixels + crop.y * pixelStride + crop.x * 4,
|
||||
pixelStride, crop.width, crop.height,
|
||||
scaledPixels.data(), sampleWidth * 4,
|
||||
sampleWidth, sampleHeight,
|
||||
crop.width < sampleWidth ? libyuv::kFilterBilinear : libyuv::kFilterBox) < 0)
|
||||
return false;
|
||||
pixels = scaledPixels.data(); pixelStride = sampleWidth * 4;
|
||||
}
|
||||
if (rotation) {
|
||||
rotatedPixels.resize(sampleWidth * sampleHeight * 4);
|
||||
if (libyuv::ARGBRotate(pixels, pixelStride, rotatedPixels.data(),
|
||||
jpeg.image_width * 4, sampleWidth, sampleHeight,
|
||||
static_cast<libyuv::RotationMode>(rotation)) < 0)
|
||||
return false;
|
||||
pixels = rotatedPixels.data(); pixelStride = jpeg.image_width * 4;
|
||||
}
|
||||
const int64_t rotatedAt = monotonicNs();
|
||||
if (std::abs(saturation - 1.0f) > .001f) {
|
||||
const float sat = saturation, other = 1.0f - sat;
|
||||
auto coefficient = [](float value) { return static_cast<int8_t>(std::lround(value * 64)); };
|
||||
const int8_t matrix[16] = {
|
||||
coefficient(.114f + .886f * sat), coefficient(.587f * other), coefficient(.299f * other), 0,
|
||||
coefficient(.114f * other), coefficient(.587f + .413f * sat), coefficient(.299f * other), 0,
|
||||
coefficient(.114f * other), coefficient(.587f * other), coefficient(.299f + .701f * sat), 0,
|
||||
0, 0, 0, 64
|
||||
};
|
||||
coloredPixels.resize(sampleWidth * sampleHeight * 4);
|
||||
if (libyuv::ARGBColorMatrix(pixels, pixelStride, coloredPixels.data(),
|
||||
jpeg.image_width * 4, matrix,
|
||||
jpeg.image_width, jpeg.image_height) < 0) return false;
|
||||
pixels = coloredPixels.data(); pixelStride = jpeg.image_width * 4;
|
||||
}
|
||||
const int64_t compressingAt = monotonicNs();
|
||||
while (jpeg.next_scanline < jpeg.image_height) {
|
||||
JSAMPROW row = const_cast<uint8_t *>(pixels + jpeg.next_scanline * pixelStride);
|
||||
jpeg_write_scanlines(&jpeg, &row, 1);
|
||||
}
|
||||
jpeg_finish_compress(&jpeg);
|
||||
jpeg_destroy_compress(&jpeg);
|
||||
const int64_t finished = monotonicNs();
|
||||
const auto gains = request->metadata().get(libcamera::controls::ColourGains);
|
||||
const auto exposure = request->metadata().get(libcamera::controls::ExposureTime);
|
||||
const auto sensorGain = request->metadata().get(libcamera::controls::AnalogueGain);
|
||||
// Independent encoders may finish out of order. Publish only newer
|
||||
// sensor frames, and serialize the atomic JPEG + metadata replacement.
|
||||
std::lock_guard<std::mutex> publish(publishMutex);
|
||||
if (sensorTime <= lastPublished) { free(data); return true; }
|
||||
std::string temporary = output + ".new";
|
||||
FILE *f = fopen(temporary.c_str(), "wb");
|
||||
bool ok = f && fwrite(data, 1, length, f) == length;
|
||||
if (f && fclose(f) != 0) ok = false;
|
||||
if (ok && rename(temporary.c_str(), output.c_str()) != 0) ok = false;
|
||||
free(data);
|
||||
if (!ok) return false;
|
||||
lastPublished = sensorTime;
|
||||
const int64_t published = monotonicNs();
|
||||
encoded++;
|
||||
fpsFrames++;
|
||||
double window = std::chrono::duration<double>(Clock::now() - fpsStarted).count();
|
||||
if (window >= 1.0) {
|
||||
recentFps = fpsFrames / window;
|
||||
fpsFrames = 0; fpsStarted = Clock::now();
|
||||
}
|
||||
std::ofstream meta(output + ".meta.new");
|
||||
meta << "{\"captured_ns\":" << sensorTime << ",\"published_ns\":" << published
|
||||
<< ",\"sensor_age_ms\":" << (published - sensorTime) / 1000000.0
|
||||
<< ",\"jpeg_ms\":" << (finished - encodingStart) / 1000000.0
|
||||
<< ",\"rotate_scale_ms\":" << (rotatedAt - encodingStart) / 1000000.0
|
||||
<< ",\"compression_ms\":" << (finished - compressingAt) / 1000000.0
|
||||
<< ",\"frames_in\":" << captured.load() << ",\"frames_out\":" << encoded.load()
|
||||
<< ",\"fps\":" << recentFps
|
||||
<< ",\"width\":" << (portrait ? sampleHeight : sampleWidth)
|
||||
<< ",\"height\":" << (portrait ? sampleWidth : sampleHeight)
|
||||
<< ",\"red_gain\":" << (gains ? (*gains)[0] : 1.0f)
|
||||
<< ",\"blue_gain\":" << (gains ? (*gains)[1] : 1.0f)
|
||||
<< ",\"exposure_us_actual\":" << (exposure ? std::to_string(*exposure) : "null")
|
||||
<< ",\"analogue_gain_actual\":" << (sensorGain ? std::to_string(*sensorGain) : "null") << "}";
|
||||
meta.close();
|
||||
rename((output + ".meta.new").c_str(), (output + ".meta").c_str());
|
||||
return true;
|
||||
}
|
||||
void encodeLoop() {
|
||||
EncoderBuffers storage;
|
||||
while (!stopping) {
|
||||
libcamera::Request *request = nullptr;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
changed.wait_for(lock, std::chrono::milliseconds(50), [&] { return latest || stopping; });
|
||||
if (stopping) break;
|
||||
if (!latest) continue;
|
||||
request = latest; latest = nullptr;
|
||||
}
|
||||
if (captured > 10 && !encode(request, storage)) { stopping = true; changed.notify_all(); break; }
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
recycle(request);
|
||||
}
|
||||
changed.notify_all();
|
||||
}
|
||||
}
|
||||
};
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2 || argc > 4 || argv[1][0] != '/') {
|
||||
std::cerr << "Usage: platina-camera-capture /absolute/path/latest.jpg [0|90|180|270] [1|2|3|4|6]\n"; return 2;
|
||||
}
|
||||
signal(SIGINT, stop); signal(SIGTERM, stop);
|
||||
Capture c;
|
||||
c.output = argv[1];
|
||||
if (argc >= 3) {
|
||||
std::string angle(argv[2]);
|
||||
if (angle != "0" && angle != "90" && angle != "180" && angle != "270") return 2;
|
||||
c.defaults.rotation = std::stoi(angle);
|
||||
}
|
||||
if (argc == 4) {
|
||||
std::string scale(argv[3]);
|
||||
if (scale != "1" && scale != "1.5" && scale != "2" && scale != "3" && scale != "4" && scale != "6") return 2;
|
||||
c.defaults.scale = std::stof(scale);
|
||||
}
|
||||
const Settings configured = c.settings();
|
||||
bool gpu = std::getenv("LIBCAMERA_SOFTISP_MODE") && std::string(std::getenv("LIBCAMERA_SOFTISP_MODE")) == "gpu";
|
||||
c.ispScale = gpu ? configured.scale : 1;
|
||||
c.ispRotation = gpu && c.ispScale > 1 ? configured.rotation : 0;
|
||||
c.ispSaturation = gpu;
|
||||
c.ispZoom = gpu;
|
||||
setenv("PLATINA_GPU_ROTATION", std::to_string(c.ispRotation).c_str(), 1);
|
||||
setenv("PLATINA_CAMERA_CONTROLS", (c.output + ".controls").c_str(), 1);
|
||||
libcamera::CameraManager manager;
|
||||
if (manager.start() < 0 || manager.cameras().size() != 1) { std::cerr << "Expected one camera\n"; return 1; }
|
||||
c.camera = manager.cameras().front();
|
||||
if (c.camera->acquire() < 0) return 1;
|
||||
auto config = c.camera->generateConfiguration({libcamera::StreamRole::Viewfinder});
|
||||
if (!config || config->empty()) return 1;
|
||||
auto &cfg = config->at(0);
|
||||
// Always read the full sensor. Output scaling never changes the field of view.
|
||||
c.maxInFlight = gpu ? 2 : 1;
|
||||
if (const char *count = std::getenv("PLATINA_CAMERA_IN_FLIGHT")) {
|
||||
try { c.maxInFlight = std::clamp(std::stoul(count), 1UL, 2UL); }
|
||||
catch (...) { return 2; }
|
||||
}
|
||||
cfg.size = { static_cast<unsigned>(4024U / c.ispScale) & ~3U, static_cast<unsigned>(3016U / c.ispScale) & ~3U };
|
||||
if (c.ispRotation == 90 || c.ispRotation == 270)
|
||||
cfg.size = {cfg.size.height, cfg.size.width};
|
||||
cfg.pixelFormat = libcamera::formats::XRGB8888;
|
||||
unsigned jpegThreads = 4;
|
||||
if (const char *count = std::getenv("PLATINA_JPEG_THREADS")) {
|
||||
try { jpegThreads = std::clamp(std::stoul(count), 1UL, 4UL); }
|
||||
catch (...) { return 2; }
|
||||
}
|
||||
cfg.bufferCount = jpegThreads + 4;
|
||||
if (config->validate() == libcamera::CameraConfiguration::Invalid || c.camera->configure(config.get()) < 0) return 1;
|
||||
for (unsigned id : {libcamera::controls::AeEnable.id(), libcamera::controls::ExposureTime.id(),
|
||||
libcamera::controls::AnalogueGain.id()}) {
|
||||
if (!c.camera->controls().count(id)) {
|
||||
std::cerr << "Camera pipeline lacks exposure controls\n";
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (cfg.pixelFormat != libcamera::formats::XRGB8888) return 1;
|
||||
c.width = cfg.size.width; c.height = cfg.size.height; c.stride = cfg.stride; c.stream = cfg.stream();
|
||||
std::cerr << "Configured " << cfg.toString() << " stride=" << cfg.stride << '\n';
|
||||
auto allocator = std::make_unique<libcamera::FrameBufferAllocator>(c.camera);
|
||||
if (allocator->allocate(c.stream) < 0) return 1;
|
||||
std::vector<std::unique_ptr<libcamera::Request>> requests;
|
||||
for (const auto &buffer : allocator->buffers(c.stream)) {
|
||||
if (buffer->planes().size() != 1) return 1;
|
||||
const auto &plane = buffer->planes()[0];
|
||||
size_t size = plane.offset + plane.length;
|
||||
if (plane.length < c.stride * c.height) return 1;
|
||||
void *base = mmap(nullptr, size, PROT_READ, MAP_SHARED, plane.fd.get(), 0);
|
||||
if (base == MAP_FAILED) return 1;
|
||||
c.maps.emplace(buffer.get(), Capture::Mapping{base, size, static_cast<uint8_t *>(base) + plane.offset});
|
||||
auto request = c.camera->createRequest();
|
||||
if (!request || request->addBuffer(c.stream, buffer.get()) < 0) return 1;
|
||||
c.ready.push_back(request.get()); requests.push_back(std::move(request));
|
||||
}
|
||||
c.camera->requestCompleted.connect(&c, &Capture::complete);
|
||||
if (c.camera->start() < 0) return 1;
|
||||
for (unsigned i = 0; i < jpegThreads; ++i)
|
||||
c.encoders.emplace_back(&Capture::encodeLoop, &c);
|
||||
bool reconfigure = false;
|
||||
auto next = Clock::now();
|
||||
while (!stopping) {
|
||||
libcamera::Request *request = nullptr;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(c.mutex);
|
||||
c.changed.wait_for(lock, std::chrono::milliseconds(50), [&] { return stopping || (c.inFlight < c.maxInFlight && !c.ready.empty()); });
|
||||
if (stopping) break;
|
||||
if (c.inFlight < c.maxInFlight && !c.ready.empty()) {
|
||||
request = c.ready.front(); c.ready.pop_front(); ++c.inFlight;
|
||||
}
|
||||
}
|
||||
if (!request) continue;
|
||||
auto s = c.settings();
|
||||
if (gpu && (double(s.scale) != c.ispScale || s.rotation != configured.rotation)) { reconfigure = true; break; }
|
||||
auto &ctrl = request->controls();
|
||||
ctrl.set(libcamera::controls::AeEnable, bool(s.exposureAuto));
|
||||
if (!s.exposureAuto) {
|
||||
ctrl.set(libcamera::controls::ExposureTime, s.exposureUs);
|
||||
ctrl.set(libcamera::controls::AnalogueGain, s.analogueGain);
|
||||
}
|
||||
ctrl.set(libcamera::controls::Gamma, s.gamma);
|
||||
ctrl.set(libcamera::controls::Contrast, s.contrast);
|
||||
// Saturation is applied with SIMD after the ISP; no costly identity CCM.
|
||||
ctrl.set(libcamera::controls::AwbEnable, bool(s.automatic));
|
||||
const float gains[2] = {s.red, s.blue};
|
||||
ctrl.set(libcamera::controls::ColourGains, libcamera::Span<const float, 2>(gains));
|
||||
next = std::max(next, Clock::now());
|
||||
std::this_thread::sleep_until(next);
|
||||
if (c.camera->queueRequest(request) < 0) stopping = true;
|
||||
next += std::chrono::microseconds(1000000 / s.fps);
|
||||
}
|
||||
stopping = true;
|
||||
c.camera->stop();
|
||||
c.changed.notify_all();
|
||||
for (auto &encoder : c.encoders) if (encoder.joinable()) encoder.join();
|
||||
c.camera->requestCompleted.disconnect(&c);
|
||||
for (auto &[buffer, map] : c.maps) munmap(map.base, map.size);
|
||||
requests.clear(); allocator->free(c.stream); allocator.reset();
|
||||
c.camera->release(); config.reset(); c.camera.reset(); manager.stop();
|
||||
std::cerr << "Stopped after " << c.captured << " camera frames and " << c.encoded << " JPEGs\n";
|
||||
if (reconfigure) { execl(argv[0], argv[0], argv[1], nullptr); return 1; }
|
||||
return c.encoded > 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
---
|
||||
version: 1
|
||||
configuration:
|
||||
software_isp:
|
||||
mode: cpu
|
||||
threads: 4
|
||||
@@ -0,0 +1,14 @@
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
# IMX363 black level plus the upstream software ISP algorithms.
|
||||
# Manual white balance is linear; saturation uses the consumer's SIMD path.
|
||||
# The investigated DNG CCM is nearly identity and is not enabled here.
|
||||
%YAML 1.1
|
||||
---
|
||||
version: 1
|
||||
algorithms:
|
||||
- BlackLevel:
|
||||
blackLevel: 4096
|
||||
- Awb:
|
||||
- Adjust:
|
||||
- Agc:
|
||||
...
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/sbin/openrc-run
|
||||
description="Platina camera web and Home Assistant controls (capture OFF at startup)"
|
||||
command="/usr/bin/python3"
|
||||
command_args="/usr/lib/platina-camera/bin/serve.py --listen 0.0.0.0"
|
||||
command_user="root:root"
|
||||
supervisor="supervise-daemon"
|
||||
pidfile="/run/platina-camera.pid"
|
||||
respawn_delay=5
|
||||
respawn_max=5
|
||||
respawn_period=1800
|
||||
output_log="/var/log/platina-camera.log"
|
||||
error_log="/var/log/platina-camera.log"
|
||||
|
||||
depend() {
|
||||
need localmount
|
||||
use networkmanager
|
||||
after udev-trigger
|
||||
}
|
||||
|
||||
start_pre() {
|
||||
checkpath --file --mode 0640 --owner root:root "$output_log"
|
||||
checkpath --directory --mode 0700 --owner root:root /etc/platina-camera
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/* SPDX-License-Identifier: LGPL-2.1-or-later */
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
namespace platina {
|
||||
|
||||
struct ExposureSettings {
|
||||
bool automatic = true;
|
||||
int32_t exposureUs = 10000;
|
||||
double gain = 1.0;
|
||||
};
|
||||
|
||||
/* Clamp before conversion to avoid integer overflow on external controls.
|
||||
* Sensor exposure uses whole lines; metadata reports the quantized result. */
|
||||
inline int32_t exposureLines(int32_t exposureUs, double lineUs,
|
||||
int32_t minimum, int32_t maximum)
|
||||
{
|
||||
double lines = std::clamp(exposureUs / lineUs,
|
||||
double(minimum), double(maximum));
|
||||
return static_cast<int32_t>(std::lround(lines));
|
||||
}
|
||||
|
||||
inline double sensorGain(double requested, double minimum, double maximum)
|
||||
{
|
||||
return std::isfinite(requested) ? std::clamp(requested, minimum, maximum) : minimum;
|
||||
}
|
||||
|
||||
} /* namespace platina */
|
||||
@@ -0,0 +1,44 @@
|
||||
/* SPDX-License-Identifier: LGPL-2.1-or-later */
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <istream>
|
||||
|
||||
namespace platina {
|
||||
|
||||
/* The controls file is atomically replaced by the controller. Zoom is appended
|
||||
* after the thirteen existing fields, preserving earlier field positions. */
|
||||
inline float zoomFromControls(std::istream &input)
|
||||
{
|
||||
double field;
|
||||
for (unsigned i = 0; i < 13; ++i) {
|
||||
if (!(input >> field) || !std::isfinite(field))
|
||||
return 1.0f;
|
||||
}
|
||||
float zoom;
|
||||
return input >> zoom && std::isfinite(zoom) && zoom >= 1.0f && zoom <= 10.0f ? zoom : 1.0f;
|
||||
}
|
||||
|
||||
/* Crop texture coordinates, not the viewport: output size stays unchanged.
|
||||
* Centered zoom commutes with each supported quarter-turn rotation. */
|
||||
inline float zoomCoordinate(float coordinate, float zoom)
|
||||
{
|
||||
return 0.5f + (coordinate - 0.5f) / zoom;
|
||||
}
|
||||
|
||||
struct ZoomCrop {
|
||||
unsigned x, y, width, height;
|
||||
};
|
||||
|
||||
/* CPU fallback crops debayered ARGB before its existing resize/rotation pass. */
|
||||
inline ZoomCrop centerCrop(unsigned width, unsigned height, float zoom)
|
||||
{
|
||||
if (zoom <= 1.0f)
|
||||
return {0, 0, width, height};
|
||||
unsigned w = std::max(4U, static_cast<unsigned>(width / zoom) & ~3U);
|
||||
unsigned h = std::max(4U, static_cast<unsigned>(height / zoom) & ~3U);
|
||||
return {(width - w) / 2, (height - h) / 2, w, h};
|
||||
}
|
||||
|
||||
} /* namespace platina */
|
||||
@@ -0,0 +1,93 @@
|
||||
<!doctype html>
|
||||
<html lang="cs"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Platina kamera</title>
|
||||
<style>
|
||||
:root{color-scheme:dark;font:14px system-ui}*{box-sizing:border-box}body{margin:0;height:100dvh;display:grid;grid-template-rows:auto minmax(0,1fr);background:#14171c;color:#eceff3}header{padding:10px 16px;display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:16px}h1{font-size:18px;margin:0}#state{font-size:12px;color:#aab8c8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}main{min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 304px;gap:12px;padding:0 12px 12px}.picture{position:relative;min-height:0;min-width:0;display:grid;place-items:center;background:#090c10;border-radius:12px;overflow:hidden}#video{position:absolute;width:100%;height:100%;object-fit:contain}#video[hidden]{display:none}#placeholder{padding:16px;text-align:center;color:#aab8c8}aside{align-self:start;min-width:0;background:#20252e;border:1px solid #303846;border-radius:12px;padding:14px;display:grid;gap:12px}h2{font-size:15px;margin:0}.basic{display:grid;gap:10px}.control{min-width:0}label{display:flex;justify-content:space-between;align-items:center;gap:8px;font-size:12px;line-height:18px;margin:0 0 3px}label output{color:#9ad1ff;white-space:nowrap;font-variant-numeric:tabular-nums}input[type=range]{display:block;width:100%;height:20px;margin:0;accent-color:#64b5fa;cursor:pointer}input:disabled{opacity:.4;cursor:default}select,button{font:inherit;padding:7px 10px;border:1px solid #4a5360;border-radius:7px;background:#303845;color:inherit;min-height:32px}select{width:100%;min-width:0;font-size:12px}button{cursor:pointer;white-space:nowrap}button:hover{border-color:#91b8de}button.primary{background:#16629c}button:disabled{opacity:.5;cursor:wait}.audio-row{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;gap:12px;padding-top:10px;border-top:1px solid #38414f}.actions{display:flex;gap:6px;flex-wrap:wrap}.actions button{flex:1;padding:7px 5px;font-size:12px}#message{font-size:12px;color:#a8d7ff;min-height:16px;margin:0}#audio-state{font-size:12px;color:#ffb6a6;margin:0}#audio-state:empty{display:none}dialog{width:min(560px,calc(100vw - 24px));max-height:calc(100dvh - 24px);padding:16px;border:1px solid #4a5360;border-radius:14px;background:#20252e;color:inherit;box-shadow:0 18px 70px #0009}dialog::backdrop{background:#0009;backdrop-filter:blur(3px)}.dialog-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px}#advanced-close{font-size:20px;line-height:20px;min-width:32px;padding:3px}.tabs{display:flex;gap:6px;margin-bottom:16px}.tabs button{flex:1;font-size:12px;padding:7px 5px}.tabs button[aria-selected=true]{background:#16629c;border-color:#64b5fa}.panel{display:grid;gap:12px}.panel[hidden]{display:none}.check{justify-content:flex-start;font-size:13px;margin:0}.readout{margin:0;color:#aab8c8;font-size:12px;line-height:18px}#colors{display:grid;gap:12px}
|
||||
@media(max-width:760px){header{padding:8px 12px;grid-template-columns:1fr auto;gap:5px 8px}#state{grid-column:1/-1;grid-row:2}main{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr) auto;gap:8px;padding:0 8px 8px}aside{padding:10px;gap:8px}.basic{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 12px}aside>h2{display:none}.audio-row{padding-top:8px}.actions button{min-height:30px}#message{font-size:11px;min-height:14px}}
|
||||
@media(max-height:580px){header{padding-top:5px;padding-bottom:5px}aside{padding:10px;gap:8px}.basic{grid-template-columns:repeat(2,minmax(0,1fr));gap:6px 10px}aside>h2{display:none}.audio-row{padding-top:6px}dialog{padding:12px}.dialog-head{margin-bottom:8px}.tabs{margin-bottom:10px}.panel,#colors{gap:8px}}
|
||||
</style>
|
||||
<header><h1>Platina kamera</h1><span id="state">Načítám stav…</span><button class="primary" id="camera-toggle" disabled>Zapnout kameru</button></header>
|
||||
<main><div class="picture"><div id="placeholder">Kamera je vypnutá.</div><img id="video" hidden alt="Živý obraz kamery"></div><aside>
|
||||
<h2>Nastavení obrazu</h2>
|
||||
<div class="basic" id="basic-controls"><div class="control" id="resolution-control"><label for="scale">Rozlišení</label><select id="scale"><option value="1">12 Mpx</option><option value="1.5">5,4 Mpx</option><option value="2">3 Mpx</option><option value="3">1,3 Mpx</option><option value="4">0,75 Mpx</option><option value="6">0,33 Mpx</option></select></div></div>
|
||||
<div class="audio-row"><button id="audio-toggle">Zapnout zvuk</button><div class="control"><label for="audio-volume">Hlasitost <output id="audio-volume-value">100 %</output></label><input id="audio-volume" type="range" min="0" max="200" value="100" step="5"></div></div>
|
||||
<p id="audio-state" role="status"></p>
|
||||
<div class="actions"><button id="advanced-toggle">Pokročilé</button><button class="primary" id="save">Uložit</button><button id="restore">Vrátit uložené</button></div>
|
||||
<p id="message" role="status"></p></aside></main>
|
||||
<dialog id="advanced" aria-labelledby="advanced-title"><div class="dialog-head"><h2 id="advanced-title">Pokročilé nastavení</h2><button id="advanced-close" aria-label="Zavřít">×</button></div>
|
||||
<div class="tabs" role="tablist" aria-label="Pokročilé nastavení"><button id="tab-exposure" role="tab" aria-selected="true" aria-controls="panel-exposure" data-panel="exposure">Expozice</button><button id="tab-white" role="tab" aria-selected="false" aria-controls="panel-white" data-panel="white" tabindex="-1">Vyvážení bílé</button><button id="tab-colors" role="tab" aria-selected="false" aria-controls="panel-colors" data-panel="colors" tabindex="-1">Barvy a orientace</button></div>
|
||||
<div class="panel" id="panel-exposure" role="tabpanel" aria-labelledby="tab-exposure"><label class="check"><input type="checkbox" id="exposure_auto"> Automatická expozice</label><div class="panel" id="exposure"></div><p id="exposure-actual" class="readout" role="status"></p></div>
|
||||
<div class="panel" id="panel-white" role="tabpanel" aria-labelledby="tab-white" hidden><label class="check"><input type="checkbox" id="automatic"> Automatické vyvážení bílé</label><div class="panel" id="white"></div></div>
|
||||
<div class="panel" id="panel-colors" role="tabpanel" aria-labelledby="tab-colors" hidden><div id="colors"></div><div class="control"><label for="rotation">Orientace</label><select id="rotation"><option value="90">Na výšku</option><option value="270">Na výšku obráceně</option><option value="0">Na šířku</option><option value="180">Na šířku obráceně</option></select></div></div>
|
||||
</dialog>
|
||||
<script>
|
||||
const defs=[['zoom','Přiblížení (×)',1,10,.1],['exposure_us','Ruční expoziční čas (µs)',100,100000,100],['analogue_gain','Ruční analogové zesílení (×)',1,8,.1],['focus','Ostření',0,1023,1],['gamma','Gama / jas',.5,4,.05],['contrast','Kontrast',.5,1.8,.02],['saturation','Sytost barev',0,2,.02],['quality','Kvalita JPEG',10,95,1],['red','Červená / vyvážení bílé',.25,4,.02],['blue','Modrá / vyvážení bílé',.25,4,.02]];
|
||||
const $=id=>document.getElementById(id),v=$('video'),status=$('state'),message=$('message');let settings=null,timer=null,online=false,applying=false,dirty=false,enabled=false,generation=null,streamGeneration=null;
|
||||
for(const [key,name,min,max,step] of defs){
|
||||
const group=document.createElement('div');group.className='control';
|
||||
const label=document.createElement('label');label.htmlFor=key;label.innerHTML=name+'<output id="'+key+'value"></output>';
|
||||
const input=document.createElement('input');Object.assign(input,{type:'range',id:key,min,max,step});group.append(label,input);
|
||||
if(['zoom','focus','quality'].includes(key))$('basic-controls').insertBefore(group,$('resolution-control'));
|
||||
else (['exposure_us','analogue_gain'].includes(key)?$('exposure'):['red','blue'].includes(key)?$('white'):$('colors')).append(group);
|
||||
input.addEventListener('input',()=>{if(!settings)return;if(key==='red'||key==='blue')$('automatic').checked=false;$(key+'value').textContent=input.value;dirty=true;clearTimeout(timer);timer=setTimeout(apply,150)});
|
||||
}
|
||||
const advanced=$('advanced'),tabs=[...document.querySelectorAll('[data-panel]')];
|
||||
function selectTab(tab){for(const button of tabs){const selected=button===tab;button.setAttribute('aria-selected',selected);button.tabIndex=selected?0:-1;$('panel-'+button.dataset.panel).hidden=!selected}}
|
||||
for(const [index,tab] of tabs.entries()){
|
||||
tab.onclick=()=>selectTab(tab);
|
||||
tab.onkeydown=e=>{let next;if(e.key==='ArrowRight')next=(index+1)%tabs.length;else if(e.key==='ArrowLeft')next=(index+tabs.length-1)%tabs.length;else if(e.key==='Home')next=0;else if(e.key==='End')next=tabs.length-1;else return;e.preventDefault();selectTab(tabs[next]);tabs[next].focus()};
|
||||
}
|
||||
$('advanced-toggle').onclick=()=>advanced.showModal();$('advanced-close').onclick=()=>advanced.close();
|
||||
|
||||
function fill(s){settings=s;for(const [key] of defs){$(key).value=s[key];$(key+'value').textContent=s[key]}$('automatic').checked=s.automatic;$('exposure_auto').checked=s.exposure_auto;exposureMode();$('rotation').value=s.rotation;$('scale').value=s.scale}
|
||||
function exposureMode(){for(const key of ['exposure_us','analogue_gain'])$(key).disabled=$('exposure_auto').checked}
|
||||
function values(){let s={...settings};for(const [key,,, ,step] of defs)s[key]=step>=1?parseInt($(key).value):parseFloat($(key).value);s.automatic=$('automatic').checked;s.exposure_auto=$('exposure_auto').checked;s.rotation=parseInt($('rotation').value);s.scale=parseFloat($('scale').value);s.fps=30;return s}
|
||||
async function post(path,data){const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});let result=await r.json();if(!r.ok)throw Error(result.error||'Nastavení se nepodařilo');return result}
|
||||
async function apply(){if(!settings)return false;while(applying)await new Promise(r=>setTimeout(r,40));applying=true;const sent=values();try{settings=await post('/settings',sent);message.textContent='Neuloženo';dirty=JSON.stringify(values())!==JSON.stringify(sent);if(dirty){clearTimeout(timer);timer=setTimeout(apply,150)}return true}catch(e){message.textContent=e.message;return false}finally{applying=false}}
|
||||
for(const key of ['automatic','exposure_auto','rotation','scale'])$(key).addEventListener('change',()=>{exposureMode();dirty=true;apply()});
|
||||
$('save').onclick=async()=>{$('save').disabled=true;clearTimeout(timer);try{if(!await apply())return;settings=await post('/save',{});message.textContent='Uloženo'}catch(e){message.textContent=e.message}finally{$('save').disabled=false}};
|
||||
$('restore').onclick=async()=>{clearTimeout(timer);try{fill(await post('/restore',{}));dirty=false;message.textContent='Obnoveno'}catch(e){message.textContent=e.message}};
|
||||
function connect(){if(enabled){v.hidden=false;$('placeholder').hidden=true;v.src='/stream.mjpg?t='+Date.now();streamGeneration=generation}}
|
||||
v.onerror=()=>{online=false;streamGeneration=null};
|
||||
$('camera-toggle').onclick=async()=>{const b=$('camera-toggle');b.disabled=true;try{await post('/camera',{enabled:!enabled});await health()}catch(e){message.textContent=e.message}finally{b.disabled=false}};
|
||||
async function health(){try{const r=await fetch('/status',{cache:'no-store'});if(!r.ok)throw Error();const m=await r.json();enabled=m.enabled;generation=m.generation;$('exposure-actual').textContent=m.state==='on'&&Number.isFinite(m.exposure_us_actual)&&Number.isFinite(m.analogue_gain_actual)?`Skutečná expozice: ${(m.exposure_us_actual/1000).toFixed(2)} ms · zesílení ${m.analogue_gain_actual.toFixed(2)}×`:'Skutečná expozice: '+(enabled?'čekám na snímek.':'kamera je vypnutá.');$('camera-toggle').disabled=false;$('camera-toggle').textContent=enabled?'Vypnout kameru':'Zapnout kameru';if(!applying&&!dirty&&!defs.some(([k])=>document.activeElement===$(k)))fill(m.settings);if(m.state==='on'){status.textContent=`Živě · ${m.fps.toFixed(1)} fps · ${m.width} × ${m.height} · zpracování ${Math.round(m.sensor_age_ms)} ms`;if(!online||streamGeneration!==generation)connect();online=true;if(settings.automatic&&!applying&&!dirty){for(const [key,actual] of [['red',m.red_gain],['blue',m.blue_gain]]){if(Number.isFinite(actual)){$(key).value=actual;$(key+'value').textContent=actual.toFixed(2)}}}}else{online=false;v.hidden=true;v.removeAttribute('src');$('placeholder').hidden=false;status.textContent=m.state==='starting'?'Spouštím kameru…':m.state==='error'?'Chyba kamery':'Kamera vypnutá';$('placeholder').textContent=m.error||(enabled?'Připravuji živý obraz…':'Kamera je vypnutá.')}}catch(e){status.textContent='Ovládání není dostupné. Zkouším znovu…';online=false;$('camera-toggle').disabled=true}}
|
||||
health();setInterval(health,1500);
|
||||
let audioController=null,audioContext=null,audioGain=null,audioNodes=new Set();
|
||||
function stopAudio(text=''){
|
||||
const controller=audioController;audioController=null;if(controller)controller.abort();
|
||||
for(const source of audioNodes){try{source.stop()}catch(e){}}audioNodes.clear();
|
||||
const context=audioContext;audioContext=null;audioGain=null;if(context)context.close().catch(()=>{});
|
||||
$('audio-toggle').textContent='Zapnout zvuk';$('audio-state').textContent=text;
|
||||
}
|
||||
$('audio-volume').oninput=()=>{const value=Number($('audio-volume').value);$('audio-volume-value').textContent=value+' %';if(audioGain)audioGain.gain.value=value/100};
|
||||
$('audio-toggle').onclick=async()=>{
|
||||
if(audioController){stopAudio();return}
|
||||
const controller=new AbortController();audioController=controller;
|
||||
$('audio-toggle').textContent='Vypnout zvuk';$('audio-state').textContent='Spouštím…';
|
||||
try{
|
||||
const context=new AudioContext({sampleRate:48000});audioContext=context;await context.resume();
|
||||
if(audioController!==controller)return;
|
||||
const gain=context.createGain();audioGain=gain;gain.gain.value=Number($('audio-volume').value)/100;gain.connect(context.destination);
|
||||
const ticketResponse=await fetch('/audio',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}',signal:controller.signal});
|
||||
const ticket=await ticketResponse.json();if(!ticketResponse.ok)throw Error(ticket.error||'Zvuk není dostupný.');
|
||||
const response=await fetch('/audio.pcm?token='+encodeURIComponent(ticket.token),{signal:controller.signal,cache:'no-store'});
|
||||
if(!response.ok){const error=await response.json();throw Error(error.error||'Mikrofon není dostupný.')}
|
||||
const reader=response.body.getReader();let pending=new Uint8Array(0),next=0,heard=false;
|
||||
while(audioController===controller){
|
||||
const {value,done}=await reader.read();if(done)break;
|
||||
const merged=new Uint8Array(pending.length+value.length);merged.set(pending);merged.set(value,pending.length);pending=merged;
|
||||
while(pending.length>=1920){
|
||||
const bytes=pending.slice(0,1920);pending=pending.slice(1920);
|
||||
const buffer=context.createBuffer(1,960,ticket.rate),samples=buffer.getChannelData(0),view=new DataView(bytes.buffer);
|
||||
for(let i=0;i<960;i++)samples[i]=view.getInt16(i*2,true)/32768;
|
||||
const now=context.currentTime;if(next<now||next>now+.4){for(const source of audioNodes){try{source.stop()}catch(e){}}audioNodes.clear();next=now+.12}
|
||||
const source=context.createBufferSource();source.buffer=buffer;source.connect(gain);audioNodes.add(source);source.onended=()=>audioNodes.delete(source);source.start(next);next+=buffer.duration;
|
||||
if(!heard){heard=true;$('audio-state').textContent='';}
|
||||
}
|
||||
}
|
||||
if(audioController===controller)stopAudio('Poslech skončil.');
|
||||
}catch(e){if(audioController===controller)stopAudio(e.name==='AbortError'?'':e.message)}
|
||||
};
|
||||
addEventListener('pagehide',()=>stopAudio());
|
||||
document.addEventListener('visibilitychange',()=>{if(document.hidden)stopAudio()});
|
||||
</script></html>
|
||||
@@ -0,0 +1,502 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Always available controls; capture is explicitly enabled and defaults OFF."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import select
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import tempfile
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
DEFAULTS = dict(focus=310, gamma=1.0, contrast=1.0, saturation=1.14, automatic=True,
|
||||
red=2.09, blue=1.49, rotation=90, scale=2, quality=50, fps=30,
|
||||
exposure_auto=True, exposure_us=10000, analogue_gain=1.0, zoom=1.0)
|
||||
RANGES = dict(focus=(0, 1023), gamma=(.5, 4), contrast=(.5, 1.8),
|
||||
saturation=(0, 2), red=(.25, 4), blue=(.25, 4), quality=(10, 95), fps=(10, 30),
|
||||
exposure_us=(100, 100000), analogue_gain=(1, 8), zoom=(1, 10))
|
||||
EXPOSURE_DEFAULTS = {key: DEFAULTS[key] for key in ('exposure_auto', 'exposure_us', 'analogue_gain')}
|
||||
|
||||
|
||||
def load_settings(path):
|
||||
value = json.loads(path.read_text())
|
||||
# Migrate only complete historical schemas; reject corrupt/unknown fields.
|
||||
if isinstance(value, dict) and set(value) == set(DEFAULTS) - set(EXPOSURE_DEFAULTS) - {'zoom'}:
|
||||
value = dict(value, **EXPOSURE_DEFAULTS)
|
||||
if isinstance(value, dict) and set(value) == set(DEFAULTS) - {'zoom'}:
|
||||
value = dict(value, zoom=1.0)
|
||||
return validate(value)
|
||||
SCALES = {1: '12 MP', 1.5: '5,4 MP', 2: '3 MP', 3: '1,3 MP', 4: '0,75 MP', 6: '0,33 MP'}
|
||||
|
||||
|
||||
def validate(value):
|
||||
if not isinstance(value, dict) or set(value) != set(DEFAULTS):
|
||||
raise ValueError('Unexpected settings fields')
|
||||
for key, item in value.items():
|
||||
if key in ('automatic', 'exposure_auto'):
|
||||
if type(item) is not bool:
|
||||
raise ValueError('Invalid ' + key)
|
||||
elif key == 'rotation':
|
||||
if type(item) is not int or item not in (0, 90, 180, 270):
|
||||
raise ValueError('Invalid rotation')
|
||||
elif key == 'scale':
|
||||
if type(item) not in (int, float) or item not in SCALES:
|
||||
raise ValueError('Invalid scale')
|
||||
else:
|
||||
if type(item) not in (int, float) or not math.isfinite(item):
|
||||
raise ValueError('Invalid ' + key)
|
||||
low, high = RANGES[key]
|
||||
if not low <= item <= high or (key in ('focus', 'quality', 'fps', 'exposure_us') and type(item) is not int):
|
||||
raise ValueError('Out of range: ' + key)
|
||||
result = dict(value)
|
||||
result['fps'] = 30
|
||||
result['scale'] = 1.5 if value['scale'] == 1.5 else int(value['scale'])
|
||||
return result
|
||||
|
||||
|
||||
def atomic(path, data):
|
||||
temporary = path.with_name(path.name + '.new')
|
||||
temporary.write_bytes(data)
|
||||
temporary.chmod(0o600)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
class Camera:
|
||||
def __init__(self, args):
|
||||
self.args = args
|
||||
self.lock = threading.RLock()
|
||||
self.settings = load_settings(args.config) if args.config.exists() else dict(DEFAULTS)
|
||||
self.saved = dict(self.settings)
|
||||
self.capture = None
|
||||
self.focus_fd = None
|
||||
self.focus_device = None
|
||||
self.focus_applied = False
|
||||
self.error = None
|
||||
self.generation = 0
|
||||
self.started = 0
|
||||
self.args.frame.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.clear_frames()
|
||||
|
||||
def clear_frames(self):
|
||||
for suffix in ('', '.new', '.meta', '.meta.new', '.controls', '.controls.new'):
|
||||
Path(str(self.args.frame) + suffix).unlink(missing_ok=True)
|
||||
|
||||
def controls(self, value):
|
||||
fields = [value['gamma'], value['contrast'], value['saturation'],
|
||||
int(value['automatic']), value['red'], value['blue'],
|
||||
value['rotation'], value['scale'], value['quality'], value['fps'],
|
||||
int(value['exposure_auto']), value['exposure_us'], value['analogue_gain'], value['zoom']]
|
||||
atomic(Path(str(self.args.frame) + '.controls'), (' '.join(map(str, fields)) + '\n').encode())
|
||||
|
||||
def focus(self, position):
|
||||
subprocess.run(['v4l2-ctl', '-d', self.focus_device,
|
||||
'--set-ctrl=focus_absolute=' + str(position)], check=True, timeout=5)
|
||||
|
||||
def configure(self, payload, save=False):
|
||||
if not isinstance(payload, dict) or not set(payload) <= set(DEFAULTS):
|
||||
raise ValueError('Unexpected settings fields')
|
||||
with self.lock:
|
||||
value = validate(dict(self.settings, **payload))
|
||||
if self.capture is not None and self.capture.poll() is None:
|
||||
if self.focus_applied and value['focus'] != self.settings['focus']:
|
||||
self.focus(value['focus'])
|
||||
self.controls(value)
|
||||
if any(value[k] != self.settings[k] for k in ('scale', 'rotation')):
|
||||
self.started = time.monotonic()
|
||||
if save:
|
||||
self.args.config.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
atomic(self.args.config, (json.dumps(value, indent=2) + '\n').encode())
|
||||
self.saved = dict(value)
|
||||
self.settings = value
|
||||
return dict(value)
|
||||
|
||||
def set_enabled(self, enabled):
|
||||
if type(enabled) is not bool:
|
||||
raise ValueError('Expected enabled: true or false')
|
||||
with self.lock:
|
||||
if not enabled:
|
||||
self.stop()
|
||||
elif self.capture is None or self.capture.poll() is not None:
|
||||
self.stop()
|
||||
self.error = None
|
||||
try:
|
||||
matches = [p for p in Path('/sys/class/video4linux').glob('v4l-subdev*')
|
||||
if (p / 'name').read_text().strip() == 'dw9714 2-000c']
|
||||
if len(matches) != 1:
|
||||
raise OSError('Rear camera is not available in this kernel')
|
||||
self.focus_device = '/dev/' + matches[0].name
|
||||
self.focus_fd = os.open(self.focus_device, os.O_RDWR | os.O_CLOEXEC)
|
||||
self.controls(self.settings)
|
||||
env = dict(os.environ,
|
||||
LD_LIBRARY_PATH='/usr/lib/platina-camera/lib:/usr/lib/platina-camera/gpu/lib:/usr/lib/platina-camera/gpu/lib/dri',
|
||||
LIBCAMERA_SOFTISP_MODE='cpu' if self.args.cpu else 'gpu',
|
||||
PLATINA_JPEG_THREADS='2' if self.args.cpu else '4',
|
||||
LIBCAMERA_LOG_LEVELS='*:WARN')
|
||||
# Experimental DMA paths must never be enabled by a stale shell environment.
|
||||
for key in ('PLATINA_GPU_INPUT_DMABUF', 'PLATINA_GPU_FLAT_DMABUF', 'PLATINA_GPU_PROFILE'):
|
||||
env.pop(key, None)
|
||||
self.capture = subprocess.Popen([self.args.capture, str(self.args.frame)], env=env)
|
||||
self.started = time.monotonic()
|
||||
self.generation += 1
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
self.stop()
|
||||
self.error = 'Kameru nelze spustit. Zkontrolujte ovladač a záznam služby.'
|
||||
raise OSError(self.error) from None
|
||||
return self.status()
|
||||
|
||||
def stop(self):
|
||||
with self.lock:
|
||||
self.generation += 1
|
||||
if self.capture is not None:
|
||||
if self.capture.poll() is None:
|
||||
self.capture.terminate()
|
||||
try:
|
||||
self.capture.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.capture.kill()
|
||||
self.capture.wait(timeout=3)
|
||||
self.capture = None
|
||||
if self.focus_fd is not None:
|
||||
os.close(self.focus_fd)
|
||||
self.focus_fd = None
|
||||
self.focus_applied = False
|
||||
self.focus_device = None
|
||||
self.clear_frames()
|
||||
self.error = None
|
||||
|
||||
def tick(self):
|
||||
with self.lock:
|
||||
if self.capture is None:
|
||||
return
|
||||
code = self.capture.poll()
|
||||
if code is not None:
|
||||
self.stop()
|
||||
self.error = 'Snímání se zastavilo. Kameru lze znovu zapnout.'
|
||||
print('Capture exited with status ' + str(code), flush=True)
|
||||
elif not self.focus_applied and self.args.frame.exists():
|
||||
try:
|
||||
self.focus(self.settings['focus'])
|
||||
self.focus_applied = True
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
self.stop()
|
||||
self.error = 'Nastavení ostření selhalo. Kameru lze znovu zapnout.'
|
||||
elif time.monotonic() - self.started > 20:
|
||||
try:
|
||||
self.latest()
|
||||
except (OSError, ValueError, KeyError):
|
||||
self.stop()
|
||||
self.error = 'Kamera nedodává aktuální obraz. Kameru lze znovu zapnout.'
|
||||
|
||||
def latest(self):
|
||||
with self.lock:
|
||||
if self.capture is None or self.capture.poll() is not None:
|
||||
raise OSError('Camera is off')
|
||||
with self.args.frame.open('rb') as stream:
|
||||
stat = os.fstat(stream.fileno())
|
||||
age = time.time() - stat.st_mtime
|
||||
if age > 2:
|
||||
raise OSError('Camera frame expired')
|
||||
data = stream.read(8 * 1024 * 1024 + 1)
|
||||
meta = json.loads(Path(str(self.args.frame) + '.meta').read_text())
|
||||
marker = re.search(rb'platina_capture_ns=([0-9]+)', data[:1024])
|
||||
if not marker:
|
||||
raise OSError('Missing frame timestamp')
|
||||
meta['captured_ns'] = int(marker.group(1))
|
||||
meta['sensor_age_ms'] = (time.monotonic_ns() - meta['captured_ns']) / 1_000_000
|
||||
if meta['sensor_age_ms'] > 2000:
|
||||
raise OSError('Sensor frame expired')
|
||||
if len(data) > 8 * 1024 * 1024 or not data.startswith(b'\xff\xd8') or not data.endswith(b'\xff\xd9'):
|
||||
raise OSError('Incomplete frame')
|
||||
return data, age, stat.st_mtime_ns, meta
|
||||
|
||||
def status(self):
|
||||
with self.lock:
|
||||
enabled = self.capture is not None and self.capture.poll() is None
|
||||
result = dict(ok=True, enabled=enabled, state='starting' if enabled else 'error' if self.error else 'off',
|
||||
error=self.error, settings=dict(self.settings), generation=self.generation)
|
||||
if enabled:
|
||||
try:
|
||||
_, age, _, meta = self.latest()
|
||||
result.update(state='on', age_seconds=round(age, 3), **meta)
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
class Audio:
|
||||
"""One on-demand PCM listener; restore the mixer on every exit path."""
|
||||
rate = 48000
|
||||
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.tokens = {}
|
||||
self.capture = None
|
||||
self.closed = False
|
||||
self.released = threading.Event()
|
||||
self.released.set()
|
||||
|
||||
def ticket(self):
|
||||
with self.lock:
|
||||
if self.closed:
|
||||
raise ValueError('Audio is stopping')
|
||||
if self.capture is not None:
|
||||
raise ValueError('Mikrofon právě používá jiný posluchač.')
|
||||
# Keep only the latest short-lived, single-use authorization.
|
||||
token = secrets.token_urlsafe(24)
|
||||
self.tokens = {token: time.monotonic() + 10}
|
||||
return dict(token=token, rate=self.rate, channels=1, format='s16le')
|
||||
|
||||
def open(self, token):
|
||||
with self.lock:
|
||||
expires = self.tokens.pop(token, 0)
|
||||
if self.closed or expires < time.monotonic() or self.capture is not None:
|
||||
raise ValueError('Poslech vypršel nebo je mikrofon obsazený.')
|
||||
if 'Xiaomi Mi 8 Lite' not in Path('/proc/asound/cards').read_text():
|
||||
raise ValueError('Mikrofon telefonu není dostupný.')
|
||||
directory = tempfile.TemporaryDirectory(prefix='platina-audio-')
|
||||
state = str(Path(directory.name) / 'mixer.state')
|
||||
saved = False
|
||||
try:
|
||||
self.command(['alsactl', '-f', state, 'store', '0'])
|
||||
saved = True
|
||||
for name, value in (
|
||||
('MultiMedia1 Mixer LPI_MI2S_TX_3', '1'),
|
||||
('Digital CIC1 MUX', 'AMIC'),
|
||||
('Digital DEC1 MUX', 'ADC2'), ('ADC2 MUX', 'INP3'),
|
||||
('ADC3 Volume', '6'), ('Digital TX1 Digital Volume', '114')):
|
||||
self.command(['amixer', '-q', '-c', '0', 'cset', 'name=' + name, value])
|
||||
process = subprocess.Popen(
|
||||
['arecord', '-q', '-D', 'hw:0,0', '-t', 'raw', '-f', 'S16_LE',
|
||||
'-r', str(self.rate), '-c', '1', '--period-size=960', '--buffer-size=3840'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
||||
self.capture = process
|
||||
self.released.clear()
|
||||
return process, directory, state
|
||||
except Exception:
|
||||
if saved:
|
||||
self.command(['alsactl', '-f', state, 'restore', '0'], check=False)
|
||||
directory.cleanup()
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def command(args, check=True):
|
||||
return subprocess.run(args, check=check, timeout=5, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL)
|
||||
|
||||
def release(self, session):
|
||||
process, directory, state = session
|
||||
with self.lock:
|
||||
try:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=3)
|
||||
process.stdout.close()
|
||||
finally:
|
||||
try:
|
||||
self.command(['alsactl', '-f', state, 'restore', '0'], check=False)
|
||||
finally:
|
||||
directory.cleanup()
|
||||
self.capture = None
|
||||
self.released.set()
|
||||
|
||||
def close(self):
|
||||
with self.lock:
|
||||
self.closed = True
|
||||
self.tokens.clear()
|
||||
if self.capture is not None and self.capture.poll() is None:
|
||||
self.capture.terminate()
|
||||
self.released.wait(timeout=8)
|
||||
|
||||
|
||||
def make_handler(camera, shutdown, audio=None):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(2)
|
||||
self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 262144)
|
||||
self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def reply(self, status, content_type, payload):
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', content_type)
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def json(self, status, value):
|
||||
self.reply(status, 'application/json', json.dumps(value).encode())
|
||||
|
||||
def do_GET(self):
|
||||
path = urlsplit(self.path).path
|
||||
try:
|
||||
if path == '/':
|
||||
self.reply(200, 'text/html; charset=utf-8', Path(__file__).with_name('preview.html').read_bytes())
|
||||
elif path == '/settings':
|
||||
with camera.lock:
|
||||
self.json(200, dict(camera.settings))
|
||||
elif path in ('/status', '/health'):
|
||||
self.json(200, camera.status())
|
||||
elif path == '/audio.pcm' and audio is not None:
|
||||
from urllib.parse import parse_qs
|
||||
origin = self.headers.get('Origin')
|
||||
if origin not in (None, 'http://' + self.headers.get('Host', '')):
|
||||
self.json(403, dict(error='Origin rejected'))
|
||||
return
|
||||
try:
|
||||
session = audio.open(parse_qs(urlsplit(self.path).query).get('token', [''])[0])
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
||||
self.json(409, dict(error=str(error)))
|
||||
return
|
||||
try:
|
||||
process = session[0]
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'application/octet-stream')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('Connection', 'close')
|
||||
self.end_headers()
|
||||
self.close_connection = True
|
||||
while not shutdown.is_set():
|
||||
if not select.select([process.stdout], [], [], 3)[0]:
|
||||
break
|
||||
data = os.read(process.stdout.fileno(), 3840)
|
||||
if not data:
|
||||
break
|
||||
self.wfile.write(data)
|
||||
self.wfile.flush()
|
||||
finally:
|
||||
audio.release(session)
|
||||
elif path in ('/snapshot.jpg', '/stream.mjpg'):
|
||||
try:
|
||||
data, _, stamp, meta = camera.latest()
|
||||
except (OSError, ValueError, KeyError):
|
||||
self.json(503, dict(ok=False, error='Camera is off or starting'))
|
||||
return
|
||||
if path == '/snapshot.jpg':
|
||||
self.reply(200, 'image/jpeg', data)
|
||||
return
|
||||
generation = camera.generation
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=frame')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.end_headers()
|
||||
while not shutdown.is_set() and camera.generation == generation:
|
||||
self.wfile.write(b'--frame\r\nContent-Type: image/jpeg\r\nContent-Length: ' + str(len(data)).encode() + b'\r\nX-Frame-Age-Ms: ' + str(round(meta['sensor_age_ms'], 2)).encode() + b'\r\n\r\n' + data + b'\r\n')
|
||||
self.wfile.flush()
|
||||
while not shutdown.wait(.005) and camera.generation == generation:
|
||||
if camera.args.frame.stat().st_mtime_ns == stamp:
|
||||
continue
|
||||
data, _, stamp, meta = camera.latest()
|
||||
break
|
||||
else:
|
||||
self.json(404, dict(error='Not found'))
|
||||
except (OSError, ValueError, KeyError):
|
||||
self.close_connection = True
|
||||
|
||||
def do_POST(self):
|
||||
path = urlsplit(self.path).path
|
||||
if path not in ('/settings', '/save', '/restore', '/camera', '/audio'):
|
||||
self.json(404, dict(error='Not found'))
|
||||
return
|
||||
if self.headers.get('Origin') not in (None, 'http://' + self.headers.get('Host', '')):
|
||||
self.json(403, dict(error='Origin rejected'))
|
||||
return
|
||||
try:
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
if not 0 < length <= 2048 or self.headers.get_content_type() != 'application/json':
|
||||
raise ValueError('Expected small JSON body')
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError('Expected JSON object')
|
||||
if path == '/audio':
|
||||
if payload or audio is None:
|
||||
raise ValueError('Expected empty object and available audio')
|
||||
self.json(200, audio.ticket())
|
||||
return
|
||||
with camera.lock:
|
||||
if path == '/camera':
|
||||
if set(payload) != {'enabled'}:
|
||||
raise ValueError('Expected enabled field')
|
||||
value = camera.set_enabled(payload['enabled'])
|
||||
elif path == '/save':
|
||||
if payload:
|
||||
raise ValueError('Expected empty object')
|
||||
value = camera.configure({}, save=True)
|
||||
elif path == '/restore':
|
||||
if payload:
|
||||
raise ValueError('Expected empty object')
|
||||
value = camera.configure(dict(camera.saved))
|
||||
else:
|
||||
value = camera.configure(payload)
|
||||
self.json(200, value)
|
||||
except (ValueError, KeyError, OSError, subprocess.SubprocessError) as error:
|
||||
self.json(400, dict(error=str(error)))
|
||||
return Handler
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--cpu', action='store_true')
|
||||
parser.add_argument('--listen', default='127.0.0.1')
|
||||
parser.add_argument('--port', type=int, default=8082)
|
||||
parser.add_argument('--frame', type=Path, default=Path('/run/platina-camera/latest.jpg'))
|
||||
parser.add_argument('--capture', default='/usr/lib/platina-camera/bin/platina-camera-capture')
|
||||
parser.add_argument('--config', type=Path, default=Path('/etc/platina-camera/preview.json'))
|
||||
parser.add_argument('--mqtt-config', type=Path, default=Path('/etc/platina-camera/mqtt.json'))
|
||||
parser.add_argument('--seconds', type=float)
|
||||
args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
shutdown = threading.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, lambda *_: shutdown.set())
|
||||
camera = Camera(args)
|
||||
audio = Audio()
|
||||
bridge = None
|
||||
server = ThreadingHTTPServer((args.listen, args.port), make_handler(camera, shutdown, audio))
|
||||
server.daemon_threads = True
|
||||
server.timeout = .1
|
||||
try:
|
||||
if args.mqtt_config.exists():
|
||||
from camera_mqtt import Bridge
|
||||
try:
|
||||
bridge = Bridge(camera, args.mqtt_config)
|
||||
bridge.start()
|
||||
except (OSError, ValueError, ImportError, KeyError, AttributeError):
|
||||
bridge = None
|
||||
print('MQTT configuration unavailable; web controls remain available', flush=True)
|
||||
print(f'Platina controls listening on {args.listen}:{args.port}; camera OFF', flush=True)
|
||||
deadline = time.monotonic() + args.seconds if args.seconds else None
|
||||
while not shutdown.is_set():
|
||||
if deadline and time.monotonic() >= deadline:
|
||||
break
|
||||
camera.tick()
|
||||
if bridge:
|
||||
bridge.tick()
|
||||
server.handle_request()
|
||||
finally:
|
||||
shutdown.set()
|
||||
audio.close()
|
||||
camera.stop()
|
||||
if bridge:
|
||||
bridge.close()
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,35 @@
|
||||
# Isolated headless Adreno userspace; no desktop, Vulkan or LLVM runtime.
|
||||
pkgname=platina-mesa-freedreno
|
||||
pkgver=26.1.6
|
||||
pkgrel=0
|
||||
pkgdesc="Minimal Freedreno EGL/GLES for the Platina camera"
|
||||
url="https://mesa3d.org/"
|
||||
arch="aarch64"
|
||||
license="MIT AND SGI-B-2.0 AND BSL-1.0"
|
||||
sonameprefix="platina-gpu-"
|
||||
ldpath="/usr/lib/platina-camera/gpu/lib:/usr/lib/platina-camera/gpu/lib/dri"
|
||||
makedepends="bison eudev-dev expat-dev flex libdrm-dev elfutils-dev meson py3-mako py3-packaging py3-ply py3-yaml zlib-dev"
|
||||
source="https://archive.mesa3d.org/mesa-$pkgver.tar.xz"
|
||||
builddir="$srcdir/mesa-$pkgver"
|
||||
options="!check"
|
||||
|
||||
build() {
|
||||
abuild-meson --prefix=/usr/lib/platina-camera/gpu \
|
||||
--libdir=/usr/lib/platina-camera/gpu/lib \
|
||||
--includedir=/usr/lib/platina-camera/gpu/include \
|
||||
--datadir=/usr/lib/platina-camera/gpu/share \
|
||||
-Dgallium-drivers=freedreno -Dfreedreno-kmds=msm \
|
||||
-Dvulkan-drivers=[] -Dplatforms=[] -Dopengl=false \
|
||||
-Dglx=disabled -Dglvnd=disabled -Degl=enabled -Dgbm=enabled \
|
||||
-Dgles1=disabled -Dgles2=enabled -Dllvm=disabled -Ddraw-use-llvm=false \
|
||||
-Dgallium-rusticl=false -Dgallium-va=disabled -Dvideo-codecs=[] \
|
||||
-Dxmlconfig=disabled -Dzstd=disabled -Dbuild-tests=false \
|
||||
-Dwerror=false . output
|
||||
meson compile -C output -j 2
|
||||
}
|
||||
package() {
|
||||
DESTDIR="$pkgdir" meson install --no-rebuild -C output
|
||||
}
|
||||
sha512sums="
|
||||
6746b73f5b87e8ff3723eee586b4b5f033dbe6d13cd0309d743b7fa484c350268859ec8ff21aadcbca7a04070cdaa7828146dd28dde4b1935bb879891d687f0b mesa-26.1.6.tar.xz
|
||||
"
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"purpose": "Rear IMX363 bringup references; not hardware validation",
|
||||
"kernel_driver": {
|
||||
"repository": "https://gitlab.com/sdm845-mainline/linux",
|
||||
"commit": "85f1df2a4ec71d7a91dd95a7a49f889d1595ffa8",
|
||||
"file": "drivers/media/i2c/imx363.c",
|
||||
"sha256": "13d15b54c0a45598d0d165b338c42ee9bbd627cb6a072bdad272e32a20c0583b",
|
||||
"license": "GPL-2.0"
|
||||
},
|
||||
"wiring": {
|
||||
"repository": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource",
|
||||
"commit": "0bb2780bccb9c7e05f0edf5db8860e779179b5f9",
|
||||
"file": "arch/arm/boot/dts/qcom/platina-camera-sensor.dtsi",
|
||||
"sha256": "40dffc957213ad4ddd7d15ac5fce65e35d3bd9215753153b68af75a586d14f2f",
|
||||
"license": "GPL-2.0-only"
|
||||
},
|
||||
"android_reference_only": {
|
||||
"repository": "https://github.com/TheMuppets/proprietary_vendor_xiaomi_platina",
|
||||
"commit": "d3c57407b34d03ff3597f67129c2bb0bdcac3005",
|
||||
"redistributed": false,
|
||||
"files": [
|
||||
{
|
||||
"file": "camera_config.xml",
|
||||
"sha256": "0a7c472da195da1e4f248680b9082a9b79e74b8f3d9f1a5eeaae1442d13dc9af"
|
||||
},
|
||||
{
|
||||
"file": "libmmcamera_platina_imx363_sunny.so",
|
||||
"sha256": "3420e804c4ac0417bf55416fb66ed0574a8e52328e71ca9162e6e2bb7554d86e"
|
||||
},
|
||||
{
|
||||
"file": "libmmcamera_platina_imx363_ofilm.so",
|
||||
"sha256": "2c90b84c787b635721f991344e2391fb416c89b05cde1604f13cfef2c8797080"
|
||||
},
|
||||
{
|
||||
"file": "libactuator_platina_dw9714_sunny.so",
|
||||
"sha256": "a59824f23b2662f42cf5b95af2c29132d564b1e5fbdc3f57987c294fd2be1c3e"
|
||||
},
|
||||
{
|
||||
"file": "libactuator_platina_dw9714_ofilm.so",
|
||||
"sha256": "d7de89e6ceeb84a020d21048e6031d7e60fdd6a8d95e6172c7add71cc34ac38e"
|
||||
}
|
||||
],
|
||||
"sensor_descriptor_evidence": {
|
||||
"elf_file_offset": 20488,
|
||||
"address_8bit": 32,
|
||||
"id_register": 22,
|
||||
"chip_id": 867
|
||||
},
|
||||
"csi": {
|
||||
"slot": 0,
|
||||
"csid": 0,
|
||||
"lane_mask": "0x1f",
|
||||
"lane_assignment": "0x4320",
|
||||
"mount_angle": 90
|
||||
}
|
||||
},
|
||||
"camss_supplies": {
|
||||
"repository": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource",
|
||||
"commit": "0bb2780bccb9c7e05f0edf5db8860e779179b5f9",
|
||||
"file": "arch/arm/boot/dts/qcom/sdm660-camera.dtsi",
|
||||
"sha256": "d72db3f96fbadf89eea91fe2cd85039ebe86239e01108a804418b930f74c643a",
|
||||
"vdda": "PM660 L1",
|
||||
"vdd_sec": "PM660L L1"
|
||||
},
|
||||
"lane_mapping": {
|
||||
"stock_table": [
|
||||
0,
|
||||
4,
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"stock_lane_assign": "0x4320",
|
||||
"hardware_lane_assign": "0x3210",
|
||||
"mainline_receiver_data_lanes": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"clock_lane_fixed_by_driver": true,
|
||||
"repository": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource",
|
||||
"commit": "0bb2780bccb9c7e05f0edf5db8860e779179b5f9",
|
||||
"files": [
|
||||
{
|
||||
"file": "drivers/media/platform/msm/camera_v2/sensor/csid/msm_csid.c",
|
||||
"sha256": "e78fa4c02696e4363170c54271b81c906fa2c917251882035686c991f97f80f2"
|
||||
},
|
||||
{
|
||||
"file": "drivers/media/platform/msm/camera_v2/sensor/csid/include/msm_csid_3_5_hwreg.h",
|
||||
"sha256": "436ef12d35c05fe6a00242b63371ad1ab50921791ece5b35cb5bdadfd85fa8a3"
|
||||
}
|
||||
]
|
||||
},
|
||||
"phy_clock_reference": {
|
||||
"url": "https://lkml.iu.edu/2010.2/01479.html",
|
||||
"author": "AngeloGioacchino Del Regno",
|
||||
"requirement": "SDM630/660 csiX_phy rate must be at least csiphyX_timer rate",
|
||||
"tested_reference_device": "Sony Xperia XA2 (SDM630)",
|
||||
"observed_platina_before_fix_hz": {
|
||||
"phy": 19200000,
|
||||
"timer": 100000000
|
||||
}
|
||||
},
|
||||
"lens": {
|
||||
"driver": "dongwoon,dw9714",
|
||||
"i2c_address_7bit": "0x0c",
|
||||
"stock_i2c_address_8bit": "0x18",
|
||||
"regulator": "cam-actuator-rear-vreg",
|
||||
"enable_gpio": 50,
|
||||
"stock_variants": [
|
||||
"platina_dw9714_sunny",
|
||||
"platina_dw9714_ofilm"
|
||||
],
|
||||
"hardware_control_verified": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user