Reset public source after withdrawing credential-bearing release

This commit is contained in:
shihabal3amri committed 2026-09-25 13:38:35 +04:00
commit 3b67c80b0a
263 files changed
+34774

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
name: Connection, display or audio problem
description: Help us reproduce an issue on your head unit.
title: '[Bug] '
body:
- type: markdown
attributes:
value: 'Test while parked. Reports are public: review diagnostic files and remove personal information before attaching them. Never post credentials.'
- type: input
id: version
attributes: {label: DiPlay version, placeholder: '0.1.0'}
validations: {required: true}
- type: input
id: car
attributes: {label: Car and head-unit model, placeholder: 'Car model/year, DiLink version, Android version'}
validations: {required: true}
- type: input
id: phone
attributes: {label: iPhone model and exact iOS version}
validations: {required: true}
- type: dropdown
id: transport
attributes:
label: Connection
options: [Wireless, USB, Both]
validations: {required: true}
- type: textarea
id: reproduce
attributes:
label: What happened and how to reproduce it
description: 'Include expected behavior, steps, display settings and whether the car is also connected to a Wi-Fi network. For wireless, include the band/channel if the report shows it.'
validations: {required: true}
- type: textarea
id: diagnostics
attributes:
label: Diagnostic report or recording
description: 'Settings → Save diagnostic report; Android 10+ saves to Downloads/DiPlay. Attach the reviewed file here. If export fails, describe exactly when.'
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Installation and connection help
url: https://github.com/shihabal3amri/DiPlay/blob/main/docs/INSTALL.md
about: Read setup and troubleshooting steps first.
+35
View File
@@ -0,0 +1,35 @@
name: Android checks
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Reject credential files in public source
run: python3 scripts/check_public_tree.py
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '25'
- uses: android-actions/setup-android@v3
with:
packages: platform-tools platforms;android-37.0 build-tools;36.0.0 ndk;28.2.13676358
- uses: gradle/actions/setup-gradle@v4
- name: Unit tests, lint and source-only debug build
run: ./gradlew :shared:testDebugUnitTest :common:testDebugUnitTest :mobile:lintDebug :mobile:assembleDebug --stacktrace
- name: Test reports
if: always()
uses: actions/upload-artifact@v4
with:
name: test-reports
path: |
shared/build/reports/tests/
common/build/reports/tests/
mobile/build/reports/lint-results-debug.html
+28
View File
@@ -0,0 +1,28 @@
name: Publish download site
on:
push:
branches: [main]
paths: ['site/**', 'scripts/build_site.py', '.github/workflows/pages.yml']
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: true
jobs:
deploy:
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v4
- run: python3 scripts/build_site.py
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
path: site
- uses: actions/deploy-pages@v4
id: deployment
+40
View File
@@ -0,0 +1,40 @@
# Android Studio and local IDE state
.idea/
*.iml
.vscode/
# Gradle and local tooling
.gradle/
.kotlin/
build/
local.properties
# Native build output
.cxx/
.externalNativeBuild/
captures/
# Local agent working notes
/agent_docs/
# OS files
.DS_Store
Thumbs.db
*.log
/.idea
# Local beta credentials and release signing (never commit)
.private/
*.jks
*.keystore
release-signing.properties
# Never commit credential containers or installable distribution artifacts.
*.pk8
*.p7b
*.p12
*.pfx
*.pem
*.key
*.apk
*.aab
+10
View File
@@ -0,0 +1,10 @@
# Source reset — 2026-09-25
- Withdrew the 0.1.0 APK and removed its release tag.
- Reset the public branch after preserving restricted local incident records.
- Removed static synthetic test private keys; generate test identities at runtime.
- Removed automatic private-asset packaging and disabled the old release build script.
- Added a build guard rejecting credential asset files.
- Replaced the download site with a five-language suspension notice.
No replacement APK has been released. Existing copies cannot be recalled by a Git history reset.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+17
View File
@@ -0,0 +1,17 @@
# DiPlay
Independent CarPlay receiver research for Android head units, based on xcertplay with a DiAuto-style interface.
## Downloads suspended
The 0.1.0 APK was withdrawn because it bundled a recovered third-party accessory identity. Do not redistribute that APK or extract its identity for new builds. No replacement APK is available.
Public branch history has been reset to this reviewed source snapshot. The previous release and tag are removed; restricted local incident records are retained. Rewriting history does not recall downloaded copies or invalidate an exposed credential.
This source snapshot contains no accessory private-key files. Synthetic test identities are generated at test runtime. Automatic private-asset packaging has been removed and the build rejects credential asset files. A source-only build does not provide working standalone CarPlay without an authorized authentication design.
[Project status](https://shihabal3amri.github.io/DiPlay/) · [Build instructions](docs/BUILD.md) · [Security](SECURITY.md) · [Privacy](docs/PRIVACY.md)
## Credits
Based on [xcertplay](https://github.com/shilapi/xcertplay), GPL-3.0. Home/settings UI and website adapt [DiAuto](https://github.com/shihabal3amri/DiAuto), AGPL-3.0. License texts and attribution remain in this repository. CarPlay and its icon belong to Apple Inc. No affiliation with Apple or BYD is implied.
+7
View File
@@ -0,0 +1,7 @@
# DiPlay
APK 下载已暂停。0.1.0 版本包含提取自第三方固件的配件身份,现已撤下。请勿继续分发该 APK 或提取其中的身份用于新构建。目前没有替代 APK。
公开分支已重置为经过审查的源代码快照。删除历史记录不会撤回已下载的副本,也不会使已泄露的凭据失效。测试密钥现在在测试运行时生成,不再存储于仓库。
[项目状态](https://shihabal3amri.github.io/DiPlay/zh-Hans/) · [完整说明](README.md)
+15
View File
@@ -0,0 +1,15 @@
# Distribution suspended
The 0.1.0 APK was withdrawn after identifying exposure of a recovered third-party accessory private key bundled in the APK. Do not redistribute the APK or reuse that identity in new packages.
The public branch has been reset and the old release/tag removed. Restricted local release records and the original repository bundle are preserved for investigation. These steps reduce exposure through project-controlled links; they do not recall existing copies or revoke the credential.
A review of the original published Git objects found no copy of the exposed key in binary or common text encodings, including the private scalar. The original Git tree did contain a different synthetic test key; that file has also been removed. Tests now generate self-signed identities at runtime.
The Android APK-signing key is separate. No evidence of its publication was found in the audited source or release contents. Changing that signing key would not remediate the accessory-key exposure.
Do not include credentials, pairing records or personal information in public issues. Use GitHub private vulnerability reporting for sensitive findings. Credential revocation or replacement must be coordinated with the verified credential owner/provider; this project cannot declare those actions completed.
A future release requires authorized authentication provisioning. Obfuscating an already exposed shared key, encrypting it with a key shipped in the app, or rewriting Git history does not restore confidentiality.
GitHub guidance: https://docs.github.com/en/code-security/tutorials/remediate-leaked-secrets/remediating-a-leaked-secret
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

+1
View File
@@ -0,0 +1 @@
/build
+64
View File
@@ -0,0 +1,64 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "com.shilapi.xcertplay"
compileSdk {
version = release(37)
}
defaultConfig {
applicationId = "com.shilapi.xcertplay"
minSdk = 28
targetSdk = 37
versionCode = 1201
versionName = "1.2.1"
}
signingConfigs {
create("release") {
storeFile = file(
providers.environmentVariable("ANDROID_KEYSTORE_PATH")
.getOrElse("missing-release-keystore.jks"),
)
storePassword = providers.environmentVariable("ANDROID_KEYSTORE_PASSWORD").getOrElse("")
keyAlias = providers.environmentVariable("ANDROID_KEY_ALIAS").getOrElse("")
keyPassword = providers.environmentVariable("ANDROID_KEY_PASSWORD").getOrElse("")
}
}
buildTypes {
release {
optimization {
enable = false
}
signingConfig = signingConfigs.getByName("release")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildFeatures {
compose = true
}
}
dependencies {
implementation(project(":common"))
implementation(project(":shared"))
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.app.automotive)
implementation(libs.androidx.appcompat)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
debugImplementation(libs.androidx.compose.ui.tooling)
}
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- The library declares API 29 for AAOS distribution, but this app does not
use its API 29+ automotive hardware or renderer components. -->
<uses-sdk tools:overrideLibrary="androidx.car.app.automotive" />
<uses-feature
android:name="android.hardware.type.automotive"
android:required="true" />
<application
android:allowBackup="true"
android:appCategory="audio"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Xcertplay">
<!-- It declares support for Android Automotive OS. -->
<meta-data
android:name="com.android.automotive"
android:resource="@xml/automotive_app_desc" />
</application>
</manifest>
+12
View File
@@ -0,0 +1,12 @@
# Add project specific R8 rules here.
# AGP will combine all keep rule files in src/main/keepRules to pass to R8
#
# For more details, see
# https://d.android.com/r/tools/r8/keep-rules
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
@@ -0,0 +1,3 @@
<resources>
<bool name="config_advanced_audio_channel_mapping">true</bool>
</resources>
+5
View File
@@ -0,0 +1,5 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.compose) apply false
}
+38
View File
@@ -0,0 +1,38 @@
plugins {
id("com.android.library")
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "com.shilapi.xcertplay.host"
compileSdk {
version = release(37)
}
defaultConfig {
minSdk = 28
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildFeatures {
compose = true
}
}
dependencies {
api(project(":shared"))
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
testImplementation(libs.junit)
testImplementation("org.robolectric:robolectric:4.17")
}
+61
View File
@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application>
<activity android:name="com.shilapi.xcertplay.DiPlayActivity"
android:exported="true" android:launchMode="singleTop"
android:configChanges="density|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:theme="@style/Theme.Xcertplay">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.shilapi.xcertplay.DiPlaySessionService"
android:exported="false" android:foregroundServiceType="connectedDevice|microphone" />
<activity
android:name="com.shilapi.xcertplay.CarPlayHostActivity"
android:configChanges="density|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:exported="true"
android:launchMode="singleTask"
android:resizeableActivity="true"
android:screenOrientation="fullSensor"
android:theme="@style/Theme.Xcertplay"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/usb_device_filter" />
</activity>
<activity
android:name="com.shilapi.xcertplay.MainActivity"
android:exported="false"
android:theme="@style/Theme.Xcertplay" />
<activity
android:name="com.shilapi.xcertplay.ImageCropActivity"
android:exported="false"
android:screenOrientation="fullSensor"
android:theme="@style/Theme.Xcertplay" />
<receiver
android:name="com.shilapi.xcertplay.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -0,0 +1,587 @@
package com.shilapi.xcertplay
import android.content.Context
import android.os.Build
import com.shilapi.xcertplay.airplay.AirPlayDisplaySettings
import com.shilapi.xcertplay.airplay.AirPlayPhysicalSizeBasis
import com.shilapi.xcertplay.airplay.CarPlayDisplayScale
import com.shilapi.xcertplay.airplay.CarPlayUiScale
import com.shilapi.xcertplay.airplay.AirPlayIdentity
import com.shilapi.xcertplay.airplay.PairingStore
import com.shilapi.xcertplay.airplay.SafeAreaCodec
import com.shilapi.xcertplay.airplay.SafeAreaRect
import com.shilapi.xcertplay.orchestration.ManualHotspotBand
import com.shilapi.xcertplay.orchestration.ManualHotspotSecurity
import com.shilapi.xcertplay.orchestration.MfiTarget
import com.shilapi.xcertplay.orchestration.WirelessHotspotMode
import com.shilapi.xcertplay.transport.LockdownPairRecord
import java.io.File
/** SharedPreferences persistence for the accessory identity and paired controllers. */
object AirPlayPersistence {
private const val PREFS = "xcertplay_airplay"
private const val KEY_IDENT_PRIVATE = "identity_private"
private const val KEY_IDENT_PUBLIC = "identity_public"
private const val KEY_PAIRING_ID = "pairing_id"
private const val KEY_PAIRING_IDS = "pairing_ids"
private const val KEY_LOCKDOWN_HOST_ID = "lockdown_host_id"
private const val KEY_LOCKDOWN_SYSTEM_BUID = "lockdown_system_buid"
private const val KEY_LOCKDOWN_WIFI_MAC = "lockdown_wifi_mac"
private const val KEY_LOCKDOWN_DEVICE_PUBLIC = "lockdown_device_public"
private const val KEY_LOCKDOWN_DEVICE_CERT = "lockdown_device_cert"
private const val KEY_LOCKDOWN_HOST_PRIVATE = "lockdown_host_private"
private const val KEY_LOCKDOWN_HOST_CERT = "lockdown_host_cert"
private const val KEY_LOCKDOWN_ROOT_PRIVATE = "lockdown_root_private"
private const val KEY_LOCKDOWN_ROOT_CERT = "lockdown_root_cert"
private const val KEY_DISPLAY_SCALE_TENTHS = "display_scale_tenths"
private const val KEY_UI_SCALE_PERCENT = "ui_scale_percent"
private const val KEY_HEVC_ENABLED = "hevc_enabled"
private const val KEY_HEVC_SOFTWARE_DECODER = "hevc_software_decoder"
private const val KEY_ADVANCED_AUDIO_CHANNEL_MAPPING = "advanced_audio_channel_mapping"
private const val KEY_WIRELESS_ENABLED = "wireless_enabled"
private const val KEY_WIRELESS_HOTSPOT_MODE = "wireless_hotspot_mode"
private const val KEY_MANUAL_HOTSPOT_SSID = "manual_hotspot_ssid"
private const val KEY_MANUAL_HOTSPOT_PASSPHRASE = "manual_hotspot_passphrase"
private const val KEY_MANUAL_HOTSPOT_BAND = "manual_hotspot_band"
private const val KEY_MANUAL_HOTSPOT_CHANNEL = "manual_hotspot_channel"
private const val KEY_MANUAL_HOTSPOT_SECURITY = "manual_hotspot_security"
private const val KEY_DEBUG_LOGS_ENABLED = "debug_logs_enabled"
private const val KEY_MANUFACTURER = "manufacturer"
private const val KEY_MODEL = "model"
private const val KEY_OEM_LABEL = "oem_label"
private const val KEY_FPS = "display_fps"
private const val KEY_WIDTH_PHYSICAL_MM = "display_width_physical_mm"
private const val KEY_PHYSICAL_SIZE_BASIS = "display_physical_size_basis"
private const val KEY_MAX_DETECTED_WIDTH = "display_max_detected_width"
private const val KEY_MAX_DETECTED_HEIGHT = "display_max_detected_height"
private const val KEY_RIGHT_HAND_DRIVE = "right_hand_drive"
private const val KEY_HIDE_TOP_BAR = "hide_top_bar"
private const val KEY_HIDE_BOTTOM_BAR = "hide_bottom_bar"
private const val KEY_SAFE_AREA_DRAW_OUTSIDE = "safe_area_draw_outside"
private const val KEY_AUTO_START_ON_BOOT = "auto_start_on_boot"
private const val KEY_LOCATION_REPORTING_ENABLED = "location_reporting_enabled"
private const val KEY_MFI_TARGET = "mfi_target"
private const val KEY_MFI_I2C_PATH = "mfi_i2c_path"
private const val KEY_REMOTE_MFI_SERVER = "remote_mfi_server"
private const val KEY_REMOTE_MFI_TOKEN = "remote_mfi_token"
private const val SAFE_AREA_KEY_PREFIX = "safe_area_"
private const val CUSTOM_ICON_FILE = "airplay-icon.png"
const val DEFAULT_MANUFACTURER = "DiPlay"
const val DEFAULT_MODEL = "DiPlay"
const val DEFAULT_OEM_LABEL = ""
const val DEFAULT_MFI_I2C_PATH = "/dev/i2c-1"
fun loadDisplayScaleTenths(context: Context): Int {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return CarPlayDisplayScale.sanitize(
prefs.getInt(KEY_DISPLAY_SCALE_TENTHS, CarPlayDisplayScale.DEFAULT_TENTHS),
)
}
fun saveDisplayScaleTenths(context: Context, tenths: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putInt(KEY_DISPLAY_SCALE_TENTHS, CarPlayDisplayScale.sanitize(tenths))
.apply()
}
fun loadHevcEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_HEVC_ENABLED, false)
fun loadUiScalePercent(context: Context): Int = CarPlayUiScale.sanitize(
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getInt(KEY_UI_SCALE_PERCENT, CarPlayUiScale.DEFAULT),
)
fun saveUiScalePercent(context: Context, percent: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putInt(KEY_UI_SCALE_PERCENT, CarPlayUiScale.sanitize(percent)).apply()
}
fun saveHevcEnabled(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_HEVC_ENABLED, enabled)
.apply()
}
fun loadHevcSoftwareDecoderEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_HEVC_SOFTWARE_DECODER, false)
fun saveHevcSoftwareDecoderEnabled(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_HEVC_SOFTWARE_DECODER, enabled)
.apply()
}
fun loadAdvancedAudioChannelMapping(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_ADVANCED_AUDIO_CHANNEL_MAPPING, false)
fun saveAdvancedAudioChannelMapping(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_ADVANCED_AUDIO_CHANNEL_MAPPING, enabled)
.apply()
}
fun loadWirelessEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_WIRELESS_ENABLED, true)
fun saveWirelessEnabled(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_WIRELESS_ENABLED, enabled)
.apply()
}
fun loadMfiTarget(context: Context): MfiTarget {
val stored = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MFI_TARGET, null)
return MfiTarget.entries.firstOrNull { it.name == stored } ?: MfiTarget.LOCAL
}
fun saveMfiTarget(context: Context, target: MfiTarget) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MFI_TARGET, target.name)
.apply()
}
fun loadMfiI2cPath(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MFI_I2C_PATH, null)
?.takeIf { it.isNotBlank() }
?: DEFAULT_MFI_I2C_PATH
fun saveMfiI2cPath(context: Context, path: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MFI_I2C_PATH, path.trim())
.apply()
}
fun loadRemoteMfiServer(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_REMOTE_MFI_SERVER, null)
.orEmpty()
fun saveRemoteMfiServer(context: Context, server: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_REMOTE_MFI_SERVER, server)
.apply()
}
fun loadRemoteMfiToken(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_REMOTE_MFI_TOKEN, null)
.orEmpty()
fun saveRemoteMfiToken(context: Context, token: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_REMOTE_MFI_TOKEN, token)
.apply()
}
fun loadWirelessHotspotMode(context: Context): WirelessHotspotMode {
val stored = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_WIRELESS_HOTSPOT_MODE, null)
val mode = WirelessHotspotMode.entries.firstOrNull { it.name == stored }
?: WirelessHotspotMode.WIFI_P2P
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
mode == WirelessHotspotMode.WIFI_P2P
) {
WirelessHotspotMode.LOCAL_ONLY_HOTSPOT
} else {
mode
}
}
fun saveWirelessHotspotMode(context: Context, mode: WirelessHotspotMode) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_WIRELESS_HOTSPOT_MODE, mode.name)
.apply()
}
fun loadManualHotspotSsid(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MANUAL_HOTSPOT_SSID, null)
.orEmpty()
fun saveManualHotspotSsid(context: Context, ssid: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MANUAL_HOTSPOT_SSID, ssid)
.apply()
}
fun loadManualHotspotPassphrase(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MANUAL_HOTSPOT_PASSPHRASE, null)
.orEmpty()
fun saveManualHotspotPassphrase(context: Context, passphrase: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MANUAL_HOTSPOT_PASSPHRASE, passphrase)
.apply()
}
fun loadManualHotspotBand(context: Context): ManualHotspotBand {
val stored = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MANUAL_HOTSPOT_BAND, null)
return ManualHotspotBand.entries.firstOrNull { it.name == stored }
?: ManualHotspotBand.AUTO
}
fun saveManualHotspotBand(context: Context, band: ManualHotspotBand) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MANUAL_HOTSPOT_BAND, band.name)
.apply()
}
fun loadManualHotspotChannel(context: Context): Int =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getInt(KEY_MANUAL_HOTSPOT_CHANNEL, 0)
.coerceIn(0, 196)
fun saveManualHotspotChannel(context: Context, channel: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putInt(KEY_MANUAL_HOTSPOT_CHANNEL, channel.coerceIn(0, 196))
.apply()
}
fun loadManualHotspotSecurity(context: Context): ManualHotspotSecurity {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val stored = prefs.getString(KEY_MANUAL_HOTSPOT_SECURITY, null)
return ManualHotspotSecurity.entries.firstOrNull { it.name == stored }
?: if (loadManualHotspotPassphrase(context).isEmpty()) {
ManualHotspotSecurity.OPEN
} else {
ManualHotspotSecurity.WPA2
}
}
fun saveManualHotspotSecurity(context: Context, security: ManualHotspotSecurity) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MANUAL_HOTSPOT_SECURITY, security.name)
.apply()
}
fun loadDebugLogsEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_DEBUG_LOGS_ENABLED, false)
fun saveDebugLogsEnabled(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_DEBUG_LOGS_ENABLED, enabled)
.apply()
}
fun loadAutoStartOnBoot(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_AUTO_START_ON_BOOT, false)
fun saveAutoStartOnBoot(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_AUTO_START_ON_BOOT, enabled)
.apply()
}
fun loadLocationReportingEnabled(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_LOCATION_REPORTING_ENABLED, false)
fun saveLocationReportingEnabled(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_LOCATION_REPORTING_ENABLED, enabled)
.apply()
}
fun loadManufacturer(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MANUFACTURER, null)
?.takeIf { it.isNotBlank() }
?: DEFAULT_MANUFACTURER
fun saveManufacturer(context: Context, manufacturer: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MANUFACTURER, manufacturer)
.apply()
}
fun loadModel(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_MODEL, null)
?.takeIf { it.isNotBlank() }
?: DEFAULT_MODEL
fun saveModel(context: Context, model: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_MODEL, model)
.apply()
}
fun loadOemLabel(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_OEM_LABEL, DEFAULT_OEM_LABEL)
.orEmpty()
fun saveOemLabel(context: Context, oemLabel: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_OEM_LABEL, oemLabel)
.apply()
}
fun loadFps(context: Context): Int = AirPlayDisplaySettings.sanitizeFps(
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getInt(KEY_FPS, 30),
)
fun saveFps(context: Context, fps: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putInt(KEY_FPS, AirPlayDisplaySettings.sanitizeFps(fps))
.apply()
}
fun loadWidthPhysicalMm(context: Context): Int =
AirPlayDisplaySettings.sanitizeWidthPhysicalMm(
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getInt(
KEY_WIDTH_PHYSICAL_MM,
AirPlayDisplaySettings.DEFAULT_WIDTH_PHYSICAL_MM,
),
)
fun saveWidthPhysicalMm(context: Context, widthPhysicalMm: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putInt(
KEY_WIDTH_PHYSICAL_MM,
AirPlayDisplaySettings.sanitizeWidthPhysicalMm(widthPhysicalMm),
)
.apply()
}
fun loadPhysicalSizeBasis(context: Context): AirPlayPhysicalSizeBasis {
val stored = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_PHYSICAL_SIZE_BASIS, null)
return AirPlayPhysicalSizeBasis.entries.firstOrNull { it.name == stored }
?: AirPlayDisplaySettings.DEFAULT_PHYSICAL_SIZE_BASIS
}
fun savePhysicalSizeBasis(context: Context, basis: AirPlayPhysicalSizeBasis) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_PHYSICAL_SIZE_BASIS, basis.name)
.apply()
}
fun loadMaximumDetectedDisplay(context: Context): Pair<Int, Int> {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return prefs.getInt(KEY_MAX_DETECTED_WIDTH, 0) to
prefs.getInt(KEY_MAX_DETECTED_HEIGHT, 0)
}
fun saveMaximumDetectedDisplay(
context: Context,
widthPixels: Int,
heightPixels: Int,
) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putInt(KEY_MAX_DETECTED_WIDTH, widthPixels.coerceAtLeast(0))
.putInt(KEY_MAX_DETECTED_HEIGHT, heightPixels.coerceAtLeast(0))
.apply()
}
fun loadRightHandDrive(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_RIGHT_HAND_DRIVE, false)
fun saveRightHandDrive(context: Context, rightHandDrive: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_RIGHT_HAND_DRIVE, rightHandDrive)
.apply()
}
fun loadHideTopBar(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_HIDE_TOP_BAR, true)
fun saveHideTopBar(context: Context, hide: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_HIDE_TOP_BAR, hide)
.apply()
}
fun loadHideBottomBar(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_HIDE_BOTTOM_BAR, true)
fun saveHideBottomBar(context: Context, hide: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_HIDE_BOTTOM_BAR, hide)
.apply()
}
fun loadSafeAreaDrawOutside(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_SAFE_AREA_DRAW_OUTSIDE, true)
fun saveSafeAreaDrawOutside(context: Context, drawOutside: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_SAFE_AREA_DRAW_OUTSIDE, drawOutside)
.apply()
}
fun loadSafeAreaRect(context: Context, widthPixels: Int, heightPixels: Int): SafeAreaRect? {
require(widthPixels > 0 && heightPixels > 0) { "Activity dimensions must be positive" }
return SafeAreaCodec.decode(
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(safeAreaKey(widthPixels, heightPixels), null),
)
}
fun saveSafeAreaRect(
context: Context,
activityWidthPixels: Int,
activityHeightPixels: Int,
rect: SafeAreaRect,
commit: Boolean = false,
) {
require(activityWidthPixels > 0 && activityHeightPixels > 0) {
"Activity dimensions must be positive"
}
val editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(
safeAreaKey(activityWidthPixels, activityHeightPixels),
SafeAreaCodec.encode(rect.clampTo(activityWidthPixels, activityHeightPixels)),
)
if (commit) editor.commit() else editor.apply()
}
fun clearSafeAreaRect(
context: Context,
activityWidthPixels: Int,
activityHeightPixels: Int,
commit: Boolean = false,
) {
require(activityWidthPixels > 0 && activityHeightPixels > 0) {
"Activity dimensions must be positive"
}
val editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(safeAreaKey(activityWidthPixels, activityHeightPixels))
if (commit) editor.commit() else editor.apply()
}
fun loadCustomAirPlayIconFile(context: Context): File? =
File(context.filesDir, CUSTOM_ICON_FILE).takeIf { it.isFile }
fun saveCustomAirPlayIcon(context: Context, encodedImage: ByteArray) {
require(encodedImage.isNotEmpty()) { "AirPlay icon data must not be empty" }
File(context.filesDir, CUSTOM_ICON_FILE).outputStream().use { output ->
output.write(encodedImage)
}
}
fun clearCustomAirPlayIcon(context: Context) {
File(context.filesDir, CUSTOM_ICON_FILE).delete()
}
fun loadIdentity(context: Context): AirPlayIdentity {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val privateKey = prefs.getString(KEY_IDENT_PRIVATE, null)
val publicKey = prefs.getString(KEY_IDENT_PUBLIC, null)
val pairingId = prefs.getString(KEY_PAIRING_ID, null)
if (privateKey != null && publicKey != null && pairingId != null) {
return AirPlayIdentity(privateKey.decodeHex(), publicKey.decodeHex(), pairingId)
}
return AirPlayIdentity.generate().also { identity ->
prefs.edit()
.putString(KEY_IDENT_PRIVATE, identity.privateKey.toHex())
.putString(KEY_IDENT_PUBLIC, identity.publicKey.toHex())
.putString(KEY_PAIRING_ID, identity.pairingId)
.apply()
}
}
fun loadPairings(context: Context, onSave: (String, ByteArray) -> Unit): PairingStore {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val store = PairingStore(onSave)
for (identifier in prefs.getStringSet(KEY_PAIRING_IDS, emptySet()).orEmpty()) {
prefs.getString("pairing.$identifier", null)?.let { store.save(identifier, it.decodeHex()) }
}
return store
}
fun savePairing(context: Context, identifier: String, longTermPublicKey: ByteArray) {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val identifiers = prefs.getStringSet(KEY_PAIRING_IDS, emptySet()).orEmpty().toMutableSet()
identifiers.add(identifier)
prefs.edit()
.putString("pairing.$identifier", longTermPublicKey.toHex())
.putStringSet(KEY_PAIRING_IDS, identifiers)
.apply()
}
fun loadLockdownRecord(context: Context): LockdownPairRecord? {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val hostId = prefs.getString(KEY_LOCKDOWN_HOST_ID, null) ?: return null
val systemBuid = prefs.getString(KEY_LOCKDOWN_SYSTEM_BUID, null) ?: return null
val wifiMac = prefs.getString(KEY_LOCKDOWN_WIFI_MAC, null) ?: return null
val devicePublic = prefs.getString(KEY_LOCKDOWN_DEVICE_PUBLIC, null) ?: return null
val deviceCert = prefs.getString(KEY_LOCKDOWN_DEVICE_CERT, null) ?: return null
val hostPrivate = prefs.getString(KEY_LOCKDOWN_HOST_PRIVATE, null) ?: return null
val hostCert = prefs.getString(KEY_LOCKDOWN_HOST_CERT, null) ?: return null
val rootPrivate = prefs.getString(KEY_LOCKDOWN_ROOT_PRIVATE, null) ?: return null
val rootCert = prefs.getString(KEY_LOCKDOWN_ROOT_CERT, null) ?: return null
return try {
LockdownPairRecord.restore(
hostId = hostId,
systemBuid = systemBuid,
wifiMacAddress = wifiMac,
devicePublicKeyPem = devicePublic.decodeHex(),
deviceCertificatePem = deviceCert.decodeHex(),
hostPrivateKeyPem = hostPrivate.decodeHex(),
hostCertificatePem = hostCert.decodeHex(),
rootPrivateKeyPem = rootPrivate.decodeHex(),
rootCertificatePem = rootCert.decodeHex(),
)
} catch (_: Exception) {
null
}
}
fun saveLockdownRecord(context: Context, record: LockdownPairRecord) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(KEY_LOCKDOWN_HOST_ID, record.hostId)
.putString(KEY_LOCKDOWN_SYSTEM_BUID, record.systemBuid)
.putString(KEY_LOCKDOWN_WIFI_MAC, record.wifiMacAddress)
.putString(KEY_LOCKDOWN_DEVICE_PUBLIC, record.devicePublicKeyPem.toHex())
.putString(KEY_LOCKDOWN_DEVICE_CERT, record.deviceCertificatePem.toHex())
.putString(KEY_LOCKDOWN_HOST_PRIVATE, record.hostPrivateKeyPem.toHex())
.putString(KEY_LOCKDOWN_HOST_CERT, record.hostCertificatePem.toHex())
.putString(KEY_LOCKDOWN_ROOT_PRIVATE, record.rootPrivateKeyPem.toHex())
.putString(KEY_LOCKDOWN_ROOT_CERT, record.rootCertificatePem.toHex())
.apply()
}
fun clearLockdownRecord(context: Context) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(KEY_LOCKDOWN_HOST_ID)
.remove(KEY_LOCKDOWN_SYSTEM_BUID)
.remove(KEY_LOCKDOWN_WIFI_MAC)
.remove(KEY_LOCKDOWN_DEVICE_PUBLIC)
.remove(KEY_LOCKDOWN_DEVICE_CERT)
.remove(KEY_LOCKDOWN_HOST_PRIVATE)
.remove(KEY_LOCKDOWN_HOST_CERT)
.remove(KEY_LOCKDOWN_ROOT_PRIVATE)
.remove(KEY_LOCKDOWN_ROOT_CERT)
.apply()
}
private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it.toInt() and 0xff) }
private fun String.decodeHex(): ByteArray {
require(length % 2 == 0) { "hex string must have even length" }
return ByteArray(length / 2) { index ->
substring(index * 2, index * 2 + 2).toInt(16).toByte()
}
}
private fun safeAreaKey(widthPixels: Int, heightPixels: Int): String =
"$SAFE_AREA_KEY_PREFIX${widthPixels}x$heightPixels"
}
@@ -0,0 +1,31 @@
package com.shilapi.xcertplay
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
/** Starts the CarPlay host after boot when the user has enabled the startup option. */
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
if (!AirPlayPersistence.loadAutoStartOnBoot(context)) return
val launch = Intent(context, DiPlayActivity::class.java).apply {
addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TOP or
Intent.FLAG_ACTIVITY_SINGLE_TOP,
)
}
try {
context.startActivity(launch)
} catch (error: RuntimeException) {
Log.w(TAG, "Boot auto-start could not launch CarPlayHostActivity", error)
}
}
private companion object {
const val TAG = "xcertplay-boot"
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,6 @@
package com.shilapi.xcertplay
import android.content.res.Configuration
internal fun isDarkMode(uiMode: Int): Boolean =
uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
@@ -0,0 +1,521 @@
// SPDX-License-Identifier: AGPL-3.0-only
// UI copy and visual language adapted from DiAuto. See docs/THIRD_PARTY_NOTICES.md.
package com.shilapi.xcertplay
import android.Manifest
import android.app.AlertDialog
import android.bluetooth.BluetoothManager
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.shilapi.xcertplay.host.R
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** DiAuto's visual language, with a connection flow for an independent CarPlay receiver. */
class DiPlayActivity : ComponentActivity() {
private val handler = Handler(Looper.getMainLooper())
private var page = "home"
private var setupError: String? = null
private var status: TextView? = null
private var connectButton: Button? = null
private var disconnectButton: Button? = null
private var lastRunning: Boolean? = null
private var pendingWireless = false
private var initialLaunch = true
private var notificationTransport = true
private var exportInProgress = false
private var exportButton: Button? = null
private val notificationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
connect(notificationTransport)
}
private val tick = object : Runnable {
override fun run() { refreshStatus(); handler.postDelayed(this, 1000) }
}
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) choosePhone() else permissionHelp("Nearby devices", "Allow Nearby devices so DiPlay can connect to your paired iPhone.")
}
private val export = registerForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri ->
if (uri != null) exportDiagnostics(uri)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, true)
window.statusBarColor = BG; window.navigationBarColor = BG
WindowInsetsControllerCompat(window, window.decorView).apply {
isAppearanceLightStatusBars = false
hide(WindowInsetsCompat.Type.statusBars())
}
setupError = runCatching { DiPlayBootstrap.ensure(this) }.exceptionOrNull()?.let {
"Local setup could not finish. Reinstall the complete DiPlay beta APK and try again."
}
page = savedInstanceState?.getString("page") ?: intent.getStringExtra("page") ?: "home"
render()
handleWirelessRecovery()
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (page != "home") { page = "home"; render() }
else { isEnabled = false; onBackPressedDispatcher.onBackPressed(); isEnabled = true }
}
})
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent); setIntent(intent)
page = intent.getStringExtra("page") ?: "home"; render()
handleWirelessRecovery()
}
override fun onSaveInstanceState(outState: Bundle) { outState.putString("page", page); super.onSaveInstanceState(outState) }
override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig); render() }
override fun onResume() {
super.onResume(); handler.removeCallbacks(tick); handler.post(tick)
if (initialLaunch) {
initialLaunch = false
if (setupError == null && !CarPlayBackgroundSession.hasSession() &&
DiPlayPreferences.autoConnect(this) && intent.getStringExtra("page") == null) {
handler.post { connect(AirPlayPersistence.loadWirelessEnabled(this)) }
}
}
}
override fun onPause() { handler.removeCallbacks(tick); super.onPause() }
private fun render() {
status = null; connectButton = null; disconnectButton = null; lastRunning = null
val scroll = ScrollView(this).apply { setBackgroundColor(BG); isFillViewport = true; clipToPadding = false }
val content = column().apply { setPadding(dp(32), dp(24), dp(32), dp(32)) }
scroll.addView(content)
val header = row().apply { gravity = Gravity.CENTER_VERTICAL }
header.addView(ImageView(this).apply { setImageResource(R.drawable.ic_carplay); contentDescription = "CarPlay" }, LinearLayout.LayoutParams(dp(36), dp(36)))
header.addView(label("DiPlay", 26, TEXT, true).apply { setPadding(dp(12), 0, 0, 0) }, LinearLayout.LayoutParams(0, dp(56), 1f))
header.addView(button(if (page == "home") "Car home" else "Back", false) {
if (page == "home") startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME))
else { page = "home"; render() }
}, LinearLayout.LayoutParams(dp(130), dp(56)))
content.addView(header)
content.addView(space(24))
when (page) {
"settings" -> settings(content)
"about" -> about(content)
else -> home(content)
}
setContentView(scroll)
refreshStatus()
}
private fun home(content: LinearLayout) {
val wide = resources.configuration.screenWidthDp >= 850
val body = column()
val left = column()
left.addView(label("YOUR PHONE. YOUR DRIVE.", 12, ACCENT, true).apply { letterSpacing = .16f })
left.addView(label("A familiar drive.", if (wide) 42 else 36, TEXT, true).apply { setPadding(0, dp(12), 0, dp(10)) })
left.addView(label("Your maps, music and conversations.\nCarPlay, right here on your car display.", 19, MUTED))
val card = card()
card.addView(label("WIRELESS CARPLAY", 12, ACCENT, true).apply { letterSpacing = .12f })
status = label("Ready when you are", 24, TEXT, true).apply { setPadding(0, dp(10), 0, dp(16)) }
card.addView(status)
connectButton = button("Connect phone", true) {
if (CarPlayBackgroundSession.hasSession()) openProjection()
else connect(true)
}
card.addView(connectButton, matchButton())
card.addView(label("Pair your iPhone with the car’s Bluetooth, then connect.\nKeep Bluetooth and Wi-Fi on.", 15, MUTED).apply { setPadding(0, dp(14), 0, 0) })
card.addView(button("Choose iPhone", false) { choosePhone() }, matchButton(16, 56))
disconnectButton = button("Disconnect", false) {
disconnectButton?.isEnabled = false
CarPlayBackgroundSession.stop { runOnUiThread { refreshStatus() } }
}.apply { visibility = View.GONE }
card.addView(disconnectButton, matchButton(10, 56))
val right = column().apply { gravity = Gravity.CENTER_HORIZONTAL }
val logo = ImageView(this).apply {
setImageResource(R.drawable.ic_carplay)
contentDescription = "CarPlay icon"
scaleType = ImageView.ScaleType.FIT_CENTER
}
val branding = column().apply {
gravity = Gravity.CENTER
addView(logo, LinearLayout.LayoutParams(dp(96), dp(96)))
}
right.addView(button("Connect with USB", false) { connect(false) }, matchButton())
right.addView(label("Plug your iPhone into a USB data port.\nAllow CarPlay when your iPhone asks.", 14, MUTED).apply { gravity = Gravity.CENTER; setPadding(dp(8), dp(10), dp(8), dp(24)) })
right.addView(button("Settings", false) { page = "settings"; render() }, matchButton())
right.addView(label("Make DiPlay feel right for your car.", 14, MUTED).apply { gravity = Gravity.CENTER; setPadding(0, dp(10), 0, dp(24)) })
right.addView(label("PUBLIC PREVIEW · ${version()}", 12, MUTED).apply { letterSpacing = .08f })
if (wide) {
// Both rows share column widths. The USB button starts at the wireless
// card's top edge, independently of hero wrapping or font scaling.
fun columns(first: View, second: View, stretchSecond: Boolean = false) = row().apply {
gravity = Gravity.TOP
addView(first, LinearLayout.LayoutParams(0, -2, 1.6f))
addView(space(40), LinearLayout.LayoutParams(dp(40), 1))
addView(second, LinearLayout.LayoutParams(0, if (stretchSecond) -1 else -2, 1f))
}
body.addView(columns(left, branding, true))
body.addView(space(26))
body.addView(columns(card, right))
} else {
body.addView(left)
body.addView(space(26))
body.addView(card)
body.addView(space(26))
body.addView(branding)
body.addView(space(24))
body.addView(right)
}
setupError?.let { body.addView(label(it, 16, WARNING).apply { setPadding(0, dp(16), 0, 0) }) }
content.addView(body)
}
private fun settings(content: LinearLayout) {
content.addView(label("Your drive, your way.", 34, TEXT, true))
content.addView(label("Apply reconnects CarPlay for icon size, resolution and frame rate. Other changes apply to your next connection.", 17, MUTED).apply { setPadding(0, dp(8), 0, dp(24)) })
section(content, "Automatic connection") { card ->
toggle(card, "Connect when DiPlay opens", "Use your last connection type and selected iPhone.", DiPlayPreferences.autoConnect(this)) { DiPlayPreferences.saveAutoConnect(this, it) }
toggle(card, "Open after the car starts", "Availability depends on your head unit’s startup settings.", AirPlayPersistence.loadAutoStartOnBoot(this)) { AirPlayPersistence.saveAutoStartOnBoot(this, it) }
card.addView(button("Choose iPhone · ${DiPlayPreferences.phoneName(this)}", false) { choosePhone() }, matchButton(12, 60))
}
section(content, "Display and performance") { card ->
iconSizeControl(card)
choice(card, "Resolution", listOf("Native", "80% · lighter load", "60% · lightest load"), listOf(10, 8, 6).indexOf(AirPlayPersistence.loadDisplayScaleTenths(this)).coerceAtLeast(0)) { AirPlayPersistence.saveDisplayScaleTenths(this, listOf(10, 8, 6)[it]) }
choice(card, "Frame rate", listOf("30 fps · lighter load", "60 fps · smoother motion"), if (AirPlayPersistence.loadFps(this) == 60) 1 else 0) { AirPlayPersistence.saveFps(this, if (it == 1) 60 else 30) }
toggle(card, "Efficient video", "Use HEVC. Leave off for the widest head-unit compatibility.", AirPlayPersistence.loadHevcEnabled(this)) { AirPlayPersistence.saveHevcEnabled(this, it) }
toggle(card, "Right-hand drive", "Place CarPlay’s controls closer to the driver.", AirPlayPersistence.loadRightHandDrive(this)) { AirPlayPersistence.saveRightHandDrive(this, it) }
toggle(card, "Full screen", "Hide the car’s system bars while CarPlay is open.", AirPlayPersistence.loadHideTopBar(this) && AirPlayPersistence.loadHideBottomBar(this)) {
AirPlayPersistence.saveHideTopBar(this, it); AirPlayPersistence.saveHideBottomBar(this, it)
}
}
section(content, "Permissions and connection help") { card ->
card.addView(label("Nearby devices connects your iPhone. Microphone enables Siri and calls. Older Android versions also require Location for wireless setup. USB mode may ask for a local VPN connection.", 16, MUTED))
card.addView(button("App permissions", false) { openSystem(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))) }, matchButton(16, 60))
card.addView(button("Bluetooth settings", false) { openSystem(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) }, matchButton(10, 60))
card.addView(button("Wireless connection help", false) { wirelessHelp() }, matchButton(10, 60))
}
section(content, "About and diagnostics") { card ->
card.addView(button("About DiPlay", false) { page = "about"; render() }, matchButton(0, 60))
exportButton = button(if (exportInProgress) "Saving report…" else "Save diagnostic report", false) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) exportDiagnostics()
else chooseReportDestination()
}.apply { isEnabled = !exportInProgress }
card.addView(exportButton, matchButton(10, 60))
val destination = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) "Reports save to Downloads/DiPlay. " else "Choose where to save your report. "
card.addView(label(destination + "Nothing is sent automatically. Protocol payloads and credentials are excluded.", 14, MUTED).apply { setPadding(0, dp(12), 0, 0) })
}
}
private fun about(content: LinearLayout) {
content.addView(label("DiPlay", 40, TEXT, true))
content.addView(label("CarPlay, at home in your car.", 20, MUTED).apply { setPadding(0, dp(8), 0, dp(24)) })
section(content, "Public preview · ${version()}") { card ->
card.addView(label("An independent CarPlay receiver for Android head units. Wired and wireless connections run on the head unit, with local authentication. A standard iPhone can connect without a jailbreak, Mac, dongle or sign-in.\n\nThis preview uses an experimental accessory identity. Compatibility with every iPhone and head unit is still being tested. It is not an Apple-certified product.", 17, TEXT))
}
section(content, "Made possible by open source") { card ->
card.addView(label("Receiver based on xcertplay, licensed under GPL-3.0. DiPlay’s interface follows DiAuto’s design, licensed under AGPL-3.0.\n\nIncludes AndroidX, Bouncy Castle, JmDNS and SLF4J. Source and license notices accompany this release.\n\nCarPlay and the CarPlay icon belong to Apple Inc. DiPlay is an independent project.", 16, MUTED))
}
}
private fun iconSizeControl(parent: LinearLayout) {
val presets = com.shilapi.xcertplay.airplay.CarPlayUiScale.presets
fun label(percent: Int) = com.shilapi.xcertplay.airplay.CarPlayUiScale.label(percent)
val control = button("Icon and text size · ${label(AirPlayPersistence.loadUiScalePercent(this))}", false) {}
control.setOnClickListener {
val current = AirPlayPersistence.loadUiScalePercent(this)
var selection = presets.indexOf(current)
AlertDialog.Builder(this).setTitle("CarPlay icon and text size")
.setSingleChoiceItems(arrayOf("Smaller · 75%", "Small · 85%", "Default", "Large · 115%"), selection) { _, index -> selection = index }
.setPositiveButton(if (CarPlayBackgroundSession.hasSession()) "Apply and reconnect" else "Save") { _, _ ->
val selected = presets[selection]
DisplayDiagnosticSnapshot.selection(this, current, selected,
selected != current && CarPlayBackgroundSession.hasSession())
AirPlayPersistence.saveUiScalePercent(this, selected)
control.text = "Icon and text size · ${label(selected)}"
if (selected != current && CarPlayBackgroundSession.hasSession()) {
connect(AirPlayPersistence.loadWirelessEnabled(this))
}
}.setNegativeButton("Cancel", null).show()
}
parent.addView(control, matchButton(0, 60))
parent.addView(label("Smaller sizes use more processing power. Choose Default if playback slows. Applying a size reconnects CarPlay.", 14, MUTED).apply {
setPadding(0, dp(8), 0, dp(18))
})
}
private fun connect(wireless: Boolean) {
if (setupError != null) { toast(setupError!!); return }
if (wireless && DiPlayPreferences.phoneAddress(this) == null) {
pendingWireless = true; choosePhone(); return
}
val preferences = getSharedPreferences("diplay", MODE_PRIVATE)
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED && !preferences.getBoolean("notification_asked", false)) {
preferences.edit().putBoolean("notification_asked", true).apply()
notificationTransport = wireless
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
return
}
val open = {
AirPlayPersistence.saveWirelessEnabled(this, wireless)
openProjection()
}
if (CarPlayBackgroundSession.hasSession()) CarPlayBackgroundSession.stop { runOnUiThread { open() } }
else open()
}
private fun openProjection() {
startActivity(Intent(this, CarPlayHostActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
}
private fun choosePhone() {
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
bluetoothPermission.launch(Manifest.permission.BLUETOOTH_CONNECT); return
}
val adapter = getSystemService(BluetoothManager::class.java)?.adapter
if (adapter == null || !adapter.isEnabled) {
AlertDialog.Builder(this).setTitle("Turn on Bluetooth")
.setMessage("Enable the car’s Bluetooth and pair your iPhone first.")
.setPositiveButton("Open Bluetooth") { _, _ -> openSystem(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) }
.setNegativeButton("Later", null).show(); return
}
val devices = runCatching { adapter.bondedDevices.sortedBy { it.name ?: "" } }.getOrDefault(emptyList())
if (devices.isEmpty()) {
AlertDialog.Builder(this).setTitle("Pair your iPhone")
.setMessage("On your iPhone, open Settings → Bluetooth and pair with the car. Then return to DiPlay and choose Connect phone.")
.setPositiveButton("Open Bluetooth") { _, _ -> openSystem(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) }
.setNegativeButton("Got it", null).show(); return
}
AlertDialog.Builder(this).setTitle("Choose your iPhone")
.setItems(devices.map { device ->
val name = device.name ?: "Paired device"
if (devices.count { it.name == device.name } > 1) "$name · ${device.address.takeLast(5)}" else name
}.toTypedArray()) { _, index ->
val device = devices[index]
DiPlayPreferences.savePhone(this, device.address, device.name ?: "iPhone")
val start = pendingWireless; pendingWireless = false
render()
if (start) connect(true)
}.setNeutralButton("Pair another") { _, _ -> openSystem(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) }
.setNegativeButton("Cancel") { _, _ -> pendingWireless = false }.show()
}
private fun wirelessHelp() {
AlertDialog.Builder(this).setTitle("Wireless connection help")
.setMessage("Pair your iPhone with the car’s Bluetooth, keep Wi-Fi on, and allow CarPlay on the iPhone. Close any other phone-projection app.\n\nIf a previous projection app left its connection running, reset CarPlay Wi-Fi below and connect again. Your car’s normal internet Wi-Fi stays on.")
.setPositiveButton("Got it", null)
.setNeutralButton("Reset CarPlay Wi-Fi") { _, _ ->
confirmWirelessReset()
}.show()
}
private fun handleWirelessRecovery() {
if (page != "wireless-recovery") return
page = "home"; render()
confirmWirelessReset()
}
private fun confirmWirelessReset() {
AlertDialog.Builder(this).setTitle("Reset CarPlay Wi-Fi?")
.setMessage("This ends the existing Wi-Fi Direct connection, including one left behind after reinstalling. Close other projection apps first. Your car’s internet Wi-Fi stays on.")
.setPositiveButton("Reset and connect") { _, _ ->
CarPlayBackgroundSession.stop { runOnUiThread { resetWirelessGroup() } }
}.setNegativeButton("Cancel", null).show()
}
private fun resetWirelessGroup() {
val manager = getSystemService(android.net.wifi.p2p.WifiP2pManager::class.java)
if (manager == null) { toast("This head unit does not support Wi-Fi Direct."); return }
val channel = manager.initialize(this, mainLooper, null)
try {
manager.requestGroupInfo(channel) { group ->
if (group == null) { channel.close(); connect(true); return@requestGroupInfo }
manager.removeGroup(channel, object : android.net.wifi.p2p.WifiP2pManager.ActionListener {
override fun onSuccess() {
val deadline = android.os.SystemClock.elapsedRealtime() + 4000
fun waitUntilRemoved() {
manager.requestGroupInfo(channel) { remaining ->
when {
remaining == null -> { channel.close(); if (!isFinishing && !isDestroyed) connect(true) }
android.os.SystemClock.elapsedRealtime() >= deadline -> {
channel.close(); toast("Wi-Fi Direct is still busy. Close the other projection app and try again.")
}
else -> handler.postDelayed({ waitUntilRemoved() }, 200)
}
}
}
waitUntilRemoved()
}
override fun onFailure(reason: Int) { channel.close(); toast("Could not reset Wi-Fi Direct. Close the other projection app and try again.") }
})
}
} catch (_: SecurityException) {
channel.close(); permissionHelp("Wireless permissions", "Allow Nearby devices and, on older Android versions, Location before resetting CarPlay Wi-Fi.")
}
}
private fun refreshStatus() {
val running = CarPlayBackgroundSession.hasSession()
status?.text = when {
setupError != null -> "Setup needs attention"
CarPlayBackgroundSession.active -> "CarPlay connected"
running -> "Connecting to your iPhone…"
DiPlayPreferences.phoneAddress(this) != null -> "Ready for ${DiPlayPreferences.phoneName(this)}"
else -> "Ready when you are"
}
if (lastRunning != running) {
connectButton?.text = if (running) "Open CarPlay" else "Connect phone"
disconnectButton?.visibility = if (running) View.VISIBLE else View.GONE
disconnectButton?.isEnabled = true
lastRunning = running
}
connectButton?.isEnabled = setupError == null
}
private fun reportFileName() = "DiPlay-${SimpleDateFormat("yyyyMMdd-HHmmss-SSS", Locale.US).format(Date())}.txt"
private fun chooseReportDestination() {
// Some head units omit or disable DocumentsUI. Launch itself can throw, before
// the result callback and the background writer's exception handler ever run.
runCatching { export.launch(reportFileName()) }.onFailure {
toast(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
"This head unit could not open a save location. Please try saving to Downloads again."
else "This head unit has no available file picker to save the report.")
}
}
private fun exportDiagnostics(uri: Uri? = null) {
if (exportInProgress) return
exportInProgress = true
exportButton?.apply { isEnabled = false; text = "Saving report…" }
val appContext = applicationContext
val fileName = reportFileName()
Thread({
val result = runCatching {
val report = buildString {
appendLine("DiPlay ${version()} · private beta diagnostic report")
appendLine("Android ${Build.VERSION.RELEASE} / API ${Build.VERSION.SDK_INT}")
appendLine("Head unit: ${Build.MANUFACTURER} ${Build.MODEL}")
appendLine("Connection: ${if (AirPlayPersistence.loadWirelessEnabled(appContext)) "wireless" else "USB"}")
appendLine("Authentication: local experimental beta identity; no remote fallback")
appendLine("Saved video preference (may differ from active session): ${if (AirPlayPersistence.loadHevcEnabled(appContext)) "HEVC" else "H.264"}; ${AirPlayPersistence.loadFps(appContext)} fps")
appendLine("Icon and text size: ${com.shilapi.xcertplay.airplay.CarPlayUiScale.label(AirPlayPersistence.loadUiScalePercent(appContext))}")
appendLine("Saved resolution preference (may differ from active session): ${AirPlayPersistence.loadDisplayScaleTenths(appContext) * 10}%")
appendLine("Session: ${if (CarPlayBackgroundSession.active) "active" else if (CarPlayBackgroundSession.hasSession()) "connecting" else "stopped"}")
appendLine("Head-unit board: ${Build.BOARD}; hardware: ${Build.HARDWARE}; build: ${Build.DISPLAY}")
appendLine()
appendLine("--- Last display negotiation (timestamps distinguish it from current settings) ---")
appendLine(DisplayDiagnosticSnapshot.report(appContext))
appendLine()
for (name in SessionLogFile.REPORT_NAMES) {
val file = File(appContext.filesDir, "logs/$name")
if (file.isFile) {
appendLine("--- $name ---")
file.useLines { lines -> lines.forEach { line -> DiagnosticRedactor.redact(line)?.let { appendLine(it) } } }
}
}
}
if (uri != null) DiagnosticExportStore.write(appContext.contentResolver, uri, report)
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
DiagnosticExportStore.saveToDownloads(appContext.contentResolver, fileName, report)
} else error("A save location is required")
}
runOnUiThread {
exportInProgress = false
if (isFinishing || isDestroyed) return@runOnUiThread
exportButton?.apply { isEnabled = true; text = "Save diagnostic report" }
if (result.isSuccess) {
AlertDialog.Builder(this).setTitle("Diagnostic report saved")
.setMessage(if (uri == null) "Downloads/DiPlay/$fileName" else "Your report was saved to the selected location.")
.setPositiveButton("Done", null).show()
} else {
AlertDialog.Builder(this).setTitle("Could not save the report")
.setMessage("Check that storage is available, or choose another save location.")
.setPositiveButton("Choose location") { _, _ -> chooseReportDestination() }
.setNegativeButton("Close", null).show()
}
}
}, "diplay-export").start()
}
private fun permissionHelp(title: String, body: String) {
AlertDialog.Builder(this).setTitle(title).setMessage(body).setPositiveButton("App settings") { _, _ ->
openSystem(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
}.setNegativeButton("Later", null).show()
}
private fun openSystem(intent: Intent) { runCatching { startActivity(intent) }.onFailure { toast("Open this setting from your car’s Settings app.") } }
private fun toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() }
private fun version() = packageManager.getPackageInfo(packageName, 0).versionName ?: "0.1.0-beta.1"
private fun section(parent: LinearLayout, title: String, build: (LinearLayout) -> Unit) {
val card = card(); card.addView(label(title, 22, TEXT, true).apply { setPadding(0, 0, 0, dp(16)) }); build(card)
parent.addView(card, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = dp(18) })
}
private fun toggle(parent: LinearLayout, title: String, description: String, value: Boolean, save: (Boolean) -> Unit) {
val line = row().apply { gravity = Gravity.CENTER_VERTICAL; setPadding(0, dp(12), 0, dp(12)) }
val text = column(); text.addView(label(title, 18, TEXT, true)); text.addView(label(description, 14, MUTED).apply { setPadding(0, dp(6), dp(16), 0) })
line.addView(text, LinearLayout.LayoutParams(0, -2, 1f))
line.addView(Switch(this).apply { contentDescription = title; isChecked = value; minHeight = dp(56); buttonTintList = ColorStateList.valueOf(ACCENT); setOnCheckedChangeListener { _, checked -> save(checked) } })
parent.addView(line)
}
private fun choice(parent: LinearLayout, title: String, options: List<String>, current: Int, save: (Int) -> Unit) {
var selection = current
val button = button("$title · ${options[selection]}", false) {}
button.setOnClickListener {
var pendingSelection = selection
AlertDialog.Builder(this).setTitle(title)
.setSingleChoiceItems(options.toTypedArray(), selection) { _, index -> pendingSelection = index }
.setPositiveButton(if (CarPlayBackgroundSession.hasSession()) "Apply and reconnect" else "Save") { _, _ ->
if (pendingSelection != selection) {
selection = pendingSelection
save(selection)
button.text = "$title · ${options[selection]}"
if (CarPlayBackgroundSession.hasSession()) {
connect(AirPlayPersistence.loadWirelessEnabled(this))
}
}
}.setNegativeButton("Cancel", null).show()
}
parent.addView(button, matchButton(0, 60)); parent.addView(space(12))
}
private fun card() = column().apply { background = rounded(SURFACE, BORDER); setPadding(dp(24), dp(24), dp(24), dp(24)) }
private fun column() = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; layoutParams = LinearLayout.LayoutParams(-1, -2) }
private fun row() = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; layoutParams = LinearLayout.LayoutParams(-1, -2) }
private fun label(value: String, size: Int, color: Int, bold: Boolean = false) = TextView(this).apply {
text = value; textSize = size.toFloat(); setTextColor(color); gravity = Gravity.CENTER_VERTICAL
typeface = if (bold) Typeface.create("sans-serif-medium", Typeface.NORMAL) else Typeface.create("sans-serif", Typeface.NORMAL)
setLineSpacing(dp(3).toFloat(), 1f)
}
private fun button(title: String, primary: Boolean, click: () -> Unit) = Button(this).apply {
text = title; isAllCaps = false; textSize = 18f; setTextColor(if (primary) BG else TEXT)
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
background = android.graphics.drawable.RippleDrawable(ColorStateList.valueOf(0x336F9FD9), rounded(if (primary) ACCENT else SURFACE, if (primary) ACCENT else BORDER), null)
setPadding(dp(16), 0, dp(16), 0); minHeight = dp(56); stateListAnimator = null
setOnClickListener { click() }
}
private fun rounded(color: Int, stroke: Int) = GradientDrawable().apply { setColor(color); cornerRadius = dp(20).toFloat(); setStroke(dp(1), stroke) }
private fun matchButton(top: Int = 0, height: Int = 68) = LinearLayout.LayoutParams(-1, dp(height)).apply { topMargin = dp(top) }
private fun space(height: Int) = View(this).apply { layoutParams = LinearLayout.LayoutParams(1, dp(height)) }
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
companion object {
private val BG = Color.rgb(12, 17, 27)
private val SURFACE = Color.rgb(21, 30, 44)
private val BORDER = Color.rgb(42, 56, 75)
private val ACCENT = Color.rgb(166, 200, 255)
private val TEXT = Color.rgb(241, 245, 252)
private val MUTED = Color.rgb(168, 182, 202)
private val WARNING = Color.rgb(255, 196, 128)
}
}
@@ -0,0 +1,16 @@
package com.shilapi.xcertplay
import android.bluetooth.BluetoothManager
import android.content.Context
import android.provider.Settings
internal object DiPlayBluetooth {
fun localAddress(context: Context): String? {
val adapter = runCatching { context.getSystemService(BluetoothManager::class.java)?.adapter?.address }.getOrNull()
val setting = runCatching { Settings.Secure.getString(context.contentResolver, "bluetooth_address") }.getOrNull()
return listOfNotNull(adapter, setting).firstOrNull {
Regex("(?i)([0-9a-f]{2}:){5}[0-9a-f]{2}").matches(it) &&
!it.startsWith("02:00:00:00:00:") && it != "00:00:00:00:00:00"
}
}
}
@@ -0,0 +1,62 @@
package com.shilapi.xcertplay
import android.content.Context
import com.shilapi.xcertplay.airplay.AirPlayIdentity
import com.shilapi.xcertplay.mfi.LocalMfiAuthenticationClient
import com.shilapi.xcertplay.orchestration.MfiTarget
import java.io.File
import java.security.MessageDigest
/** Installs the private beta's experimental identity. It has no remote fallback. */
internal object DiPlayBootstrap {
@Volatile private var ready = false
@Synchronized fun ensure(context: Context) {
if (ready) return
val target = File(context.noBackupFilesDir, LocalMfiAuthenticationClient.DIRECTORY)
if (!target.exists()) {
val staging = File(context.noBackupFilesDir, "offline-mfi-staging")
staging.deleteRecursively()
check(staging.mkdirs()) { "Could not prepare local authentication" }
staging.setReadable(false, false); staging.setReadable(true, true)
staging.setExecutable(false, false); staging.setExecutable(true, true)
try {
for (name in listOf("identity.pk8", "certificate.p7b")) {
val file = File(staging, name)
context.assets.open("offline-mfi/$name").use { input ->
file.outputStream().use { output -> input.copyTo(output) }
}
file.setReadable(false, false); file.setReadable(true, true)
file.setWritable(false, false); file.setWritable(true, true)
}
LocalMfiAuthenticationClient.load(staging)
check(staging.renameTo(target)) { "Could not install local authentication" }
} finally {
staging.deleteRecursively()
}
}
LocalMfiAuthenticationClient.load(target)
AirPlayPersistence.saveMfiTarget(context, MfiTarget.LOCAL)
AirPlayPersistence.saveDebugLogsEnabled(context, false)
ready = true
}
fun deviceId(identity: AirPlayIdentity): String {
val bytes = MessageDigest.getInstance("SHA-256").digest(identity.publicKey).take(6).toByteArray()
bytes[0] = ((bytes[0].toInt() and 0xfc) or 0x02).toByte()
return bytes.joinToString(":") { "%02X".format(it.toInt() and 0xff) }
}
}
internal object DiPlayPreferences {
private fun prefs(context: Context) = context.getSharedPreferences("diplay", Context.MODE_PRIVATE)
fun phoneAddress(context: Context): String? = prefs(context).getString("phone_address", null)
fun phoneName(context: Context): String = prefs(context).getString("phone_name", null) ?: "Your iPhone"
fun savePhone(context: Context, address: String, name: String) {
prefs(context).edit().putString("phone_address", address).putString("phone_name", name).apply()
}
fun autoConnect(context: Context) = prefs(context).getBoolean("auto_connect", false)
fun saveAutoConnect(context: Context, value: Boolean) {
prefs(context).edit().putBoolean("auto_connect", value).apply()
}
}
@@ -0,0 +1,52 @@
package com.shilapi.xcertplay
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import com.shilapi.xcertplay.host.R
/** Keeps an explicitly started connection alive when another car app is in the foreground. */
class DiPlaySessionService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
CarPlayBackgroundSession.stop()
stopSelf()
return START_NOT_STICKY
}
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(NotificationChannel(CHANNEL, "CarPlay connection", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, CarPlayHostActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val stop = PendingIntent.getService(this, 1, Intent(this, DiPlaySessionService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val notification = Notification.Builder(this, CHANNEL)
.setSmallIcon(R.drawable.ic_diplay_notification)
.setContentTitle("DiPlay")
.setContentText("CarPlay connection running")
.setContentIntent(open).setOngoing(true)
.addAction(Notification.Action.Builder(null, "Disconnect", stop).build()).build()
if (Build.VERSION.SDK_INT >= 29) {
var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
if (Build.VERSION.SDK_INT >= 30 && checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
}
startForeground(1, notification, types)
} else startForeground(1, notification)
return START_NOT_STICKY
}
override fun onTaskRemoved(rootIntent: Intent?) {
CarPlayBackgroundSession.stop()
stopSelf()
}
companion object {
const val ACTION_STOP = "com.shihab.diplay.DISCONNECT"
private const val CHANNEL = "diplay_connection"
}
}
@@ -0,0 +1,43 @@
package com.shilapi.xcertplay
import android.content.ContentResolver
import android.content.ContentValues
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import java.io.IOException
/** Saves an app-owned report without depending on an OEM's document-picker activity. */
internal object DiagnosticExportStore {
@RequiresApi(Build.VERSION_CODES.Q)
fun saveToDownloads(resolver: ContentResolver, fileName: String, report: String): Uri {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, fileName)
put(MediaStore.Downloads.MIME_TYPE, "text/plain")
put(MediaStore.Downloads.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOADS}/DiPlay")
put(MediaStore.Downloads.IS_PENDING, 1)
}
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: throw IOException("Downloads could not create the report")
try {
write(resolver, uri, report)
val published = resolver.update(uri, ContentValues().apply {
put(MediaStore.Downloads.IS_PENDING, 0)
}, null, null)
if (published != 1) throw IOException("Downloads could not publish the report")
return uri
} catch (error: Exception) {
// Only remove the entry created by this call; never leave a partial report behind.
runCatching { resolver.delete(uri, null, null) }
throw error
}
}
fun write(resolver: ContentResolver, uri: Uri, report: String) {
val stream = resolver.openOutputStream(uri, "wt")
?: throw IOException("Report destination is unavailable")
stream.bufferedWriter(Charsets.UTF_8).use { it.write(report) }
}
}
@@ -0,0 +1,17 @@
package com.shilapi.xcertplay
/** Diagnostics describe state transitions; protocol payloads and credentials are never exported. */
internal object DiagnosticRedactor {
private val secret = Regex("(?i)(pass(word|phrase)?|token|private.?key|certificate|pair.?record|ssid|body=|payload=|hex=)")
private val mac = Regex("(?i)(?<![0-9a-f])(?:[0-9a-f]{2}:){5}[0-9a-f]{2}(?![0-9a-f])")
private val identifier = Regex("(?i)\\b[0-9a-f]{24,}\\b|\\b[0-9a-f]{8}-[0-9a-f-]{27,}\\b")
private val address = Regex("(?<![0-9])(?:[0-9]{1,3}\\.){3}[0-9]{1,3}(?![0-9])")
private val namedDevice = Regex("(?i)(phone|device|peer|host)?name[=:]")
private val ipv6 = Regex("(?i)(?:[0-9a-f]{1,4}:)*[0-9a-f]{0,4}::[0-9a-f:]*(?:%[a-z0-9_.-]+)?|(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}")
fun redact(line: String): String? {
if (line.contains("TRACE ") || line.contains("PHONE ") || line.contains('\n') || line.contains('\r')) return null
if (secret.containsMatchIn(line) || namedDevice.containsMatchIn(line)) return null
return line.replace(mac, "[address]").replace(identifier, "[identifier]")
.replace(address, "[ip]").replace(ipv6, "[ip]").take(700)
}
}
@@ -0,0 +1,58 @@
package com.shilapi.xcertplay
import android.content.Context
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
/** Small, redacted snapshot retained separately from the rotating session logs. */
internal object DisplayDiagnosticSnapshot {
private const val PREFS = "diplay_display_diagnostics"
private val fields = listOf("selection", "request", "capability", "effective", "phone", "decoder", "output")
private fun stamp() = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).format(Date())
@Synchronized
fun selection(context: Context, previous: Int, selected: Int, reconnect: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("selection",
"${stamp()} Size setting previous=$previous% selected=$selected% reconnect=$reconnect").apply()
}
@Synchronized
fun begin(context: Context, request: String, capability: String, effective: String): String {
val attempt = UUID.randomUUID().toString()
val editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
fields.filter { it != "selection" }.forEach(editor::remove)
editor.putString("attempt", attempt)
for ((key, line) in listOf("request" to request, "capability" to capability, "effective" to effective)) {
DiagnosticRedactor.redact(line)?.let { editor.putString(key, "${stamp()} $it") }
}
editor.apply()
return attempt
}
@Synchronized
fun currentAttempt(context: Context): String? =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("attempt", null)
@Synchronized
fun record(context: Context, attempt: String?, message: String) {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
if (attempt == null || prefs.getString("attempt", null) != attempt) return
val field = when {
message.startsWith("Phone display peer ") -> "phone"
message.startsWith("Video: decoder=") || message.startsWith("Video: decoder configuration failed") -> "decoder"
message.startsWith("Video: output format ") -> "output"
else -> return
}
val safe = DiagnosticRedactor.redact(message) ?: return
prefs.edit().putString(field, "${stamp()} $safe").apply()
}
@Synchronized
fun report(context: Context): String {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return fields.mapNotNull { prefs.getString(it, null)?.let(DiagnosticRedactor::redact) }
.joinToString("\n").ifEmpty { "No display negotiation recorded yet." }
}
}
@@ -0,0 +1,393 @@
package com.shilapi.xcertplay
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import java.io.ByteArrayOutputStream
import java.util.concurrent.Executors
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
/** Loads one local image and writes a user-positioned 1:1 PNG into the AirPlay icon slot. */
class ImageCropActivity : Activity() {
private val executor = Executors.newSingleThreadExecutor()
private lateinit var cropView: SquareCropView
private lateinit var statusView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val uri = intent.data
if (uri == null) {
finish()
return
}
cropView = SquareCropView(this)
statusView = TextView(this).apply {
setTextColor(Color.WHITE)
textSize = 16f
gravity = Gravity.CENTER
setPadding(dp(12), dp(8), dp(12), dp(8))
text = "Loading image"
}
val controls = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER
setPadding(dp(16), dp(10), dp(16), dp(16))
}
controls.addView(
Button(this).apply {
text = "Cancel"
isAllCaps = false
setOnClickListener {
setResult(RESULT_CANCELED)
finish()
}
},
LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f),
)
controls.addView(
Button(this).apply {
text = "Save 1:1"
isAllCaps = false
setOnClickListener { saveCrop() }
},
LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f).apply {
marginStart = dp(12)
},
)
val root = FrameLayout(this).apply {
setBackgroundColor(Color.BLACK)
addView(
cropView,
FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
),
)
addView(
statusView,
FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.TOP or Gravity.CENTER_HORIZONTAL,
).apply { topMargin = dp(12) },
)
addView(
controls,
FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM,
),
)
}
setContentView(root)
executor.execute {
val bitmap = try {
decodeBitmap(uri)
} catch (_: Exception) {
null
}
runOnUiThread {
if (isFinishing || isDestroyed) {
bitmap?.recycle()
return@runOnUiThread
}
if (bitmap == null) {
statusView.text = "Could not decode image"
} else {
cropView.setBitmap(bitmap)
statusView.text = "Drag to move, pinch to zoom"
}
}
}
}
override fun onDestroy() {
executor.shutdownNow()
cropView.bitmap?.recycle()
super.onDestroy()
}
private fun saveCrop() {
val cropped = cropView.cropToSquare() ?: run {
statusView.text = "Image is not ready"
return
}
val encoded = ByteArrayOutputStream().use { output ->
if (!cropped.compress(Bitmap.CompressFormat.PNG, 100, output)) {
cropped.recycle()
statusView.text = "Could not encode image"
return
}
cropped.recycle()
output.toByteArray()
}
try {
AirPlayPersistence.saveCustomAirPlayIcon(applicationContext, encoded)
setResult(
RESULT_OK,
Intent().putExtra(EXTRA_CROP_COMPLETE, true),
)
finish()
} catch (_: Exception) {
statusView.text = "Could not save image"
}
}
private fun decodeBitmap(uri: Uri): Bitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, bounds)
}
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sampleSize = 1
while (max(bounds.outWidth, bounds.outHeight) / sampleSize > MAX_DECODE_EDGE) {
sampleSize *= 2
}
val options = BitmapFactory.Options().apply {
inSampleSize = sampleSize
inPreferredConfig = Bitmap.Config.ARGB_8888
}
return contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, options)
}
}
private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()
private class SquareCropView(context: android.content.Context) : View(context) {
private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
private val dimPaint = Paint().apply { color = Color.argb(145, 0, 0, 0) }
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
style = Paint.Style.STROKE
strokeWidth = 2f * resources.displayMetrics.density
}
private val gridPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.argb(150, 255, 255, 255)
style = Paint.Style.STROKE
strokeWidth = 1f * resources.displayMetrics.density
}
private val matrix = Matrix()
private val viewport = RectF()
private val mappedBitmap = RectF()
private var minimumScale = 1f
private var maximumScale = 1f
private var lastX = 0f
private var lastY = 0f
private var lastDistance = 0f
var bitmap: Bitmap? = null
private set
fun setBitmap(value: Bitmap) {
bitmap?.recycle()
bitmap = value
if (width > 0 && height > 0) configure()
invalidate()
}
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
configure()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val source = bitmap ?: return
canvas.drawColor(Color.BLACK)
canvas.drawRect(0f, 0f, width.toFloat(), viewport.top, dimPaint)
canvas.drawRect(0f, viewport.bottom, width.toFloat(), height.toFloat(), dimPaint)
canvas.drawRect(0f, viewport.top, viewport.left, viewport.bottom, dimPaint)
canvas.drawRect(viewport.right, viewport.top, width.toFloat(), viewport.bottom, dimPaint)
val save = canvas.save()
canvas.clipRect(viewport)
canvas.drawBitmap(source, matrix, imagePaint)
canvas.restoreToCount(save)
canvas.drawRect(viewport, borderPaint)
val thirdWidth = viewport.width() / 3f
val thirdHeight = viewport.height() / 3f
canvas.drawLine(viewport.left + thirdWidth, viewport.top, viewport.left + thirdWidth, viewport.bottom, gridPaint)
canvas.drawLine(viewport.right - thirdWidth, viewport.top, viewport.right - thirdWidth, viewport.bottom, gridPaint)
canvas.drawLine(viewport.left, viewport.top + thirdHeight, viewport.right, viewport.top + thirdHeight, gridPaint)
canvas.drawLine(viewport.left, viewport.bottom - thirdHeight, viewport.right, viewport.bottom - thirdHeight, gridPaint)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (bitmap == null) return true
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
lastX = event.x
lastY = event.y
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
lastDistance = pointerDistance(event)
return true
}
MotionEvent.ACTION_MOVE -> {
if (event.pointerCount >= 2) {
val distance = pointerDistance(event)
if (lastDistance > 0f) {
val factor = distance / lastDistance
matrix.postScale(
factor,
factor,
(event.getX(0) + event.getX(1)) / 2f,
(event.getY(0) + event.getY(1)) / 2f,
)
}
lastDistance = distance
} else {
matrix.postTranslate(event.x - lastX, event.y - lastY)
}
lastX = event.x
lastY = event.y
constrainMatrix()
invalidate()
return true
}
MotionEvent.ACTION_POINTER_UP -> {
lastDistance = 0f
return true
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
lastDistance = 0f
performClick()
return true
}
}
return super.onTouchEvent(event)
}
override fun performClick(): Boolean {
super.performClick()
return true
}
fun cropToSquare(): Bitmap? {
val source = bitmap ?: return null
if (viewport.width() <= 0f || viewport.height() <= 0f) return null
val inverse = Matrix()
if (!matrix.invert(inverse)) return null
val sourceRect = RectF()
inverse.mapRect(sourceRect, viewport)
val left = floor(sourceRect.left).toInt().coerceIn(0, source.width - 1)
val top = floor(sourceRect.top).toInt().coerceIn(0, source.height - 1)
val right = ceil(sourceRect.right).toInt().coerceIn(left + 1, source.width)
val bottom = ceil(sourceRect.bottom).toInt().coerceIn(top + 1, source.height)
val square = min(right - left, bottom - top)
val centerX = (left + right) / 2
val centerY = (top + bottom) / 2
val cropLeft = (centerX - square / 2).coerceIn(0, source.width - square)
val cropTop = (centerY - square / 2).coerceIn(0, source.height - square)
val cropped = Bitmap.createBitmap(source, cropLeft, cropTop, square, square)
val output = Bitmap.createBitmap(
OUTPUT_ICON_PIXELS,
OUTPUT_ICON_PIXELS,
Bitmap.Config.ARGB_8888,
)
Canvas(output).drawBitmap(
cropped,
null,
RectF(0f, 0f, OUTPUT_ICON_PIXELS.toFloat(), OUTPUT_ICON_PIXELS.toFloat()),
imagePaint,
)
if (cropped !== source) cropped.recycle()
return output
}
private fun configure() {
val source = bitmap ?: return
if (width <= 0 || height <= 0) return
val side = min(width, height).toFloat() - 2f * CROP_PADDING_DP * resources.displayMetrics.density
if (side <= 0f) return
viewport.set(
(width - side) / 2f,
(height - side) / 2f,
(width + side) / 2f,
(height + side) / 2f,
)
minimumScale = max(side / source.width, side / source.height)
maximumScale = minimumScale * MAX_ZOOM
matrix.reset()
matrix.postScale(minimumScale, minimumScale)
matrix.postTranslate(
viewport.centerX() - source.width * minimumScale / 2f,
viewport.centerY() - source.height * minimumScale / 2f,
)
constrainMatrix()
invalidate()
}
private fun constrainMatrix() {
val source = bitmap ?: return
val values = FloatArray(9)
matrix.getValues(values)
val scale = values[Matrix.MSCALE_X]
if (scale < minimumScale) {
matrix.postScale(minimumScale / scale, minimumScale / scale, viewport.centerX(), viewport.centerY())
} else if (scale > maximumScale) {
matrix.postScale(maximumScale / scale, maximumScale / scale, viewport.centerX(), viewport.centerY())
}
mappedBitmap.set(0f, 0f, source.width.toFloat(), source.height.toFloat())
matrix.mapRect(mappedBitmap)
var dx = 0f
var dy = 0f
if (mappedBitmap.left > viewport.left) dx = viewport.left - mappedBitmap.left
if (mappedBitmap.right < viewport.right) dx = viewport.right - mappedBitmap.right
if (mappedBitmap.top > viewport.top) dy = viewport.top - mappedBitmap.top
if (mappedBitmap.bottom < viewport.bottom) dy = viewport.bottom - mappedBitmap.bottom
if (dx != 0f || dy != 0f) matrix.postTranslate(dx, dy)
}
private fun pointerDistance(event: MotionEvent): Float {
if (event.pointerCount < 2) return 0f
val dx = event.getX(0) - event.getX(1)
val dy = event.getY(0) - event.getY(1)
return kotlin.math.sqrt(dx * dx + dy * dy)
}
private companion object {
const val CROP_PADDING_DP = 24f
const val MAX_ZOOM = 8f
}
}
companion object {
const val EXTRA_CROP_COMPLETE = "crop_complete"
private const val MAX_DECODE_EDGE = 2048
private const val OUTPUT_ICON_PIXELS = 1024
}
}
@@ -0,0 +1,122 @@
package com.shilapi.xcertplay
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.shilapi.xcertplay.mfi.MfiProtocolMajorResult
import com.shilapi.xcertplay.mfi.MfiSelfCheck
import com.shilapi.xcertplay.mfi.MfiSelfCheckResult
import com.shilapi.xcertplay.transport.LinuxI2cTransport
import com.shilapi.xcertplay.ui.theme.XcertplayTheme
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class MainActivity : ComponentActivity() {
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
private var status by mutableStateOf<DiagnosticStatus>(DiagnosticStatus.Idle)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
XcertplayTheme {
var devicePath by remember { mutableStateOf("/dev/i2c-1") }
Scaffold(modifier = Modifier.fillMaxSize()) { padding ->
Column(
modifier = Modifier.padding(padding).padding(24.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text("Board I2C diagnostic")
OutlinedTextField(
value = devicePath,
onValueChange = { devicePath = it },
modifier = Modifier.fillMaxWidth(),
label = { Text("Linux I2C device") },
singleLine = true,
enabled = status !is DiagnosticStatus.Running,
)
Button(
onClick = { runSelfCheck(devicePath) },
enabled = status !is DiagnosticStatus.Running,
) {
Text("Run MFi self-check")
}
Spacer(Modifier.height(4.dp))
Text(status.message())
Text("CH341 requires deployment-specific VID/PID configuration.")
}
}
}
}
}
override fun onDestroy() {
executor.shutdownNow()
super.onDestroy()
}
private fun runSelfCheck(devicePath: String) {
status = DiagnosticStatus.Running
executor.execute {
val next = try {
LinuxI2cTransport.open(devicePath).use { MfiSelfCheck(it).run() }
.let { DiagnosticStatus.Result(it) }
} catch (error: LinkageError) {
DiagnosticStatus.Failure(error.message ?: "I2C native library is unavailable")
} catch (error: Exception) {
DiagnosticStatus.Failure(error.message ?: error.javaClass.simpleName)
}
runOnUiThread {
if (!isFinishing && !isDestroyed) status = next
}
}
}
}
private sealed class DiagnosticStatus {
data object Idle : DiagnosticStatus()
data object Running : DiagnosticStatus()
data class Result(val selfCheck: MfiSelfCheckResult) : DiagnosticStatus()
data class Failure(val message: String) : DiagnosticStatus()
fun message(): String = when (this) {
Idle -> "Idle"
Running -> "Running…"
is Failure -> "Failed: $message"
is Result -> {
val chip = selfCheck.chip ?: return if (selfCheck.discovery.interrupted) {
"MFi scan interrupted"
} else {
"Found: none"
}
val major = when (val result = chip.protocolMajor) {
is MfiProtocolMajorResult.Value -> "%d".format(result.major)
is MfiProtocolMajorResult.MfiFailure -> result.error.message ?: result.error.javaClass.simpleName
is MfiProtocolMajorResult.TransportFailure -> result.error.message ?: result.error.javaClass.simpleName
}
"Found: 0x%02X; device version: 0x%02X; protocol major (raw): %s".format(
chip.address7Bit,
chip.deviceVersion,
major,
)
}
}
}
@@ -0,0 +1,186 @@
package com.shilapi.xcertplay
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.MotionEvent
import android.view.View
import com.shilapi.xcertplay.airplay.AirPlaySafeArea
import com.shilapi.xcertplay.airplay.SafeAreaRect
/** Full-screen editor for the two horizontal and two vertical safe-area boundaries. */
class SafeAreaEditorView(context: Context) : View(context) {
private enum class Edge {
LEFT,
TOP,
RIGHT,
BOTTOM,
}
private val density = resources.displayMetrics.density
private val touchRadius = 40f * density
private val dimPaint = Paint().apply { color = Color.argb(118, 0, 0, 0) }
private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.rgb(127, 205, 154)
strokeWidth = 3f * density
style = Paint.Style.STROKE
}
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.argb(210, 255, 255, 255)
strokeWidth = 1f * density
style = Paint.Style.STROKE
}
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
textSize = 15f * density * resources.configuration.fontScale
typeface = android.graphics.Typeface.MONOSPACE
}
private var rect: SafeAreaRect? = null
private var sourceRect: SafeAreaRect? = null
private var sourceWidth = 0
private var sourceHeight = 0
private var activeEdge: Edge? = null
init {
isClickable = true
}
fun setRect(value: SafeAreaRect, sourceWidthPixels: Int, sourceHeightPixels: Int) {
require(sourceWidthPixels > 0 && sourceHeightPixels > 0) {
"Source dimensions must be positive"
}
sourceWidth = sourceWidthPixels
sourceHeight = sourceHeightPixels
sourceRect = value
if (width > 0 && height > 0) {
rect = AirPlaySafeArea.scaleRect(
value,
sourceWidth,
sourceHeight,
width,
height,
)
invalidate()
}
}
fun currentRectForSource(): SafeAreaRect? {
sourceRect?.let { return it }
val current = rect ?: return null
if (sourceWidth <= 0 || sourceHeight <= 0 || width <= 0 || height <= 0) return null
return AirPlaySafeArea.scaleRect(current, width, height, sourceWidth, sourceHeight)
}
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
if (width <= 0 || height <= 0) return
val source = sourceRect ?: AirPlaySafeArea.default(width, height)
rect = if (sourceWidth > 0 && sourceHeight > 0) {
AirPlaySafeArea.scaleRect(source, sourceWidth, sourceHeight, width, height)
} else {
source.clampTo(width, height)
}
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val safe = rect ?: return
val width = width.toFloat()
val height = height.toFloat()
val left = safe.left.toFloat()
val top = safe.top.toFloat()
val right = safe.right.toFloat()
val bottom = safe.bottom.toFloat()
canvas.drawRect(0f, 0f, width, top, dimPaint)
canvas.drawRect(0f, bottom, width, height, dimPaint)
canvas.drawRect(0f, top, left, bottom, dimPaint)
canvas.drawRect(right, top, width, bottom, dimPaint)
canvas.drawRect(left, top, right, bottom, borderPaint)
canvas.drawLine(left, 0f, left, height, linePaint)
canvas.drawLine(right, 0f, right, height, linePaint)
canvas.drawLine(0f, top, width, top, linePaint)
canvas.drawLine(0f, bottom, width, bottom, linePaint)
drawLabel(canvas, "x=${safe.left}", left + 8f * density, top + 20f * density)
drawLabel(canvas, "x=${safe.right}", right + 8f * density, bottom - 8f * density)
drawLabel(canvas, "y=${safe.top}", left + 8f * density, top - 8f * density)
drawLabel(canvas, "y=${safe.bottom}", right - 88f * density, bottom + 20f * density)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val safe = rect ?: return true
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
activeEdge = nearestEdge(event.x, event.y, safe)
return true
}
MotionEvent.ACTION_MOVE -> {
val edge = activeEdge ?: return true
val moved = moveEdge(safe, edge, event.x, event.y)
rect = moved
if (sourceWidth > 0 && sourceHeight > 0 && width > 0 && height > 0) {
sourceRect = AirPlaySafeArea.scaleRect(
moved,
width,
height,
sourceWidth,
sourceHeight,
)
}
invalidate()
return true
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
activeEdge = null
performClick()
return true
}
}
return super.onTouchEvent(event)
}
override fun performClick(): Boolean {
super.performClick()
return true
}
private fun nearestEdge(x: Float, y: Float, safe: SafeAreaRect): Edge? {
val candidates = listOf(
Edge.LEFT to kotlin.math.abs(x - safe.left),
Edge.RIGHT to kotlin.math.abs(x - safe.right),
Edge.TOP to kotlin.math.abs(y - safe.top),
Edge.BOTTOM to kotlin.math.abs(y - safe.bottom),
).filter { it.second <= touchRadius }
return candidates.minByOrNull { it.second }?.first
}
private fun moveEdge(safe: SafeAreaRect, edge: Edge, x: Float, y: Float): SafeAreaRect {
val pointX = x.toInt().coerceIn(0, width)
val pointY = y.toInt().coerceIn(0, height)
return when (edge) {
Edge.LEFT -> safe.copy(left = pointX.coerceIn(0, safe.right - 1))
Edge.TOP -> safe.copy(top = pointY.coerceIn(0, safe.bottom - 1))
Edge.RIGHT -> safe.copy(right = pointX.coerceIn(safe.left + 1, width))
Edge.BOTTOM -> safe.copy(bottom = pointY.coerceIn(safe.top + 1, height))
}
}
private fun drawLabel(canvas: Canvas, value: String, x: Float, y: Float) {
val horizontalMin = 4f * density
val horizontalMax = (width - textPaint.measureText(value) - 4f * density)
.coerceAtLeast(horizontalMin)
val verticalMin = textPaint.textSize + 4f * density
val verticalMax = (height - 4f * density).coerceAtLeast(verticalMin)
val safeX = x.coerceIn(horizontalMin, horizontalMax)
val safeY = y.coerceIn(verticalMin, verticalMax)
canvas.drawText(value, safeX, safeY, textPaint)
}
}
@@ -0,0 +1,45 @@
package com.shilapi.xcertplay
import java.io.Closeable
import java.io.File
/** Bounded, private diagnostics. Each write is redacted before touching storage. */
internal class SessionLogFile(val file: File) : Closeable {
private val lock = Any()
private var closed = false
fun reset(header: String) = synchronized(lock) {
if (!closed) {
file.parentFile?.mkdirs()
rotate()
file.writeText("")
append(header)
}
}
fun append(line: String) = synchronized(lock) {
if (closed) return@synchronized
val safe = DiagnosticRedactor.redact(line) ?: return@synchronized
runCatching {
if (file.length() > MAX_BYTES) {
rotate()
file.writeText("")
}
file.appendText(safe + "\n")
}
Unit
}
private fun rotate() {
if (!file.exists() || file.length() == 0L) return
for (index in ARCHIVE_NAMES.lastIndex downTo 1) {
val source = File(file.parentFile, ARCHIVE_NAMES[index - 1])
val destination = File(file.parentFile, ARCHIVE_NAMES[index])
if (source.exists()) source.copyTo(destination, overwrite = true)
}
file.copyTo(File(file.parentFile, ARCHIVE_NAMES.first()), overwrite = true)
}
override fun close() = synchronized(lock) { closed = true }
companion object {
const val MAX_BYTES = 512 * 1024L
private val ARCHIVE_NAMES = listOf("previous.log") + (2..7).map { "previous-$it.log" }
val REPORT_NAMES = ARCHIVE_NAMES.reversed() + "diplay.log"
}
}
@@ -0,0 +1,11 @@
package com.shilapi.xcertplay.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
@@ -0,0 +1,58 @@
package com.shilapi.xcertplay.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun XcertplayTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@@ -0,0 +1,34 @@
package com.shilapi.xcertplay.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

