Full Code of yzyhk904/hifi-maximizer-mod for AI

master 345125958497 cached
19 files
251.3 KB
62.7k tokens
1 requests
Download .txt
Showing preview only (261K chars total). Download the full file or copy to clipboard to get everything.
Repository: yzyhk904/hifi-maximizer-mod
Branch: master
Commit: 345125958497
Files: 19
Total size: 251.3 KB

Directory structure:
gitextract_1qviyzmq/

├── LICENSE
├── META-INF/
│   └── com/
│       └── google/
│           └── android/
│               ├── update-binary
│               └── updater-script
├── README.md
├── changelog.md
├── customize-functions.sh
├── customize.sh
├── jitter-reducer-functions.shlib
├── module.prop
├── post-fs-data.sh
├── service-functions.sh
├── service-optimizer.sh
├── service.sh
├── system.prop
├── system.prop-workaround
├── templates/
│   ├── bypass_offload_safer_template.xml
│   ├── bypass_offload_template.xml
│   └── offload_hifi_playback_template.xml
└── uninstall.sh

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 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 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 <https://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
<https://www.gnu.org/licenses/>.


================================================
FILE: META-INF/com/google/android/update-binary
================================================
#!/sbin/sh

#################
# Initialization
#################

umask 022

# echo before loading util_functions
ui_print() { echo "$1"; }

require_new_magisk() {
  ui_print "*******************************"
  ui_print " Please install Magisk v20.4+! "
  ui_print "*******************************"
  exit 1
}

#########################
# Load util_functions.sh
#########################

OUTFD=$2
ZIPFILE=$3

mount /data 2>/dev/null

[ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk
. /data/adb/magisk/util_functions.sh
[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk

install_module
exit 0


================================================
FILE: META-INF/com/google/android/updater-script
================================================
#MAGISK


================================================
FILE: README.md
================================================
## A Magisk module for maximizing the digital audio fidelity by reducing jitters on audio outputs (USB DACs, Bluetooth a2dp, DLNA, etc.)

So many music lovers abandon audio quality on smart phones and DAP's by believing its causes are delivered from analog components. However, the most crucial cuase of it is actually less than 50 Hz jitter (i.e., the standard deviation of actual audio data rate with a low-pass filter; usually converting into time-domain) on digital audio outputs that generates very short reverb or foggy sound like distortion on analog audio outputs. Although larger than 50 Hz (shorter than 20 msec. interval) jitter can be easily reduced under the hearable level by a PLL (Phase Locked Loop) in DAC's, the other (especially less than 10 Hz or longer than 100 msec. interval) modulates and distorts audio outputs by fluctuating the master clock in a DAC through the PLL. For further explanation, see my another magisk module ["Audio jitter silencer"](https://github.com/Magisk-Modules-Alt-Repo/audio-jitter-silencer).

For maximizing the audio fidelity, this module reduces less than 50 Hz (longer than 20 msec interval) jitters on digital audio outputs by optimizing kenel tunables (CPU & GPU  governors, thermal control, CPU hotplug, I/O scheduler, Virtual memory), Selinux mode, WIFI parameters, etc. as follows,

* For Reducing Jitters:
    <ol type="1">
    <li>CPU & GPU governor<br>
        change their governors to "performance" (additionally fixed at the max frequency).</li>
    <li>I/O scheduler<br>
        scheduler preference: "deadline" ("cfq" if "deadline" doesn't exist); optimize its tunables.</li>
    <li>Virtual memory<br>
        change "swappiness" to 0%, "laptop mode" to 1, etc.</li>
    <li>Thermal Control<br>
        disable Qcomm "core control" and stop thermal servers (e.g., "thermald", "thermal-engine", "thermal", "mi_thermald", etc.).</li>
    <li>CPU hotplug<br>
        stop "MPDecision" server (if exists).</li>
    <li>Disable MediaTek EAS+ scheduler<br>
        ```echo '1' > "/proc/cpufreq/cpufreq_sched_disable"```</li>
    <li>Doze<br>
        stop the Android doze server.</li>
    <li>Selinux mode<br>
        change the mode to "permissive".</li>
    <li>Adaptive battery saving features<br>
        disable wifi suspend optimizations, the adaptive battery management, the adaptive charging management and the adaptive connectivity management.</li>
    <li>Kill effect chains<br>
        force ignoring ```/vendor/etc/audio_effects.xml``` to disable equalizers, virtualizers, reverb's, visualizer, echo cancelers, automatic gain controls, etc. (very few vulnerable equalizers may crash by this killing, but please ignore it)</li>
    <li>Disable the android built-in spatial audio feature (A13 or higher; especially Tensor devices)<br/>
         bypass an otiose audio pass.</li>
    <li>Disable aocd service<br/>
        disable "aocd server" generating significant jitter on audio outputs, esp. on USB.</li>
    <li>Disable pre-installed Moto Dolby and Digital Wellbeing features<br/>
        hide their apps (no modifications); please manually uninstall Digital Wellbeing app if remaining as a usual app.</li>
    <li>Disable Logd service<br/>
        disable "logd server", "traced server" and "traced_probes server" interfering jitter on audio outputs.</li>
    <li>Disable camera service<br/>
        disable "camera server" interfering jitter on audio outputs.</li>
    </ol>
<br/>

* For Convenience and Audio Quality:
    <ol type="1">
    <li> Disable DRC (Dynamic Range Control, i.e., a kind of compression)<br/>
        modify ```/vendor/etc/*/audio_policy_configuration*.xml``` to disable DRC if DRC has been enabled on a stock firmware.</li>
    <li>Volume steps<br/>
        change the number of steps in media volume to 100 steps (0.4~0.7dB per step).</li>
    <li>Disables the sound dose feature of the mixer<br/>
        Not to defocuse the shape of sound images, also reduce jitter.</li>
    <li>Resampling quality<br/>
        change AudioFlinger's resampling quality from the AOSP standard one (stop band attenuation 90dB & cut off 100% of the Nyquist frequency & half filter length 32) to a very mastering quality (194dB & 98% & 520, 179dB & 99% & 408, 167dB & 106% & 368 or 160db & 91% & 480 (or 320 for low performance devices), i.e., no resampling distortion in a real sense even though the 160dB targeted attenuation is not accomplished in the AOSP implementation). However, install <a href="https://github.com/Magisk-Modules-Alt-Repo/resampling-for-cheapies">"Resampling for cheapies" module</a> together to override these resampling settings if you intend to use LDAC bluetooth earphones or DAC's under $30.</li>
    <li>Adjust a USB transfer period of the USB HAL driver (not the Qcomm hardware offload USB driver, but including ones of Tensor and MTK devices)<br/>
        for directly reducing the jitter of a PLL in a DAC (even in an asynchronous mode); Use <a href="https://github.com/yzyhk904/USB_SampleRate_Changer">"USB_SampleRate_Changer"</a> or <a href="https://github.com/Magisk-Modules-Alt-Repo/audio-samplerate-changer">"Audio Samplerate Changer"</a> to switch from the usual hardware offload USB driver to the USB HAL one.</li>
    <li>Set an audio scheduling tunable "vendor.audio.adm.buffering.ms" "2"<br/>
         to reduce jitter on all audio outputs.</li>
    <li>Nullify volume listener libraries in "soundfx" folders  for disabling slight compression (maybe a peak limiter only on Qcomm devices).</li>
    <li>Set 192kHz & 32bit mode (max., but automatic for lower capability DAC's) for all the USB audio outputs (including non- Hi-Res audio tracks) of Tensor devices exceptionally<br/>
         because Tensor devices lower audio quality extremely for lower sample rates and bit depths, though the quality of in-DAC over-sampling filters is much worse than that of the re-sampling filter used by this module and the filters lower the quality particularly for input of lower sample rates as usual.
</li>
    </ol>
<br/><br/>

* Don't forget to install ["Audio jitter silencer"](https://github.com/Magisk-Modules-Alt-Repo/audio-jitter-silencer) together and uninstall "Digital Wellbeing" app (for reducing very large jitters which this module cannot reduce by itself)! And uninstall ["Audio misc. settings"](https://github.com/Magisk-Modules-Alt-Repo/audio-misc-settings) and ["DRC remover"](https://github.com/Magisk-Modules-Alt-Repo/drc-remover) if they have already been installed, because all their functions are included in this module. Additionally if your device uses a Tensor SoC, uninstall ["USB Samplerate Unlocker"](https://github.com/Magisk-Modules-Alt-Repo/usb-samplerate-unlocker) for the same reason.

* Don't use Am@zon music using a much worse internal re-sampler which bypasses the mastering quality re-sampling in the OS mixer (audioFlinger). Other music streaming services don't use such an internal re-sampler, as far as I know.

* This module has been tested on LineageOS and crDroid ROM's, and phh GSI's (Android 10 ~ 16, Qualcomm & MediaTek SoC, and Arm32 & Arm64 combinations). For users of Motorola and Xiaomi stock ROM's, try to install a GSI through DSU and this module together once, then you could know how much the ROM's degrade audio quality probably for adapting to regulations.

* Note: Entry class USB DAC's usually adopt an interface chip communicating with the adaptive mode or the synchronous one defined in the USB audio standard. As in these modes an Android host controller sends audio sampling rate clock signals to the DAC, jitter generated at the host side affects the audio quality of the DAC tremendously. Higher class DAC's communicate with the asynchronous mode (also defined in the standard) to a host controller, but they actually use a PLL to reduce jitter from the host not to stutter even in heavy jitter situations. As this result, they behave as the adaptive mode with a feedback loop to dynamically adjust the host side sampling clock signals while referring a DAC side clock in a real sense, so even with asynchronous mode they are more or less affected by host side jitter. You can see the mode of your USB DAC by opening "/proc/asound/card1/stream0" on your phone while playing music. Please see a word in parentheses at "Endpoint:" lines; "SYNC", "ADAPTIVE" or "ASYNC" means that your DAC uses "synchronous", "adaptive" or "asynchronous" mode to communicate to your phone, respectively. Moreover, almost all audio peripherals, e.g., bluetooth earphones, internal DAC's, network audio devices have a PLL in themselves and are affected by host side jitter for the same reason.

* I recommend expert users not to install ["Audio jitter silencer"](https://github.com/Magisk-Modules-Alt-Repo/audio-jitter-silencer), but manually to disable "Manage apps automatically" in "Battery manager" (or "Adaptive battery" of "Adaptive preferences") in the battery section (needless to say, don't enable battery savers, performance limiters and the like), turn off "Adaptive connectivity" in the Network & internet section (if exists), and changing "Battery optimization" from "Optimize" to "Don't optimize" (or change "Battery usage" from "Optimized" to "Unrestricted") for following app's manually through the settings UI of Android OS (to lower less than 10Hz jitter making extremely short reverb or foggy sound like distortion) even though disabling the Android doze itself: music (streaming) player apps, their licensing apps (if exist), "AirMusic" (if exists), "AirMusic  Recording Service" (system app; if exists), equalizer apps (if exist), "Bluetooth" (system app), "Bluetooth MIDI Service" (system app), "MTP Host" (system app), "NFC Service" (system app; if exists), "Magisk" (if exists), System WebView apps (system app), Browser apps, "PhhTrebleApp" (system app; if exists), "Android Services Library" (system app), "Android Shared Library" (system app), "Android System" (system app), "System UI" (system app), "Input Devices" (system app), {Gesture, 3 Button, 2  Button} Navigation Bar apps (which you are using only; system app), "crDroid System" (system app; if exists), "LineageOS System" (system app; if exists), launcher app, "Google Play Store" (system app), "Google Play services" (system app), "Styles & wallpaper" or the like (system app), {Lineage, crDroid, Arrow, etc.} themes app (system app; if exists),  "AOSP panel" (system app; if exists), "OmniJaws" (system app; if exists), "OmniStyle" (system app; if exists), "Active Edge Service" (system app; if exists), "Android Device Security Module" (system app; if exists), "Call Management" (system app; if exists), "Phone" (system app; if exists), "Phone Calls" (system app; if exists), "Phone Services" (system app; if exists), "Phone and Messaging Storage" (system app; if exists), "Storage Manager" (system app), "Default" (system app; if exists), "Default StatusBar" (system app; if exists), "Wfd Service" (system app; if exists), "Wallpaper" or the like (system app), "Adreno Graphics Drivers" (system app; if exists), "com.android.providers.media" (system app), "Files by Google" (system app; if exists), "Google Play Services for AR" (system app; if exists), "Google Services Framework" (system app), "Waterfall cutout" (system app), "Punch Hole cutout" (system app), "Network Manager" (system app), "Companion Device Manager" (system app), "Intent Filter Verification Service" (system app), "Calendar", camera apps, keyboard app, kernel adiutors (if exist), etc. And uninstall "Digital Wellbeing" (system app; if it exists) itself or change "Battery usage" from "Optimized" to "Restricted" (this is very harmful for audio like camera servers). Because "Audio jitter silencer" isn't complete and needs some maintenance after its installation.

* See also my companion script ["USB_SampleRate_Changer"](https://github.com/yzyhk904/USB_SampleRate_Changer) to change the sample rate of the USB (HAL) audio class driver and a 3.5mm jack on the fly like Bluetooth LDAC or Windows mixer to enjoy high resolution sound or to reduce resampling distortion (actually pre-echo, ringing and intermodulation) ultimately, and its simplified Magisk module version ["Audio Samplerate Changer"](https://github.com/Magisk-Modules-Alt-Repo/audio-samplerate-changer).

* Tips: If you use "AirMusic" to transmit audio data, I recommend setting around 4599 msec additional delay to reduce jitter distortion on the AirMusic panel to display target device(s).

* Note1: Please remember that this module will stop the thermal control (including CPU core controls, CPU hotplugs and thermal services), the "logd server" and the "camera server" (interfering jitter on audio outputs), disable SELinux enforcing mode and doze (battery saver while idling) on your device. If you like to enable these features, modify variables in "service.sh", respectively. Especially, note that the "Youtube" app became recetly to need the camera server for launching for some unexplained reason.

* Note2: If you prefer (too sensitive?) Bluetooth earphones to wired headphones and DLNA renderers, set "DisableClearestTone" variable to be "yes" in "service.sh".

* Appendix A. Examples of Re-sampling Parameters:
    
    
    | Stop band attenuation (dB) | Half filter length | Cut-off (%) | Stop band (%) | Memo |
    | ---: | ---: | ---: | ---: | ---- |
    | 90 | 32 | 100 | | AOSP default |
    | This mod. parameters: | - | - | - | - |
    | 159 | 320 | 92 | | Low Performance devices under A12 |
    | 159 | 480 | 92 | | High Performance devices under A12 |
    | 165 | 360 | | 104 | Low Performance devices for A12 and later |
    | 179 | 408 | | 99 | High Performance devices for A12 and later, and Galaxy S4 |
    | 194 | 520 | | 98 | Very High Performance devices |
    | External examples: | - | - | - | - |
    | 100 | 29 | (91) | 109 | AK4493 (Sharp roll-off N-fold over-sampling) |
    | 150 | 42 | (91) | 109 | AK4191EQ (Sharp roll-off N-fold over-sampling) |
    | 120 | 35 | (97) | 110 | ES9038PRO (Fast roll-off N-fold over-sampling) |
    | vary 50 ~ 118 | 34 | 96 | (398) | ES9039PRO (Fast roll-off N-fold over-sampling) |
    | 110 | 40 | (96) | 109 | CS43131 (Fast roll-off N-fold over-sampling) |
    | 110 | 40 | (96) | 109 | CS43198 (Fast roll-off N-fold over-sampling) |
    | 98 | 130 | 98.5 | | MacOS Leopard (guess) |
    | 159 | 240 | | 99 | iZotope, No-Alias (guess) |
    | 100 | 64 | | 99 | SoX HQ linear phase (guess) |
    | 170 | 520 | | 99 | SoX VHQ linear phase (guess) |

<br/>
<br/>

## DISCLAIMER

* I am not responsible for any damage that may occur to your device, so it is your own choice whether to attempt this module or not.

##


================================================
FILE: changelog.md
================================================
## Change logs

# v2.5.16
* Tuned I/O scheduling parameters for POCO F6, POCO F3, Motorola G54's and Pixel 6's 

# v2.5.15
* Added a USB DAC workaround for A17 beta3 of Pixel 6's for greater than 192 kHz samplerates; they have a bug that cannot detect any appropriate sample rate and depth of a USB DAC, but they can or may work for USB DAC's having a XMOS digital interface chip if specifying any sample rate and depth

# v2.5.14
* Optimized I/O scheduler tunables for MTK Dimensity
* Changed the USB audio driver for Pixel 6's so as to use the USB HAL audio driver instead of the USB audio offload driver
* Changed re-sampling parameters for Pixel 6's to use the same for cheapies
* Fixed a bug that greater than 96 kHz sample rates had not been unlocked

# v2.5.13
* Nullifying the volume listener for no compressing audio (maybe a peak limiter) on Motorola devices
* Changed an error message for no Magisk mirrors
* Stop AOCXD daemon on Tensor devices

# v2.5.12
* Tuned for POCO F3 and other "kona" board devices by adjusteding their core control parameters
* Improved and fixed GPU boosting for recent Qcomm and Mtk SoC's
* Fixed the audio policy configuration template for Tensor devices

# v2.5.11
* Tuned for POCO F6 (optimized for the ISIS kernel)
* Tuned for POCO F6 (optimized for the stock kernel, but not for the ISIS kernel)
* Tuned for POCO F3 (Android 15)
* Fixed for InfiR kernel about VM tunables

# v2.5.10
* Adapted to run with my new module "Audio Samplerate Changer"

# v2.5.9
* Optimized I/O scheduler tunables for POCO F6
* Added a support for Tensor G4 (zumapro)
* Tuned I/O scheduler tunables especially for "resampling-for-cheapies"
* Fixed an always 192 kHz USB  audio output mode for Pixel 8 and 9 series
* Changed the USB offload driver configuration of Tensor devices to be automatic max. detection
* Changed a mirroring warning for incompatible Magisk v28.0; Please use [Compatible magisk-mirroring](https://github.com/Magisk-Modules-Alt-Repo/compatible-magisk-mirroring) and Magisk v28.0 together
* Added better re-sampling parameters for very high performance devices

# v2.5.8
* Added disabling Dolby control support for USB DAC's on HyperOS not to reboot
* Excluded "MotorolaSettingsProvider" on Motorala devices only for avoiding their bootloop
* Changed the USB period_us from 2250 usec to 2000 usec to optimize for 48 kHz Opus tracks (recent majority)
* Adjusted jitter optimizations and others for YTM's format change from AAC (141; 44.1 kHz & 256 kbps cbr stereo) to Opus (774; 48 kHz & 256 kbps vbr stereo)
* Added new props "audio.safemedia.force=false" and "audio.safemedia.csd.force=false"
* Fixed above disabling Dolby control support (manufacturer mismatch)

# v2.5.7
* Changed head ahead buffer sizes from 16960 kB to 17000 kB to reduce I/O jitter
* Adjusted NrRequests of I/O scheduling
* Changed dirty_ratio and dirty_background_ration to be 100 to reduce jitter
* Adjusted re-sampling parameters for old devices
* Changed adjustSoC_mq for A14 and later clover not to round I/O parameters
* Adjusted cfq I/O parameters for SDM69x devices
* Changed the way how to get the actual audio policy file path in the service phase because some ROM's fail to execute "dumpsys" in the phase

# v2.5.6
* Added "compatible Magisk-mirroring" message for incompatible Magisk variants

# v2.5.5
* Tuned the USB period size for SDM845 devices (2500 usec to 2250 usec)
* Tuned the USB period size for other devices (to 2250 usec)
* Fixed logically wrong selinux prop settings (no meaning for magisk's magic mount mechanism)
* Added checking incompatible Magisk variants

# v2.5.4
* Tuned the USB period size for Tensor devices (2625 usec to 2250 usec)
* Fixed for Pixel 8's

# v2.5.3
* Changed the re-sampling parameters for Galaxy S4 to the general purpose ones (optimized for 3.5mm jack; not USB DAC's)
* Reduced I/O scheduling jitter on Tensor and SDM660 devices
* Reduced CFQ I/O scheduling jitter on Qcomm devices

# v2.5.2
* Tuned tunables of I/O scheduler
* Added warning messages for unneeded magisk modules

# v2.5.1
* Stopped Tensor device's AOC daemon for reducing significant jitter
* Optimized "extras/jitter-reducer.sh" for reducing I/O scheduling jitter on Tensor devices

# v2.5.0
* Optimized for Tensor devices by tuning GPU & I/O scheduling and replacing their stock audio policy configuration
* Hid preinstalled "Digital Wellbeing" feature for reducing significant jitter (please uninstall this manually if remaining as a usual app)

# v2.4.2
* Optimized "extras/jitter-reducer.sh" for reducing I/O scheduling jitter
* "extras/jitter-reducer.sh" now confirms and sets the cpu scaling max freq to its available max (sometimes the scaling max freq has been lowered before by a controller on some devices)

# v2.4.1
* Added support for ColorOS (experimental)

# v2.4.0
* Fixed some SELinux related bugs for Magisk v26.0's new magic mount feature
* Diabled pre-installed Moto Dolby features for reducing large jitter caused by them

# v2.3.2
* Added support for Tensor devices to bypass their spatial audio feature for reducing jitter distortion

# v2.3.1
* Added support for MTK A12 vendor primary audio HAL for reducing USB audio jitter
* Fixed a bug of DRC removing on phh GSI's (umounted in the boot process of phh GSI's)

# v2.3.0
* Nullified volume listener libraries in "soundfx" folders for disabling slight compression (maybe a peak limiter only on Qcomm devices).
Tuned for "mq-deadline", "kyber" and "none" I/O scheduler (latest kernel common schedulers?)
* Added support to the Nyx kernel 4.19
* Restructured source codes to be sharable with the jitter-reducer.sh in USB_SampleRate_Changer, audio-misc-settings and drc-remover

# v2.2.1
* Adjusted a USB transfer period of the USB HAL driver for reducing jitter

# v2.2.0
* Tuned kernel tunables by assuming an audio scheduling tunable "vendor.audio.adm.buffering.ms" to be "2"
* Adjusted a USB period to reduce jitter

# v2.1.8
* Disabled the Android doze system itself for reducing jitter considerably even though battery optimizations of app's are effective
* Tuned kernel tunables for SDM 8 series, MTK Dimensity's and Galaxy S4 (LineageOS 18.1)

# v2.1.7
* Changed resampling parameters for A12 or later (not having an aliasing processing bug)
* Tuned I/O scheduler tunables

# v2.1.6
* Improved tunable values of the deadline I/O scheduler

# v2.1.5
* Fixed a bug that DRC was not detected when updating from an old module
* Tuned parameters of the I/O scheduler

# v2.1.4
* Resampling quality changes from attenuation 140dB & length 320 to 160dB & 480

# v2.1.2
* Improved AudioFlinger's resampling quality (stopband 140dB, cutoff 91%)

# v2.1.1
* Enhanced the vm jitter reducer to handle "swap_ratio" and "swap_ratio_enable" for Snapdradons
* Optimized tunables of the I/O jitter reducer
* Added LICENSE

# v2.1.0
* The GPU frequency became to be fixed really at the max frequency for Qualcomm Soc and MediaTek SoC
* I/O scheduler tunables were optimized for audio clearness

# v2.0.5
* nr_requests was optimized

# v2.0.4
* Optimized I/O jitter reducer and fixed a bug disabling effects framework under PHH GSI's

# v2.0.2
* I/O tunables improved

# v2.0.1
* Initial public release

# v2.0.0
* Initial public pre-release
* Supported audio policy configuration XML files for "disable a2dp offload", "force-disable a2dp offload", and so on

# v1.4.0
* Moved scattered functions into "functions.sh" together, and treated IO Schedulers more rigorously

# v1.3.0
* Realme support (/proc/sys/vm/direct_swappiness)

# v1.2.0
* Stopped camera servers interfering in jitters on audio outputs, and reformatted source codes

# v1.1.0
* Stopped the EAS+ scheduling feature for MediaTek CPUs

# v1.0.0
* Initial limited release

##


================================================
FILE: customize-functions.sh
================================================
#!/system/bin/sh

# Check whether Magisk magic mount compatible or not
function isMagiskMountCompatible()
{
    local tmp="$(magisk --path)"
    if [ -z "$tmp" ]; then
        return 1
    elif [ -d "${tmp}/.magisk/mirror/vendor" ]; then
        return 0
    else
        return 1
    fi
}

# Get the active audio policy configuration fille from the audioserever
function getActivePolicyFile()
{
    dumpsys media.audio_policy | awk ' 
        /^ Config source: / {
            print $3
        }' 
}

# Extract the file name of an audio_policy_volumes.xml
function getVolumeFile()
{
    if [ $# -gt 0  -a  -r "$1" ]; then
        grep -m 1 -e '<xi:include[[:space:]]*href[[:space:]]*=[[:space:]]*".*audio_policy_volumes.*\.xml"' "$1" | awk -F '"' '{ print $2 }'
    else
        return 1
    fi
}

# Extract the file name of a default_volume_tables.xml
function getDefaultVolumeFile()
{
    if [ $# -gt 0  -a  -r "$1" ]; then
        grep -m 1 -e '<xi:include[[:space:]]*href[[:space:]]*=[[:space:]]*".*default_volume_tables.*\.xml"' "$1" | awk -F '"' '{ print $2 }'
    else
        return 1
    fi
}

function stopDRC()
{
    # stopDRC has two args specifying a main audio policy configuration XML file (eg. audio_policy_configuration.xml) and its dummy one to be overridden

     if [ $# -eq 2  -a  -r "$1"  -a  -w "$2" ]; then
        # Copy and override an original audio_policy_configuration.xml to its dummy file
        cp -f "$1" "$2"
        # Change audio_policy_configuration.xml file to remove DRC
        sed -i 's/speaker_drc_enabled[:space:]*=[:space:]*"true"/speaker_drc_enabled="false"/' "$2"
    fi
}

# Get the actual audio configuration XML file name, even for Xiaomi, OnePlus, etc.  stock devices
#    that may overlay another file on the dummy mount point file

function getActualConfigXML()
{
    if [ $# -eq 1 ]; then
        local dir=${1%/*}
        local fname=${1##*/}
        local sname=${fname%.*}
        
        if [ -r "${dir}/${sname}_sec.xml" ]; then
            echo "${dir}/${sname}_sec.xml"
        elif [ -e "${dir}_qssi"  -a  -r "${dir}_qssi/${fname}" ]; then
            # OnePlus stock pattern
            echo "${dir}_qssi/${fname}"
        elif [ "${dir##*/}"  = "sku_`getprop ro.board.platform`"  -a  -r "${dir%/*}/${fname}" ]; then
            # OnePlus stock pattern2
            echo "${dir%/*}/${fname}"
        elif [ -r "${dir}/audio/${fname}" ]; then
            # Xiaomi stock pattern
            echo "${dir}/audio/${fname}"
        elif [ -r "${dir}/${sname}_base.xml" ]; then
            echo "${dir}/${sname}_base.xml"
        else
            echo "$1"
        fi
    fi
}

function toHexLE()
{
    if [ $# -eq 1  -a  $1 -gt 0 ]; then
        printf "%2.2x%2.2x%2.2x%2.2x" $(( $1 % 256 ))  $(( $1 / 256 % 256 ))  $(( $1 / 256 / 256 % 256 ))  $(( $1 / 256 / 256 / 256 % 256 ))
        return 0
    else
        return 1
    fi
}

function toHexLineLE()
{
    if [ $# -eq 1 ]; then
        local i
        for i in $1; do
            toHexLE $i
        done
        return 0
    else
        return 1
    fi
}

function toHexString()
{
    if [ $# -ge 1 ]; then
        local tmp
        tmp=`echo -n "$1" | xxd -p | tr -d ' \n'`
        if [ $# -eq 2 ]; then
            if [ ${#tmp} -ge $2 ]; then
                echo -n ${tmp:0:$2}
            else
                local strt=`expr ${#tmp} + 1`
                echo -n "$tmp"
                for i in `seq $strt $2` ; do
                    echo -n "0"
                done
            fi
        else
            echo -n "$tmp"
        fi
    else
      return 1
    fi
}

# Patch libalsautils.so and audio_usb_aoc.so (Tensor's offload USB driver) to map a property string to another
#   arg1: original libalsautils.so file;  arg2: patched libalsautils.so file; 
function patchMapProperty()
{
    local orig_prop='ro.audio.usb.period_us'
    local new_prop='vendor.audio.usb.perio'
    
    if [ $# -eq 2  -a  -r "$1" ]; then
      local pat1=`toHexString "$orig_prop"`
      local pat2=`toHexString "$new_prop" ${#pat1}`
      
      xxd -p <"$1" | tr -d ' \n' | sed -e "s/$pat1/$pat2/" \
          | awk 'BEGIN {
                 foldWidth=60
                 getline buf
                 len=length(buf)
                 for (i=1; i <= len; i+=foldWidth) {
                     if (i + foldWidth - 1 <= len)
                         print substr(buf, i, foldWidth)
                     else
                         print substr(buf, i, len)
                 }
                 exit
             }'  \
         | xxd -r -p >"$2"
      return $?
    else
      return 1
    fi
}

# Patch libalsautils.so to clear the 96kHz lock of USB audio class drivers
#   arg1: original libalsautils.so file;  arg2: patched libalsautils.so file; 
#     optional arg3: "max" (clearing upto 768kHz), "full" (clearing upto 386kHz), "default" or others (clearing upto 192kHz)
function patchClearLock()
{
    local orig_rates='96000  88200  192000  176400  48000  44100  32000  24000  22050  16000  12000  11025  8000'
    local new_rates='192000  176400  96000  88200  48000  44100  32000  24000  22050  16000  12000  11025  8000'
    
    if [ $# -ge 2  -a  -r "$1" ]; then
        if [ $# -gt 2 ]; then
            case "$3" in
                "max" )
                    new_rates='768000  705600  384000  352800  192000  176400  96000  88200  48000  44100  24000  16000  8000'
                    ;;
                "full" )
                    new_rates='384000  352800  192000  176400  96000  88200  48000  44100  32000  24000  16000  12000  8000'
                    ;;
                "default" | * )
                    ;;
          esac
      fi

        local pat1=`toHexLineLE "$orig_rates"`
        local pat2=`toHexLineLE "$new_rates"`
      
        # A workaroud for a SELinux permission bug on Android 12
        local prop1=`toHexString "ro.audio.usb.period_us"`
        local prop2=`toHexString "vendor.audio.usb.perio"`
      
        xxd -p <"$1" | tr -d ' \n' | sed -e "s/$prop1/$prop2/" -e "s/$pat1/$pat2/" \
            | awk 'BEGIN {
                foldWidth=60
                getline buf
                len=length(buf)
                for (i=1; i <= len; i+=foldWidth) {
                    if (i + foldWidth - 1 <= len)
                        print substr(buf, i, foldWidth)
                    else
                        print substr(buf, i, len)
                }
                exit
              }'  \
            | xxd -r -p >"$2"
            
        return $?
        
    else
        
        return 1
    fi
}

# Patch audio_usb_aoc.so file to clear the 192kHz lock of USB audio class Tensor offload drivers
#   arg1: original audio_usb_aoc.so file;  arg2: patched audio_usb_aoc.so file; 
function patchClearTensorOffloadLock()
{
    local orig_rates='192000  96000  48000  44100  32000  24000  22050  16000  12000  11025  8000'
    local new_rates='768000  705600  384000  352800  192000  176400  96000  88200  48000  44100  8000'

    if [ $# -ge 2  -a  -r "$1" ]; then
        local pat1=`toHexLineLE "$orig_rates"`
        local pat2=`toHexLineLE "$new_rates"`

        # A workaroud for a SELinux permission bug on Android 12
        local prop1=`toHexString "ro.audio.usb.period_us"`
        local prop2=`toHexString "vendor.audio.usb.perio"`

        # sample rate limiter at 192kHz
        local ul1=`toHexLineLE "192000"`
        local ul2=`toHexLineLE "768000"`
          
#        Don't work yet. Need more inviestigations
#        xxd -p <"$1" | tr -d ' \n' | sed -e "s/$prop1/$prop2/" -e "s/$ul1/$ul2/" -e "s/$pat1/$pat2/" \
        xxd -p <"$1" | tr -d ' \n' | sed -e "s/$prop1/$prop2/" \
            | awk 'BEGIN {
                 foldWidth=60
                 getline buf
                 len=length(buf)
                 for (i=1; i <= len; i+=foldWidth) {
                     if (i + foldWidth - 1 <= len)
                         print substr(buf, i, foldWidth)
                     else
                         print substr(buf, i, len)
                 }
                 exit
               }'  \
             | xxd -r -p >"$2"
             
        return $?
        
    else
        return 1
    fi
}

function makeLibraries()
{
    local MAGISKPATH="$(magisk --path)"
    local d lname
    
    for d in "lib" "lib64"; do
        for lname in "libalsautils.so" "libalsautilsv2.so" "audio_usb_aoc.so"; do
            if [ -r "${MAGISKPATH}/.magisk/mirror/vendor/${d}/${lname}" ]; then
                mkdir -p "${MODPATH}/system/vendor/${d}"
                patchMapProperty "${MAGISKPATH}/.magisk/mirror/vendor/${d}/${lname}" "${MODPATH}/system/vendor/${d}/${lname}"
                chmod 644 "${MODPATH}/system/vendor/${d}/${lname}"
                chcon u:object_r:vendor_file:s0 "${MODPATH}/system/vendor/${d}/${lname}"
                chown root:root "${MODPATH}/system/vendor/${d}/${lname}"
                chmod -R a+rX "${MODPATH}/system/vendor/${d}"
                if [ -z "${REPLACEFILES}" ]; then
                    REPLACEFILES="/system/vendor/${d}/${lname}"
                else
                    REPLACEFILES="${REPLACEFILES} /system/vendor/${d}/${lname}"
                fi
            fi
        done        
    done
    
}

function makeUnlockedLibraries()
{
    local MAGISKPATH="$(magisk --path)"
    local d lname
    
    for d in "lib" "lib64"; do
        for lname in "libalsautils.so" "libalsautilsv2.so"; do
            if [ -r "${MAGISKPATH}/.magisk/mirror/vendor/${d}/${lname}" ]; then
                mkdir -p "${MODPATH}/system/vendor/${d}"
                patchClearLock "${MAGISKPATH}/.magisk/mirror/vendor/${d}/${lname}" "${MODPATH}/system/vendor/${d}/${lname}" "max"
                chmod 644 "${MODPATH}/system/vendor/${d}/${lname}"
                chcon u:object_r:vendor_file:s0 "${MODPATH}/system/vendor/${d}/${lname}"
                chown root:root "${MODPATH}/system/vendor/${d}/${lname}"
                chmod -R a+rX "${MODPATH}/system/vendor/${d}"
                if [ -z "${REPLACEFILES}" ]; then
                    REPLACEFILES="/system/vendor/${d}/${lname}"
                else
                    REPLACEFILES="${REPLACEFILES} /system/vendor/${d}/${lname}"
                fi
            fi
        done        
        for lname in "audio_usb_aoc.so"; do
            if [ -r "${MAGISKPATH}/.magisk/mirror/vendor/${d}/${lname}" ]; then
                mkdir -p "${MODPATH}/system/vendor/${d}"
                patchClearTensorOffloadLock "${MAGISKPATH}/.magisk/mirror/vendor/${d}/${lname}" "${MODPATH}/system/vendor/${d}/${lname}"
                chmod 644 "${MODPATH}/system/vendor/${d}/${lname}"
                chcon u:object_r:vendor_file:s0 "${MODPATH}/system/vendor/${d}/${lname}"
                chown root:root "${MODPATH}/system/vendor/${d}/${lname}"
                chmod -R a+rX "${MODPATH}/system/vendor/${d}"
                if [ -z "${REPLACEFILES}" ]; then
                    REPLACEFILES="/system/vendor/${d}/${lname}"
                else
                    REPLACEFILES="${REPLACEFILES} /system/vendor/${d}/${lname}"
                fi
            fi
        done        
    done
    
}

# Replace system property values for old Androids and some low performance SoC's

function loosenedMessage()
{
    local freq="96kHz"
    if [ $# -gt 0 ]; then
        freq="$1"
    fi
    
    ui_print ""
    ui_print "****************************************************************"
    ui_print " Loosened the USB jitter level for more than $freq USB outputs! "
    ui_print "   (\"USB Samplerate Unlocker\" was detected) "
    ui_print "****************************************************************"
    ui_print ""
}

function replaceSystemProps_VHPerf()
{
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop-workaround"
   
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.enable_at_samplerate=.*$/ro\.audio\.resampler\.psd\.enable_at_samplerate=44100/' \
        -e 's/ro\.audio\.resampler\.psd\.stopband=.*$/ro\.audio\.resampler\.psd\.stopband=194/' \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=520/' \
        -e 's/ro\.audio\.resampler\.psd\.tbwcheat=.*$/ro\.audio\.resampler\.psd\.tbwcheat=98/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.enable_at_samplerate=.*$/ro\.audio\.resampler\.psd\.enable_at_samplerate=44100/' \
        -e 's/ro\.audio\.resampler\.psd\.stopband=.*$/ro\.audio\.resampler\.psd\.stopband=194/' \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=520/' \
        -e 's/ro\.audio\.resampler\.psd\.tbwcheat=.*$/ro\.audio\.resampler\.psd\.tbwcheat=98/' \
            "$MODPATH/system.prop-workaround"
}

function replaceSystemProps_Old()
{
    if [ -e "${MODPATH%/*/*}/modules/usb-samplerate-unlocker"  -o  -e "${MODPATH%/*/*}/modules_update/usb-samplerate-unlocker" ]; then
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2250/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2250/' \
                "$MODPATH/system.prop"
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2250/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2250/' \
                "$MODPATH/system.prop-workaround"
        
        loosenedMessage
        
    else
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2250/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2250/' \
                "$MODPATH/system.prop"
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2250/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2250/' \
                "$MODPATH/system.prop-workaround"
    
    fi
    
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.enable_at_samplerate=.*$/ro\.audio\.resampler\.psd\.enable_at_samplerate=48000/' \
        -e 's/ro\.audio\.resampler\.psd\.stopband=.*$/ro\.audio\.resampler\.psd\.stopband=165/' \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=360/' \
        -e 's/ro\.audio\.resampler\.psd\.tbwcheat=.*$/ro\.audio\.resampler\.psd\.tbwcheat=104/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=320/' \
            "$MODPATH/system.prop-workaround"

}

function replaceSystemProps_S4()
{
    if [ -e "${MODPATH%/*/*}/modules/usb-samplerate-unlocker"  -o  -e "${MODPATH%/*/*}/modules_update/usb-samplerate-unlocker" ]; then
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=5000/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=5000/' \
                "$MODPATH/system.prop"
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=5000/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=5000/' \
                "$MODPATH/system.prop-workaround"
        
        loosenedMessage
        
    else
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=3875/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=3875/' \
                "$MODPATH/system.prop"
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=3875/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=3875/' \
                "$MODPATH/system.prop-workaround"

    fi
    
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.enable_at_samplerate=.*$/ro\.audio\.resampler\.psd\.enable_at_samplerate=48000/' \
        -e 's/ro\.audio\.resampler\.psd\.stopband=.*$/ro\.audio\.resampler\.psd\.stopband=165/' \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=360/' \
        -e 's/ro\.audio\.resampler\.psd\.tbwcheat=.*$/ro\.audio\.resampler\.psd\.tbwcheat=104/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=320/' \
            "$MODPATH/system.prop-workaround"
}

function replaceSystemProps_Kona()
{
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=4000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=4000/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=4000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=4000/' \
            "$MODPATH/system.prop-workaround"
}

function replaceSystemProps_SDM845()
{
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop-workaround"
}

function replaceSystemProps_SDM()
{
    # Do nothing even if "usb-samplerate-unlocker" exists
    :
}

function replaceSystemProps_MTK_Dimensity()
{
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop-workaround"
}

function replaceSystemProps_Tensor()
{
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop"
    sed -i \
        -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
        -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
            "$MODPATH/system.prop-workaround"
            
    sed -i \
        -e 's/ro\.audio\.resampler\.psd\.enable_at_samplerate=.*$/ro\.audio\.resampler\.psd\.enable_at_samplerate=48000/' \
        -e 's/ro\.audio\.resampler\.psd\.stopband=.*$/ro\.audio\.resampler\.psd\.stopband=194/' \
        -e 's/ro\.audio\.resampler\.psd\.halflength=.*$/ro\.audio\.resampler\.psd\.halflength=520/' \
        -e 's/ro\.audio\.resampler\.psd\.tbwcheat=.*$/ro\.audio\.resampler\.psd\.tbwcheat=83/' \
            "$MODPATH/system.prop"
}

function replaceSystemProps_Others()
{
    if [ -e "${MODPATH%/*/*}/modules/usb-samplerate-unlocker"  -o  -e "${MODPATH%/*/*}/modules_update/usb-samplerate-unlocker" ]; then
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
                "$MODPATH/system.prop"
        sed -i \
            -e 's/vendor\.audio\.usb\.perio=.*$/vendor\.audio\.usb\.perio=2000/' \
            -e 's/vendor\.audio\.usb\.out\.period_us=.*$/vendor\.audio\.usb\.out\.period_us=2000/' \
                "$MODPATH/system.prop-workaround"
        
        loosenedMessage
        
    fi
    
}

# HyperOS v2.0 and Motorola stock OS v15.0 cannot increase the number of volume steps

function deleteSystemProps_for_some_Stocks()
{
    local Moto="`getprop ro.mot.build.customerid`"
    local MIUI="`getprop ro.miui.ui.version.code`"
    local AndroidVersion="`getprop ro.system.build.version.release`"

    if [  -n "$MIUI"  -a  "$MIUI" -ge 14 ] || [ -n "$Moto"  -a  "$AndroidVersion" -ge 15 ]; then
        sed -i \
            -e '/^ro\.config\.media_vol_steps=/d' \
                "$MODPATH/system.prop"
        sed -i \
            -e '/^ro\.config\.media_vol_steps=/d' \
                "$MODPATH/system.prop-workaround"
        
    fi
    
}

function stopSpatializer()
{
    # stopSpatializer has two args specifying an audio policy configuration XML file (eg. bluetooth_audio_policy_configuration_7_0.xml) 
    #   and its dummy one to be overridden

    if [ $# -eq 2  -a  -r "$1"  -a  -w "$2" ]; then
        # Copy and override an original audio_policy_configuration.xml to its dummy file
        cp -f "$1" "$2"
        # Change an audio_policy_configuration.xml file to remove Spatializer
        sed -i 's/flags[:space:]*=[:space:]*"AUDIO_OUTPUT_FLAG_SPATIALIZER"//' "$2"
    fi
}

function deSpatializeAudioPolicyConfig()
{
    if [ $# -ne 1  -o  -z "$1"  -o  ! -r "$1" ]; then
        return 1
    fi
    local MAGISKPATH="$(magisk --path)"
    local configXML="$1"
    
    # Don't use "$MAGISKPATH/.magisk/mirror/system${configXML}" instead of "$MAGISKPATH/.magisk/mirror${configXML}".
    # In some cases, the former may link to overlaied "${configXML}" by Magisk itself (not original mirrored "${configXML}").
    local mirrorConfigXML="$MAGISKPATH/.magisk/mirror${configXML}"

    if [ -n "$configXML"  -a  -r "$mirrorConfigXML" ]; then
        grep -e "flags[[:space:]]*=[[:space:]]*\"AUDIO_OUTPUT_FLAG_SPATIALIZER\"" "$mirrorConfigXML" >"/dev/null" 2>&1
        if [ "$?" -eq 0 ]; then
            local modConfigXML="$MODPATH/system${configXML}"
            mkdir -p "${modConfigXML%/*}"
            touch "$modConfigXML"
            stopSpatializer "$mirrorConfigXML" "$modConfigXML"
            chmod 644 "$modConfigXML"
            chcon u:object_r:vendor_configs_file:s0 "$modConfigXML"
            chown root:root "$modConfigXML"
            chmod -R a+rX "${modConfigXML%/*}"
            if [ -z "$REPLACEFILES" ]; then
                REPLACEFILES="/system${configXML}"
            else
                REPLACEFILES="$REPLACEFILES /system${configXML}"
            fi
        fi
    fi
}

function disablePrivApps()
{
    if [ $# -ne 1  -o  -z "$1" ]; then
        return 1
    fi

    local MAGISKPATH="$(magisk --path)"
    local dir mdir
    local PrivApps="$1"
    
    for dir in $PrivApps; do
        if [ -d "${MAGISKPATH}/.magisk/mirror${dir}" ]; then
            case "${dir}" in
                /system/* )
                    dir="${dir#/system}"
                ;;
            esac
            mdir="${MODPATH}/system${dir}"
            mkdir -p "$mdir"
            chmod a+rx "$mdir"
            if [ -z "$REPLACE" ]; then
                REPLACE="/system${dir}"
            else
                REPLACE="${REPLACE} /system${dir}"
            fi
        fi
    done
}

function ui_print_replacelist()
{
    local f
    for f in $1; do
        ui_print "- Replace target file: $f"
    done
}


================================================
FILE: customize.sh
================================================
#!/system/bin/sh

[ -z "$(magisk --path)" ] && alias magisk='ksu-magisk'

. "$MODPATH/customize-functions.sh"

if ! isMagiskMountCompatible; then
    abort '  ***
  Aborted by no magisk-mirrors (even including kernelSUs):
    Try again after reawaking the mirrors
        by installing my another magisk/kernelSU module
        "Compatible Magisk-mirroring" and rebooting

  ***'
fi

MAGISKTMP="$(magisk --path)/.magisk"

# Note: Don't use "${MAGISKTMP}/mirror/system/vendor/*" instaed of "${MAGISKTMP}/mirror/vendor/*".
# In some cases, the former may link to overlaied "/system/vendor" by Magisk itself (not mirrored original one).

REPLACE=""
REPLACEFILES=""

# Check if on a Tensor (except zumapro) device or not
case "`getprop ro.board.platform`" in
    gs* | "zuma" )
        tensorFlag=1
        ;;
    * )
        tensorFlag=0
        ;;
esac

if [ "$tensorFlag" -eq 1 ]; then
    # Unlocks the limiter of Tensor device's USB offload driver from 96kHz to 192kHz
    fname="/system/vendor/etc/audio_platform_configuration.xml"
    if [ -r "$fname" ]; then
        mkdir -p "${MODPATH}${fname%/*}"
        sed -e 's|min_rate="[1-9][0-9]*"|min_rate="44100"|g' \
            -e 's|"MaxSamplingRate=[1-9][0-9]*,|"MaxSamplingRate=192000,|' \
                <"${MAGISKTMP}/mirror${fname#/system}" >"${MODPATH}${fname}"
        touch "${MODPATH}${fname}"
        chmod 644 "${MODPATH}${fname}"
        chcon u:object_r:vendor_configs_file:s0 "${MODPATH}${fname}"
        chown root:root "${MODPATH}${fname}"
        chmod -R a+rX "${MODPATH}${fname%/*}"
        if [ -z "${REPLACEFILES}" ]; then
            REPLACEFILES="${fname}"
        else
            REPLACEFILES="${REPLACEFILES} ${fname}"
        fi
    fi
    
fi

# If detecting DRC-enabled or Tensor SoC, then make a DRC-less or Tensor specifically tuned config file and overlay
#
# Set the active configuration file name retrieved from the audio policy server
configXML="`getActivePolicyFile`"

# configXML is usually placed under "/vendor/etc" (or "/vendor/etc/audio"), but
# "/my_product/etc" and "/odm/etc" are used on ColorOS (RealmeUI) and OxygenOS(?)
case "$configXML" in
    /vendor/etc/* | /my_product/etc/* | /odm/etc/* | /system/etc/* | /product/etc/* )
        if [ -n "$MAGISKTMP"  -a  -r "${MAGISKTMP}/mirror${configXML}" ]; then
            mirrorConfigXML="${MAGISKTMP}/mirror${configXML}"
        else
            mirrorConfigXML="$configXML"
        fi
        mirrorConfigXML="`getActualConfigXML \"${mirrorConfigXML}\"`"
        case "${configXML}" in
            /system/* )
                configXML="${configXML#/system}"
            ;;
        esac
        modConfigXML="$MODPATH/system${configXML}"
        
        # If DRC enabled, modify audio policy configuration to stopt DRC
        grep -e "speaker_drc_enabled[[:space:]]*=[[:space:]]*\"true\"" $mirrorConfigXML >"/dev/null" 2>&1
        if [ "$?" -eq 0 ]; then
            drcFlag=1
        else
            drcFlag=0
        fi
        
        if [ "$drcFlag" -eq 1  -o  "$tensorFlag" -eq 1 ]; then
            mkdir -p "${modConfigXML%/*}"
            touch "$modConfigXML"
            if [ "$drcFlag" -eq 1 ]; then
                stopDRC "$mirrorConfigXML" "$modConfigXML"
            else
                DRC_enabled="false"
                USB_module="usbv2"
                BT_module="bluetooth"
                SampleRatePrimary="48000"
                AudioFormatPrimary="AUDIO_FORMAT_PCM_32_BIT"
                VolumeFile=$(getVolumeFile "$mirrorConfigXML")
                templateFile="$MODPATH/templates/offload_hifi_playback_template.xml"
                
                if [ -z "$VolumeFile" ]; then
                    VolumeFile="/vendor/etc/audio_policy_volumes.xml"
                fi
                DefaultVolumeFile=$(getDefaultVolumeFile "$mirrorConfigXML")
                if [ -z "$DefaultVolumeFile" ]; then
                    DefaultVolumeFile="/vendor/etc/default_volume_tables.xml"
                fi

                if [ "`getprop ro.build.version.codename`" = "CinnamonBun" ]; then
                    # A17 beta3 of Pixel 6's have a bug that cannot detect any appropriate sample rate and depth of a DAC
                    # But they can or may work for DAC's having a XMOS digital interface chip if specifying any sample rate and depth
                    templateFile="$MODPATH/templates/bypass_offload_safer_template.xml"
                    SampleRatePrimary="768000"
                elif [ "`getprop ro.build.date.utc`" -ge "1762519080" ]; then
                    # A USB HAL driver bug has been fixed since Dec. 2025
                    templateFile="$MODPATH/templates/bypass_offload_template.xml"
                fi
                
                sed   -e "s|%DRC_ENABLED%|$DRC_enabled|" -e "s|%USB_MODULE%|$USB_module|" -e "s|%BT_MODULE%|$BT_module|" \
                        -e "s|%SAMPLING_RATE%|$SampleRatePrimary|" -e "s|%AUDIO_FORMAT%|$AudioFormatPrimary|" \
                        -e "s|%VOLUME_FILE%|$VolumeFile|" -e "s|%DEFAULT_VOLUME_FILE%|$DefaultVolumeFile|" \
                        "$templateFile" >"$modConfigXML"
            fi
            chmod 644 "$modConfigXML"
            chcon u:object_r:vendor_configs_file:s0 "$modConfigXML"
            chown root:root "$modConfigXML"
            chmod -R a+rX "${modConfigXML%/*}"
            REPLACEFILES="/system${configXML} $REPLACEFILES"
            
            # If "${configXML}" isn't symbolically linked to "$/system/{configXML}", 
            #   disable Magisk's "magic mount" and mount "${configXML}" by this module itself in "service.sh"
            if [ ! -e "/system${configXML}" ]; then
                touch "$MODPATH/skip_mount"
            fi
        fi
        ;;
    "N/A" )
        # AIDL only devices or ones in some trouble
        ;;
    * )
        ;;
esac

# Make patched ALSA utility libraries for "ro.audio.usb.period_us"
makeUnlockedLibraries

# Remove post-A13 (especially Tensor's) spatial audio flags in an audio configuration file for avoiding errors
deSpatializeAudioPolicyConfig "/vendor/etc/bluetooth_audio_policy_configuration_7_0.xml"

# Disabe pre-installed Moto Dolby faetures and Wellbeing for reducing very large jitter caused by them
#   Excluded "MotorolaSettingsProvider" on Motorala devices for avoiding bootloop
if [ "`getprop ro.product.manufacturer`" = "motorola" ]; then
    disablePrivApps "
/system_ext/priv-app/MotoDolbyDax3
/system_ext/priv-app/daxService
/system_ext/priv-app/DaxUI
/system_ext/app/MotoSignatureApp
/product/priv-app/WellbeingPrebuilt
/product/priv-app/Wellbeing
/system_ext/priv-app/WellbeingPrebuilt
/system_ext/priv-app/Wellbeing
"
else
    disablePrivApps "
/system_ext/priv-app/MotoDolbyDax3
/system_ext/priv-app/MotorolaSettingsProvider
/system_ext/priv-app/daxService
/system_ext/priv-app/DaxUI
/system_ext/app/MotoSignatureApp
/product/priv-app/WellbeingPrebuilt
/product/priv-app/Wellbeing
/system_ext/priv-app/WellbeingPrebuilt
/system_ext/priv-app/Wellbeing
"
fi

if "$IS64BIT"; then
    board="`getprop ro.board.platform`"
    case "$board" in
        zuma* | "pineapple" )
            replaceSystemProps_VHPerf
            ;;
        "kona" | "kalama" | "shima" | "yupik" )
            replaceSystemProps_Kona
            ;;
        "sdm845" )
            replaceSystemProps_SDM845
            ;;
        gs* )
            replaceSystemProps_Tensor
            ;;
        "sdm660" | "bengal" | "holi" )
            replaceSystemProps_SDM
            ;;
        mt68* )
            replaceSystemProps_MTK_Dimensity
            ;;
        mt67[56]? )
            replaceSystemProps_Others
            ;;
        * )
            replaceSystemProps_Others
            ;;
    esac

    deleteSystemProps_for_some_Stocks

else
    if [ "`getprop ro.build.product`" = "jfltexx" ]; then
        replaceSystemProps_S4
    else
        replaceSystemProps_Old
    fi

fi

# AudioFlinger's resampler has a bug on an Android OS of which version is less than 12.
# This bug makes the resampler to distort audible audio output by wrong aliasing processing
#   when specifying a transition band around or higher than the Nyquist frequency

if [ "`getprop ro.system.build.version.release`" -lt "12"  -a  "`getprop ro.system.build.date.utc`" -lt "1648632000" ]; then
    mv -f "$MODPATH/system.prop-workaround" "$MODPATH/system.prop"
else
    rm -f "$MODPATH/system.prop-workaround"
fi

# Warning unneeded magisk modules

if [ -e "${MODPATH%/*/*}/modules/audio-misc-settings" ]; then
    ui_print ""
    ui_print "****************************************************************"
    ui_print " Uninstall \"Audio misc. settings\" manually later; this module includes all its features"
    ui_print "****************************************************************"
    ui_print ""
fi
if [ -e "${MODPATH%/*/*}/modules/drc-remover" ]; then
    ui_print ""
    ui_print "****************************************************************"
    ui_print " Uninstall \"DRC remover\" manually later; this module includes all its features"
    ui_print "****************************************************************"
    ui_print ""
fi
if [ "$tensorFlag" -eq 1  -a  -e "${MODPATH%/*/*}/modules/usb-samplerate-unlocker" ]; then
    ui_print ""
    ui_print "****************************************************************"
    ui_print " Uninstall \"USB Samplerate Unlocker\" manually later; this module includes all its features"
    ui_print "****************************************************************"
    ui_print ""
fi
if [ "$tensorFlag" -eq 1  -a  -e "${MODPATH%/*/*}/modules/audio-samplerate-changer" ]; then
    ui_print ""
    ui_print "****************************************************************"
    ui_print " Uninstall \"Audio Samplerate Changer\" manually later; this module includes all its features"
    ui_print "****************************************************************"
    ui_print ""
fi
 
rm -f "$MODPATH/customize-functions.sh" "$MODPATH/LICENSE" "$MODPATH/README.md" "$MODPATH/changelog.md"
rm -rf "$MODPATH/templates"
ui_print_replacelist "$REPLACEFILES"


================================================
FILE: jitter-reducer-functions.shlib
================================================
#!/system/bin/sh

function forceOnlineCPUs()
{
    local i st en
    IFS="-" read st en <"/sys/devices/system/cpu/present"
    if [ -n "$st"  -a  -n "$en"  -a "$st" -ge 0  -a  "$en" -ge 0 ]; then
        for i in `seq $st $en`; do
            if [ -e "/sys/devices/system/cpu/cpu$i/online" ]; then
                chmod 644 "/sys/devices/system/cpu/cpu$i/online"
                echo '1' >"/sys/devices/system/cpu/cpu$i/online"
            fi
        done
    fi
}

function searchDefaultCpuGovernor()
{
    # Search default CPU governor
    local gov=""
    local i
    for i in `cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors`; do
        if [ "$i" = "walt"  -o  "$i" = "sugov_ext"  -o  "$i" = "sched_pixel"  -o  "$i" = "schedutil" ]; then
            gov="$i"
            break;
        elif [ ! "$gov" = "schedplus" ]; then
             if [ "$i" = "schedplus" ]; then
                gov="$i"
            elif [ ! "$gov" = "interactive" ]; then
                gov="$i"
            fi
        fi
    done
    if [ -z "$gov" ]; then
        gov="performance"
    fi
    echo "$gov"
}

function reduceSelinuxJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"
        
        if [ $flag -gt 0 ]; then
            setenforce 0
        elif [ $flag -lt 0 ]; then
            if [ "`getprop ro.build.product`" = "jfltexx"  -a   "`getprop ro.system.build.version.release`" -ge "12" ]; then
                echo "Warning: ignored trying to change Selinux mode" 1>&2
            else
                setenforce 1
            fi
            
        fi
        
        if [ $printStatus -gt 0 ]; then
            echo "  Selinux mode: `getenforce`"
        fi
    else
        return 1
    fi
}

function reduceThermalJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"
        
        if [ $flag -gt 0 ]; then   
         
            # Stop thermal core control
            if [ -w "/sys/module/msm_thermal/core_control/enabled" ]; then
                echo '0' > "/sys/module/msm_thermal/core_control/enabled"
            fi
            if [ -r "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                local i st en
                IFS="-" read st en <"/sys/devices/system/cpu/present"
                if [ -n "$st"  -a  -n "$en"  -a "$st" -ge 0  -a  "$en" -ge 0 ]; then
                    if [ -w "/sys/devices/system/cpu/cpu7/core_ctl/enable" ]; then
                        # SD850 or higher type core control
                        local ncpu_remained=7
                        
                        echo '1'  > "/sys/devices/system/cpu/cpu7/core_ctl/enable"
                        echo '1'  > "/sys/devices/system/cpu/cpu7/core_ctl/min_cpus"
                        echo '55'  > "/sys/devices/system/cpu/cpu7/core_ctl/busy_down_thres"
                        echo '0'  > "/sys/devices/system/cpu/cpu7/core_ctl/busy_up_thres"
                        echo '2900'  > "/sys/devices/system/cpu/cpu7/core_ctl/offline_delay_ms"
                        echo '0'  > "/sys/devices/system/cpu/cpu7/core_ctl/enable"
                        if [ -w "/sys/devices/system/cpu/cpu3/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu3/core_ctl/enable"
                            # min_cpus cannot be set to be 4, so 3
                            echo '3'  > "/sys/devices/system/cpu/cpu3/core_ctl/min_cpus"
                            echo '55 55 55'  > "/sys/devices/system/cpu/cpu3/core_ctl/busy_down_thres"
                            echo '0 0 0'  > "/sys/devices/system/cpu/cpu3/core_ctl/busy_up_thres"
                            echo '2900'  > "/sys/devices/system/cpu/cpu3/core_ctl/offline_delay_ms"
                            echo '0'  > "/sys/devices/system/cpu/cpu3/core_ctl/enable"
                            ncpu_remained=3
                        elif [ -w "/sys/devices/system/cpu/cpu4/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu4/core_ctl/enable"
                            echo '3'  > "/sys/devices/system/cpu/cpu4/core_ctl/min_cpus"
                            echo '55 55 55'  > "/sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres"
                            echo '0 0 0'  > "/sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres"
                            echo '2900'  > "/sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms"
                            echo '0'  > "/sys/devices/system/cpu/cpu4/core_ctl/enable"
                            ncpu_remained=4
                        fi
                        if [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                            echo "$ncpu_remained"  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                            echo '55 55 55 55'  > "/sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres"
                            echo '0 0 0 0'  > "/sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres"
                            echo '2900'  > "/sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms"
                            echo '0'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        fi
                    elif [ -w "/sys/devices/system/cpu/cpu6/core_ctl/enable" ]; then
                        # Dimensity type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu6/core_ctl/enable"
                        echo '2'  > "/sys/devices/system/cpu/cpu6/core_ctl/min_cpus"
                        echo '0'  > "/sys/devices/system/cpu/cpu6/core_ctl/enable"
                        if [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                            echo '6'  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                            echo '0'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        fi
                    elif [ -w "/sys/devices/system/cpu/cpu4/core_ctl/enable" ]; then
                        # SD840 or lower type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu4/core_ctl/enable"
                        echo '4'  > "/sys/devices/system/cpu/cpu4/core_ctl/min_cpus"
                        echo '0'  > "/sys/devices/system/cpu/cpu4/core_ctl/enable"
                        if [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                            echo '4'  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                            echo '0'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        fi
                    elif [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                        # unknown type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        echo '4'  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                        echo '0'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                    fi
                fi
            fi
            # Stop the MPDecision (CPU hotplug)
            if [ "`getprop init.svc.mpdecision`" = "running" ]; then
                setprop ctl.stop mpdecision
                forceOnlineCPUs
            elif [ "`getprop init.svc.mpdecision`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.mpdecision`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                    forceOnlineCPUs
                fi
            elif [ "`getprop init.svc.vendor.mpdecision`" = "running" ]; then
                setprop ctl.stop vendor.mpdecision
                forceOnlineCPUs
            elif [ "`getprop init.svc.vendor.mpdecision`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.vendor.mpdecision`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                    forceOnlineCPUs
                fi
            fi
            # Stop the thermal server
            if [ "`getprop init.svc.thermal`" = "running" ]; then
                setprop ctl.stop thermal
            elif [ "`getprop init.svc.thermal`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.thermal`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            elif [ "`getprop init.svc.vendor.thermal`" = "running" ]; then
                setprop ctl.stop vendor.thermal
            elif [ "`getprop init.svc.vendor.thermal`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.vendor.thermal`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            
            # Stop MTK thermald and thermal_core
            if [ "`getprop init.svc.thermald`" = "running" ]; then
                setprop ctl.stop thermald
            elif [ "`getprop init.svc.thermald`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.thermald`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.thermal_core`" = "running" ]; then
                setprop ctl.stop thermal_core
            elif [ "`getprop init.svc.thermal_core`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.thermal_core`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi

            # Stop the mi_thermald server
            if [ "`getprop init.svc.mi_thermald`" = "running" ]; then
                setprop ctl.stop mi_thermald
            elif [ "`getprop init.svc.mi_thermald`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.mi_thermald`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            elif [ "`getprop init.svc.vendor.mi_thermald`" = "running" ]; then
                setprop ctl.stop vendor.mi_thermald
            elif [ "`getprop init.svc.vendor.mi_thermald`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.vendor.mi_thermald`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            # Stop the thermal-engine server
            if [ "`getprop init.svc.thermal-engine`" = "running" ]; then
                setprop ctl.stop thermal-engine
            elif [ "`getprop init.svc.thermal-engine`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.thermal-engine`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            elif [ "`getprop init.svc.vendor.thermal-engine`" = "running" ]; then
                setprop ctl.stop vendor.thermal-engine
            elif [ "`getprop init.svc.vendor.thermal-engine`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.vendor.thermal-engine`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            # For MediaTek CPU's
            if [ -w "/proc/cpufreq/cpufreq_sched_disable" ]; then
                echo '1' > "/proc/cpufreq/cpufreq_sched_disable"
                forceOnlineCPUs
            fi
        
        elif [ $flag -lt 0 ]; then
        
            # Start thermal core control
             if [ -w "/sys/module/msm_thermal/core_control/enabled" ]; then
                echo '1' > "/sys/module/msm_thermal/core_control/enabled"
            fi
            if [ -r "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                local st en
                IFS="-" read st en <"/sys/devices/system/cpu/present"
                if [ -n "$st"  -a  -n "$en"  -a "$st" -ge 0  -a  "$en" -ge 0 ]; then
                    if [ -w "/sys/devices/system/cpu/cpu7/core_ctl/enable" ]; then
                        local ncpu_remained=7
                        # SD850 or higher type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu7/core_ctl/enable"
                        echo '0'  > "/sys/devices/system/cpu/cpu7/core_ctl/min_cpus"
                        echo '30'  > "/sys/devices/system/cpu/cpu7/core_ctl/busy_down_thres"
                        echo '60'  > "/sys/devices/system/cpu/cpu7/core_ctl/busy_up_thres"
                        echo '100'  > "/sys/devices/system/cpu/cpu7/core_ctl/offline_delay_ms"
                        if [ -w "/sys/devices/system/cpu/cpu3/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu3/core_ctl/enable"
                            echo '3'  > "/sys/devices/system/cpu/cpu3/core_ctl/min_cpus"
                            echo '30 30 30'  > "/sys/devices/system/cpu/cpu3/core_ctl/busy_down_thres"
                            echo '60 60 60'  > "/sys/devices/system/cpu/cpu3/core_ctl/busy_up_thres"
                            echo '100'  > "/sys/devices/system/cpu/cpu3/core_ctl/offline_delay_ms"
                            ncpu_remained=3
                        elif [ -w "/sys/devices/system/cpu/cpu4/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu4/core_ctl/enable"
                            echo '2'  > "/sys/devices/system/cpu/cpu4/core_ctl/min_cpus"
                            echo '30 30 30'  > "/sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres"
                            echo '60 60 60'  > "/sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres"
                            echo '100'  > "/sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms"
                            ncpu_remained=4
                        fi
                        if [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                            echo "$ncpu_remained"  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                            echo '0 0 0 0'  > "/sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres"
                            echo '0 0 0 0'  > "/sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres"
                            echo '100'  > "/sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms"
                            echo '0'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        fi
                    elif [ -w "/sys/devices/system/cpu/cpu6/core_ctl/enable" ]; then
                        # Dimensity type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu6/core_ctl/enable"
                        if [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        fi
                    elif [ -w "/sys/devices/system/cpu/cpu4/core_ctl/enable" ]; then
                        # SD840 or lower type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu4/core_ctl/enable"
                        echo '1'  > "/sys/devices/system/cpu/cpu4/core_ctl/min_cpus"
                        if [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                            echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                        fi
                    elif [ -w "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                        # unknown type core control
                        echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/enable"
                        echo '1'  > "/sys/devices/system/cpu/cpu0/core_ctl/min_cpus"
                    fi
                fi
            fi
            # Start the MPDecision (CPU hotplug)
            if [ "`getprop init.svc.mpdecision`" = "stopped" ]; then
                setprop ctl.start mpdecision
                forceOnlineCPUs
            elif [ "`getprop init.svc.vendor.mpdecision`" = "stopped" ]; then
                setprop ctl.start vendor.mpdecision
                forceOnlineCPUs
            fi
            # Start the thermal server
            if [ "`getprop init.svc.thermal`" = "stopped" ]; then
                setprop ctl.start thermal
            elif [ "`getprop init.svc.vendor.thermal`" = "stopped" ]; then
                setprop ctl.start vendor.thermal
            fi
            # Start the MTK thermald and thermal_core server
            if [ "`getprop init.svc.thermald`" = "stopped" ]; then
                setprop ctl.start thermald
            fi
            if [ "`getprop init.svc.thermal_core`" = "stopped" ]; then
                setprop ctl.start thermal_core
            fi
            # Start the mi_thermald server
            if [ "`getprop init.svc.mi_thermald`" = "stopped" ]; then
                setprop ctl.start mi_thermald
            elif [ "`getprop init.svc.vendor.mi_thermald`" = "stopped" ]; then
                setprop ctl.start vendor.mi_thermald
            fi
            # Start the thermal-engine server
            if [ "`getprop init.svc.thermal-engine`" = "stopped" ]; then
                setprop ctl.start thermal-engine
            elif [ "`getprop init.svc.vendor.thermal-engine`" = "stopped" ]; then
                setprop ctl.start vendor.thermal-engine
            fi
            # For MediaTek CPU's
            if [ -w "/proc/cpufreq/cpufreq_sched_disable" ]; then
                val="`searchDefaultCpuGovernor`"
                if [ "$val" = "schedutil"  -a  "`getprop ro.vendor.build.version.release`" -lt "11" ]; then
                    echo "    Notice: EAS hasn't been enabled, so skipping thermal MTK EAS+ enabling" 1>&2
                else
                    echo '0' > "/proc/cpufreq/cpufreq_sched_disable"
                fi
            fi
        
        fi
      
        if [ $printStatus -gt 0 ]; then
            local found=0
            
            # Qualcomm Core control
            if [ -w "/sys/module/msm_thermal/core_control/enabled" ]; then
                if [ "`cat /sys/module/msm_thermal/core_control/enabled`" -eq 0 ]; then
                    echo "  Thermal msm_thermal: disabled"
                else
                    echo "  Thermal msm_thermal: enabled"
                fi
                found=1
            fi
            if [ -r "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                local i st en ctl_enabled=0
                IFS="-" read st en <"/sys/devices/system/cpu/present"
                if [ -n "$st"  -a  -n "$en"  -a "$st" -ge 0  -a  "$en" -ge 0 ]; then
                    if [ -r "/sys/devices/system/cpu/cpu7/core_ctl/enable" ]; then
                        read ctl_enabled <"/sys/devices/system/cpu/cpu7/core_ctl/enable"
                    elif [ -r "/sys/devices/system/cpu/cpu6/core_ctl/enable" ]; then
                        read ctl_enabled <"/sys/devices/system/cpu/cpu6/core_ctl/enable"
                    elif [ -r "/sys/devices/system/cpu/cpu4/core_ctl/enable" ]; then
                        read ctl_enabled <"/sys/devices/system/cpu/cpu4/core_ctl/enable"
                    elif [ -r "/sys/devices/system/cpu/cpu0/core_ctl/enable" ]; then
                        read ctl_enabled <"/sys/devices/system/cpu/cpu0/core_ctl/enable"
                    fi
                    if [ "$ctl_enabled" -gt 0 ]; then
                        echo "  Thermal core_ctl: enabled"
                    else
                        echo "  Thermal core_ctl: disabled"
                    fi
                    found=1
                fi
            fi
            if [ -n "`getprop init.svc.thermal`" ]; then
                echo "  Thermal server: `getprop init.svc.thermal`"
                found=1
            elif [ -n "`getprop init.svc.vendor.thermal`" ]; then
                echo "  Thermal server: `getprop init.svc.vendor.thermal`"
                found=1
            fi
            if [ -n "`getprop init.svc.thermald`" ]; then
                echo "  Thermal MTK thermald: `getprop init.svc.thermald`"
                found=1
            fi
            if [ -n "`getprop init.svc.thermal_core`" ]; then
                echo "  Thermal MTK thermal_core: `getprop init.svc.thermal_core`"
                found=1
            fi
            if [ -n "`getprop init.svc.mi_thermald`" ]; then
                echo "  Thermal mi_thermald: `getprop init.svc.mi_thermald`"
                found=1
            elif [ -n "`getprop init.svc.vendor.mi_thermald`" ]; then
                echo "  Thermal mi_thermald: `getprop init.svc.vendor.mi_thermald`"
                found=1
            fi
            if [ -n "`getprop init.svc.thermal-engine`" ]; then
                echo "  Thermal thermal-engine: `getprop init.svc.thermal-engine`"
                found=1
            elif [ -n "`getprop init.svc.vendor.thermal-engine`" ]; then
                echo "  Thermal thermal-engine: `getprop init.svc.vendor.thermal-engine`"
                found=1
            fi

            # MPDecision
            if [ -n "`getprop init.svc.mpdecision`" ]; then
                echo "  Thermal MPDecision: `getprop init.svc.mpdecision`"
                found=1
            elif [ -n "`getprop init.svc.vendor.mpdecision`" ]; then
                echo "  Thermal MPDecision: `getprop init.svc.vendor.mpdecision`"
                found=1
            fi

            # MediaTek EAS+ scheduling
            if [ -r "/proc/cpufreq/cpufreq_sched_disable" ]; then
                set `cat /proc/cpufreq/cpufreq_sched_disable`
                val=$3
                if [ "$val" -eq '1' ]; then
                    echo "  Thermal MTK EAS+: stopped"
                else
                    echo "  Thermal MTK EAS+: running"
                fi
                found=1
            fi
            
            if [ $found -eq 0 ]; then
                echo "  Thermal control: N/A"
            fi
        # End of status print section
        fi
        
    else
        return 1
    fi
}

function reduceDozeJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"

        if [ $flag -gt 0 ]; then
            # Disable Doze of the device
            dumpsys deviceidle disable all 1>"/dev/null" 2>&1
        elif [ $flag -lt 0 ]; then
            # Enable Doze of the device
            dumpsys deviceidle enable all 1>"/dev/null" 2>&1
        fi
        
        if [ $printStatus -gt 0 ]; then
            if [ "`dumpsys deviceidle enabled all`" -gt 0 ]; then
                echo "  Doze battery saver: enabled"
            else
                echo "  Doze battery saver: disabled"
            fi
        fi
        
    else
        return 1
    fi
}

function getQcomGpuFreq()
{
    local isMax="0"
    
    if [ $# -eq 1  -a  "$1" = "max" ]; then
        isMax="1"
    fi
    
    if [ -r "/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies"  -a  -r "/sys/class/kgsl/kgsl-3d0/min_pwrlevel" ]; then
        local tab x y freq=""
        
        read tab <"/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies"
        if [ -z "$tab" ]; then
            return 1
        fi
        set $tab 1>"/dev/null" 2>&1
        
        if [ "$isMax" -eq 1 ]; then
            freq="$1"
        elif [ -r "/sys/class/kgsl/kgsl-3d0/default_pwrlevel" ]; then
            read x <"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
            read y <"/sys/class/kgsl/kgsl-3d0/default_pwrlevel"
            if [ "$y" -lt "$x" ]; then
                x="$y"
            fi
            if [ "$x" -lt $# ]; then
                shift $x
            fi
            freq="$1"
        else
            # no estimation possible, so check the current real GPU clock
            read freq <"/sys/class/kgsl/kgsl-3d0/gpuclk"
        fi
        
        if [ -n "$freq" ]; then
            echo "$freq"
            return 0
        else
            return 1
        fi
        
    else
        return 1
    fi
}

function getMtkGpuFreqKhz()
{
    local isMax="0"
    
    if [ $# -eq 1  -a  "$1" = "max" ]; then
        isMax="1"
    fi
    
    if [ -r "/proc/gpufreq/gpufreq_opp_dump" ]; then
        local x1 x2 x3 x4 x5 freq="" IFS=" ,"
        
        if [ "$isMax" -eq 1 ]; then
            read x1 x2 x3 x4 x5 <"/proc/gpufreq/gpufreq_opp_dump"
            freq="$x4"
        else
            while read x1 x2 x3 x4 x5; do
                freq="$x4"
            done <"/proc/gpufreq/gpufreq_opp_dump"
        fi
        
        if [ -n "$freq" ]; then
            echo "$freq"
            return 0
        else
            return 1
        fi
        
    elif [ -r "/proc/gpufreqv2/gpu_working_opp_table"  -a  "$isMax" -eq 1 ]; then
        local x1 x2 x3 x4 freq="" IFS=" ,"
        
        read x1 x2 x3 x4 <"/proc/gpufreqv2/gpu_working_opp_table"
        freq="$x3"
        
        if [ -n "$freq" ]; then
            echo "$freq"
            return 0
        else
            return 1
        fi
        
    elif [ -r "/proc/gpufreqv2/gpufreq_status" ]; then
        local x1 x2 x3 x4 x5 x6 x7 freq="" IFS=" ,"
       
       { 
            read
            read x1 x2 x3 x4 x5 x6
            freq="$x5"
            
            if [ -n "$freq" ]; then
                echo "$freq"
                return 0
            else
                return 1
            fi
        } <"/proc/gpufreqv2/gpufreq_status"
        return 0

    else
        return 1
    fi
}

function getTensorGpuFreqKhz()
{
    local isMax="0"
    
    if [ $# -eq 1  -a  "$1" = "max" ]; then
        isMax="1"
    elif [ $# -eq 1  -a  "$1" = "min" ]; then
        isMax="-1"
    fi
    
    if [ -r "/sys/devices/platform/1c500000.mali/available_frequencies" ]; then
        local tab x freq=""
        
        read tab <"/sys/devices/platform/1c500000.mali/available_frequencies"
        if [ -z "$tab" ]; then
            return 1
        fi
        set $tab 1>"/dev/null" 2>&1
        
        if [ "$isMax" -eq 1 ]; then
            freq="$1"
        elif [ "$isMax" -eq -1 ]; then
            freq="$(eval echo '$'{$#})"
        else
            # return the current GPU clock
            read freq <"/sys/devices/platform/1c500000.mali/cur_freq"
        fi
        
        if [ -n "$freq" ]; then
            echo "$freq"
            return 0
        else
            return 1
        fi
        
    else
        return 1
    fi
}

function isMtkGpuFreqFixed()
{
    if [ -r "/proc/gpufreq/gpufreq_opp_freq" ]; then
        local x1 x2 x3 x4 x5
        read x1 x2 x3 x4 x5 <"/proc/gpufreq/gpufreq_opp_freq"
        if [ "$x5" = "enabled" ]; then
            return 0
        else
            return 1
        fi
    elif [ -r "/proc/gpufreqv2/fix_target_opp_index" ]; then
        local x1 x2 x3 x4 x5 x6
        read x1 x2 x3 x4 x5 x6 <"/proc/gpufreqv2/fix_target_opp_index"
        if [ "$x6" = "disabled" ]; then
            return 1
        else
            return 0
        fi
    else
        return 1
    fi
}

function validGpuGovernor()
{
    if [ $# -eq 2  -a  -r "$1" ]; then
        local lst
        local gov="$2"
        local i
        lst="`cat <\"$1\"`"
        for i in $lst; do
            if [ "$i" = "$gov" ]; then
                return 0
            fi
        done
        return 1
    else
        return 1
    fi
}

function getGpuBusmonPath()
{
    local x
    
    if [ -e "/sys/class/devfreq/soc:qcom,kgsl-busmon" ]; then
        x="/sys/class/devfreq/soc:qcom,kgsl-busmon"
    elif [ -e "/sys/class/devfreq/kgsl-busmon" ]; then
        x="/sys/class/devfreq/kgsl-busmon"
     else
        x=""
     fi
     echo "$x"
     return 0
}

function reduceGovernorJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"
        local x

        if [ $flag -gt 0 ]; then
        
            # CPU governor
            # prevent CPU offline stuck by forcing online between double  governor writing 
            local i st en
            IFS="-" read st en <"/sys/devices/system/cpu/present"
            if [ -n "$st"  -a  -n "$en"  -a "$st" -ge 0  -a  "$en" -ge 0 ]; then
                for i in `seq $st $en`; do
                    if [ -e "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor" ]; then
                        chmod 644 "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor"
                        echo 'performance' >"/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor"
                        chmod 644 "/sys/devices/system/cpu/cpu$i/online"
                        echo '1' >"/sys/devices/system/cpu/cpu$i/online"
                        # Set the cpu max freq to the scaling_max_freq because some devices sometimes set it to be lower
                        read x <"/sys/devices/system/cpu/cpu$i/cpufreq/cpuinfo_max_freq"
                        chmod 644 "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_max_freq"
                        echo "$x" >"/sys/devices/system/cpu/cpu$i/cpufreq/scaling_max_freq"
                        echo 'performance' >"/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor"
                    fi
                done
            fi

            # Support for the Nyx kernel and others; Disable a workqueue power efficient featute
            if [ -e "/sys/module/workqueue/parameters/power_efficient" ]; then
                chmod 644 "/sys/module/workqueue/parameters/power_efficient"
                echo 'N' >"/sys/module/workqueue/parameters/power_efficient"
            fi

            # GPU's
            if [ -w "/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor" ]; then
                # For old Qcomm GPU's
                echo 'performance' >"/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor"
                if [ -w "/sys/class/kgsl/kgsl-3d0/min_pwrlevel" ]; then
                    # Set the min power level to be maximum
                    read x <"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                    if [ "$x" -ne 0 ]; then
                        echo "0" >"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                    fi
                fi
            elif [ -w "/sys/class/kgsl/kgsl-3d0/devfreq/governor" ]; then
                # For Qcomm GPU's
                if validGpuGovernor "/sys/class/kgsl/kgsl-3d0/devfreq/available_governors" "performance"; then
                    # Check whether "performance" governor exists or not because some Qcomm recent GPU's don't have the governor
                    echo 'performance' >"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                    sleep 0.1
                fi
                if [ -w "/sys/class/kgsl/kgsl-3d0/devfreq/min_freq" ]; then
                    # Set the min freq
                    read x <"/sys/class/kgsl/kgsl-3d0/devfreq/max_freq"
                    if [ "$x" -ne 0 ]; then
                        echo "$x" >"/sys/class/kgsl/kgsl-3d0/devfreq/min_freq"
                    fi
                fi
                if [ -w "/sys/class/kgsl/kgsl-3d0/min_pwrlevel" ]; then
                    # Set the min power level to be maximum
                    read x <"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                    if [ "$x" -ne 0 ]; then
                        echo "0" >"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                    fi
                fi
                if [ -w "/sys/class/kgsl/kgsl-3d0/default_pwrlevel" ]; then
                    # Set the default power level to be maximum
                    read x <"/sys/class/kgsl/kgsl-3d0/default_pwrlevel"
                    if [ "$x" -ne 0 ]; then
                        echo "0" >"/sys/class/kgsl/kgsl-3d0/default_pwrlevel"
                    fi
                fi
                # For some Qcomm GPU's, because they revert the governor after setting min_pwrlevel several times
                if validGpuGovernor "/sys/class/kgsl/kgsl-3d0/devfreq/available_governors" "performance"; then
                    for i in `seq 1 9`; do
                        x="`echo \"scale=1;${i}/10\" | bc`"
                        sleep $x
                        read x <"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                        if [ "$x" = "performance" ]; then
                            break
                        fi
                        echo 'performance' >"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                    done
                fi
                if [ -w "/sys/class/kgsl/kgsl-3d0/throttling" ]; then
                        echo "0" >"/sys/class/kgsl/kgsl-3d0/throttling"
                fi
                if [ -w "/sys/class/devfreq/soc:qcom,gpubw/min_freq" ]; then
                    # Set the min freq
                    read x <"/sys/class/devfreq/soc:qcom,gpubw/max_freq"
                    if [ "$x" -ne 0 ]; then
                        echo "$x" >"/sys/class/devfreq/soc:qcom,gpubw/min_freq"
                    fi
                fi
                local busmon="`getGpuBusmonPath`"
                if [ -w "${busmon}/min_freq" ]; then
                    # Set the min freq
                    read x <"${busmon}/max_freq"
                    if [ "$x" -ne 0 ]; then
                        echo "$x" >"${busmon}/min_freq"
                    fi
                    echo "performance" >"${busmon}/governor"
                fi
            elif [ -w "/proc/gpufreq/gpufreq_opp_freq" ]; then
                # Maximum fixed frequency setting for MediaTek GPU's
                local freq="`getMtkGpuFreqKhz \"max\"`"
                if [ -n "$freq" ]; then
                    echo "$freq" >"/proc/gpufreq/gpufreq_opp_freq"
                fi
            elif [ -w "/proc/gpufreqv2/fix_target_opp_index" ]; then
                # Maximum fixed frequency (index 0) setting for MediaTek GPU's
                echo "0" >"/proc/gpufreqv2/fix_target_opp_index"
            elif [ -w "/sys/devices/platform/1c500000.mali/hint_min_freq" ]; then
                # Maximum fixed frequency setting for Tensor GPU's
                # This makes audio quality poor really, so is avoided
                local freq="`getTensorGpuFreqKhz \"max\"`"
                if [ -n "$freq" ]; then
                    #echo "$freq" >"/sys/devices/platform/1c500000.mali/hint_min_freq"
                    :
                fi
            fi
            
        elif [ $flag -lt 0 ]; then

            # CPU's governor
            local gov="`searchDefaultCpuGovernor`"
            # prevent CPU offline stuck by forcing online between double  governor writing
            local i st en
            IFS="-" read st en <"/sys/devices/system/cpu/present"
            if [ -n "$st"  -a  -n "$en"  -a "$st" -ge 0  -a  "$en" -ge 0 ]; then
                for i in `seq $st $en`; do
                    if [ -e "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor" ]; then
                        chmod 644 "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor"
                        echo "$gov" >"/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor"
                        chmod 644 "/sys/devices/system/cpu/cpu$i/online"
                        echo '1' >"/sys/devices/system/cpu/cpu$i/online"
                        echo "$gov" >"/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor"
                    fi
                done
            fi
            
            # Support for the Nyx kernel and others; Revert a workqueue power efficient featute
            if [ -e "/sys/module/workqueue/parameters/power_efficient" ]; then
                chmod 644 "/sys/module/workqueue/parameters/power_efficient"
                echo 'Y' >"/sys/module/workqueue/parameters/power_efficient"
            fi

            # GPU's
            if [ -w "/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor" ]; then
                # Default GPU governor for old Qcomm GPU's
                if [ "`getprop ro.build.product`" = "jfltexx"  -a   "`getprop ro.system.build.version.release`" -ge "12" ]; then
                    echo 'performance' >"/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor"
                else
                    echo 'ondemand' >"/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor"
                fi
                if [ -r "/sys/class/kgsl/kgsl-3d0/num_pwrlevels"  -a  -w "/sys/class/kgsl/kgsl-3d0/min_pwrlevel" ]; then
                    # Set the min power level to be minimum
                    local x="4"
                    local tmp
                    read x <"/sys/class/kgsl/kgsl-3d0/num_pwrlevels"
                    x="`expr $x - 1`"
                    if [ -n "$x" ]; then
                        read tmp <"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                        if [ "$tmp" -ne "$x" ]; then
                            echo "$x" >"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                        fi
                    fi
                fi
            elif [ -w "/sys/class/kgsl/kgsl-3d0/devfreq/governor" ]; then
                local x
                # Default GPU governor for Qcomm GPU's
                echo 'msm-adreno-tz' >"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                sleep 0.1
                if [ -r "/sys/class/kgsl/kgsl-3d0/num_pwrlevels"  -a  -w "/sys/class/kgsl/kgsl-3d0/min_pwrlevel" ]; then
                    # Set the min power level to be minimum
                    x="6"
                    local tmp
                    read x <"/sys/class/kgsl/kgsl-3d0/num_pwrlevels"
                    x="`expr $x - 1`"
                    if [ -n "$x" ]; then
                        read tmp <"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                        if [ "$tmp" -ne "$x" ]; then
                            echo "$x" >"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                        fi
                    fi
                fi
                if [ -r "/sys/class/kgsl/kgsl-3d0/min_pwrlevel"  -a  -w "/sys/class/kgsl/kgsl-3d0/default_pwrlevel" ]; then
                    read x <"/sys/class/kgsl/kgsl-3d0/min_pwrlevel"
                    if [ -n "$x" ]; then
                        echo "$x" >"/sys/class/kgsl/kgsl-3d0/default_pwrlevel"
                    fi
                fi
                if [ -w "/sys/class/kgsl/kgsl-3d0/devfreq/min_freq" ]; then
                    # Set the min freq to the lowest
                    echo "0" >"/sys/class/kgsl/kgsl-3d0/devfreq/min_freq"
                fi

                # For some Qcomm GPU's, because they revert the governor after setting min_pwrlevel several times
                for i in `seq 1 9`; do
                    x="`echo \"scale=1;${i}/10\" | bc`"
                    sleep $x
                    read x <"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                    if [ "$x" = "msm-adreno-tz" ]; then
                        break
                    fi
                    echo 'msm-adreno-tz' >"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                done
                if [ -w "/sys/class/kgsl/kgsl-3d0/throttling" ]; then
                        echo "1" >"/sys/class/kgsl/kgsl-3d0/throttling"
                fi
                if [ -w "/sys/class/devfreq/soc:qcom,gpubw/min_freq" ]; then
                    echo "0" >"/sys/class/devfreq/soc:qcom,gpubw/min_freq"
                fi
                local busmon="`getGpuBusmonPath`"
                if [ -w "${busmon}/min_freq" ]; then
                    # Set the min freq
                    echo "0" >"${busmon}/min_freq"
                    echo "gpubw_mon" >"${busmon}/governor"
                fi
            elif [ -w "/proc/gpufreq/gpufreq_opp_freq" ]; then
                # Variable frequency setting for MediaTek GPU's
                echo '0' >"/proc/gpufreq/gpufreq_opp_freq"
            elif [ -w "/proc/gpufreqv2/fix_target_opp_index" ]; then
                # Variable frequency (index -1) setting for MediaTek GPU's
                echo "-1" >"/proc/gpufreqv2/fix_target_opp_index"
            elif [ -w "/sys/devices/platform/1c500000.mali/hint_min_freq" ]; then
                # Variable frequency setting for Tensor GPU's
                local freq="`getTensorGpuFreqKhz \"min\"`"
                if [ -n "$freq" ]; then
                    echo "$freq" >"/sys/devices/platform/1c500000.mali/hint_min_freq"
                fi
            fi
            
        fi
        
        if [ $printStatus -gt 0 ]; then
            #CPU Governor
            if [ -r "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor" ]; then
                # Support for the Nyx kernel and others; Print the status of a workqueue power efficient featute
                if [ -r "/sys/module/workqueue/parameters/power_efficient" ]; then
                    local pf
                    read pf <"/sys/module/workqueue/parameters/power_efficient"
                    if [ "$pf" = "Y" ]; then
                        pf="yes"
                    else
                        pf="no"
                    fi
                    echo "  Gov. CPU: `cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor` (wq psave: $pf)"
                else
                    echo "  Gov. CPU: `cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor`"
                fi
            fi
            
            if [ -r "/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor" ]; then
                # For old Qcomm GPU Governor
                local freq gov
                read gov <"/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor"
                if [ "$gov" = "performance" ]; then
                    freq="`getQcomGpuFreq \"max\"`"
                    freq="`expr $freq / 1000000`MHz"
                    echo "  Gov. GPU: performance (fixed: $freq)"
                else
                    freq="`getQcomGpuFreq \"typical\"`"
                    freq="`expr $freq / 1000000`Mhz"
                    echo "  Gov. GPU: $gov (typ.: $freq)"
                fi
            elif [ -w "/sys/class/kgsl/kgsl-3d0/devfreq/governor" ]; then
                # For Qcomm GPU Governor
                local freq gov def_pwrl
                read gov <"/sys/class/kgsl/kgsl-3d0/devfreq/governor"
                if [ -r "/sys/class/kgsl/kgsl-3d0/default_pwrlevel" ]; then
                    read def_pwrl <"/sys/class/kgsl/kgsl-3d0/default_pwrlevel"
                else
                    def_pwrl="1"
                fi
                if [ "$gov" = "performance"  -o  "$def_pwrl" -eq 0 ]; then
                    freq="`getQcomGpuFreq \"max\"`"
                    freq="`expr $freq / 1000000`MHz"
                    echo "  Gov. GPU: $gov (fixed: $freq)"
                else
                    freq="`getQcomGpuFreq \"typical\"`"
                    freq="`expr $freq / 1000000`MHz"
                    echo "  Gov. GPU: $gov (typ.: $freq)"
                fi
            elif [ -r "/proc/gpufreq/gpufreq_opp_freq"  -o  -r "/proc/gpufreqv2/gpu_working_opp_table" ]; then
                # For getting MediaTek GPU settings
                local freq
                if isMtkGpuFreqFixed; then
                    freq="`getMtkGpuFreqKhz \"max\"`"
                    freq="`expr $freq / 1000`MHz"
                    echo "  Gov. GPU: max freq (fixed: $freq)"
                else
                    freq="`getMtkGpuFreqKhz \"typical\"`"
                    freq="`expr $freq / 1000`MHz"
                    echo "  Gov. GPU: variable freq (typ.: $freq)"
                fi
            elif [ -r "/sys/devices/platform/1c500000.mali/cur_freq" ]; then
                # Get the current Tensor GPU frequency
                local freq="`getTensorGpuFreqKhz`"
                if [ "$freq" = "`getTensorGpuFreqKhz \"max\"`" ]; then
                    freq="`expr $freq / 1000`MHz"
                    echo "  Gov. GPU: max freq (fixed: $freq)"
                else
                    freq="`expr $freq / 1000`MHz"
                    echo "  Gov. GPU: variable freq (typ.: $freq)"
                fi
            fi
        fi
        
    else
        return 1
    fi
}

function reduceLogdJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"

        if [ $flag -gt 0 ]; then
        
            # Stop the Logd servers
            if [ "`getprop init.svc.logd`" = "running" ]; then
                setprop ctl.stop logd
            elif [ "`getprop init.svc.logd`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.logd`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.traced`" = "running" ]; then
                setprop ctl.stop traced
            elif [ "`getprop init.svc.traced`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.traced`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.traced_probes`" = "running" ]; then
                setprop ctl.stop traced_probes
            elif [ "`getprop init.svc.traced_probes`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.traced_probes`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            
        elif [ $flag -lt 0 ]; then
        
            # Start the Logd servers
            if [ "`getprop init.svc.traced_probes`" = "stopped" ]; then
                setprop ctl.start traced_probes
            elif [ "`getprop init.svc.traced_probes`" = "stopping" ]; then
                setprop ctl.restart traced_probes
            fi
            if [ "`getprop init.svc.traced`" = "stopped" ]; then
                setprop ctl.start traced
            elif [ "`getprop init.svc.traced`" = "stopping" ]; then
                setprop ctl.restart traced
            fi
            if [ "`getprop init.svc.logd`" = "stopped" ]; then
                setprop ctl.start logd
            elif [ "`getprop init.svc.logd`" = "stopping" ]; then
                setprop ctl.restart logd
            fi
            
        fi
        
        if [ $printStatus -gt 0 ]; then
            local val="`getprop init.svc.logd`"
            if [ -n  "$val" ]; then
                echo "  Logd main server: $val"
            fi
            val="`getprop init.svc.traced`"
            if [ -n  "$val" ]; then
                echo "  Logd traced server: $val"
            fi
            val="`getprop init.svc.traced_probes`"
            if [ -n  "$val" ]; then
                echo "  Logd traced_probes server: $val"
            fi
        fi
        
    else
        return 1
    fi
}

function reduceCameraJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"

        if [ $flag -gt 0 ]; then
        
            # Stop the camera servers
            if [ "`getprop init.svc.qcamerasvr`" = "running" ]; then
                setprop ctl.stop qcamerasvr
            elif [ "`getprop init.svc.qcamerasvr`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.qcamerasvr`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.vendor.qcamerasvr`" = "running" ]; then
                setprop ctl.stop vendor.qcamerasvr
            elif [ "`getprop init.svc.vendor.qcamerasvr`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.vendor.qcamerasvr`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.cameraserver`" = "running" ]; then
                setprop ctl.stop cameraserver
            elif [ "`getprop init.svc.cameraserver`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.cameraserver`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.camerasloganserver`" = "running" ]; then
                setprop ctl.stop camerasloganserver
            elif [ "`getprop init.svc.camerasloganserver`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.camerasloganserver`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            if [ "`getprop init.svc.camerahalserver`" = "running" ]; then
                setprop ctl.stop camerahalserver
            elif [ "`getprop init.svc.camerahalserver`" = "stopping" ]; then
                local pid="`getprop init.svc_debug_pid.camerahalserver`"
                if [ -n "$pid" ]; then
                    kill -HUP $pid 1>"/dev/null" 2>&1
                fi
            fi
            
        elif [ $flag -lt 0 ]; then
        
            # Start the camera servers
            if [ "`getprop init.svc.qcamerasvr`" = "stopped" ]; then
                setprop ctl.start qcamerasvr
            elif [ "`getprop init.svc.qcamerasvr`" = "stopping" ]; then
                setprop ctl.restart qcamerasvr
            fi
            if [ "`getprop init.svc.vendor.qcamerasvr`" = "stopped" ]; then
                setprop ctl.start vendor.qcamerasvr
            elif [ "`getprop init.svc.vendor.qcamerasvr`" = "stopping" ]; then
                setprop ctl.restart vendor.qcamerasvr
            fi
            if [ "`getprop init.svc.cameraserver`" = "stopped" ]; then
                setprop ctl.start cameraserver
            fi
            if [ "`getprop init.svc.camerasloganserver`" = "stopped" ]; then
                setprop ctl.start camerasloganserver
            fi
            if [ "`getprop init.svc.camerahalserver`" = "stopped" ]; then
                setprop ctl.start camerahalserver
            fi
            
        fi
        
        if [ $printStatus -gt 0 ]; then
            local val="`getprop init.svc.qcamerasvr`"
            if [ -n  "$val" ]; then
                echo "  Qcom camera server: $val"
                return 0
            fi
            val="`getprop init.svc.vendor.qcamerasvr`"
            if [ -n  "$val" ]; then
                echo "  Qcom camera server: $val"
                return 0
            fi
            val="`getprop init.svc.cameraserver`"
            if [ -n  "$val" ]; then
                echo "  Camera server: $val"
                return 0
            fi
        fi
        
    else
        return 1
    fi
}

# choose the best I/O scheduler for very Hifi audio outputs, and output it into the standard output
function chooseBestIOScheduler()
{
    if [ $# -eq 1  -a  -r "$1" ]; then
        local x scheds ret_val=""
  
        scheds="`tr -d '[]' <\"$1\"`"
        for x in $scheds; do
            case "$x" in
                "deadline" ) ret_val="deadline"; break ;;
                "mq-deadline" ) ret_val="mq-deadline"; break ;;
                "kyber" ) ret_val="kyber" ;;
                "cfq" ) if [ "$ret_val" != "kyber" ]; then ret_val="cfq"; fi ;;
                "noop" | "none" ) if [ "$ret_val" != "cfq"  -o  "$ret_val" != "kyber" ]; then ret_val="$x"; fi ;;
                * ) ;;
            esac
        done
        echo "$ret_val"
        return 0
    else
        return 1
    fi
}

function selectedScheduler()
{
    if [ $# -eq 1  -a  -r "$1" ]; then
        local sched="`cat \"$1\"`"
        if [ -n "$sched" ]; then
            local val
            val=`expr "$sched" : '[^[]*\[\([^]]*\)\]'`
            echo "$val"
            return 0
        else
            return 1
        fi
        
    else
        return 1
    fi
}

function validScheduler()
{
    if [ $# -eq 2  -a  -r "$1" ]; then
        local lst
        local sched="$2"
        local i
        lst="`tr -d '[]' <\"$1\"`"
        for i in $lst; do
            if [ "$i" = "$sched" ]; then
                return 0
            fi
        done
        return 1
    else
        return 1
    fi
}

function nth()
{
    if [ $# -eq 2  -a  -n "$1" ]; then
    
        if [ -n "$2"  -a  "$2" -gt 0 ]; then
        
            local v
            local i=1
            
            for v in $1; do
                if [ "$2" -eq "$i" ]; then
                    echo "$v"
                    return 0
                else
                    i="`expr $i + 1`"
                fi
            done
            return 1
            
        else
        
            retrun 1
            
        fi
        
    else
    
        return 1
        
    fi
}

function getSocModelName()
{
    local modelName="`getprop ro.board.platform`"
    case "$modelName" in
            sd* | msm* | exynos* | mt* | gs* )
                echo "$modelName"
                return 0
                ;;
            zuma* )
                echo "gs301"
                return 0
                ;;
            * )
                case "`getprop ro.boot.hardware`" in
                    qcom )
                        # High performance Qcomm SoC devices tend to have code names
                        # (not real SoC name, but compatible name in this library)
                        case "$modelName" in
                            "kona" | "kalama" | "shima" | "yupik" )
                                echo "sdm870"
                                ;;
                            "bengal" )
                                echo "sdm680"
                                ;;
                            "holi" )
                                echo "sdm680"
                                ;;
                            "pineapple" )
                                echo "sm8635"
                                ;;
                            * )
                                 if [ -r "/sys/devices/system/cpu/cpu7/core_ctl/enable" ]; then
                                    echo "sdm855"
                                 else
                                    echo "sdm845"
                                 fi
                                ;;
                        esac
                        return 0
                        ;;
                    * )
                        echo "unknown"
                        return 0
                        ;;
                esac
                ;;
    esac
    
    return 1
}

function adjustForSoC()
{
    if [ $# -eq 1  -a  -n "$1"  -a  "$1" -ge 0 ]; then
        case "`getSocModelName`" in
            sdm* | msm* | sd* | exynos* )
                echo "`expr  '(' $1 / 10 ')' '*' 10 + '(' '(' $1 % 10 ')' / 3 ')' '*' 3`"
                ;;
            mt6* )
                echo "`expr '(' '(' $1 + 1 ')' / 4 ')' '*' 4`"
                ;;
            * )
                echo "$1"
                ;;
        esac
        return 0
        
    else
        return 1
        
    fi
}

function adjustForSoC_mq()
{
    if [ $# -eq 1  -a  -n "$1"  -a  "$1" -ge 0 ]; then
        local kername="`uname -r`"
        kername=${kername#*-}

        case  "$kername" in
            perf* | android* )
                # Round to multiples of 4; for Xiaomi Bengal and Google kernels
                echo "`expr  '(' '(' $1 + 2 ')' / 4 ')' '*' 4`"
                return 0
                ;;
            SouthWest* | Nyx* )
                # for Nyx and SouthWest kernels (100Hz)
                if [ "$1" -ge 250 ]; then
                    # Round off (<7) and up (>=7)
                    echo "`expr  '(' '(' $1 + 3 ')' / 10 ')' '*' 10`"
                else
                    # Round down
                    echo "`expr  '(' '(' $1 + 0 ')' / 10 ')' '*' 10`"
                fi
                return 0
                ;;
            * )
               if [ "`getprop ro.build.product`" = "clover"  -a  "`getprop ro.build.version.release`" -ge "14" ]; then
                    # Not Round for A14 and later (1000Hz kernels)
                    echo "$1"
                else
                    adjustForSoC "$1"
                fi
                 return 0
                ;;
        esac
        return 0
        
    else
        return 1
        
    fi
}

function adjustSchedulerParameter()
{
    if [ $# -eq 3 ]; then
        
        if [ "$1" = "deadline"  -a  -n "$2"  -a  -n "$3" ]; then
            case "$2" in
                "read_expire" )
                    echo "`adjustForSoC \"$3\"`"
                    ;;
                "write_expire" )
                    echo "`adjustForSoC \"$3\"`"
                    ;;
                * )
                    echo "$3"
                    ;;
            esac
        elif [ "$1" = "mq-deadline"  -a  -n "$2"  -a  -n "$3" ]; then
            case "$2" in
                "read_expire" )
                    echo "`adjustForSoC_mq \"$3\"`"
                    ;;
                "write_expire" )
                    echo "`adjustForSoC_mq \"$3\"`"
                    ;;
                * )
                    echo "$3"
                    ;;
            esac
        else
            echo "$3"
        fi
        return 0
        
    else
        
        return 1
        
    fi
}

function getSchedulerParams()
{
    if [ $# -eq 1 ]; then
        case "$1" in
            "deadline" | "mq-deadline" )
                echo "fifo_batch front_merges read_expire write_expire writes_starved"
                ;;
            "cfq" )
                echo "back_seek_penalty fifo_expire_async fifo_expire_sync group_idle low_latency quantum slice_async slice_async_rq \
                    slice_async_us slice_idle slice_sync target_latency"
                ;;
            "kyber" )
                echo "read_lat_nsec write_lat_nsec"
                ;;
            "noop" | "none" | * )
                echo ""
                ;;
        esac
        return 0
    else
        return 1
    fi
}

function getSchedulerValues()
{
    if [ $# -eq 2 ]; then
        case "$1" in
            "deadline" | "mq-deadline" )
                #   fifo_batch front_merges read_expire write_expire writes_starved
                case "$2" in
                    "light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm8[5-9]* | sdm9* | gs* )
                                echo "71 0 28 496 0"
                                ;;
                            sdm8* )
                                echo "73 0 24 484 0"
                                ;;
                            * )
                                echo "64 0 32 504 0"
                                ;;
                        esac
                        ;;
                    "m-light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm8[5-9]* | sdm9* | gs* )
                                echo "92 0 36 516 0"
                                ;;
                            sdm8* )
                                echo "92 0 36 516 0"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "92 0 36 516 0"
                                ;;
                            mt68* )
                                echo "92 0 36 516 0"
                                ;;
                            mt67[7-9]? )
                                echo "92 0 36 516 0"
                                ;;
                            * )
                                echo "92 0 36 516 0"
                                ;;
                        esac
                        ;;
                    "boost" )
                        case "`getSocModelName`" in
                            sm[6-8]* )
                                echo "139 0 36 516 0"
                                ;;
                            sdm8[5-9]* | sdm9* )
                                echo "145 0 36 516 0"
                                ;;
                            gs* )
                                echo "145 0 36 516 0"
                                ;;
                            sdm8* )
                                echo "133 0 36 516 0"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "133 0 38 517 0"
                                ;;
                            mt68* )
                                echo "149 0 36 516 0"
                                ;;
                            mt67[7-9]? )
                                echo "139 0 36 516 0"
                                ;;
                            * )
                                echo "139 0 36 516 0"
                                ;;
                        esac
                        ;;
                    "medium" | *)
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm8[5-9]* | sdm9* )
                                echo "127 0 36 516 0"
                                ;;
                            gs* )
                                echo "127 0 36 516 0"
                                ;;
                            sdm8* )
                                echo "127 0 36 516 0"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "127 0 38 517 0"
                                ;;
                            mt68* )
                                echo "127 0 36 516 0"
                                ;;
                            mt67[7-9]? )
                                echo "127 0 36 516 0"
                                ;;
                            * )
                                echo "127 0 36 516 0"
                                ;;
                        esac
                        ;;
                esac
                ;;
                
            "cfq" )
                #   back_seek_penalty fifo_expire_async fifo_expire_sync group_idle low_latency quantum slice_async slice_async_rq
                #       slice_async_us slice_idle slice_sync target_latency
                case "$2" in
                    "light" )
                        echo "1 3 3 0 1 1 3 46 3000 0 3 3"
                        ;;
                    "m-light" )
                        echo "1 3 3 0 1 1 3 51 3000 0 3 3"
                        ;;
                    "boost" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | mt68* | gs* | sd* | exynos* )
                                echo "1 1 1 0 1 1 0 77 877 0 1 1"
                                ;;
                            * )
                                echo "1 3 3 0 1 1 3 59 3000 0 3 3"
                                ;;
                        esac
                        ;;
                    "medium" | * )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | mt68* | gs* | sd* | exynos* )
                                echo "1 1 1 0 1 1 0 77 877 0 1 1"
                                ;;
                            * )
                                echo "1 3 3 0 1 1 3 59 3000 0 3 3"
                                ;;
                        esac
                        ;;
                esac
                ;;
                
            "kyber" )
                #  read_lat_nsec write_lat_nsec
                echo "1000001 1000001"
                ;;
                
            "noop" | "none" | * )
                echo ""
                ;;
                
        esac
        return 0
    else
        return 1
    fi
}

