From 655d0f5b4944295334b7125aec1e7b07d2419668 Mon Sep 17 00:00:00 2001
From: Sukecz <222629366+Sukecz@users.noreply.github.com>
Date: Tue, 27 Oct 2026 11:45:42 +0100
Subject: [PATCH] Release 0.8.1 camera, browser audio and compact controls
---
.github/workflows/check.yml | 2 +-
CHANGELOG.md | 52 +
LICENSES/LGPL-2.1 | 501 ++++++
NOTICE | 29 +-
README.md | 185 +-
docs/BUILDING.md | 26 +-
docs/CAMERA.md | 138 ++
docs/HARDWARE.md | 5 +
docs/INSTALLATION.md | 13 +-
docs/LICENSING.md | 8 +-
.../0031-media-i2c-imx363.patch | 1556 +++++++++++++++++
.../0032-platina-rear-camera.patch | 82 +
.../0033-camss-sdm660-ispif.patch | 35 +
.../0034-camss-sdm660-ispif-power-votes.patch | 75 +
.../0035-camss-sdm660-phy-clock-rates.patch | 43 +
.../0036-platina-rear-focus.patch | 26 +
.../0037-imx363-full-field-binning.patch | 116 ++
...0038-imx363-platina-legacy-frequency.patch | 36 +
.../0039-venus-legacy-h264-transform.patch | 30 +
.../linux-postmarketos-qcom-sdm660/APKBUILD | 23 +-
.../config-postmarketos-qcom-sdm660.aarch64 | 7 +-
.../0001-imx363-properties.patch | 56 +
.../0002-simple-manual-white-balance.patch | 80 +
.../0003-platina-full-field-gpu-scale.patch | 47 +
.../0004-overlap-gpu-statistics.patch | 56 +
.../0005-platina-gpu-profile-dmabuf.patch | 160 ++
...0006-platina-gpu-rotation-saturation.patch | 99 ++
.../0011-simple-manual-exposure.patch | 110 ++
.../0012-platina-gpu-zoom.patch | 37 +
project/camera/libcamera-headless/APKBUILD | 91 +
.../camera/libcamera-headless/camera_mqtt.py | 182 ++
project/camera/libcamera-headless/capture.cpp | 389 +++++
.../libcamera-headless/configuration.yaml | 7 +
project/camera/libcamera-headless/imx363.yaml | 14 +
.../libcamera-headless/platina-camera.openrc | 23 +
.../libcamera-headless/platina_exposure.h | 31 +
.../camera/libcamera-headless/platina_zoom.h | 44 +
.../camera/libcamera-headless/preview.html | 93 +
project/camera/libcamera-headless/serve.py | 502 ++++++
project/camera/mesa-freedreno/APKBUILD | 35 +
project/camera/reference.json | 118 ++
project/release.json | 4 +-
project/sources.lock.json | 2 +-
scripts/build-camera-userspace.py | 61 +
tests/camera_exposure.cpp | 28 +
tests/camera_zoom.cpp | 41 +
tests/test_camera_control.py | 317 ++++
tests/test_camera_exposure_native.py | 28 +
tests/test_camera_lane_mapping.py | 28 +
49 files changed, 5549 insertions(+), 122 deletions(-)
create mode 100644 LICENSES/LGPL-2.1
create mode 100644 docs/CAMERA.md
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0031-media-i2c-imx363.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0032-platina-rear-camera.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0033-camss-sdm660-ispif.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0034-camss-sdm660-ispif-power-votes.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0035-camss-sdm660-phy-clock-rates.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0036-platina-rear-focus.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0037-imx363-full-field-binning.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0038-imx363-platina-legacy-frequency.patch
create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0039-venus-legacy-h264-transform.patch
create mode 100644 project/camera/libcamera-headless/0001-imx363-properties.patch
create mode 100644 project/camera/libcamera-headless/0002-simple-manual-white-balance.patch
create mode 100644 project/camera/libcamera-headless/0003-platina-full-field-gpu-scale.patch
create mode 100644 project/camera/libcamera-headless/0004-overlap-gpu-statistics.patch
create mode 100644 project/camera/libcamera-headless/0005-platina-gpu-profile-dmabuf.patch
create mode 100644 project/camera/libcamera-headless/0006-platina-gpu-rotation-saturation.patch
create mode 100644 project/camera/libcamera-headless/0011-simple-manual-exposure.patch
create mode 100644 project/camera/libcamera-headless/0012-platina-gpu-zoom.patch
create mode 100644 project/camera/libcamera-headless/APKBUILD
create mode 100644 project/camera/libcamera-headless/camera_mqtt.py
create mode 100644 project/camera/libcamera-headless/capture.cpp
create mode 100644 project/camera/libcamera-headless/configuration.yaml
create mode 100644 project/camera/libcamera-headless/imx363.yaml
create mode 100644 project/camera/libcamera-headless/platina-camera.openrc
create mode 100644 project/camera/libcamera-headless/platina_exposure.h
create mode 100644 project/camera/libcamera-headless/platina_zoom.h
create mode 100644 project/camera/libcamera-headless/preview.html
create mode 100644 project/camera/libcamera-headless/serve.py
create mode 100644 project/camera/mesa-freedreno/APKBUILD
create mode 100644 project/camera/reference.json
create mode 100755 scripts/build-camera-userspace.py
create mode 100644 tests/camera_exposure.cpp
create mode 100644 tests/camera_zoom.cpp
create mode 100644 tests/test_camera_control.py
create mode 100644 tests/test_camera_exposure_native.py
create mode 100644 tests/test_camera_lane_mapping.py
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index 92d9ed7..b1043ca 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -19,6 +19,6 @@ jobs:
- name: Install host tools for screen integration tests
run: |
sudo apt-get update
- sudo apt-get install -y --no-install-recommends python3-pil fonts-dejavu-core
+ sudo apt-get install -y --no-install-recommends g++ python3-pil fonts-dejavu-core
- name: Validate sources and run offline tests
run: make check
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20ec60f..00b5dc1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,57 @@
# Changelog
+## 0.8.1 — 2026-10-27, compact camera release
+
+- Restore the millisecond processing label in the compact live header. Its value
+ is frame age at status-read time, not isolated JPEG time or browser latency.
+- Signed camera userspace 0.7.1-r31 and integration 0.8.1 were checked on the
+ existing phone; boot and settings were preserved. Publish source, not binaries.
+- Includes the camera/audio/control features below, plus build recipes, regression
+ tests, source attribution and updated installation/qualification documentation.
+
+## 0.8.0 — compact controls and 10× zoom
+
+- Digital zoom 1–10× in the shared web/HA JPEG pipeline.
+- Keep zoom, focus, JPEG, resolution and audio in the compact main panel. Put
+ exposure, white balance, colors and rotation in a tabbed Advanced dialog.
+- Remove the target-FPS slider and fix the capture target at 30; actual output
+ rates remain dependent on scene, resolution and processing capacity.
+- Remove verbose audio hints. Desktop/mobile page and dialog geometry were
+ checked without scrolling; live browser checked 10× MJPEG at 2008×2680.
+
+## 0.7.0 — shared digital zoom
+
+- Centered GPU input crop before debayering/scaling, with a CPU ARGB fallback.
+- Live web/API/MQTT control and settings migration; output dimensions unchanged.
+- Zoom applies to snapshots and the same MJPEG used by Home Assistant.
+
+## 0.6.0 — exposure controls
+
+- Expose auto/manual sensor time and analogue gain through Simple IPA, web/API
+ and MQTT. Report actual sensor metadata separately from requested settings.
+- Bound requests to configured sensor limits and preserve complete older configs.
+- Broader physical exposure-response and image-quality qualification is pending.
+
+## 0.5.0 — optional browser microphone
+
+- Explicit ON/OFF mono PCM16 48 kHz browser listening and local volume control.
+- Single-listener lifecycle, mixer restore and cleanup on disconnect/page exit.
+- Audio is separate from MJPEG; no synchronized A/V or audio in the HA camera.
+
+## 0.4.1 — JPEG range
+
+- Extend JPEG quality to 10–95. Lower quality reduced bytes in short tests;
+ it did not establish a meaningful overall FPS improvement.
+
+## 0.4.0 — camera and Home Assistant
+
+- IMX363 rear camera with DW9714 focus, full-field GPU MJPEG and six output sizes.
+- OFF-by-default OpenRC controls, explicit capture ON/OFF, live settings and
+ MQTT Discovery for Home Assistant. Image requests do not start capture.
+- Existing installation boot/restart and HA image/control paths were tested.
+- H.264/Venus development is not a working encoding feature and remains deferred.
+
+
## 0.3.1 — fresh-image integration
- New local images include versioned boot and shutdown screens, display helpers,
diff --git a/LICENSES/LGPL-2.1 b/LICENSES/LGPL-2.1
new file mode 100644
index 0000000..f6683e7
--- /dev/null
+++ b/LICENSES/LGPL-2.1
@@ -0,0 +1,501 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ , 1 April 1990
+ Moe Ghoul, President of Vice
+
+That's all there is to it!
diff --git a/NOTICE b/NOTICE
index 3279328..80aad43 100644
--- a/NOTICE
+++ b/NOTICE
@@ -39,6 +39,33 @@ Tianma panel reference
- GPL-2.0-only downstream panel data, with variant values recorded from matching
stock panel data. Exact reference hashes are in tianma-reference.json.
+Camera sensor reference
+- Intel Corporation and the IMX363 module authors, carried by sdm845-mainline.
+- https://gitlab.com/sdm845-mainline/linux/-/blob/85f1df2a4ec71d7a91dd95a7a49f889d1595ffa8/drivers/media/i2c/imx363.c
+- GPL-2.0 driver; original copyright and module author declarations retained.
+- Platina camera wiring is derived from the Xiaomi GPL-2.0-only device tree
+ referenced above. Proprietary Android camera libraries are not distributed.
+
+libcamera and camera userspace
+- libcamera contributors, including the authors named in retained source and
+ patch headers; IMX363 properties/gain support credits Samuel LEGROS.
+- https://libcamera.org/ and https://patchwork.libcamera.org/patch/28201/
+- The camera recipe fetches libcamera 0.7.1 under its upstream LGPL/GPL/component
+ licenses. Changes to LGPL libcamera sources and the explicitly marked sensor
+ conversion/crop helpers retain LGPL-2.1-or-later terms. The original capture
+ consumer is GPL-2.0-only. This does not relicense upstream libcamera.
+- The full upstream source and its notices are fetched during builds. No IPA
+ signing private keys, proprietary Android camera libraries or calibration
+ dumps are distributed here.
+
+Mesa, libyuv and camera runtime dependencies
+- Mesa/Freedreno contributors: https://mesa3d.org/ (the fetched package declares
+ MIT, SGI-B-2.0 and BSL-1.0 component licenses; preserve upstream notices).
+- libyuv contributors: https://chromium.googlesource.com/libyuv/libyuv/
+- ALSA, Paho MQTT, libjpeg-turbo and the remaining external packages retain their
+ own licenses. This repository supplies recipes/integration, not their full
+ source trees or a replacement blanket license.
+
External dependencies
- pmbootstrap (GPLv3), the full kernel and distro packages are fetched
from pinned upstream sources during preparation/build. Their original notices
@@ -51,6 +78,6 @@ Firmware
It does not restrict the GPL-2.0-only recipe/helper source written here.
- No redistribution permission for those payloads is granted by this repository.
-License texts: LICENSE (GPLv2), LICENSES/GPL-3.0, LICENSES/MIT and
+License texts: LICENSE (GPLv2), LICENSES/GPL-3.0, LICENSES/LGPL-2.1, LICENSES/MIT and
LICENSES/BSD-2-Clause. Upstream copyright and license notices take precedence
for inherited material. See docs/LICENSING.md for scope and source links.
diff --git a/README.md b/README.md
index f51577e..4008cf0 100644
--- a/README.md
+++ b/README.md
@@ -4,107 +4,94 @@
# Platina Linux for Xiaomi Mi 8 Lite
-Turn a **Xiaomi Mi 8 Lite (platina, M1808D2TG, Qualcomm Snapdragon 660 / SDM660)**
-into a small **headless Linux server** with Wi-Fi, USB networking and SSH.
-Platina Linux is a device integration built on **postmarketOS and Alpine Linux**,
-using the SDM660 mainline-oriented kernel port. It boots Linux directly from eMMC;
-this is not Android, a container inside Android, or a desktop phone OS.
+Turn a **Xiaomi Mi 8 Lite (platina, M1808D2TG, Snapdragon 660 / SDM660)** into
+an ARM64 **headless Linux server** with Wi-Fi, USB networking and key-only SSH.
+Built on postmarketOS and Alpine Linux, it boots directly from eMMC.
[](https://github.com/Sukecz/platina-linux/actions/workflows/check.yml)
[](LICENSE)
[](docs/HARDWARE.md)
-**Verified existing-installation integration: 0.3.1** · **Kernel: 7.2.12-r1 / 7.2.12-sdm660** · **Development / early hardware testing**
+**Integration: 0.8.1 · Development / early hardware testing · Source-only release**
-**Source/build integration: 0.3.1.** Fresh image builds include both screens,
-display helpers and the shutdown service. The tested phone was updated in place
-to 0.3.1, with screen preview and normal restart verified. The newly built full
-installation image passed offline audits and has not been flashed as a full image.
+The existing test phone runs 0.8.1 with a rear-camera MJPEG stream, optional
+browser microphone listening, compact controls and digital zoom up to 10×.
+Capture is OFF after startup. This is a tested existing-installation update,
+not a fully qualified new installation image or a complete smartphone OS.
-[Installation](docs/INSTALLATION.md) · [Build from source](docs/BUILDING.md)
-· [Display development](docs/DISPLAY.md) · [Shutdown](docs/SHUTDOWN.md)
-· [Changelog](CHANGELOG.md) · [Licensing](docs/LICENSING.md)
+[Installation](docs/INSTALLATION.md) · [Build](docs/BUILDING.md)
+· [Camera, audio and Home Assistant](docs/CAMERA.md)
+· [Display](docs/DISPLAY.md) · [Shutdown](docs/SHUTDOWN.md)
+· [Changelog](CHANGELOG.md) · [Releases](https://github.com/Sukecz/platina-linux/releases)
-## What it does
+## Camera and compact controls
-- **Real Linux on the phone:** an ARM64 Alpine userspace, package manager and OpenRC services.
-- **Remote administration:** key-only OpenSSH over Wi-Fi or the USB network gadget,
- with root login and SSH password login disabled.
-- **Reconnect automatically:** NetworkManager restores the configured Wi-Fi connection;
- USB networking provides a separate local administration path.
-- **Headless by default:** keep the backlight dark while running background services.
-- **Battery and charger operation:** use Wi-Fi while running on the battery or a separate charger.
-- **Integrated Tianma display:** boot logo, brightness and ten repeated display
- off/on cycles have been physically verified. Full LCD rail shutdown remains pending.
-- **Repeatable development:** pinned source revisions, versioned recipes, checksum
- verification, offline tests and separate build/export/audit steps.
+The main web panel contains **zoom, focus, JPEG quality, resolution and audio**.
+Exposure, white balance, colors and orientation are in the **Advanced / Pokročilé**
+dialog. Desktop and mobile layouts were checked without page scrolling.
+The header shows actual FPS, resolution and a millisecond processing label
+(frame age since the sensor timestamp, including waiting/processing).
-The goal is a practical always-on server. **Long-term 24/7 stability and sustained
-power balance have not yet been qualified.** Existing phone components keep their
-own support limits; this project does not claim full smartphone functionality.
+- **Digital zoom 1–10×:** a centered crop in the shared image pipeline, so a web
+ zoom change also appears in the Home Assistant image. Resolution stays fixed;
+ digital zoom cannot add missing detail.
+- **Six output sizes:** 12, 5.4, 3, 1.3, 0.75 and 0.33 MP. At 1× zoom they retain
+ the full sensor field of view. JPEG quality ranges from 10 to 95.
+- **Exposure and white balance:** automatic/manual modes, live sensor time/gain
+ telemetry, manual focus and color controls. The capture target is fixed at
+ 30 FPS; observed output rates depend on scene, resolution and processing load.
+- **Browser audio:** explicit microphone ON/OFF and volume control. Audio and
+ MJPEG remain separate and are not precisely synchronized.
+- **Home Assistant:** MQTT Discovery controls and a shared MJPEG/snapshot output.
+ The current HA MJPEG camera **does not carry audio**. A unified A/V stream is
+ deferred; no always-on transcoder or external server is required by this release.
+
+Open `http://platina.local:8082/` on your own qualified installation.
+The service has no user login: keep it on a trusted network or behind an
+appropriate authenticated proxy/VPN. See the [camera guide](docs/CAMERA.md)
+for source builds, credentials, startup policy and qualification limits.
## Feature status
-**Last reviewed: 2026-10-23.** Status describes tests on the maintainer's Mi 8 Lite,
-not a guarantee for every device or panel variant.
+Last reviewed **2026-10-27**, on the maintainer's Tianma Mi 8 Lite.
+🟢 Verified · 🟠 Partial / awaiting qualification · 🔴 Unsupported / not working
-🟢 **Verified** · 🟠 **Partial / prepared / awaiting hardware testing** · 🔴 **Not working / unsupported**
-
-| Feature | Status | What has been verified |
+| Feature | Status | Evidence and limits |
|---|:---:|---|
-| Linux boot from internal eMMC | 🟢 | Installed system, normal startup and repeated restarts |
-| ARM64 userspace and OpenRC | 🟢 | postmarketOS v26.06 / Alpine; services start after boot |
-| SSH over Wi-Fi | 🟢 | Direct LAN login with an administrator key |
-| SSH over USB networking | 🟢 | USB gadget administration on a Linux host |
-| SSH authentication hardening | 🟢 | Password and root SSH login disabled; administrator uses sudo |
-| Wi-Fi reconnect | 🟢 | Reconnect after radio recovery; network configuration persists |
-| USB network recovery | 🟢 | Software disconnect/reconnect and address recovery |
-| mDNS hostname | 🟢 | `platina.local` on a compatible local network |
-| eMMC / ext4 storage | 🟢 | Read/write root filesystem and offline image checks |
-| Battery operation | 🟢 | Wi-Fi administration with data USB physically disconnected |
-| Separate charger operation | 🟢 | Operation and charging confirmed with a suitable charger/cable |
-| Battery / thermal telemetry | 🟢 | Battery information and CPU, GPU and battery temperature readings |
-| Physical shutdown buttons and screen | 🟢 | Power + Volume Up held for 3 s, release both; Power off logo and battery shutdown physically verified |
-| Staying off while USB power is connected | 🔴 | Accepted limitation: disconnect USB/charger before shutdown; otherwise the bootloader starts Linux again |
-| Short boot logo | 🟢 | Automatic logo and subsequent shutdown physically confirmed after normal boot in 0.2.0 |
-| Integrated Tianma NT36672A panel driver | 🟢 | Kernel 7.2.12-r1: RAM boot, normal eMMC boot, image and ten off/on cycles verified |
-| Display power, brightness and custom images | 🟠 | Brightness and driver powerdown verified; VSP/VSN remain fixed always-on. Custom-image conversion tested offline |
-| Beszel monitoring | 🟠 | Native monitoring tested separately; optional custom hub/power-chart integration is outside this source base |
-| VPN access from outside the home network | 🟠 | A LAN jump-host route was tested; a real off-site client test is pending |
-| Continuous 48–72-hour uptime | 🟠 | Qualification is pending; shorter successful tests are not a soak test |
-| Sustained charging / wall power use | 🟠 | Short charger tests passed; long-term balance and wall-meter measurements are pending |
-| CPU frequency scaling | 🟠 | Port/platform limitation; no supported full scaling claim |
-| Audio, Bluetooth, camera and SD card | 🟠 | Not functionally qualified by this project |
-| Touchscreen on the tested device | 🔴 | Controller initialization fails; headless administration is unaffected |
-| Mobile calls / mobile data | 🔴 | Outside the supported headless-server feature set |
-| Android apps / Android services | 🔴 | This system replaces the running Android environment |
-| Other Xiaomi Mi 8 models / other phones | 🔴 | This port targets **Mi 8 Lite / platina only** |
+| Linux boot from eMMC, ARM64 Alpine and OpenRC | 🟢 | Normal starts and repeated restarts |
+| Key-only SSH over Wi-Fi and USB networking | 🟢 | Administrator login; password/root SSH login disabled |
+| Wi-Fi reconnect, USB recovery and mDNS | 🟢 | Tested recovery paths and local hostname |
+| eMMC / ext4 and battery operation | 🟢 | Installed system and physically disconnected data USB operation |
+| Separate charger operation | 🟢 | Short physical charging/operation tests |
+| Battery / CPU / GPU thermal telemetry | 🟢 | Readings available; state-of-charge accuracy and low-battery policy need work |
+| Tianma NT36672A display | 🟢 | Boot logo, brightness and ten off/on cycles tested |
+| Full display power removal | 🟠 | VSP/VSN remain fixed always-on; full rail shutdown/power savings unproven |
+| Power + Volume Up shutdown | 🟢 | Hold both 3 seconds, release both; physical battery shutdown tested |
+| Staying off with USB/charger attached | 🔴 | Disconnect external power before shutdown; charger boot starts Linux again |
+| Rear camera, web controls and HA MJPEG | 🟠 | Live 2008×2680 MJPEG/zoom/UI checked; color, exposure response and long-term qualification remain limited |
+| Browser microphone | 🟠 | PCM playback/lifecycle checked; subjective quality and synchronized A/V not qualified |
+| H.264 / shared video and audio in HA | 🔴 | Deferred; Venus is not a working hardware encoder path |
+| Continuous 48–72-hour operation / sustained power balance | 🟠 | Qualification pending; short tests are not a soak test |
+| Off-site VPN access | 🟠 | Local jump route checked; real off-site client test pending |
+| CPU frequency scaling | 🟠 | No supported full DVFS claim |
+| Bluetooth and SD card | 🟠 | Not functionally qualified |
+| Touchscreen on this device | 🔴 | Controller initialization fails |
+| Mobile calls/data and Android apps | 🔴 | Outside this headless integration |
-To switch the phone off and keep it off, **disconnect USB/the charger first**,
-hold **Power + Volume Up for at least 3 seconds**, then release both buttons.
-The Platina logo and Power off screen appear during shutdown. The shutdown
-service is enabled; experimental PMIC trigger changes are not loaded automatically.
+## Build and installation boundaries
-The checked-in candidate sources are **kernel 7.2.12-r1 + device 5-r31**. The
-physically verified 0.2.0 installation uses that kernel with device 5-r30 and
-the documented runtime initramfs adjustments. The public firmware recipe is 2-r5, with a newly written packaging
-helper; proprietary firmware payloads are supplied locally by each builder.
-No prebuilt installation images or binary firmware are published here.
+The tested camera installation uses **kernel 7.2.12-sdm660, r9 boot plus r11
+sensor module**, with signed `platina-libcamera` **0.7.1-r31** and isolated Mesa
+26.1.6. The checked-in kernel recipe is the **7.2.12-r12 development candidate**,
+with device 5-r31 and the public source firmware recipe 2-r5. That combined kernel
+and a new full 0.8.1 image have **not** passed a complete hardware installation test.
+Camera packages are built/installed separately; `make images` does not yet add them.
-## Hardware
-
-**Tested:** Xiaomi Mi 8 Lite, model **M1808D2TG**, codename **platina**, Snapdragon 660,
-4 GB RAM / 64 GB eMMC, **Tianma NT36672A 1080 × 2280 LCD**.
-Other RAM/storage variants and BOE panel variants are not qualified. Check the
-codename and actual panel before using the display candidate. The Mi 8, Mi 8 SE,
-Mi 8 Pro and Mi 8 Lite are different devices.
-
-## Getting started
-
-You need an unlocked bootloader, a Linux build host, your own SSH public key,
-matching stock firmware inputs and a recovery plan. **Initial installation erases
-Android user data.** Follow the [installation guide](docs/INSTALLATION.md), including
-its backup, device identification and RAM-test stages before a permanent flash.
+No prebuilt APKs, boot/rootfs images, proprietary firmware or calibration data
+are published. Provide your own administrator public key and matching firmware,
+retain a verified recovery path, and qualify each new kernel/image on your device.
+Initial installation erases Android user data. See [installation](docs/INSTALLATION.md)
+and [building](docs/BUILDING.md) before any flash.
```sh
git clone https://github.com/Sukecz/platina-linux.git
@@ -113,28 +100,24 @@ make doctor
make check
```
-The public tree contains the current port recipes, build and audit tools,
-display sources, regression tests and documentation. Configuration, firmware,
-phone backups and generated images remain local.
+To stay powered off, **disconnect USB/the charger**, hold **Power + Volume Up
+for at least 3 seconds**, then release both. Attached power triggers a charger-mode
+boot; this accepted limitation is not changed by the camera release.
-## Updating this project
-
-The table above is maintained alongside code changes. A successful compilation
-means **built**, an offline audit means **audited**, and a physical phone test means
-**hardware verified**. These states are recorded separately.
-
-Platina's integration version lives in `project/release.json`; it is independent
-of the Linux and Alpine version numbers. Integration 0.2.0 records the physically tested Tianma driver; 0.3.0 adds
-the shutdown chord and screen. Display rail and USB charger-boot limits are documented.
+Only **Mi 8 Lite / platina** and the tested **Tianma NT36672A** panel are qualified
+here. Other Mi 8 models and BOE panel variants need their own integration/tests.
+Integration versions are separate from kernel and Alpine package versions.
## Credits and license
Built on [postmarketOS](https://postmarketos.org/), [Alpine Linux](https://alpinelinux.org/),
-[SDM660 mainline](https://github.com/sdm660-mainline/linux) and the
+[SDM660 mainline](https://github.com/sdm660-mainline/linux),
+[libcamera](https://libcamera.org/), [Mesa](https://mesa3d.org/) and the
[community Mi 8 Lite port](https://github.com/macosmojave2-alt/postmarket-mi8lite-platina).
-The panel sequence is based on Xiaomi's published kernel sources and matching
-stock panel data. Original authors and source notices are retained.
+Xiaomi's published kernel sources provide device/panel reference data.
+Original authors, SPDX declarations and upstream notices are retained.
-**Original Platina contributions: GPL-2.0-only.** Third-party code retains its
-own licenses; firmware remains proprietary and is not included. See
-[LICENSE](LICENSE), [NOTICE](NOTICE) and the [licensing notes](docs/LICENSING.md).
+Original integration contributions are **GPL-2.0-only** unless marked otherwise;
+libcamera-derived code and helpers retain their LGPL terms. Firmware remains
+proprietary and is not included. See [LICENSE](LICENSE), [NOTICE](NOTICE) and
+[licensing](docs/LICENSING.md).
diff --git a/docs/BUILDING.md b/docs/BUILDING.md
index a4c3f8c..6e0d226 100644
--- a/docs/BUILDING.md
+++ b/docs/BUILDING.md
@@ -1,9 +1,12 @@
# Building Platina Linux
-This is a source-only development port. Kernel 7.2.12-r1 and the 0.3.1 in-place
-runtime update were tested on a Tianma Mi 8 Lite. Source version 0.3.1 integrates
-that runtime into newly built images; the new full image still requires its own
-hardware acceptance. There is no ready-made stable release.
+This is a source-only development port. Integration **0.8.1**, signed camera
+userspace **0.7.1-r31** and the existing r9-boot/r11-sensor runtime combination
+were checked on one Tianma Mi 8 Lite. The public kernel recipe is **7.2.12-r12**,
+a development candidate, not the exact tested boot/modules combination.
+A combined r12 kernel and a new full 0.8.1 installation image are not hardware
+qualified. The last full base image was built/audited for 0.3.1.
+Camera packages are separate; see [CAMERA.md](CAMERA.md).
## Build host
@@ -14,7 +17,7 @@ It uses two jobs at nice level 10. No host services or phones are restarted.
On Debian/Ubuntu, typical host tools are:
```sh
-sudo apt install git python3 make sudo openssh-client e2fsprogs util-linux kmod mtools fastboot
+sudo apt install git g++ python3 make sudo openssh-client e2fsprogs util-linux kmod mtools fastboot
# Required for the versioned boot/shutdown screens included by make images.
sudo apt install python3-pil fonts-dejavu-core
```
@@ -23,6 +26,7 @@ sudo apt install python3-pil fonts-dejavu-core
and package dependencies are installed inside the build chroots by pmbootstrap.
Python's standard library is enough for the basic offline test suite; the image
runtime integration tests and full image builder also need Pillow and DejaVu Sans.
+Camera conversion/crop tests compile small native C++ programs with `g++`.
## Personal build inputs
@@ -115,3 +119,15 @@ The original logo is preserved; the integration version is added during renderin
These commands create separate local bundles for review or an explicitly planned
existing-installation update. A fresh `make images` already includes both release
screens. See [display setup](DISPLAY.md) and [shutdown behavior](SHUTDOWN.md).
+
+## Camera packages
+
+After preparing the candidate environment, build the isolated Mesa and camera
+packages locally with `scripts/build-camera-userspace.py`; see the complete
+[camera guide](CAMERA.md#source-build-and-installation-boundary). The camera
+package pins libcamera 0.7.1-r31 and the active control/GPU patches. Inactive DMA,
+LUT and other rejected experiment patches are not part of this source release.
+No camera credentials, host-specific deployment helpers or prebuilt APKs are
+included. `make images` currently integrates the base display/shutdown runtime,
+not the separately installed camera packages. Do not describe such an image as
+a fully tested 0.8.1 camera installation.
diff --git a/docs/CAMERA.md b/docs/CAMERA.md
new file mode 100644
index 0000000..9d8c6a1
--- /dev/null
+++ b/docs/CAMERA.md
@@ -0,0 +1,138 @@
+# Camera, browser audio and Home Assistant
+
+Platina Linux **0.8.1** provides a headless rear-camera service on the tested
+Xiaomi Mi 8 Lite with an IMX363 sensor and DW9714 focus actuator. It runs with
+the display dark. This is development software, qualified on one device.
+
+## What is available
+
+- Live MJPEG and snapshots, using an isolated Freedreno GPU software ISP.
+- Six output sizes: 12, 5.4, 3, 1.3, 0.75 and 0.33 megapixels. At 1× zoom,
+ changing output resolution retains the full sensor field of view.
+- Centered digital zoom **1–10×**, applied before the shared JPEG output.
+ A zoom change in the web UI therefore also changes the Home Assistant image.
+ Output dimensions stay constant; digital enlargement cannot restore detail.
+- Manual focus and JPEG quality 10–95. The capture target is fixed at 30 FPS;
+ actual delivered FPS depend on resolution, scene and processing capacity.
+- Automatic/manual exposure, requested exposure time 100–100000 microseconds
+ and analogue gain 1–8×. The sensor clamps time/gain to its configured limits.
+ Actual exposure time and gain are reported separately from requested values.
+- Automatic/manual white balance, gamma, contrast, saturation and rotation.
+- Optional live browser microphone listening, mono PCM16 at 48 kHz, with local
+ volume control. Audio is a separate stream and is not synchronized with MJPEG.
+
+## Compact web UI
+
+Open `http://platina.local:8082/`, or use your phone's own network address.
+The main panel contains zoom, focus, JPEG quality, resolution and audio controls.
+The **Advanced / Pokročilé** dialog has tabs for exposure, white balance, and
+colors/orientation. Values apply live; Save and Restore saved include advanced
+settings. Existing complete settings files are migrated without resetting them.
+
+The header shows actual FPS, dimensions and the restored processing-time label.
+That millisecond value is **frame age since the sensor timestamp at status-read
+time**, including waiting/processing; it is not an isolated JPEG encode time or
+an end-to-end browser latency measurement. The compact layout and dialogs were
+checked without page scrolling at desktop, phone and landscape viewport sizes.
+
+Camera capture is **OFF after each service/system startup**. Loading the page,
+snapshot or MJPEG URL does not enable capture. Stop releases capture and focus,
+removes the last frame, and lets the sensor/lens suspend. Audio also requires an
+explicit action, allows one listener and stops when the page is hidden/closed.
+It does not record sound to disk.
+
+The service listens on all interfaces and has no account/password login. Use a
+trusted network or an authenticated proxy/VPN; do not expose its port directly
+to the Internet. The short-lived audio ticket is an activation mechanism,
+not user authentication.
+
+## Home Assistant
+
+Configure MQTT locally on the phone in `/etc/platina-camera/mqtt.json`, owned by
+root with mode `0600`. Supply your own broker credentials; no maintainer settings
+are included. The expected JSON keys are `host`, optional `port`, `username`,
+`password`, `topic`, `device_id` and `web_url`. Use a unique device ID and topic.
+The optional `py3-paho-mqtt` dependency is installed by the camera package.
+
+MQTT Discovery publishes camera enable/disable, image settings, digital zoom,
+actual FPS and exposure telemetry. Commands retained by the broker are ignored
+so they cannot restart capture after a reconnect. MQTT setting changes are
+saved automatically; the web UI retains its explicit Save action. The legacy
+target-FPS setting is normalized to 30 and has no web slider.
+
+Add Home Assistant's **MJPEG IP Camera** integration using your own phone's URLs:
+
+- MJPEG: `http://platina.local:8082/stream.mjpg`
+- Still image: `http://platina.local:8082/snapshot.jpg`
+
+The HA host must resolve that name, or you can use the phone's own reserved
+address. Both URLs use the same already-processed image, including zoom. They
+return HTTP 503 while capture is OFF. Use the discovered camera switch to enable
+capture explicitly. No dashboard, HA token or broker password is bundled.
+
+**The existing HA MJPEG camera has no audio.** Browser PCM listening does not
+add an audio track to that entity. A shared H.264/AAC or WebRTC path would require
+additional encoding, timing and playback work. It is deferred in this release;
+there is no continuously running transcoder or dependency on an external server.
+
+## Source build and installation boundary
+
+The camera packages are separate from the base image recipe. After preparing
+your own candidate environment as described in [BUILDING.md](BUILDING.md):
+
+```sh
+python3 scripts/build-camera-userspace.py --component mesa --lax
+python3 scripts/build-camera-userspace.py --component userspace --lax
+```
+
+This builds isolated Mesa/Freedreno 26.1.6 and `platina-libcamera` 0.7.1-r31.
+The latter includes the camera consumer, HTTP/MQTT controller, UI, OpenRC service
+and the active libcamera patches. Neither command connects to a phone. These
+packages are not automatically installed by `make images`.
+
+Before any installation, qualify a matching camera-enabled kernel and modules,
+the IMX363/CCI/CAMSS media graph and DW9714 actuator on your own device. A
+display-only kernel is insufficient. The source kernel candidate is 7.2.12-r12;
+the tested installation instead uses the separately tested r9 boot and r11 sensor
+module runtime combination. **The combined r12 kernel and a new full 0.8.1 image
+have not passed a complete hardware installation test.** Do not replace a
+working boot/modules set merely to install the camera userspace.
+
+Install only your own signed camera/Mesa packages with your matching APK public
+key, preserving existing configuration and rollback packages. On a qualified
+installation the service can be enabled/started with:
+
+```sh
+sudo rc-update add platina-camera default
+sudo rc-service platina-camera start
+```
+
+Starting this service exposes controls and MQTT; capture remains OFF. Review
+logs in `/var/log/platina-camera.log` and enable capture through the web or MQTT.
+The service currently runs as root for device/mixer access; privilege reduction
+has not been qualified. Generic building steps are not permission to flash
+another device or reuse another phone's calibration/firmware/configuration.
+
+## Validation and remaining limits
+
+The existing phone received signed 0.7.1-r31 userspace and integration 0.8.1.
+Runtime files matched the built package; its existing boot and system boot ID
+were preserved. Zoom 10× and decoded 2008×2680 MJPEG were exercised through the
+live browser. Compact controls, advanced tabs, save/restore, MQTT Discovery and
+the exposure control interface were checked. The 0.8.1 header change was tested
+with synthetic frame metadata while keeping the phone's capture OFF.
+
+Browser audio data/lifecycle and short audio/video coexistence tests passed.
+These do not establish subjective microphone quality, synchronized A/V, precise
+power cost, or long-term capture reliability. The exposure response, color/zoom
+quality and microphone quality still need broader physical qualification.
+Short samples around 14–15 FPS are observations, not guaranteed performance.
+
+Venus H.264 experiments previously encountered firmware/kernel failures and are
+not a working encoder path. Do not enable the block based solely on a compiled
+driver or the partial legacy-transform patch in the development kernel recipe.
+Front/secondary cameras, autofocus and full camera ISP tuning are not qualified.
+
+Sources and attribution: [NOTICE](../NOTICE),
+[licensing](LICENSING.md), [HA MJPEG](https://www.home-assistant.io/integrations/mjpeg/)
+and [HA Stream](https://www.home-assistant.io/integrations/stream/).
diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md
index 4ddf6f9..42924df 100644
--- a/docs/HARDWARE.md
+++ b/docs/HARDWARE.md
@@ -17,3 +17,8 @@ The phone has to stay awake for this headless-server use case.
Before repurposing an older phone, inspect its battery and check its storage
health. Keep a recovery route through the unlocked bootloader and Fastboot.
See the [feature matrix](../README.md#feature-status) for actual support status.
+
+The tested rear-camera path is Sony IMX363 with a DW9714 focus actuator. Optional
+browser audio uses one tested built-in microphone path. Other camera suppliers,
+front/secondary sensors and other microphone paths are not interchangeable proof
+of support. See [camera status and limitations](CAMERA.md).
diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md
index 1c811f3..e99c391 100644
--- a/docs/INSTALLATION.md
+++ b/docs/INSTALLATION.md
@@ -1,11 +1,12 @@
# Install Linux on Xiaomi Mi 8 Lite (platina)
-**Development port.** The maintainer's existing installation boots and provides
-SSH; kernel 7.2.12-r1 and integration 0.3.0 passed physical Tianma display and
-shutdown tests. The existing installation also passed its 0.3.1 runtime update
-and restart checks. New full images built from 0.3.1 have a separate acceptance
-requirement. There is no supported prebuilt installer.
-Build your own images using [BUILDING.md](BUILDING.md).
+**Development port.** The maintainer's existing phone runs integration0.8.1
+with a separately qualified r9 boot/r11 camera-sensor runtime. The source kernel
+recipe is7.2.12-r12; its combined full installation has not been hardware accepted.
+The last new base image was built/audited for0.3.1. Current camera packages are
+installed separately and are not included automatically by `make images`.
+There is no supported prebuilt installer. See [BUILDING.md](BUILDING.md) and
+[CAMERA.md](CAMERA.md) for the build and camera qualification boundaries.
These steps are for a **fresh installation** on **Mi 8 Lite / platina**.
Flashing `userdata` destroys Android apps and personal data. For an existing Linux
diff --git a/docs/LICENSING.md b/docs/LICENSING.md
index 93973e5..d775b97 100644
--- a/docs/LICENSING.md
+++ b/docs/LICENSING.md
@@ -37,6 +37,12 @@ are one GPLv2 program. Existing copyrights and SPDX notices are retained.
source. The public firmware revision is 2-r5 to distinguish this packaging change.
- **Firmware binaries:** proprietary and absent from this Git repository. Each
builder supplies matching inputs locally and must respect their own usage rights.
+- **Camera/software ISP:** upstream libcamera licenses remain applicable. Changes
+ to LGPL sources and the explicitly marked exposure/zoom helpers retain
+ LGPL-2.1-or-later. The original camera consumer is GPL-2.0-only. See the
+ included LGPL-2.1 text and the original SPDX/author notices.
+- **Mesa/Freedreno and other camera dependencies:** fetched separately by recipes;
+ their component licenses are not replaced by the integration's GPLv2 license.
- **External toolchains/packages:** retain their own licenses; the source repository
does not vendor the full distro or claim ownership of those projects.
@@ -47,7 +53,7 @@ Full attribution and license texts are in NOTICE and LICENSES/.
## Source publication versus image publication
-This initial public repository contains source and the project logo. It does not
+This public release contains source and the project logo. It does not
publish APKs, prebuilt disk/boot images, stock ROMs or device calibration backups.
Building a local image does not automatically grant permission to redistribute
its proprietary firmware, nor make a personalized SSH key/configuration public.
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0031-media-i2c-imx363.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0031-media-i2c-imx363.patch
new file mode 100644
index 0000000..fc691a7
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0031-media-i2c-imx363.patch
@@ -0,0 +1,1556 @@
+From: Platina Linux contributors
+Subject: [PATCH] media: i2c: carry IMX363 from sdm845-mainline with safe reset sequencing
+
+Driver from sdm845-mainline/linux 85f1df2a4ec71d7a91dd95a7a49f889d1595ffa8
+(sdm845-7.1-rc1-r0), drivers/media/i2c/imx363.c, GPL-2.0.
+Original Intel copyright and module authors retained. Platina changes:
+hold reset through power/clock startup, propagate clock-enable failures,
+and log a successfully verified chip ID. Physical capture is not yet verified.
+
+--- a/drivers/media/i2c/Kconfig
++++ b/drivers/media/i2c/Kconfig
+@@ -265,6 +265,13 @@
+
+ To compile this driver as a module, choose M here: the
+ module will be called imx355.
++
++config VIDEO_IMX363
++ tristate "Sony IMX363 sensor support"
++ select V4L2_CCI_I2C
++ help
++ V4L2 driver for the Sony IMX363 camera sensor.
++ The module will be called imx363.
+
+ config VIDEO_IMX412
+ tristate "Sony IMX412 sensor support"
+--- a/drivers/media/i2c/Makefile
++++ b/drivers/media/i2c/Makefile
+@@ -59,6 +59,7 @@
+ obj-$(CONFIG_VIDEO_IMX334) += imx334.o
+ obj-$(CONFIG_VIDEO_IMX335) += imx335.o
+ obj-$(CONFIG_VIDEO_IMX355) += imx355.o
++obj-$(CONFIG_VIDEO_IMX363) += imx363.o
+ obj-$(CONFIG_VIDEO_IMX412) += imx412.o
+ obj-$(CONFIG_VIDEO_IMX415) += imx415.o
+ obj-$(CONFIG_VIDEO_IR_I2C) += ir-kbd-i2c.o
+--- /dev/null
++++ b/drivers/media/i2c/imx363.c
+@@ -0,0 +1,1518 @@
++// SPDX-License-Identifier: GPL-2.0
++// Copyright (C) 2018 Intel Corporation
++
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++
++#define IMX363_REG_MODE_SELECT CCI_REG8(0x0100)
++#define IMX363_MODE_STANDBY 0x00
++#define IMX363_MODE_STREAMING 0x01
++
++#define IMX363_REG_RESET CCI_REG8(0x0103)
++
++/* Chip ID */
++#define IMX363_REG_CHIP_ID CCI_REG16(0x0016)
++#define IMX363_CHIP_ID 0x0363
++
++/* V_TIMING internal */
++// basically frame length lines? from downstream
++#define IMX363_VTS_30FPS 3136 //0c40
++// #define IMX363_VTS_30FPS_2K 0x0638
++#define IMX363_VTS_30FPS_HD 1296
++#define IMX363_VTS_MAX 65525
++
++/* HBLANK control - read only */
++#define IMX363_PPL_DEFAULT 8832
++
++/* Exposure control */
++#define IMX363_REG_EXPOSURE CCI_REG16(0x0202)
++#define IMX363_EXPOSURE_OFFSET 10
++#define IMX363_EXPOSURE_MIN 4
++#define IMX363_EXPOSURE_STEP 1
++#define IMX363_EXPOSURE_DEFAULT 0x640
++#define IMX363_EXPOSURE_MAX (IMX363_VTS_MAX - IMX363_EXPOSURE_OFFSET)
++
++/* Analog gain control */
++#define IMX363_REG_ANALOG_GAIN CCI_REG16(0x0204)
++#define IMX363_ANA_GAIN_MIN 0
++#define IMX363_ANA_GAIN_MAX 480
++#define IMX363_ANA_GAIN_STEP 1
++#define IMX363_ANA_GAIN_DEFAULT 0x0
++
++/* Digital gain control */
++#define IMX363_REG_GR_DIGITAL_GAIN CCI_REG16(0x020e)
++#define IMX363_REG_R_DIGITAL_GAIN CCI_REG16(0x0210)
++#define IMX363_REG_B_DIGITAL_GAIN CCI_REG16(0x0212)
++#define IMX363_REG_GB_DIGITAL_GAIN CCI_REG16(0x0214)
++#define IMX363_DGTL_GAIN_MIN 0
++#define IMX363_DGTL_GAIN_MAX 4096 /* Max = 0xFFF */
++#define IMX363_DGTL_GAIN_DEFAULT 1024
++#define IMX363_DGTL_GAIN_STEP 1
++
++/* HDR control */
++#define IMX363_REG_HDR CCI_REG8(0x0220)
++#define IMX363_HDR_ON BIT(0)
++#define IMX363_REG_HDR_RATIO CCI_REG8(0x0222)
++#define IMX363_HDR_RATIO_MIN 0
++#define IMX363_HDR_RATIO_MAX 5
++#define IMX363_HDR_RATIO_STEP 1
++#define IMX363_HDR_RATIO_DEFAULT 0x0
++
++/* Test Pattern Control */
++#define IMX363_REG_TEST_PATTERN CCI_REG16(0x0600)
++
++#define IMX363_CLK_BLANK_STOP CCI_REG8(0x4040)
++
++/* Orientation */
++#define REG_MIRROR_FLIP_CONTROL CCI_REG8(0x0101)
++#define REG_CONFIG_MIRROR_HFLIP 0x01
++#define REG_CONFIG_MIRROR_VFLIP 0x02
++
++/* IMX363 native and active pixel array size. */
++#define IMX363_NATIVE_WIDTH 4048U
++#define IMX363_NATIVE_HEIGHT 3168U
++#define IMX363_PIXEL_ARRAY_LEFT 8U
++#define IMX363_PIXEL_ARRAY_TOP 24U
++#define IMX363_PIXEL_ARRAY_WIDTH 4032U
++#define IMX363_PIXEL_ARRAY_HEIGHT 3024U
++
++/* regs */
++#define IMX363_REG_PLL_MULT_DRIV CCI_REG8(0x0310)
++#define IMX363_REG_IVTPXCK_DIV CCI_REG8(0x0301)
++#define IMX363_REG_IVTSYCK_DIV CCI_REG8(0x0303)
++#define IMX363_REG_PREPLLCK_VT_DIV CCI_REG8(0x0305)
++#define IMX363_REG_IOPPXCK_DIV CCI_REG8(0x0309)
++#define IMX363_REG_IOPSYCK_DIV CCI_REG8(0x030b)
++#define IMX363_REG_PREPLLCK_OP_DIV CCI_REG8(0x030d)
++#define IMX363_REG_PHASE_PIX_OUTEN CCI_REG8(0x3030)
++#define IMX363_REG_PDPIX_DATA_RATE CCI_REG8(0x3032)
++#define IMX363_REG_SCALE_MODE CCI_REG8(0x0401)
++#define IMX363_REG_SCALE_MODE_EXT CCI_REG8(0x3038)
++#define IMX363_REG_AF_WINDOW_MODE CCI_REG8(0x7bcd)
++#define IMX363_REG_FRM_LENGTH_CTL CCI_REG8(0x0350)
++#define IMX363_REG_CSI_LANE_MODE CCI_REG8(0x0114)
++#define IMX363_REG_X_EVN_INC CCI_REG8(0x0381)
++#define IMX363_REG_X_ODD_INC CCI_REG8(0x0383)
++#define IMX363_REG_Y_EVN_INC CCI_REG8(0x0385)
++#define IMX363_REG_Y_ODD_INC CCI_REG8(0x0387)
++#define IMX363_REG_BINNING_MODE CCI_REG8(0x0900)
++#define IMX363_REG_BINNING_TYPE_V CCI_REG8(0x0901)
++#define IMX363_REG_FORCE_FD_SUM CCI_REG8(0x300d)
++#define IMX363_REG_DIG_CROP_X_OFFSET CCI_REG16(0x0408)
++#define IMX363_REG_DIG_CROP_Y_OFFSET CCI_REG16(0x040a)
++#define IMX363_REG_DIG_CROP_IMAGE_WIDTH CCI_REG16(0x040c)
++#define IMX363_REG_DIG_CROP_IMAGE_HEIGHT CCI_REG16(0x040e)
++#define IMX363_REG_SCALE_M CCI_REG16(0x0404)
++#define IMX363_REG_X_OUT_SIZE CCI_REG16(0x034c)
++#define IMX363_REG_Y_OUT_SIZE CCI_REG16(0x034e)
++#define IMX363_REG_X_ADD_STA CCI_REG16(0x0344)
++#define IMX363_REG_Y_ADD_STA CCI_REG16(0x0346)
++#define IMX363_REG_X_ADD_END CCI_REG16(0x0348)
++#define IMX363_REG_Y_ADD_END CCI_REG16(0x034a)
++#define IMX363_REG_EXCK_FREQ CCI_REG16(0x0136)
++#define IMX363_REG_CSI_DT_FMT CCI_REG16(0x0112)
++#define IMX363_REG_LINE_LENGTH_PCK CCI_REG16(0x0342)
++#define IMX363_REG_SCALE_M_EXT CCI_REG16(0x303a)
++#define IMX363_REG_FRM_LENGTH_LINES CCI_REG16(0x0340)
++#define IMX363_REG_FINE_INTEG_TIME CCI_REG8(0x0200)
++#define IMX363_REG_PLL_IVT_MPY CCI_REG16(0x0306)
++#define IMX363_REG_PLL_IOP_MPY CCI_REG16(0x030e)
++#define IMX363_REG_REQ_LINK_BIT_RATE_MBPS_H CCI_REG16(0x0820)
++#define IMX363_REG_REQ_LINK_BIT_RATE_MBPS_L CCI_REG16(0x0822)
++
++struct imx363_reg_list {
++ u32 num_of_regs;
++ const struct cci_reg_sequence *regs;
++};
++
++struct imx363_link_cfg {
++ unsigned int lf_to_pix_rate_factor;
++ struct imx363_reg_list reg_list;
++};
++
++enum {
++ IMX363_2_LANE_MODE,
++ IMX363_4_LANE_MODE,
++ IMX363_LANE_CONFIGS,
++};
++
++/* Link frequency config */
++struct imx363_link_freq_config {
++ u32 pixels_per_line;
++
++ /* Configuration for this link frequency / num lanes selection */
++ struct imx363_link_cfg link_cfg[IMX363_LANE_CONFIGS];
++};
++
++/* Mode : resolution and related config&values */
++struct imx363_mode {
++ /* Frame width */
++ u32 width;
++ /* Frame height */
++ u32 height;
++
++ /* V-timing */
++ u32 vts_def;
++ u32 vts_min;
++
++ /* Index of Link frequency config to be used */
++ u32 link_freq_index;
++ /* Default register values */
++ struct imx363_reg_list reg_list;
++
++ /* Analog crop rectangle */
++ struct v4l2_rect crop;
++};
++
++static const struct cci_reg_sequence mipi_2300mbps_24mhz_2l[] = {
++ { IMX363_REG_EXCK_FREQ, 0x1800 },
++ { IMX363_REG_IVTPXCK_DIV, 10 },
++ { IMX363_REG_IVTSYCK_DIV, 2 },
++ { IMX363_REG_PREPLLCK_VT_DIV, 4 },
++ { IMX363_REG_PLL_IVT_MPY, 212 },
++ { IMX363_REG_IOPPXCK_DIV, 10 },
++ { IMX363_REG_IOPSYCK_DIV, 1 },
++ { IMX363_REG_PREPLLCK_OP_DIV, 2 },
++ { IMX363_REG_PLL_IOP_MPY, 216 },
++ { IMX363_REG_PLL_MULT_DRIV, 0 },
++
++ { IMX363_REG_CSI_LANE_MODE, 1 },
++};
++
++static const struct cci_reg_sequence mipi_2300mbps_24mhz_4l[] = {
++ { IMX363_REG_EXCK_FREQ, 0x1800 },
++ { IMX363_REG_IVTPXCK_DIV, 3 },
++ { IMX363_REG_IVTSYCK_DIV, 2 },
++ { IMX363_REG_PREPLLCK_VT_DIV, 4 },
++ { IMX363_REG_PLL_IVT_MPY, 208 },
++ { IMX363_REG_IOPPXCK_DIV, 10 },
++ { IMX363_REG_IOPSYCK_DIV, 1 },
++ { IMX363_REG_PREPLLCK_OP_DIV, 4 },
++ { IMX363_REG_PLL_IOP_MPY, 230 },
++ { IMX363_REG_PLL_MULT_DRIV, 1 },
++
++ { IMX363_REG_CSI_LANE_MODE, 3 },
++ // { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_H, 2300 * 4 },
++ // { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_L, 0 },
++};
++
++static const struct cci_reg_sequence mipi_642mbps_24mhz_2l[] = {
++ { IMX363_REG_EXCK_FREQ, 0x1800 },
++ { IMX363_REG_IVTPXCK_DIV, 5 },
++ { IMX363_REG_IVTSYCK_DIV, 2 },
++ { IMX363_REG_PREPLLCK_VT_DIV, 4 },
++ { IMX363_REG_PLL_IVT_MPY, 107 },
++ { IMX363_REG_IOPPXCK_DIV, 10 },
++ { IMX363_REG_IOPSYCK_DIV, 1 },
++ { IMX363_REG_PREPLLCK_OP_DIV, 2 },
++ { IMX363_REG_PLL_IOP_MPY, 216 },
++ { IMX363_REG_PLL_MULT_DRIV, 0 },
++
++ { IMX363_REG_CSI_LANE_MODE, 1 },
++ { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_H, 642 * 2 },
++ { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_L, 0 },
++};
++
++static const struct cci_reg_sequence mipi_642mbps_24mhz_4l[] = {
++ { IMX363_REG_EXCK_FREQ, 0x1800 },
++ { IMX363_REG_IVTPXCK_DIV, 5 },
++ { IMX363_REG_IVTSYCK_DIV, 2 },
++ { IMX363_REG_PREPLLCK_VT_DIV, 4 },
++ { IMX363_REG_PLL_IVT_MPY, 107 },
++ { IMX363_REG_IOPPXCK_DIV, 10 },
++ { IMX363_REG_IOPSYCK_DIV, 1 },
++ { IMX363_REG_PREPLLCK_OP_DIV, 2 },
++ { IMX363_REG_PLL_IOP_MPY, 216 },
++ { IMX363_REG_PLL_MULT_DRIV, 0 },
++
++ { IMX363_REG_CSI_LANE_MODE, 3 },
++ { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_H, 642 * 4 },
++ { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_L, 0 },
++};
++
++static const struct cci_reg_sequence mode_common_regs[] = {
++ // Magical IMX363 Regs & Values - Found in downstream.
++ // Doesn't affect output except for the few noted. So disable.
++ // { CCI_REG8(0x31a3), 0x00 },
++ // { CCI_REG8(0x64d4), 0x01 },
++ // { CCI_REG8(0x64d5), 0xaa },
++ // { CCI_REG8(0x64d6), 0x01 },
++ // { CCI_REG8(0x64d7), 0xa9 },
++ // { CCI_REG8(0x64d8), 0x01 },
++ // { CCI_REG8(0x64d9), 0xa5 },
++ // { CCI_REG8(0x64da), 0x01 },
++ // { CCI_REG8(0x64db), 0xa1 },
++ // { CCI_REG8(0x720a), 0x24 },
++ // { CCI_REG8(0x720b), 0x89 },
++ // { CCI_REG8(0x720c), 0x85 },
++ // { CCI_REG8(0x720d), 0xa1 },
++ // { CCI_REG8(0x720e), 0x6e },
++ // { CCI_REG8(0x729c), 0x59 },
++ // { CCI_REG8(0x817c), 0xff },
++ // { CCI_REG8(0x817d), 0x80 },
++ // { CCI_REG8(0x9348), 0x96 },
++ // { CCI_REG8(0x934b), 0x8c },
++ // { CCI_REG8(0x934c), 0x82 },
++ // { CCI_REG8(0x9353), 0xaa },
++ // { CCI_REG8(0x9354), 0xaa },
++ // { CCI_REG8(0x30F4), 0x02 },
++ // { CCI_REG8(0x30F5), 0x80 },
++ // { CCI_REG8(0x31A5), 0x00 }, //causes white output
++ // { CCI_REG8(0x31A6), 0x00 }, //causes white output
++ // { CCI_REG8(0x560F), 0xBE }, //causes cropped corrupted nonsensical output
++ // { CCI_REG8(0x5856), 0x08 },
++ // { CCI_REG8(0x58D0), 0x10 },
++ // { CCI_REG8(0x734A), 0x01 },
++ // { CCI_REG8(0x734F), 0x2B },
++ // { CCI_REG8(0x7441), 0x55 },
++ // { CCI_REG8(0x7914), 0x03 },
++ // { CCI_REG8(0x7928), 0x04 },
++ // { CCI_REG8(0x7929), 0x04 },
++ // { CCI_REG8(0x793F), 0x03 },
++
++ // present in imx258. not present in android downstream logs. doesn't seem to affect output.
++ // {IMX363_REG_SCALE_MODE_EXT, 0},
++ // {IMX363_REG_SCALE_M_EXT, 16},
++ // {IMX363_REG_FORCE_FD_SUM, 1},
++ // {IMX363_REG_FRM_LENGTH_CTL, 0},
++ // {IMX363_REG_ANALOG_GAIN, 0},
++ // {IMX363_REG_GR_DIGITAL_GAIN, 256},
++ // {IMX363_REG_R_DIGITAL_GAIN, 256},
++ // {IMX363_REG_B_DIGITAL_GAIN, 256},
++ // {IMX363_REG_GB_DIGITAL_GAIN, 256},
++ // {IMX363_REG_AF_WINDOW_MODE, 0},
++ // {IMX363_REG_PHASE_PIX_OUTEN, 0},
++ // {IMX363_REG_PDPIX_DATA_RATE, 0},
++ // {IMX363_REG_HDR, 0},
++
++ // Seems important. Probably will work even without specifying these. But let's just set it anyway.
++ // {IMX363_REG_CSI_DT_FMT, 0x0a0a},
++ // {IMX363_REG_LINE_LENGTH_PCK, IMX363_PPL_DEFAULT},
++ {CCI_REG8(0x0136), 0x18},
++ {CCI_REG8(0x0137), 0x00},
++ {CCI_REG8(0x31A3), 0x00},
++ {CCI_REG8(0x64D4), 0x01},
++ {CCI_REG8(0x64D5), 0xAA},
++ {CCI_REG8(0x64D6), 0x01},
++ {CCI_REG8(0x64D7), 0xA9},
++ {CCI_REG8(0x64D8), 0x01},
++ {CCI_REG8(0x64D9), 0xA5},
++ {CCI_REG8(0x64DA), 0x01},
++ {CCI_REG8(0x64DB), 0xA1},
++ {CCI_REG8(0x720A), 0x24},
++ {CCI_REG8(0x720B), 0x89},
++ {CCI_REG8(0x720C), 0x85},
++ {CCI_REG8(0x720D), 0xA1},
++ {CCI_REG8(0x720E), 0x6E},
++ {CCI_REG8(0x729C), 0x59},
++ {CCI_REG8(0x817C), 0xFF},
++ {CCI_REG8(0x817D), 0x80},
++ {CCI_REG8(0x9348), 0x96},
++ {CCI_REG8(0x934B), 0x8C},
++ {CCI_REG8(0x934C), 0x82},
++ {CCI_REG8(0x9353), 0xAA},
++ {CCI_REG8(0x9354), 0xAA},
++ {CCI_REG8(0x4073), 0x30},
++};
++
++static const struct cci_reg_sequence mode_4032x3024_regs[] = {
++ // {IMX363_REG_BINNING_MODE, 0},
++ // {IMX363_REG_BINNING_TYPE_V, 0x11},
++ // // {IMX363_REG_SCALE_MODE, 1},
++ // // {IMX363_REG_SCALE_M, 64},
++ // {IMX363_REG_X_ADD_STA, 0}, // analog cropping
++ // {IMX363_REG_Y_ADD_STA, 0},
++ // {IMX363_REG_X_ADD_END, 4031},
++ // {IMX363_REG_Y_ADD_END, 3023},
++ // {IMX363_REG_X_EVN_INC, 1}, //subsampling
++ // {IMX363_REG_X_ODD_INC, 1},
++ // {IMX363_REG_Y_EVN_INC, 1},
++ // {IMX363_REG_Y_ODD_INC, 1},
++ // {IMX363_REG_DIG_CROP_X_OFFSET, 0}, // digital cropping
++ // {IMX363_REG_DIG_CROP_Y_OFFSET, 0},
++ // {IMX363_REG_DIG_CROP_IMAGE_WIDTH, 4032},
++ // {IMX363_REG_DIG_CROP_IMAGE_HEIGHT, 3024},
++ // {IMX363_REG_X_OUT_SIZE, 4032},
++ // {IMX363_REG_Y_OUT_SIZE, 3024},
++ // {IMX363_REG_FRM_LENGTH_LINES, IMX363_VTS_30FPS},
++ {CCI_REG8(0x0112), 0x0A},
++ {CCI_REG8(0x0113), 0x0A},
++ {CCI_REG8(0x0114), 0x03},
++ {CCI_REG8(0x0220), 0x00},
++ {CCI_REG8(0x0221), 0x11},
++ {CCI_REG8(0x0340), 0x0C},
++ {CCI_REG8(0x0341), 0x62},
++ {CCI_REG8(0x0342), 0x22},
++ {CCI_REG8(0x0343), 0x80},
++ {CCI_REG8(0x0381), 0x01},
++ {CCI_REG8(0x0383), 0x01},
++ {CCI_REG8(0x0385), 0x01},
++ {CCI_REG8(0x0387), 0x01},
++ {CCI_REG8(0x0900), 0x00},
++ {CCI_REG8(0x0901), 0x11},
++ {CCI_REG8(0x30F4), 0x02},
++ {CCI_REG8(0x30F5), 0x80},
++ {CCI_REG8(0x30F6), 0x00},
++ {CCI_REG8(0x30F7), 0xc8},
++ {CCI_REG8(0x31A0), 0x00},
++ {CCI_REG8(0x31A5), 0x00},
++ {CCI_REG8(0x31A6), 0x00},
++ {CCI_REG8(0x560F), 0xbe},
++ {CCI_REG8(0x5856), 0x08},
++ {CCI_REG8(0x58D0), 0x10},
++ {CCI_REG8(0x734A), 0x01},
++ {CCI_REG8(0x734F), 0x2b},
++ {CCI_REG8(0x7441), 0x55},
++ {CCI_REG8(0x7914), 0x03},
++ {CCI_REG8(0x7928), 0x04},
++ {CCI_REG8(0x7929), 0x04},
++ {CCI_REG8(0x793F), 0x03},
++ {CCI_REG8(0xBC7B), 0x18},
++ {CCI_REG8(0x0344), 0x00},
++ {CCI_REG8(0x0345), 0x00},
++ {CCI_REG8(0x0346), 0x00},
++ {CCI_REG8(0x0347), 0x00},
++ {CCI_REG8(0x0348), 0x0F},
++ {CCI_REG8(0x0349), 0xBF},
++ {CCI_REG8(0x034A), 0x0B},
++ {CCI_REG8(0x034B), 0xCF},
++ {CCI_REG8(0x034C), 0x0F},
++ {CCI_REG8(0x034D), 0xC0},
++ {CCI_REG8(0x034E), 0x0B},
++ {CCI_REG8(0x034F), 0xD0},
++ {CCI_REG8(0x0408), 0x00},
++ {CCI_REG8(0x0409), 0x00},
++ {CCI_REG8(0x040A), 0x00},
++ {CCI_REG8(0x040B), 0x00},
++ {CCI_REG8(0x040C), 0x0F},
++ {CCI_REG8(0x040D), 0xC0},
++ {CCI_REG8(0x040E), 0x0B},
++ {CCI_REG8(0x040F), 0xD0},
++ {CCI_REG8(0x0301), 0x03},
++ {CCI_REG8(0x0303), 0x02},
++ {CCI_REG8(0x0305), 0x04},
++ {CCI_REG8(0x0306), 0x00},
++ {CCI_REG8(0x0307), 0xd2},
++ {CCI_REG8(0x0309), 0x0A},
++ {CCI_REG8(0x030B), 0x01},
++ {CCI_REG8(0x030D), 0x04},
++ {CCI_REG8(0x030E), 0x00},
++ {CCI_REG8(0x030F), 0xdf},
++ {CCI_REG8(0x0310), 0x01},
++ {CCI_REG8(0x0202), 0x0C},
++ {CCI_REG8(0x0203), 0x52},
++ {CCI_REG8(0x0224), 0x06},
++ {CCI_REG8(0x0225), 0x29},
++ {CCI_REG8(0x0204), 0x00},
++ {CCI_REG8(0x0205), 0x00},
++ {CCI_REG8(0x0216), 0x00},
++ {CCI_REG8(0x0217), 0x00},
++ {CCI_REG8(0x020E), 0x01},
++ {CCI_REG8(0x020F), 0x00},
++ {CCI_REG8(0x0226), 0x01},
++ {CCI_REG8(0x0227), 0x00},
++};
++
++static const struct cci_reg_sequence mode_1920_1080_regs[] = {
++ {IMX363_REG_BINNING_MODE, 1},
++ {IMX363_REG_BINNING_TYPE_V, 0x42},
++ // {IMX363_REG_SCALE_MODE, 1},
++ // {IMX363_REG_SCALE_M, 64},
++ {IMX363_REG_X_ADD_STA, 0}, // analog cropping
++ {IMX363_REG_Y_ADD_STA, 0},
++ {IMX363_REG_X_ADD_END, 4031},
++ {IMX363_REG_Y_ADD_END, 3023},
++ {IMX363_REG_X_EVN_INC, 1}, //subsampling
++ {IMX363_REG_X_ODD_INC, 1},
++ {IMX363_REG_Y_EVN_INC, 1},
++ {IMX363_REG_Y_ODD_INC, 1},
++ {IMX363_REG_DIG_CROP_X_OFFSET, 0}, // digital cropping
++ {IMX363_REG_DIG_CROP_Y_OFFSET, 0},
++ {IMX363_REG_DIG_CROP_IMAGE_WIDTH, 1920},
++ {IMX363_REG_DIG_CROP_IMAGE_HEIGHT, 1080},
++ {IMX363_REG_X_OUT_SIZE, 1920},
++ {IMX363_REG_Y_OUT_SIZE, 1080},
++ {IMX363_REG_FRM_LENGTH_LINES, IMX363_VTS_30FPS_HD},
++};
++
++/*
++ * The supported formats.
++ * This table MUST contain 4 entries per format, to cover the various flip
++ * combinations in the order
++ * - no flip
++ * - h flip
++ * - v flip
++ * - h&v flips
++ */
++static const u32 codes[] = {
++ /* 10-bit modes. */
++ MEDIA_BUS_FMT_SRGGB10_1X10,
++ MEDIA_BUS_FMT_SGRBG10_1X10,
++ MEDIA_BUS_FMT_SGBRG10_1X10,
++ MEDIA_BUS_FMT_SBGGR10_1X10
++};
++
++static const char * const imx363_test_pattern_menu[] = {
++ "Disabled",
++ "Solid Colour",
++ "Eight Vertical Colour Bars",
++ "Colour Bars With Fade to Grey",
++ "Pseudorandom Sequence (PN9)",
++};
++
++/* regulator supplies */
++static const char * const imx363_supply_name[] = {
++ /* Supplies can be enabled in any order */
++ "vana", /* Analog (2.8V) supply */
++ "vdig", /* Digital Core (1.2V) supply */
++ "vif", /* IF (1.8V) supply */
++};
++
++#define IMX363_NUM_SUPPLIES ARRAY_SIZE(imx363_supply_name)
++
++enum {
++ IMX363_LINK_FREQ_2300MBPS,
++ IMX363_LINK_FREQ_640MBPS,
++};
++
++/*
++ * Pixel rate does not necessarily relate to link frequency on this sensor as
++ * there is a FIFO between the pixel array pipeline and the MIPI serializer.
++ * The recommendation from Sony is that the pixel array is always run with a
++ * line length of 8832 pixels, which means that there is a large amount of
++ * blanking time for the 1048x780 mode. There is no need to replicate this
++ * blanking on the CSI2 bus, and the configuration of register 0x0301 allows the
++ * divider to be altered.
++ *
++ * The actual factor between link frequency and pixel rate is in the
++ * imx363_link_cfg, so use this to convert between the two.
++ * bits per pixel being 10, and D-PHY being DDR is assumed by this function, so
++ * the value is only the combination of number of lanes and pixel clock divider.
++ */
++static u64 link_freq_to_pixel_rate(u64 f, const struct imx363_link_cfg *link_cfg)
++{
++ f *= 2 * link_cfg->lf_to_pix_rate_factor;
++ do_div(f, 10);
++
++ return f;
++}
++
++/* Menu items for LINK_FREQ V4L2 control */
++/* Configurations for supported link frequencies */
++// static const s64 link_freq_menu_items_19_2[] = {
++// 633600000ULL,
++// 320000000ULL,
++// };
++
++static const s64 link_freq_menu_items_24[] = {
++ 636000000ULL, // NOT SURE HOW TO FIND THIS VALUE
++ 321000000ULL,
++};
++
++#define REGS(_list) { .num_of_regs = ARRAY_SIZE(_list), .regs = _list, }
++
++static const struct imx363_link_freq_config link_freq_configs_24[] = {
++ [IMX363_LINK_FREQ_2300MBPS] = {
++ .pixels_per_line = IMX363_PPL_DEFAULT,
++ .link_cfg = {
++ [IMX363_2_LANE_MODE] = {
++ .lf_to_pix_rate_factor = 2,
++ .reg_list = REGS(mipi_2300mbps_24mhz_2l),
++ },
++ [IMX363_4_LANE_MODE] = {
++ .lf_to_pix_rate_factor = 4,
++ .reg_list = REGS(mipi_2300mbps_24mhz_4l),
++ },
++ }
++ },
++ [IMX363_LINK_FREQ_640MBPS] = {
++ .pixels_per_line = IMX363_PPL_DEFAULT,
++ .link_cfg = {
++ [IMX363_2_LANE_MODE] = {
++ .lf_to_pix_rate_factor = 2 * 2,
++ .reg_list = REGS(mipi_642mbps_24mhz_2l),
++ },
++ [IMX363_4_LANE_MODE] = {
++ .lf_to_pix_rate_factor = 4,
++ .reg_list = REGS(mipi_642mbps_24mhz_4l),
++ },
++ }
++ },
++};
++
++/* Mode configs */
++static const struct imx363_mode supported_modes[] = {
++ {
++ .width = 4032,
++ .height = 3024,
++ .vts_def = IMX363_VTS_30FPS,
++ .vts_min = IMX363_VTS_30FPS,
++ .reg_list = {
++ .num_of_regs = ARRAY_SIZE(mode_4032x3024_regs),
++ .regs = mode_4032x3024_regs,
++ },
++ .link_freq_index = IMX363_LINK_FREQ_2300MBPS,
++ .crop = {
++ .left = IMX363_PIXEL_ARRAY_LEFT,
++ .top = IMX363_PIXEL_ARRAY_TOP,
++ .width = IMX363_PIXEL_ARRAY_WIDTH,
++ .height = IMX363_PIXEL_ARRAY_HEIGHT,
++ },
++ },
++ {
++ .width = 1920,
++ .height = 1080,
++ .vts_def = IMX363_VTS_30FPS_HD,
++ .vts_min = IMX363_VTS_30FPS_HD,
++ .reg_list = {
++ .num_of_regs = ARRAY_SIZE(mode_1920_1080_regs),
++ .regs = mode_1920_1080_regs,
++ },
++ .link_freq_index = IMX363_LINK_FREQ_640MBPS,
++ .crop = {
++ .left = IMX363_PIXEL_ARRAY_LEFT,
++ .top = IMX363_PIXEL_ARRAY_TOP,
++ .width = 4032,
++ .height = 3024,
++ },
++ },
++};
++
++struct imx363 {
++ struct v4l2_subdev sd;
++ struct media_pad pad;
++ struct regmap *regmap;
++
++ struct v4l2_ctrl_handler ctrl_handler;
++ /* V4L2 Controls */
++ struct v4l2_ctrl *link_freq;
++ struct v4l2_ctrl *pixel_rate;
++ struct v4l2_ctrl *vblank;
++ struct v4l2_ctrl *hblank;
++ struct v4l2_ctrl *exposure;
++ struct v4l2_ctrl *hflip;
++ struct v4l2_ctrl *vflip;
++
++ /* Current mode */
++ const struct imx363_mode *cur_mode;
++
++ unsigned long link_freq_bitmap;
++ const struct imx363_link_freq_config *link_freq_configs;
++ const s64 *link_freq_menu_items;
++ unsigned int lane_mode_idx;
++ unsigned int csi2_flags;
++
++ struct gpio_desc *reset_gpio;
++
++ /*
++ * Mutex for serialized access:
++ * Protect sensor module set pad format and start/stop streaming safely.
++ */
++ struct mutex mutex;
++
++ struct clk *clk;
++ struct regulator_bulk_data supplies[IMX363_NUM_SUPPLIES];
++};
++
++static inline struct imx363 *to_imx363(struct v4l2_subdev *_sd)
++{
++ return container_of(_sd, struct imx363, sd);
++}
++
++/* Get bayer order based on flip setting. */
++static u32 imx363_get_format_code(const struct imx363 *imx363)
++{
++ unsigned int i;
++
++ lockdep_assert_held(&imx363->mutex);
++
++ i = (imx363->vflip->val ? 2 : 0) |
++ (imx363->hflip->val ? 1 : 0);
++
++ return codes[i];
++}
++
++/* Open sub-device */
++static int imx363_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
++{
++ struct imx363 *imx363 = to_imx363(sd);
++ struct v4l2_mbus_framefmt *try_fmt =
++ v4l2_subdev_state_get_format(fh->state, 0);
++ struct v4l2_rect *try_crop;
++
++ /* Initialize try_fmt */
++ try_fmt->width = supported_modes[0].width;
++ try_fmt->height = supported_modes[0].height;
++ try_fmt->code = imx363_get_format_code(imx363);
++ try_fmt->field = V4L2_FIELD_NONE;
++
++ /* Initialize try_crop */
++ try_crop = v4l2_subdev_state_get_crop(fh->state, 0);
++ try_crop->left = IMX363_PIXEL_ARRAY_LEFT;
++ try_crop->top = IMX363_PIXEL_ARRAY_TOP;
++ try_crop->width = IMX363_PIXEL_ARRAY_WIDTH;
++ try_crop->height = IMX363_PIXEL_ARRAY_HEIGHT;
++
++ return 0;
++}
++
++static int imx363_update_digital_gain(struct imx363 *imx363, u32 val)
++{
++ int ret = 0;
++
++ cci_write(imx363->regmap, IMX363_REG_GR_DIGITAL_GAIN, val, &ret);
++ cci_write(imx363->regmap, IMX363_REG_GB_DIGITAL_GAIN, val, &ret);
++ cci_write(imx363->regmap, IMX363_REG_R_DIGITAL_GAIN, val, &ret);
++ cci_write(imx363->regmap, IMX363_REG_B_DIGITAL_GAIN, val, &ret);
++
++ return ret;
++}
++
++static void imx363_adjust_exposure_range(struct imx363 *imx363)
++{
++ int exposure_max, exposure_def;
++
++ /* Honour the VBLANK limits when setting exposure. */
++ exposure_max = imx363->cur_mode->height + imx363->vblank->val -
++ IMX363_EXPOSURE_OFFSET;
++ exposure_def = min(exposure_max, imx363->exposure->val);
++ __v4l2_ctrl_modify_range(imx363->exposure, imx363->exposure->minimum,
++ exposure_max, imx363->exposure->step,
++ exposure_def);
++}
++
++static int imx363_set_ctrl(struct v4l2_ctrl *ctrl)
++{
++ struct imx363 *imx363 =
++ container_of(ctrl->handler, struct imx363, ctrl_handler);
++ struct i2c_client *client = v4l2_get_subdevdata(&imx363->sd);
++ int ret = 0;
++
++ /*
++ * The VBLANK control may change the limits of usable exposure, so check
++ * and adjust if necessary.
++ */
++ if (ctrl->id == V4L2_CID_VBLANK)
++ imx363_adjust_exposure_range(imx363);
++
++ /*
++ * Applying V4L2 control value only happens
++ * when power is up for streaming
++ */
++ if (pm_runtime_get_if_in_use(&client->dev) == 0)
++ return 0;
++
++ switch (ctrl->id) {
++ case V4L2_CID_ANALOGUE_GAIN:
++ ret = cci_write(imx363->regmap, IMX363_REG_ANALOG_GAIN,
++ ctrl->val, NULL);
++ break;
++ case V4L2_CID_EXPOSURE:
++ ret = cci_write(imx363->regmap, IMX363_REG_EXPOSURE,
++ ctrl->val, NULL);
++ break;
++ case V4L2_CID_DIGITAL_GAIN:
++ ret = imx363_update_digital_gain(imx363, ctrl->val);
++ break;
++ case V4L2_CID_TEST_PATTERN:
++ ret = cci_write(imx363->regmap, IMX363_REG_TEST_PATTERN,
++ ctrl->val, NULL);
++ break;
++ case V4L2_CID_WIDE_DYNAMIC_RANGE:
++ if (!ctrl->val) {
++ ret = cci_write(imx363->regmap, IMX363_REG_HDR,
++ IMX363_HDR_RATIO_MIN, NULL);
++ } else {
++ ret = cci_write(imx363->regmap, IMX363_REG_HDR,
++ IMX363_HDR_ON, NULL);
++ if (ret)
++ break;
++ ret = cci_write(imx363->regmap, IMX363_REG_HDR_RATIO,
++ BIT(IMX363_HDR_RATIO_MAX), NULL);
++ }
++ break;
++ case V4L2_CID_VBLANK:
++ ret = cci_write(imx363->regmap, IMX363_REG_FRM_LENGTH_LINES,
++ imx363->cur_mode->height + ctrl->val, NULL);
++ break;
++ case V4L2_CID_VFLIP:
++ case V4L2_CID_HFLIP:
++ ret = cci_write(imx363->regmap, REG_MIRROR_FLIP_CONTROL,
++ (imx363->hflip->val ?
++ REG_CONFIG_MIRROR_HFLIP : 0) |
++ (imx363->vflip->val ?
++ REG_CONFIG_MIRROR_VFLIP : 0),
++ NULL);
++ break;
++ default:
++ dev_info(&client->dev,
++ "ctrl(id:0x%x,val:0x%x) is not handled\n",
++ ctrl->id, ctrl->val);
++ ret = -EINVAL;
++ break;
++ }
++
++ pm_runtime_put(&client->dev);
++
++ return ret;
++}
++
++static const struct v4l2_ctrl_ops imx363_ctrl_ops = {
++ .s_ctrl = imx363_set_ctrl,
++};
++
++static int imx363_enum_mbus_code(struct v4l2_subdev *sd,
++ struct v4l2_subdev_state *sd_state,
++ struct v4l2_subdev_mbus_code_enum *code)
++{
++ struct imx363 *imx363 = to_imx363(sd);
++
++ /* Only one bayer format (10 bit) is supported */
++ if (code->index > 0)
++ return -EINVAL;
++
++ code->code = imx363_get_format_code(imx363);
++
++ return 0;
++}
++
++static int imx363_enum_frame_size(struct v4l2_subdev *sd,
++ struct v4l2_subdev_state *sd_state,
++ struct v4l2_subdev_frame_size_enum *fse)
++{
++ struct imx363 *imx363 = to_imx363(sd);
++
++ if (fse->index >= ARRAY_SIZE(supported_modes))
++ return -EINVAL;
++
++ if (fse->code != imx363_get_format_code(imx363))
++ return -EINVAL;
++
++ fse->min_width = supported_modes[fse->index].width;
++ fse->max_width = fse->min_width;
++ fse->min_height = supported_modes[fse->index].height;
++ fse->max_height = fse->min_height;
++
++ return 0;
++}
++
++static void imx363_update_pad_format(struct imx363 *imx363,
++ const struct imx363_mode *mode,
++ struct v4l2_subdev_format *fmt)
++{
++ fmt->format.width = mode->width;
++ fmt->format.height = mode->height;
++ fmt->format.code = imx363_get_format_code(imx363);
++ fmt->format.field = V4L2_FIELD_NONE;
++}
++
++static int __imx363_get_pad_format(struct imx363 *imx363,
++ struct v4l2_subdev_state *sd_state,
++ struct v4l2_subdev_format *fmt)
++{
++ if (fmt->which == V4L2_SUBDEV_FORMAT_TRY)
++ fmt->format = *v4l2_subdev_state_get_format(sd_state,
++ fmt->pad);
++ else
++ imx363_update_pad_format(imx363, imx363->cur_mode, fmt);
++
++ return 0;
++}
++
++static int imx363_get_pad_format(struct v4l2_subdev *sd,
++ struct v4l2_subdev_state *sd_state,
++ struct v4l2_subdev_format *fmt)
++{
++ struct imx363 *imx363 = to_imx363(sd);
++ int ret;
++
++ mutex_lock(&imx363->mutex);
++ ret = __imx363_get_pad_format(imx363, sd_state, fmt);
++ mutex_unlock(&imx363->mutex);
++
++ return ret;
++}
++
++static int imx363_set_pad_format(struct v4l2_subdev *sd,
++ struct v4l2_subdev_state *sd_state,
++ struct v4l2_subdev_format *fmt)
++{
++ struct imx363 *imx363 = to_imx363(sd);
++ const struct imx363_link_freq_config *link_freq_cfgs;
++ const struct imx363_link_cfg *link_cfg;
++ struct v4l2_mbus_framefmt *framefmt;
++ const struct imx363_mode *mode;
++ s32 vblank_def;
++ s32 vblank_min;
++ s64 h_blank;
++ s64 pixel_rate;
++ s64 link_freq;
++
++ mutex_lock(&imx363->mutex);
++
++ fmt->format.code = imx363_get_format_code(imx363);
++
++ mode = v4l2_find_nearest_size(supported_modes,
++ ARRAY_SIZE(supported_modes), width, height,
++ fmt->format.width, fmt->format.height);
++ imx363_update_pad_format(imx363, mode, fmt);
++ if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
++ framefmt = v4l2_subdev_state_get_format(sd_state, fmt->pad);
++ *framefmt = fmt->format;
++ } else {
++ imx363->cur_mode = mode;
++ __v4l2_ctrl_s_ctrl(imx363->link_freq, mode->link_freq_index);
++
++ link_freq = imx363->link_freq_menu_items[mode->link_freq_index];
++ link_freq_cfgs =
++ &imx363->link_freq_configs[mode->link_freq_index];
++
++ link_cfg = &link_freq_cfgs->link_cfg[imx363->lane_mode_idx];
++ pixel_rate = link_freq_to_pixel_rate(link_freq, link_cfg);
++ __v4l2_ctrl_modify_range(imx363->pixel_rate, pixel_rate,
++ pixel_rate, 1, pixel_rate);
++ /* Update limits and set FPS to default */
++ vblank_def = imx363->cur_mode->vts_def -
++ imx363->cur_mode->height;
++ vblank_min = imx363->cur_mode->vts_min -
++ imx363->cur_mode->height;
++ __v4l2_ctrl_modify_range(
++ imx363->vblank, vblank_min,
++ IMX363_VTS_MAX - imx363->cur_mode->height, 1,
++ vblank_def);
++ __v4l2_ctrl_s_ctrl(imx363->vblank, vblank_def);
++ h_blank =
++ imx363->link_freq_configs[mode->link_freq_index].pixels_per_line
++ - imx363->cur_mode->width;
++ __v4l2_ctrl_modify_range(imx363->hblank, h_blank,
++ h_blank, 1, h_blank);
++ }
++
++ mutex_unlock(&imx363->mutex);
++
++ return 0;
++}
++
++static const struct v4l2_rect *
++__imx363_get_pad_crop(struct imx363 *imx363,
++ struct v4l2_subdev_state *sd_state,
++ unsigned int pad, enum v4l2_subdev_format_whence which)
++{
++ switch (which) {
++ case V4L2_SUBDEV_FORMAT_TRY:
++ return v4l2_subdev_state_get_crop(sd_state, pad);
++ case V4L2_SUBDEV_FORMAT_ACTIVE:
++ return &imx363->cur_mode->crop;
++ }
++
++ return NULL;
++}
++
++static int imx363_get_selection(struct v4l2_subdev *sd,
++ struct v4l2_subdev_state *sd_state,
++ struct v4l2_subdev_selection *sel)
++{
++ switch (sel->target) {
++ case V4L2_SEL_TGT_CROP: {
++ struct imx363 *imx363 = to_imx363(sd);
++
++ mutex_lock(&imx363->mutex);
++ sel->r = *__imx363_get_pad_crop(imx363, sd_state, sel->pad,
++ sel->which);
++ mutex_unlock(&imx363->mutex);
++
++ return 0;
++ }
++
++ case V4L2_SEL_TGT_NATIVE_SIZE:
++ sel->r.left = 0;
++ sel->r.top = 0;
++ sel->r.width = IMX363_NATIVE_WIDTH;
++ sel->r.height = IMX363_NATIVE_HEIGHT;
++
++ return 0;
++
++ case V4L2_SEL_TGT_CROP_DEFAULT:
++ case V4L2_SEL_TGT_CROP_BOUNDS:
++ sel->r.left = IMX363_PIXEL_ARRAY_LEFT;
++ sel->r.top = IMX363_PIXEL_ARRAY_TOP;
++ sel->r.width = IMX363_PIXEL_ARRAY_WIDTH;
++ sel->r.height = IMX363_PIXEL_ARRAY_HEIGHT;
++
++ return 0;
++ }
++
++ return -EINVAL;
++}
++
++/* Start streaming */
++static int imx363_start_streaming(struct imx363 *imx363)
++{
++ struct i2c_client *client = v4l2_get_subdevdata(&imx363->sd);
++ const struct imx363_reg_list *reg_list;
++ const struct imx363_link_freq_config *link_freq_cfg;
++ int ret, link_freq_index;
++
++ ret = cci_write(imx363->regmap, IMX363_REG_RESET, 0x01, NULL);
++ if (ret) {
++ dev_err(&client->dev, "%s failed to reset sensor\n", __func__);
++ return ret;
++ }
++
++ /* 12ms is required from poweron to standby */
++ fsleep(12000);
++
++ /* Setup PLL */
++ link_freq_index = imx363->cur_mode->link_freq_index;
++ link_freq_cfg = &imx363->link_freq_configs[link_freq_index];
++
++ reg_list = &link_freq_cfg->link_cfg[imx363->lane_mode_idx].reg_list;
++ ret = cci_multi_reg_write(imx363->regmap, reg_list->regs, reg_list->num_of_regs, NULL);
++ if (ret) {
++ dev_err(&client->dev, "%s failed to set plls\n", __func__);
++ return ret;
++ }
++
++ ret = cci_multi_reg_write(imx363->regmap, mode_common_regs,
++ ARRAY_SIZE(mode_common_regs), NULL);
++ if (ret) {
++ dev_err(&client->dev, "%s failed to set common regs\n", __func__);
++ return ret;
++ }
++
++ ret = cci_write(imx363->regmap, IMX363_CLK_BLANK_STOP,
++ !!(imx363->csi2_flags & V4L2_MBUS_CSI2_NONCONTINUOUS_CLOCK),
++ NULL);
++ if (ret) {
++ dev_err(&client->dev, "%s failed to set clock lane mode\n", __func__);
++ return ret;
++ }
++
++ /* Apply default values of current mode */
++ reg_list = &imx363->cur_mode->reg_list;
++ ret = cci_multi_reg_write(imx363->regmap, reg_list->regs, reg_list->num_of_regs, NULL);
++ if (ret) {
++ dev_err(&client->dev, "%s failed to set mode\n", __func__);
++ return ret;
++ }
++
++ /* Apply customized values from user */
++ ret = __v4l2_ctrl_handler_setup(imx363->sd.ctrl_handler);
++ if (ret)
++ return ret;
++
++ /* set stream on register */
++ return cci_write(imx363->regmap, IMX363_REG_MODE_SELECT,
++ IMX363_MODE_STREAMING, NULL);
++}
++
++/* Stop streaming */
++static int imx363_stop_streaming(struct imx363 *imx363)
++{
++ struct i2c_client *client = v4l2_get_subdevdata(&imx363->sd);
++ int ret;
++
++ /* set stream off register */
++ ret = cci_write(imx363->regmap, IMX363_REG_MODE_SELECT,
++ IMX363_MODE_STANDBY, NULL);
++ if (ret)
++ dev_err(&client->dev, "%s failed to set stream\n", __func__);
++
++ /*
++ * Return success even if it was an error, as there is nothing the
++ * caller can do about it.
++ */
++ return 0;
++}
++
++static int imx363_power_on(struct device *dev)
++{
++ struct v4l2_subdev *sd = dev_get_drvdata(dev);
++ struct imx363 *imx363 = to_imx363(sd);
++ int ret;
++
++ ret = regulator_bulk_enable(IMX363_NUM_SUPPLIES,
++ imx363->supplies);
++ if (ret) {
++ dev_err(dev, "%s: failed to enable regulators\n",
++ __func__);
++ return ret;
++ }
++
++ usleep_range(400, 600);
++
++ ret = clk_prepare_enable(imx363->clk);
++ if (ret) {
++ dev_err(dev, "failed to enable clock\n");
++ regulator_bulk_disable(IMX363_NUM_SUPPLIES, imx363->supplies);
++ return ret;
++ }
++
++ /* Keep reset asserted until supplies and the external clock are ready. */
++ usleep_range(1000, 1200);
++ gpiod_set_value_cansleep(imx363->reset_gpio, 0);
++ usleep_range(1000, 1200);
++
++ return 0;
++}
++
++static int imx363_power_off(struct device *dev)
++{
++ struct v4l2_subdev *sd = dev_get_drvdata(dev);
++ struct imx363 *imx363 = to_imx363(sd);
++
++ gpiod_set_value_cansleep(imx363->reset_gpio, 1);
++ clk_disable_unprepare(imx363->clk);
++
++ regulator_bulk_disable(IMX363_NUM_SUPPLIES, imx363->supplies);
++
++ return 0;
++}
++
++static int imx363_set_stream(struct v4l2_subdev *sd, int enable)
++{
++ struct imx363 *imx363 = to_imx363(sd);
++ struct i2c_client *client = v4l2_get_subdevdata(sd);
++ int ret = 0;
++
++ mutex_lock(&imx363->mutex);
++
++ if (enable) {
++ ret = pm_runtime_resume_and_get(&client->dev);
++ if (ret < 0)
++ goto err_unlock;
++
++ /*
++ * Apply default & customized values
++ * and then start streaming.
++ */
++ ret = imx363_start_streaming(imx363);
++ if (ret)
++ goto err_rpm_put;
++ } else {
++ imx363_stop_streaming(imx363);
++ pm_runtime_put(&client->dev);
++ }
++
++ mutex_unlock(&imx363->mutex);
++
++ return ret;
++
++err_rpm_put:
++ pm_runtime_put(&client->dev);
++err_unlock:
++ mutex_unlock(&imx363->mutex);
++
++ return ret;
++}
++
++/* Verify chip ID */
++static int imx363_identify_module(struct imx363 *imx363)
++{
++ struct i2c_client *client = v4l2_get_subdevdata(&imx363->sd);
++ int ret;
++ u64 val;
++
++ ret = cci_read(imx363->regmap, IMX363_REG_CHIP_ID,
++ &val, NULL);
++ if (ret) {
++ dev_err(&client->dev, "failed to read chip id %x\n",
++ IMX363_CHIP_ID);
++ return ret;
++ }
++
++ if (val != IMX363_CHIP_ID) {
++ dev_err(&client->dev, "chip id mismatch: %x!=%llx\n",
++ IMX363_CHIP_ID, val);
++ return -EIO;
++ }
++
++ return 0;
++}
++
++static const struct v4l2_subdev_video_ops imx363_video_ops = {
++ .s_stream = imx363_set_stream,
++};
++
++static const struct v4l2_subdev_pad_ops imx363_pad_ops = {
++ .enum_mbus_code = imx363_enum_mbus_code,
++ .get_fmt = imx363_get_pad_format,
++ .set_fmt = imx363_set_pad_format,
++ .enum_frame_size = imx363_enum_frame_size,
++ .get_selection = imx363_get_selection,
++};
++
++static const struct v4l2_subdev_ops imx363_subdev_ops = {
++ .video = &imx363_video_ops,
++ .pad = &imx363_pad_ops,
++};
++
++static const struct v4l2_subdev_internal_ops imx363_internal_ops = {
++ .open = imx363_open,
++};
++
++/* Initialize control handlers */
++static int imx363_init_controls(struct imx363 *imx363)
++{
++ struct i2c_client *client = v4l2_get_subdevdata(&imx363->sd);
++ const struct imx363_link_freq_config *link_freq_cfgs;
++ struct v4l2_fwnode_device_properties props;
++ struct v4l2_ctrl_handler *ctrl_hdlr;
++ const struct imx363_link_cfg *link_cfg;
++ s64 vblank_def;
++ s64 vblank_min;
++ s64 pixel_rate;
++ int ret;
++
++ ctrl_hdlr = &imx363->ctrl_handler;
++ ret = v4l2_ctrl_handler_init(ctrl_hdlr, 13);
++ if (ret)
++ return ret;
++
++ mutex_init(&imx363->mutex);
++ ctrl_hdlr->lock = &imx363->mutex;
++ imx363->link_freq = v4l2_ctrl_new_int_menu(ctrl_hdlr,
++ &imx363_ctrl_ops,
++ V4L2_CID_LINK_FREQ,
++ ARRAY_SIZE(link_freq_menu_items_24) - 1,
++ 0,
++ imx363->link_freq_menu_items);
++
++ if (imx363->link_freq)
++ imx363->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY;
++
++ imx363->hflip = v4l2_ctrl_new_std(ctrl_hdlr, &imx363_ctrl_ops,
++ V4L2_CID_HFLIP, 0, 1, 1, 1);
++ if (imx363->hflip)
++ imx363->hflip->flags |= V4L2_CTRL_FLAG_MODIFY_LAYOUT;
++
++ imx363->vflip = v4l2_ctrl_new_std(ctrl_hdlr, &imx363_ctrl_ops,
++ V4L2_CID_VFLIP, 0, 1, 1, 1);
++ if (imx363->vflip)
++ imx363->vflip->flags |= V4L2_CTRL_FLAG_MODIFY_LAYOUT;
++
++ link_freq_cfgs = &imx363->link_freq_configs[0];
++ link_cfg = link_freq_cfgs[imx363->lane_mode_idx].link_cfg;
++ pixel_rate = link_freq_to_pixel_rate(imx363->link_freq_menu_items[0],
++ link_cfg);
++ printk(KERN_INFO "imx363: pixel_rate: %lld\n", pixel_rate);
++
++ /* By default, PIXEL_RATE is read only */
++ imx363->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &imx363_ctrl_ops,
++ V4L2_CID_PIXEL_RATE,
++ pixel_rate, pixel_rate,
++ 1, pixel_rate);
++
++ vblank_def = imx363->cur_mode->vts_def - imx363->cur_mode->height;
++ vblank_min = imx363->cur_mode->vts_min - imx363->cur_mode->height;
++ imx363->vblank = v4l2_ctrl_new_std(
++ ctrl_hdlr, &imx363_ctrl_ops, V4L2_CID_VBLANK,
++ vblank_min,
++ IMX363_VTS_MAX - imx363->cur_mode->height, 1,
++ vblank_def);
++
++ imx363->hblank = v4l2_ctrl_new_std(
++ ctrl_hdlr, &imx363_ctrl_ops, V4L2_CID_HBLANK,
++ IMX363_PPL_DEFAULT - imx363->cur_mode->width,
++ IMX363_PPL_DEFAULT - imx363->cur_mode->width,
++ 1,
++ IMX363_PPL_DEFAULT - imx363->cur_mode->width);
++
++ if (imx363->hblank)
++ imx363->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY;
++
++ imx363->exposure = v4l2_ctrl_new_std(
++ ctrl_hdlr, &imx363_ctrl_ops,
++ V4L2_CID_EXPOSURE, IMX363_EXPOSURE_MIN,
++ IMX363_EXPOSURE_MAX, IMX363_EXPOSURE_STEP,
++ IMX363_EXPOSURE_DEFAULT);
++
++ v4l2_ctrl_new_std(ctrl_hdlr, &imx363_ctrl_ops, V4L2_CID_ANALOGUE_GAIN,
++ IMX363_ANA_GAIN_MIN, IMX363_ANA_GAIN_MAX,
++ IMX363_ANA_GAIN_STEP, IMX363_ANA_GAIN_DEFAULT);
++
++ v4l2_ctrl_new_std(ctrl_hdlr, &imx363_ctrl_ops, V4L2_CID_DIGITAL_GAIN,
++ IMX363_DGTL_GAIN_MIN, IMX363_DGTL_GAIN_MAX,
++ IMX363_DGTL_GAIN_STEP,
++ IMX363_DGTL_GAIN_DEFAULT);
++
++ v4l2_ctrl_new_std(ctrl_hdlr, &imx363_ctrl_ops, V4L2_CID_WIDE_DYNAMIC_RANGE,
++ 0, 1, 1, IMX363_HDR_RATIO_DEFAULT);
++
++ v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &imx363_ctrl_ops,
++ V4L2_CID_TEST_PATTERN,
++ ARRAY_SIZE(imx363_test_pattern_menu) - 1,
++ 0, 0, imx363_test_pattern_menu);
++
++ if (ctrl_hdlr->error) {
++ ret = ctrl_hdlr->error;
++ dev_err(&client->dev, "%s control init failed (%d)\n",
++ __func__, ret);
++ goto error;
++ }
++
++ ret = v4l2_fwnode_device_parse(&client->dev, &props);
++ if (ret)
++ goto error;
++
++ ret = v4l2_ctrl_new_fwnode_properties(ctrl_hdlr, &imx363_ctrl_ops,
++ &props);
++ if (ret)
++ goto error;
++
++ imx363->sd.ctrl_handler = ctrl_hdlr;
++
++ return 0;
++
++error:
++ v4l2_ctrl_handler_free(ctrl_hdlr);
++ mutex_destroy(&imx363->mutex);
++
++ return ret;
++}
++
++static void imx363_free_controls(struct imx363 *imx363)
++{
++ v4l2_ctrl_handler_free(imx363->sd.ctrl_handler);
++ mutex_destroy(&imx363->mutex);
++}
++
++static int imx363_get_regulators(struct imx363 *imx363,
++ struct i2c_client *client)
++{
++ unsigned int i;
++
++ for (i = 0; i < IMX363_NUM_SUPPLIES; i++)
++ imx363->supplies[i].supply = imx363_supply_name[i];
++
++ return devm_regulator_bulk_get(&client->dev,
++ IMX363_NUM_SUPPLIES, imx363->supplies);
++}
++
++static int imx363_probe(struct i2c_client *client)
++{
++ struct imx363 *imx363;
++ struct fwnode_handle *endpoint;
++ struct v4l2_fwnode_endpoint ep = {
++ .bus_type = V4L2_MBUS_CSI2_DPHY
++ };
++ int ret;
++ u32 val = 0;
++
++ imx363 = devm_kzalloc(&client->dev, sizeof(*imx363), GFP_KERNEL);
++ if (!imx363)
++ return -ENOMEM;
++
++ imx363->regmap = devm_cci_regmap_init_i2c(client, 16);
++ if (IS_ERR(imx363->regmap)) {
++ ret = PTR_ERR(imx363->regmap);
++ dev_err(&client->dev, "failed to initialize CCI: %d\n", ret);
++ return ret;
++ }
++
++ ret = imx363_get_regulators(imx363, client);
++ if (ret)
++ return dev_err_probe(&client->dev, ret,
++ "failed to get regulators\n");
++
++ imx363->clk = devm_clk_get_optional(&client->dev, NULL);
++ if (IS_ERR(imx363->clk))
++ return dev_err_probe(&client->dev, PTR_ERR(imx363->clk),
++ "error getting clock\n");
++ // if (!imx363->clk) {
++ // dev_warn(&client->dev,
++ // "no clock provided, using clock-frequency property\n");
++
++ device_property_read_u32(&client->dev, "clock-frequency", &val);
++ // } else {
++ // val = clk_get_rate(imx363->clk);
++ // }
++ ret = clk_set_rate(imx363->clk, val);
++ if (ret)
++ return dev_err_probe(&client->dev, ret,
++ "failed to set clock rate\n");
++
++ switch (val) {
++ // case 19200000:
++ // imx363->link_freq_configs = link_freq_configs_19_2;
++ // imx363->link_freq_menu_items = link_freq_menu_items_19_2;
++ // break;
++ case 24000000:
++ imx363->link_freq_configs = link_freq_configs_24;
++ imx363->link_freq_menu_items = link_freq_menu_items_24;
++ break;
++ default:
++ dev_err(&client->dev, "input clock frequency of %u not supported\n",
++ val);
++ return -EINVAL;
++ }
++
++ endpoint = fwnode_graph_get_next_endpoint(dev_fwnode(&client->dev), NULL);
++ if (!endpoint) {
++ dev_err(&client->dev, "Endpoint node not found\n");
++ return -EINVAL;
++ }
++
++ ret = v4l2_fwnode_endpoint_alloc_parse(endpoint, &ep);
++ fwnode_handle_put(endpoint);
++ if (ret) {
++ dev_err(&client->dev, "Parsing endpoint node failed\n");
++ return ret;
++ }
++
++ ret = v4l2_link_freq_to_bitmap(&client->dev,
++ ep.link_frequencies,
++ ep.nr_of_link_frequencies,
++ imx363->link_freq_menu_items,
++ ARRAY_SIZE(link_freq_menu_items_24),
++ &imx363->link_freq_bitmap);
++ if (ret) {
++ dev_err(&client->dev, "Link frequency not supported\n");
++ goto error_endpoint_free;
++ }
++
++ /* Get number of data lanes */
++ switch (ep.bus.mipi_csi2.num_data_lanes) {
++ case 2:
++ imx363->lane_mode_idx = IMX363_2_LANE_MODE;
++ break;
++ case 4:
++ imx363->lane_mode_idx = IMX363_4_LANE_MODE;
++ printk(KERN_INFO "imx363: 4 lanes\n");
++ break;
++ default:
++ dev_err(&client->dev, "Invalid data lanes: %u\n",
++ ep.bus.mipi_csi2.num_data_lanes);
++ ret = -EINVAL;
++ goto error_endpoint_free;
++ }
++
++ imx363->csi2_flags = ep.bus.mipi_csi2.flags;
++
++ /* request optional reset pin */
++ imx363->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset",
++ GPIOD_OUT_HIGH);
++ if (IS_ERR(imx363->reset_gpio))
++ return PTR_ERR(imx363->reset_gpio);
++
++ /* Initialize subdev */
++ v4l2_i2c_subdev_init(&imx363->sd, client, &imx363_subdev_ops);
++
++ /* Will be powered off via pm_runtime_idle */
++ ret = imx363_power_on(&client->dev);
++ if (ret)
++ goto error_endpoint_free;
++
++ /* Check module identity */
++ ret = imx363_identify_module(imx363);
++ if (ret)
++ goto error_identify;
++
++ dev_info(&client->dev, "verified Sony IMX363 chip ID 0x0363\n");
++
++ /* Set default mode to max resolution */
++ imx363->cur_mode = &supported_modes[0];
++
++ ret = imx363_init_controls(imx363);
++ if (ret)
++ goto error_identify;
++
++ /* Initialize subdev */
++ imx363->sd.internal_ops = &imx363_internal_ops;
++ imx363->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
++ imx363->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
++
++ /* Initialize source pad */
++ imx363->pad.flags = MEDIA_PAD_FL_SOURCE;
++
++ ret = media_entity_pads_init(&imx363->sd.entity, 1, &imx363->pad);
++ if (ret)
++ goto error_handler_free;
++
++ ret = v4l2_async_register_subdev_sensor(&imx363->sd);
++ if (ret < 0)
++ goto error_media_entity;
++
++ pm_runtime_set_active(&client->dev);
++ pm_runtime_enable(&client->dev);
++ pm_runtime_idle(&client->dev);
++ v4l2_fwnode_endpoint_free(&ep);
++
++ return 0;
++
++error_media_entity:
++ media_entity_cleanup(&imx363->sd.entity);
++
++error_handler_free:
++ imx363_free_controls(imx363);
++
++error_identify:
++ imx363_power_off(&client->dev);
++
++error_endpoint_free:
++ v4l2_fwnode_endpoint_free(&ep);
++
++ return ret;
++}
++
++static void imx363_remove(struct i2c_client *client)
++{
++ struct v4l2_subdev *sd = i2c_get_clientdata(client);
++ struct imx363 *imx363 = to_imx363(sd);
++
++ v4l2_async_unregister_subdev(sd);
++ media_entity_cleanup(&sd->entity);
++ imx363_free_controls(imx363);
++
++ pm_runtime_disable(&client->dev);
++ if (!pm_runtime_status_suspended(&client->dev))
++ imx363_power_off(&client->dev);
++ pm_runtime_set_suspended(&client->dev);
++}
++
++static const struct dev_pm_ops imx363_pm_ops = {
++ SET_RUNTIME_PM_OPS(imx363_power_off, imx363_power_on, NULL)
++};
++
++#ifdef CONFIG_ACPI
++static const struct acpi_device_id imx363_acpi_ids[] = {
++ { "SONY363A" },
++ { /* sentinel */ }
++};
++
++MODULE_DEVICE_TABLE(acpi, imx363_acpi_ids);
++#endif
++
++static const struct of_device_id imx363_dt_ids[] = {
++ { .compatible = "sony,imx363"},
++ { /* sentinel */ }
++};
++MODULE_DEVICE_TABLE(of, imx363_dt_ids);
++
++static struct i2c_driver imx363_i2c_driver = {
++ .driver = {
++ .name = "imx363",
++ .pm = &imx363_pm_ops,
++ .acpi_match_table = ACPI_PTR(imx363_acpi_ids),
++ .of_match_table = imx363_dt_ids,
++ },
++ .probe = imx363_probe,
++ .remove = imx363_remove,
++};
++
++module_i2c_driver(imx363_i2c_driver);
++
++MODULE_AUTHOR("Yeh, Andy ");
++MODULE_AUTHOR("Chiang, Alan");
++MODULE_AUTHOR("Chen, Jason");
++MODULE_DESCRIPTION("Sony IMX363 sensor driver");
++MODULE_LICENSE("GPL");
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0032-platina-rear-camera.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0032-platina-rear-camera.patch
new file mode 100644
index 0000000..4f6ba43
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0032-platina-rear-camera.patch
@@ -0,0 +1,82 @@
+From: Platina Linux contributors
+Subject: [PATCH] arm64: dts: qcom: platina: wire the rear IMX363 camera
+
+Wiring from Xiaomi platina-o-oss 0bb2780bccb9c7e05f0edf5db8860e779179b5f9,
+platina-camera-sensor.dtsi (GPL-2.0-only). Rear slot: CCI0, reset GPIO46,
+MCLK0 24MHz, CSIPHY0; stock camera config uses lane mask 0x1f/map 0x4320.
+Both Sunny and Ofilm sensor descriptors specify 8-bit address 0x20,
+ID register 0x0016, ID 0x0363. No front/aux camera, flash or lens actuator.
+Stock CSID v3.5/v5.0 remaps lane numbers through {0,4,1,2,3}:
+0x4320 becomes hardware 0x3210. Mainline therefore needs data-lanes 0,1,2,3;
+its fixed PHY clock lane is not exposed in DT.
+Existing board-specific camera supply gates are preserved. CAMSS CSID
+supplies map to PM660 L1 and PM660L L1 per stock sdm660-camera.dtsi.
+
+--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
++++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+@@ -303,6 +303,65 @@
+ };
+ };
+
++
++/* Rear main camera: stock platina camera slot 0, CCI master 0, CSIPHY 0. */
++&camss {
++ vdda-supply = <&vreg_l1a_1p225>;
++ vdd_sec-supply = <&vreg_l1b_0p925>;
++ power-domains = <&mmcc CAMSS_VFE0_GDSC>,
++ <&mmcc CAMSS_VFE1_GDSC>,
++ <&mmcc CAMSS_TOP_GDSC>;
++ status = "okay";
++
++ ports {
++ port@0 {
++ reg = <0>;
++ platina_csiphy0_ep: endpoint {
++ data-lanes = <0 1 2 3>;
++ remote-endpoint = <&platina_imx363_ep>;
++ };
++ };
++ };
++};
++
++&cci {
++ status = "okay";
++ pinctrl-0 = <&cci0_default>;
++};
++
++&cci_i2c0 {
++ status = "okay";
++
++ camera@10 {
++ compatible = "sony,imx363";
++ reg = <0x10>;
++ reset-gpios = <&tlmm 46 GPIO_ACTIVE_LOW>;
++ pinctrl-names = "default";
++ pinctrl-0 = <&camera_rear_default>;
++ clocks = <&mmcc CAMSS_MCLK0_CLK>;
++ clock-names = "xvclk";
++ clock-frequency = <24000000>;
++ vana-supply = <&cam_avdd_rear_vreg>;
++ vdig-supply = <&cam_dvdd_rear_vreg>;
++ vif-supply = <&vreg_l14a_1p8>;
++ orientation = <1>;
++ rotation = <90>;
++
++ port {
++ platina_imx363_ep: endpoint {
++ clock-lanes = <0>;
++ data-lanes = <1 2 3 4>;
++ link-frequencies = /bits/ 64 <636000000 340000000>;
++ remote-endpoint = <&platina_csiphy0_ep>;
++ };
++ };
++ };
++};
++
++&cci_i2c1 {
++ status = "disabled";
++};
++
+ &blsp1_uart2 {
+ status = "okay";
+ };
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0033-camss-sdm660-ispif.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0033-camss-sdm660-ispif.patch
new file mode 100644
index 0000000..f9917e0
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0033-camss-sdm660-ispif.patch
@@ -0,0 +1,35 @@
+From: Platina Linux contributors
+Subject: [PATCH] media: qcom: camss: restore SDM660 ISPIF and CSI mux
+
+The SDM660 resource table provides ISPIF and camss-ispif.c already handles
+CAMSS_660, but camss_probe() omits this version from allocation. The null
+ISPIF silently creates a direct CSID -> VFE graph which does not match the
+hardware. Include SDM660 in the existing ISPIF allocation condition.
+Observed on Platina: sensor identity succeeds, direct graph never delivers
+SOF and times out. This change restores the hardware path, not a bypass. Map the existing
+SDM660 CSIPHY clock-mux resource as on the other legacy ISPIF platforms.
+
+--- a/drivers/media/platform/qcom/camss/camss.c
++++ b/drivers/media/platform/qcom/camss/camss.c
+@@ -5388,7 +5388,8 @@
+ if (camss->res->version == CAMSS_8x16 ||
+ camss->res->version == CAMSS_8x39 ||
+ camss->res->version == CAMSS_8x53 ||
+- camss->res->version == CAMSS_8x96) {
++ camss->res->version == CAMSS_8x96 ||
++ camss->res->version == CAMSS_660) {
+ camss->ispif = devm_kcalloc(dev, 1, sizeof(*camss->ispif), GFP_KERNEL);
+ if (!camss->ispif)
+ return -ENOMEM;
+--- a/drivers/media/platform/qcom/camss/camss-csiphy.c
++++ b/drivers/media/platform/qcom/camss/camss-csiphy.c
+@@ -606,7 +606,8 @@
+ if (camss->res->version == CAMSS_8x16 ||
+ camss->res->version == CAMSS_8x39 ||
+ camss->res->version == CAMSS_8x53 ||
+- camss->res->version == CAMSS_8x96) {
++ camss->res->version == CAMSS_8x96 ||
++ camss->res->version == CAMSS_660) {
+ csiphy->base_clk_mux =
+ devm_platform_ioremap_resource_byname(pdev, res->reg[1]);
+ if (IS_ERR(csiphy->base_clk_mux))
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0034-camss-sdm660-ispif-power-votes.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0034-camss-sdm660-ispif-power-votes.patch
new file mode 100644
index 0000000..356d943
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0034-camss-sdm660-ispif-power-votes.patch
@@ -0,0 +1,75 @@
+From: Platina Linux contributors
+Subject: [PATCH] media: qcom: camss: separate SDM660 ISPIF reset power votes
+
+ISPIF reset and VFE streaming both call the VFE power-domain helpers.
+Those helpers use a single genpd_link pointer; a nested reset drops and
+clears it, then stream teardown calls device_link_del(NULL). Observed
+on Platina r4 after a bounded no-frame capture test, with an Oops at
+vfe_pm_domain_off/device_link_put_kref.
+
+Use balanced runtime-PM votes on the attached genpd devices for SDM660
+ISPIF reset, keeping the stream-owned links intact. Unwind successful
+votes on second-domain or reset-clock enable failure. Other platform
+power-vote implementations are unchanged.
+
+--- a/drivers/media/platform/qcom/camss/camss.c
++++ b/drivers/media/platform/qcom/camss/camss.c
+@@ -4675,7 +4675,13 @@
+ if (id < camss->res->vfe_num) {
+ struct vfe_device *vfe = &camss->vfe[id];
+
+- ret = vfe->res->hw_ops->pm_domain_on(vfe);
++ /* ISPIF reset temporarily votes for both VFEs. Do not reuse the
++ * stream's genpd_link: nested reset would clear that live pointer.
++ */
++ if (camss->res->version == CAMSS_660)
++ ret = vfe->genpd ? pm_runtime_resume_and_get(vfe->genpd) : 0;
++ else
++ ret = vfe->res->hw_ops->pm_domain_on(vfe);
+ }
+
+ return ret;
+@@ -4686,7 +4692,12 @@
+ if (id < camss->res->vfe_num) {
+ struct vfe_device *vfe = &camss->vfe[id];
+
+- vfe->res->hw_ops->pm_domain_off(vfe);
++ if (camss->res->version == CAMSS_660) {
++ if (vfe->genpd)
++ pm_runtime_put_sync(vfe->genpd);
++ } else {
++ vfe->res->hw_ops->pm_domain_off(vfe);
++ }
+ }
+ }
+
+--- a/drivers/media/platform/qcom/camss/camss-ispif.c
++++ b/drivers/media/platform/qcom/camss/camss-ispif.c
+@@ -329,13 +329,13 @@
+
+ ret = camss_pm_domain_on(camss, PM_DOMAIN_VFE1);
+ if (ret < 0)
+- return ret;
++ goto domain0_off;
+
+ ret = camss_enable_clocks(ispif->nclocks_for_reset,
+ ispif->clock_for_reset,
+ camss->dev);
+ if (ret < 0)
+- return ret;
++ goto domain1_off;
+
+ ret = ispif_vfe_reset(ispif, vfe_id);
+ if (ret)
+@@ -343,8 +343,10 @@
+
+ camss_disable_clocks(ispif->nclocks_for_reset, ispif->clock_for_reset);
+
++domain1_off:
++ camss_pm_domain_off(camss, PM_DOMAIN_VFE1);
++domain0_off:
+ camss_pm_domain_off(camss, PM_DOMAIN_VFE0);
+- camss_pm_domain_off(camss, PM_DOMAIN_VFE1);
+
+ return ret;
+ }
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0035-camss-sdm660-phy-clock-rates.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0035-camss-sdm660-phy-clock-rates.patch
new file mode 100644
index 0000000..ae18c62
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0035-camss-sdm660-phy-clock-rates.patch
@@ -0,0 +1,43 @@
+From: Platina Linux contributors
+Subject: [PATCH] media: qcom: camss: provide SDM660 PHY clock rate tables
+
+SDM660 requires csiX_phy >= csiphyX_timer. The selection logic is present
+but skips csiX_phy because its resource clock_rate table contains only 0.
+Observed during a real Platina IMX363 stream: timer 100MHz, csi0_phy 19.2MHz;
+the sensor frame counter increments, and CSID internal testgen reaches RAM,
+but external sensor data produces no VFE SOF. Give the PHY the same existing
+supported levels as its timer so the intended selection logic runs.
+
+Reference: AngeloGioacchino Del Regno, tested Sony Xperia XA2 SDM630 series,
+https://lkml.iu.edu/2010.2/01479.html
+This restores the requirement from the original SDM630/660 CAMSS port.
+
+--- a/drivers/media/platform/qcom/camss/camss.c
++++ b/drivers/media/platform/qcom/camss/camss.c
+@@ -830,7 +830,7 @@
+ { 0 },
+ { 0 },
+ { 100000000, 200000000, 269333333 },
+- { 0 } },
++ { 100000000, 200000000, 269333333 } },
+ .reg = { "csiphy0", "csiphy0_clk_mux" },
+ .interrupt = { "csiphy0" },
+ .csiphy = {
+@@ -849,7 +849,7 @@
+ { 0 },
+ { 0 },
+ { 100000000, 200000000, 269333333 },
+- { 0 } },
++ { 100000000, 200000000, 269333333 } },
+ .reg = { "csiphy1", "csiphy1_clk_mux" },
+ .interrupt = { "csiphy1" },
+ .csiphy = {
+@@ -868,7 +868,7 @@
+ { 0 },
+ { 0 },
+ { 100000000, 200000000, 269333333 },
+- { 0 } },
++ { 100000000, 200000000, 269333333 } },
+ .reg = { "csiphy2", "csiphy2_clk_mux" },
+ .interrupt = { "csiphy2" },
+ .csiphy = {
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0036-platina-rear-focus.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0036-platina-rear-focus.patch
new file mode 100644
index 0000000..2b66ec8
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0036-platina-rear-focus.patch
@@ -0,0 +1,26 @@
+From: Platina Linux contributors
+Subject: [PATCH] arm64: dts: qcom: platina: connect rear DW9714 lens
+
+Stock camera_config.xml selects platina_dw9714_sunny/ofilm for IMX363.
+Both actuator descriptors use 8-bit address 0x18 (7-bit 0x0c).
+Reuse the existing board actuator regulator (TLMM50, 3.6V) and the
+upstream DW9714 driver. No flash, auxiliary camera or arbitrary probing.
+
+--- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
++++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts
+@@ -332,8 +332,15 @@
+ &cci_i2c0 {
+ status = "okay";
+
++ cam_rear_focus: lens@c {
++ compatible = "dongwoon,dw9714";
++ reg = <0x0c>;
++ vcc-supply = <&cam_actuator_rear_vreg>;
++ };
++
+ camera@10 {
+ compatible = "sony,imx363";
++ lens-focus = <&cam_rear_focus>;
+ reg = <0x10>;
+ reset-gpios = <&tlmm 46 GPIO_ACTIVE_LOW>;
+ pinctrl-names = "default";
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0037-imx363-full-field-binning.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0037-imx363-full-field-binning.patch
new file mode 100644
index 0000000..9d09b87
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0037-imx363-full-field-binning.patch
@@ -0,0 +1,116 @@
+From: Platina Linux contributors
+Subject: [PATCH] media: imx363: replace broken HD mode with stock 2x2 timing
+
+Use the complete four-lane clock/readout timing for a 2016x1512 full-field
+2x2 mode rather than the imported 1080p mode. This is the geometry and
+clock tuple of the stock Platina main sensor: binning 0x22, line 3144,
+frame 2968, VT 280MHz and MIPI link 340MHz. Internal readout timing is at
+0x30f4..0x30f7, not 0x31f4..0x31f7. The earlier r9 candidate's incomplete
+clock/readout tuple produced a grid and cropped field; it was rejected.
+Only this four-lane mode is validated on Platina; the unused two-lane
+clock table is inherited and untested. Full-resolution mode is preserved.
+Related upstream report: https://gitlab.com/sdm845-mainline/linux/-/merge_requests/104
+
+--- a/drivers/media/i2c/imx363.c
++++ b/drivers/media/i2c/imx363.c
+@@ -222,21 +222,19 @@
+ { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_L, 0 },
+ };
+
++/* Four-lane 2016x1512 stock timing: VT 280MHz, link 340MHz. */
+ static const struct cci_reg_sequence mipi_642mbps_24mhz_4l[] = {
+ { IMX363_REG_EXCK_FREQ, 0x1800 },
+- { IMX363_REG_IVTPXCK_DIV, 5 },
++ { IMX363_REG_IVTPXCK_DIV, 3 },
+ { IMX363_REG_IVTSYCK_DIV, 2 },
+ { IMX363_REG_PREPLLCK_VT_DIV, 4 },
+- { IMX363_REG_PLL_IVT_MPY, 107 },
++ { IMX363_REG_PLL_IVT_MPY, 70 },
+ { IMX363_REG_IOPPXCK_DIV, 10 },
+- { IMX363_REG_IOPSYCK_DIV, 1 },
+- { IMX363_REG_PREPLLCK_OP_DIV, 2 },
+- { IMX363_REG_PLL_IOP_MPY, 216 },
+- { IMX363_REG_PLL_MULT_DRIV, 0 },
+-
++ { IMX363_REG_IOPSYCK_DIV, 2 },
++ { IMX363_REG_PREPLLCK_OP_DIV, 3 },
++ { IMX363_REG_PLL_IOP_MPY, 170 },
++ { IMX363_REG_PLL_MULT_DRIV, 1 },
+ { IMX363_REG_CSI_LANE_MODE, 3 },
+- { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_H, 642 * 4 },
+- { IMX363_REG_REQ_LINK_BIT_RATE_MBPS_L, 0 },
+ };
+
+ static const struct cci_reg_sequence mode_common_regs[] = {
+@@ -422,9 +420,9 @@
+ {CCI_REG8(0x0227), 0x00},
+ };
+
+-static const struct cci_reg_sequence mode_1920_1080_regs[] = {
++static const struct cci_reg_sequence mode_2016_1512_regs[] = {
+ {IMX363_REG_BINNING_MODE, 1},
+- {IMX363_REG_BINNING_TYPE_V, 0x42},
++ {IMX363_REG_BINNING_TYPE_V, 0x22},
+ // {IMX363_REG_SCALE_MODE, 1},
+ // {IMX363_REG_SCALE_M, 64},
+ {IMX363_REG_X_ADD_STA, 0}, // analog cropping
+@@ -437,11 +435,16 @@
+ {IMX363_REG_Y_ODD_INC, 1},
+ {IMX363_REG_DIG_CROP_X_OFFSET, 0}, // digital cropping
+ {IMX363_REG_DIG_CROP_Y_OFFSET, 0},
+- {IMX363_REG_DIG_CROP_IMAGE_WIDTH, 1920},
+- {IMX363_REG_DIG_CROP_IMAGE_HEIGHT, 1080},
+- {IMX363_REG_X_OUT_SIZE, 1920},
+- {IMX363_REG_Y_OUT_SIZE, 1080},
+- {IMX363_REG_FRM_LENGTH_LINES, IMX363_VTS_30FPS_HD},
++ {IMX363_REG_DIG_CROP_IMAGE_WIDTH, 2016},
++ {IMX363_REG_DIG_CROP_IMAGE_HEIGHT, 1512},
++ {IMX363_REG_X_OUT_SIZE, 2016},
++ {IMX363_REG_Y_OUT_SIZE, 1512},
++ {IMX363_REG_FRM_LENGTH_LINES, 2968},
++ {IMX363_REG_LINE_LENGTH_PCK, 3144},
++ {CCI_REG8(0x30f4), 0x02},
++ {CCI_REG8(0x30f5), 0x58},
++ {CCI_REG8(0x30f6), 0x00},
++ {CCI_REG8(0x30f7), 0x14},
+ };
+
+ /*
+@@ -515,7 +518,7 @@
+
+ static const s64 link_freq_menu_items_24[] = {
+ 636000000ULL, // NOT SURE HOW TO FIND THIS VALUE
+- 321000000ULL,
++ 340000000ULL,
+ };
+
+ #define REGS(_list) { .num_of_regs = ARRAY_SIZE(_list), .regs = _list, }
+@@ -535,7 +538,7 @@
+ }
+ },
+ [IMX363_LINK_FREQ_640MBPS] = {
+- .pixels_per_line = IMX363_PPL_DEFAULT,
++ .pixels_per_line = 3144,
+ .link_cfg = {
+ [IMX363_2_LANE_MODE] = {
+ .lf_to_pix_rate_factor = 2 * 2,
+@@ -569,13 +572,13 @@
+ },
+ },
+ {
+- .width = 1920,
+- .height = 1080,
+- .vts_def = IMX363_VTS_30FPS_HD,
+- .vts_min = IMX363_VTS_30FPS_HD,
++ .width = 2016,
++ .height = 1512,
++ .vts_def = 2968,
++ .vts_min = 2968,
+ .reg_list = {
+- .num_of_regs = ARRAY_SIZE(mode_1920_1080_regs),
+- .regs = mode_1920_1080_regs,
++ .num_of_regs = ARRAY_SIZE(mode_2016_1512_regs),
++ .regs = mode_2016_1512_regs,
+ },
+ .link_freq_index = IMX363_LINK_FREQ_640MBPS,
+ .crop = {
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0038-imx363-platina-legacy-frequency.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0038-imx363-platina-legacy-frequency.patch
new file mode 100644
index 0000000..5033f1f
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0038-imx363-platina-legacy-frequency.patch
@@ -0,0 +1,36 @@
+From: Platina Linux contributors
+Subject: [PATCH] media: imx363: accept the older Platina link frequency spelling
+
+Older Platina camera DTs advertised the experimental 321MHz four-lane
+mode. Interpret that value as the corrected 340MHz clock tuple, only on
+Xiaomi Platina with a 24MHz external clock and four data lanes. This
+permits a backed-up camera-module-only test on the running camera kernel,
+without writing the boot partition or interrupting charger operation.
+The local endpoint copy is changed; the live device tree is untouched.
+
+--- a/drivers/media/i2c/imx363.c
++++ b/drivers/media/i2c/imx363.c
+@@ -6,6 +6,7 @@
+ #include
+ #include
+ #include
++#include
+ #include
+ #include
+ #include
+@@ -1368,6 +1369,15 @@
+ return ret;
+ }
+
++ if (of_machine_is_compatible("xiaomi,platina") &&
++ clk_get_rate(imx363->clk) == 24000000 &&
++ ep.bus.mipi_csi2.num_data_lanes == 4) {
++ unsigned int i;
++
++ for (i = 0; i < ep.nr_of_link_frequencies; i++)
++ if (ep.link_frequencies[i] == 321000000)
++ ep.link_frequencies[i] = 340000000;
++ }
+ ret = v4l2_link_freq_to_bitmap(&client->dev,
+ ep.link_frequencies,
+ ep.nr_of_link_frequencies,
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0039-venus-legacy-h264-transform.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0039-venus-legacy-h264-transform.patch
new file mode 100644
index 0000000..124ba39
--- /dev/null
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0039-venus-legacy-h264-transform.patch
@@ -0,0 +1,30 @@
+--- a/drivers/media/platform/qcom/venus/venc.c
++++ b/drivers/media/platform/qcom/venus/venc.c
+@@ -723,15 +723,18 @@
+ if (ret)
+ return ret;
+
+- ptype = HFI_PROPERTY_PARAM_VENC_H264_TRANSFORM_8X8;
+- h264_transform.enable_type = 0;
+- if (ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_HIGH ||
+- ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH)
+- h264_transform.enable_type = ctr->h264_8x8_transform;
+-
+- ret = hfi_session_set_property(inst, ptype, &h264_transform);
+- if (ret)
+- return ret;
++ /* This command is implemented by the 4xx/6xx packetizers only. */
++ if (IS_V4(inst->core) || IS_V6(inst->core)) {
++ ptype = HFI_PROPERTY_PARAM_VENC_H264_TRANSFORM_8X8;
++ h264_transform.enable_type = 0;
++ if (ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_HIGH ||
++ ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH)
++ h264_transform.enable_type = ctr->h264_8x8_transform;
++
++ ret = hfi_session_set_property(inst, ptype, &h264_transform);
++ if (ret)
++ return ret;
++ }
+
+ if (ctr->layer_bitrate) {
+ unsigned int i;
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD
index f328511..eac423e 100644
--- a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD
@@ -3,7 +3,7 @@ maintainer="Alexey Minnekhanov "
_flavor="postmarketos-qcom-sdm660"
pkgname=linux-$_flavor
pkgver=7.2.12
-pkgrel=1
+pkgrel=12
pkgdesc="Close to mainline linux kernel for Qualcomm Snapdragon 660 SoC"
arch="aarch64"
url="https://kernel.org/"
@@ -26,6 +26,7 @@ makedepends="
zstd
pahole
linux-headers
+ kmod
elfutils-dev
"
@@ -57,6 +58,15 @@ source="
0028-platina-touch-regulator-cleanup.patch
0029-sdm660-mdp-clock-safe-rate-change.patch
0030-platina-tianma-panel.patch
+ 0031-media-i2c-imx363.patch
+ 0032-platina-rear-camera.patch
+ 0033-camss-sdm660-ispif.patch
+ 0034-camss-sdm660-ispif-power-votes.patch
+ 0035-camss-sdm660-phy-clock-rates.patch
+ 0036-platina-rear-focus.patch
+ 0037-imx363-full-field-binning.patch
+ 0038-imx363-platina-legacy-frequency.patch
+ 0039-venus-legacy-h264-transform.patch
stable-7.2.3-4.patch
stable-7.2.4-5.patch
stable-7.2.5-6.patch
@@ -119,7 +129,7 @@ package() {
}
sha512sums="
b56636f4d7429e971a70c1b7237fda4d5795fbe422c01f6fc6038220c2e831bf4479bd411b5e04e4db45de4fb8ec15a9e0e312b6479e2067709062af3dfd6997 linux-dd1ed52c8ceef4f16715118ed0252fe75adbe71d.tar.gz
-2a21ce86163c1f33d2fc8bf1d84823c4c6221f67abdcb32e7a11f27325eb5dc7ffc968bc56d15b469aa5aa4b8381ba077e6abe018bd69a69049124e331228304 config-postmarketos-qcom-sdm660.aarch64
+25f1d9cd84243a011d14a25b55f76857522ebc2b7c4ccea36dea59e8f8aa36d27069daf6ee57292c9800fb4eabcfc0c8767fb0c98f045b40dd2f81ace632e859 config-postmarketos-qcom-sdm660.aarch64
0ed47ad2e1cf773a49ab542b4f6ccc2baf61a4186e51cda8f70bacce6c30c687305f8c7f327cdd9b3919358ca18eaac28c7c9b82bfec73e5fe492663afdec825 0001-platina-enable-display.patch
83b9efa9b1a46499d1936f9e3f90b832458ace687a5ad3892ae1787a09997491efb9cc1bb0db44007adda97900ae2e3ce1b7dafa28ecb4cd84a95ade8667f05b 0002-panel-simple-td4320.patch
2ff1034abfbaf3c5bf56233b46a6c5a066015a982d4e55e5fd34c5d908d145305c7a99fd7731057b8fd5b9afc3e595b60856f6e0a0af921cfbff068eb744757b 0004-synaptics-tcm-driver.patch
@@ -143,6 +153,15 @@ ae97edcc2302b088a3d83539139199e9f5a19c3a11f66a3512b979b93673755f300b6458f7ddfaaa
c04261993d81ae94ae8f6e86df93e6e37390fd8b7746f8d54eaf957e818cdf92691fdeb8b9a5adae220fcd199189aea268c837b6482e13a70a9de9aeaafaacc5 0028-platina-touch-regulator-cleanup.patch
07f552abed2177d7c0a4fd731692c934d54f8ad4d117ecad3e1eab4ceedd546b07c6fc01c693dae65a09fc1581b987db4bb7f3cdffa4488b20919a32a1790621 0029-sdm660-mdp-clock-safe-rate-change.patch
e845d83a8bb8e7bb7cc59bb309b78b920460f4d31b9c962e00119321e3f01a65bfcc2cc3185d609a0b99a73c9deed5d705d58afdf06d8dac2e409ad15f821d68 0030-platina-tianma-panel.patch
+812f71e8752570036ed74c06c5ad28a84269a6ed137335d51af887a7084c20bb9aa533603c771afd12b11867b2d65cee9300ad13e8c68bb33b2fd0668a2236cb 0031-media-i2c-imx363.patch
+11cbf744686f28317e44cbebf48bbde98d287f818e447a26417d7246dad959228b4c62233914ffd13af6cb77d867af060eea3755a873484008f17ef8a8626fbc 0032-platina-rear-camera.patch
+cf94af7b03cff9d08bc2b581f7bbc8bf3bc1f1b1a826f5715c1853b2a7ad856beacce07ce442586ba67b43ca2a6fbac6479a985a0033c65f808ef42d7d63d9e2 0033-camss-sdm660-ispif.patch
+73d684cc1e21454f9b065930ee93a3edfc61154f0765c457f26afb23df18b2261ace202c4b34754d175434e8f258f1d234ae11c8c80cb7c6c22c500ed174ec87 0034-camss-sdm660-ispif-power-votes.patch
+c2930b7daca8ccc6af37232fff7395cbbb8062aa413554aa7a6aa17f83480cc6d554b5941e22ee958426a2ced9a223037bdd945c0658abdc13b4da55d7ff88c8 0035-camss-sdm660-phy-clock-rates.patch
+ecfee5c3fde9c5342195d5e25f7103d909144d9602497aa4de713fc55d9c03f89601081535d43da74002d147295f554f445c6ccb74813a1cce8de71d48df800a 0036-platina-rear-focus.patch
+62031fc20f13bec1bc9a0a67134a2967acbf76cd2d9d3eea9cf5d8176d5bbe61e0063b165b9caf959ec8d923fbb8897cb7421c723d38d695da51a2cb3eddf6c2 0037-imx363-full-field-binning.patch
+b1094708de883b3aecaf52ddc7f9315c150f6234165ab02ef7a021bc18da4d56cc5eab0f9239583a3b596c307ef71b891f0d735d889156e783b7bb21ba26b448 0038-imx363-platina-legacy-frequency.patch
+61a598e63d83c0489ba130231cd0a4c2dc4351de5c122cef9b7170f7f516bae7573c744535035c53e2642a96d13fe5048c07e4c908de8f64c90a3cd8809ee84c 0039-venus-legacy-h264-transform.patch
1a7f9cf2443c0f059ac64a78dddee77fca584288edeea943aa45db05fb5e3b7b2930dab595f6c0911671bf5517bd64550a65b097f47d5179cc7454ec90db56cd stable-7.2.3-4.patch
303d4a717c67d5dbb5d17c37882b3ef1b6b44b3cf9b17723a611efe1f028019d5ef53c0e3595ed79f5468a46ede2d640171b9dd97ce2dd99b487d0406ef79f16 stable-7.2.4-5.patch
b09a94d0eb3c0382ad8998843019ea0d52ae5a89ad7ba54072b21eeea2c7ee602c57a32a0d9b99a2c5ae1f581dadc4d4395096e905b54678affc18125d9b8cba stable-7.2.5-6.patch
diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/config-postmarketos-qcom-sdm660.aarch64 b/ports/candidate/linux-postmarketos-qcom-sdm660/config-postmarketos-qcom-sdm660.aarch64
index 145ae47..e8ff9a0 100644
--- a/ports/candidate/linux-postmarketos-qcom-sdm660/config-postmarketos-qcom-sdm660.aarch64
+++ b/ports/candidate/linux-postmarketos-qcom-sdm660/config-postmarketos-qcom-sdm660.aarch64
@@ -2671,7 +2671,7 @@ CONFIG_I2C_GPIO=y
# CONFIG_I2C_NOMADIK is not set
# CONFIG_I2C_OCORES is not set
# CONFIG_I2C_PCA_PLATFORM is not set
-# CONFIG_I2C_QCOM_CCI is not set
+CONFIG_I2C_QCOM_CCI=m
# CONFIG_I2C_QCOM_GENI is not set
CONFIG_I2C_QUP=y
# CONFIG_I2C_RK3X is not set
@@ -3573,6 +3573,8 @@ CONFIG_MEDIA_CONTROLLER=y
#
CONFIG_VIDEO_V4L2_I2C=y
CONFIG_VIDEO_V4L2_SUBDEV_API=y
+CONFIG_V4L2_CCI=m
+CONFIG_V4L2_CCI_I2C=m
# CONFIG_VIDEO_ADV_DEBUG is not set
# CONFIG_VIDEO_FIXED_MINOR_RANGES is not set
CONFIG_V4L2_MEM2MEM_DEV=m
@@ -3752,6 +3754,7 @@ CONFIG_VIDEO_CAMERA_SENSOR=y
# CONFIG_VIDEO_IMX334 is not set
# CONFIG_VIDEO_IMX335 is not set
# CONFIG_VIDEO_IMX355 is not set
+CONFIG_VIDEO_IMX363=m
# CONFIG_VIDEO_IMX412 is not set
# CONFIG_VIDEO_IMX415 is not set
# CONFIG_VIDEO_MT9M001 is not set
@@ -3824,7 +3827,7 @@ CONFIG_VIDEO_CAMERA_SENSOR=y
CONFIG_VIDEO_CAMERA_LENS=y
# CONFIG_VIDEO_AD5820 is not set
# CONFIG_VIDEO_AK7375 is not set
-# CONFIG_VIDEO_DW9714 is not set
+CONFIG_VIDEO_DW9714=m
# CONFIG_VIDEO_DW9719 is not set
# CONFIG_VIDEO_DW9768 is not set
# CONFIG_VIDEO_DW9807_VCM is not set
diff --git a/project/camera/libcamera-headless/0001-imx363-properties.patch b/project/camera/libcamera-headless/0001-imx363-properties.patch
new file mode 100644
index 0000000..b05254b
--- /dev/null
+++ b/project/camera/libcamera-headless/0001-imx363-properties.patch
@@ -0,0 +1,56 @@
+From: Samuel LEGROS
+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
+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 = {},
diff --git a/project/camera/libcamera-headless/0002-simple-manual-white-balance.patch b/project/camera/libcamera-headless/0002-simple-manual-white-balance.patch
new file mode 100644
index 0000000..5a703a8
--- /dev/null
+++ b/project/camera/libcamera-headless/0002-simple-manual-white-balance.patch
@@ -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{ { 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 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(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;
diff --git a/project/camera/libcamera-headless/0003-platina-full-field-gpu-scale.patch b/project/camera/libcamera-headless/0003-platina-full-field-gpu-scale.patch
new file mode 100644
index 0000000..7846e77
--- /dev/null
+++ b/project/camera/libcamera-headless/0003-platina-full-field-gpu-scale.patch
@@ -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);
+
diff --git a/project/camera/libcamera-headless/0004-overlap-gpu-statistics.patch b/project/camera/libcamera-headless/0004-overlap-gpu-statistics.patch
new file mode 100644
index 0000000..3c27299
--- /dev/null
+++ b/project/camera/libcamera-headless/0004-overlap-gpu-statistics.patch
@@ -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);
diff --git a/project/camera/libcamera-headless/0005-platina-gpu-profile-dmabuf.patch b/project/camera/libcamera-headless/0005-platina-gpu-profile-dmabuf.patch
new file mode 100644
index 0000000..b2e075f
--- /dev/null
+++ b/project/camera/libcamera-headless/0005-platina-gpu-profile-dmabuf.patch
@@ -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
++#include
+ #include
+ #include
+
+@@ -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(b - a).count();
++}
++
+
+ /**
+ * \class DebayerEGL
+@@ -36,6 +44,8 @@
+ DebayerEGL::DebayerEGL(std::unique_ptr 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 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(width_, height_, inputConfig_.stride, GL_TEXTURE0, 0);
++ eglImageBayerIn_ = std::make_unique(inputConfig_.stride / bytesPerPixel_, height_, inputConfig_.stride, GL_TEXTURE0, 0);
+
+ /* Texture we will render to */
+ eglImageBayerOut_ = std::make_unique(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_;
diff --git a/project/camera/libcamera-headless/0006-platina-gpu-rotation-saturation.patch b/project/camera/libcamera-headless/0006-platina-gpu-rotation-saturation.patch
new file mode 100644
index 0000000..edc91c8
--- /dev/null
+++ b/project/camera/libcamera-headless/0006-platina-gpu-rotation-saturation.patch
@@ -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
+ #include
++#include
+ #include
+ #include
+
+@@ -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);
diff --git a/project/camera/libcamera-headless/0011-simple-manual-exposure.patch b/project/camera/libcamera-headless/0011-simple-manual-exposure.patch
new file mode 100644
index 0000000..344c3b0
--- /dev/null
+++ b/project/camera/libcamera-headless/0011-simple-manual-exposure.patch
@@ -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());
+ 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(), 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
+
+ #include "core_ipa_interface.h"
++#include "algorithms/platina_exposure.h"
+
+ namespace libcamera {
+
+@@ -64,6 +65,7 @@
+ };
+
+ struct IPAFrameContext : public FrameContext {
++ platina::ExposureSettings exposureControl;
+ Matrix ccm;
+
+ struct {
diff --git a/project/camera/libcamera-headless/0012-platina-gpu-zoom.patch b/project/camera/libcamera-headless/0012-platina-gpu-zoom.patch
new file mode 100644
index 0000000..df7adf3
--- /dev/null
+++ b/project/camera/libcamera-headless/0012-platina-gpu-zoom.patch
@@ -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
+ #include
+ #include
++#include "platina_zoom.h"
+ #include
+ #include
+
+@@ -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 */
diff --git a/project/camera/libcamera-headless/APKBUILD b/project/camera/libcamera-headless/APKBUILD
new file mode 100644
index 0000000..661e348
--- /dev/null
+++ b/project/camera/libcamera-headless/APKBUILD
@@ -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
+"
diff --git a/project/camera/libcamera-headless/camera_mqtt.py b/project/camera/libcamera-headless/camera_mqtt.py
new file mode 100644
index 0000000..084aeef
--- /dev/null
+++ b/project/camera/libcamera-headless/camera_mqtt.py
@@ -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()
diff --git a/project/camera/libcamera-headless/capture.cpp b/project/camera/libcamera-headless/capture.cpp
new file mode 100644
index 0000000..bf94440
--- /dev/null
+++ b/project/camera/libcamera-headless/capture.cpp
@@ -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
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include