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. [![Source checks](https://github.com/Sukecz/platina-linux/actions/workflows/check.yml/badge.svg)](https://github.com/Sukecz/platina-linux/actions/workflows/check.yml) [![License: GPL v2](https://img.shields.io/badge/License-GPL_v2-blue.svg)](LICENSE) [![Device: Xiaomi Mi 8 Lite](https://img.shields.io/badge/device-Xiaomi_Mi_8_Lite-ff6900)](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 +#include +#include +#include +#include +#include +#include "platina_exposure.h" +#include "platina_zoom.h" + +using Clock = std::chrono::steady_clock; +static std::atomic stopping{false}; +static_assert(std::atomic::is_always_lock_free); +static void stop(int) { stopping = true; } +static int64_t monotonicNs() { + return std::chrono::duration_cast(Clock::now().time_since_epoch()).count(); +} +struct Settings { + float gamma = 2.2f, contrast = 1.0f, saturation = 1.0f, red = 1.0f, blue = 1.0f; + float scale = 2.0f; + int automatic = 1, rotation = 90, quality = 50, fps = 30; + int exposureAuto = 1, exposureUs = 10000; + float analogueGain = 1.0f; + float zoom = 1.0f; +}; +class Capture { +public: + std::shared_ptr camera; + libcamera::Stream *stream = nullptr; + unsigned width = 0, height = 0, stride = 0; + double ispScale = 1; + int ispRotation = 0; + bool ispSaturation = false; + bool ispZoom = false; + unsigned inFlight = 0, maxInFlight = 1; + struct EncoderBuffers { std::vector scaled, rotated, colored, packed; }; + std::mutex publishMutex; + int64_t lastPublished = 0; + Clock::time_point fpsStarted = Clock::now(); + unsigned fpsFrames = 0; + double recentFps = 0; + std::string output; + Settings defaults; + struct Mapping { void *base; size_t size; uint8_t *pixels; }; + std::map maps; + std::mutex mutex; + std::condition_variable changed; + std::deque ready; + libcamera::Request *latest = nullptr; + std::atomic captured{0}, encoded{0}; + std::vector encoders; + Clock::time_point started = Clock::now(); + + Settings settings() const { + Settings s = defaults; + std::ifstream file(output + ".controls"); + Settings candidate; + if (file >> candidate.gamma >> candidate.contrast >> candidate.saturation >> + candidate.automatic >> candidate.red >> candidate.blue >> candidate.rotation >> + candidate.scale >> candidate.quality >> candidate.fps >> + candidate.exposureAuto >> candidate.exposureUs >> candidate.analogueGain >> candidate.zoom) { + if (std::isfinite(candidate.gamma) && candidate.gamma >= .5f && candidate.gamma <= 4 && + std::isfinite(candidate.contrast) && candidate.contrast >= .5f && candidate.contrast <= 1.8f && + std::isfinite(candidate.saturation) && candidate.saturation >= 0 && candidate.saturation <= 2 && + std::isfinite(candidate.red) && candidate.red >= .25f && candidate.red <= 4 && + std::isfinite(candidate.blue) && candidate.blue >= .25f && candidate.blue <= 4 && + (candidate.automatic == 0 || candidate.automatic == 1) && + (candidate.rotation == 0 || candidate.rotation == 90 || candidate.rotation == 180 || candidate.rotation == 270) && + (candidate.scale == 1 || candidate.scale == 1.5f || candidate.scale == 2 || candidate.scale == 3 || candidate.scale == 4 || candidate.scale == 6) && candidate.quality >= 10 && candidate.quality <= 95 && + candidate.fps >= 10 && candidate.fps <= 30 && + (candidate.exposureAuto == 0 || candidate.exposureAuto == 1) && + candidate.exposureUs >= 100 && candidate.exposureUs <= 100000 && + std::isfinite(candidate.analogueGain) && candidate.analogueGain >= 1 && candidate.analogueGain <= 8 && + std::isfinite(candidate.zoom) && candidate.zoom >= 1 && candidate.zoom <= 10) + { candidate.fps = 30; s = candidate; } + } + return s; + } + void recycle(libcamera::Request *request) { + request->reuse(libcamera::Request::ReuseBuffers); + ready.push_back(request); + } + void complete(libcamera::Request *request) { + if (request->status() == libcamera::Request::RequestCancelled || stopping) return; + auto *buffer = request->findBuffer(stream); + if (!buffer || buffer->metadata().status != libcamera::FrameMetadata::FrameSuccess) { + std::cerr << "Camera buffer failed\n"; stopping = true; changed.notify_all(); return; + } + captured++; + { + std::lock_guard lock(mutex); + // Drop an obsolete job before it enters the encoder. + if (latest) recycle(latest); + latest = request; + if (inFlight) --inFlight; + } + changed.notify_all(); + } + bool encode(libcamera::Request *request, EncoderBuffers &storage) { + auto &scaledPixels = storage.scaled; + auto &rotatedPixels = storage.rotated; + auto &coloredPixels = storage.colored; + const Settings s = settings(); + const int rotation = (s.rotation - ispRotation + 360) % 360; + const float saturation = ispSaturation ? 1.0f : s.saturation; + auto *buffer = request->findBuffer(stream); + const auto &m = maps.at(buffer); + struct jpeg_compress_struct jpeg{}; + struct jpeg_error_mgr error{}; + jpeg.err = jpeg_std_error(&error); + jpeg_create_compress(&jpeg); + unsigned char *data = nullptr; + unsigned long length = 0; + jpeg_mem_dest(&jpeg, &data, &length); + const double scale = std::max(1.0, double(s.scale) / ispScale); + const unsigned sampleWidth = static_cast(width / scale) & ~3U, sampleHeight = static_cast(height / scale) & ~3U; + const bool portrait = rotation == 90 || rotation == 270; + jpeg.image_width = portrait ? sampleHeight : sampleWidth; + jpeg.image_height = portrait ? sampleWidth : sampleHeight; + jpeg.input_components = 4; + jpeg.in_color_space = JCS_EXT_BGRX; + jpeg_set_defaults(&jpeg); + jpeg_set_quality(&jpeg, s.quality, TRUE); + jpeg_start_compress(&jpeg, TRUE); + const auto sensorTime = request->metadata().get(libcamera::controls::SensorTimestamp).value_or(monotonicNs()); + char marker[80]; + int markerLength = snprintf(marker, sizeof(marker), "platina_capture_ns=%lld", static_cast(sensorTime)); + jpeg_write_marker(&jpeg, JPEG_COM, reinterpret_cast(marker), markerLength); + const int64_t encodingStart = monotonicNs(); + const uint8_t *pixels = m.pixels; + unsigned pixelStride = stride; + // GPU stride 8192 causes severe cache-set conflicts during transposition. + // Copy rows once into a tightly packed cached buffer before rotation. + if (rotation && scale == 1 && stride % 4096 == 0) { + storage.packed.resize(width * height * 4); + for (unsigned y = 0; y < height; ++y) + std::memcpy(storage.packed.data() + y * width * 4, + pixels + y * stride, width * 4); + pixels = storage.packed.data(); pixelStride = width * 4; + } + const auto crop = platina::centerCrop(width, height, ispZoom ? 1.0f : s.zoom); + if (scale > 1 || (!ispZoom && s.zoom > 1)) { + scaledPixels.resize(sampleWidth * sampleHeight * 4); + if (libyuv::ARGBScale(pixels + crop.y * pixelStride + crop.x * 4, + pixelStride, crop.width, crop.height, + scaledPixels.data(), sampleWidth * 4, + sampleWidth, sampleHeight, + crop.width < sampleWidth ? libyuv::kFilterBilinear : libyuv::kFilterBox) < 0) + return false; + pixels = scaledPixels.data(); pixelStride = sampleWidth * 4; + } + if (rotation) { + rotatedPixels.resize(sampleWidth * sampleHeight * 4); + if (libyuv::ARGBRotate(pixels, pixelStride, rotatedPixels.data(), + jpeg.image_width * 4, sampleWidth, sampleHeight, + static_cast(rotation)) < 0) + return false; + pixels = rotatedPixels.data(); pixelStride = jpeg.image_width * 4; + } + const int64_t rotatedAt = monotonicNs(); + if (std::abs(saturation - 1.0f) > .001f) { + const float sat = saturation, other = 1.0f - sat; + auto coefficient = [](float value) { return static_cast(std::lround(value * 64)); }; + const int8_t matrix[16] = { + coefficient(.114f + .886f * sat), coefficient(.587f * other), coefficient(.299f * other), 0, + coefficient(.114f * other), coefficient(.587f + .413f * sat), coefficient(.299f * other), 0, + coefficient(.114f * other), coefficient(.587f * other), coefficient(.299f + .701f * sat), 0, + 0, 0, 0, 64 + }; + coloredPixels.resize(sampleWidth * sampleHeight * 4); + if (libyuv::ARGBColorMatrix(pixels, pixelStride, coloredPixels.data(), + jpeg.image_width * 4, matrix, + jpeg.image_width, jpeg.image_height) < 0) return false; + pixels = coloredPixels.data(); pixelStride = jpeg.image_width * 4; + } + const int64_t compressingAt = monotonicNs(); + while (jpeg.next_scanline < jpeg.image_height) { + JSAMPROW row = const_cast(pixels + jpeg.next_scanline * pixelStride); + jpeg_write_scanlines(&jpeg, &row, 1); + } + jpeg_finish_compress(&jpeg); + jpeg_destroy_compress(&jpeg); + const int64_t finished = monotonicNs(); + const auto gains = request->metadata().get(libcamera::controls::ColourGains); + const auto exposure = request->metadata().get(libcamera::controls::ExposureTime); + const auto sensorGain = request->metadata().get(libcamera::controls::AnalogueGain); + // Independent encoders may finish out of order. Publish only newer + // sensor frames, and serialize the atomic JPEG + metadata replacement. + std::lock_guard publish(publishMutex); + if (sensorTime <= lastPublished) { free(data); return true; } + std::string temporary = output + ".new"; + FILE *f = fopen(temporary.c_str(), "wb"); + bool ok = f && fwrite(data, 1, length, f) == length; + if (f && fclose(f) != 0) ok = false; + if (ok && rename(temporary.c_str(), output.c_str()) != 0) ok = false; + free(data); + if (!ok) return false; + lastPublished = sensorTime; + const int64_t published = monotonicNs(); + encoded++; + fpsFrames++; + double window = std::chrono::duration(Clock::now() - fpsStarted).count(); + if (window >= 1.0) { + recentFps = fpsFrames / window; + fpsFrames = 0; fpsStarted = Clock::now(); + } + std::ofstream meta(output + ".meta.new"); + meta << "{\"captured_ns\":" << sensorTime << ",\"published_ns\":" << published + << ",\"sensor_age_ms\":" << (published - sensorTime) / 1000000.0 + << ",\"jpeg_ms\":" << (finished - encodingStart) / 1000000.0 + << ",\"rotate_scale_ms\":" << (rotatedAt - encodingStart) / 1000000.0 + << ",\"compression_ms\":" << (finished - compressingAt) / 1000000.0 + << ",\"frames_in\":" << captured.load() << ",\"frames_out\":" << encoded.load() + << ",\"fps\":" << recentFps + << ",\"width\":" << (portrait ? sampleHeight : sampleWidth) + << ",\"height\":" << (portrait ? sampleWidth : sampleHeight) + << ",\"red_gain\":" << (gains ? (*gains)[0] : 1.0f) + << ",\"blue_gain\":" << (gains ? (*gains)[1] : 1.0f) + << ",\"exposure_us_actual\":" << (exposure ? std::to_string(*exposure) : "null") + << ",\"analogue_gain_actual\":" << (sensorGain ? std::to_string(*sensorGain) : "null") << "}"; + meta.close(); + rename((output + ".meta.new").c_str(), (output + ".meta").c_str()); + return true; + } + void encodeLoop() { + EncoderBuffers storage; + while (!stopping) { + libcamera::Request *request = nullptr; + { + std::unique_lock lock(mutex); + changed.wait_for(lock, std::chrono::milliseconds(50), [&] { return latest || stopping; }); + if (stopping) break; + if (!latest) continue; + request = latest; latest = nullptr; + } + if (captured > 10 && !encode(request, storage)) { stopping = true; changed.notify_all(); break; } + { + std::lock_guard lock(mutex); + recycle(request); + } + changed.notify_all(); + } + } +}; +int main(int argc, char **argv) { + if (argc < 2 || argc > 4 || argv[1][0] != '/') { + std::cerr << "Usage: platina-camera-capture /absolute/path/latest.jpg [0|90|180|270] [1|2|3|4|6]\n"; return 2; + } + signal(SIGINT, stop); signal(SIGTERM, stop); + Capture c; + c.output = argv[1]; + if (argc >= 3) { + std::string angle(argv[2]); + if (angle != "0" && angle != "90" && angle != "180" && angle != "270") return 2; + c.defaults.rotation = std::stoi(angle); + } + if (argc == 4) { + std::string scale(argv[3]); + if (scale != "1" && scale != "1.5" && scale != "2" && scale != "3" && scale != "4" && scale != "6") return 2; + c.defaults.scale = std::stof(scale); + } + const Settings configured = c.settings(); + bool gpu = std::getenv("LIBCAMERA_SOFTISP_MODE") && std::string(std::getenv("LIBCAMERA_SOFTISP_MODE")) == "gpu"; + c.ispScale = gpu ? configured.scale : 1; + c.ispRotation = gpu && c.ispScale > 1 ? configured.rotation : 0; + c.ispSaturation = gpu; + c.ispZoom = gpu; + setenv("PLATINA_GPU_ROTATION", std::to_string(c.ispRotation).c_str(), 1); + setenv("PLATINA_CAMERA_CONTROLS", (c.output + ".controls").c_str(), 1); + libcamera::CameraManager manager; + if (manager.start() < 0 || manager.cameras().size() != 1) { std::cerr << "Expected one camera\n"; return 1; } + c.camera = manager.cameras().front(); + if (c.camera->acquire() < 0) return 1; + auto config = c.camera->generateConfiguration({libcamera::StreamRole::Viewfinder}); + if (!config || config->empty()) return 1; + auto &cfg = config->at(0); + // Always read the full sensor. Output scaling never changes the field of view. + c.maxInFlight = gpu ? 2 : 1; + if (const char *count = std::getenv("PLATINA_CAMERA_IN_FLIGHT")) { + try { c.maxInFlight = std::clamp(std::stoul(count), 1UL, 2UL); } + catch (...) { return 2; } + } + cfg.size = { static_cast(4024U / c.ispScale) & ~3U, static_cast(3016U / c.ispScale) & ~3U }; + if (c.ispRotation == 90 || c.ispRotation == 270) + cfg.size = {cfg.size.height, cfg.size.width}; + cfg.pixelFormat = libcamera::formats::XRGB8888; + unsigned jpegThreads = 4; + if (const char *count = std::getenv("PLATINA_JPEG_THREADS")) { + try { jpegThreads = std::clamp(std::stoul(count), 1UL, 4UL); } + catch (...) { return 2; } + } + cfg.bufferCount = jpegThreads + 4; + if (config->validate() == libcamera::CameraConfiguration::Invalid || c.camera->configure(config.get()) < 0) return 1; + for (unsigned id : {libcamera::controls::AeEnable.id(), libcamera::controls::ExposureTime.id(), + libcamera::controls::AnalogueGain.id()}) { + if (!c.camera->controls().count(id)) { + std::cerr << "Camera pipeline lacks exposure controls\n"; + return 1; + } + } + if (cfg.pixelFormat != libcamera::formats::XRGB8888) return 1; + c.width = cfg.size.width; c.height = cfg.size.height; c.stride = cfg.stride; c.stream = cfg.stream(); + std::cerr << "Configured " << cfg.toString() << " stride=" << cfg.stride << '\n'; + auto allocator = std::make_unique(c.camera); + if (allocator->allocate(c.stream) < 0) return 1; + std::vector> requests; + for (const auto &buffer : allocator->buffers(c.stream)) { + if (buffer->planes().size() != 1) return 1; + const auto &plane = buffer->planes()[0]; + size_t size = plane.offset + plane.length; + if (plane.length < c.stride * c.height) return 1; + void *base = mmap(nullptr, size, PROT_READ, MAP_SHARED, plane.fd.get(), 0); + if (base == MAP_FAILED) return 1; + c.maps.emplace(buffer.get(), Capture::Mapping{base, size, static_cast(base) + plane.offset}); + auto request = c.camera->createRequest(); + if (!request || request->addBuffer(c.stream, buffer.get()) < 0) return 1; + c.ready.push_back(request.get()); requests.push_back(std::move(request)); + } + c.camera->requestCompleted.connect(&c, &Capture::complete); + if (c.camera->start() < 0) return 1; + for (unsigned i = 0; i < jpegThreads; ++i) + c.encoders.emplace_back(&Capture::encodeLoop, &c); + bool reconfigure = false; + auto next = Clock::now(); + while (!stopping) { + libcamera::Request *request = nullptr; + { + std::unique_lock lock(c.mutex); + c.changed.wait_for(lock, std::chrono::milliseconds(50), [&] { return stopping || (c.inFlight < c.maxInFlight && !c.ready.empty()); }); + if (stopping) break; + if (c.inFlight < c.maxInFlight && !c.ready.empty()) { + request = c.ready.front(); c.ready.pop_front(); ++c.inFlight; + } + } + if (!request) continue; + auto s = c.settings(); + if (gpu && (double(s.scale) != c.ispScale || s.rotation != configured.rotation)) { reconfigure = true; break; } + auto &ctrl = request->controls(); + ctrl.set(libcamera::controls::AeEnable, bool(s.exposureAuto)); + if (!s.exposureAuto) { + ctrl.set(libcamera::controls::ExposureTime, s.exposureUs); + ctrl.set(libcamera::controls::AnalogueGain, s.analogueGain); + } + ctrl.set(libcamera::controls::Gamma, s.gamma); + ctrl.set(libcamera::controls::Contrast, s.contrast); + // Saturation is applied with SIMD after the ISP; no costly identity CCM. + ctrl.set(libcamera::controls::AwbEnable, bool(s.automatic)); + const float gains[2] = {s.red, s.blue}; + ctrl.set(libcamera::controls::ColourGains, libcamera::Span(gains)); + next = std::max(next, Clock::now()); + std::this_thread::sleep_until(next); + if (c.camera->queueRequest(request) < 0) stopping = true; + next += std::chrono::microseconds(1000000 / s.fps); + } + stopping = true; + c.camera->stop(); + c.changed.notify_all(); + for (auto &encoder : c.encoders) if (encoder.joinable()) encoder.join(); + c.camera->requestCompleted.disconnect(&c); + for (auto &[buffer, map] : c.maps) munmap(map.base, map.size); + requests.clear(); allocator->free(c.stream); allocator.reset(); + c.camera->release(); config.reset(); c.camera.reset(); manager.stop(); + std::cerr << "Stopped after " << c.captured << " camera frames and " << c.encoded << " JPEGs\n"; + if (reconfigure) { execl(argv[0], argv[0], argv[1], nullptr); return 1; } + return c.encoded > 0 ? 0 : 1; +} diff --git a/project/camera/libcamera-headless/configuration.yaml b/project/camera/libcamera-headless/configuration.yaml new file mode 100644 index 0000000..437c41a --- /dev/null +++ b/project/camera/libcamera-headless/configuration.yaml @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: CC0-1.0 +--- +version: 1 +configuration: + software_isp: + mode: cpu + threads: 4 diff --git a/project/camera/libcamera-headless/imx363.yaml b/project/camera/libcamera-headless/imx363.yaml new file mode 100644 index 0000000..7cd1b4a --- /dev/null +++ b/project/camera/libcamera-headless/imx363.yaml @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: CC0-1.0 +# IMX363 black level plus the upstream software ISP algorithms. +# Manual white balance is linear; saturation uses the consumer's SIMD path. +# The investigated DNG CCM is nearly identity and is not enabled here. +%YAML 1.1 +--- +version: 1 +algorithms: + - BlackLevel: + blackLevel: 4096 + - Awb: + - Adjust: + - Agc: +... diff --git a/project/camera/libcamera-headless/platina-camera.openrc b/project/camera/libcamera-headless/platina-camera.openrc new file mode 100644 index 0000000..9f990e0 --- /dev/null +++ b/project/camera/libcamera-headless/platina-camera.openrc @@ -0,0 +1,23 @@ +#!/sbin/openrc-run +description="Platina camera web and Home Assistant controls (capture OFF at startup)" +command="/usr/bin/python3" +command_args="/usr/lib/platina-camera/bin/serve.py --listen 0.0.0.0" +command_user="root:root" +supervisor="supervise-daemon" +pidfile="/run/platina-camera.pid" +respawn_delay=5 +respawn_max=5 +respawn_period=1800 +output_log="/var/log/platina-camera.log" +error_log="/var/log/platina-camera.log" + +depend() { + need localmount + use networkmanager + after udev-trigger +} + +start_pre() { + checkpath --file --mode 0640 --owner root:root "$output_log" + checkpath --directory --mode 0700 --owner root:root /etc/platina-camera +} diff --git a/project/camera/libcamera-headless/platina_exposure.h b/project/camera/libcamera-headless/platina_exposure.h new file mode 100644 index 0000000..f867fe6 --- /dev/null +++ b/project/camera/libcamera-headless/platina_exposure.h @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +#pragma once + +#include +#include +#include + +namespace platina { + +struct ExposureSettings { + bool automatic = true; + int32_t exposureUs = 10000; + double gain = 1.0; +}; + +/* Clamp before conversion to avoid integer overflow on external controls. + * Sensor exposure uses whole lines; metadata reports the quantized result. */ +inline int32_t exposureLines(int32_t exposureUs, double lineUs, + int32_t minimum, int32_t maximum) +{ + double lines = std::clamp(exposureUs / lineUs, + double(minimum), double(maximum)); + return static_cast(std::lround(lines)); +} + +inline double sensorGain(double requested, double minimum, double maximum) +{ + return std::isfinite(requested) ? std::clamp(requested, minimum, maximum) : minimum; +} + +} /* namespace platina */ diff --git a/project/camera/libcamera-headless/platina_zoom.h b/project/camera/libcamera-headless/platina_zoom.h new file mode 100644 index 0000000..ec3b968 --- /dev/null +++ b/project/camera/libcamera-headless/platina_zoom.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +#pragma once + +#include +#include +#include + +namespace platina { + +/* The controls file is atomically replaced by the controller. Zoom is appended + * after the thirteen existing fields, preserving earlier field positions. */ +inline float zoomFromControls(std::istream &input) +{ + double field; + for (unsigned i = 0; i < 13; ++i) { + if (!(input >> field) || !std::isfinite(field)) + return 1.0f; + } + float zoom; + return input >> zoom && std::isfinite(zoom) && zoom >= 1.0f && zoom <= 10.0f ? zoom : 1.0f; +} + +/* Crop texture coordinates, not the viewport: output size stays unchanged. + * Centered zoom commutes with each supported quarter-turn rotation. */ +inline float zoomCoordinate(float coordinate, float zoom) +{ + return 0.5f + (coordinate - 0.5f) / zoom; +} + +struct ZoomCrop { + unsigned x, y, width, height; +}; + +/* CPU fallback crops debayered ARGB before its existing resize/rotation pass. */ +inline ZoomCrop centerCrop(unsigned width, unsigned height, float zoom) +{ + if (zoom <= 1.0f) + return {0, 0, width, height}; + unsigned w = std::max(4U, static_cast(width / zoom) & ~3U); + unsigned h = std::max(4U, static_cast(height / zoom) & ~3U); + return {(width - w) / 2, (height - h) / 2, w, h}; +} + +} /* namespace platina */ diff --git a/project/camera/libcamera-headless/preview.html b/project/camera/libcamera-headless/preview.html new file mode 100644 index 0000000..1b4780b --- /dev/null +++ b/project/camera/libcamera-headless/preview.html @@ -0,0 +1,93 @@ + + +Platina kamera + +

Platina kamera

Načítám stav…
+
Kamera je vypnutá.
+

Pokročilé nastavení

+
+

+ + +
+ diff --git a/project/camera/libcamera-headless/serve.py b/project/camera/libcamera-headless/serve.py new file mode 100644 index 0000000..48de46f --- /dev/null +++ b/project/camera/libcamera-headless/serve.py @@ -0,0 +1,502 @@ +#!/usr/bin/env python3 +"""Always available controls; capture is explicitly enabled and defaults OFF.""" +import argparse +import json +import math +import os +from pathlib import Path +import re +import secrets +import select +import signal +import socket +import subprocess +import threading +import tempfile +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlsplit + +DEFAULTS = dict(focus=310, gamma=1.0, contrast=1.0, saturation=1.14, automatic=True, + red=2.09, blue=1.49, rotation=90, scale=2, quality=50, fps=30, + exposure_auto=True, exposure_us=10000, analogue_gain=1.0, zoom=1.0) +RANGES = dict(focus=(0, 1023), gamma=(.5, 4), contrast=(.5, 1.8), + saturation=(0, 2), red=(.25, 4), blue=(.25, 4), quality=(10, 95), fps=(10, 30), + exposure_us=(100, 100000), analogue_gain=(1, 8), zoom=(1, 10)) +EXPOSURE_DEFAULTS = {key: DEFAULTS[key] for key in ('exposure_auto', 'exposure_us', 'analogue_gain')} + + +def load_settings(path): + value = json.loads(path.read_text()) + # Migrate only complete historical schemas; reject corrupt/unknown fields. + if isinstance(value, dict) and set(value) == set(DEFAULTS) - set(EXPOSURE_DEFAULTS) - {'zoom'}: + value = dict(value, **EXPOSURE_DEFAULTS) + if isinstance(value, dict) and set(value) == set(DEFAULTS) - {'zoom'}: + value = dict(value, zoom=1.0) + return validate(value) +SCALES = {1: '12 MP', 1.5: '5,4 MP', 2: '3 MP', 3: '1,3 MP', 4: '0,75 MP', 6: '0,33 MP'} + + +def validate(value): + if not isinstance(value, dict) or set(value) != set(DEFAULTS): + raise ValueError('Unexpected settings fields') + for key, item in value.items(): + if key in ('automatic', 'exposure_auto'): + if type(item) is not bool: + raise ValueError('Invalid ' + key) + elif key == 'rotation': + if type(item) is not int or item not in (0, 90, 180, 270): + raise ValueError('Invalid rotation') + elif key == 'scale': + if type(item) not in (int, float) or item not in SCALES: + raise ValueError('Invalid scale') + else: + if type(item) not in (int, float) or not math.isfinite(item): + raise ValueError('Invalid ' + key) + low, high = RANGES[key] + if not low <= item <= high or (key in ('focus', 'quality', 'fps', 'exposure_us') and type(item) is not int): + raise ValueError('Out of range: ' + key) + result = dict(value) + result['fps'] = 30 + result['scale'] = 1.5 if value['scale'] == 1.5 else int(value['scale']) + return result + + +def atomic(path, data): + temporary = path.with_name(path.name + '.new') + temporary.write_bytes(data) + temporary.chmod(0o600) + temporary.replace(path) + + +class Camera: + def __init__(self, args): + self.args = args + self.lock = threading.RLock() + self.settings = load_settings(args.config) if args.config.exists() else dict(DEFAULTS) + self.saved = dict(self.settings) + self.capture = None + self.focus_fd = None + self.focus_device = None + self.focus_applied = False + self.error = None + self.generation = 0 + self.started = 0 + self.args.frame.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + self.clear_frames() + + def clear_frames(self): + for suffix in ('', '.new', '.meta', '.meta.new', '.controls', '.controls.new'): + Path(str(self.args.frame) + suffix).unlink(missing_ok=True) + + def controls(self, value): + fields = [value['gamma'], value['contrast'], value['saturation'], + int(value['automatic']), value['red'], value['blue'], + value['rotation'], value['scale'], value['quality'], value['fps'], + int(value['exposure_auto']), value['exposure_us'], value['analogue_gain'], value['zoom']] + atomic(Path(str(self.args.frame) + '.controls'), (' '.join(map(str, fields)) + '\n').encode()) + + def focus(self, position): + subprocess.run(['v4l2-ctl', '-d', self.focus_device, + '--set-ctrl=focus_absolute=' + str(position)], check=True, timeout=5) + + def configure(self, payload, save=False): + if not isinstance(payload, dict) or not set(payload) <= set(DEFAULTS): + raise ValueError('Unexpected settings fields') + with self.lock: + value = validate(dict(self.settings, **payload)) + if self.capture is not None and self.capture.poll() is None: + if self.focus_applied and value['focus'] != self.settings['focus']: + self.focus(value['focus']) + self.controls(value) + if any(value[k] != self.settings[k] for k in ('scale', 'rotation')): + self.started = time.monotonic() + if save: + self.args.config.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + atomic(self.args.config, (json.dumps(value, indent=2) + '\n').encode()) + self.saved = dict(value) + self.settings = value + return dict(value) + + def set_enabled(self, enabled): + if type(enabled) is not bool: + raise ValueError('Expected enabled: true or false') + with self.lock: + if not enabled: + self.stop() + elif self.capture is None or self.capture.poll() is not None: + self.stop() + self.error = None + try: + matches = [p for p in Path('/sys/class/video4linux').glob('v4l-subdev*') + if (p / 'name').read_text().strip() == 'dw9714 2-000c'] + if len(matches) != 1: + raise OSError('Rear camera is not available in this kernel') + self.focus_device = '/dev/' + matches[0].name + self.focus_fd = os.open(self.focus_device, os.O_RDWR | os.O_CLOEXEC) + self.controls(self.settings) + env = dict(os.environ, + LD_LIBRARY_PATH='/usr/lib/platina-camera/lib:/usr/lib/platina-camera/gpu/lib:/usr/lib/platina-camera/gpu/lib/dri', + LIBCAMERA_SOFTISP_MODE='cpu' if self.args.cpu else 'gpu', + PLATINA_JPEG_THREADS='2' if self.args.cpu else '4', + LIBCAMERA_LOG_LEVELS='*:WARN') + # Experimental DMA paths must never be enabled by a stale shell environment. + for key in ('PLATINA_GPU_INPUT_DMABUF', 'PLATINA_GPU_FLAT_DMABUF', 'PLATINA_GPU_PROFILE'): + env.pop(key, None) + self.capture = subprocess.Popen([self.args.capture, str(self.args.frame)], env=env) + self.started = time.monotonic() + self.generation += 1 + except (OSError, subprocess.SubprocessError): + self.stop() + self.error = 'Kameru nelze spustit. Zkontrolujte ovladač a záznam služby.' + raise OSError(self.error) from None + return self.status() + + def stop(self): + with self.lock: + self.generation += 1 + if self.capture is not None: + if self.capture.poll() is None: + self.capture.terminate() + try: + self.capture.wait(timeout=8) + except subprocess.TimeoutExpired: + self.capture.kill() + self.capture.wait(timeout=3) + self.capture = None + if self.focus_fd is not None: + os.close(self.focus_fd) + self.focus_fd = None + self.focus_applied = False + self.focus_device = None + self.clear_frames() + self.error = None + + def tick(self): + with self.lock: + if self.capture is None: + return + code = self.capture.poll() + if code is not None: + self.stop() + self.error = 'Snímání se zastavilo. Kameru lze znovu zapnout.' + print('Capture exited with status ' + str(code), flush=True) + elif not self.focus_applied and self.args.frame.exists(): + try: + self.focus(self.settings['focus']) + self.focus_applied = True + except (OSError, subprocess.SubprocessError): + self.stop() + self.error = 'Nastavení ostření selhalo. Kameru lze znovu zapnout.' + elif time.monotonic() - self.started > 20: + try: + self.latest() + except (OSError, ValueError, KeyError): + self.stop() + self.error = 'Kamera nedodává aktuální obraz. Kameru lze znovu zapnout.' + + def latest(self): + with self.lock: + if self.capture is None or self.capture.poll() is not None: + raise OSError('Camera is off') + with self.args.frame.open('rb') as stream: + stat = os.fstat(stream.fileno()) + age = time.time() - stat.st_mtime + if age > 2: + raise OSError('Camera frame expired') + data = stream.read(8 * 1024 * 1024 + 1) + meta = json.loads(Path(str(self.args.frame) + '.meta').read_text()) + marker = re.search(rb'platina_capture_ns=([0-9]+)', data[:1024]) + if not marker: + raise OSError('Missing frame timestamp') + meta['captured_ns'] = int(marker.group(1)) + meta['sensor_age_ms'] = (time.monotonic_ns() - meta['captured_ns']) / 1_000_000 + if meta['sensor_age_ms'] > 2000: + raise OSError('Sensor frame expired') + if len(data) > 8 * 1024 * 1024 or not data.startswith(b'\xff\xd8') or not data.endswith(b'\xff\xd9'): + raise OSError('Incomplete frame') + return data, age, stat.st_mtime_ns, meta + + def status(self): + with self.lock: + enabled = self.capture is not None and self.capture.poll() is None + result = dict(ok=True, enabled=enabled, state='starting' if enabled else 'error' if self.error else 'off', + error=self.error, settings=dict(self.settings), generation=self.generation) + if enabled: + try: + _, age, _, meta = self.latest() + result.update(state='on', age_seconds=round(age, 3), **meta) + except (OSError, ValueError, KeyError): + pass + return result + + +class Audio: + """One on-demand PCM listener; restore the mixer on every exit path.""" + rate = 48000 + + def __init__(self): + self.lock = threading.Lock() + self.tokens = {} + self.capture = None + self.closed = False + self.released = threading.Event() + self.released.set() + + def ticket(self): + with self.lock: + if self.closed: + raise ValueError('Audio is stopping') + if self.capture is not None: + raise ValueError('Mikrofon právě používá jiný posluchač.') + # Keep only the latest short-lived, single-use authorization. + token = secrets.token_urlsafe(24) + self.tokens = {token: time.monotonic() + 10} + return dict(token=token, rate=self.rate, channels=1, format='s16le') + + def open(self, token): + with self.lock: + expires = self.tokens.pop(token, 0) + if self.closed or expires < time.monotonic() or self.capture is not None: + raise ValueError('Poslech vypršel nebo je mikrofon obsazený.') + if 'Xiaomi Mi 8 Lite' not in Path('/proc/asound/cards').read_text(): + raise ValueError('Mikrofon telefonu není dostupný.') + directory = tempfile.TemporaryDirectory(prefix='platina-audio-') + state = str(Path(directory.name) / 'mixer.state') + saved = False + try: + self.command(['alsactl', '-f', state, 'store', '0']) + saved = True + for name, value in ( + ('MultiMedia1 Mixer LPI_MI2S_TX_3', '1'), + ('Digital CIC1 MUX', 'AMIC'), + ('Digital DEC1 MUX', 'ADC2'), ('ADC2 MUX', 'INP3'), + ('ADC3 Volume', '6'), ('Digital TX1 Digital Volume', '114')): + self.command(['amixer', '-q', '-c', '0', 'cset', 'name=' + name, value]) + process = subprocess.Popen( + ['arecord', '-q', '-D', 'hw:0,0', '-t', 'raw', '-f', 'S16_LE', + '-r', str(self.rate), '-c', '1', '--period-size=960', '--buffer-size=3840'], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + self.capture = process + self.released.clear() + return process, directory, state + except Exception: + if saved: + self.command(['alsactl', '-f', state, 'restore', '0'], check=False) + directory.cleanup() + raise + + @staticmethod + def command(args, check=True): + return subprocess.run(args, check=check, timeout=5, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + + def release(self, session): + process, directory, state = session + with self.lock: + try: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=3) + process.stdout.close() + finally: + try: + self.command(['alsactl', '-f', state, 'restore', '0'], check=False) + finally: + directory.cleanup() + self.capture = None + self.released.set() + + def close(self): + with self.lock: + self.closed = True + self.tokens.clear() + if self.capture is not None and self.capture.poll() is None: + self.capture.terminate() + self.released.wait(timeout=8) + + +def make_handler(camera, shutdown, audio=None): + class Handler(BaseHTTPRequestHandler): + def setup(self): + super().setup() + self.connection.settimeout(2) + self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 262144) + self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + + def log_message(self, *_): + pass + + def reply(self, status, content_type, payload): + self.send_response(status) + self.send_header('Content-Type', content_type) + self.send_header('Content-Length', str(len(payload))) + self.send_header('Cache-Control', 'no-store') + self.send_header('X-Content-Type-Options', 'nosniff') + self.end_headers() + self.wfile.write(payload) + + def json(self, status, value): + self.reply(status, 'application/json', json.dumps(value).encode()) + + def do_GET(self): + path = urlsplit(self.path).path + try: + if path == '/': + self.reply(200, 'text/html; charset=utf-8', Path(__file__).with_name('preview.html').read_bytes()) + elif path == '/settings': + with camera.lock: + self.json(200, dict(camera.settings)) + elif path in ('/status', '/health'): + self.json(200, camera.status()) + elif path == '/audio.pcm' and audio is not None: + from urllib.parse import parse_qs + origin = self.headers.get('Origin') + if origin not in (None, 'http://' + self.headers.get('Host', '')): + self.json(403, dict(error='Origin rejected')) + return + try: + session = audio.open(parse_qs(urlsplit(self.path).query).get('token', [''])[0]) + except (OSError, ValueError, subprocess.SubprocessError) as error: + self.json(409, dict(error=str(error))) + return + try: + process = session[0] + self.send_response(200) + self.send_header('Content-Type', 'application/octet-stream') + self.send_header('Cache-Control', 'no-store') + self.send_header('Connection', 'close') + self.end_headers() + self.close_connection = True + while not shutdown.is_set(): + if not select.select([process.stdout], [], [], 3)[0]: + break + data = os.read(process.stdout.fileno(), 3840) + if not data: + break + self.wfile.write(data) + self.wfile.flush() + finally: + audio.release(session) + elif path in ('/snapshot.jpg', '/stream.mjpg'): + try: + data, _, stamp, meta = camera.latest() + except (OSError, ValueError, KeyError): + self.json(503, dict(ok=False, error='Camera is off or starting')) + return + if path == '/snapshot.jpg': + self.reply(200, 'image/jpeg', data) + return + generation = camera.generation + self.send_response(200) + self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=frame') + self.send_header('Cache-Control', 'no-store') + self.end_headers() + while not shutdown.is_set() and camera.generation == generation: + self.wfile.write(b'--frame\r\nContent-Type: image/jpeg\r\nContent-Length: ' + str(len(data)).encode() + b'\r\nX-Frame-Age-Ms: ' + str(round(meta['sensor_age_ms'], 2)).encode() + b'\r\n\r\n' + data + b'\r\n') + self.wfile.flush() + while not shutdown.wait(.005) and camera.generation == generation: + if camera.args.frame.stat().st_mtime_ns == stamp: + continue + data, _, stamp, meta = camera.latest() + break + else: + self.json(404, dict(error='Not found')) + except (OSError, ValueError, KeyError): + self.close_connection = True + + def do_POST(self): + path = urlsplit(self.path).path + if path not in ('/settings', '/save', '/restore', '/camera', '/audio'): + self.json(404, dict(error='Not found')) + return + if self.headers.get('Origin') not in (None, 'http://' + self.headers.get('Host', '')): + self.json(403, dict(error='Origin rejected')) + return + try: + length = int(self.headers.get('Content-Length', '0')) + if not 0 < length <= 2048 or self.headers.get_content_type() != 'application/json': + raise ValueError('Expected small JSON body') + payload = json.loads(self.rfile.read(length)) + if not isinstance(payload, dict): + raise ValueError('Expected JSON object') + if path == '/audio': + if payload or audio is None: + raise ValueError('Expected empty object and available audio') + self.json(200, audio.ticket()) + return + with camera.lock: + if path == '/camera': + if set(payload) != {'enabled'}: + raise ValueError('Expected enabled field') + value = camera.set_enabled(payload['enabled']) + elif path == '/save': + if payload: + raise ValueError('Expected empty object') + value = camera.configure({}, save=True) + elif path == '/restore': + if payload: + raise ValueError('Expected empty object') + value = camera.configure(dict(camera.saved)) + else: + value = camera.configure(payload) + self.json(200, value) + except (ValueError, KeyError, OSError, subprocess.SubprocessError) as error: + self.json(400, dict(error=str(error))) + return Handler + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--cpu', action='store_true') + parser.add_argument('--listen', default='127.0.0.1') + parser.add_argument('--port', type=int, default=8082) + parser.add_argument('--frame', type=Path, default=Path('/run/platina-camera/latest.jpg')) + parser.add_argument('--capture', default='/usr/lib/platina-camera/bin/platina-camera-capture') + parser.add_argument('--config', type=Path, default=Path('/etc/platina-camera/preview.json')) + parser.add_argument('--mqtt-config', type=Path, default=Path('/etc/platina-camera/mqtt.json')) + parser.add_argument('--seconds', type=float) + args = parser.parse_args() + os.umask(0o077) + shutdown = threading.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, lambda *_: shutdown.set()) + camera = Camera(args) + audio = Audio() + bridge = None + server = ThreadingHTTPServer((args.listen, args.port), make_handler(camera, shutdown, audio)) + server.daemon_threads = True + server.timeout = .1 + try: + if args.mqtt_config.exists(): + from camera_mqtt import Bridge + try: + bridge = Bridge(camera, args.mqtt_config) + bridge.start() + except (OSError, ValueError, ImportError, KeyError, AttributeError): + bridge = None + print('MQTT configuration unavailable; web controls remain available', flush=True) + print(f'Platina controls listening on {args.listen}:{args.port}; camera OFF', flush=True) + deadline = time.monotonic() + args.seconds if args.seconds else None + while not shutdown.is_set(): + if deadline and time.monotonic() >= deadline: + break + camera.tick() + if bridge: + bridge.tick() + server.handle_request() + finally: + shutdown.set() + audio.close() + camera.stop() + if bridge: + bridge.close() + server.server_close() + + +if __name__ == '__main__': + main() diff --git a/project/camera/mesa-freedreno/APKBUILD b/project/camera/mesa-freedreno/APKBUILD new file mode 100644 index 0000000..a43ad24 --- /dev/null +++ b/project/camera/mesa-freedreno/APKBUILD @@ -0,0 +1,35 @@ +# Isolated headless Adreno userspace; no desktop, Vulkan or LLVM runtime. +pkgname=platina-mesa-freedreno +pkgver=26.1.6 +pkgrel=0 +pkgdesc="Minimal Freedreno EGL/GLES for the Platina camera" +url="https://mesa3d.org/" +arch="aarch64" +license="MIT AND SGI-B-2.0 AND BSL-1.0" +sonameprefix="platina-gpu-" +ldpath="/usr/lib/platina-camera/gpu/lib:/usr/lib/platina-camera/gpu/lib/dri" +makedepends="bison eudev-dev expat-dev flex libdrm-dev elfutils-dev meson py3-mako py3-packaging py3-ply py3-yaml zlib-dev" +source="https://archive.mesa3d.org/mesa-$pkgver.tar.xz" +builddir="$srcdir/mesa-$pkgver" +options="!check" + +build() { + abuild-meson --prefix=/usr/lib/platina-camera/gpu \ + --libdir=/usr/lib/platina-camera/gpu/lib \ + --includedir=/usr/lib/platina-camera/gpu/include \ + --datadir=/usr/lib/platina-camera/gpu/share \ + -Dgallium-drivers=freedreno -Dfreedreno-kmds=msm \ + -Dvulkan-drivers=[] -Dplatforms=[] -Dopengl=false \ + -Dglx=disabled -Dglvnd=disabled -Degl=enabled -Dgbm=enabled \ + -Dgles1=disabled -Dgles2=enabled -Dllvm=disabled -Ddraw-use-llvm=false \ + -Dgallium-rusticl=false -Dgallium-va=disabled -Dvideo-codecs=[] \ + -Dxmlconfig=disabled -Dzstd=disabled -Dbuild-tests=false \ + -Dwerror=false . output + meson compile -C output -j 2 +} +package() { + DESTDIR="$pkgdir" meson install --no-rebuild -C output +} +sha512sums=" +6746b73f5b87e8ff3723eee586b4b5f033dbe6d13cd0309d743b7fa484c350268859ec8ff21aadcbca7a04070cdaa7828146dd28dde4b1935bb879891d687f0b mesa-26.1.6.tar.xz +" diff --git a/project/camera/reference.json b/project/camera/reference.json new file mode 100644 index 0000000..62ad7a0 --- /dev/null +++ b/project/camera/reference.json @@ -0,0 +1,118 @@ +{ + "schema": 1, + "purpose": "Rear IMX363 bringup references; not hardware validation", + "kernel_driver": { + "repository": "https://gitlab.com/sdm845-mainline/linux", + "commit": "85f1df2a4ec71d7a91dd95a7a49f889d1595ffa8", + "file": "drivers/media/i2c/imx363.c", + "sha256": "13d15b54c0a45598d0d165b338c42ee9bbd627cb6a072bdad272e32a20c0583b", + "license": "GPL-2.0" + }, + "wiring": { + "repository": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource", + "commit": "0bb2780bccb9c7e05f0edf5db8860e779179b5f9", + "file": "arch/arm/boot/dts/qcom/platina-camera-sensor.dtsi", + "sha256": "40dffc957213ad4ddd7d15ac5fce65e35d3bd9215753153b68af75a586d14f2f", + "license": "GPL-2.0-only" + }, + "android_reference_only": { + "repository": "https://github.com/TheMuppets/proprietary_vendor_xiaomi_platina", + "commit": "d3c57407b34d03ff3597f67129c2bb0bdcac3005", + "redistributed": false, + "files": [ + { + "file": "camera_config.xml", + "sha256": "0a7c472da195da1e4f248680b9082a9b79e74b8f3d9f1a5eeaae1442d13dc9af" + }, + { + "file": "libmmcamera_platina_imx363_sunny.so", + "sha256": "3420e804c4ac0417bf55416fb66ed0574a8e52328e71ca9162e6e2bb7554d86e" + }, + { + "file": "libmmcamera_platina_imx363_ofilm.so", + "sha256": "2c90b84c787b635721f991344e2391fb416c89b05cde1604f13cfef2c8797080" + }, + { + "file": "libactuator_platina_dw9714_sunny.so", + "sha256": "a59824f23b2662f42cf5b95af2c29132d564b1e5fbdc3f57987c294fd2be1c3e" + }, + { + "file": "libactuator_platina_dw9714_ofilm.so", + "sha256": "d7de89e6ceeb84a020d21048e6031d7e60fdd6a8d95e6172c7add71cc34ac38e" + } + ], + "sensor_descriptor_evidence": { + "elf_file_offset": 20488, + "address_8bit": 32, + "id_register": 22, + "chip_id": 867 + }, + "csi": { + "slot": 0, + "csid": 0, + "lane_mask": "0x1f", + "lane_assignment": "0x4320", + "mount_angle": 90 + } + }, + "camss_supplies": { + "repository": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource", + "commit": "0bb2780bccb9c7e05f0edf5db8860e779179b5f9", + "file": "arch/arm/boot/dts/qcom/sdm660-camera.dtsi", + "sha256": "d72db3f96fbadf89eea91fe2cd85039ebe86239e01108a804418b930f74c643a", + "vdda": "PM660 L1", + "vdd_sec": "PM660L L1" + }, + "lane_mapping": { + "stock_table": [ + 0, + 4, + 1, + 2, + 3 + ], + "stock_lane_assign": "0x4320", + "hardware_lane_assign": "0x3210", + "mainline_receiver_data_lanes": [ + 0, + 1, + 2, + 3 + ], + "clock_lane_fixed_by_driver": true, + "repository": "https://github.com/MiCode/Xiaomi_Kernel_OpenSource", + "commit": "0bb2780bccb9c7e05f0edf5db8860e779179b5f9", + "files": [ + { + "file": "drivers/media/platform/msm/camera_v2/sensor/csid/msm_csid.c", + "sha256": "e78fa4c02696e4363170c54271b81c906fa2c917251882035686c991f97f80f2" + }, + { + "file": "drivers/media/platform/msm/camera_v2/sensor/csid/include/msm_csid_3_5_hwreg.h", + "sha256": "436ef12d35c05fe6a00242b63371ad1ab50921791ece5b35cb5bdadfd85fa8a3" + } + ] + }, + "phy_clock_reference": { + "url": "https://lkml.iu.edu/2010.2/01479.html", + "author": "AngeloGioacchino Del Regno", + "requirement": "SDM630/660 csiX_phy rate must be at least csiphyX_timer rate", + "tested_reference_device": "Sony Xperia XA2 (SDM630)", + "observed_platina_before_fix_hz": { + "phy": 19200000, + "timer": 100000000 + } + }, + "lens": { + "driver": "dongwoon,dw9714", + "i2c_address_7bit": "0x0c", + "stock_i2c_address_8bit": "0x18", + "regulator": "cam-actuator-rear-vreg", + "enable_gpio": 50, + "stock_variants": [ + "platina_dw9714_sunny", + "platina_dw9714_ofilm" + ], + "hardware_control_verified": false + } +} diff --git a/project/release.json b/project/release.json index 58026c1..795cf83 100644 --- a/project/release.json +++ b/project/release.json @@ -1,7 +1,7 @@ { "schema": 1, "name": "Platina Linux", - "version": "0.3.1", + "version": "0.8.1", "channel": "development", - "released": "2026-10-23" + "released": "2026-10-27" } diff --git a/project/sources.lock.json b/project/sources.lock.json index aba0283..f7dd5ca 100644 --- a/project/sources.lock.json +++ b/project/sources.lock.json @@ -16,7 +16,7 @@ "candidate": { "ports": "ports/candidate", "kernel": "7.2.12", - "kernel_package": "7.2.12-r1", + "kernel_package": "7.2.12-r12", "device_package": "5-r31", "firmware_package": "2-r5" } diff --git a/scripts/build-camera-userspace.py b/scripts/build-camera-userspace.py new file mode 100755 index 0000000..1fc2db7 --- /dev/null +++ b/scripts/build-camera-userspace.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Build scoped camera userspace components locally; never deploy or flash.""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import subprocess + +ROOT = Path(__file__).resolve().parents[1] + + +def hashes(directory): + result = {} + for path in sorted(directory.iterdir()): + if path.name == '__pycache__' and path.is_dir() and not path.is_symlink(): + continue + if not path.is_file() or path.is_symlink(): + raise ValueError('Unexpected camera recipe entry: ' + path.name) + result[path.name] = hashlib.sha256(path.read_bytes()).hexdigest() + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--component', choices=('userspace', 'mesa'), default='userspace') + parser.add_argument('--prepare-only', action='store_true') + parser.add_argument('--lax', action='store_true', help='Reuse existing build chroots') + args = parser.parse_args() + folder, package = {'userspace': ('libcamera-headless', 'platina-libcamera'), + 'mesa': ('mesa-freedreno', 'platina-mesa-freedreno')}[args.component] + source = ROOT / 'project/camera' / folder + managed = ROOT / 'sources/pmaports-managed-candidate' + destination = managed / 'device/testing' / package + stamp = managed / ('.platina-camera-' + args.component + '.json') + config = ROOT / 'config/pmbootstrap-managed-candidate.cfg' + if not config.is_file() or not (managed / '.platina-managed.json').is_file(): + raise ValueError('Prepare the managed candidate profile first') + expected = hashes(source) + if destination.exists(): + if not stamp.is_file() or hashes(destination) != json.loads(stamp.read_text())['files']: + raise ValueError('Preserve/review existing camera recipe edits before updating') + else: + destination.mkdir() + for path in destination.iterdir(): + if path.name not in expected: + path.unlink() + for name in expected: + shutil.copyfile(source / name, destination / name) + stamp.write_text(json.dumps({'files': expected}, indent=2) + '\n') + if not args.prepare_only: + command = ['python3', str(ROOT / 'tools/pmbootstrap/pmbootstrap.py'), + '-c', str(config), 'build', '--arch', 'aarch64', package] + if args.lax: + command.append('--lax') + subprocess.run(command, check=True) + print('Camera runtime prepared/built locally; no phone action performed.') + + +if __name__ == '__main__': + main() diff --git a/tests/camera_exposure.cpp b/tests/camera_exposure.cpp new file mode 100644 index 0000000..50ed594 --- /dev/null +++ b/tests/camera_exposure.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "platina_exposure.h" +#include +#include + +int main() +{ + // Microseconds must become sensor lines, with rounding and mode limits. + assert(platina::exposureLines(10000, 12.5, 4, 2000) == 800); + assert(platina::exposureLines(100, 30, 4, 2000) == 4); + assert(platina::exposureLines(100000, 12.5, 4, 2000) == 2000); + assert(platina::exposureLines(100, 12, 4, 2000) == 8); + assert(platina::exposureLines(102, 12, 4, 2000) == 9); + assert(platina::exposureLines(std::numeric_limits::max(), .01, 1, 65535) == 65535); + assert(platina::sensorGain(8, 1, 4) == 4); + assert(platina::sensorGain(.5, 1, 8) == 1); + assert(platina::sensorGain(2.5, 1, 8) == 2.5); + assert(platina::sensorGain(std::numeric_limits::quiet_NaN(), 1, 8) == 1); + assert(platina::sensorGain(std::numeric_limits::infinity(), 1, 8) == 1); + + // Frame snapshots preserve their own manual request when later frames change. + platina::ExposureSettings settings; + assert(settings.automatic); + settings = {false, 25000, 2.5}; + const auto frame = settings; + settings = {true, 5000, 1}; + assert(!frame.automatic && frame.exposureUs == 25000 && frame.gain == 2.5); +} diff --git a/tests/camera_zoom.cpp b/tests/camera_zoom.cpp new file mode 100644 index 0000000..7fed9c4 --- /dev/null +++ b/tests/camera_zoom.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "platina_zoom.h" +#include +#include +#include + +int main() +{ + const std::string old = "1.1 1 1.14 1 1.89 1.61 90 1.5 40 30 0 25000 2.5"; + for (auto value : {"1", "1.5", "2", "2.5", "4", "8", "10"}) { + std::istringstream stream(old + " " + value); + assert(platina::zoomFromControls(stream) == std::stof(value)); + } + for (auto value : {"", "0", "0.99", "10.01", "nan", "inf", "broken"}) { + std::istringstream stream(old + " " + value); + assert(platina::zoomFromControls(stream) == 1); + } + std::istringstream truncated("1 1 1 1"); + assert(platina::zoomFromControls(truncated) == 1); + for (float zoom : {1.0f, 1.5f, 2.0f, 4.0f, 8.0f, 10.0f}) { + float low = platina::zoomCoordinate(0, zoom); + float high = platina::zoomCoordinate(1, zoom); + assert(low >= 0 && high <= 1); + assert(std::abs((high - low) - 1 / zoom) < 0.000001f); + assert(platina::zoomCoordinate(.5f, zoom) == .5f); + for (float x : {0.0f, .25f, .5f, 1.0f}) { + // All quarter-turn coordinate transforms use only x/y and 1-x/y. + assert(std::abs(platina::zoomCoordinate(1-x, zoom) - + (1-platina::zoomCoordinate(x, zoom))) < 0.000001f); + } + for (unsigned scale : {1U, 2U, 3U, 4U, 6U}) { + const unsigned w = (4024U / scale) & ~3U, h = (3016U / scale) & ~3U; + const auto crop = platina::centerCrop(w, h, zoom); + assert(crop.x * 2 + crop.width == w && crop.y * 2 + crop.height == h); + assert(crop.width % 4 == 0 && crop.height % 4 == 0); + assert(crop.x + crop.width <= w && crop.y + crop.height <= h); + assert(std::abs(double(crop.width) / w - 1 / zoom) < 4.0 / w); + if (zoom == 1) assert(crop.x == 0 && crop.y == 0 && crop.width == w && crop.height == h); + } + } +} diff --git a/tests/test_camera_control.py b/tests/test_camera_control.py new file mode 100644 index 0000000..ad2f0aa --- /dev/null +++ b/tests/test_camera_control.py @@ -0,0 +1,317 @@ +"""Capture lifetime, privacy defaults and HTTP/MQTT control regressions.""" +import importlib.util +import json +import os +from pathlib import Path +import queue +from types import SimpleNamespace +import tempfile +import threading +import unittest +from unittest.mock import Mock, patch +from urllib.error import HTTPError +from urllib.request import Request, urlopen +from http.server import ThreadingHTTPServer + +ROOT = Path(__file__).resolve().parents[1] + + +def module(name): + spec = importlib.util.spec_from_file_location(name, ROOT / 'project/camera/libcamera-headless' / (name + '.py')) + value = importlib.util.module_from_spec(spec) + spec.loader.exec_module(value) + return value + + +serve = module('serve') +mqtt = module('camera_mqtt') + + +class ControlTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + root = Path(self.tmp.name) + self.args = SimpleNamespace(config=root / 'settings.json', frame=root / 'run/frame.jpg', + capture='unused', cpu=False) + self.camera = serve.Camera(self.args) + self.audio = serve.Audio() + self.stop = threading.Event() + self.server = ThreadingHTTPServer(('127.0.0.1', 0), serve.make_handler(self.camera, self.stop, self.audio)) + self.server.daemon_threads = True + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.base = 'http://127.0.0.1:' + str(self.server.server_port) + + def tearDown(self): + self.stop.set() + self.server.shutdown() + self.server.server_close() + self.thread.join() + self.camera.stop() + self.audio.close() + self.tmp.cleanup() + + def get(self, path): + with urlopen(self.base + path, timeout=3) as response: + return json.load(response) + + def post(self, path, payload, origin=None): + headers = {'Content-Type': 'application/json'} + if origin: + headers['Origin'] = origin + request = Request(self.base + path, data=json.dumps(payload).encode(), headers=headers) + with urlopen(request, timeout=3) as response: + return json.load(response) + + def test_boot_off_and_reading_image_never_enables_capture(self): + self.assertEqual(self.get('/status')['state'], 'off') + for endpoint in ('/snapshot.jpg', '/stream.mjpg'): + with self.assertRaises(HTTPError) as error: + self.get(endpoint) + self.assertEqual(error.exception.code, 503) + self.assertIsNone(self.camera.capture) + + def test_settings_off_persist_but_capture_does_not(self): + self.post('/settings', {'focus': 430, 'quality': 10, 'scale': 1.5}) + self.post('/save', {}) + after = serve.Camera(self.args) + self.assertFalse(after.status()['enabled']) + self.assertEqual(after.settings['focus'], 430) + self.assertEqual(after.settings['quality'], 10) + self.assertEqual(after.settings['scale'], 1.5) + self.assertEqual(self.args.config.stat().st_mode & 0o777, 0o600) + self.assertIsNone(self.camera.focus_fd) + + def test_audio_requires_explicit_same_origin_ticket(self): + with patch.object(serve.subprocess, 'Popen') as popen: + with self.assertRaises(HTTPError) as error: + self.get('/audio.pcm') + self.assertEqual(error.exception.code, 409) + with self.assertRaises(HTTPError) as error: + self.post('/audio', {}, 'http://other.example') + self.assertEqual(error.exception.code, 403) + self.assertEqual(self.post('/audio', {})['rate'], 48000) + self.assertIsNone(self.audio.capture) + popen.assert_not_called() + + def test_invalid_partial_settings_are_atomic(self): + before = self.get('/settings') + with self.assertRaises(HTTPError): + self.post('/settings', {'quality': 9, 'focus': 999}) + self.assertEqual(self.get('/settings'), before) + with self.assertRaises(HTTPError): + self.post('/settings', {'scale': True}) + + def test_legacy_settings_migrate_without_writing_or_starting_capture(self): + legacy = {key: value for key, value in serve.DEFAULTS.items() + if key not in serve.EXPOSURE_DEFAULTS and key != 'zoom'} + legacy.update(focus=308, quality=40, automatic=False, scale=1.5) + original = json.dumps(legacy).encode() + self.args.config.write_bytes(original) + after = serve.Camera(self.args) + self.assertEqual(after.settings, dict(legacy, **serve.EXPOSURE_DEFAULTS, zoom=1.0)) + self.assertFalse(after.status()['enabled']) + self.assertEqual(self.args.config.read_bytes(), original) + # A partially missing new schema is corruption, not a legacy config. + self.args.config.write_text(json.dumps(dict(legacy, exposure_auto=False))) + with self.assertRaises(ValueError): + serve.Camera(self.args) + + def test_exposure_api_save_restore_and_control_wire_format(self): + desired = dict(exposure_auto=False, exposure_us=25000, analogue_gain=2.5) + self.post('/settings', desired) + self.post('/save', {}) + self.post('/settings', {'exposure_auto': True, 'exposure_us': 5000}) + restored = self.post('/restore', {}) + for key, value in desired.items(): + self.assertEqual(restored[key], value) + self.camera.controls(restored) + fields = Path(str(self.args.frame) + '.controls').read_text().split() + self.assertEqual(fields[-4:], ['0', '25000', '2.5', '1.0']) + self.assertEqual(serve.Camera(self.args).settings, restored) + self.assertFalse(self.camera.status()['enabled']) + + def test_exposure_validation_preserves_settings_on_rejection(self): + before = self.get('/settings') + for payload in ({'exposure_auto': 1}, {'exposure_us': 10000.5}, + {'exposure_us': True}, {'exposure_us': 99}, {'exposure_us': 100001}, + {'analogue_gain': 0}, {'analogue_gain': 8.01}, {'analogue_gain': float('nan')}): + with self.subTest(payload=payload): + with self.assertRaises(HTTPError): + self.post('/settings', payload) + self.assertEqual(self.get('/settings'), before) + + def test_mqtt_exposure_changes_are_acknowledged_saved_and_do_not_start_camera(self): + bridge = mqtt.Bridge.__new__(mqtt.Bridge) + bridge.camera = self.camera + bridge.command('exposure_us', '100000') + bridge.command('analogue_gain', '8') + bridge.command('exposure_auto', 'OFF') + self.assertEqual(self.camera.settings['exposure_us'], 100000) + self.assertEqual(self.camera.settings['analogue_gain'], 8) + self.assertFalse(self.camera.settings['exposure_auto']) + self.assertEqual(serve.Camera(self.args).settings, self.camera.settings) + for key, value in [('exposure_auto', 'true'), ('exposure_us', '100.1'), ('analogue_gain', 'inf')]: + with self.assertRaises(ValueError): + bridge.command(key, value) + self.assertFalse(self.camera.status()['enabled']) + + def test_discovery_separates_requested_controls_and_actual_telemetry(self): + entries = mqtt.discovery(dict(topic='platina/camera', device_id='platina', web_url='http://platina:8082/')) + entities = {topic.split('/')[-2]: payload for topic, payload in entries} + self.assertEqual(entities['exposure_us']['max'], 100000) + self.assertEqual(entities['analogue_gain']['min'], 1) + self.assertIn('settings.exposure_auto', entities['exposure_auto']['value_template']) + for key in ('exposure_us_actual', 'analogue_gain_actual'): + self.assertNotIn('command_topic', entities[key]) + self.assertNotIn('availability_topic', entities[key]) + self.assertEqual(entities[key]['availability_mode'], 'all') + self.assertIn("state == 'on'", entities[key]['availability'][1]['value_template']) + + def test_zoom_migrates_exposure_schema_without_changing_manual_exposure(self): + legacy = {key: value for key, value in serve.DEFAULTS.items() if key != 'zoom'} + legacy.update(exposure_auto=False, exposure_us=25000, analogue_gain=2.5, focus=308) + self.args.config.write_text(json.dumps(legacy)) + before = self.args.config.read_bytes() + after = serve.Camera(self.args) + self.assertEqual(after.settings, dict(legacy, zoom=1.0)) + self.assertEqual(self.args.config.read_bytes(), before) + self.assertFalse(after.status()['enabled']) + + def test_zoom_live_save_restore_and_mqtt_share_one_setting(self): + self.post('/settings', {'zoom': 2.5}) + self.post('/save', {}) + bridge = mqtt.Bridge.__new__(mqtt.Bridge) + bridge.camera = self.camera + bridge.command('zoom', '4') + self.assertEqual(self.get('/status')['settings']['zoom'], 4) + self.assertEqual(serve.Camera(self.args).settings['zoom'], 4) + self.post('/settings', {'zoom': 1}) + self.assertEqual(self.post('/restore', {})['zoom'], 4) + self.camera.controls(self.camera.settings) + self.assertEqual(Path(str(self.args.frame) + '.controls').read_text().split()[-1], '4.0') + self.assertFalse(self.get('/status')['enabled']) + + def test_zoom_validation_is_atomic(self): + before = self.get('/settings') + for value in [0.99, 10.01, True, '2', None, float('nan'), float('inf')]: + with self.subTest(value=value): + with self.assertRaises(HTTPError): + self.post('/settings', {'zoom': value, 'focus': 999}) + self.assertEqual(self.get('/settings'), before) + entries = mqtt.discovery(dict(topic='platina/camera', device_id='platina', web_url='http://platina:8082/')) + zoom = next(payload for topic, payload in entries if topic.endswith('/zoom/config')) + self.assertEqual((zoom['min'], zoom['max'], zoom['step']), (1, 10, .1)) + self.assertIn('settings.zoom', zoom['value_template']) + + def test_extended_zoom_and_fixed_target_fps(self): + self.post('/settings', {'zoom': 10, 'fps': 10}) + self.assertEqual(self.get('/settings')['zoom'], 10) + self.assertEqual(self.get('/settings')['fps'], 30) + self.post('/save', {}) + self.assertEqual(serve.Camera(self.args).settings['fps'], 30) + bridge = mqtt.Bridge.__new__(mqtt.Bridge) + bridge.camera = self.camera + bridge.command('fps', '15') + self.assertEqual(self.camera.settings['fps'], 30) + + def test_cross_origin_rejected(self): + with self.assertRaises(HTTPError) as error: + self.post('/camera', {'enabled': True}, 'http://other.example') + self.assertEqual(error.exception.code, 403) + self.assertFalse(self.get('/status')['enabled']) + + def test_stop_releases_lens_and_removes_last_frame(self): + frame = self.args.frame + frame.write_bytes(b'old private image') + lens = frame.with_name('lens') + lens.write_bytes(b'') + fd = os.open(lens, os.O_RDONLY) + child = Mock() + child.poll.return_value = None + self.camera.capture = child + self.camera.focus_fd = fd + self.post('/camera', {'enabled': False}) + child.terminate.assert_called_once() + child.wait.assert_called_once_with(timeout=8) + self.assertFalse(frame.exists()) + with self.assertRaises(OSError): + os.fstat(fd) + self.assertEqual(self.get('/status')['state'], 'off') + + def test_capture_failure_keeps_controls_available(self): + child = Mock() + child.poll.return_value = 1 + self.camera.capture = child + self.camera.tick() + self.assertEqual(self.get('/status')['state'], 'error') + self.post('/settings', {'focus': 320}) + self.assertEqual(self.get('/settings')['focus'], 320) + self.post('/camera', {'enabled': False}) + self.assertEqual(self.get('/status')['state'], 'off') + + def test_retained_mqtt_on_is_ignored(self): + bridge = mqtt.Bridge.__new__(mqtt.Bridge) + bridge.commands = queue.Queue() + message = SimpleNamespace(topic='platina/camera/set/enabled', payload=b'ON', retain=True) + bridge.on_message(None, None, message) + self.assertTrue(bridge.commands.empty()) + message.retain = False + bridge.on_message(None, None, message) + self.assertEqual(bridge.commands.get_nowait(), ('enabled', 'ON')) + + +class AudioTests(unittest.TestCase): + def test_ticket_never_opens_microphone_and_expires(self): + audio = serve.Audio() + with patch.object(serve.subprocess, 'Popen') as popen: + ticket = audio.ticket() + self.assertIsNone(audio.capture) + audio.tokens[ticket['token']] = 0 + with self.assertRaises(ValueError): + audio.open(ticket['token']) + with self.assertRaises(ValueError): + audio.open('not-authorized') + popen.assert_not_called() + + def test_capture_exclusive_single_use_and_restores_mixer(self): + audio = serve.Audio() + audio.command = Mock() + process = Mock() + process.poll.return_value = None + token = audio.ticket()['token'] + with patch.object(serve.Path, 'read_text', return_value='Xiaomi Mi 8 Lite'), \ + patch.object(serve.subprocess, 'Popen', return_value=process): + session = audio.open(token) + with self.assertRaises(ValueError): + audio.ticket() + with self.assertRaises(ValueError): + audio.open(token) + audio.release(session) + self.assertIsNone(audio.capture) + process.terminate.assert_called_once() + self.assertTrue(audio.released.is_set()) + self.assertEqual(audio.command.call_args.args[0][3:], ['restore', '0']) + self.assertFalse(Path(session[1].name).exists()) + + def test_failed_route_restores_original_mixer(self): + audio = serve.Audio() + audio.command = Mock(side_effect=[None, OSError('route failed'), None]) + with patch.object(serve.Path, 'read_text', return_value='Xiaomi Mi 8 Lite'): + with self.assertRaises(OSError): + audio.open(audio.ticket()['token']) + self.assertEqual(audio.command.call_args.args[0][3:], ['restore', '0']) + self.assertIsNone(audio.capture) + + def test_shutdown_revokes_unused_tickets(self): + audio = serve.Audio() + ticket = audio.ticket() + audio.close() + with self.assertRaises(ValueError): + audio.open(ticket['token']) + with self.assertRaises(ValueError): + audio.ticket() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_camera_exposure_native.py b/tests/test_camera_exposure_native.py new file mode 100644 index 0000000..53e9267 --- /dev/null +++ b/tests/test_camera_exposure_native.py @@ -0,0 +1,28 @@ +"""Exercise sensor conversion code used by the actual ARM64 IPA build.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class NativeExposureTests(unittest.TestCase): + @unittest.skipUnless(shutil.which('c++'), 'A C++ compiler is required for sensor conversion checks') + def test_sensor_line_conversion_and_gain_limits(self): + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / 'exposure' + subprocess.run(['c++', '-std=c++17', '-Wall', '-Wextra', '-Werror', + '-I' + str(ROOT / 'project/camera/libcamera-headless'), + str(ROOT / 'tests/camera_exposure.cpp'), '-o', str(binary)], check=True) + subprocess.run([str(binary)], check=True) + + @unittest.skipUnless(shutil.which('c++'), 'A C++ compiler is required for crop checks') + def test_zoom_coordinates_crop_geometry_and_wire_parser(self): + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / 'zoom' + subprocess.run(['c++', '-std=c++17', '-Wall', '-Wextra', '-Werror', + '-I' + str(ROOT / 'project/camera/libcamera-headless'), + str(ROOT / 'tests/camera_zoom.cpp'), '-o', str(binary)], check=True) + subprocess.run([str(binary)], check=True) diff --git a/tests/test_camera_lane_mapping.py b/tests/test_camera_lane_mapping.py new file mode 100644 index 0000000..a672ff2 --- /dev/null +++ b/tests/test_camera_lane_mapping.py @@ -0,0 +1,28 @@ +"""Keep Android lane descriptors distinct from the CSID hardware lane numbers.""" +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class CameraLaneMappingTests(unittest.TestCase): + def test_receiver_uses_the_stock_driver_translation(self): + reference = json.loads((ROOT / 'project/camera/reference.json').read_text()) + mapping = reference['lane_mapping'] + android = int(reference['android_reference_only']['csi']['lane_assignment'], 16) + # Xiaomi msm_csid.c translates each nibble through the hardware table. + translated = [mapping['stock_table'][(android >> (4 * lane)) & 15] + for lane in range(4)] + patch = (ROOT / 'ports/candidate/linux-postmarketos-qcom-sdm660/0032-platina-rear-camera.patch').read_text() + receiver = patch.split('platina_csiphy0_ep: endpoint {', 1)[1].split('remote-endpoint', 1)[0] + configured = [int(n) for n in re.search(r'data-lanes = <([^>]+)>', receiver)[1].split()] + self.assertEqual(configured, translated) + self.assertEqual(sum(n << (4 * i) for i, n in enumerate(configured)), + int(mapping['hardware_lane_assign'], 16)) + self.assertNotIn('clock-lanes', receiver) + + +if __name__ == '__main__': + unittest.main()