function getSchedulerNrRequests()
{
    if [ $# -eq 2 ]; then
        
        case "$1" in
            "mq-deadline" | "kyber" | "bfq" )
                case "`getSocModelName`" in
                    sm[6-8]* )
                        echo "2031"
                        ;;
                    gs* )
                        echo "2031"
                        ;;
                    mt68* )
                        echo "2031"
                        ;;
                    * )
                        echo "2031"
                        ;;
                esac
                ;;
                
            "none" )
                echo "31"
                ;;
                
            "deadline" )
                case "$2" in
                    "light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm8[5-9]* | sdm9* | gs* )
                                echo "80645"
                                ;;
                            sdm8* )
                                echo "80000"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "81660"
                                ;;
                            * )
                                echo "78550"
                                ;;
                        esac
                        ;;
                    "m-light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm8[5-9]* | sdm9* | gs* )
                                echo "86170"
                                ;;
                            sdm8* )
                                echo "86164"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "86170"
                                ;;
                            mt68* )
                                echo "86174"
                                ;;
                            mt67[6-9]? )
                                echo "86172"
                                ;;
                            * )
                                echo "86172"
                                ;;
                        esac
                        ;;
                    "boost" )
                        case "`getSocModelName`" in
                            sm[6-8]* )
                                echo "86181"
                                ;;
                            sdm8[5-9]* | sdm9* )
                                echo "86179"
                                ;;
                            gs* )
                                echo "86181"
                                ;;
                            sdm8* )
                                echo "86193"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "86193"
                                ;;
                            mt68* )
                                echo "86181"
                                ;;
                            mt67[7-9]? )
                                echo "86181"
                                ;;
                            * )
                                echo "86181"
                                ;;
                        esac
                        ;;
                    "medium" | * )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm8[5-9]* | sdm9* | gs* )
                                echo "86179"
                                ;;
                            sdm8* )
                                echo "86179"
                                ;;
                            sdm* | msm* | sd* | exynos* )
                                echo "86179"
                                ;;
                            mt68* )
                                echo "86179"
                                ;;
                            mt67[6-9]? )
                                echo "86179"
                                ;;
                            * )
                                echo "86179"
                                ;;
                        esac
                        ;;
                esac
                ;;
                
            "cfq" )
                case "$2" in
                    "light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86021"
                                ;;
                            * )
                                echo "86021"
                                ;;
                        esac
                        ;;
                    "m-light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86164"
                                ;;
                            * )
                                echo "86164"
                                ;;
                        esac
                        ;;
                    "boost" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86172"
                                ;;
                            * )
                                echo "86172"
                                ;;
                        esac
                        ;;
                    "medium" | * )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86172"
                                ;;
                            * )
                                echo "86172"
                                ;;
                        esac
                        ;;
                esac
                ;;
            
            "noop" | * )
                case "$2" in
                    "light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "80645"
                                ;;
                            * )
                                echo "80645"
                                ;;
                        esac
                        ;;
                    "m-light" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86164"
                                ;;
                            * )
                                echo "86164"
                                ;;
                        esac
                        ;;
                    "boost" )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86172"
                                ;;
                            * )
                                echo "86172"
                                ;;
                        esac
                        ;;
                    "medium" | * )
                        case "`getSocModelName`" in
                            sm[6-8]* | sdm* | msm* | sd* | exynos* | gs* )
                                echo "86172"
                                ;;
                            * )
                                echo "86172"
                                ;;
                        esac
                        ;;
                esac
               ;;
                
        esac
        return 0
    else
        return 1
    fi
}