@@ -0,0 +1,3 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:fillColor="#FFFFFFFF" android:pathData="M3,4L21,4L21,18L14,18L14,20L10,20L10,18L3,18ZM5,6L5,16L19,16L19,6ZM10,8L16,11L10,14Z" android:fillType="evenOdd" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+3
View File
@@ -0,0 +1,3 @@
<resources>
<bool name="config_advanced_audio_channel_mapping">false</bool>
</resources>
+3
View File
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">DiPlay</string>
</resources>
+11
View File
@@ -0,0 +1,11 @@
<resources>
<style name="Theme.Xcertplay" parent="android:Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:colorAccent">#A6C8FF</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:navigationBarColor">#0C111B</item>
<item name="android:statusBarColor">#0C111B</item>
<item name="android:windowBackground">#0C111B</item>
<item name="android:windowActionModeOverlay">true</item>
</style>
</resources>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
<exclude domain="device_root" path="." />
<exclude domain="device_file" path="." />
<exclude domain="device_database" path="." />
<exclude domain="device_sharedpref" path="." />
</full-backup-content>
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
<exclude domain="device_root" path="." />
<exclude domain="device_file" path="." />
<exclude domain="device_database" path="." />
<exclude domain="device_sharedpref" path="." />
</cloud-backup>
<device-transfer>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
<exclude domain="device_root" path="." />
<exclude domain="device_file" path="." />
<exclude domain="device_database" path="." />
<exclude domain="device_sharedpref" path="." />
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- CH341 USB\VID_1A86&PID_5512&REV_0304 -->
<usb-device vendor-id="6790" product-id="21778" />
</resources>
@@ -0,0 +1,19 @@
package com.shilapi.xcertplay
import android.content.res.Configuration
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class DarkModeTest {
@Test
fun darkModeIsDetectedWithUnrelatedConfigurationBits() {
assertTrue(isDarkMode(Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_CAR))
}
@Test
fun lightAndUndefinedModesAreNotDark() {
assertFalse(isDarkMode(Configuration.UI_MODE_NIGHT_NO))
assertFalse(isDarkMode(Configuration.UI_MODE_NIGHT_UNDEFINED))
}
}
@@ -0,0 +1,119 @@
package com.shilapi.xcertplay
import android.content.ContentProvider
import android.content.ContentValues
import android.content.pm.ProviderInfo
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowContentResolver
import java.io.File
import java.io.IOException
/** Exercise the Android 10 storage path, including OEM/provider failure responses. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [29], manifest = Config.NONE)
class DiagnosticExportStoreTest {
private lateinit var provider: DownloadsProvider
private val resolver get() = RuntimeEnvironment.getApplication().contentResolver
@Before fun setup() {
val context = RuntimeEnvironment.getApplication()
provider = DownloadsProvider(File(context.cacheDir, "export-test.txt"))
provider.attachInfo(context, ProviderInfo().apply { authority = "media" })
ShadowContentResolver.registerProviderInternal("media", provider)
}
@Test fun android10SavesUtf8ReportToDownloadsAndPublishesAfterClosingIt() {
val report = "DiPlay · diagnostic report\nVideo: H.264\n"
val uri = DiagnosticExportStore.saveToDownloads(resolver, "DiPlay-test.txt", report)
assertEquals(provider.uri, uri)
assertEquals(report, provider.file.readText())
assertEquals("Download/DiPlay", provider.insertValues!!.getAsString(MediaStore.Downloads.RELATIVE_PATH))
assertEquals("text/plain", provider.insertValues!!.getAsString(MediaStore.Downloads.MIME_TYPE))
assertEquals(1, provider.insertValues!!.getAsInteger(MediaStore.Downloads.IS_PENDING))
assertEquals(0, provider.publishValues!!.getAsInteger(MediaStore.Downloads.IS_PENDING))
assertEquals(report, provider.contentAtPublish)
assertFalse(provider.deleted)
}
@Test fun unavailableDownloadsDoesNotReturnFalseSuccess() {
provider.refuseInsert = true
assertThrows(IOException::class.java) {
DiagnosticExportStore.saveToDownloads(resolver, "test.txt", "report")
}
assertNull(provider.publishValues)
assertFalse(provider.deleted)
}
@Test fun deniedWriteRemovesOnlyTheNewPendingEntry() {
provider.denyWrite = true
assertThrows(SecurityException::class.java) {
DiagnosticExportStore.saveToDownloads(resolver, "test.txt", "report")
}
assertTrue(provider.deleted)
assertNull(provider.publishValues)
}
@Test fun failedPublishDoesNotLeaveAnInvisibleReport() {
provider.refusePublish = true
assertThrows(IOException::class.java) {
DiagnosticExportStore.saveToDownloads(resolver, "test.txt", "report")
}
assertTrue(provider.deleted)
}
@Test fun selectedDocumentIsWrittenButNeverDeletedOnFailure() {
provider.denyWrite = true
assertThrows(SecurityException::class.java) {
DiagnosticExportStore.write(resolver, provider.uri, "report")
}
assertFalse(provider.deleted)
}
private class DownloadsProvider(val file: File) : ContentProvider() {
val uri: Uri = Uri.parse("content://media/external/downloads/41")
var insertValues: ContentValues? = null
var publishValues: ContentValues? = null
var contentAtPublish: String? = null
var deleted = false
var refuseInsert = false
var denyWrite = false
var refusePublish = false
override fun onCreate() = true
override fun insert(uri: Uri, values: ContentValues?): Uri? {
assertEquals(MediaStore.Downloads.EXTERNAL_CONTENT_URI, uri)
insertValues = ContentValues(values)
return if (refuseInsert) null else this.uri
}
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
assertEquals(this.uri, uri)
assertEquals("wt", mode)
if (denyWrite) throw SecurityException("Test provider refused write")
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_CREATE or
ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_TRUNCATE)
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
assertEquals(this.uri, uri)
publishValues = ContentValues(values)
contentAtPublish = file.readText()
return if (refusePublish) 0 else 1
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
assertEquals(this.uri, uri)
deleted = true
file.delete()
return 1
}
override fun getType(uri: Uri) = "text/plain"
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
}
}
@@ -0,0 +1,63 @@
package com.shilapi.xcertplay
import org.junit.Assert.*
import org.junit.Test
import java.nio.file.Files
class DiagnosticRedactorTest {
@Test fun payloadAndCredentialLinesNeverReachReports() {
for (line in listOf("TRACE IAP2 tx key", "hotspot passphrase=secret", "token=secret", "certificate bytes=607", "rx body={phone: 'Jane'}", "ok\nsecret", "wifi ssid=Home", "wireless name=Jane Smith’s iPhone")) {
assertNull(line, DiagnosticRedactor.redact(line))
}
}
@Test fun stateTransitionsSurviveWithoutAddressesOrIdentifiers() {
val line = DiagnosticRedactor.redact("connected peer=C0:A6:00:29:58:0A ip=192.168.31.71 id=0123456789abcdef0123456789abcdef ipv6=fe80::1234:5678:abcd:9%p2p0")!!
assertTrue(line.contains("connected"))
assertFalse(line.contains("C0:A6")); assertFalse(line.contains("192.168")); assertFalse(line.contains("012345")); assertFalse(line.contains("fe80"))
}
@Test fun logRotationIsBoundedAndRedactionHappensBeforeDisk() {
val folder = Files.createTempDirectory("diplay-log-test").toFile()
try {
val log = SessionLogFile(folder.resolve("diplay.log"))
log.reset("started")
log.append("password=secret")
repeat(1600) { log.append("connection state " + "x".repeat(690)) }
log.append("CarPlay connected")
log.close()
assertTrue(folder.resolve("diplay.log").length() <= SessionLogFile.MAX_BYTES + 701)
assertTrue(folder.resolve("previous.log").length() <= SessionLogFile.MAX_BYTES + 701)
assertTrue(folder.resolve("diplay.log").readText().contains("CarPlay connected"))
assertFalse(folder.listFiles()!!.any { it.readText().contains("secret") })
} finally { folder.deleteRecursively() }
}
@Test fun failuresSurviveLaterSuccessfulSessionsAndOldestHistoryExpires() {
val folder = Files.createTempDirectory("diplay-history-test").toFile()
try {
repeat(10) { session ->
SessionLogFile(folder.resolve("diplay.log")).use {
it.reset("session=$session")
it.append(if (session == 3) "Wi-Fi P2P create rejected code=0" else "CarPlay connected")
it.append("password=secret")
}
}
val history = SessionLogFile.REPORT_NAMES.map { folder.resolve(it).readText() }
assertEquals(8, folder.listFiles()!!.size)
assertTrue(history.first().contains("session=2"))
assertTrue(history.last().contains("session=9"))
assertTrue(history.any { it.contains("rejected code=0") })
assertFalse(history.any { it.contains("secret") })
} finally { folder.deleteRecursively() }
}
@Test fun safeWifiMetadataSurvivesWithoutWeakeningCredentialFilters() {
val lines = listOf(
"Wi-Fi P2P preflight wifiEnabled=true locationEnabled=false permissionGranted=true stationMHz=5180",
"Wi-Fi P2P create mode=FIXED_2_GHZ frequencyMHz=2437",
"Wi-Fi P2P create rejected code=0 reason=generic error",
"Wi-Fi P2P ready mode=FIXED_2_GHZ band=2.4 GHz channel=6 frequencyMHz=2437",
"Wi-Fi P2P channel requestedMHz=2437 actualMHz=2412 matched=false",
"wireless hotspot backend=Wi-Fi P2P iface=p2p0 host=192.168.49.1 band=5 GHz channel=36 frequency=5180MHz",
)
for (line in lines) assertNotNull(line, DiagnosticRedactor.redact(line))
assertFalse(DiagnosticRedactor.redact(lines.last())!!.contains("192.168.49.1"))
}
}
@@ -0,0 +1,60 @@
package com.shilapi.xcertplay
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [29], manifest = Config.NONE)
class DisplayDiagnosticSnapshotTest {
private val context get() = RuntimeEnvironment.getApplication()
@Test fun requestedSizeSurvivesAFallbackAndSubsequentPreferenceReset() {
DisplayDiagnosticSnapshot.selection(context, 100, 75, true)
DisplayDiagnosticSnapshot.begin(context,
"Display request selected=Smaller percent=75 surface=1920x1080 candidate=2560x1440",
"Decoder capability codec=c2.test hardware=true sizeSupported=false result=canvas_dimensions_unsupported",
"Display effective percent=100 canvas=1920x1080 decision=canvas_dimensions_unsupported")
AirPlayPersistence.saveUiScalePercent(context, 100)
val report = DisplayDiagnosticSnapshot.report(context)
assertTrue(report.contains("selected=75% reconnect=true"))
assertTrue(report.contains("percent=75"))
assertTrue(report.contains("percent=100"))
assertTrue(report.contains("canvas_dimensions_unsupported"))
}
@Test fun actualOutputAndPhoneVersionsSurviveReportRedaction() {
val attempt = DisplayDiagnosticSnapshot.begin(context, "Display request selected=Smaller",
"Decoder capability result=supported", "Display effective canvas=2560x1440")
DisplayDiagnosticSnapshot.record(context, attempt, "Phone display peer model=iPhone11,2 ios=18.7.10 airplay=950.7.1")
DisplayDiagnosticSnapshot.record(context, attempt, "Video: decoder=c2.mtk.avc.decoder mime=video/avc size=2560x1440")
DisplayDiagnosticSnapshot.record(context, attempt, "Video: output format requested=2560x1440 coded=1920x1088 crop=0,0,1919,1079")
val report = DisplayDiagnosticSnapshot.report(context)
assertTrue(report.contains("ios=18.7.10"))
assertTrue(report.contains("decoder=c2.mtk.avc.decoder"))
assertTrue(report.contains("coded=1920x1088"))
assertTrue(report.contains("crop=0,0,1919,1079"))
}
@Test fun reconnectClearsOldOutputAndRejectsLateCallbacks() {
val old = DisplayDiagnosticSnapshot.begin(context, "old request", "old capability", "old effective")
DisplayDiagnosticSnapshot.record(context, old, "Video: output format coded=2560x1440")
val current = DisplayDiagnosticSnapshot.begin(context, "new request", "new capability", "new effective")
DisplayDiagnosticSnapshot.record(context, old, "Video: output format coded=800x480")
assertFalse(DisplayDiagnosticSnapshot.report(context).contains("coded="))
assertEquals(current, DisplayDiagnosticSnapshot.currentAttempt(context))
}
@Test fun onlySupportedMetadataIsStoredAndItIsBounded() {
val attempt = DisplayDiagnosticSnapshot.begin(context, "request", "capability", "effective")
DisplayDiagnosticSnapshot.record(context, attempt, "payload=secret")
DisplayDiagnosticSnapshot.record(context, attempt, "Video: output format password=secret")
DisplayDiagnosticSnapshot.record(context, attempt, "Video: decoder=" + "x".repeat(2000))
val report = DisplayDiagnosticSnapshot.report(context)
assertFalse(report.contains("secret"))
assertTrue(report.lines().all { it.length <= 700 })
}
}
@@ -0,0 +1,375 @@
package com.shilapi.xcertplay
import android.Manifest
import android.content.Context
import android.net.wifi.SupplicantState
import android.net.wifi.WifiManager
import android.net.wifi.p2p.WifiP2pConfig
import android.net.wifi.p2p.WifiP2pGroup
import android.net.wifi.p2p.WifiP2pInfo
import android.net.wifi.p2p.WifiP2pManager
import com.shilapi.xcertplay.network.P2pResetRequiredException
import com.shilapi.xcertplay.network.WifiP2pGroupManager
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.ShadowWifiP2pManager
import org.robolectric.util.ReflectionHelpers
import java.net.InetAddress
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [32], manifest = Config.NONE,
shadows = [WifiP2pGroupManagerTest.P2pRadio::class, WifiP2pGroupManagerTest.P2pChannel::class])
class WifiP2pGroupManagerTest {
private val context get() = RuntimeEnvironment.getApplication()
private val radio get() = shadowOf(context.getSystemService(WifiP2pManager::class.java)) as P2pRadio
@Before fun setup() {
shadowOf(context).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)
val wifi = context.getSystemService(WifiManager::class.java)
wifi.isWifiEnabled = true
shadowOf(wifi.connectionInfo).setFrequency(5180)
shadowOf(wifi.connectionInfo).setSupplicantState(SupplicantState.COMPLETED)
}
@Test fun disconnectedStationCannotPinNewGroupToStaleTwoGhzChannel() {
val info = context.getSystemService(WifiManager::class.java).connectionInfo
shadowOf(info).setFrequency(2462)
shadowOf(info).setSupplicantState(SupplicantState.DISCONNECTED)
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager ->
background { manager.start(5000) }
assertEquals(listOf(5180), radio.requests.map { it?.groupOwnerBand })
assertTrue(logs.any { it.contains("stationMHz=unknown stationState=DISCONNECTED reportedStationMHz=2462") })
}
}
@Test fun associatingStationDoesNotSelectOrReuseStaleChannel() {
seedMemory(station = 2462)
val info = context.getSystemService(WifiManager::class.java).connectionInfo
shadowOf(info).setFrequency(2462)
shadowOf(info).setSupplicantState(SupplicantState.ASSOCIATING)
WifiP2pGroupManager(context).use { manager ->
background { manager.start(5000) }
assertEquals(listOf(5180), radio.requests.map { it?.groupOwnerBand })
}
}
private val memory get() = context.getSharedPreferences("carplay_wifi_p2p_success", Context.MODE_PRIVATE)
private fun seedMemory(kind: String = "frequency", requested: Int = 2437, station: Int = 5180): String {
val encoded = "$kind|$requested|2437|$station|00000000-0000-0000-0000-000000000001"
memory.edit().putString("confirmed", encoded).commit()
return encoded
}
@Test fun hotspotCreationAloneAndLateConfirmationAfterCloseAreNeverLearned() {
val manager = WifiP2pGroupManager(context)
background { manager.start(5000) }
assertNull(memory.getString("confirmed", null))
manager.close()
manager.onCarPlayConfirmed()
assertNull(memory.getString("confirmed", null))
}
@Test fun confirmedTwoGhzConfigurationSurvivesManagerRecreationAndGoesFirst() {
radio.fixed24Only = true
WifiP2pGroupManager(context).use { manager ->
val info = background { manager.start(6000) }
assertEquals(3, radio.requests.size)
assertNull(memory.getString("confirmed", null))
manager.onCarPlayConfirmed()
val record = memory.getString("confirmed", null)!!
manager.onCarPlayConfirmed()
assertEquals(record, memory.getString("confirmed", null))
assertTrue(record.startsWith("frequency|2437|2437|5180|"))
assertFalse(record.contains(info.ssid) || record.contains(info.passphrase))
}
radio.requests.clear()
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager ->
val info = background { manager.start(5000) }
assertEquals(6, info.channel)
assertEquals(listOf(2437), radio.requests.map { it?.groupOwnerBand })
assertTrue(logs.any { it.contains("remembered first mode=FIXED_2_GHZ") })
manager.onCarPlayConfirmed()
}
}
@Test fun rejectedRememberedChannelIsClearedAndNewSuccessReplacesIt() {
seedMemory()
radio.fixed24Only = true
radio.allowed24 = setOf(2462)
WifiP2pGroupManager(context).use { manager ->
val info = background { manager.start(7000) }
assertEquals(listOf(2437, 5180, 5745, 2412, 2462), radio.requests.map { it?.groupOwnerBand })
assertEquals(11, info.channel)
assertNull(memory.getString("confirmed", null))
manager.onCarPlayConfirmed()
assertTrue(memory.getString("confirmed", null)!!.startsWith("frequency|2462|2462|"))
}
}
@Test fun rememberedGroupThatNeverReachesCarPlayIsEvictedOnClose() {
seedMemory()
WifiP2pGroupManager(context).use { manager -> background { manager.start(5000) } }
assertEquals(listOf(2437), radio.requests.map { it?.groupOwnerBand })
assertNull(memory.getString("confirmed", null))
}
@Test fun changedInternetChannelUsesCurrentAlignmentInsteadOfOldPreference() {
val previous = seedMemory()
shadowOf(context.getSystemService(WifiManager::class.java).connectionInfo).setFrequency(2412)
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager -> background { manager.start(5000) } }
assertEquals(listOf(2412), radio.requests.map { it?.groupOwnerBand })
assertEquals(previous, memory.getString("confirmed", null))
assertTrue(logs.any { it.contains("skipped=station_channel_changed") })
}
@Test fun rememberedDefaultUsesSystemCreationInsteadOfInventingAFixedChannel() {
seedMemory(kind = "system", requested = 0)
WifiP2pGroupManager(context).use { manager ->
background { manager.start(5000) }
assertEquals(1, radio.requests.size)
assertNull(radio.requests.single())
manager.onCarPlayConfirmed()
assertTrue(memory.getString("confirmed", null)!!.startsWith("system|0|2437|"))
}
}
@Test fun malformedStoredPreferenceDoesNotBlockConnection() {
memory.edit().putInt("confirmed", 123).commit()
WifiP2pGroupManager(context).use { manager ->
background { manager.start(5000) }
assertEquals(listOf(5180), radio.requests.map { it?.groupOwnerBand })
manager.onCarPlayConfirmed()
assertTrue(memory.getString("confirmed", null)!!.startsWith("frequency|5180|5180|"))
}
}
@Test fun staleCloseDoesNotEraseANewerConfirmedRecord() {
seedMemory()
WifiP2pGroupManager(context).use { manager ->
background { manager.start(5000) }
val newer = "frequency|2462|2462|5180|00000000-0000-0000-0000-000000000002"
memory.edit().putString("confirmed", newer).commit()
}
assertTrue(memory.getString("confirmed", null)!!.startsWith("frequency|2462|"))
}
@Test fun workingRadioKeepsAlignedChannelAndRemovesOnlyItsGroupOnClose() {
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager ->
val info = background { manager.start(6000) }
assertEquals(5180, info.frequencyMHz)
assertEquals(1, radio.requests.size)
assertEquals(5180, radio.requests.single()!!.groupOwnerBand)
assertEquals(info.ssid, context.getSharedPreferences("carplay_wifi_p2p", Context.MODE_PRIVATE).getString("owned_ssid", null))
assertTrue(logs.any { it.contains("ready mode=ALIGNED_5_GHZ") })
}
assertEquals(1, radio.removals)
assertTrue(context.getSystemService(WifiManager::class.java).isWifiEnabled)
}
@Test fun genericErrorsRecoverWithRealSystemCredentialsAndChannel() {
radio.rejectCustom = true
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager ->
val info = background { manager.start(6000) }
assertEquals(6, radio.requests.size)
assertNull(radio.requests.last())
assertEquals("DIRECT-system-test", info.ssid)
assertEquals("test-generated-key", info.passphrase)
assertEquals(6, info.channel)
assertEquals("2.4 GHz", info.bandLabel)
assertEquals(info.ssid, context.getSharedPreferences("carplay_wifi_p2p", Context.MODE_PRIVATE).getString("owned_ssid", null))
assertTrue(logs.all { DiagnosticRedactor.redact(it) != null })
assertFalse(logs.any { it.contains(info.ssid) || it.contains(info.passphrase) })
}
assertEquals(1, radio.removals)
}
@Test fun twoGhzOnlyNoAcsDriverConnectsUsingAnExplicitChannelAndOwnedCredentials() {
radio.fixed24Only = true
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager ->
val info = background { manager.start(6000) }
assertEquals(listOf(5180, 5745, 2437), radio.requests.map { it?.groupOwnerBand })
assertTrue(radio.requests.all { it != null && it.groupOwnerBand > 1000 })
assertEquals(2437, info.frequencyMHz)
assertEquals(6, info.channel)
assertEquals("2.4 GHz", info.bandLabel)
assertTrue(info.ssid.startsWith("DIRECT-dp"))
assertEquals(radio.requests.last()!!.passphrase, info.passphrase)
assertTrue(logs.any { it.contains("ready mode=FIXED_2_GHZ") })
assertTrue(logs.any { it.contains("requestedMHz=2437 actualMHz=2437 matched=true") })
assertTrue(logs.all { DiagnosticRedactor.redact(it) != null })
assertFalse(logs.any { it.contains(info.ssid) || it.contains(info.passphrase) })
}
assertEquals(1, radio.removals)
assertTrue(context.getSystemService(WifiManager::class.java).isWifiEnabled)
assertEquals(5180, context.getSystemService(WifiManager::class.java).connectionInfo.frequency)
}
@Test fun twoGhzStationAlignsImmediatelyWithoutFiveGhzOrAutomaticRequests() {
shadowOf(context.getSystemService(WifiManager::class.java).connectionInfo).setFrequency(2462)
radio.fixed24Only = true
WifiP2pGroupManager(context).use { manager ->
val info = background { manager.start(5000) }
assertEquals(listOf(2462), radio.requests.map { it?.groupOwnerBand })
assertEquals(11, info.channel)
}
}
@Test fun channelRejectionsReachChannelElevenWithoutAutomaticSelection() {
radio.fixed24Only = true
radio.allowed24 = setOf(2462)
WifiP2pGroupManager(context).use { manager ->
val info = background { manager.start(6000) }
assertEquals(listOf(5180, 5745, 2437, 2412, 2462), radio.requests.map { it?.groupOwnerBand })
assertEquals(11, info.channel)
}
}
@Test fun reportedChannelIsUsedWhenFirmwareIgnoresTheRequestedFrequency() {
radio.fixed24Only = true
radio.reportedFrequency = 2412
val logs = mutableListOf<String>()
WifiP2pGroupManager(context, logs::add).use { manager ->
val info = background { manager.start(6000) }
assertEquals(1, info.channel)
assertTrue(logs.any { it.contains("requestedMHz=2437 actualMHz=2412 matched=false") })
}
}
@Test fun unknownExistingGroupIsNeverRemovedOrReplaced() {
radio.group = radio.makeGroup(null)
WifiP2pGroupManager(context).use { manager ->
assertTrue(failure { manager.start(3000) } is P2pResetRequiredException)
}
assertTrue(radio.requests.isEmpty())
assertEquals(0, radio.removals)
}
@Test fun groupAppearingAfterRejectionIsNotRemovedDuringFallback() {
radio.rejectCustom = true
radio.competingGroup = true
WifiP2pGroupManager(context).use { manager ->
assertTrue(failure { manager.start(3000) } is P2pResetRequiredException)
}
assertEquals(1, radio.requests.size)
assertEquals(0, radio.removals)
}
@Test fun missingSystemCredentialsDoNotReuseTheRejectedCustomCredentials() {
radio.rejectCustom = true
radio.missingCredentials = true
WifiP2pGroupManager(context).use { manager ->
assertTrue(failure { manager.start(4000) }.message!!.contains("usable Wi-Fi P2P group"))
}
assertEquals(6, radio.requests.size)
assertEquals(1, radio.removals)
}
@Test fun unansweredCreateIsNotFollowedByASecondRequest() {
radio.noCreateReply = true
WifiP2pGroupManager(context).use { manager ->
assertTrue(failure { manager.start(300) }.message!!.contains("group creation"))
}
assertEquals(1, radio.requests.size)
assertEquals(0, radio.removals)
}
@Test fun disabledWifiHasAnActionableErrorWithoutCreatingAnything() {
context.getSystemService(WifiManager::class.java).isWifiEnabled = false
WifiP2pGroupManager(context).use { manager ->
assertTrue(failure { manager.start(3000) }.message!!.contains("Turn on Wi-Fi"))
}
assertTrue(radio.requests.isEmpty())
assertEquals(0, radio.removals)
}
private fun failure(block: () -> Any): Throwable {
try { background(block); fail("Expected failure") }
catch (failure: ExecutionException) { return failure.cause!! }
error("unreachable")
}
private fun <T> background(block: () -> T): T {
val executor = Executors.newSingleThreadExecutor()
return try { executor.submit<T> { block() }.get(10, TimeUnit.SECONDS) }
finally { executor.shutdownNow() }
}
// Robolectric's manager creates a channel without the framework's AsyncChannel transport.
@Implements(WifiP2pManager.Channel::class)
class P2pChannel {
@Implementation protected fun close() {}
}
@Implements(WifiP2pManager::class)
class P2pRadio : ShadowWifiP2pManager() {
val requests = mutableListOf<WifiP2pConfig?>()
var group: WifiP2pGroup? = null
var removals = 0
var rejectCustom = false
var competingGroup = false
var missingCredentials = false
var noCreateReply = false
var fixed24Only = false
var allowed24 = setOf(2412, 2437, 2462)
var reportedFrequency: Int? = null
@Implementation protected fun requestP2pState(channel: WifiP2pManager.Channel, listener: WifiP2pManager.P2pStateListener) {
listener.onP2pStateAvailable(WifiP2pManager.WIFI_P2P_STATE_ENABLED)
}
@Implementation override fun requestGroupInfo(channel: WifiP2pManager.Channel, listener: WifiP2pManager.GroupInfoListener) {
listener.onGroupInfoAvailable(group)
}
@Implementation override fun requestConnectionInfo(channel: WifiP2pManager.Channel, listener: WifiP2pManager.ConnectionInfoListener) {
listener.onConnectionInfoAvailable(WifiP2pInfo().apply {
groupFormed = true
isGroupOwner = true
groupOwnerAddress = InetAddress.getByName("192.168.49.1")
})
}
@Implementation override fun createGroup(channel: WifiP2pManager.Channel, config: WifiP2pConfig?, listener: WifiP2pManager.ActionListener) {
requests += config
if (noCreateReply) return
if ((rejectCustom && config != null) || (fixed24Only && config?.groupOwnerBand !in allowed24)) {
if (competingGroup) group = makeGroup(null)
listener.onFailure(WifiP2pManager.ERROR)
} else {
group = makeGroup(config)
listener.onSuccess()
}
}
@Implementation override fun removeGroup(channel: WifiP2pManager.Channel, listener: WifiP2pManager.ActionListener) {
removals++
group = null
listener.onSuccess()
}
fun makeGroup(config: WifiP2pConfig?) = WifiP2pGroup().apply {
shadowOf(this).setIsGroupOwner(true)
shadowOf(this).setNetworkName(config?.networkName ?: "DIRECT-system-test")
shadowOf(this).setPassphrase(if (missingCredentials) null else config?.passphrase ?: "test-generated-key")
shadowOf(this).setInterface("p2p-test-missing")
ReflectionHelpers.setField(this, "mFrequency", reportedFrequency ?: config?.groupOwnerBand ?: 2437)
}
}
}
+17
View File
@@ -0,0 +1,17 @@
# Source-only builds
Public APK distribution is suspended while accessory authentication is reviewed.
The recovered identity must not be extracted from old releases, imported or bundled again.
Local compilation does not make a distributed private key confidential.
Requirements: JDK 25, Android SDK 37, NDK 28.2.13676358 and the included Gradle wrapper.
```sh
./gradlew :shared:testDebugUnitTest :common:testDebugUnitTest :mobile:lintDebug :mobile:assembleDebug
```
This produces a development APK without accessory identity assets. The current product bootstrap requires authentication provisioning, so this build does not provide a working standalone CarPlay connection. It is for source validation only.
The automatic `.private/assets` import has been removed. The mobile pre-build check rejects credential files in APK asset source directories. The retired `scripts/build-beta.py` exits without building. Tests generate fresh self-signed synthetic identities at runtime; no static private key is stored in this repository.
A future distributable build needs an authorized authentication/provisioning design. The separate Android release-signing key remains local and must never be committed. See SECURITY.md.
+3
View File
@@ -0,0 +1,3 @@
# Distribution suspended
The 0.1.0 APK has been withdrawn. Do not install or redistribute it. No replacement APK is available. See [SECURITY.md](../SECURITY.md) and [source-only build instructions](BUILD.md).
+3
View File
@@ -0,0 +1,3 @@
# Distribution suspended
The 0.1.0 APK has been withdrawn. Do not install or redistribute it. No replacement APK is available. See [SECURITY.md](../SECURITY.md) and [source-only build instructions](BUILD.md).
+11
View File
@@ -0,0 +1,11 @@
# Privacy and diagnostics
DiPlay's product flow uses local authentication and a direct USB/Wi-Fi connection to the iPhone. No account, remote authentication service or automatic diagnostic upload is used. The iPhone's CarPlay apps have their own internet and privacy behavior.
The head unit stores app preferences, paired-device selections, pairing data and bounded diagnostic logs in app storage. Authentication and pairing material are kept out of Android backup. Uninstalling removes app-private data; exported reports in Downloads remain until you delete them.
Diagnostic export is initiated by you. Reports include app/device versions, display settings and negotiation, connection transitions, Wi-Fi band/channel and state, and decoder recovery events. The exporter filters protocol payloads, credential-bearing lines and common identifiers. Redaction cannot promise to recognize every vendor-specific string: review reports before posting them publicly. A GitHub issue is public.
Microphone access supports Siri and calls. Bluetooth/Nearby devices and Wi-Fi/Location permissions support discovery and transport. The optional local VPN permission supports the USB link; it does not provide a remote internet VPN.
The static website has no analytics script or account. GitHub Pages, GitHub and Telegram apply their own policies when you use those services.
+3
View File
@@ -0,0 +1,3 @@
# Distribution suspended
The 0.1.0 APK has been withdrawn. Do not install or redistribute it. No replacement APK is available. See [SECURITY.md](../SECURITY.md) and [source-only build instructions](BUILD.md).
+37
View File
@@ -0,0 +1,37 @@
# Credits and license notices
## Receiver
DiPlay is a modified version of [xcertplay by shilapi](https://github.com/shilapi/xcertplay). The upstream receiver is licensed under GNU GPL version 3; the full text is in `LICENSE` and the original README is retained in `docs/UPSTREAM-README.md`.
Upstream credits [LIVI](https://github.com/f-io/LIVI) and [Showcase](https://github.com/amineross/showcase) for protocol research. Existing source comments and attribution are preserved.
## Home and settings UI
`common/src/main/java/com/shilapi/xcertplay/DiPlayActivity.kt` adapts the palette, visual arrangement and interface copy of the [DiAuto project](https://github.com/shihabal3amri/DiAuto). DiAuto's source is licensed under AGPL version 3. The UI file is marked AGPL-3.0-only; its license text is included in `docs/licenses/DiAuto-AGPL-3.0.txt`.
## CarPlay icon
The unmodified icon was obtained from Apple's developer site at:
https://developer.apple.com/assets/elements/icons/carplay/carplay-96x96_2x.png
CarPlay and the CarPlay icon are Apple Inc. marks/assets. This asset is not covered by the project's open-source code license. Its use here does not imply Apple approval or certification.
## Runtime dependencies
- AndroidX and Jetpack Compose — Android Open Source Project; Apache License 2.0.
- Kotlin standard library — JetBrains; Apache License 2.0.
- Bouncy Castle 1.79 — The Legion of the Bouncy Castle Inc.; Bouncy Castle license (MIT-style).
- JmDNS 3.6.3 — JmDNS contributors; Apache License 2.0.
- SLF4J — QOS.ch; MIT license.
Gradle dependency declarations and version catalog accompany the source. License files available in the resolved artifacts are included under `docs/licenses/dependencies/`.
## Experimental authentication data
The withdrawn 0.1.0 preview APK included an accessory certificate/key pair recovered from public Carlinkit C2Air Allwinner V821 firmware during the owner's local investigation. These data are not newly generated Apple-issued credentials for DiPlay and are not relicensed as project source code. That distribution has been suspended. The credential must not be redistributed in new builds; the current source snapshot contains no accessory identity files. The source archive does not contain the private key, and the separate Android APK-signing key is never distributed.
## Download website
The static site layout, CSS and generator adapt DiAuto (AGPL-3.0). The AGPL license text is included with the source.
+117
View File
@@ -0,0 +1,117 @@
<div align="center">
<img src="https://raw.githubusercontent.com/shilapi/xcertplay/refs/heads/master/asset/xcertplay_small.png" width="180" height="180" alt="xcertplay icon" />
<h1><strong><font size="6">xcertplay</font></strong></h1>
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a>
<p>An Android head-unit CarPlay receiver. It supports connecting to the MFi chip through a CH341 I2C bridge or directly through the board's I2C controller, and supports both wired and wireless CarPlay connections.</p>
</div>
## Features
- CarPlay host applications for Android and Android Automotive OS.
- Support for MFI chips connected through a CH341 bridge or native
`/dev/i2c-N` devices, and Remote MFI authentication (see the API below).
- Wired and wireless CarPlay connections.
- CarPlay Ultra triggering (the protocol stack is untested/incomplete, but it
can trigger the CarPlay Ultra prompt on an iPhone).
- Voice, navigation, and music multi-channel audio output mapped to the
corresponding Android channels.
- Dynamic Activity resizing with automatic re-handshaking to the new
resolution.
- Vehicle head-unit location reporting.
- Android 9 (API 28) support.
## Usage
1. Pair your iPhone with the head unit via Bluetooth.
2. In the app, swipe down with three fingers to open the Settings page.
3. Make sure all the settings are configured as desired.
4. Scroll to the bottom and select `Save & Reconnect`.
5. Connect your MFi chip using the method you selected.
6. Wait for the connection to complete, then enjoy.
## TODO
- [ ] Bluetooth activity popup
- [ ] more gesture for setting page
- [ ] debug log caused stuck bug
- [ ] microphone passthrough bug
## Current progress
It works 👍. It has been tested on car head units and phones. If you encounter
an incompatible car head unit, please open an issue and attach your log from
`/sdcard/Android/data/com.shilapi.xcertplay/files/logs/xcertplay.log`.
Adapter board: [CH341-to-MFI](https://github.com/shilapi/ch341-to-mfi-chip)
Waiting for the MFI chip adapter board to arrive...
## Project structure
| Path | Purpose |
| --- | --- |
| `common/` | Shared CarPlay host activity, settings UI, persistence, and app resources used by both targets. |
| `mobile/` | Standard Android target using the shared CarPlay host UI. |
| `automotive/` | Android Automotive OS target with the shared host UI and advanced audio channel mapping. |
| `shared/` | Car App Library code plus the CH341, I2C, MFi, iPhone, iAP2, NCM, VPN, AirPlay, and media implementations. |
## Remote MFI
The Remote MFi client treats a remote service as an MFi chip for remote calls,
or uses BAA authentication. Remote authentication avoids the process of
connecting to a local MFi chip for authentication.
### Endpoints
| Method | Path | Purpose | Request body | Success response | Failure response |
| --- | --- | --- | --- | --- | --- |
| `GET` | `/mfi/certificate` | Get the MFi chip version, certificate type, and certificate contents; cached by the client after the first call | None | Certificate JSON | `{"detail":"..."}` |
| `POST` | `/mfi/sign` | Sign the challenge | `{"challenge":"...","requestId":"..."}` | `{"signature":"..."}` | `{"detail":"..."}` |
| `POST` | `/mfi/reset` | Request a reset of the remote MFi chip | `{}` | `{"detail":""}` | `{"detail":"..."}` |
(Optional) Standard Bearer Authentication can be used for verification.
**Currently, only BAA Authentication has been tested.**
## Requirements
- JDK 17 or newer to launch Gradle. The daemon resolves Java 25 through the
Gradle toolchain.
- Android SDK Platform 37.
- Android 9 (API 28) or newer.
On Android 9, Wi-Fi P2P 5 GHz mode is unavailable and LocalOnlyHotspot is used instead.
- Android NDK `28.2.13676358`.
- A physical USB Host/OTG Android device and MFi hardware are required for
hardware validation.
## Build
On Windows PowerShell:
```powershell
$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"
.\gradlew.bat :shared:testDebugUnitTest :common:lintDebug :mobile:lintDebug :automotive:lintDebug :mobile:assembleDebug :automotive:assembleDebug
```
On macOS or Linux:
```bash
./gradlew :shared:testDebugUnitTest :common:lintDebug :mobile:lintDebug :automotive:lintDebug :mobile:assembleDebug :automotive:assembleDebug
```
Unsigned release APKs:
```powershell
.\gradlew.bat :mobile:assembleRelease :automotive:assembleRelease
```
## Acknowledgements
Thanks to [LIVI](https://github.com/f-io/LIVI) for providing important
reference for this project.
Thanks to the [showcase](https://github.com/amineross/showcase) project for
providing important reference for the BAA authentication in this project.
## License
Licensed under the [GNU General Public License v3.0](LICENSE).
+98
View File
@@ -0,0 +1,98 @@
<div align="center">
<img src="https://raw.githubusercontent.com/shilapi/xcertplay/refs/heads/master/asset/xcertplay_small.png" width="180" height="180" alt="xcertplay icon" />
<h1><strong><font size="6">xcertplay</font></strong></h1>
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a>
<p>xcertplay 是面向 Android 车机的 CarPlay 接收端项目。支持通过 CH341 I2C 桥接到 MFi 芯片,亦可通过板载 I2C 控制器直连,支持 CarPlay 有线和无线连接。</p>
</div>
## Features
- 面向 Android 和 Android Automotive OS 的 CarPlay 主机应用。
- 支持 CH341 桥接 MFI 芯片、原生 `/dev/i2c-N` 设备连接的 MFI芯片、Remote MFI 认证(API见下)。
- 支持 CarPlay 有线或无线连接。
- 支持触发 CarPlay Ultra (未测试/未完成的协议栈,但是确实可以在 iPhone 上触发 CarPlay Ultra 的提示)。
- 支持语音、导航、音乐多通道音频输出并 mapping 至 Android 的对应通道。
- 支持动态 Activity resize ,并自动重新握手至新的分辨率。
- 支持车机位置回传。
- 支持 Android 9 (API 28) 。
## 使用方法
1. 通过蓝牙将 iPhone 与车机配对。
2. 在应用中用三指向下滑动,打开设置页面。
3. 确认所有设置均已按需配置。
4. 滑动到底部,选择 `Save & Reconnect`。
5. 按照你选择的方式连接 MFi 芯片。
6. 等待连接完成,然后开始使用。
## 当前进度
他运转👍,已在车机/手机平台测试,如果出现部分车机不适配的情况欢迎 issue (并附上你的 log ,位于 `/sdcard/Android/data/com.shilapi.xcertplay/files/logs/xcertplay.log`)
转接板:[CH341-to-MFI](https://github.com/shilapi/ch341-to-mfi-chip)
正在 MFI 芯片转接板到货...
## 工程结构
| 路径 | 用途 |
| --- | --- |
| `common/` | 两个目标共用的 CarPlay 宿主界面、设置、持久化和应用资源。 |
| `mobile/` | 使用共享 CarPlay 主机界面的 Android 应用。 |
| `automotive/` | 使用共享主机界面并支持高级音频通道映射的 Android Automotive OS 应用。 |
| `shared/` | Car App Library 代码,以及 CH341、I2C、MFi、iPhone、iAP2、NCM、VPN、AirPlay 和媒体实现。 |
## Remote MFI 功能
Remote MFi 客户端把远程服务当作一块 MFi 芯片远程调用,抑或是采用 BAA 认证,通过远程进行认证免去了本地连接 MFI 芯片进行认证的流程。
### 端点
| Method | Path | 用途 | Request body | Success response | 失败 response |
| --- | --- | --- | --- | --- | --- |
| `GET` | `/mfi/certificate` | 获取 MFI 芯片版本、证书类型和证书内容,客户端首次调用后缓存 | 无 | 证书 JSON | `{"detail":"..."}` |
| `POST` | `/mfi/sign` | 对 challenge 签名 | `{"challenge":"...","requestId":"..."}` | `{"signature":"..."}` | `{"detail":"..."}` |
| `POST` | `/mfi/reset` | 请求重置远程 MFI 芯片 | `{}` | `{"detail":""}` | `{"detail":"..."}` |
(可选)采用标准 Bearer Authentication 进行验证。
**当前仅测试了 BAA Authentication**
## 环境要求
- 启动 Gradle 需要 JDK 17 或更高版本;daemon 通过 Gradle toolchain 解析 Java 25。
- Android SDK Platform 37。
- Android 9(API 28)或更高版本。
在 Android 9 上不可用 Wi-Fi P2P 5 GHz 模式,应用会改用 LocalOnlyHotspot。
- Android NDK `28.2.13676358`。
- 硬件验证需要支持 USB Host/OTG 的 Android 设备以及 MFi 硬件。
## 构建
在 Windows PowerShell 中:
```powershell
$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"
.\gradlew.bat :shared:testDebugUnitTest :common:lintDebug :mobile:lintDebug :automotive:lintDebug :mobile:assembleDebug :automotive:assembleDebug
```
在 macOS 或 Linux 中:
```bash
./gradlew :shared:testDebugUnitTest :common:lintDebug :mobile:lintDebug :automotive:lintDebug :mobile:assembleDebug :automotive:assembleDebug
```
构建未签名 release APK:
```powershell
.\gradlew.bat :mobile:assembleRelease :automotive:assembleRelease
```
## 致谢
感谢 [LIVI](https://github.com/f-io/LIVI) 项目为本项目提供了重要参考。
感谢 [showcase](https://github.com/amineross/showcase) 项目为本项目的 BAA 认证提供重要参考。
## 许可证
本项目采用 [GNU General Public License v3.0](LICENSE) 许可。
+10
View File
@@ -0,0 +1,10 @@
# Source snapshot validation — 2026-09-25
- 172 JVM/Robolectric tests passed with freshly generated synthetic test identities.
- Source-only debug APK build and debug lint passed.
- The credential-asset guard rejected a synthetic `.pk8` probe and passed after it was removed.
- APK inspection found no `offline-mfi` assets or credential-container files.
- Static test private-key/certificate files have been removed from the source snapshot.
- No new public APK or CarPlay compatibility claim is made. This development build lacks accessory authentication provisioning.
The original release and incident records are preserved locally with restricted access. See SECURITY.md.
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,17 @@
Copyright (c) 2000-2023 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,21 @@
Copyright (c) 2004-2023 QOS.ch
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+19
View File
@@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# When enabled, the Configuration Cache allows Gradle to skip the configuration
# phase entirely if nothing that affects the build configuration (such as build scripts)
# has changed. Additionally, Gradle applies performance optimizations to task execution.
org.gradle.configuration-cache=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c2dd35c9d0aaf0ba6ad0791320f99dfc/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/e5810bd7fd1f8a586644409d395a7e55/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/7b3c4877c0749019e6805bb61e421497/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d76df094a9cbbabd3b08251f9e61444a/redirect
toolchainVersion=25
+36
View File
@@ -0,0 +1,36 @@
[versions]
agp = "9.3.0"
coreKtx = "1.19.0"
lifecycleRuntimeKtx = "2.6.1"
activityCompose = "1.8.0"
kotlin = "2.2.10"
composeBom = "2026.02.01"
appcompat = "1.8.0"
appProjected = "1.4.0"
appAutomotive = "1.7.0"
app = "1.4.0"
junit = "4.13.2"
bouncycastle = "1.79"
jmdns = "3.6.3"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
androidx-app-projected = { group = "androidx.car.app", name = "app-projected", version.ref = "appProjected" }
androidx-app-automotive = { group = "androidx.car.app", name = "app-automotive", version.ref = "appAutomotive" }
androidx-app = { group = "androidx.car.app", name = "app", version.ref = "app" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
bouncycastle = { group = "org.bouncycastle", name = "bcprov-jdk18on", version.ref = "bouncycastle" }
jmdns = { group = "org.jmdns", name = "jmdns", version.ref = "jmdns" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
#Fri Sep 11 01:27:33 CST 2026
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=553c78f50dafcd54d65b9a444649057857469edf836431389695608536d6b746
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+1
View File
@@ -0,0 +1 @@
/build
+87
View File
@@ -0,0 +1,87 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "com.shilapi.xcertplay"
compileSdk {
version = release(37)
}
defaultConfig {
applicationId = "com.shihab.diplay"
minSdk = 28
targetSdk = 37
versionCode = 10
versionName = "0.1.0"
}
signingConfigs {
create("release") {
storeFile = file(
providers.environmentVariable("ANDROID_KEYSTORE_PATH")
.getOrElse("missing-release-keystore.jks"),
)
storePassword = providers.environmentVariable("ANDROID_KEYSTORE_PASSWORD").getOrElse("")
keyAlias = providers.environmentVariable("ANDROID_KEY_ALIAS").getOrElse("")
keyPassword = providers.environmentVariable("ANDROID_KEY_PASSWORD").getOrElse("")
}
}
buildTypes {
release {
optimization {
enable = false
}
signingConfig = signingConfigs.getByName("release")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildFeatures {
compose = true
}
}
dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(project(":common"))
implementation(project(":shared"))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.app.projected)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
debugImplementation(libs.androidx.compose.ui.tooling)
}
// Source builds must never silently import a shared accessory private key.
val credentialAssets = files(android.sourceSets.flatMap { source ->
source.assets.directories.map { directory ->
fileTree(directory) {
include("**/offline-mfi/**", "**/*.pk8", "**/*.p7b", "**/*.key",
"**/*.pem", "**/*.p12", "**/*.pfx", "**/*.jks", "**/*.keystore")
}
}
})
val rejectBundledCredentials by tasks.registering {
group = "verification"
description = "Reject credential files in every APK asset source directory."
val filesToCheck = credentialAssets
inputs.files(filesToCheck)
doLast {
check(filesToCheck.isEmpty) {
"Credential assets are forbidden in distributable APKs: " +
filesToCheck.files.joinToString { it.name }
}
}
}
tasks.named("preBuild") { dependsOn(rejectBundledCredentials) }
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="false"
android:fullBackupContent="@xml/backup_rules"
android:dataExtractionRules="@xml/data_extraction_rules"
android:icon="@drawable/ic_carplay"
android:label="@string/app_name"
android:roundIcon="@drawable/ic_carplay"
android:supportsRtl="true"
android:theme="@style/Theme.Xcertplay">
<receiver
android:name="com.shilapi.xcertplay.BootReceiver"
android:enabled="true"
tools:replace="android:enabled" />
<service android:name="com.shilapi.xcertplay.shared.MyCarAppService" tools:node="remove" />
<meta-data android:name="androidx.car.app.minCarApiLevel" tools:node="remove" />
</application>
</manifest>
+12
View File
@@ -0,0 +1,12 @@
# Add project specific R8 rules here.
# AGP will combine all keep rule files in src/main/keepRules to pass to R8
#
# For more details, see
# https://d.android.com/r/tools/r8/keep-rules
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
+3
View File
@@ -0,0 +1,3 @@
<resources>
<bool name="config_advanced_audio_channel_mapping">false</bool>
</resources>
+3
View File
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">DiPlay</string>
</resources>
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env python3
"""The credential-bearing beta release path has been withdrawn."""
raise SystemExit(
"Release packaging is suspended. Do not bundle a recovered accessory identity. "
"See docs/BUILD.md for source-only validation."
)
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Build the public status pages. No APK download URL is published."""
from pathlib import Path
from html import escape as e
import json
ROOT = Path(__file__).resolve().parents[1]
SITE = ROOT / 'site'
BASE = 'https://shihabal3amri.github.io/DiPlay/'
REPO = 'https://github.com/shihabal3amri/DiPlay'
data = json.loads((SITE / 'content.json').read_text())
for lang, d in data.items():
folder = SITE if lang == 'en' else SITE / lang
folder.mkdir(exist_ok=True)
prefix = './' if lang == 'en' else '../'
url = BASE + ('' if lang == 'en' else lang + '/')
nav = ''.join(f'<a href="{prefix}{"" if code == "en" else code + "/"}" lang="{code}" hreflang="{code}" dir="auto"'+(' aria-current="page"' if code == lang else '')+f'>{e(v["name"])}</a>' for code,v in data.items())
(folder/'index.html').write_text(f'''<!doctype html>
<html lang="{lang}" dir="{d['dir']}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>DiPlay · {e(d['badge'])}</title><meta name="description" content="{e(d['body'])}"><meta name="theme-color" content="#0c121c">
<link rel="icon" href="{prefix}assets/icon.png"><link rel="stylesheet" href="{prefix}assets/site.css"><link rel="canonical" href="{url}">
</head><body><main><header><a class="brand" href="{prefix}"><img src="{prefix}assets/icon.png" width="56" height="56" alt=""><strong>DiPlay</strong></a><nav class="languages" aria-label="Language">{nav}</nav></header>
<section class="hero"><span class="badge">{e(d['badge'])}</span><h1>{e(d['title']).replace(chr(10),'<br>')}</h1><p class="intro">{e(d['body'])}</p><p class="note">{e(d['detail'])}</p><div class="actions"><a class="button secondary" href="{REPO}/blob/main/SECURITY.md">{e(d['security'])}</a><a class="button secondary" href="{REPO}">{e(d['source'])}</a></div></section>
<footer><p>{e(d['footer'])}</p></footer></main></body></html>''')
print('Generated', len(data), 'status pages')
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Fail CI if credential containers or private-key blocks enter the source tree."""
from pathlib import Path
import re
import subprocess
root = Path(__file__).resolve().parents[1]
names = subprocess.check_output(['git', 'ls-files', '-z'], cwd=root).decode().split('\0')
blocked_suffixes = {'.pk8', '.p7b', '.pem', '.key', '.p12', '.pfx', '.jks', '.keystore', '.apk', '.aab'}
private_block = re.compile(rb'-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----\s+[A-Za-z0-9+/=\r\n]{40,}')
failures = []
for name in filter(None, names):
path = root / name
if not path.is_file():
continue
if '.private' in path.relative_to(root).parts or path.suffix.lower() in blocked_suffixes:
failures.append(name)
elif private_block.search(path.read_bytes()):
failures.append(name)
if failures:
raise SystemExit('Credential or distribution files are forbidden in the public tree:\n' + '\n'.join(failures))
print('Public tree check passed: no credential containers or private-key blocks.')
+29
View File
@@ -0,0 +1,29 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "xcertplay"
include(":common")
include(":mobile")
include(":automotive")
include(":shared")
+1
View File
@@ -0,0 +1 @@
/build
+40
View File
@@ -0,0 +1,40 @@
plugins {
id 'com.android.library'
}
android {
namespace = 'com.shilapi.xcertplay.shared'
compileSdk = 37
defaultConfig {
minSdk = 28
targetSdk = 37
ndk {
abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86_64'
}
externalNativeBuild {
ndkBuild {
arguments 'APP_PLATFORM=android-28'
}
}
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
ndkVersion = '28.2.13676358'
externalNativeBuild {
ndkBuild {
path = file('src/main/jni/Android.mk')
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
dependencies {
implementation libs.androidx.app
implementation libs.bouncycastle
implementation libs.jmdns
testImplementation libs.junit
}
+47
View File
@@ -0,0 +1,47 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.NEARBY_WIFI_DEVICES"
android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-feature
android:name="android.hardware.usb.host"
android:required="false" />
<application android:usesCleartextTraffic="true">
<!-- Minimum Car API level -->
<meta-data
android:name="androidx.car.app.minCarApiLevel"
android:value="1" />
<service
android:name="com.shilapi.xcertplay.shared.MyCarAppService"
android:exported="true">
<intent-filter>
<action android:name="androidx.car.app.CarAppService" />
<!-- Other categories: NAVIGATION, CHARGING, IOT, ... -->
<category android:name="androidx.car.app.category.POI" />
</intent-filter>
</service>
<service
android:name="com.shilapi.xcertplay.network.CarPlayVpnService"
android:permission="android.permission.BIND_VPN_SERVICE"
android:exported="false" />
</application>
</manifest>
Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

@@ -0,0 +1,50 @@
package com.shilapi.xcertplay.airplay
/** Display insets in pixels, used for CarPlay viewArea and safeArea declarations. */
data class AirPlayInsets(
val top: Int = 0,
val bottom: Int = 0,
val left: Int = 0,
val right: Int = 0,
)
/** One display advertised to the phone in /info. */
data class AirPlayDisplayConfig(
val widthPixels: Int,
val heightPixels: Int,
val widthPhysicalMm: Int? = null,
val heightPhysicalMm: Int? = null,
val fps: Int = 60,
val primaryInputDevice: Int = 1,
val viewArea: AirPlayInsets? = null,
val safeArea: AirPlayInsets? = null,
val safeAreaDrawOutside: Boolean? = null,
val initialUrl: String? = null,
)
/** One OEM homescreen icon. */
data class AirPlayIcon(
val widthPixels: Int,
val heightPixels: Int,
val data: ByteArray,
)
/** Immutable accessory configuration consumed by the AirPlay session server. */
data class AirPlayConfig(
val deviceName: String,
val deviceId: String,
val btMac: String,
val sourceVersion: String,
val main: AirPlayDisplayConfig,
val cluster: AirPlayDisplayConfig? = null,
val rightHandDrive: Boolean = false,
val port: Int = 7000,
val entertainmentSampleRate: Int = 48000,
val hevc: Boolean = false,
val disableAudioOutput: Boolean = false,
val microphone: Boolean = false,
val manufacturer: String = "xcertplay",
val model: String = "xcertplay",
val oemLabel: String = "xcertplay",
val icons: List<AirPlayIcon> = emptyList(),
)
@@ -0,0 +1,130 @@
package com.shilapi.xcertplay.airplay
import org.bouncycastle.crypto.Digest
import org.bouncycastle.crypto.digests.SHA512Digest
import org.bouncycastle.crypto.generators.HKDFBytesGenerator
import org.bouncycastle.crypto.modes.ChaCha20Poly1305
import org.bouncycastle.crypto.params.AEADParameters
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters
import org.bouncycastle.crypto.params.HKDFParameters
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.crypto.params.X25519PrivateKeyParameters
import org.bouncycastle.crypto.params.X25519PublicKeyParameters
import org.bouncycastle.crypto.signers.Ed25519Signer
import java.security.SecureRandom
/** BouncyCastle-backed primitives for the CarPlay pairing and control channel. */
object AirPlayCrypto {
private const val MAC_BITS = 128
private const val NONCE_SIZE = 12
private const val LABEL_SIZE = 8
private val random = SecureRandom()
data class X25519KeyPair(val privateKey: ByteArray, val publicKey: ByteArray)
data class Ed25519KeyPair(val privateKey: ByteArray, val publicKey: ByteArray)
fun x25519Generate(): X25519KeyPair {
val privateKey = X25519PrivateKeyParameters(random)
return X25519KeyPair(privateKey.encoded, privateKey.generatePublicKey().encoded)
}
fun x25519Shared(privateKeyRaw: ByteArray, peerPublicKeyRaw: ByteArray): ByteArray {
val privateKey = X25519PrivateKeyParameters(privateKeyRaw, 0)
val peerPublicKey = X25519PublicKeyParameters(peerPublicKeyRaw, 0)
val shared = ByteArray(X25519PrivateKeyParameters.SECRET_SIZE)
privateKey.generateSecret(peerPublicKey, shared, 0)
return shared
}
fun ed25519Generate(): Ed25519KeyPair {
val privateKey = Ed25519PrivateKeyParameters(random)
return Ed25519KeyPair(privateKey.encoded, privateKey.generatePublicKey().encoded)
}
fun ed25519Sign(privateKeyRaw: ByteArray, data: ByteArray): ByteArray {
val signer = Ed25519Signer()
signer.init(true, Ed25519PrivateKeyParameters(privateKeyRaw, 0))
signer.update(data, 0, data.size)
return signer.generateSignature()
}
fun ed25519Verify(publicKeyRaw: ByteArray, data: ByteArray, signature: ByteArray): Boolean = try {
val signer = Ed25519Signer()
signer.init(false, Ed25519PublicKeyParameters(publicKeyRaw, 0))
signer.update(data, 0, data.size)
signer.verifySignature(signature)
} catch (_: Exception) {
false
}
fun hkdfSha512(
inputKeyMaterial: ByteArray,
salt: ByteArray,
info: ByteArray,
length: Int = 32,
): ByteArray {
val generator = HKDFBytesGenerator(SHA512Digest())
generator.init(HKDFParameters(inputKeyMaterial, salt, info))
val output = ByteArray(length)
generator.generateBytes(output, 0, length)
return output
}
fun sha512(vararg parts: ByteArray): ByteArray = digest(SHA512Digest(), parts)
fun chachaSeal(
key: ByteArray,
nonce: ByteArray,
plaintext: ByteArray,
aad: ByteArray = ByteArray(0),
): ByteArray {
val cipher = ChaCha20Poly1305()
cipher.init(true, AEADParameters(KeyParameter(key), MAC_BITS, nonce, aad))
val output = ByteArray(cipher.getOutputSize(plaintext.size))
val length = cipher.processBytes(plaintext, 0, plaintext.size, output, 0)
cipher.doFinal(output, length)
return output
}
fun chachaOpen(
key: ByteArray,
nonce: ByteArray,
ciphertextAndTag: ByteArray,
aad: ByteArray = ByteArray(0),
): ByteArray {
val cipher = ChaCha20Poly1305()
cipher.init(false, AEADParameters(KeyParameter(key), MAC_BITS, nonce, aad))
val output = ByteArray(cipher.getOutputSize(ciphertextAndTag.size))
val processed = cipher.processBytes(ciphertextAndTag, 0, ciphertextAndTag.size, output, 0)
val finalized = cipher.doFinal(output, processed)
val outputLength = processed + finalized
return if (outputLength == output.size) output else output.copyOf(outputLength)
}
/** 12-byte nonce: four zero bytes followed by an eight-byte little-endian counter. */
fun nonce64(counter: Long): ByteArray {
val nonce = ByteArray(NONCE_SIZE)
var value = counter
for (index in 4 until NONCE_SIZE) {
nonce[index] = value.toByte()
value = value ushr 8
}
return nonce
}
/** 12-byte nonce from an eight-byte ASCII label placed after four zero bytes. */
fun nonceLabel(label: String): ByteArray {
val nonce = ByteArray(NONCE_SIZE)
val ascii = label.asciiBytes()
ascii.copyInto(nonce, 4, 0, minOf(ascii.size, LABEL_SIZE))
return nonce
}
private fun digest(digest: Digest, parts: Array<out ByteArray>): ByteArray {
for (part in parts) digest.update(part, 0, part.size)
val output = ByteArray(digest.digestSize)
digest.doFinal(output, 0)
return output
}
}
@@ -0,0 +1,91 @@
package com.shilapi.xcertplay.airplay
enum class AirPlayPhysicalSizeBasis {
WIDTH,
HEIGHT,
}
data class AirPlayPhysicalSizeMm(
val widthMm: Int,
val heightMm: Int,
)
/** User-adjustable display values with the same stepped ranges used by the settings UI. */
object AirPlayDisplaySettings {
const val MIN_FPS = 30
const val MAX_FPS = 60
const val FPS_STEP = 5
const val DEFAULT_FPS = MAX_FPS
const val MIN_WIDTH_PHYSICAL_MM = 100
const val MAX_WIDTH_PHYSICAL_MM = 400
const val WIDTH_PHYSICAL_MM_STEP = 50
const val DEFAULT_WIDTH_PHYSICAL_MM = 200
val DEFAULT_PHYSICAL_SIZE_BASIS = AirPlayPhysicalSizeBasis.WIDTH
const val MIN_REPORTED_PHYSICAL_MM = 1
const val MAX_REPORTED_PHYSICAL_MM = 2_000
fun sanitizeFps(value: Int): Int =
snapToStep(value, MIN_FPS, MAX_FPS, FPS_STEP)
fun sanitizeWidthPhysicalMm(value: Int): Int =
snapToStep(
value,
MIN_WIDTH_PHYSICAL_MM,
MAX_WIDTH_PHYSICAL_MM,
WIDTH_PHYSICAL_MM_STEP,
)
fun sanitizeReportedPhysicalMm(value: Int): Int =
value.coerceIn(MIN_REPORTED_PHYSICAL_MM, MAX_REPORTED_PHYSICAL_MM)
fun resolvePhysicalSizeMm(
currentWidthPixels: Int,
currentHeightPixels: Int,
maximumWidthPixels: Int,
maximumHeightPixels: Int,
referenceMillimeters: Int,
basis: AirPlayPhysicalSizeBasis,
): AirPlayPhysicalSizeMm {
require(currentWidthPixels > 0 && currentHeightPixels > 0) {
"Current display dimensions must be positive"
}
require(maximumWidthPixels > 0 && maximumHeightPixels > 0) {
"Maximum display dimensions must be positive"
}
val referencePixels = when (basis) {
AirPlayPhysicalSizeBasis.WIDTH ->
currentWidthPixels.toDouble() / maximumWidthPixels
AirPlayPhysicalSizeBasis.HEIGHT ->
currentHeightPixels.toDouble() / maximumHeightPixels
}
val referenceMm = referenceMillimeters.coerceAtLeast(1) * referencePixels
val widthMm: Double
val heightMm: Double
when (basis) {
AirPlayPhysicalSizeBasis.WIDTH -> {
widthMm = referenceMm
heightMm = widthMm * currentHeightPixels / currentWidthPixels
}
AirPlayPhysicalSizeBasis.HEIGHT -> {
heightMm = referenceMm
widthMm = heightMm * currentWidthPixels / currentHeightPixels
}
}
return AirPlayPhysicalSizeMm(
widthMm = sanitizeReportedPhysicalMm(Math.round(widthMm).toInt()),
heightMm = sanitizeReportedPhysicalMm(Math.round(heightMm).toInt()),
)
}
fun fpsProgress(value: Int): Int =
(sanitizeFps(value) - MIN_FPS) / FPS_STEP
fun widthPhysicalMmProgress(value: Int): Int =
(sanitizeWidthPhysicalMm(value) - MIN_WIDTH_PHYSICAL_MM) / WIDTH_PHYSICAL_MM_STEP
private fun snapToStep(value: Int, minimum: Int, maximum: Int, step: Int): Int {
val clamped = value.coerceIn(minimum, maximum)
return (((clamped - minimum) + step / 2) / step) * step + minimum
}
}
@@ -0,0 +1,141 @@
package com.shilapi.xcertplay.airplay
/** One normalized touch contact (0..1 coordinates). */
data class AirPlayContact(
val id: Int,
val x: Double,
val y: Double,
val down: Boolean,
)
/** Momentary knob/button state for the head-unit rotary controller. */
data class AirPlayKnobState(
val select: Boolean = false,
val home: Boolean = false,
val back: Boolean = false,
val x: Int = 0,
val y: Int = 0,
val wheel: Int = 0,
)
/** CarPlay HID device descriptors and report encoders. */
object AirPlayHid {
const val TOUCH_HID_UID = 0x2a2a2a2a
const val KNOB_HID_UID = 0x2a2a2a2b
const val MEDIA_HID_UID = 0x2a2a2a2c
const val TELEPHONY_HID_UID = 0x2a2a2a2d
private const val TOUCH_CONTACTS = 2
private const val BYTES_PER_FINGER = 6
fun touchHidDevice(xMax: Int, yMax: Int, displayUuid: String): Map<String, Any?> =
hidDeviceEntry(TOUCH_HID_UID, "xcertplay Touchscreen", multitouchDescriptor(xMax, yMax), displayUuid)
fun knobHidDevice(displayUuid: String): Map<String, Any?> =
hidDeviceEntry(KNOB_HID_UID, "xcertplay Knob", knobDescriptor, displayUuid)
fun mediaHidDevice(displayUuid: String): Map<String, Any?> =
hidDeviceEntry(MEDIA_HID_UID, "xcertplay Media", mediaDescriptor, displayUuid)
fun telephonyHidDevice(displayUuid: String): Map<String, Any?> =
hidDeviceEntry(TELEPHONY_HID_UID, "xcertplay Telephony", telephonyDescriptor, displayUuid)
fun touchReport(contacts: List<AirPlayContact>): ByteArray {
val report = ByteArray(BYTES_PER_FINGER * TOUCH_CONTACTS)
for (slot in 0 until TOUCH_CONTACTS) {
val offset = slot * BYTES_PER_FINGER
report[offset] = slot.toByte()
val contact = contacts.getOrNull(slot) ?: continue
report[offset + 1] = if (contact.down) 0x01 else 0x00
writeU16Le(report, offset + 2, Math.round(contact.x.coerceAtLeast(0.0)).toInt())
writeU16Le(report, offset + 4, Math.round(contact.y.coerceAtLeast(0.0)).toInt())
}
return report
}
fun knobReport(state: AirPlayKnobState): ByteArray {
val report = ByteArray(4)
report[0] = (
(if (state.select) 0x01 else 0) or
(if (state.home) 0x02 else 0) or
(if (state.back) 0x04 else 0)
).toByte()
report[1] = clampAxis(state.x)
report[2] = clampAxis(state.y)
report[3] = clampAxis(state.wheel)
return report
}
fun mediaReport(index: Int): ByteArray = byteArrayOf(index.toByte())
fun telephonyReport(index: Int): ByteArray = byteArrayOf(index.toByte())
private fun hidDeviceEntry(
uid: Int,
name: String,
descriptor: ByteArray,
displayUuid: String,
): Map<String, Any?> = linkedMapOf(
"hidProductID" to 1L,
"hidVendorID" to 2L,
"hidCountryCode" to 0L,
"uuid" to uid.toString(16),
"name" to name,
"displayUUID" to displayUuid,
"hidDescriptor" to descriptor,
)
private fun multitouchDescriptor(xMax: Int, yMax: Int): ByteArray {
val bytes = ArrayList<Int>()
bytes.addAll(intArrayOf(0x05, 0x0d, 0x09, 0x04, 0xa1, 0x01).toList())
repeat(TOUCH_CONTACTS) { bytes.addAll(fingerCollection(xMax, yMax).toList()) }
bytes.add(0xc0)
return bytes.map { it.toByte() }.toByteArray()
}
private fun fingerCollection(xMax: Int, yMax: Int): IntArray = intArrayOf(
0x05, 0x0d, 0x09, 0x22, 0xa1, 0x02,
0x09, 0x38, 0x75, 0x08, 0x95, 0x01, 0x81, 0x02,
0x15, 0x00, 0x25, 0x01, 0x09, 0x33, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02,
0x95, 0x07, 0x81, 0x03,
0x05, 0x01, 0x26, xMax and 0xff, (xMax shr 8) and 0xff, 0x09, 0x30, 0x75, 0x10, 0x95, 0x01, 0x81, 0x02,
0x26, yMax and 0xff, (yMax shr 8) and 0xff, 0x09, 0x31, 0x81, 0x02, 0xc0,
)
private val knobDescriptor = descriptor(
0x05, 0x01, 0x09, 0x08, 0xa1, 0x01,
0x05, 0x09, 0x09, 0x01, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02,
0x05, 0x0c, 0x0a, 0x23, 0x02, 0x0a, 0x24, 0x02, 0x95, 0x02, 0x81, 0x02,
0x95, 0x05, 0x81, 0x01,
0x05, 0x01, 0x09, 0x01, 0xa1, 0x00,
0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02, 0xc0,
0x09, 0x38, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x01, 0x81, 0x06, 0xc0,
)
private val mediaDescriptor = descriptor(
0x05, 0x0c, 0x09, 0x01, 0xa1, 0x01,
0x15, 0x00, 0x25, 0x06, 0x05, 0x0c,
0x0a, 0x00, 0x00, 0x0a, 0xb0, 0x00, 0x0a, 0xb1, 0x00, 0x0a, 0xcd, 0x00,
0x0a, 0xb5, 0x00, 0x0a, 0xb6, 0x00, 0x0a, 0x9e, 0x02,
0x75, 0x08, 0x95, 0x01, 0x81, 0x00, 0xc0,
)
private val telephonyDescriptor = descriptor(
0x05, 0x0b, 0x09, 0x07, 0xa1, 0x01,
0x15, 0x00, 0x25, 0x11, 0x05, 0x0b,
0x09, 0x00, 0x09, 0x20, 0x09, 0x21, 0x09, 0x26, 0x09, 0x2f,
0x09, 0xb0, 0x09, 0xb1, 0x09, 0xb2, 0x09, 0xb3, 0x09, 0xb4, 0x09, 0xb5,
0x09, 0xb6, 0x09, 0xb7, 0x09, 0xb8, 0x09, 0xb9, 0x09, 0xba, 0x09, 0xbb,
0x05, 0x07, 0x09, 0x2a,
0x75, 0x08, 0x95, 0x01, 0x81, 0x00, 0xc0,
)
private fun descriptor(vararg bytes: Int): ByteArray = ByteArray(bytes.size) { bytes[it].toByte() }
private fun clampAxis(value: Int): Byte = value.coerceIn(-127, 127).toByte()
private fun writeU16Le(target: ByteArray, offset: Int, value: Int) {
target[offset] = (value and 0xff).toByte()
target[offset + 1] = ((value ushr 8) and 0xff).toByte()
}
}
@@ -0,0 +1,174 @@
package com.shilapi.xcertplay.airplay
import com.shilapi.xcertplay.transport.BlockingDuplexByteStream
import java.io.IOException
import java.util.ArrayDeque
import kotlin.math.min
/**
* Full-duplex adapter for the CarPlay iAP2 DataStream.
*
* Inbound iAP2 bytes come from [IapTunnel]; outbound bytes are sent over the encrypted AirPlay
* event channel using the `iAPSendMessage` command.
*/
internal class AirPlayIapTunnelStream(
private val session: AirPlaySession,
private val tunnel: IapTunnel,
private val sendCommand: (ByteArray, Long) -> Boolean = { data, timeoutMillis ->
session.sendIapMessage(data, timeoutMillis)
},
) : BlockingDuplexByteStream {
private val lock = Object()
private val pending = ArrayDeque<ByteArray>()
private var pendingBytes = 0
private var closed = false
private var terminalFailure: Throwable? = null
private var closeLocation: String? = null
fun listen(): Int = tunnel.listen(
object : IapTunnel.Listener {
override fun onOpen(remoteAddress: String?) {
session.logTrace(
"AirPlay iAP tunnel connected remote=${remoteAddress ?: "unknown"}",
)
}
override fun onIap(bytes: ByteArray) = offer(bytes)
override fun onDebug(message: String) {
session.logTrace(message)
}
override fun onClosed(cause: Throwable?) {
session.logTrace(
"AirPlay iAP tunnel closed cause=" +
"${cause?.javaClass?.simpleName ?: "peer EOF"}: " +
"${cause?.message ?: "no detail"}",
)
val shouldCloseSession = markFailed(cause)
if (shouldCloseSession) session.close()
}
},
)
override fun send(data: ByteArray) {
synchronized(lock) {
throwTerminalFailureLocked()
if (closed) throw closedFailureLocked()
}
if (!tunnel.awaitPeerConnection(PEER_CONNECT_TIMEOUT_MILLIS)) {
throw IOException("CarPlay iAP tunnel peer did not connect")
}
synchronized(lock) {
throwTerminalFailureLocked()
if (closed) throw closedFailureLocked()
}
if (!sendCommand(data, EVENT_READY_TIMEOUT_MILLIS)) {
throw IOException("AirPlay event channel rejected an iAP message")
}
}
override fun recv(maxBytes: Int, timeoutMillis: Long): ByteArray? {
require(maxBytes > 0) { "maxBytes must be positive" }
require(timeoutMillis >= 0) { "timeoutMillis must not be negative" }
val deadlineNanos = System.nanoTime() + timeoutMillis * NANOS_PER_MILLISECOND
synchronized(lock) {
while (true) {
takePendingLocked(maxBytes)?.let { return it }
throwTerminalFailureLocked()
if (closed) return EMPTY
val remainingNanos = deadlineNanos - System.nanoTime()
if (remainingNanos <= 0) return null
try {
lock.wait(
remainingNanos / NANOS_PER_MILLISECOND,
(remainingNanos % NANOS_PER_MILLISECOND).toInt(),
)
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
return null
}
}
}
}
override fun close() {
synchronized(lock) {
if (closed) return
closed = true
closeLocation = closeCaller()
lock.notifyAll()
}
tunnel.close()
}
private fun offer(bytes: ByteArray) {
if (bytes.isEmpty()) return
synchronized(lock) {
if (closed || terminalFailure != null) return
if (pendingBytes + bytes.size > MAX_PENDING_BYTES) {
terminalFailure = IOException("AirPlay iAP tunnel pending-data limit exceeded")
lock.notifyAll()
tunnel.close()
return
}
pending.addLast(bytes.copyOf())
pendingBytes += bytes.size
lock.notifyAll()
}
}
private fun markFailed(cause: Throwable?): Boolean {
synchronized(lock) {
if (closed || terminalFailure != null) return false
terminalFailure = cause ?: IOException("AirPlay iAP tunnel terminated")
lock.notifyAll()
return true
}
}
private fun throwTerminalFailureLocked() {
val failure = terminalFailure ?: return
throw IOException(
"AirPlay iAP tunnel failed: " +
"${failure.javaClass.simpleName}: ${failure.message ?: "unknown error"}",
failure,
)
}
private fun closedFailureLocked(): IOException = IOException(
buildString {
append("AirPlay iAP tunnel is closed")
closeLocation?.let { append("; requested by $it") }
},
)
private fun closeCaller(): String =
Thread.currentThread().stackTrace
.drop(2)
.take(8)
.joinToString(" <- ") { frame ->
"${frame.className.substringAfterLast('.')}.${frame.methodName}:${frame.lineNumber}"
}
private fun takePendingLocked(maxBytes: Int): ByteArray? {
val chunk = pending.pollFirst() ?: return null
pendingBytes -= chunk.size
if (chunk.size <= maxBytes) return chunk
val head = chunk.copyOf(maxBytes)
val tail = chunk.copyOfRange(maxBytes, chunk.size)
pending.addFirst(tail)
pendingBytes += tail.size
return head
}
private companion object {
const val MAX_PENDING_BYTES = 1_048_576
const val PEER_CONNECT_TIMEOUT_MILLIS = 15_000L
const val EVENT_READY_TIMEOUT_MILLIS = 10_000L
const val NANOS_PER_MILLISECOND = 1_000_000L
val EMPTY = ByteArray(0)
}
}
@@ -0,0 +1,19 @@
package com.shilapi.xcertplay.airplay
import java.util.UUID
/** Long-term Ed25519 identity of the CarPlay accessory, persisted by the caller. */
data class AirPlayIdentity(
val privateKey: ByteArray,
val publicKey: ByteArray,
val pairingId: String,
) {
val publicKeyHex: String get() = publicKey.toHexString()
companion object {
fun generate(): AirPlayIdentity {
val keyPair = AirPlayCrypto.ed25519Generate()
return AirPlayIdentity(keyPair.privateKey, keyPair.publicKey, UUID.randomUUID().toString())
}
}
}
@@ -0,0 +1,199 @@
package com.shilapi.xcertplay.airplay
/**
* Builds the /info response the phone reads before it requests media streams.
*
* The declaration is complete on purpose: it must carry the display, audio formats/latencies,
* CarPlay resource modes, and the HID input devices, otherwise the phone aborts the session.
*/
object AirPlayInfoPlist {
const val MAIN_UUID = "b7e6c5a0-1111-4000-8000-000000000001"
const val ALT_UUID = "b7e6c5a0-2222-4000-8000-000000000002"
private const val STREAM_TYPE_MAIN_SCREEN = 110
private const val STREAM_TYPE_ALT_SCREEN = 111
private const val DISPLAY_FEATURE_KNOBS = 0x02
private const val DISPLAY_FEATURE_HIGH_FIDELITY_TOUCH = 0x08
private const val CARPLAY_FEATURES = 0x615653aee2L
private const val CARPLAY_AUDIO_FEATURES = 0x10004540a00L
private val CARPLAY_FEATURES_NO_AUDIO = CARPLAY_FEATURES and CARPLAY_AUDIO_FEATURES.inv()
private const val RESOURCE_SCREEN = 1
private const val RESOURCE_AUDIO = 2
private const val TRANSFER_TAKE = 1
private const val PRIORITY_NICE_TO_HAVE = 100
private const val CONSTRAINT_ANYTIME = 100
fun build(config: AirPlayConfig): Map<String, Any?> {
val displays = arrayListOf<Any?>(
displayEntry(config.main, STREAM_TYPE_MAIN_SCREEN, MAIN_UUID),
)
config.cluster?.let { displays.add(displayEntry(it, STREAM_TYPE_ALT_SCREEN, ALT_UUID)) }
val info = linkedMapOf<String, Any?>(
"sourceVersion" to config.sourceVersion,
"features" to if (config.disableAudioOutput) CARPLAY_FEATURES_NO_AUDIO else CARPLAY_FEATURES,
"statusFlags" to 4L,
"model" to config.model,
"manufacturer" to config.manufacturer,
"deviceID" to config.deviceId,
"bluetoothIDs" to listOf(config.btMac),
"name" to config.deviceName,
"rightHandDrive" to config.rightHandDrive,
"keepAliveLowPower" to false,
"keepAliveSendStatsAsBody" to false,
"modes" to modes(),
)
if (!config.disableAudioOutput) {
info["audioLatencies"] = audioLatencies()
info["audioFormats"] = audioFormats(config.entertainmentSampleRate, config.microphone)
}
info["extendedFeatures"] = listOf("vocoderInfo", "enhancedRequestCarUI")
info["displays"] = displays
info["hidDevices"] = listOf(
AirPlayHid.touchHidDevice(config.main.widthPixels, config.main.heightPixels, MAIN_UUID),
AirPlayHid.knobHidDevice(MAIN_UUID),
AirPlayHid.mediaHidDevice(MAIN_UUID),
AirPlayHid.telephonyHidDevice(MAIN_UUID),
)
if (config.icons.isNotEmpty()) {
info["oemIconVisible"] = true
info["oemIconLabel"] = config.oemLabel
info["oemIcons"] = config.icons.map { icon ->
linkedMapOf(
"imageData" to icon.data,
"widthPixels" to icon.widthPixels,
"heightPixels" to icon.heightPixels,
"prerendered" to true,
)
}
}
if (config.hevc) info["hevcInfo"] = emptyMap<String, Any?>()
return info
}
private fun resource(resourceId: Int): Map<String, Any?> = linkedMapOf(
"resourceID" to resourceId,
"transferType" to TRANSFER_TAKE,
"transferPriority" to PRIORITY_NICE_TO_HAVE,
"takeConstraint" to CONSTRAINT_ANYTIME,
"borrowConstraint" to CONSTRAINT_ANYTIME,
"unborrowConstraint" to CONSTRAINT_ANYTIME,
)
private fun modes(): Map<String, Any?> = linkedMapOf(
"resources" to listOf(resource(RESOURCE_SCREEN), resource(RESOURCE_AUDIO)),
"appStates" to listOf(
linkedMapOf("appStateID" to 2, "state" to false),
linkedMapOf("appStateID" to 1, "speechMode" to -1),
linkedMapOf("appStateID" to 3, "state" to false),
),
)
private fun audioLatencies(): List<Map<String, Any?>> {
fun base(type: Int, audioType: String? = null): Map<String, Any?> {
val entry = linkedMapOf<String, Any?>(
"type" to type,
"inputLatencyMicros" to 0L,
"outputLatencyMicros" to 0L,
)
if (audioType != null) entry["audioType"] = audioType
return entry
}
return listOf(
base(100), base(100, "default"), base(100, "media"), base(100, "telephony"),
base(100, "speechRecognition"), base(100, "alert"), base(101), base(101, "default"),
base(102, "default"),
)
}
private fun audioFormats(
entertainmentRate: Int,
microphone: Boolean,
): List<Map<String, Any?>> {
fun format(type: Int, audioType: String, outputFormats: Int, inputFormats: Int? = null): Map<String, Any?> {
val entry = linkedMapOf<String, Any?>(
"type" to type,
"audioType" to audioType,
"audioOutputFormats" to outputFormats,
)
if (inputFormats != null) entry["audioInputFormats"] = inputFormats
return entry
}
val is48 = entertainmentRate == 48000
val pcmVoice = 0x3fc
val pcm = pcmVoice or (if (is48) 0xc000 else 0xc00)
val pcmMono = 0x154 or (if (is48) 0x4000 else 0x400)
val opus = 0x70000000
val aacLc = if (is48) 0x800000 else 0x400000
val pcmInput = if (microphone) pcmMono else null
val wirelessInput = if (microphone) pcmMono or opus else null
return listOf(
format(100, "compatibility", pcm, pcmInput),
format(101, "compatibility", pcm),
format(100, "default", pcm or opus, wirelessInput),
format(100, "alert", pcm or opus),
format(100, "media", pcm),
format(100, "telephony", pcmMono or opus, wirelessInput),
format(100, "speechRecognition", pcmMono or opus, wirelessInput),
format(101, "default", pcm or opus),
format(102, "media", aacLc),
)
}
private fun displayEntry(display: AirPlayDisplayConfig, type: Int, uuid: String): Map<String, Any?> {
val widthPhysical = AirPlayDisplaySettings.sanitizeReportedPhysicalMm(
display.widthPhysicalMm ?: AirPlayDisplaySettings.DEFAULT_WIDTH_PHYSICAL_MM,
)
val heightPhysical = AirPlayDisplaySettings.sanitizeReportedPhysicalMm(
display.heightPhysicalMm
?: Math.round(
widthPhysical * display.heightPixels.toDouble() / display.widthPixels,
).toInt(),
)
val fps = AirPlayDisplaySettings.sanitizeFps(display.fps)
val entry = linkedMapOf<String, Any?>(
"uuid" to uuid,
"type" to type,
"maxFPS" to fps,
"widthPixels" to display.widthPixels,
"heightPixels" to display.heightPixels,
"widthPhysical" to widthPhysical,
"heightPhysical" to heightPhysical,
"features" to (DISPLAY_FEATURE_HIGH_FIDELITY_TOUCH or DISPLAY_FEATURE_KNOBS),
"primaryInputDevice" to display.primaryInputDevice,
)
entry["viewAreas"] = listOf(areaDict(display))
entry["initialViewArea"] = 0
if (display.initialUrl != null) entry["initialURL"] = display.initialUrl
return entry
}
private fun areaDict(display: AirPlayDisplayConfig): Map<String, Any?> {
// The session SETUP response enables "viewAreas", so /info must always describe one.
// A display without custom insets uses the full panel for both the view and safe areas.
val view = display.viewArea ?: AirPlayInsets()
val width = display.widthPixels
val height = display.heightPixels
val result = linkedMapOf<String, Any?>(
"widthPixels" to (width - view.left - view.right),
"heightPixels" to (height - view.top - view.bottom),
"originXPixels" to view.left,
"originYPixels" to view.top,
)
val safe = display.safeArea ?: AirPlayInsets()
val safeArea = linkedMapOf<String, Any?>(
"widthPixels" to (width - safe.left - safe.right),
"heightPixels" to (height - safe.top - safe.bottom),
"originXPixels" to safe.left,
"originYPixels" to safe.top,
"drawUIOutsideSafeArea" to (display.safeAreaDrawOutside ?: true),
)
result["safeArea"] = safeArea
return result
}
}
@@ -0,0 +1,13 @@
package com.shilapi.xcertplay.airplay
/** Only product/version tokens, never the phone's name, addresses or pairing identifiers. */
object AirPlayPeerDiagnostics {
private val modelToken = Regex("(?:iPhone|iPad|iPod)[0-9]{1,3},[0-9]{1,3}")
private val versionToken = Regex("[0-9][0-9A-Za-z._-]{0,39}")
fun summary(model: String, osVersion: String, sourceVersion: String): String {
fun version(value: String) = value.takeIf(versionToken::matches) ?: "not_reported"
return "Phone display peer model=${model.takeIf(modelToken::matches) ?: "not_reported"} " +
"ios=${version(osVersion)} airplay=${version(sourceVersion)}"
}
}
@@ -0,0 +1,736 @@
package com.shilapi.xcertplay.airplay
import android.util.Log
import com.shilapi.xcertplay.mfi.MfiAuthenticator
import com.shilapi.xcertplay.transport.BlockingDuplexByteStream
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.Closeable
import java.math.BigInteger
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicBoolean
data class AirPlayDeviceInfo(
val name: String,
val deviceId: String,
val wifiMac: String,
val model: String,
)
/** Session lifecycle and command callbacks for the driver/UI layer. */
interface AirPlaySessionListener {
fun onSessionActive(session: AirPlaySession) {}
fun onSessionEnded(session: AirPlaySession) {}
fun onVideoFrameRendered(session: AirPlaySession) {}
fun onTransportError(message: String) {}
fun onDeviceInfo(session: AirPlaySession, info: AirPlayDeviceInfo) {}
fun onHostUiRequested(session: AirPlaySession) {}
fun onCommand(session: AirPlaySession, type: String, params: Map<String, Any?>) {}
fun onDebugLog(message: String) {}
}
/** Stream transport seam; media decode/render is supplied by a later layer. */
interface AirPlayMediaHandler {
fun onScreen(session: AirPlaySession, type: Int, stream: Map<String, Any?>): Int? = null
fun onAudio(session: AirPlaySession, type: Int, stream: Map<String, Any?>): Map<String, Any?>? = null
fun onDataStream(session: AirPlaySession, stream: Map<String, Any?>): Map<String, Any?>? = null
fun onFeedback(session: AirPlaySession): Map<String, Any?>? = null
fun onTeardown(session: AirPlaySession, type: Int) {}
fun onSessionClosed(session: AirPlaySession) {}
fun setIapTunnelHandler(handler: ((BlockingDuplexByteStream) -> Boolean)?) {}
fun onSetupResponseSent(session: AirPlaySession) {}
}
/**
* One CarPlay AirPlay control connection.
*
* It owns the RTSP framing, pairing/auth/info routing, the encrypted event channel used for HID
* input, stream SETUP/TEARDOWN routing, the NTP timing exchange, and the keep-alive socket.
*/
class AirPlaySession(
private val socket: Socket,
private val config: AirPlayConfig,
private val identity: AirPlayIdentity,
private val pairings: PairingStore,
private val mfi: MfiAuthenticator?,
private val listener: AirPlaySessionListener,
private val media: AirPlayMediaHandler,
) : Closeable {
internal val pairSetup = PairSetup(identity, pairings)
internal val pairVerify = PairVerify(identity, pairings)
internal var cipher: ControlCipher? = null
internal var encBuf = ByteArray(0)
internal var deviceBtMac = ""
internal val activeStreams = linkedSetOf<Int>()
private val closed = AtomicBoolean(false)
private val notified = AtomicBoolean(false)
private var eventServer: ServerSocket? = null
private var eventSocket: Socket? = null
private var eventCipher: ControlCipher? = null
private var eventCseq = 0
private var pendingNightMode: Boolean? = null
private val firstTouchSendLogged = AtomicBoolean(false)
private val touchSendFailureLogged = AtomicBoolean(false)
private val ntp = NtpClock()
private var keepAliveSocket: DatagramSocket? = null
private var keepAliveThread: Thread? = null
private val eventWriteLock = Any()
private val eventThreads = CopyOnWriteArrayList<Thread>()
val host: String = socket.inetAddress?.hostAddress ?: ""
val localAddress: InetAddress? = socket.localAddress
private val peerAddress: InetAddress? = socket.inetAddress
internal val remoteAddress: InetAddress?
get() = (socket.remoteSocketAddress as? InetSocketAddress)?.address
val controllerId: String? get() = pairVerify.verifiedControllerId
val sharedSecret: ByteArray? get() = pairVerify.shared?.copyOf()
fun syncedNtp(): BigInteger = ntp.syncedNtp()
internal fun logDebug(message: String) = debugLog(message)
internal fun videoFrameRendered() {
if (!closed.get()) listener.onVideoFrameRendered(this)
}
internal fun logTrace(message: String) = trace(message)
fun start() {
Thread(::runControl, "airplay-control").apply {
isDaemon = true
start()
}
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
safeClose(socket)
try {
media.onSessionClosed(this)
} catch (error: Exception) {
Log.w(TAG, "airplay media stream teardown failed", error)
}
teardown()
if (notified.compareAndSet(false, true)) listener.onSessionEnded(this)
}
fun sendCommand(command: Map<String, Any?>): Boolean = synchronized(eventWriteLock) {
sendCommandLocked(command)
}
private fun sendCommandLocked(command: Map<String, Any?>): Boolean {
val socket = eventSocket ?: return false
val cipher = eventCipher ?: return false
eventCseq++
val body = BplistCodec.encode(command)
val head = "POST /command RTSP/1.0\r\n" +
"Content-Type: $PLIST_CONTENT_TYPE\r\n" +
"Content-Length: ${body.size}\r\n" +
"CSeq: $eventCseq\r\n\r\n"
trace("airplay event tx headers=$head bodyHex=${body.toHex()}")
return try {
val bytes = cipher.encrypt(head.toByteArray(Charsets.US_ASCII) + body)
val output = socket.getOutputStream()
output.write(bytes)
output.flush()
true
} catch (error: Exception) {
Log.w(TAG, "airplay event command failed type=${command["type"]}", error)
close()
false
}
}
fun sendTouch(contacts: List<AirPlayContact>): Boolean {
val scaled = contacts.map {
it.copy(x = it.x * config.main.widthPixels, y = it.y * config.main.heightPixels)
}
val report = AirPlayHid.touchReport(scaled)
val sent = sendHidReport(AirPlayHid.TOUCH_HID_UID, report)
if (sent && firstTouchSendLogged.compareAndSet(false, true)) {
val first = scaled.firstOrNull()
Log.i(
TAG,
"airplay touch report sent contacts=${scaled.size} first=" +
"(${first?.x},${first?.y},down=${first?.down}) report=${report.toHexString()}",
)
} else if (!sent && touchSendFailureLogged.compareAndSet(false, true)) {
Log.w(TAG, "airplay touch dropped: event channel is not ready")
}
return sent
}
fun sendKnob(state: AirPlayKnobState, momentary: Boolean = true) {
sendHidReport(AirPlayHid.KNOB_HID_UID, AirPlayHid.knobReport(state))
if (momentary) sendHidReport(AirPlayHid.KNOB_HID_UID, AirPlayHid.knobReport(AirPlayKnobState()))
}
fun sendKnobSelect(down: Boolean) =
sendHidReport(AirPlayHid.KNOB_HID_UID, AirPlayHid.knobReport(AirPlayKnobState(select = down)))
fun sendMedia(index: Int) {
sendHidReport(AirPlayHid.MEDIA_HID_UID, AirPlayHid.mediaReport(index))
sendHidReport(AirPlayHid.MEDIA_HID_UID, AirPlayHid.mediaReport(0))
}
fun sendTelephony(index: Int) {
sendHidReport(AirPlayHid.TELEPHONY_HID_UID, AirPlayHid.telephonyReport(index))
sendHidReport(AirPlayHid.TELEPHONY_HID_UID, AirPlayHid.telephonyReport(0))
}
fun invokeSiri() {
sendCommand(linkedMapOf("type" to "requestSiri", "params" to linkedMapOf("siriAction" to 2)))
sendCommand(linkedMapOf("type" to "requestSiri", "params" to linkedMapOf("siriAction" to 3)))
}
fun sendIapMessage(data: ByteArray, timeoutMillis: Long = 0L): Boolean {
require(timeoutMillis >= 0) { "timeoutMillis must not be negative" }
val command = linkedMapOf<String, Any?>(
"type" to "iAPSendMessage",
"params" to linkedMapOf("data" to data),
)
if (timeoutMillis == 0L) return sendCommand(command)
val deadlineNanos = System.nanoTime() + timeoutMillis * NANOS_PER_MILLISECOND
while (true) {
val sent = synchronized(eventWriteLock) {
if (eventSocket == null || eventCipher == null) {
null
} else {
sendCommandLocked(command)
}
}
if (sent != null) return sent
if (closed.get()) return false
val remainingNanos = deadlineNanos - System.nanoTime()
if (remainingNanos <= 0) return false
val sleepMillis = minOf(
EVENT_READY_POLL_MILLIS,
(remainingNanos + NANOS_PER_MILLISECOND - 1) / NANOS_PER_MILLISECOND,
).coerceAtLeast(1)
try {
Thread.sleep(sleepMillis)
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
return false
}
}
}
fun setNightMode(night: Boolean): Boolean = synchronized(eventWriteLock) {
pendingNightMode = night
sendPendingNightModeLocked()
}
private fun sendPendingNightModeLocked(): Boolean {
val night = pendingNightMode ?: return true
val sent = sendCommandLocked(
linkedMapOf("type" to "setNightMode", "params" to linkedMapOf("nightMode" to night)),
)
if (sent) pendingNightMode = null
return sent
}
private fun sendHidReport(uid: Int, report: ByteArray): Boolean =
sendCommand(
linkedMapOf(
"type" to "hidSendReport",
"uuid" to uid.toString(16),
"hidReport" to report,
),
)
private fun runControl() {
val input = BufferedInputStream(socket.getInputStream())
val output = BufferedOutputStream(socket.getOutputStream())
var accumulated = ByteArray(0)
val buffer = ByteArray(READ_CHUNK_BYTES)
var closeReason = "session closed"
try {
while (!closed.get()) {
val count = input.read(buffer)
if (count < 0) {
closeReason = "peer EOF"
break
}
var plaintext = buffer.copyOf(count)
val activeCipher = cipher
if (activeCipher != null) {
encBuf += plaintext
val decrypted = try {
activeCipher.decrypt(encBuf)
} catch (error: Exception) {
closeReason = "control decrypt failed: ${error.message ?: error.javaClass.simpleName}"
Log.e(TAG, "airplay $closeReason encrypted=${encBuf.size}", error)
break
}
encBuf = decrypted.rest
plaintext = decrypted.data
}
accumulated += plaintext
val parsed = RtspMessage.parseMessages(accumulated)
accumulated = parsed.rest
for (request in parsed.messages) {
val cseq = request.headers["cseq"] ?: "-"
val path = request.path.lowercase()
val showInDebugOverlay =
!path.endsWith("/feedback") &&
!(request.method == "POST" && path.endsWith("/command"))
debugLog(
"airplay rx ${request.method} ${request.path} cseq=$cseq body=${request.body.size}",
showInDebugOverlay,
)
trace(
"airplay control rx headers=${request.headers} " +
"bodyHex=${request.body.toHex()}",
)
val response = try {
handle(request)
} catch (error: Exception) {
Log.e(
TAG,
"airplay handler failed ${request.method} ${request.path} cseq=$cseq",
error,
)
RtspMessage.Response(status = 500)
}
debugLog(
"airplay tx status=${response.status ?: 200} cseq=$cseq body=${response.body.size}",
showInDebugOverlay,
)
val wire = RtspMessage.buildResponse(request, response)
trace("airplay control tx wireHex=${wire.toHex()}")
output.write(cipher?.encrypt(wire) ?: wire)
if (cipher == null && pairVerify.controlKeys != null) {
val keys = pairVerify.controlKeys!!
cipher = ControlCipher(keys.readKey, keys.writeKey)
debugLog("airplay control encryption enabled")
}
}
output.flush()
notifySetupResponseSent()
}
} catch (error: Exception) {
closeReason = "control I/O failed: ${error.message ?: error.javaClass.simpleName}"
if (!closed.get()) Log.e(TAG, "airplay $closeReason", error)
} finally {
debugLog("airplay control closing reason=$closeReason activeStreams=$activeStreams")
close()
}
}
private fun handle(request: RtspMessage.Request): RtspMessage.Response {
when (request.method) {
"SETUP" -> return handleSetup(request)
"RECORD" -> {
listener.onSessionActive(this)
return RtspMessage.Response(status = 200)
}
"TEARDOWN" -> return handleTeardown(request)
}
val path = request.path.lowercase()
return when {
path.endsWith("/pair-setup") -> RtspMessage.Response(
headers = mapOf("Content-Type" to PAIRING_CONTENT_TYPE),
body = pairSetup.handle(request.body),
)
path.endsWith("/pair-verify") -> RtspMessage.Response(
headers = mapOf("Content-Type" to PAIRING_CONTENT_TYPE),
body = pairVerify.handle(request.body),
)
path.endsWith("/auth-setup") -> {
val body = mfi?.let { MfiSapAuthSetup.handle(request.body, it) }
if (body == null) RtspMessage.Response(status = 400)
else RtspMessage.Response(headers = mapOf("Content-Type" to OCTET_CONTENT_TYPE), body = body)
}
path.endsWith("/info") -> {
val info = AirPlayInfoPlist.build(config)
if (request.body.isNotEmpty()) {
val requestInfo = try {
BplistCodec.decode(request.body).toString()
} catch (_: Exception) {
"<unparseable ${request.body.size} bytes>"
}
debugLog("airplay /info request=$requestInfo")
}
Log.i(
TAG,
"airplay /info features=${info["features"]} " +
"audioFormats=${(info["audioFormats"] as? List<*>)?.size ?: 0} " +
"audioLatencies=${(info["audioLatencies"] as? List<*>)?.size ?: 0}",
)
debugLog("airplay /info displays=${info["displays"]}")
RtspMessage.Response(
headers = mapOf("Content-Type" to PLIST_CONTENT_TYPE),
body = BplistCodec.encode(info),
)
}
request.method == "POST" && path.endsWith("/command") -> handleCommand(request)
request.method == "POST" && path.endsWith("/feedback") -> {
val body = media.onFeedback(this)
if (body == null) {
RtspMessage.Response(status = 200)
} else {
RtspMessage.Response(
headers = mapOf("Content-Type" to PLIST_CONTENT_TYPE),
body = BplistCodec.encode(body),
)
}
}
else -> RtspMessage.Response(status = 200)
}
}
private fun notifySetupResponseSent() {
try {
media.onSetupResponseSent(this)
} catch (error: Exception) {
Log.w(TAG, "airplay SETUP response callback failed", error)
}
}
private fun debugLog(message: String, uiVisible: Boolean = true) {
Log.i(TAG, message)
if (!uiVisible) return
try {
listener.onDebugLog(message)
} catch (error: Exception) {
Log.w(TAG, "debug log callback failed", error)
}
}
private fun trace(message: String) {
try {
listener.onDebugLog("TRACE $message")
} catch (error: Exception) {
Log.w(TAG, "trace log callback failed", error)
}
}
private fun handleSetup(request: RtspMessage.Request): RtspMessage.Response {
val dict = try {
asMap(BplistCodec.decode(request.body)) ?: return RtspMessage.Response(status = 400)
} catch (error: Exception) {
Log.e(TAG, "airplay SETUP plist decode failed body=${request.body.size}", error)
return RtspMessage.Response(status = 400)
}
debugLog("airplay SETUP keys=${dict.keys.sorted()}")
val streams = dict["streams"] as? List<*>
if (streams != null) {
val responseStreams = handleStreams(streams)
debugLog("airplay SETUP response streams=$responseStreams")
val body = BplistCodec.encode(linkedMapOf("streams" to responseStreams))
trace("airplay SETUP response bplistHex=${body.toHex()}")
return RtspMessage.Response(headers = mapOf("Content-Type" to PLIST_CONTENT_TYPE), body = body)
}
val name = string(dict["name"])
val deviceId = string(dict["deviceID"])
val wifiMac = string(dict["macAddress"]).lowercase()
val model = string(dict["model"])
debugLog(AirPlayPeerDiagnostics.summary(model, string(dict["osVersion"]), string(dict["sourceVersion"])))
if (deviceId.isNotEmpty()) deviceBtMac = deviceId
if (name.isNotEmpty() || deviceId.isNotEmpty() || wifiMac.isNotEmpty()) {
listener.onDeviceInfo(this, AirPlayDeviceInfo(name, deviceId, wifiMac, model))
}
val peerTimingPort = long(dict["timingPort"])?.toInt() ?: 0
val response = linkedMapOf<String, Any?>(
"timingPort" to openTiming(peerTimingPort),
"eventPort" to openEvent(),
)
if (dict["keepAliveLowPower"] == true || dict["keepAliveLowPower"] == 1L) {
response["keepAlivePort"] = openKeepAlive()
}
val features = mutableListOf<String>()
if (config.hevc) features.add("hevc")
features.add("iAPChannel")
features.add("viewAreas")
if (config.cluster != null) features.add("altScreen")
response["enabledFeatures"] = features
return RtspMessage.Response(
headers = mapOf("Content-Type" to PLIST_CONTENT_TYPE),
body = BplistCodec.encode(response),
)
}
private fun handleStreams(streams: List<*>): List<Any?> {
val result = arrayListOf<Any?>()
for (entry in streams) {
val stream = asMap(entry) ?: continue
val type = long(stream["type"])?.toInt() ?: continue
debugLog("airplay SETUP stream type=$type payload=$stream")
when (type) {
STREAM_TYPE_MAIN_SCREEN, STREAM_TYPE_ALT_SCREEN -> {
val port = media.onScreen(this, type, stream)
debugLog("airplay screen stream type=$type dataPort=${port ?: "rejected"}")
if (port != null) {
activeStreams.add(type)
result.add(linkedMapOf("type" to type, "dataPort" to port))
}
}
STREAM_TYPE_MAIN_AUDIO, STREAM_TYPE_ALT_AUDIO, STREAM_TYPE_MAIN_HIGH_AUDIO -> {
val streamResponse = media.onAudio(this, type, stream)
debugLog(
"airplay audio stream type=$type accepted=${streamResponse != null} " +
"dataPort=${streamResponse?.get("dataPort") ?: "none"} " +
"controlPort=${streamResponse?.get("controlPort") ?: "none"}",
)
if (streamResponse != null) {
activeStreams.add(type)
result.add(streamResponse)
}
}
STREAM_TYPE_DATA -> {
val streamResponse = media.onDataStream(this, stream)
debugLog(
"airplay data stream type=$type accepted=${streamResponse != null} " +
"dataPort=${streamResponse?.get("dataPort") ?: "none"}",
)
if (streamResponse != null) {
activeStreams.add(type)
result.add(streamResponse)
}
}
else -> debugLog("airplay unsupported stream type=$type")
}
}
return result
}
private fun handleCommand(request: RtspMessage.Request): RtspMessage.Response {
val body = try {
asMap(BplistCodec.decode(request.body)) ?: emptyMap()
} catch (_: Exception) {
emptyMap<String, Any?>()
}
val type = string(body["type"])
val params = asMap(body["params"]) ?: emptyMap()
debugLog("airplay command type=$type keys=${params.keys.sorted()}")
if (type == "requestUI") listener.onHostUiRequested(this)
listener.onCommand(this, type, params)
return RtspMessage.Response(status = 200)
}
private fun handleTeardown(request: RtspMessage.Request): RtspMessage.Response {
var decodedBody: Any? = null
val types = try {
val decoded = BplistCodec.decode(request.body)
decodedBody = decoded
val dict = asMap(decoded)
(dict?.get("streams") as? List<*>)
?.mapNotNull { entry -> long(asMap(entry)?.get("type"))?.toInt() }
?: emptyList()
} catch (_: Exception) {
emptyList()
}
debugLog(
"airplay TEARDOWN types=$types activeBefore=$activeStreams " +
"body=${request.body.size} bytes payload=$decodedBody",
)
trace("airplay TEARDOWN raw${request.body.size}Hex=${request.body.toHex()}")
if (types.isEmpty()) {
activeStreams.toList().forEach { media.onTeardown(this, it) }
activeStreams.clear()
} else {
types.forEach { type -> if (activeStreams.remove(type)) media.onTeardown(this, type) }
}
return RtspMessage.Response(status = 200)
}
private fun openTiming(peerPort: Int): Int {
val port = ntp.listen()
if (peerPort > 0) peerAddress?.let { ntp.start(it, peerPort) }
return port
}
private fun openKeepAlive(): Int {
val socket = DatagramSocket(null)
socket.reuseAddress = true
socket.bind(InetSocketAddress(InetAddress.getByName("::"), 0))
keepAliveSocket = socket
keepAliveThread = Thread({ runKeepAlive(socket) }, "airplay-keepalive").apply {
isDaemon = true
start()
}
return socket.localPort
}
private fun runKeepAlive(socket: DatagramSocket) {
val buffer = ByteArray(512)
while (!closed.get()) {
try {
socket.receive(DatagramPacket(buffer, buffer.size))
} catch (_: Exception) {
if (closed.get()) return
}
}
}
private fun openEvent(): Int {
val server = ServerSocket(0, 50, InetAddress.getByName("::"))
eventServer = server
spawnEvent("airplay-event-accept") { acceptEvent(server) }
return server.localPort
}
private fun teardown() {
ntp.close()
safeClose(keepAliveSocket)
keepAliveSocket = null
keepAliveThread?.interrupt()
keepAliveThread = null
safeClose(eventServer)
eventServer = null
safeClose(eventSocket)
eventSocket = null
eventCipher = null
eventThreads.forEach { it.interrupt() }
eventThreads.clear()
}
private fun acceptEvent(server: ServerSocket) {
try {
val socket = server.accept()
socket.setSoLinger(true, 0)
debugLog("airplay event connection accepted from ${socket.remoteSocketAddress}")
eventSocket = socket
val shared = pairVerify.shared
if (shared == null) {
Log.e(TAG, "airplay event rejected: pair-verify shared secret unavailable")
safeClose(socket)
close()
return
}
val writeKey = AirPlayCrypto.hkdfSha512(
shared,
"Events-Salt".asciiBytes(),
"Events-Write-Encryption-Key".asciiBytes(),
32,
)
val readKey = AirPlayCrypto.hkdfSha512(
shared,
"Events-Salt".asciiBytes(),
"Events-Read-Encryption-Key".asciiBytes(),
32,
)
eventCipher = ControlCipher(readKey, writeKey)
synchronized(eventWriteLock) {
sendPendingNightModeLocked()
}
runEventRead(socket)
} catch (error: Exception) {
if (!closed.get()) {
Log.e(TAG, "airplay event accept failed", error)
close()
}
}
}
private fun runEventRead(socket: Socket) {
try {
val input = BufferedInputStream(socket.getInputStream())
val output = BufferedOutputStream(socket.getOutputStream())
var encrypted = ByteArray(0)
var plaintext = ByteArray(0)
val buffer = ByteArray(READ_CHUNK_BYTES)
while (!closed.get()) {
val count = input.read(buffer)
if (count < 0) break
val cipher = eventCipher ?: break
encrypted += buffer.copyOf(count)
val decrypted = try {
cipher.decrypt(encrypted)
} catch (error: Exception) {
Log.e(TAG, "airplay event decrypt failed encrypted=${encrypted.size}", error)
break
}
encrypted = decrypted.rest
plaintext += decrypted.data
val parsed = RtspMessage.parseMessages(plaintext)
plaintext = parsed.rest
for (message in parsed.messages) {
if (message.method.startsWith("RTSP/") || message.method.startsWith("HTTP/")) continue
debugLog(
"airplay event rx ${message.method} ${message.path} cseq=${message.headers["cseq"] ?: "-"} body=${message.body.size}",
)
val response = RtspMessage.buildResponse(message, RtspMessage.Response(status = 200))
trace(
"airplay event rx headers=${message.headers} " +
"bodyHex=${message.body.toHex()}",
)
trace("airplay event tx wireHex=${response.toHex()}")
synchronized(eventWriteLock) {
output.write(cipher.encrypt(response))
output.flush()
}
}
}
} catch (error: Exception) {
if (!closed.get()) Log.e(TAG, "airplay event read failed", error)
} finally {
debugLog("airplay event connection closed")
if (eventSocket === socket) eventSocket = null
eventCipher = null
safeClose(socket)
if (!closed.get()) close()
}
}
private fun spawnEvent(name: String, body: () -> Unit) {
val thread = Thread(body, name).apply { isDaemon = true }
eventThreads.add(thread)
thread.start()
}
private companion object {
const val TAG = "xcertplay-usb"
const val PLIST_CONTENT_TYPE = "application/x-apple-binary-plist"
const val PAIRING_CONTENT_TYPE = "application/pairing+tlv8"
const val OCTET_CONTENT_TYPE = "application/octet-stream"
const val STREAM_TYPE_MAIN_SCREEN = 110
const val STREAM_TYPE_ALT_SCREEN = 111
const val STREAM_TYPE_MAIN_AUDIO = 100
const val STREAM_TYPE_ALT_AUDIO = 101
const val STREAM_TYPE_MAIN_HIGH_AUDIO = 102
const val STREAM_TYPE_DATA = 130
const val READ_CHUNK_BYTES = 16 * 1024
const val EVENT_READY_POLL_MILLIS = 25L
const val NANOS_PER_MILLISECOND = 1_000_000L
}
}
internal fun safeClose(closeable: Closeable?) {
try {
closeable?.close()
} catch (_: Exception) {
// Best-effort close.
}
}
private fun ByteArray.toHex(): String =
joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and 0xff) }
private fun asMap(value: Any?): Map<String, Any?>? {
val map = value as? Map<*, *> ?: return null
val result = LinkedHashMap<String, Any?>(map.size)
for ((key, entry) in map) result[key.toString()] = entry
return result
}
private fun string(value: Any?): String = value as? String ?: ""
private fun long(value: Any?): Long? = (value as? Number)?.toLong()
@@ -0,0 +1,136 @@
package com.shilapi.xcertplay.airplay
import android.util.Log
import java.io.BufferedOutputStream
import java.io.Closeable
import java.io.DataOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.concurrent.atomic.AtomicBoolean
/**
* Diagnostic capture for the encrypted UDP datagrams and decrypted RTP packets of one audio
* stream. The caller must opt in by supplying a capture directory.
*
* File format:
* bytes 0..7: "XCAUDIO1"
* int32 version
* int32 stream type
* int64 wall-clock start time (milliseconds)
* repeated records:
* int32 wire length
* int32 decrypted RTP length, or -1 when authentication failed
* int32 RTP sample position, or -1 when unavailable
* int64 monotonic timestamp (nanoseconds)
* int32 UTF-8 error length
* wire bytes
* decrypted RTP bytes when length >= 0
* UTF-8 error bytes
*/
class AudioPacketCapture(
directory: File,
private val streamType: Int,
private val maxPackets: Int = 512,
private val maxBytes: Long = 16L * 1024L * 1024L,
) : Closeable {
private val closed = AtomicBoolean(false)
private var packets = 0
private var bytesWritten: Long = (MAGIC.size + HEADER_BYTES).toLong()
private val output: DataOutputStream?
val file: File
init {
val captureDirectory = if (directory.isDirectory || directory.mkdirs()) {
directory
} else {
null
}
file = if (captureDirectory == null) {
File(directory, "audio-capture-unavailable-type-$streamType.xcap")
} else {
File(
captureDirectory,
"audio-${System.currentTimeMillis()}-type-$streamType.xcap",
)
}
output = if (captureDirectory == null) {
null
} else {
try {
DataOutputStream(BufferedOutputStream(FileOutputStream(file, false))).also {
it.write(MAGIC)
it.writeInt(VERSION)
it.writeInt(streamType)
it.writeLong(System.currentTimeMillis())
it.flush()
Log.i(TAG, "audio capture started type=$streamType file=${file.absolutePath}")
}
} catch (error: Exception) {
Log.w(TAG, "audio capture could not open type=$streamType", error)
null
}
}
}
fun record(
wire: ByteArray,
rtp: ByteArray?,
sample: Int?,
error: Throwable?,
) {
if (output == null || closed.get()) return
synchronized(this) {
if (closed.get() || packets >= maxPackets) return
val errorBytes = error?.message?.toByteArray(Charsets.UTF_8) ?: ByteArray(0)
val recordBytes = 4L * 4 + 8 + wire.size + (rtp?.size ?: 0) + errorBytes.size
if (bytesWritten + recordBytes > maxBytes) {
close()
return
}
try {
output.writeInt(wire.size)
output.writeInt(rtp?.size ?: -1)
output.writeInt(sample ?: -1)
output.writeLong(System.nanoTime())
output.writeInt(errorBytes.size)
output.write(wire)
if (rtp != null) output.write(rtp)
output.write(errorBytes)
packets += 1
bytesWritten += recordBytes
if (packets % FLUSH_INTERVAL_PACKETS == 0) output.flush()
if (packets >= maxPackets) close()
} catch (failure: Exception) {
Log.w(TAG, "audio capture write failed type=$streamType", failure)
close()
}
}
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
try {
output?.flush()
output?.close()
} catch (error: Exception) {
Log.w(TAG, "audio capture close failed type=$streamType", error)
} finally {
if (output != null) {
Log.i(
TAG,
"audio capture stopped type=$streamType packets=$packets " +
"bytes=$bytesWritten file=${file.absolutePath}",
)
}
}
}
private companion object {
const val TAG = "xcertplay-usb"
const val VERSION = 1
const val HEADER_BYTES = 16
const val FLUSH_INTERVAL_PACKETS = 16
val MAGIC = "XCAUDIO1".toByteArray(Charsets.US_ASCII)
}
}
@@ -0,0 +1,229 @@
package com.shilapi.xcertplay.airplay
import java.io.Closeable
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
enum class AudioCodecKind { AAC_LC, OPUS, LPCM }
data class AudioFormat(
val codec: AudioCodecKind,
val sampleRate: Int,
val channels: Int,
val payloadType: Int,
val audioType: String = "media",
)
/**
* Binds the RTP data and RTCP control UDP ports for one CarPlay audio stream.
*
* Wire layout follows LIVI `livi_audio_stream`: one RTP packet per datagram, a 12-byte header,
* ciphertext, a 16-byte tag, then an 8-byte little-endian nonce. The header's last eight bytes
* (timestamp + SSRC) are the AEAD associated data.
*/
class AudioStream(
private val key: ByteArray,
private val streamType: Int = -1,
) : Closeable {
interface Listener {
fun onStarted(firstSample: Int) {}
fun onRtp(rtp: ByteArray, sample: Int) {}
fun onPacket(
wire: ByteArray,
rtp: ByteArray?,
sample: Int?,
error: Throwable?,
) {}
}
private val closed = AtomicBoolean(false)
private val receivedPackets = AtomicInteger()
private val decryptedPackets = AtomicInteger()
private val authenticationFailures = AtomicInteger()
private var dataSocket: DatagramSocket? = null
private var controlSocket: DatagramSocket? = null
private var dataThread: Thread? = null
private var controlThread: Thread? = null
private var started = false
fun listen(listener: Listener): Pair<Int, Int> {
val data = bindAnyPort()
val control = bindAnyPort()
dataSocket = data
controlSocket = control
dataThread = Thread({ runData(data, listener) }, "airplay-audio-rx").apply {
isDaemon = true
start()
}
controlThread = Thread({ runControl(control) }, "airplay-rtcp-rx").apply {
isDaemon = true
start()
}
return data.localPort to control.localPort
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
dataSocket?.close()
controlSocket?.close()
dataThread?.interrupt()
controlThread?.interrupt()
}
private fun runData(socket: DatagramSocket, listener: Listener) {
val buffer = ByteArray(DATAGRAM_BYTES)
while (!closed.get()) {
val packet = DatagramPacket(buffer, buffer.size)
try {
socket.receive(packet)
} catch (_: Exception) {
if (closed.get()) return else continue
}
val wire = packet.data.copyOf(packet.length)
val packetNumber = receivedPackets.incrementAndGet()
if (wire.size < RTP_HEADER_LEN + TAIL_LEN) {
if (packetNumber == 1) {
android.util.Log.w(
TAG,
"audio stream type=$streamType short packet bytes=${wire.size}",
)
}
listener.onPacket(
wire,
null,
null,
IOException("audio packet shorter than RTP header plus tail"),
)
continue
}
val aad = wire.copyOfRange(4, RTP_HEADER_LEN)
val sealedEnd = wire.size - NONCE_LEN
val sealed = wire.copyOfRange(RTP_HEADER_LEN, sealedEnd)
val shortNonce = wire.copyOfRange(sealedEnd, wire.size)
val nonce = ByteArray(12).also { shortNonce.copyInto(it, 4) }
val sample = readU32Be(wire, 4)
val payload = try {
AirPlayCrypto.chachaOpen(key, nonce, sealed, aad)
} catch (error: Exception) {
val failureNumber = authenticationFailures.incrementAndGet()
if (failureNumber == 1) {
android.util.Log.w(
TAG,
"audio stream type=$streamType first decrypt failure " +
"wire=${wire.toHexString()}",
error,
)
}
listener.onPacket(wire, null, sample, error)
continue
}
val rtp = wire.copyOf(RTP_HEADER_LEN) + payload
val decryptedNumber = decryptedPackets.incrementAndGet()
if (decryptedNumber <= FIRST_PACKET_LOG_COUNT) {
android.util.Log.i(
TAG,
"audio stream type=$streamType packet=$decryptedNumber sample=$sample " +
"wireBytes=${wire.size} payloadBytes=${payload.size} " +
"payloadHead=${payload.copyOf(minOf(payload.size, 16)).toHexString()}",
)
} else if (decryptedNumber % PACKET_LOG_INTERVAL == 0) {
android.util.Log.i(
TAG,
"audio stream type=$streamType decrypted=$decryptedNumber " +
"authFailures=${authenticationFailures.get()}",
)
}
listener.onPacket(wire, rtp, sample, null)
if (!started) {
started = true
listener.onStarted(sample)
}
listener.onRtp(rtp, sample)
}
}
private fun runControl(socket: DatagramSocket) {
val buffer = ByteArray(DATAGRAM_BYTES)
while (!closed.get()) {
try {
socket.receive(DatagramPacket(buffer, buffer.size))
} catch (_: Exception) {
if (closed.get()) return
}
}
}
private fun bindAnyPort(): DatagramSocket {
val socket = DatagramSocket(null)
socket.reuseAddress = true
socket.bind(InetSocketAddress(InetAddress.getByName("::"), 0))
return socket
}
private fun readU32Be(source: ByteArray, offset: Int): Int =
((source[offset].toInt() and 0xff) shl 24) or
((source[offset + 1].toInt() and 0xff) shl 16) or
((source[offset + 2].toInt() and 0xff) shl 8) or
(source[offset + 3].toInt() and 0xff)
private fun ByteArray.toHexString(): String =
joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
private companion object {
const val TAG = "xcertplay-usb"
const val DATAGRAM_BYTES = 4_096
const val RTP_HEADER_LEN = 12
const val TAG_LEN = 16
const val NONCE_LEN = 8
const val TAIL_LEN = TAG_LEN + NONCE_LEN
const val FIRST_PACKET_LOG_COUNT = 3
const val PACKET_LOG_INTERVAL = 100
}
}
/** Maps the phone's negotiated audioFormat bits to a decode/render format. */
object AudioStreamCodec {
fun fromFormatBits(bits: Long, payloadType: Int, audioType: String = "media"): AudioFormat {
val isAacLc = (bits and (AAC_LC_44K_STEREO or AAC_LC_48K_STEREO)) != 0L
val isOpus = (bits and OPUS_MONO) != 0L
val pcm = PCM_FORMAT[bits]
return when {
isOpus -> AudioFormat(AudioCodecKind.OPUS, 48_000, 1, payloadType, audioType)
isAacLc -> AudioFormat(
AudioCodecKind.AAC_LC,
if ((bits and AAC_LC_48K_STEREO) != 0L) 48_000 else 44_100,
2,
payloadType,
audioType,
)
pcm != null -> AudioFormat(AudioCodecKind.LPCM, pcm.first, pcm.second, payloadType, audioType)
else -> AudioFormat(AudioCodecKind.LPCM, 44_100, 2, payloadType, audioType)
}
}
private const val AAC_LC_44K_STEREO = 0x400000L
private const val AAC_LC_48K_STEREO = 0x800000L
private const val OPUS_MONO = 0x10000000L or 0x20000000L or 0x40000000L
private val PCM_FORMAT = mapOf(
0x4L to (8_000 to 1),
0x8L to (8_000 to 2),
0x10L to (16_000 to 1),
0x20L to (16_000 to 2),
0x40L to (24_000 to 1),
0x80L to (24_000 to 2),
0x100L to (32_000 to 1),
0x200L to (32_000 to 2),
0x400L to (44_100 to 1),
0x800L to (44_100 to 2),
0x4000L to (48_000 to 1),
0x8000L to (48_000 to 2),
)
}
@@ -0,0 +1,274 @@
package com.shilapi.xcertplay.airplay
/**
* Minimal Apple binary property list (bplist00) codec for the CarPlay control channel.
*
* It covers the subset the stack emits and reads: dictionaries, arrays, ASCII and UTF-16
* strings, raw data, non-negative integers, 32/64-bit reals, and booleans. Dictionary keys are
* serialized in insertion order, matching the reference implementation this stack targets.
*/
object BplistCodec {
private val magic = "bplist00".toByteArray(Charsets.US_ASCII)
fun decode(bytes: ByteArray): Any? {
require(bytes.size >= 40) { "bplist: too short" }
require(bytes.copyOfRange(0, magic.size).contentEquals(magic)) { "bplist: bad magic" }
val trailer = bytes.size - 32
val offsetSize = bytes[trailer + 6].toInt() and 0xff
val refSize = bytes[trailer + 7].toInt() and 0xff
val numObjects = readBigEndianLong(bytes, (trailer + 8).toLong(), 8).toInt()
val topObject = readBigEndianLong(bytes, (trailer + 16).toLong(), 8).toInt()
val offsetTable = readBigEndianLong(bytes, (trailer + 24).toLong(), 8)
val offsets = LongArray(numObjects)
for (index in offsets.indices) {
offsets[index] = readBigEndianLong(bytes, offsetTable + index.toLong() * offsetSize, offsetSize)
}
return readObject(bytes, offsets, refSize, topObject)
}
fun encode(root: Any?): ByteArray {
val nodes = ArrayList<Node>()
fun add(value: Any?): Int {
val index = nodes.size
nodes.add(Leaf(ByteArray(0)))
when (value) {
is Boolean -> nodes[index] = Leaf(byteArrayOf(if (value) 0x09 else 0x08))
is java.math.BigInteger -> {
require(value.signum() >= 0) { "bplist: negative integers are not supported" }
require(value.bitLength() <= 64) { "bplist: integer exceeds 64 bits" }
nodes[index] = Leaf(encodeUnsignedInt(value))
}
is Byte, is Short, is Int, is Long -> {
val number = (value as Number).toLong()
nodes[index] = if (number >= 0) {
Leaf(encodeInt(number))
} else {
Leaf(byteArrayOf(0x23) + bigEndian(number.toDouble().toRawBits(), 8))
}
}
is Float, is Double -> {
val number = (value as Number).toDouble()
nodes[index] = Leaf(byteArrayOf(0x23) + bigEndian(number.toRawBits(), 8))
}
is String -> nodes[index] = Leaf(encodeString(value))
is ByteArray -> nodes[index] = Leaf(marker(0x4, value.size) + value)
is List<*> -> {
val refs = value.map { add(it) }.toIntArray()
nodes[index] = Container(marker(0xa, value.size), refs)
}
is Map<*, *> -> {
val entries = value.entries.toList()
val keyRefs = entries.map { add(it.key.toString()) }.toIntArray()
val valueRefs = entries.map { add(it.value) }.toIntArray()
nodes[index] = Container(marker(0xd, entries.size), keyRefs + valueRefs)
}
else -> throw IllegalArgumentException("bplist: unsupported value $value")
}
return index
}
val topIndex = add(root)
val refSize = when {
nodes.size > 0xffff -> 4
nodes.size > 0xff -> 2
else -> 1
}
val parts = ArrayList<ByteArray>(nodes.size + 2)
parts.add(magic)
var cursor = magic.size
val offsets = ArrayList<Int>(nodes.size)
for (node in nodes) {
offsets.add(cursor)
val serialized = when (node) {
is Leaf -> node.body
is Container -> node.head + refBytes(node.refs, refSize)
}
parts.add(serialized)
cursor += serialized.size
}
val offsetTableOffset = cursor
val offsetSize = when {
cursor > 0xffff -> 4
cursor > 0xff -> 2
else -> 1
}
for (offset in offsets) parts.add(bigEndian(offset.toLong(), offsetSize))
val trailer = ByteArray(32)
trailer[6] = offsetSize.toByte()
trailer[7] = refSize.toByte()
writeBigEndian(trailer, 8, nodes.size.toLong(), 8)
writeBigEndian(trailer, 16, topIndex.toLong(), 8)
writeBigEndian(trailer, 24, offsetTableOffset.toLong(), 8)
parts.add(trailer)
return concatBytes(*parts.toTypedArray())
}
private fun readObject(bytes: ByteArray, offsets: LongArray, refSize: Int, index: Int): Any? {
var position = offsets[index].toInt()
val markerByte = bytes[position].toInt() and 0xff
val type = markerByte ushr 4
val nibble = markerByte and 0x0f
position++
fun readCount(): Int {
if (nibble != 0x0f) return nibble
val sizeMarker = bytes[position].toInt() and 0xff
position++
val intBytes = 1 shl (sizeMarker and 0x0f)
val count = readBigEndianLong(bytes, position.toLong(), intBytes).toInt()
position += intBytes
return count
}
return when (type) {
0x0 -> when (nibble) {
0x08 -> false
0x09 -> true
else -> throw IllegalArgumentException("bplist: unsupported primitive 0x0$nibble")
}
0x1 -> {
val size = 1 shl nibble
readBigEndianLong(bytes, position.toLong(), size)
}
0x2 -> {
val size = 1 shl nibble
when (size) {
4 -> Float.fromBits(readBigEndianLong(bytes, position.toLong(), size).toInt())
8 -> Double.fromBits(readBigEndianLong(bytes, position.toLong(), size))
else -> throw IllegalArgumentException("bplist: unsupported real size $size")
}
}
0x4 -> {
val count = readCount()
bytes.copyOfRange(position, position + count)
}
0x5 -> {
val count = readCount()
String(bytes, position, count, Charsets.US_ASCII)
}
0x6 -> {
val count = readCount()
String(bytes, position, count * 2, Charsets.UTF_16BE)
}
0xa -> {
val count = readCount()
val array = ArrayList<Any?>(count)
for (i in 0 until count) {
val reference = readBigEndianLong(bytes, position + i.toLong() * refSize, refSize).toInt()
array.add(readObject(bytes, offsets, refSize, reference))
}
array
}
0xd -> {
val count = readCount()
val dict = LinkedHashMap<String, Any?>(count)
for (i in 0 until count) {
val keyReference = readBigEndianLong(bytes, position + i.toLong() * refSize, refSize).toInt()
val valueReference =
readBigEndianLong(bytes, position + (count + i).toLong() * refSize, refSize).toInt()
dict[readObject(bytes, offsets, refSize, keyReference).toString()] =
readObject(bytes, offsets, refSize, valueReference)
}
dict
}
else -> throw IllegalArgumentException("bplist: unsupported object type 0x${type.toString(16)}")
}
}
private fun encodeString(value: String): ByteArray {
val ascii = value.all { it.code <= 0x7f }
return if (ascii) {
marker(0x5, value.length) + value.toByteArray(Charsets.US_ASCII)
} else {
marker(0x6, value.length) + value.toByteArray(Charsets.UTF_16BE)
}
}
private fun encodeInt(number: Long): ByteArray {
val size = when {
number > 0xffffffffL -> 8
number > 0xffffL -> 4
number > 0xffL -> 2
else -> 1
}
val log = when (size) {
8 -> 3
4 -> 2
2 -> 1
else -> 0
}
return byteArrayOf((0x10 or log).toByte()) + bigEndian(number, size)
}
private fun encodeUnsignedInt(number: java.math.BigInteger): ByteArray {
val size = when {
number.bitLength() > 32 -> 8
number.bitLength() > 16 -> 4
number.bitLength() > 8 -> 2
else -> 1
}
val log = when (size) {
8 -> 3
4 -> 2
2 -> 1
else -> 0
}
val raw = number.toByteArray()
return byteArrayOf((0x10 or log).toByte()) + raw.copyOfRange(raw.size - size, raw.size)
}
private fun marker(type: Int, count: Int): ByteArray {
if (count < 0x0f) return byteArrayOf(((type shl 4) or count).toByte())
val size = when {
count > 0xffff -> 4
count > 0xff -> 2
else -> 1
}
val log = when (size) {
4 -> 2
2 -> 1
else -> 0
}
return byteArrayOf(((type shl 4) or 0x0f).toByte(), (0x10 or log).toByte()) +
bigEndian(count.toLong(), size)
}
private fun refBytes(refs: IntArray, refSize: Int): ByteArray {
val output = ByteArray(refs.size * refSize)
for (index in refs.indices) writeBigEndian(output, index * refSize, refs[index].toLong(), refSize)
return output
}
private fun bigEndian(value: Long, size: Int): ByteArray {
val output = ByteArray(size)
writeBigEndian(output, 0, value, size)
return output
}
private fun writeBigEndian(target: ByteArray, offset: Int, value: Long, size: Int) {
var current = value
for (index in size - 1 downTo 0) {
target[offset + index] = (current and 0xff).toByte()
current = current ushr 8
}
}
private fun readBigEndianLong(bytes: ByteArray, offset: Long, size: Int): Long {
var value = 0L
var base = offset.toInt()
for (index in 0 until size) {
value = (value shl 8) or (bytes[base + index].toLong() and 0xffL)
}
return value
}
private sealed class Node
private class Leaf(val body: ByteArray) : Node()
private class Container(val head: ByteArray, val refs: IntArray) : Node()
}
@@ -0,0 +1,24 @@
package com.shilapi.xcertplay.airplay
internal fun concatBytes(vararg arrays: ByteArray): ByteArray {
val output = ByteArray(arrays.sumOf { it.size })
var offset = 0
for (array in arrays) {
array.copyInto(output, offset)
offset += array.size
}
return output
}
internal fun String.asciiBytes(): ByteArray = toByteArray(Charsets.US_ASCII)
internal fun ByteArray.toHexString(): String {
val alphabet = "0123456789abcdef"
val output = CharArray(size * 2)
for (index in indices) {
val value = this[index].toInt() and 0xff
output[index * 2] = alphabet[value ushr 4]
output[index * 2 + 1] = alphabet[value and 0x0f]
}
return String(output)
}
@@ -0,0 +1,31 @@
package com.shilapi.xcertplay.airplay
/**
* Display scaling uses tenths so the UI can expose only the supported 0.3x..1.0x steps.
*/
object CarPlayDisplayScale {
const val MIN_TENTHS = 3
const val MAX_TENTHS = 10
const val DEFAULT_TENTHS = MAX_TENTHS
fun sanitize(tenths: Int): Int = tenths.coerceIn(MIN_TENTHS, MAX_TENTHS)
fun label(tenths: Int): String {
val value = sanitize(tenths)
return "${value / 10}.${value % 10}x"
}
fun apply(display: AirPlayDisplayConfig, tenths: Int): AirPlayDisplayConfig {
val value = sanitize(tenths)
return display.copy(
widthPixels = scalePixels(display.widthPixels, value),
heightPixels = scalePixels(display.heightPixels, value),
)
}
private fun scalePixels(pixels: Int, tenths: Int): Int {
require(pixels > 0) { "pixels must be positive" }
val scaled = ((pixels.toLong() * tenths + 5L) / 10L).toInt().coerceAtLeast(1)
return if (scaled % 2 == 0) scaled else scaled + 1
}
}
Loaded 100 of 263 files, more files were not shown because too many files have changed in this diff. Show more