function reduceIoJitter() 
{
    if [ $# -eq 4 ]; then
        local flag="$1"
        local ioScheduler="$2"
        local toneMode="$3"
        local printStatus="$4"

        if [ $flag -gt 0 ]; then
        
            local sched params vals nr_requests
            local i p v j
            for i in sda mmcblk0 mmcblk1; do
                if [ -d "/sys/block/$i/queue" ]; then
                    if [ -z "$ioScheduler"  -o  "$ioScheduler" = "*" ]; then
                        sched="`chooseBestIOScheduler \"/sys/block/$i/queue/scheduler\"`"
                    else
                        sched="$ioScheduler"
                    fi
                    if validScheduler "/sys/block/$i/queue/scheduler" "$sched"; then
                        
                        params="`getSchedulerParams \"$sched\"`"
                        vals="`getSchedulerValues \"$sched\" \"$toneMode\"`"
                        nr_requests="`getSchedulerNrRequests \"$sched\" \"$toneMode\"`"
                        echo "$sched" >"/sys/block/$i/queue/scheduler"
                        echo '17000' >"/sys/block/$i/queue/read_ahead_kb"
                        echo '0' >"/sys/block/$i/queue/iostats"
                        echo '0' >"/sys/block/$i/queue/add_random"
                        echo '2' >"/sys/block/$i/queue/rq_affinity"
                        echo '2' >"/sys/block/$i/queue/nomerges"
                        echo "$nr_requests" >"/sys/block/$i/queue/nr_requests"
                        # waiting for kenel tunables syncing
                        sleep 0.05
                        read v <"/sys/block/$i/queue/nr_requests"
                        if [ "$nr_requests" -ne "$v" ]; then
                            # If exceeding its max value, then use a safe kenel value (for multi-queue schedulers) within 2048 (except its "none" scheduler)
                            if [ "$sched" = "none" ]; then
                                echo "31" >"/sys/block/$i/queue/nr_requests"
                            else
                                echo "2031" >"/sys/block/$i/queue/nr_requests"
                            fi
                        fi
                        
                        # For 5.10 or later Kernels
                        if [ "$sched" = "mq-deadline" ]; then
                            if [ -w "/sys/block/$i/queue/iosched/async_depth" ]; then
                                case "`getSocModelName`" in
                                    sm[6-8]* )
                                        echo '30' >"/sys/block/$i/queue/iosched/async_depth"
                                        ;;
                                    gs* )
                                        echo '30' >"/sys/block/$i/queue/iosched/async_depth"
                                        ;;
                                    mt68* )
                                        echo '30' >"/sys/block/$i/queue/iosched/async_depth"
                                        ;;
                                    * )
                                        echo '30' >"/sys/block/$i/queue/iosched/async_depth"
                                        ;;
                                esac
                            fi
                            if [ -w "/sys/block/$i/queue/iosched/prio_aging_expire" ]; then
                                case "`getSocModelName`" in
                                    sm[6-8]* )
                                        echo '6903164' >"/sys/block/$i/queue/iosched/prio_aging_expire"
                                        ;;
                                    gs* )
                                        echo '6903164' >"/sys/block/$i/queue/iosched/prio_aging_expire"
                                        ;;
                                    * )
                                        echo '6903152' >"/sys/block/$i/queue/iosched/prio_aging_expire"
                                        ;;
                                esac
                            elif [ -w "/sys/block/$i/queue/iosched/aging_expire" ]; then
                                # for MTK Dimensity
                                echo '6903164' >"/sys/block/$i/queue/iosched/aging_expire"
                            fi
                        fi
                        
                        j=1
                        for p in $params; do
                            v="`nth \"$vals\" \"$j\"`"
                            v="`adjustSchedulerParameter \"$sched\" \"$p\" \"$v\"`"
                            if [ -w "/sys/block/$i/queue/iosched/$p"  -a  -n "$v"  -a  "$v" -ge 0 ]; then
                                echo "$v" >"/sys/block/$i/queue/iosched/$p"
                            fi
                            j="`expr $j + 1`"
                        done
                        
                    else
                        
                        local sched_lst="`tr -d '[]'  <\"/sys/block/$i/queue/scheduler\"`"
                        echo "Warning: ignoring wrong I/O scheduler (\"$sched\") settings for block device \"/dev/$i\"." 1>&2
                        echo "  available I/O schedulers: $sched_lst" 1>&2
                        
                    fi
                fi
            done
            
        elif [ $flag -lt 0 ]; then
        
            for i in sda mmcblk0 mmcblk1; do
                if [ -d "/sys/block/$i/queue" ]; then
                    if validScheduler "/sys/block/$i/queue/scheduler" "noop"; then
                        echo 'noop' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "none"; then
                        echo 'none' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    fi
                    
                    local kerVersion="`uname -r`"
                    kerVersion=${kerVersion%%.*}
                    if [ "`getprop ro.build.product`" = "jfltexx" ] && validScheduler "/sys/block/$i/queue/scheduler" "deadline"; then
                        echo 'deadline' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif [ "$kerVersion" -ge 6 ] && validScheduler "/sys/block/$i/queue/scheduler" "mq-deadline"; then
                        echo 'mq-deadline' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "ssg"; then
                        echo 'ssg' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif [ "`getprop ro.soc.manufacturer`" = "Mediatek"  -a  "$kerVersion" -eq 5 ] \
                          && validScheduler "/sys/block/$i/queue/scheduler" "mq-deadline"; then
                        echo 'mq-deadline' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "cfq"; then
                        echo 'cfq' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "bfq"; then
                        echo 'bfq' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "mq-deadline"; then
                        echo 'mq-deadline' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "kyber"; then
                        echo 'kyber' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    elif validScheduler "/sys/block/$i/queue/scheduler" "deadline"; then
                        echo 'deadline' >"/sys/block/$i/queue/scheduler"
                        sleep 0.05
                    fi
                    
                    echo '1' >"/sys/block/$i/queue/iostats"
                    echo '0' >"/sys/block/$i/queue/add_random"
                    echo '1' >"/sys/block/$i/queue/rq_affinity"
                    echo '0' >"/sys/block/$i/queue/nomerges"
                    
                    case "`getSocModelName`" in
                        sm[6-8]* | sdm8[5-9]* | sdm9* | sdm66* )
                            echo '512' >"/sys/block/$i/queue/read_ahead_kb"
                            echo '128' >"/sys/block/$i/queue/nr_requests"
                            ;;
                        gs* )
                            echo '128' >"/sys/block/$i/queue/read_ahead_kb"
                            echo '64' >"/sys/block/$i/queue/nr_requests"
                            ;;
                        * )
                            if [ "`getprop ro.build.product`" = "jfltexx"  -a   "`getprop ro.system.build.version.release`" -ge "12" ]; then
                                echo '512' >"/sys/block/$i/queue/read_ahead_kb"
                            else
                                echo '128' >"/sys/block/$i/queue/read_ahead_kb"
                            fi
                            
                            echo '128' >"/sys/block/$i/queue/nr_requests"
                            ;;
                    esac
                fi
            done
            
        fi
        
        if [ $printStatus -gt 0 ]; then
            local i j val lst
            for i in sda mmcblk0 mmcblk1; do
                if [ -d "/sys/block/$i/queue" ]; then
                    val="`selectedScheduler \"/sys/block/$i/queue/scheduler\"`"
                    echo "  I/O scheduler: $val"
                    lst="`ls \"/sys/block/$i/queue/iosched/\"*`" 2>"/dev/null"
                    if [ -n "$lst" ]; then
                        echo "    {"
                        for j in $lst; do
                            val="`cat \"$j\"`"
                            echo "      ${j##*/}: $val"
                        done
                        echo "    }"
                    fi
                    val="`cat \"/sys/block/$i/queue/read_ahead_kb\"`"
                    echo "  I/O read ahead size: $val KB"
                    val="`cat \"/sys/block/$i/queue/iostats\"`"
                    echo "  I/O iostat: $val"
                    val="`cat \"/sys/block/$i/queue/rq_affinity\"`"
                    echo "  I/O rq affinity: $val"
                    val="`cat \"/sys/block/$i/queue/nomerges\"`"
                    echo "  I/O nomerges: $val"
                    val="`cat \"/sys/block/$i/queue/nr_requests\"`"
                    echo "  I/O nr requests: $val"
                    break
                fi
            done
        fi
        
    else
        return 1
    fi
}

function reduceVmJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"

        if [ $flag -gt 0 ]; then
        
            if [ -w "/proc/sys/vm/swappiness" ]; then
                echo '0' >"/proc/sys/vm/swappiness"
            fi
            if [ -w "/proc/sys/vm/direct_swappiness" ]; then
                echo '0' >"/proc/sys/vm/direct_swappiness"
            fi
            if [ -w "/proc/sys/vm/dirty_ratio" ]; then
                echo '100' >"/proc/sys/vm/dirty_ratio"
            fi
            if [ -w "/proc/sys/vm/dirty_background_ratio" ]; then
                echo '100' >"/proc/sys/vm/dirty_background_ratio"
            elif [ -w "/proc/sys/vm/dirty_background_ratio_nosys" ]; then
                echo '100' >"/proc/sys/vm/dirty_background_ratio_nosys"
            fi
            if [ -w "/proc/sys/vm/dirty_expire_centisecs" ]; then
                echo '1201001' >"/proc/sys/vm/dirty_expire_centisecs"
            elif [ -w "/proc/sys/vm/dirty_expire_centisecs_nosys" ]; then
                echo '1201001' >"/proc/sys/vm/dirty_expire_centisecs_nosys"
            fi
            echo '221001' >"/proc/sys/vm/dirty_writeback_centisecs"
            echo '1' >"/proc/sys/vm/laptop_mode"
            if [ -w "/proc/sys/vm/swap_ratio" ]; then
                echo '0' >"/proc/sys/vm/swap_ratio"
            fi
            if [ -w "/proc/sys/vm/swap_ratio_enable" ]; then
                echo '1' >"/proc/sys/vm/swap_ratio_enable"
            fi
            
        elif [ $flag -lt 0 ]; then
        
            if [ -w "/proc/sys/vm/swappiness" ]; then
                echo '60' >"/proc/sys/vm/swappiness"
            fi
            if [ -w "/proc/sys/vm/direct_swappiness" ]; then
                echo '60' >"/proc/sys/vm/direct_swappiness"
            fi
            if [ -w "/proc/sys/vm/dirty_ratio" ]; then
                echo '20' >"/proc/sys/vm/dirty_ratio"
            fi
            if [ -w "/proc/sys/vm/dirty_background_ratio" ]; then
                echo '10' >"/proc/sys/vm/dirty_background_ratio"
            elif [ -w "/proc/sys/vm/dirty_background_ratio_nosys" ]; then
                echo '10' >"/proc/sys/vm/dirty_background_ratio_nosys"
            fi
            if [ -w "/proc/sys/vm/dirty_expire_centisecs" ]; then
                echo '200' >"/proc/sys/vm/dirty_expire_centisecs"
                echo '500' >"/proc/sys/vm/dirty_writeback_centisecs"
            elif [ -w "/proc/sys/vm/dirty_expire_centisecs_nosys" ]; then
                echo '3000' >"/proc/sys/vm/dirty_expire_centisecs_nosys"
                echo '0' >"/proc/sys/vm/dirty_writeback_centisecs"
            fi
            echo '0' >"/proc/sys/vm/laptop_mode"
            if [ -w "/proc/sys/vm/swap_ratio" ]; then
                echo '100' >"/proc/sys/vm/swap_ratio"
            fi
            if [ -w "/proc/sys/vm/swap_ratio_enable" ]; then
                echo '0' >"/proc/sys/vm/swap_ratio_enable"
            fi
            
        fi
        
        if [ $printStatus -gt 0 ]; then
            # I don't know the reason, but "read val <'/proc/sys/vm/swappiness'", etc. cannot get its whole value (only first one character)
            local val
            if [ -r "/proc/sys/vm/swappiness" ]; then
                val="`cat /proc/sys/vm/swappiness`"
                if [ -n "$val" ]; then
                    echo "  VM swappiness: $val"
                fi
            fi
            if [ -r "/proc/sys/vm/direct_swappiness" ]; then
                val="`cat /proc/sys/vm/direct_swappiness`"
                if [ -n "$val" ]; then
                    echo "  VM direct_swappiness: $val"
                fi
            fi
            if [ -r "/proc/sys/vm/dirty_ratio" ]; then
                val="`cat /proc/sys/vm/dirty_ratio`"
                if [ -n "$val" ]; then
                    echo "  VM dirty ratio: $val"
                fi
            fi
            if [ -r "/proc/sys/vm/dirty_background_ratio" ]; then
                val="`cat /proc/sys/vm/dirty_background_ratio`"
                if [ -n "$val" ]; then
                    echo "  VM dirty background ratio: $val"
                fi
            elif [ -r "/proc/sys/vm/dirty_background_ratio_nosys" ]; then
                val="`cat /proc/sys/vm/dirty_background_ratio_nosys`"
                if [ -n "$val" ]; then
                    echo "  VM dirty background ratio (nosys): $val"
                fi
            fi
            if [ -r "/proc/sys/vm/dirty_expire_centisecs" ]; then
                val="`cat /proc/sys/vm/dirty_expire_centisecs`"
                if [ -n "$val" ]; then
                    echo "  VM dirty expire centisecs: $val"
                fi
            elif [ -r "/proc/sys/vm/dirty_expire_centisecs_nosys" ]; then
                val="`cat /proc/sys/vm/dirty_expire_centisecs_nosys`"
                if [ -n "$val" ]; then
                    echo "  VM dirty expire centisecs (nosys): $val"
                fi
            fi
            val="`cat /proc/sys/vm/dirty_writeback_centisecs`"
            if [ -n "$val" ]; then
                echo "  VM dirty writeback centisecs: $val"
            fi
            val="`cat /proc/sys/vm/laptop_mode`"
            if [ "$val" = "1" ]; then
                echo "  VM laptop mode: on"
            else
                echo "  VM laptop mode: off"
            fi
            if [ -r "/proc/sys/vm/swap_ratio" ]; then
                val="`cat /proc/sys/vm/swap_ratio`"
                if [ -n "$val" ]; then
                    echo "  VM swap_ratio: $val"
                fi
            fi
            if [ -r "/proc/sys/vm/swap_ratio_enable" ]; then
                val="`cat /proc/sys/vm/swap_ratio_enable`"
                if [ -n "$val" ]; then
                    echo "  VM swap_ratio_enable: $val"
                fi
            fi
            # End of print status
        fi
        
    else
        return 1
    fi
}

function reloadAudioserver()
{
    # wait for system boot completion and audiosever boot up
    local i
    for i in `seq 1 3` ; do
        if [ "`getprop sys.boot_completed`" = "1"  -a  -n "`getprop init.svc.audioserver`" ]; then
            break
        fi
        sleep 0.9
    done

    if [ -n "`getprop init.svc.audioserver`" ]; then

        setprop ctl.restart audioserver
        sleep 0.2
        if [ "`getprop init.svc.audioserver`" != "running" ]; then
            # workaround for Android 12 old devices hanging up the audioserver after "setprop ctl.restart audioserver" is executed
            local pid="`getprop init.svc_debug_pid.audioserver`"
            if [ -n "$pid" ]; then
                kill -HUP $pid 1>"/dev/null" 2>&1
            fi
            for i in `seq 1 10` ; do
                sleep 0.2
                if [ "`getprop init.svc.audioserver`" = "running" ]; then
                    break
                elif [ $i -eq 10 ]; then
                    echo "audioserver reload failed!" 1>&2
                    return 1
                fi
            done
        fi
        return 0
        
    else
        echo "audioserver is not found!" 1>&2 
        return 1
    fi
}

function which_resetprop_command()
{
    type resetprop 1>"/dev/null" 2>&1
    if [ $? -eq 0 ]; then
        echo "resetprop"
    else
        type resetprop_phh 1>"/dev/null" 2>&1
        if [ $? -eq 0 ]; then
            echo "resetprop_phh"
        else
            return 1
        fi
    fi
    return 0
}

function reduceEffectJitter()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"
        local val

        if [ $flag -gt 0 ]; then
            resetprop_command="`which_resetprop_command`"
            if [ -n "$resetprop_command" ]; then
                # Workaround for recent Pixel Firmwares (not to reboot when resetprop'ing)
                "$resetprop_command" --delete ro.audio.ignore_effects 1>"/dev/null" 2>&1
                # End of workaround
                
                "$resetprop_command" ro.audio.ignore_effects true
                # support for Tensor devices, etc.
                val="`getprop ro.audio.spatializer_enabled`"
                if [ -n "$val"  -a  "$val" = "true" ]; then
                    # Workaround for recent Pixel Firmwares (not to reboot when resetprop'ing)
                    "$resetprop_command" --delete ro.audio.spatializer_enabled 1>"/dev/null" 2>&1
                    # End of workaround
                    
                    "$resetprop_command" ro.audio.spatializer_enabled false
                fi
                # Stop Tensor device's AOC daemon for reducing significant jitter
                if [ "`getprop init.svc.aocd`" = "running" ]; then
                    setprop ctl.stop aocd
                fi
                # Stop Tensor device's AOCX daemon for reducing significant jitter
                if [ "`getprop init.svc.aocxd`" = "running" ]; then
                    setprop ctl.stop aocxd
                fi
                reloadAudioserver
            else
                return 2
            fi
        elif [ $flag -lt 0 ]; then
            resetprop_command="`which_resetprop_command`"
            if [ -n "$resetprop_command" ]; then
                "$resetprop_command" --delete ro.audio.ignore_effects
                # support for Tensor devices, etc.
                val="`getprop ro.audio.spatializer_enabled`"
                if [ -n "$val"  -a  "$val" = "false" ]; then
                    # Workaround for recent Pixel Firmwares (not to reboot when resetprop'ing)
                    "$resetprop_command" --delete ro.audio.spatializer_enabled 1>"/dev/null" 2>&1
                    # End of workaround
                    
                    "$resetprop_command" ro.audio.spatializer_enabled true
                fi
                if [ "`getprop init.svc.aocd`" = "stopped" ]; then
                    setprop ctl.start aocd
                fi
                if [ "`getprop init.svc.aocxd`" = "stopped" ]; then
                    setprop ctl.start aocxd
                fi
                reloadAudioserver
            else
                return 2
            fi
        fi
        
        if [ $printStatus -gt 0 ]; then
            val="`getprop ro.audio.ignore_effects`"
            if [ -n "$val"  -a  "$val" = "true" ]; then
                echo "  Effects framework: disabled"
            else
                echo "  Effects framework: enabled"
            fi
            
            val="`getprop init.svc.aocd`"
            if [ -n "$val"  ]; then
                echo "  Effects AOC server: $val"
            fi
            val="`getprop init.svc.aocxd`"
            if [ -n "$val"  ]; then
                echo "  Effects AOCX server: $val"
            fi
            
        fi
        
        return 0
        
    else
        return 1
    fi
}

function restartWifi()
{
    local val="`settings get global wifi_on`"
    
    if [ -n "$val"  -a  "$val" != "0" ]; then
        svc wifi disable
        svc wifi enable
    fi
}

function reduceWifiJitter ()
{
    if [ $# -eq 3 ]; then
        local flag="$1"
        local restartFlag="$2"
        local printStatus="$3"

        if [ $flag -gt 0 ]; then
        
            # Reducing wifi jitter by suspend wifi optimizations
            settings put global wifi_suspend_optimizations_enabled 0 1>"/dev/null" 2>&1
            settings put secure adaptive_connectivity_enabled 0 1>"/dev/null" 2>&1
            if [ "$restartFlag" = "Restart" ]; then
                restartWifi
            fi
            
        elif [ $flag -lt 0 ]; then
        
            # Revert wifi jitter by suspend wifi optimizations
            settings delete global wifi_suspend_optimizations_enabled 1>"/dev/null" 2>&1
            settings delete secure adaptive_connectivity_enabled 1>"/dev/null" 2>&1
            if [ "$restartFlag" = "Restart" ]; then
                restartWifi
            fi
        
        fi
        
        if [ $printStatus -gt 0 ]; then
            local val="`settings get global wifi_suspend_optimizations_enabled`"
            if [ -n "$val"  -a  "$val" = "0" ]; then
                echo "  Wifi suspend optimizations: disabled"
            else
                echo "  Wifi suspend optimizations: enabled"
            fi
            val="`settings get secure adaptive_connectivity_enabled`"
            if [ -n "$val"  -a  "$val" = "0" ]; then
                echo "  Wifi adaptive connectivity: disabled"
            else
                echo "  Wifi adaptive connectivity: enabled"
            fi
        fi

    else
        return 1
    fi
}

function reduceBatteryJitter ()
{
    if [ $# -eq 2 ]; then
        local flag="$1"
        local printStatus="$2"

        if [ $flag -gt 0 ]; then
        
            # Reducing battery jitters
            settings put global adaptive_battery_management_enabled 0 1>"/dev/null" 2>&1
            settings put secure adaptive_charging_enabled 0 1>"/dev/null" 2>&1
            
        elif [ $flag -lt 0 ]; then
        
            # Revert battery jitters
            settings delete global adaptive_battery_management_enabled 1>"/dev/null" 2>&1
            settings delete secure adaptive_charging_enabled 1>"/dev/null" 2>&1
        
        fi
        
        if [ $printStatus -gt 0 ]; then
            local val="`settings get global adaptive_battery_management_enabled`"
            if [ -n "$val"  -a  "$val" = "0" ]; then
                echo "  Battery adaptive management: disabled"
            else
                echo "  Battery adaptive management: enabled"
            fi
            val="`settings get secure adaptive_charging_enabled`"
            if [ -n "$val"  -a  "$val" = "0" ]; then
                echo "  Battery adaptive charging: disabled"
            else
                echo "  Battery adaptive charging: enabled"
            fi
        fi

    else
        return 1
    fi
}


================================================
FILE: module.prop
================================================
id=hifi-maximizer-mod
name=Hifi Maximizer
version=v2.5.16
versionCode=2516
author=zyhk
description=A module for maximizing the digital audio fidelity by reducing jitters on audio outputs (USB DACs, Bluetooth a2dp, DLNA, etc.)


================================================
FILE: post-fs-data.sh
================================================
#!/system/bin/sh

# Do NOT assume where your module will be located.
# ALWAYS use $MODDIR if you need to know where this script and module is placed.
# This will make sure your module will still work if Magisk change its mount point in the future
  MODDIR=${0%/*}

# This script will be executed in post-fs-data mode

if [ \( -e "${MODDIR%/*/*}/modules/usb-samplerate-unlocker"  -a  ! -e "${MODDIR%/*/*}/modules/usb-samplerate-unlocker/disable" \) \
        -o  -e "${MODDIR%/*/*}/modules_update/usb-samplerate-unlocker" ] || \
    [ \( -e "${MODDIR%/*/*}/modules/audio-samplerate-changer"  -a  ! -e "${MODDIR%/*/*}/modules/audio-samplerate-changer/disable" \) \
        -o  -e "${MODDIR%/*/*}/modules_update/audio-samplerate-changer" ]; then
        
    # If usb-samplerate-unlock or audio-samplerate-changer exists, save related libraries and file(s) elsewhere
    # becausethey will do the same thing in themselves.
    for d in "lib" "lib64"; do
        for lname in "libalsautils.so" "libalsautilsv2.so"; do
            if [ -r "${MODDIR}/system/vendor/${d}/${lname}" ]; then
                mkdir -p "${MODDIR}/save/vendor/${d}"
                mv "${MODDIR}/system/vendor/${d}/${lname}" "${MODDIR}/save/vendor/${d}/${lname}"
            fi
        done        
    done
    
    for fname in "audio_platform_configuration.xml"; do
        if [ -r "${MODDIR}/system/vendor/etc/${fname}" ]; then
            mkdir -p "${MODDIR}/save/vendor/etc"
            mv "${MODDIR}/system/vendor/etc/${fname}" "${MODDIR}/save/vendor/etc/${fname}"
        fi
    done
    
else

    # If usb-samplerate-unlock doesn't exist, restore related libraries and file(s) from their saved folders.
    for d in "lib" "lib64"; do
        for lname in "libalsautils.so" "libalsautilsv2.so"; do
            if [ -r "${MODDIR}/save/vendor/${d}/${lname}"  -a  -e "${MODDIR}/system/vendor/${d}" ]; then
                mv "${MODDIR}/save/vendor/${d}/${lname}" "${MODDIR}/system/vendor/${d}/${lname}"
                chmod 644 "${MODDIR}/system/vendor/${d}/${lname}"
            fi
        done        
    done

    for fname in "audio_platform_configuration.xml"; do
        if [ -r "${MODDIR}/save/vendor/etc/${fname}"  -a  -e "${MODDIR}/system/vendor/etc" ]; then
            mv "${MODDIR}/save/vendor/etc/${fname}" "${MODDIR}/system/vendor/etc/${fname}"
            chmod 644 "${MODDIR}/system/vendor/etc/${fname}"
        fi
    done

fi


================================================
FILE: service-functions.sh
================================================
#!/system/bin/sh

function reloadAudioServer()
{
    if [ -n "`getprop init.svc.audioserver`" ]; then
        setprop ctl.restart audioserver
        sleep 1.2
        if [ "`getprop init.svc.audioserver`" != "running" ]; then
            # workaround for Android 12 old devices hanging up the audioserver after "setprop ctl.restart audioserver" is executed
            local pid="`getprop init.svc_debug_pid.audioserver`"
            if [ -n "$pid" ]; then
                kill -HUP $pid 1>"/dev/null" 2>&1
            fi
        fi
    fi
}

# Sleep some secs needed for Audioserver's preparation
function waitAudioServer()
{
    # wait for system boot completion and audiosever boot up
    sleep 11
    local i
    for i in `seq 1 10` ; do
        if [ "`getprop sys.boot_completed`" = "1"  -a  -n "`getprop init.svc.audioserver`" ]; then
            break
        fi
        sleep $i
    done
}

# A rewritten version because some ROM's fail to execute "dumpsys media.audio_policy" on the service phase
#  arg1 : Magisk's module folder path, typically "/data/adb/modules/<module name>"
function remountFiles()
{
    local modPath flist x deletePat forceReload=0
    
    if [ $# -eq 1  -a  -e "$1" ]; then
        modPath="$1"
    else
        return
    fi
    
    deletePat=$(echo "${modPath}/system" | sed -e 's/\//\\\//g')
    
    # Get absolute paths for Magisk's magic mount, then remount by itself
    flist="`find \"${modPath}/system\" -type f | sed -e \"s/$deletePat//\"`"

    # Check if the audio policy XML file and others mounted by Magisk is still unmounted.
    # Some Qcomm devices from Xiaomi, OnePlus, etc. overlays another on it in a boot process
    # and phh GSI's on Qcomm devices unmount it for the phh settings of the GSI's.

    for x in $flist; do
        if [ -e "${modPath}/skip_mount"  -a  "${x##*/}" = ".replace" ]; then
            # Mount a directory instead of ".replace" file if skipping Magisk's magic mount
            mount -o bind "${modPath}/system${x%/.replace}" "${x%/.replace}"
            forceReload=1
        elif [ -r "$x"  -a  -r "${modPath}/system${x}" ]; then
            cmp "$x" "${modPath}/system${x}" >"/dev/null" 2>&1
            if [ "$?" -ne 0 ]; then
                umount "$x" >"/dev/null" 2>&1
                umount "$x" >"/dev/null" 2>&1
                mount -o bind "${modPath}/system${x}" "$x"
                forceReload=1
            fi
        fi
    done
    
    if [ "$forceReload" -gt 0 ]; then
        # Since this library file may be shared multiple modules, it is needed to disperse the timing of each module not to collide
        sleep $(expr $RANDOM % 20)
        reloadAudioServer
    fi
}


================================================
FILE: service-optimizer.sh
================================================
#!/system/bin/sh

# MODDIR=${0%/*} will be inherited from the parent sh module

# This script functions will be used in services mode

. "$MODDIR/jitter-reducer-functions.shlib"

function disableAdaptiveFeatures()
{
    # Reducing jitter by battery draining and charging manager, and 5G data manager
    settings put global adaptive_battery_management_enabled 0
    settings put secure adaptive_charging_enabled 0
    settings put secure adaptive_connectivity_enabled 0
    # Reducing wifi jitter by suspend wifi optimizations
    settings put global wifi_suspend_optimizations_enabled 0
}

function setVolumeMediaSteps()
{
    # Volume medial steps to be 100 if a volume steps facility is used
    settings put system volume_steps_music 100
}

function forceIgnoreAudioEffects()
{
    local force_restart_server=0

    if [ "`getprop persist.sys.phh.disable_audio_effects`" = "0" ]; then
        # Workaround for recent Pixel Firmwares (not to reboot when resetprop'ing)
        resetprop --delete ro.audio.ignore_effects 1>"/dev/null" 2>&1
        # End of workaround
        resetprop ro.audio.ignore_effects true
        force_restart_server=1
    fi
    
    # Stop Tensor device's AOC daemons for reducing significant jitter
    if [ "`getprop init.svc.aocd`" = "running" ]; then
        setprop ctl.stop aocd
        force_restart_server=1
    fi
    if [ "`getprop init.svc.aocxd`" = "running" ]; then
        setprop ctl.stop aocxd
        force_restart_server=1
    fi

    # Nullifying the volume listener for no compressing audio (maybe a peak limiter)
    #   for Qcomm devices only?
    if [ -r "/vendor/lib/soundfx/libvolumelistener.so" ]; then
        mount -o bind "/dev/null" "/vendor/lib/soundfx/libvolumelistener.so"
        force_restart_server=1
    fi
    if [ -r "/vendor/lib64/soundfx/libvolumelistener.so" ]; then
        mount -o bind "/dev/null" "/vendor/lib64/soundfx/libvolumelistener.so"
        force_restart_server=1
    fi

    #   for Motorola devices only?
    if [ -r "/vendor/lib/soundfx/libdlbvol.so" ]; then
        mount -o bind "/dev/null" "/vendor/lib/soundfx/libdlbvol.so"
        force_restart_server=1
    fi
    if [ -r "/vendor/lib64/soundfx/libdlbvol.so" ]; then
        mount -o bind "/dev/null" "/vendor/lib64/soundfx/libdlbvol.so"
        force_restart_server=1
    fi

    if [ "$force_restart_server" = "1"  -o  "`getprop ro.system.build.version.release`" -ge "12" ]; then
        reloadAudioServer       
    fi
}

# This function has six arguments:
# 1. Enable $1:thermal core control, $2:Camera service (interfering in jitters on audio outputs), $3:Selinux enforcing, $4:Doze (battery optimizations)
#     and $5:Logd service or not, respectively ("yes" or "no")
# 2. Disable $6:clearest tone ("yes" or "no"), perhaps for sensitive Bluetooth earphones.

function optimizeOS()
{  
    if [ $# -neq 6 ]; then
        exit 1
    fi

    if [ "$1" = "no" ]; then
        reduceThermalJitter 1 0
    fi
    if [ "$2" = "no" ]; then
        reduceCameraJitter 1 0
    fi
    if [ "$3" = "no" ]; then
        reduceSelinuxJitter 1 0
    fi
    if [ "$4" = "no" ]; then
        reduceDozeJitter 1 0
    fi
    if [ "$5" = "no" ]; then
        reduceLogdJitter 1 0
    fi
    reduceGovernorJitter 1 0
    if [ "$6" = "no" ]; then
        reduceIoJitter 1 '*' 'boost' 0
    else
        reduceIoJitter 1 '*' 'medium' 0
    fi
    reduceVmJitter 1 0
    forceIgnoreAudioEffects
    disableAdaptiveFeatures
    setVolumeMediaSteps
}


================================================
FILE: service.sh
================================================
#!/system/bin/sh
# Do NOT assume where your module will be located. ALWAYS use $MODDIR if you need to know where this script and module is placed.
# This will make sure your module will still work if Magisk change its mount point in the future
# no longer assume "$MAGISKTMP=/sbin/.magisk" if Android 11 or later
#
# This script will be executed in service mode
#

MODDIR=${0%/*}
# MAGISKPATH=$(magisk --path)
# MAGISKTMP=$MAGISKPATH/.magisk

. "$MODDIR/service-functions.sh"
. "$MODDIR/service-optimizer.sh"

#

# 1. Enable thermal control, Camera service (interfering in jitters on audio outputs), Selinux enforcing, Doze (battery optimizations)
#     and Logd service or not, respectively ("yes" or "no").
# 2. Disable clearest tone ("yes" or "no"), perhaps for sensitive Bluetooth earphones.

EnableThermalControl="no"
EnableCameraService="no"
EnableSelinuxEnforcing="no"
EnableDoze="no"
EnableLogdService="no"

DisableClearestTone="no"

# sleep more than 30 secs (waitAudioServer) needed for "settings" commands 
#   to become effective and another kernel tunables setting process completion in an orphan process

(((waitAudioServer; remountFile "$MODDIR"; optimizeOS $EnableThermalControl $EnableCameraService $EnableSelinuxEnforcing \
                        $EnableDoze $EnableLogdService $DisableClearestTone)  0<&- &>"/dev/null" &) &)


================================================
FILE: system.prop
================================================
ro.config.media_vol_steps=100
audio.safemedia.bypass=true
audio.safemedia.force=false
audio.safemedia.csd.force=false
ro.audio.ignore_effects=true
ro.audio.spatializer_enabled=false
ro.vendor.audio.dolby.dax.support=false
vendor.audio.dolby.control.support=false
vendor.audio.usb.perio=2000
vendor.audio.usb.out.period_us=2000
vendor.audio.usb.out.period_count=2
vendor.audio_hal.period_size=120
vendor.audio_hal.period_multiplier=1
vendor.audio.adm.buffering.ms=2
persist.bluetooth.sbc_hd_higher_bitrate=1
af.resampler.quality=
Download .txt
gitextract_1qviyzmq/

├── LICENSE
├── META-INF/
│   └── com/
│       └── google/
│           └── android/
│               ├── update-binary
│               └── updater-script
├── README.md
├── changelog.md
├── customize-functions.sh
├── customize.sh
├── jitter-reducer-functions.shlib
├── module.prop
├── post-fs-data.sh
├── service-functions.sh
├── service-optimizer.sh
├── service.sh
├── system.prop
├── system.prop-workaround
├── templates/
│   ├── bypass_offload_safer_template.xml
│   ├── bypass_offload_template.xml
│   └── offload_hifi_playback_template.xml
└── uninstall.sh
Condensed preview — 19 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (271K chars).
[
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "META-INF/com/google/android/update-binary",
    "chars": 612,
    "preview": "#!/sbin/sh\n\n#################\n# Initialization\n#################\n\numask 022\n\n# echo before loading util_functions\nui_pri"
  },
  {
    "path": "META-INF/com/google/android/updater-script",
    "chars": 8,
    "preview": "#MAGISK\n"
  },
  {
    "path": "README.md",
    "chars": 14677,
    "preview": "## A Magisk module for maximizing the digital audio fidelity by reducing jitters on audio outputs (USB DACs, Bluetooth a"
  },
  {
    "path": "changelog.md",
    "chars": 7738,
    "preview": "## Change logs\n\n# v2.5.16\n* Tuned I/O scheduling parameters for POCO F6, POCO F3, Motorola G54's and Pixel 6's \n\n# v2.5."
  },
  {
    "path": "customize-functions.sh",
    "chars": 23476,
    "preview": "#!/system/bin/sh\n\n# Check whether Magisk magic mount compatible or not\nfunction isMagiskMountCompatible()\n{\n    local tm"
  },
  {
    "path": "customize.sh",
    "chars": 10113,
    "preview": "#!/system/bin/sh\n\n[ -z \"$(magisk --path)\" ] && alias magisk='ksu-magisk'\n\n. \"$MODPATH/customize-functions.sh\"\n\nif ! isMa"
  },
  {
    "path": "jitter-reducer-functions.shlib",
    "chars": 96421,
    "preview": "#!/system/bin/sh\n\nfunction forceOnlineCPUs()\n{\n    local i st en\n    IFS=\"-\" read st en <\"/sys/devices/system/cpu/presen"
  },
  {
    "path": "module.prop",
    "chars": 226,
    "preview": "id=hifi-maximizer-mod\nname=Hifi Maximizer\nversion=v2.5.16\nversionCode=2516\nauthor=zyhk\ndescription=A module for maximizi"
  },
  {
    "path": "post-fs-data.sh",
    "chars": 2422,
    "preview": "#!/system/bin/sh\n\n# Do NOT assume where your module will be located.\n# ALWAYS use $MODDIR if you need to know where this"
  },
  {
    "path": "service-functions.sh",
    "chars": 2675,
    "preview": "#!/system/bin/sh\n\nfunction reloadAudioServer()\n{\n    if [ -n \"`getprop init.svc.audioserver`\" ]; then\n        setprop ct"
  },
  {
    "path": "service-optimizer.sh",
    "chars": 3478,
    "preview": "#!/system/bin/sh\n\n# MODDIR=${0%/*} will be inherited from the parent sh module\n\n# This script functions will be used in "
  },
  {
    "path": "service.sh",
    "chars": 1345,
    "preview": "#!/system/bin/sh\n# Do NOT assume where your module will be located. ALWAYS use $MODDIR if you need to know where this sc"
  },
  {
    "path": "system.prop",
    "chars": 689,
    "preview": "ro.config.media_vol_steps=100\naudio.safemedia.bypass=true\naudio.safemedia.force=false\naudio.safemedia.csd.force=false\nro"
  },
  {
    "path": "system.prop-workaround",
    "chars": 695,
    "preview": "ro.config.media_vol_steps=100\naudio.safemedia.bypass=true\naudio.safemedia.force=false\naudio.safemedia.csd.force=false\nro"
  },
  {
    "path": "templates/bypass_offload_safer_template.xml",
    "chars": 19138,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<!-- Copyright (C) 2020 The Android Open Source Project\n     Lic"
  },
  {
    "path": "templates/bypass_offload_template.xml",
    "chars": 18950,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<!-- Copyright (C) 2020 The Android Open Source Project\n     Lic"
  },
  {
    "path": "templates/offload_hifi_playback_template.xml",
    "chars": 19100,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<!-- Copyright (C) 2020 The Android Open Source Project\n     Lic"
  },
  {
    "path": "uninstall.sh",
    "chars": 1007,
    "preview": "#!/system/bin/sh\n# Do NOT assume where your module will be located. ALWAYS use $MODDIR if you need to know where this sc"
  }
]

About this extraction

This page contains the full source code of the yzyhk904/hifi-maximizer-mod GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 19 files (251.3 KB), approximately 62.7k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!