initial commit

Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
This commit is contained in:
Sagi Dayan 2024-01-16 17:21:35 +02:00
commit 48661005be
Signed by: sagi
GPG key ID: FAB96BFC63B46458
941 changed files with 332406 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
build/

76
.golangci.yml Normal file
View file

@ -0,0 +1,76 @@
# This file contains all available configuration options
# with their default values.
# options for analysis running
run:
# default concurrency is a available CPU number
concurrency: 4
# timeout for analysis, e.g. 30s, 5m, default is 1m
timeout: 10m
# exit code when at least one issue was found, default is 1
issues-exit-code: 1
# include test files or not, default is true
tests: true
# which dirs to skip: issues from them won't be reported;
# can use regexp here: generated.*, regexp is applied on full path;
# default value is empty list, but default dirs are skipped independently
# from this option's value (see skip-dirs-use-default).
skip-dirs:
- bin
- deploy
- docs
- examples
- hack
- packaging
- reports
# output configuration options
output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
format: colored-line-number
# print lines of code with issue, default is true
print-issued-lines: true
# print linter name in the end of issue text, default is true
print-linter-name: true
# make issues output unique by line, default is true
uniq-by-line: true
issues:
# List of regexps of issue texts to exclude, empty list by default.
# But independently from this option we use default exclude patterns,
# it can be disabled by `exclude-use-default: false`. To list all
# excluded by default patterns execute `golangci-lint run --help`
exclude:
- 'declaration of "err" shadows declaration at'
linters:
enable:
- megacheck
- govet
- gocyclo
- gofmt
- gosec
- megacheck
- unconvert
- gci
- goimports
- exportloopref
linters-settings:
govet:
check-shadowing: true
settings:
printf:
funcs:
- Infof
- Warnf
- Errorf
- Fatalf

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

33
Makefile Normal file
View file

@ -0,0 +1,33 @@
BINARY_NAME=subsonic-tui
BUILD_FOLDER=build
.PHONY: build
build:
GOARCH=amd64 GOOS=darwin go build -o ${BUILD_FOLDER}/${BINARY_NAME}-darwin main.go
GOARCH=amd64 GOOS=linux go build -o ${BUILD_FOLDER}/${BINARY_NAME}-linux main.go
GOARCH=amd64 GOOS=windows go build -o ${BUILD_FOLDER}/${BINARY_NAME}-windows main.go
run: build
./${BINARY_NAME}
clean:
go clean
rm ${BINARY_NAME}-darwin
rm ${BINARY_NAME}-linux
rm ${BINARY_NAME}-windows
test:
go test ./...
test_coverage:
go test ./... -coverprofile=coverage.out
dep:
go mod download
vet:
go vet
lint:
golangci-lint run --enable-all

91
README.md Normal file
View file

@ -0,0 +1,91 @@
# Subsonic TUI
**NOTE ⚠ !!: This is under heavy development! Do not fork just yet. Im still force pushing to main!**
A Subsonic client and player written in go.
subsonictui (Name in progress) is a simple and easy to use player for Linux, Mac and (yes...) Windows.
<p align="center">
<img src="./assets/screenshot.png" alt="Screenshot">
<img src="./assets/screenshot-miniplayer.png" alt="Screenshot mini player">
</p>
> Note: Screenshots blurred for (I dont know) copyright issues?
## Features
- [x] Browse Artists/Albums/Playlists
- [x] Artist view
- [x] Playlist view
- [x] Miniplayer on small screen
- [x] Album view
- [x] Search
- [x] Playback
- [x] Scrobble (configurable)
- [x] Play album
- [x] Shuffle album
- [x] Add album to queue
- [x] Add song to queue
- [x] Play Next/Prev
- [x] Stop/Pause
- [x] Generate artist radio
- [x] Generate song radio
- [-] Desktop integration
- [x] Linux (MPRIS)
- [ ] Windows
- [ ] MacOS
- [ ] Playlist management
- [ ] Add song to playlist
- [ ] Create playlist from queue
## Keybindings
| Key(s) | Action |
|------------------------------------------------------------------------------|-------------------------------------------------|
| <kbd>`</kbd> | Focus on Main pane |
| <kbd>1</kbd> | Focus on Atrists pane |
| <kbd>2</kbd> | Focus on Albums pane |
| <kbd>3</kbd> | Focus on Playlists pane |
| <kbd>4</kbd> | Focus on Queue pane |
| <kbd>Arrow keys</kbd> or <kbd>h</kbd> <kbd>j</kbd> <kbd>k</kbd> <kbd>l</kbd> | Navigation in a pane. Shift for switching panes |
| <kbd>g</kbd> | Jump to first item in a list of a pane |
| <kbd>G</kbd> | Jump to last item in a list of a pane |
| <kbd>n</kbd> | Next song |
| <kbd>N</kbd> | Prev song |
| <kbd>q</kbd> | Exit |
| <kbd>r</kbd> | While on a song - Start Song radio |
| <kbd>s</kbd> | Playback - Stop |
| <kbd>p</kbd> | Playback - Toggle Play/Pause |
| <kbd>c</kbd> | Stop, clear queue |
| <kbd>/</kbd> | Search |
| <kbd>?</kbd> | Help |
## Config
`subsonictui` stores a config file at:
- Linux: `$HOME/.config/subsonictui/config.yaml`
- macOS: `$HOME/Library/Application Support/subsonictui/config.yaml`
- Windows: `C:\\Users\%USER%\AppData\Roaming\subsonictui\config.yaml`
## Development
### Build Dependencies
subsonictui uses [Beep](https://github.com/faiface/beep), that uses [OTO](https://github.com/hajimehoshi/oto) under the hood, so you will need OTO dependencies.
Mainly on Linux you will need `alsa-devel`.
To Build the project:
```
$ make build
```
## Special Thanks
subsonictui is built on top of a few projects. I would like to thank them here
- [go-subsonic](https://github.com/delucks/go-subsonic)
- [OTO](https://github.com/hajimehoshi/oto)
- [Beep](https://github.com/faiface/beep)
- [tview](https://github.com/rivo/tview)
- [tcell](https://github.com/gdamore/tcell)
- [MPRIS server](https://github.com/quarckster/go-mpris-server)
Thank you for creating wondeful software that everyone can use. Including myself.

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

BIN
assets/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

28
go.mod Normal file
View file

@ -0,0 +1,28 @@
module git.dayanhub.com/sagi/subsonic-tui
go 1.21.5
require (
github.com/creasty/defaults v1.7.0
github.com/delucks/go-subsonic v0.0.0-20220915164742-2744002c4be5
github.com/gdamore/tcell/v2 v2.7.4
github.com/godbus/dbus/v5 v5.1.0
github.com/gopxl/beep v1.4.0
github.com/quarckster/go-mpris-server v1.0.3
github.com/rivo/tview v0.0.0-20240307173318-e804876934a1
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/ebitengine/oto/v3 v3.1.1 // indirect
github.com/ebitengine/purego v0.6.1 // indirect
github.com/gdamore/encoding v1.0.1 // indirect
github.com/hajimehoshi/go-mp3 v0.3.4 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/term v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
)

83
go.sum Normal file
View file

@ -0,0 +1,83 @@
github.com/creasty/defaults v1.7.0 h1:eNdqZvc5B509z18lD8yc212CAqJNvfT1Jq6L8WowdBA=
github.com/creasty/defaults v1.7.0/go.mod h1:iGzKe6pbEHnpMPtfDXZEr0NVxWnPTjb1bbDy08fPzYM=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/delucks/go-subsonic v0.0.0-20220915164742-2744002c4be5 h1:RuuxidatioSKGOiBzL1mTY4X22DQD8weEbS3iRLHnAg=
github.com/delucks/go-subsonic v0.0.0-20220915164742-2744002c4be5/go.mod h1:vnbEuj6Z20PLcHB4rrLQAOXGMjtULfMGhRVSFPcSdUo=
github.com/ebitengine/oto/v3 v3.1.1 h1:utFNkSF4yXqA7VhMg7oHp3OSdz3vuzJQ42rCDnd8pc8=
github.com/ebitengine/oto/v3 v3.1.1/go.mod h1:bQM4zk9glIVjTynn8X0Lp1zngTlZltFFfzJvx543vdA=
github.com/ebitengine/purego v0.6.1 h1:sjN8rfzbhXQ59/pE+wInswbU9aMDHiwlup4p/a07Mkg=
github.com/ebitengine/purego v0.6.1/go.mod h1:ah1In8AOtksoNK6yk5z1HTJeUkC1Ez4Wk2idgGslMwQ=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw=
github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo=
github.com/gdamore/tcell/v2 v2.7.4 h1:sg6/UnTM9jGpZU+oFYAsDahfchWAFW8Xx2yFinNSAYU=
github.com/gdamore/tcell/v2 v2.7.4/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gopxl/beep v1.4.0 h1:pJERVDZMJkf49R1g/tV9DhVct4xNRuTlyMnMa53gGsc=
github.com/gopxl/beep v1.4.0/go.mod h1:gGVz7MJKlfHrmkzr0wSLGNyY7oisM6rFWJnaLjNxEwA=
github.com/hajimehoshi/go-mp3 v0.3.4 h1:NUP7pBYH8OguP4diaTZ9wJbUbk3tC0KlfzsEpWmYj68=
github.com/hajimehoshi/go-mp3 v0.3.4/go.mod h1:fRtZraRFcWb0pu7ok0LqyFhCUrPeMsGRSVop0eemFmo=
github.com/hajimehoshi/oto/v2 v2.3.1/go.mod h1:seWLbgHH7AyUMYKfKYT9pg7PhUu9/SisyJvNTT+ASQo=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quarckster/go-mpris-server v1.0.3 h1:ef6d3DpxlORtdEBHnhQ/j3gS0Z3+YUfXeJhC9L9DZvA=
github.com/quarckster/go-mpris-server v1.0.3/go.mod h1:2b4IdrpnEoEfU+6fQKjYhAgdvsiz4JxmTpDAUrMJVO4=
github.com/rivo/tview v0.0.0-20240307173318-e804876934a1 h1:bWLHTRekAy497pE7+nXSuzXwwFHI0XauRzz6roUvY+s=
github.com/rivo/tview v0.0.0-20240307173318-e804876934a1/go.mod h1:02iFIz7K/A9jGCvrizLPvoqr4cEIx7q54RH5Qudkrss=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -0,0 +1,97 @@
package client
import (
"fmt"
"image"
"image/jpeg"
"os"
"path"
)
type artcache struct {
artPaths map[string]string
cacheDir string
}
var ArtCache *artcache
func (c *artcache) saveArt(id string, img image.Image) *string {
path := c.GetPath(id)
if path != nil {
return path
}
path = c.saveImage(id, img)
if path != nil {
c.artPaths[id] = *path
}
return path
}
func (c *artcache) saveImage(id string, img image.Image) *string {
filePath := c.filepath(id)
f, err := os.Create(filePath)
defer func() {
_ = f.Close()
}()
if err != nil {
return nil
}
err = jpeg.Encode(f, img, nil)
if err != nil {
return nil
}
return &filePath
}
func (c *artcache) GetPath(id string) *string {
if path, ok := c.artPaths[id]; ok {
return &path
}
return nil
}
func (c *artcache) GetImage(id string) *image.Image {
path := c.GetPath(id)
if path == nil {
return nil
}
f, err := os.Open(*path)
if err != nil {
return nil
}
defer func() {
_ = f.Close()
}()
img, err := jpeg.Decode(f)
if err != nil {
return nil
}
return &img
}
func (c *artcache) filepath(id string) string {
return path.Join(c.cacheDir, fmt.Sprintf("%s.jpg", id))
}
func (c *artcache) Destroy() {
os.RemoveAll(c.cacheDir)
}
func init() {
tmpDir := os.TempDir()
cacheDir := path.Join(tmpDir, fmt.Sprintf("subsonic-tui-%d", os.Getpid()))
err := os.Mkdir(cacheDir, 0777)
if err != nil {
panic("Failed to create cacheDir")
}
ArtCache = &artcache{
cacheDir: cacheDir,
artPaths: make(map[string]string),
}
}

163
internal/client/client.go Normal file
View file

@ -0,0 +1,163 @@
package client
import (
"fmt"
"image"
"io"
"net/http"
"sync"
"git.dayanhub.com/sagi/subsonic-tui/internal/common"
"github.com/delucks/go-subsonic"
)
type Client struct {
client subsonic.Client
}
func NewClient(baseURL string) *Client {
var client subsonic.Client = subsonic.Client{
Client: &http.Client{},
ClientName: "subsonic-tui",
BaseUrl: baseURL,
PasswordAuth: true,
}
return &Client{
client: client,
}
}
func (c *Client) Authenticate(username, password string) error {
c.client.User = username
return c.client.Authenticate(password)
}
func (c *Client) GetUser() (*subsonic.User, error) {
return c.client.GetUser(c.client.User)
}
func (c *Client) GetPlaylists() ([]*subsonic.Playlist, error) {
return c.client.GetPlaylists(map[string]string{})
}
func (c *Client) GetPlaylist(ID string) (*subsonic.Playlist, error) {
return c.client.GetPlaylist(ID)
}
func (c *Client) GetArtists() ([]*subsonic.ArtistID3, error) {
indexes, err := c.client.GetArtists(map[string]string{})
if err != nil {
return nil, err
}
artists := []*subsonic.ArtistID3{}
for _, i := range indexes.Index {
artists = append(artists, i.Artist...)
}
return artists, nil
}
func (c *Client) GetAlbums() ([]*subsonic.AlbumID3, error) {
return c.client.GetAlbumList2("alphabeticalByName", map[string]string{
"size": "500",
})
}
func (c *Client) GetArtist(ID string) (*subsonic.ArtistID3, error) {
return c.client.GetArtist(ID)
}
func (c *Client) GetArtistInfo(ID string) (*subsonic.ArtistInfo2, error) {
return c.client.GetArtistInfo2(ID, map[string]string{
"count": "20",
})
}
func (c *Client) GetAlbum(ID string) (*subsonic.AlbumID3, error) {
return c.client.GetAlbum(ID)
}
func (c *Client) GetCoverArt(ID string) (image.Image, error) {
if img := ArtCache.GetImage(ID); img != nil {
return *img, nil
}
img, err := c.client.GetCoverArt(ID, map[string]string{
//"size": "64",
})
if err != nil {
return nil, err
}
ArtCache.saveArt(ID, img)
return img, err
}
func (c *Client) GetSimilarSongs(artistID string, maxSongs int) ([]*subsonic.Child, error) {
max := fmt.Sprintf("%d", maxSongs)
return c.client.GetSimilarSongs2(artistID, map[string]string{
"count": max,
})
}
func (c *Client) Stream(ID string) (io.Reader, error) {
return c.client.Stream(ID, map[string]string{
"format": "mp3",
})
}
func (c *Client) Scrobble(ID string) error {
return c.client.Scrobble(ID, map[string]string{})
}
func (c *Client) GetTopSongs(name string, max int) ([]*subsonic.Child, error) {
count := fmt.Sprintf("%d", max)
return c.client.GetTopSongs(name, map[string]string{
"count": count,
})
}
func (c *Client) Search(query string) (*subsonic.SearchResult3, error) {
return c.client.Search3(query, map[string]string{
"artistCount": "20",
"songCount": "20",
"albumCount": "20",
})
}
func (c *Client) GetExperimentalArtistRadio(artistId3 *subsonic.ArtistID3, info *subsonic.ArtistInfo2, max int) ([]*subsonic.Child, error) {
var wg sync.WaitGroup
ID := artistId3.ID
similarArtists := info.SimilarArtist
songs := []*subsonic.Child{}
similarArtistsSongs := 10
thisArtistFactor := 3
portion := len(info.SimilarArtist) * similarArtistsSongs * thisArtistFactor
wg.Add(2)
go func() {
s, _ := c.GetSimilarSongs(ID, portion)
songs = append(songs, s...)
wg.Done()
}()
go func() {
s, _ := c.GetTopSongs(artistId3.Name, similarArtistsSongs)
songs = append(songs, s...)
wg.Done()
}()
common.ShuffleSlice(similarArtists)
for _, a := range similarArtists {
wg.Add(1)
artist := a
go func() {
s, _ := c.GetSimilarSongs(artist.ID, similarArtistsSongs)
songs = append(songs, s...)
wg.Done()
}()
}
wg.Wait()
if max > len(songs) {
max = len(songs)
}
songs = songs[:max]
common.ShuffleSlice(songs)
return songs, nil
}

View file

@ -0,0 +1,21 @@
package common
import (
"crypto/rand"
"math/big"
"reflect"
)
func ShuffleSlice(slice interface{}) {
rv := reflect.ValueOf(slice)
swap := reflect.Swapper(slice)
length := rv.Len()
for i := length - 1; i > 0; i-- {
j, err := rand.Int(rand.Reader, big.NewInt(int64(i+1)))
if err != nil {
panic("Shuffle error")
}
swap(i, int(j.Int64()))
}
}

21
internal/config/colors.go Normal file
View file

@ -0,0 +1,21 @@
package config
import (
"github.com/gdamore/tcell/v2"
)
const (
ColorBackground = tcell.ColorDefault
ColorSelectedBoarder = tcell.ColorRed
ColorBluredBoarder = tcell.ColorWhite
ColorText = tcell.ColorWhite
ColorTextAccent = tcell.ColorYellow
ColorPlaybackProgressElapsed = tcell.ColorLightCyan
ColorPlaybackProgressRemaining = tcell.ColorBlack
ColorQueuePlayedBg = tcell.ColorBlack
ColorQueuePlayingBg = tcell.ColorDarkRed
ColorButtonBg = tcell.ColorBlue
ColorButtonTxt = tcell.ColorBlack
ColorButtonSelectedBg = tcell.ColorYellow
ColorButtonSelectedTxt = tcell.ColorDarkRed
)

123
internal/config/config.go Normal file
View file

@ -0,0 +1,123 @@
package config
import (
"encoding/base64"
"fmt"
"os"
"path"
"strings"
"github.com/creasty/defaults"
"gopkg.in/yaml.v3"
)
var configPath string
type _config struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
URL string `yaml:"url"`
EnableScrobble bool `yaml:"enable_scrobble" default:"false"`
MaxRadioSongs int `yaml:"max_radio_songs" default:"50"`
ExperimentalRadioAlgo bool `yaml:"experimental_radio_algo" default:"false"`
}
var configStruct *_config
func init() {
userConfigDir, err := os.UserConfigDir()
configDir := path.Join(userConfigDir, "subsonictui")
configPath = path.Join(configDir, "config.yaml")
if err != nil {
fmt.Printf("[ERROR] Failed to fetch user config directory. %e\n", err)
os.Exit(1)
}
if _, err := os.Stat(configDir); os.IsNotExist(err) {
err := os.MkdirAll(configDir, 0700)
if err != nil {
panic(err)
}
}
var configFile *os.File
if _, err := os.Stat(configPath); os.IsNotExist(err) {
configFile, err = os.Create(configPath)
defer func() {
err := configFile.Close()
if err != nil {
panic(err)
}
}()
if err != nil {
fmt.Printf("[ERROR] Failed to create config file @ %s. %e\n", configPath, err)
os.Exit(1)
}
}
configStruct, err = loadConfig()
if err != nil {
fmt.Printf("[ERROR] Failed to load config file @ %s. %e\n", configPath, err)
os.Exit(1)
}
fmt.Printf("Init Config %s\n", configPath)
}
func URL() string {
return configStruct.URL
}
func Username() string {
return configStruct.Username
}
func Password() string {
p, _ := base64.StdEncoding.DecodeString(configStruct.Password)
return strings.TrimSpace(string(p))
}
func ScrobbleEnabled() bool {
return configStruct.EnableScrobble
}
func MaxRadioSongs() int {
return configStruct.MaxRadioSongs
}
func ExperimentalRadioAlgo() bool {
return configStruct.ExperimentalRadioAlgo
}
func SetPassword(p string) {
configStruct.Password = base64.StdEncoding.EncodeToString([]byte(p))
}
func SetUsername(u string) {
configStruct.Username = u
}
func SetURL(u string) {
configStruct.URL = u
}
func loadConfig() (*_config, error) {
c := &_config{}
err := defaults.Set(c)
if err != nil {
panic(err)
}
file, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
if err = yaml.Unmarshal(file, c); err != nil {
return nil, err
}
return c, nil
}
func SaveConfig() {
yml, err := yaml.Marshal(configStruct)
if err != nil {
fmt.Printf("[ERROR] Failed to convert config to yaml. %e\n", err)
os.Exit(1)
}
err = os.WriteFile(configPath, yml, 0600)
if err != nil {
fmt.Printf("[ERROR] Failed to save config file @ %s. %e\n", configPath, err)
os.Exit(1)
}
}

View file

@ -0,0 +1,223 @@
package playback
import (
"io"
"time"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"github.com/delucks/go-subsonic"
"github.com/gopxl/beep"
"github.com/gopxl/beep/mp3"
"github.com/gopxl/beep/speaker"
)
type PlaybackState int
const (
PlaybackStateStopped = iota
PlaybackStatePaused
PlaybackStatePlaying
)
type Controller struct {
client *client.Client
stream beep.StreamSeekCloser
song *subsonic.Child
songElapsedFunc func(song *subsonic.Child, elapsed time.Duration)
initialFormat *beep.Format
currentFormat *beep.Format
position float64
closeChan chan bool
songEndedChan chan bool
songEndedFunc func(song *subsonic.Child)
ctrl *beep.Ctrl
desktopPlayback DesktopPlayback
queue *queue
playbackState PlaybackState
}
func NewController(client *client.Client) *Controller {
controller := &Controller{
client: client,
closeChan: make(chan bool),
songEndedChan: make(chan bool),
playbackState: PlaybackStateStopped,
queue: newQueue(),
}
controller.desktopPlayback = desktopPlayer(controller)
controller.desktopPlayback.Start()
go controller.playbackTicker()
return controller
}
func (c *Controller) State() PlaybackState {
return c.playbackState
}
func (c *Controller) Play(song *subsonic.Child) {
if song == nil {
return
}
r, err := c.client.Stream(song.ID)
if err != nil {
//TODO: Log error
c.Stop()
return
}
c.Stream(r, song)
}
func (c *Controller) Next() {
song := c.queue.Next()
if song != nil {
c.Play(song)
}
}
func (c *Controller) AddToQueue(songs []*subsonic.Child) {
shouldPlay := c.queue.Add(songs...)
if shouldPlay {
c.Play(c.queue.GetCurrentSong())
}
c.desktopPlayback.OnPlaylistChanged()
}
func (c *Controller) GetQueuePosition() int {
return c.queue.GetPosition()
}
func (c *Controller) GetCurrentSong() *subsonic.Child {
return c.queue.GetCurrentSong()
}
func (c *Controller) SetQueue(songs []*subsonic.Child) {
c.queue.Clear()
c.Stop()
c.queue.Set(songs)
c.Play(c.queue.GetCurrentSong())
c.desktopPlayback.OnPlaylistChanged()
}
func (c *Controller) SetQueuePosition(position int) {
s := c.queue.SetPosition(position)
c.Play(s)
}
func (c *Controller) Prev() {
song := c.queue.Prev()
if song != nil {
c.Play(song)
}
}
func (c *Controller) GetQueue() []*subsonic.Child {
return c.queue.Get()
}
func (c *Controller) ClearQueue() {
c.Stop()
c.queue.Clear()
c.desktopPlayback.OnPlayPause()
c.desktopPlayback.OnSongChanged()
c.desktopPlayback.OnPlaylistChanged()
}
func (c *Controller) SetSongElapsedFunc(f func(sing *subsonic.Child, elapsed time.Duration)) {
c.songElapsedFunc = f
}
func (c *Controller) SetSongEndedFunc(f func(song *subsonic.Child)) {
c.songEndedFunc = f
}
func (c *Controller) Close() error {
c.Stop()
c.closeChan <- true
return nil
}
func (c *Controller) TogglePlayPause() {
if c.playbackState != PlaybackStateStopped {
c.ctrl.Paused = !c.ctrl.Paused
if c.ctrl.Paused {
c.playbackState = PlaybackStatePaused
} else {
c.playbackState = PlaybackStatePlaying
}
}
c.desktopPlayback.OnPlayPause()
}
func (c *Controller) Stop() {
if c.ctrl == nil {
return
}
speaker.Clear()
c.ctrl.Paused = true
c.playbackState = PlaybackStateStopped
c.ctrl = nil
c.stream = nil
c.songElapsedFunc(c.song, time.Duration(0))
c.song = nil
c.position = 0
c.desktopPlayback.OnPlayPause()
c.desktopPlayback.OnPlaylistChanged()
}
func (c *Controller) playbackTicker() {
for {
select {
case <-c.closeChan:
return
case <-c.songEndedChan:
c.Stop()
c.Next()
default:
if c.playbackState == PlaybackStatePlaying && c.song != nil {
if c.stream != nil {
pos := c.stream.Position()
elapsed := c.currentFormat.SampleRate.D(pos).Round(time.Second)
c.position = elapsed.Seconds()
c.songElapsedFunc(c.song, elapsed)
c.desktopPlayback.OnPositionChanged(int(c.position))
}
}
}
time.Sleep(time.Second)
}
}
func (c *Controller) Stream(reader io.Reader, song *subsonic.Child) {
c.Stop()
// Ensure artwork cache...
_, _ = c.client.GetCoverArt(song.CoverArt)
readerCloser := io.NopCloser(reader)
decodedMp3, format, err := mp3.Decode(readerCloser)
decodedMp3.Position()
if err != nil {
panic("mp3.NewDecoder failed: " + err.Error())
}
if c.initialFormat == nil {
c.initialFormat = &format
}
c.currentFormat = &format
var stream beep.Streamer = decodedMp3
if err = speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10)); err != nil {
stream = beep.Resample(3, format.SampleRate, c.initialFormat.SampleRate, decodedMp3)
}
c.stream = decodedMp3
c.song = song
ctrl := &beep.Ctrl{Streamer: stream}
c.ctrl = ctrl
c.playbackState = PlaybackStatePlaying
speaker.Play(beep.Seq(ctrl, beep.Callback(func() {
c.songEndedFunc(song)
c.songEndedChan <- true
})))
c.desktopPlayback.OnSongChanged()
c.desktopPlayback.OnPlayPause()
}

View file

@ -0,0 +1,10 @@
package playback
type DesktopPlayback interface {
Start()
Stop() error
OnPlayPause()
OnPlaylistChanged()
OnSongChanged()
OnPositionChanged(sec int)
}

249
internal/playback/mpris.go Normal file
View file

@ -0,0 +1,249 @@
package playback
import (
"encoding/base32"
"fmt"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"github.com/delucks/go-subsonic"
"github.com/godbus/dbus/v5"
"github.com/quarckster/go-mpris-server/pkg/events"
"github.com/quarckster/go-mpris-server/pkg/server"
. "github.com/quarckster/go-mpris-server/pkg/types"
)
const (
mprisPlayerNmae = "MehSonic"
mprisNoTrack = "/org/mpris/MediaPlayer2/TrackList/NoTrack"
)
type mprisRoot struct{}
func (r mprisRoot) Raise() error {
return nil
}
func (r mprisRoot) Quit() error {
return nil
}
func (r mprisRoot) CanQuit() (bool, error) {
return true, nil
}
func (r mprisRoot) CanRaise() (bool, error) {
return false, nil
}
func (r mprisRoot) HasTrackList() (bool, error) {
return false, nil
}
func (r mprisRoot) Identity() (string, error) {
return mprisPlayerNmae, nil
}
func (r mprisRoot) SupportedUriSchemes() ([]string, error) {
return []string{}, nil
}
func (r mprisRoot) SupportedMimeTypes() ([]string, error) {
return []string{}, nil
}
type mprisPlayer struct {
ctrl *Controller
}
// Implement other methods of `pkg.types.OrgMprisMediaPlayer2PlayerAdapter`
func (p mprisPlayer) Next() error {
p.ctrl.Next()
return nil
}
func (p mprisPlayer) Previous() error {
p.ctrl.Prev()
return nil
}
func (p mprisPlayer) Pause() error {
if p.ctrl.State() == PlaybackStatePlaying {
p.ctrl.TogglePlayPause()
}
return nil
}
func (p mprisPlayer) PlayPause() error {
switch p.ctrl.State() {
case PlaybackStatePaused, PlaybackStatePlaying:
p.ctrl.TogglePlayPause()
case PlaybackStateStopped:
p.ctrl.Play(p.ctrl.GetCurrentSong())
}
return nil
}
func (p mprisPlayer) Stop() error {
p.ctrl.Stop()
return nil
}
func (p mprisPlayer) Play() error {
switch p.ctrl.State() {
case PlaybackStatePaused:
p.ctrl.TogglePlayPause()
case PlaybackStateStopped:
p.ctrl.Play(p.ctrl.GetCurrentSong())
}
return nil
}
func (p mprisPlayer) Seek(offset Microseconds) error {
return nil
}
func (p mprisPlayer) SetPosition(trackId string, position Microseconds) error {
return nil
}
func (p mprisPlayer) OpenUri(uri string) error {
return nil
}
func (p mprisPlayer) PlaybackStatus() (PlaybackStatus, error) {
switch p.ctrl.State() {
case PlaybackStatePlaying:
return PlaybackStatusPlaying, nil
case PlaybackStatePaused:
return PlaybackStatusPaused, nil
case PlaybackStateStopped:
return PlaybackStatusStopped, nil
}
// Should not get here
return PlaybackStatusStopped, nil
}
func (p mprisPlayer) Rate() (float64, error) {
return 1, nil
}
func (p mprisPlayer) SetRate(float64) error {
return nil
}
func (p mprisPlayer) Metadata() (Metadata, error) {
s := p.ctrl.GetCurrentSong()
objPath := mprisNoTrack
if s != nil {
objPath = encodeTrackId(s.ID)
} else {
s = &subsonic.Child{}
}
md := Metadata{
TrackId: dbus.ObjectPath(objPath),
Length: secondsToMicroseconds(s.Duration),
Title: s.Title,
Album: s.Album,
Artist: []string{s.Artist},
DiscNumber: s.DiscNumber,
Genre: []string{s.Genre},
TrackNumber: s.Track,
UserRating: float64(s.UserRating),
UseCount: int(s.PlayCount),
}
artw := client.ArtCache.GetPath(s.CoverArt)
if artw != nil {
md.ArtUrl = fmt.Sprintf("file://%s", *artw)
}
return md, nil
}
func (p mprisPlayer) Volume() (float64, error) {
return 1, nil
}
func (p mprisPlayer) SetVolume(float64) error {
return nil
}
func (p mprisPlayer) Position() (int64, error) {
return int64(secondsToMicroseconds(int(p.ctrl.position))), nil
}
func (p mprisPlayer) MinimumRate() (float64, error) {
return 1, nil
}
func (p mprisPlayer) MaximumRate() (float64, error) {
return 1, nil
}
func (p mprisPlayer) CanGoNext() (bool, error) {
return p.ctrl.queue.HasNext(), nil
}
func (p mprisPlayer) CanGoPrevious() (bool, error) {
return p.ctrl.queue.HasPrev(), nil
}
func (p mprisPlayer) CanPlay() (bool, error) {
return p.ctrl.GetCurrentSong() != nil, nil
}
func (p mprisPlayer) CanPause() (bool, error) {
return true, nil
}
func (p mprisPlayer) CanSeek() (bool, error) {
return false, nil
}
func (p mprisPlayer) CanControl() (bool, error) {
return true, nil
}
var _ DesktopPlayback = &mprisPlayback{}
type mprisPlayback struct {
root mprisRoot
player mprisPlayer
eventHandler *events.EventHandler
server *server.Server
err error
}
func (p *mprisPlayback) Start() {
go func() {
p.err = p.server.Listen()
}()
}
func (p *mprisPlayback) Stop() error {
return p.server.Stop()
}
func (p *mprisPlayback) OnPlayPause() {
if p.err != nil {
return
}
p.err = p.eventHandler.Player.OnPlayPause()
}
func (p *mprisPlayback) OnPlaylistChanged() {
if p.err != nil {
return
}
p.err = p.eventHandler.Player.OnOptions()
}
func (p *mprisPlayback) OnSongChanged() {
if p.err != nil {
return
}
p.err = p.eventHandler.Player.OnTitle()
}
func (p *mprisPlayback) OnPositionChanged(position int) {
if p.err != nil {
return
}
p.err = p.eventHandler.Player.OnSeek(secondsToMicroseconds(position))
if p.err != nil {
return
}
p.err = p.eventHandler.Player.OnOptions()
}
func desktopPlayer(c *Controller) DesktopPlayback {
r := mprisRoot{}
p := mprisPlayer{
ctrl: c,
}
s := server.NewServer(mprisPlayerNmae, r, p)
ev := events.NewEventHandler(s)
return &mprisPlayback{
root: r,
player: p,
server: s,
eventHandler: ev,
}
}
func secondsToMicroseconds(s int) Microseconds {
return Microseconds(s * 1_000_000)
}
func encodeTrackId(id string) string {
data := []byte(id)
return fmt.Sprintf("/%s/Track/%s", mprisPlayerNmae, base32.StdEncoding.WithPadding('0').EncodeToString(data))
}

View file

@ -0,0 +1,84 @@
package playback
import "github.com/delucks/go-subsonic"
type queue struct {
currentSong int
songQueue []*subsonic.Child
}
func newQueue() *queue {
return &queue{
currentSong: 0,
songQueue: []*subsonic.Child{},
}
}
func (q *queue) Set(songs []*subsonic.Child) {
q.currentSong = 0
q.songQueue = songs
}
func (q *queue) Clear() {
q.currentSong = 0
q.songQueue = []*subsonic.Child{}
}
// returns true if queue was empty before addition
func (q *queue) Add(songs ...*subsonic.Child) bool {
shouldStartPlaying := len(q.songQueue) == 0
q.songQueue = append(q.songQueue, songs...)
if shouldStartPlaying {
q.currentSong = 0
return true
}
return false
}
// returns a song if position has changed
func (q *queue) SetPosition(position int) *subsonic.Child {
if position == q.currentSong || position < 0 || len(q.songQueue) < position {
return nil
}
q.currentSong = position
return q.GetCurrentSong()
}
func (q *queue) GetPosition() int {
return q.currentSong
}
func (q *queue) GetCurrentSong() *subsonic.Child {
if len(q.songQueue) == 0 {
return nil
}
return q.songQueue[q.currentSong]
}
func (q *queue) HasPrev() bool {
return 0 < q.currentSong
}
func (q *queue) HasNext() bool {
return q.currentSong < len(q.songQueue)-1
}
func (q *queue) Next() *subsonic.Child {
if len(q.songQueue) > q.currentSong+1 {
q.currentSong = q.currentSong + 1
return q.GetCurrentSong()
}
return nil
}
func (q *queue) Prev() *subsonic.Child {
if q.currentSong > 0 {
q.currentSong = q.currentSong - 1
return q.GetCurrentSong()
}
return nil
}
func (q *queue) Get() []*subsonic.Child {
return q.songQueue
}

124
internal/tui/tui.go Normal file
View file

@ -0,0 +1,124 @@
package tui
import (
"fmt"
"os"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"git.dayanhub.com/sagi/subsonic-tui/internal/playback"
"git.dayanhub.com/sagi/subsonic-tui/internal/tui/views"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
type TUI struct {
app *tview.Application
layout views.View
client *client.Client
playbackCtl *playback.Controller
}
func NewLogin() *TUI {
app := tview.NewApplication()
layout := views.NewLoginView(func(u, p, url string) {
c := client.NewClient(url)
err := c.Authenticate(u, p)
if err != nil {
app.Stop()
fmt.Printf("[Error] Failed to login. Aborting %e", err)
os.Exit(1)
}
config.SetURL(url)
config.SetUsername(u)
config.SetPassword(p)
config.SaveConfig()
app.Stop()
}, func() {
app.Stop()
os.Exit(0)
})
app.EnableMouse(true).
SetRoot(layout.GetView(), true)
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if event.Key() == tcell.KeyEsc {
app.Stop()
os.Exit(0)
}
return event
})
return &TUI{
app: app,
layout: layout,
}
}
func NewPlayer(client *client.Client, playbackCtl *playback.Controller) *TUI {
app := tview.NewApplication()
layout := views.NewLayout(client, playbackCtl, func() {
go app.Draw()
})
help := views.NewHelp()
pages := tview.NewPages()
pages.AddPage("app", layout.GetView(), true, true)
pages.AddPage("help", help.GetView(), true, false)
help.SetKeyPressedFunc(func() {
pages.SwitchToPage("app")
})
app.EnableMouse(true).
SetRoot(pages, true)
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if currentPage, _ := pages.GetFrontPage(); currentPage == "help" {
pages.SwitchToPage("app")
help.GetView().Blur()
layout.GetView().Focus(nil)
return nil
}
if layout.Mode() == views.StatusModeSearch {
return event
}
if event.Rune() == 'q' {
app.Stop()
fmt.Println("Exiting..")
return nil
} else if event.Rune() == 'h' {
return tcell.NewEventKey(tcell.KeyLeft, rune(tcell.KeyLeft), event.Modifiers())
} else if event.Rune() == 'j' {
return tcell.NewEventKey(tcell.KeyDown, rune(tcell.KeyDown), event.Modifiers())
} else if event.Rune() == 'k' {
return tcell.NewEventKey(tcell.KeyUp, rune(tcell.KeyUp), event.Modifiers())
} else if event.Rune() == 'l' {
return tcell.NewEventKey(tcell.KeyRight, rune(tcell.KeyRight), event.Modifiers())
} else if event.Rune() == '?' {
pages.SwitchToPage("help")
layout.GetView().Blur()
go app.Draw()
}
return event
})
app.SetAfterDrawFunc(func(screen tcell.Screen) {
layout.Update()
})
app.GetFocus().Blur()
//app.SetFocus(layout.GetView())
return &TUI{
app: app,
layout: layout,
client: client,
playbackCtl: playbackCtl,
}
}
func (t *TUI) Run() error {
return t.app.Run()
}

View file

@ -0,0 +1,73 @@
package views
import (
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/delucks/go-subsonic"
"github.com/rivo/tview"
)
var _ View = &albums{}
type albums struct {
view *tview.Table
client *client.Client
albums []*subsonic.AlbumID3
callback func(albumID string)
}
func NewAlbums(client *client.Client) *albums {
list := tview.NewTable()
list.SetBackgroundColor(config.ColorBackground)
list.SetTitle("Albums [2]")
list.SetBorder(true)
resp, _ := client.GetAlbums()
obj := &albums{
view: list,
client: client,
albums: resp,
}
list.SetSelectedFunc(func(row, column int) {
obj.callback(obj.albums[row].ID)
})
list.SetFocusFunc(func() {
list.SetBorderColor(config.ColorSelectedBoarder)
list.SetSelectable(true, false)
})
list.SetBlurFunc(func() {
list.SetBorderColor(config.ColorBluredBoarder)
list.SetSelectable(false, false)
})
obj.Update()
return obj
}
func (a *albums) SetAlbums(al []*subsonic.AlbumID3) {
a.albums = al
a.Update()
}
func (a *albums) Update() {
a.view.Clear()
for i, pl := range a.albums {
title := tview.NewTableCell(pl.Name).SetExpansion(1).SetMaxWidth(15)
artist := tview.NewTableCell(pl.Artist).SetExpansion(1).SetAlign(tview.AlignRight)
a.view.SetCell(i, 0, title)
a.view.SetCell(i, 1, artist)
}
}
func (a *albums) SetCallback(f func(albumID string)) {
a.callback = f
}
func (a *albums) GetView() tview.Primitive {
return a.view
}

View file

@ -0,0 +1,70 @@
package views
import (
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/delucks/go-subsonic"
"github.com/rivo/tview"
)
var _ View = &artists{}
type artists struct {
view *tview.Table
client *client.Client
artists []*subsonic.ArtistID3
selectArtistFunc func(artistId string)
openArtistFunc func(artistId string)
}
func NewArtists(client *client.Client) *artists {
list := tview.NewTable()
list.SetBackgroundColor(config.ColorBackground)
list.SetTitle("Artists [1]")
list.SetBorder(true)
list.SetFocusFunc(func() {
list.SetBorderColor(config.ColorSelectedBoarder)
list.SetSelectable(true, false)
})
list.SetBlurFunc(func() {
list.SetBorderColor(config.ColorBluredBoarder)
list.SetSelectable(false, false)
})
arts, _ := client.GetArtists()
for i, artist := range arts {
cell := tview.NewTableCell(artist.Name).SetExpansion(1)
list.SetCell(i, 0, cell)
// list.AddItem(artist.Name, fmt.Sprintf("%s", artist.Name), '0', nil)
}
resp := &artists{
view: list,
client: client,
artists: arts,
}
list.SetSelectedFunc(func(row, column int) {
resp.openArtistFunc(resp.artists[row].ID)
})
return resp
}
func (a *artists) SetSelectArtistFunc(f func(artistId string)) {
a.selectArtistFunc = f
}
func (a *artists) SetOpenArtistFunc(f func(artistId string)) {
a.openArtistFunc = f
}
func (a *artists) Update() {
}
func (a *artists) GetView() tview.Primitive {
return a.view
}

View file

@ -0,0 +1,21 @@
package views
import (
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
func NewButton(label string) *tview.Button {
style := tcell.Style{}
inactiveS := style.Background(config.ColorButtonBg).
Foreground(config.ColorButtonTxt).Bold(true)
activeS := style.Background(config.ColorButtonSelectedBg).
Foreground(config.ColorButtonSelectedTxt).Bold(true).Underline(true)
b := tview.NewButton(label)
b.SetStyle(inactiveS)
b.SetActivatedStyle(activeS)
return b
}

113
internal/tui/views/help.go Normal file
View file

@ -0,0 +1,113 @@
package views
import (
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/rivo/tview"
)
var _ View = &help{}
type help struct {
view *tview.Flex
keyPressedFunc func()
}
type keyMap struct {
key string
description string
}
var keyMaps = []keyMap{
{
"Arrows", "Navigation",
},
{
"h, j, k, l", "Navigation. Use [shift] for moving panes",
},
{
"g", "Jump to top",
},
{
"G", "Jump to bottom",
},
{
"p", "Toggle Play/Pause",
},
{
"s", "Stop",
},
{
"n", "Play next song",
},
{
"N", "Play previous song",
},
{
"c", "Stop and clear queue",
},
{
"r", "Start song radio",
},
{
"/", "Search",
},
{
"q", "Quit",
},
}
func NewHelp() *help {
h := &help{}
view := tview.NewTable()
view.SetBackgroundColor(config.ColorBackground)
height := 16
width := 100
view.SetBorder(true)
view.SetTitle(" Keybindings ")
view.SetTitleAlign(tview.AlignCenter)
for i, km := range keyMaps {
odd := i%2 != 0
txtColor := config.ColorText
if odd {
txtColor = config.ColorTextAccent
}
keyCell := tview.NewTableCell(km.key).
SetExpansion(1).
SetAlign(tview.AlignCenter).
SetTextColor(txtColor)
descCell := tview.NewTableCell(km.description).
SetExpansion(1).
SetAlign(tview.AlignCenter).
SetTextColor(txtColor)
view.SetCell(i, 0, keyCell)
view.SetCell(i, 1, descCell)
}
innerFlex := tview.NewFlex().SetDirection(tview.FlexRow).
AddItem(EmptyBox, 0, 1, false).
AddItem(view, height, 1, true).
AddItem(EmptyBox, 0, 1, false)
innerFlex.SetBackgroundColor(config.ColorBackground)
wrapper := tview.NewFlex().
AddItem(EmptyBox, 0, 1, false).
AddItem(innerFlex, width, 1, true).
AddItem(EmptyBox, 0, 1, false)
wrapper.SetBackgroundColor((config.ColorBackground))
h.view = wrapper
return h
}
func (h *help) GetView() tview.Primitive {
return h.view
}
func (h *help) Update() {
}
func (h *help) SetKeyPressedFunc(f func()) {
h.keyPressedFunc = f
}

View file

@ -0,0 +1,398 @@
package views
import (
"time"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"git.dayanhub.com/sagi/subsonic-tui/internal/playback"
"github.com/delucks/go-subsonic"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
var _ View = &layout{}
type layout struct {
view *tview.Pages
player View
currentFocusedView tview.Primitive
smallView *tview.Flex
largeView *tview.Grid
status *statusLine
mainView *main
}
func NewLayout(client *client.Client, playbackCtl *playback.Controller, refreshUI func()) *layout {
layout := &layout{}
largeView := tview.NewGrid().SetRows(0, 4, 1)
largeView.SetBackgroundColor(config.ColorBackground)
smallView := tview.NewFlex().SetDirection(tview.FlexRow)
smallView.SetBackgroundColor(config.ColorBackground)
layout.largeView = largeView
layout.smallView = smallView
pages := tview.NewPages()
pages.SetBackgroundColor(config.ColorBackground)
// Status / command / search
statusLine := NewStatusLine()
layout.status = statusLine
// Side Panel (Artist/Albums/Playlist)
albums := NewAlbums(client)
artists := NewArtists(client)
playlists := NewPlaylists(client)
sidePanel := tview.NewGrid().SetRows(0, 0, 0)
sidePanel.AddItem(artists.GetView(), 0, 0, 1, 1, 0, 0, false)
sidePanel.AddItem(albums.GetView(), 1, 0, 1, 1, 0, 0, false)
sidePanel.AddItem(playlists.GetView(), 2, 0, 1, 1, 0, 0, false)
// main pane
main := NewMainView(client, statusLine.Log)
layout.mainView = main
// Queue
queue := NewQueue()
// Main view
mainView := tview.NewFlex()
mainView.SetBackgroundColor(config.ColorBackground)
mainView.AddItem(sidePanel, 0, 1, false)
mainView.AddItem(main.GetView(), 0, 2, false)
mainView.AddItem(queue.GetView(), 0, 1, false)
largeView.AddItem(mainView, 0, 0, 1, 3, 0, 0, false)
// Player
player := NewPlayer(client)
largeView.AddItem(player.GetView(), 1, 0, 1, 3, 0, 0, false)
// Add status line
largeView.AddItem(statusLine.GetView(), 2, 0, 1, 3, 0, 0, false)
// Callbacks
artists.SetSelectArtistFunc(func(artistId string) {
artists.view.Blur()
statusLine.Log("Fetching artist's albums...")
go func() {
a, _ := client.GetArtist(artistId)
albums.SetAlbums(a.Album)
albums.GetView().Focus(nil)
refreshUI()
}()
})
artists.SetOpenArtistFunc(func(artistId string) {
artists.view.Blur()
statusLine.Log("Fetching artists...")
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
go func() {
a, _ := client.GetArtist(artistId)
main.SetArtist(a)
main.GetView().Focus(nil)
refreshUI()
}()
})
albums.SetCallback(func(albumID string) {
albums.view.Blur()
statusLine.Log("Fetching album...")
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
go func() {
a, _ := client.GetAlbum(albumID)
main.SetAlbum(a)
main.view.Focus(nil)
refreshUI()
}()
})
playlists.SetCallback(func(p *subsonic.Playlist) {
playlists.view.Blur()
statusLine.Log("Fetching playlist...")
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
go func() {
playlist, _ := client.GetPlaylist(p.ID)
main.SetPlaylist(playlist)
main.view.Focus(nil)
refreshUI()
}()
})
main.SetPlayAllFunc(func(songs ...*subsonic.Child) {
statusLine.Log("Loaded #%d songs.", len(songs))
playbackCtl.SetQueue(songs)
queue.Update(songs, playbackCtl.GetQueuePosition())
})
main.SetPlayAddSongFunc(func(song ...*subsonic.Child) {
statusLine.Log("Added #%d songs to queue.", len(song))
playbackCtl.AddToQueue(song)
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
})
playbackCtl.SetSongElapsedFunc(func(song *subsonic.Child, elapsed time.Duration) {
player.SetSongInfo(song)
player.UpdateProgress(elapsed)
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
refreshUI()
})
playbackCtl.SetSongEndedFunc(func(song *subsonic.Child) {
statusLine.Log("")
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
if config.ScrobbleEnabled() {
// Scrobble
_ = client.Scrobble(song.ID)
}
})
queue.SetPlayFunc(func(position int) {
playbackCtl.SetQueuePosition(position)
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
})
statusLine.SetOnUpdateFunc(func() {
refreshUI()
})
statusLine.SetSearchFunc(func(quary string) {
if len(quary) == 0 {
layout.currentFocusedView.Focus(nil)
statusLine.Log("Search canceled")
return
}
// Search...
statusLine.Log("Searching for '%s'....", quary)
statusLine.view.Blur()
go func() {
result, _ := client.Search(quary)
layout.currentFocusedView.Blur()
main.SetSearch(result, quary)
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
refreshUI()
}()
})
// Key Bindings
pages.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if statusLine.Mode() == StatusModeSearch {
return event
}
if event.Rune() == '1' {
// Focus Artists
artists.view.Blur()
albums.view.Blur()
playlists.view.Blur()
main.view.Blur()
queue.view.Blur()
artists.view.Focus(nil)
layout.currentFocusedView = artists.GetView()
layout.rebuildSmallView()
return nil
} else if event.Rune() == '2' {
// Focus Albums
artists.view.Blur()
albums.view.Blur()
playlists.view.Blur()
main.view.Blur()
queue.view.Blur()
albums.view.Focus(nil)
layout.currentFocusedView = albums.GetView()
layout.rebuildSmallView()
return nil
} else if event.Rune() == '3' {
// Focus Playlists
artists.view.Blur()
albums.view.Blur()
playlists.view.Blur()
main.view.Blur()
queue.view.Blur()
playlists.view.Focus(nil)
layout.currentFocusedView = playlists.GetView()
layout.rebuildSmallView()
return nil
} else if event.Rune() == '`' {
// Focus Songs
artists.view.Blur()
albums.view.Blur()
playlists.view.Blur()
main.view.Blur()
queue.view.Blur()
main.view.Focus(nil)
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
return nil
} else if event.Rune() == '4' {
// Focus Queue
artists.view.Blur()
albums.view.Blur()
playlists.view.Blur()
main.view.Blur()
queue.view.Blur()
queue.view.Focus(nil)
layout.currentFocusedView = queue.GetView()
layout.rebuildSmallView()
return nil
} else if event.Rune() == 'n' {
playbackCtl.Next()
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
return nil
} else if event.Rune() == 'N' {
playbackCtl.Prev()
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
return nil
} else if event.Rune() == 's' {
playbackCtl.Stop()
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
return nil
} else if event.Rune() == 'p' {
if playbackCtl.State() == playback.PlaybackStateStopped {
song := playbackCtl.GetCurrentSong()
if song != nil {
playbackCtl.Play(song)
}
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
return nil
}
playbackCtl.TogglePlayPause()
return nil
} else if event.Rune() == 'c' {
playbackCtl.ClearQueue()
queue.Update(playbackCtl.GetQueue(), playbackCtl.GetQueuePosition())
return nil
} else if event.Rune() == '/' {
layout.currentFocusedView.Blur()
statusLine.Search()
refreshUI()
return nil
} else if event.Rune() == 'L' {
if layout.currentFocusedView == albums.GetView() {
layout.currentFocusedView.Blur()
main.view.Focus(nil)
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == artists.GetView() {
layout.currentFocusedView.Blur()
main.view.Focus(nil)
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == playlists.GetView() {
layout.currentFocusedView.Blur()
main.view.Focus(nil)
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == main.GetView() {
layout.currentFocusedView.Blur()
queue.view.Focus(nil)
layout.currentFocusedView = queue.GetView()
layout.rebuildSmallView()
}
} else if event.Rune() == 'H' {
if layout.currentFocusedView == queue.GetView() {
layout.currentFocusedView.Blur()
main.view.Focus(nil)
layout.currentFocusedView = main.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == main.GetView() {
layout.currentFocusedView.Blur()
artists.view.Focus(nil)
layout.currentFocusedView = artists.GetView()
layout.rebuildSmallView()
}
} else if event.Rune() == 'J' {
if layout.currentFocusedView == albums.GetView() {
layout.currentFocusedView.Blur()
playlists.view.Focus(nil)
layout.currentFocusedView = playlists.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == artists.GetView() {
layout.currentFocusedView.Blur()
albums.view.Focus(nil)
layout.currentFocusedView = albums.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == playlists.GetView() {
layout.currentFocusedView.Blur()
artists.view.Focus(nil)
layout.currentFocusedView = artists.GetView()
layout.rebuildSmallView()
}
} else if event.Rune() == 'K' {
if layout.currentFocusedView == albums.GetView() {
layout.currentFocusedView.Blur()
artists.view.Focus(nil)
layout.currentFocusedView = artists.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == artists.GetView() {
layout.currentFocusedView.Blur()
playlists.view.Focus(nil)
layout.currentFocusedView = playlists.GetView()
layout.rebuildSmallView()
} else if layout.currentFocusedView == playlists.GetView() {
layout.currentFocusedView.Blur()
albums.view.Focus(nil)
layout.currentFocusedView = albums.GetView()
layout.rebuildSmallView()
}
}
return event
})
largeView.SetFocusFunc(func() {
largeView.Blur()
layout.currentFocusedView.Focus(nil)
})
smallView.SetFocusFunc(func() {
smallView.Blur()
layout.currentFocusedView.Focus(nil)
})
statusLine.Log("Press '?' for help")
pages.AddPage("small", smallView, true, false)
pages.AddPage("large", largeView, true, true)
layout.view = pages
layout.player = player
//Auto focus on artists
artists.GetView().Focus(nil)
layout.currentFocusedView = artists.GetView()
layout.rebuildSmallView()
return layout
}
func (l *layout) rebuildSmallView() {
l.smallView.Clear()
l.smallView.AddItem(l.currentFocusedView, 0, 1, false)
l.smallView.AddItem(l.player.GetView(), 4, 0, false)
l.smallView.AddItem(l.status.GetView(), 1, 0, false)
}
func (l *layout) Mode() Statusmode {
return l.status.Mode()
}
func (l *layout) GetView() tview.Primitive {
return l.view
}
func (l *layout) Update() {
_, _, w, h := l.view.GetRect()
page, _ := l.view.GetFrontPage()
smallView := w < 100 || h < 30
if smallView {
if page != "small" {
l.mainView.SetMiniView(true)
go l.view.SwitchToPage("small")
return
}
} else {
if page != "large" {
l.mainView.SetMiniView(false)
go l.view.SwitchToPage("large")
return
}
}
l.player.Update()
}

View file

@ -0,0 +1,73 @@
package views
import (
"github.com/rivo/tview"
)
var _ View = &login{}
const (
ViewEventLoginClicked = "login-clicked"
)
type login struct {
view *tview.Flex
form *tview.Form
username string
password string
url string
loginFunc func(u, p, url string)
exitFunc func()
}
func (l *login) GetView() tview.Primitive {
return l.view
}
func (l *login) onFormLogin() {
l.loginFunc(l.username, l.password, l.url)
}
func NewLoginView(loginFunc func(u, p, url string), exitFunc func()) View {
l := &login{}
l.loginFunc = loginFunc
l.exitFunc = exitFunc
form := tview.NewForm().
AddInputField("Server URL", "https://", 20, nil, func(text string) {
l.url = text
}).
AddInputField("Username", "", 20, nil, func(text string) {
l.username = text
}).
AddPasswordField("Password", "", 20, '*', func(text string) {
l.password = text
}).
AddButton("Login", l.onFormLogin).
AddButton("Quit", func() {
l.exitFunc()
})
form.SetBorder(true).SetTitle(" Login ").SetTitleAlign(tview.AlignCenter)
width := 50
height := 20
wrapper := tview.NewFlex().
AddItem(nil, 0, 1, false).
AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
AddItem(nil, 0, 1, false).
AddItem(form, height, 1, true).
AddItem(nil, 0, 1, false), width, 1, true).
AddItem(nil, 0, 1, false)
l.view = wrapper
l.form = form
l.GetView().Focus(func(p tview.Primitive) {})
form.SetFocus(0)
return l
}
func (l *login) Update() {
}

616
internal/tui/views/main.go Normal file
View file

@ -0,0 +1,616 @@
package views
import (
"fmt"
"strconv"
"time"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/common"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/delucks/go-subsonic"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
var _ View = &main{}
type mainviewmode int
const (
mainModeAlbum mainviewmode = iota
mainModePlaylist mainviewmode = iota
mainModeArtist mainviewmode = iota
mainModeSearch mainviewmode = iota
)
type main struct {
view *tview.Flex
client *client.Client
mode mainviewmode
query string
miniView bool
album *subsonic.AlbumID3
searchResult *subsonic.SearchResult3
playlist *subsonic.Playlist
songList *tview.Table
artist *subsonic.ArtistID3
artistInfo *subsonic.ArtistInfo2
playAllFunc func(song ...*subsonic.Child)
addSongsFunc func(song ...*subsonic.Child)
log func(format string, a ...any)
}
func NewMainView(client *client.Client, log func(format string, a ...any)) *main {
playlistAlbum := &main{
client: client,
log: log,
}
flex := tview.NewFlex().SetDirection(tview.FlexRow)
flex.SetBackgroundColor(config.ColorBackground)
flex.SetTitle("Subsonic TUI [`]")
flex.SetBorder(true)
flex.SetFocusFunc(func() {
flex.SetBorderColor(config.ColorSelectedBoarder)
if playlistAlbum.songList != nil {
//playlistAlbum.view.Blur()
playlistAlbum.songList.Focus(nil)
}
})
flex.SetBlurFunc(func() {
flex.SetBorderColor(config.ColorBluredBoarder)
if playlistAlbum.songList != nil {
playlistAlbum.songList.Blur()
}
})
playlistAlbum.view = flex
// Empty Box for starters...
playlistAlbum.view.AddItem(EmptyBox, 0, 1, false)
return playlistAlbum
}
func (m *main) SetMiniView(mini bool) {
m.miniView = mini
}
func (m *main) SetAlbum(album *subsonic.AlbumID3) {
m.mode = mainModeAlbum
m.album = album
m.Update()
m.log("")
}
func (m *main) SetPlaylist(playlist *subsonic.Playlist) {
m.mode = mainModePlaylist
m.playlist = playlist
m.Update()
m.log("")
}
func (m *main) SetArtist(artist *subsonic.ArtistID3) {
m.mode = mainModeArtist
m.artist = artist
info, _ := m.client.GetArtistInfo(artist.ID)
m.artistInfo = info
m.Update()
m.log("")
}
func (m *main) SetSearch(result *subsonic.SearchResult3, query string) {
m.mode = mainModeSearch
m.searchResult = result
m.query = query
m.Update()
m.log("Found #%d artists, #%d albums and #%d songs",
len(result.Artist),
len(result.Album),
len(result.Song),
)
}
func (m *main) drawPlaylist() {
subtitle := fmt.Sprintf("%s\n\nCreated by: %s | %s", m.playlist.Comment, m.playlist.Owner, time.Duration(m.playlist.Duration*int(time.Second)).String())
m.populateHeader(m.playlist.Name, subtitle, m.playlist.Duration, m.playlist.CoverArt)
playBtn := m.drawPlaylistAlbumButtons(m.playlist.Entry)
m.populateSongs(m.playlist.Entry, playBtn)
}
func (m *main) drawAlbum() {
subtitle := fmt.Sprintf("%s\n\n%d | %s", m.album.Artist, m.album.Year, time.Duration(m.album.Duration*int(time.Second)).String())
m.populateHeader(m.album.Name, subtitle, m.album.Duration, m.album.CoverArt)
playBtn := m.drawPlaylistAlbumButtons(m.album.Song)
m.populateSongs(m.album.Song, playBtn)
}
func (m *main) drawArtist() {
m.populateHeader(m.artist.Name, m.artistInfo.Biography, 0, m.artist.CoverArt)
btn := m.drawArtistButtons()
m.populateAlbums(btn)
}
func (m *main) drawSearch() {
sub := fmt.Sprintf("Query: %s", m.query)
m.populateHeader("Search Results", sub, 0, "")
m.populateSearchResults()
}
func (m *main) Update() {
m.view.Clear()
switch m.mode {
case mainModeAlbum:
m.drawAlbum()
case mainModePlaylist:
m.drawPlaylist()
case mainModeArtist:
m.drawArtist()
case mainModeSearch:
m.drawSearch()
}
m.songList.Focus(nil)
}
func (m *main) drawArtistButtons() *tview.Button {
// Add buttons: Radio
songs, _ := m.client.GetTopSongs(m.artist.Name, 10)
f := tview.NewFlex()
f.SetBackgroundColor(config.ColorBackground)
f.SetBorderPadding(0, 0, 2, 2)
// Buttons
radio := NewButton("Radio")
top10 := NewButton("Top 10")
// Button callbacks
top10.SetSelectedFunc(func() {
top10.Blur()
m.log("Playing %s's top 10 songs", m.artist.Name)
m.playAllFunc(songs...)
m.songList.Focus(nil)
})
radio.SetSelectedFunc(func() {
radio.Blur()
m.log("Generating %s's radio", m.artist.Name)
go func() {
radioSongs := []*subsonic.Child{}
if config.ExperimentalRadioAlgo() {
radioSongs, _ = m.client.GetExperimentalArtistRadio(m.artist, m.artistInfo, config.MaxRadioSongs())
}
if len(radioSongs) == 0 {
radioSongs, _ = m.client.GetSimilarSongs(m.artist.ID, config.MaxRadioSongs())
}
common.ShuffleSlice(radioSongs)
m.playAllFunc(radioSongs...)
}()
m.songList.Focus(nil)
})
radio.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyDown:
radio.Blur()
m.songList.Focus(nil)
return nil
case tcell.KeyRight:
radio.Blur()
top10.Focus(nil)
return nil
}
return event
})
top10.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyDown:
top10.Blur()
m.songList.Focus(nil)
return nil
case tcell.KeyLeft:
top10.Blur()
radio.Focus(nil)
return nil
}
return event
})
f.AddItem(radio, 0, 1, false)
f.AddItem(EmptyBox, 0, 1, false)
if len(songs) > 0 {
f.AddItem(top10, 0, 1, false)
}
f.AddItem(EmptyBox, 0, 1, false)
// Add the buttons to the view
m.view.AddItem(f, 1, 0, false)
// Margin bottom of 1 line
m.view.AddItem(EmptyBox, 1, 0, false)
return radio
}
func (m *main) populateAlbums(btn *tview.Button) {
table := tview.NewTable()
table.SetBackgroundColor(config.ColorBackground)
table.SetWrapSelection(true, false)
for i, album := range m.artist.Album {
year := tview.NewTableCell(fmt.Sprintf("%d", album.Year)).SetTextColor(config.ColorTextAccent)
name := tview.NewTableCell(album.Name).SetExpansion(2).SetAlign(tview.AlignCenter)
d := time.Second * time.Duration(album.Duration)
duration := tview.NewTableCell(d.String()).SetAlign(tview.AlignRight).SetExpansion(1)
table.SetCell(i, 0, year)
table.SetCell(i, 1, name)
table.SetCell(i, 2, duration)
}
table.SetFocusFunc(func() {
m.view.SetBorderColor(config.ColorSelectedBoarder)
table.SetSelectable(true, false)
})
table.SetBlurFunc(func() {
m.view.SetBorderColor(config.ColorBluredBoarder)
table.SetSelectable(false, false)
})
table.SetSelectedFunc(func(row, column int) {
alb, _ := m.client.GetAlbum(m.artist.Album[row].ID)
m.SetAlbum(alb)
m.view.Focus(nil)
})
table.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
row, _ := m.songList.GetSelection()
if row == 0 && event.Key() == tcell.KeyUp {
table.Blur()
m.view.SetBorderColor(config.ColorSelectedBoarder)
btn.Focus(nil)
return nil
}
return event
})
m.songList = table
m.view.AddItem(table, 0, 1, false)
}
func (m *main) drawPlaylistAlbumButtons(songs []*subsonic.Child) *tview.Button {
// Add buttons: Play | Shuffle | Add to queue
f := tview.NewFlex()
f.SetBackgroundColor(config.ColorBackground)
f.SetBorderPadding(0, 0, 2, 2)
// Buttons
play := NewButton("Play")
shuffle := NewButton("Shuffle")
queue := NewButton("Queue")
artist := NewButton("Artist")
// Button callbacks
play.SetSelectedFunc(func() {
play.Blur()
m.playAllFunc(songs...)
m.songList.Focus(nil)
})
play.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyLeft:
play.Blur()
artist.Focus(nil)
return nil
case tcell.KeyRight:
play.Blur()
shuffle.Focus(nil)
return nil
case tcell.KeyDown:
play.Blur()
m.songList.Focus(nil)
return nil
}
return event
})
shuffle.SetSelectedFunc(func() {
shuffle.Blur()
cpy := make([]*subsonic.Child, len(songs))
copy(cpy, songs)
common.ShuffleSlice(cpy)
m.playAllFunc(cpy...)
m.songList.Focus(nil)
})
shuffle.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyLeft:
shuffle.Blur()
play.Focus(nil)
return nil
case tcell.KeyRight:
shuffle.Blur()
queue.Focus(nil)
return nil
case tcell.KeyDown:
shuffle.Blur()
m.songList.Focus(nil)
return nil
}
return event
})
queue.SetSelectedFunc(func() {
queue.Blur()
m.addSongsFunc(songs...)
m.songList.Focus(nil)
})
queue.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyLeft:
queue.Blur()
shuffle.Focus(nil)
return nil
case tcell.KeyRight:
queue.Blur()
artist.Focus(nil)
return nil
case tcell.KeyDown:
queue.Blur()
m.songList.Focus(nil)
return nil
}
return event
})
artist.SetSelectedFunc(func() {
artist.Blur()
ar, _ := m.client.GetArtist(m.album.ArtistID)
m.SetArtist(ar)
m.songList.Focus(nil)
})
artist.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyLeft:
artist.Blur()
queue.Focus(nil)
return nil
case tcell.KeyRight:
artist.Blur()
play.Focus(nil)
return nil
case tcell.KeyDown:
artist.Blur()
m.songList.Focus(nil)
return nil
}
return event
})
f.AddItem(play, 0, 1, true)
f.AddItem(EmptyBox, 0, 1, false)
f.AddItem(shuffle, 0, 1, false)
f.AddItem(EmptyBox, 0, 1, false)
f.AddItem(queue, 0, 1, false)
f.AddItem(EmptyBox, 0, 1, false)
f.AddItem(artist, 0, 1, false)
// Add the buttons to the view
m.view.AddItem(f, 1, 0, false)
// Margin bottom of 1 line
m.view.AddItem(EmptyBox, 1, 0, false)
return play
}
func (m *main) populateSongs(songs []*subsonic.Child, play *tview.Button) {
table := tview.NewTable()
table.SetBackgroundColor(config.ColorBackground)
table.SetWrapSelection(true, false)
for i, song := range songs {
num := tview.NewTableCell(fmt.Sprintf("%d", i+1)).SetTextColor(config.ColorTextAccent)
title := tview.NewTableCell(song.Title).SetMaxWidth(15).SetExpansion(2)
artist := tview.NewTableCell(song.Artist).SetMaxWidth(15).SetExpansion(1)
d := time.Second * time.Duration(song.Duration)
duration := tview.NewTableCell(d.String()).SetAlign(tview.AlignRight).SetExpansion(1)
table.SetCell(i, 0, num)
table.SetCell(i, 1, title)
table.SetCell(i, 2, artist)
table.SetCell(i, 3, duration)
}
m.songList = table
table.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
// on first line and pressing up -> play button
row, _ := table.GetSelection()
if row == 0 && event.Key() == tcell.KeyUp {
table.Blur()
m.view.SetBorderColor(config.ColorSelectedBoarder)
play.Focus(nil)
return nil
} else if event.Rune() == 'r' {
song := songs[row]
m.log("Generating song (%s) radio....", song.Title)
go func() {
radioSongs, _ := m.client.GetSimilarSongs(song.ID, config.MaxRadioSongs())
m.playAllFunc(radioSongs...)
}()
}
return event
})
table.SetFocusFunc(func() {
m.view.SetBorderColor(config.ColorSelectedBoarder)
table.SetSelectable(true, false)
})
table.SetBlurFunc(func() {
m.view.SetBorderColor(config.ColorBluredBoarder)
table.SetSelectable(false, false)
})
m.songList.SetSelectedFunc(func(row, column int) {
m.addSongsFunc(songs[row])
})
m.view.AddItem(table, 0, 1, false)
}
func (m *main) populateSearchResults() {
table := tview.NewTable()
table.SetBackgroundColor(config.ColorBackground)
table.SetWrapSelection(true, false)
row := 0
lastArtist := 0
lastAlbum := 0
// Artists
if len(m.searchResult.Artist) > 0 {
// Header
header := tview.NewTableCell("Artists").SetSelectable(false)
table.SetCell(row, 0, header)
row++
//List
for i, artist := range m.searchResult.Artist {
index := tview.NewTableCell(fmt.Sprintf("%d", i+1)).
SetTextColor(config.ColorTextAccent)
a := tview.NewTableCell(artist.Name).SetExpansion(2).SetMaxWidth(15)
acount := tview.NewTableCell(fmt.Sprintf("%d Albums", artist.AlbumCount)).
SetExpansion(1).SetAlign(tview.AlignRight).SetMaxWidth(15)
table.SetCell(row, 0, index)
table.SetCell(row, 1, a)
table.SetCell(row, 2, acount)
row++
}
lastArtist = row
}
// Albums
if len(m.searchResult.Album) > 0 {
// Header
header := tview.NewTableCell("Albums").SetSelectable(false)
table.SetCell(row, 0, header)
row++
//List
for i, album := range m.searchResult.Album {
index := tview.NewTableCell(fmt.Sprintf("%d", i+1)).
SetTextColor(config.ColorTextAccent)
title := tview.NewTableCell(album.Name).SetExpansion(2).SetMaxWidth(15)
artist := tview.NewTableCell(album.Artist).
SetExpansion(1).SetAlign(tview.AlignRight).SetMaxWidth(15)
table.SetCell(row, 0, index)
table.SetCell(row, 1, title)
table.SetCell(row, 2, artist)
row++
}
lastAlbum = row
}
// Songs
if len(m.searchResult.Song) > 0 {
// Header
header := tview.NewTableCell("Songs").SetSelectable(false)
table.SetCell(row, 0, header)
row++
//List
for i, song := range m.searchResult.Song {
index := tview.NewTableCell(fmt.Sprintf("%d", i+1)).
SetTextColor(config.ColorTextAccent)
title := tview.NewTableCell(song.Title).SetExpansion(2).SetMaxWidth(15)
artist := tview.NewTableCell(song.Artist).
SetExpansion(1).SetAlign(tview.AlignRight).SetMaxWidth(15)
table.SetCell(row, 0, index)
table.SetCell(row, 1, title)
table.SetCell(row, 2, artist)
row++
}
}
m.songList = table
table.SetFocusFunc(func() {
m.view.SetBorderColor(config.ColorSelectedBoarder)
table.SetSelectable(true, false)
})
table.SetBlurFunc(func() {
m.view.SetBorderColor(config.ColorBluredBoarder)
table.SetSelectable(false, false)
})
table.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
row, _ := table.GetSelection()
if row <= lastAlbum {
return event
}
if event.Rune() != 'r' {
return event
}
cell := table.GetCell(row, 0)
index, err := strconv.Atoi(cell.Text)
if err != nil {
return nil
}
song := m.searchResult.Song[index-1]
m.log("Generating song (%s) radio....", song.Title)
go func() {
radioSongs, _ := m.client.GetSimilarSongs(song.ID, config.MaxRadioSongs())
m.playAllFunc(radioSongs...)
}()
return nil
})
m.songList.SetSelectedFunc(func(row, column int) {
cell := table.GetCell(row, 0)
index, err := strconv.Atoi(cell.Text)
if err != nil {
return
}
if row <= lastArtist {
artist, _ := m.client.GetArtist(m.searchResult.Artist[index-1].ID)
m.SetArtist(artist)
} else if lastArtist < row && row <= lastAlbum {
album, _ := m.client.GetAlbum(m.searchResult.Album[index-1].ID)
m.SetAlbum(album)
} else {
m.addSongsFunc(m.searchResult.Song[index-1])
}
})
m.view.AddItem(table, 0, 1, false)
}
func (m *main) populateHeader(title, subtitle string,
duration int, coverArtID string) {
header := tview.NewFlex()
header.SetBackgroundColor(config.ColorBackground)
art := tview.NewImage()
art.SetBackgroundColor(config.ColorBackground)
img, _ := m.client.GetCoverArt(coverArtID)
art.SetImage(img)
t := tview.NewTextView().
SetTextColor(config.ColorTextAccent).
SetTextAlign(tview.AlignCenter).
SetText(title)
t.SetBackgroundColor(config.ColorBackground)
s := tview.NewTextView().
SetTextColor(config.ColorText).
SetTextAlign(tview.AlignCenter).
SetText(subtitle).SetWordWrap(true)
s.SetBackgroundColor(config.ColorBackground)
g := tview.NewFlex().SetDirection(tview.FlexRow)
g.SetBackgroundColor(config.ColorBackground)
g.AddItem(EmptyBox, 1, 1, false)
g.AddItem(t, 1, 1, false)
g.AddItem(s, 0, 1, false)
header.AddItem(art, 0, 1, false)
header.AddItem(g, 0, 3, false)
size := 6
if m.miniView {
size = 4
}
m.view.AddItem(header, size, 1, false)
// Margin bottom of 1 line
if !m.miniView {
m.view.AddItem(EmptyBox, 1, 0, false)
}
}
func (m *main) SetPlayAllFunc(f func(song ...*subsonic.Child)) {
m.playAllFunc = f
}
func (m *main) SetPlayAddSongFunc(f func(song ...*subsonic.Child)) {
m.addSongsFunc = f
}
func (m *main) GetView() tview.Primitive {
return m.view
}

View file

@ -0,0 +1,117 @@
package views
import (
"fmt"
"time"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/delucks/go-subsonic"
"github.com/rivo/tview"
)
var _ View = &player{}
type player struct {
client *client.Client
view tview.Primitive
grid *tview.Grid
artwork *tview.Image
progress *tview.Flex
songInfo *tview.TextView
song *subsonic.Child
}
func NewPlayer(client *client.Client) *player {
grid := tview.NewGrid().SetColumns(9, 0)
grid.SetBackgroundColor(config.ColorBackground)
//album art
art := tview.NewImage()
art.SetBackgroundColor(config.ColorBackground)
grid.AddItem(art, 0, 0, 1, 1, 4, 4, false)
// Progress
progress := tview.NewFlex()
progress.SetBackgroundColor(config.ColorBackground)
// Song songInfo
songInfo := tview.NewTextView()
songInfo.SetDynamicColors(true)
songInfo.SetBackgroundColor(config.ColorBackground)
// Info + Progress
songProg := tview.NewFlex().SetDirection(tview.FlexRow)
songProg.AddItem(songInfo, 0, 4, false)
songProg.AddItem(progress, 0, 1, false)
grid.AddItem(songProg, 0, 1, 1, 1, 0, 0, false)
player := &player{
client: client,
view: grid,
artwork: art,
songInfo: songInfo,
grid: grid,
progress: progress,
}
player.SetSongInfo(&subsonic.Child{
Title: "Subsonic TUI",
Album: "MaVeZe",
Artist: "ZeGoomba",
CoverArt: "",
Duration: 0,
})
player.UpdateProgress(time.Duration(0))
return player
}
func (p *player) SetSongInfo(song *subsonic.Child) {
info := fmt.Sprintf("[yellow]Title:[white] %s\n[yellow]Album:[white] %s\n[yellow]Atrists:[white] %s",
song.Title, song.Album, song.Artist)
p.songInfo.SetText(info)
p.song = song
p.LoadAlbumArt(song.CoverArt)
}
func (p *player) LoadAlbumArt(ID string) {
i, _ := p.client.GetCoverArt(ID)
p.artwork.SetImage(i)
}
func (p *player) UpdateProgress(elapsed time.Duration) {
if p.song.Duration == 0 {
// Startup... Show version number
versionInfo := tview.NewTextView().SetText("Version: 0.1")
versionInfo.SetBackgroundColor(config.ColorPlaybackProgressRemaining)
versionInfo.SetTextColor(config.ColorPlaybackProgressElapsed)
p.progress.AddItem(versionInfo, 0, 1, false)
return
}
songDuration := time.Duration(p.song.Duration) * time.Second
overlappedBox := tview.NewTextView()
overlappedBox.SetBackgroundColor(config.ColorPlaybackProgressElapsed)
overlappedBox.SetTextColor(config.ColorPlaybackProgressRemaining)
overlappedBox.SetText(songDuration.String())
remainingBox := tview.NewTextView()
remainingBox.SetBackgroundColor(config.ColorPlaybackProgressRemaining)
remainingBox.SetTextColor(config.ColorPlaybackProgressElapsed)
remainingBox.SetTextAlign(tview.AlignRight)
rm := time.Duration(songDuration.Seconds()-elapsed.Seconds()) * time.Second
remaining := fmt.Sprintf("-%s", rm.String())
remainingBox.SetText(remaining)
p.progress.Clear()
p.progress.AddItem(overlappedBox, 0, int(elapsed.Seconds()), false)
p.progress.AddItem(remainingBox, 0, int(songDuration.Seconds())-int(elapsed.Seconds()), false)
}
func (p *player) GetView() tview.Primitive {
return p.view
}
func (p *player) Update() {
//p.UpdateProgress("00:00", 50)
}

View file

@ -0,0 +1,63 @@
package views
import (
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/delucks/go-subsonic"
"github.com/rivo/tview"
)
var _ View = &playlists{}
type playlists struct {
view *tview.Table
client *client.Client
callback func(playlist *subsonic.Playlist)
}
func NewPlaylists(client *client.Client) *playlists {
obj := &playlists{
client: client,
}
list := tview.NewTable()
list.SetBackgroundColor(config.ColorBackground)
list.SetTitle("Playlists [3]")
list.SetBorder(true)
list.SetFocusFunc(func() {
list.SetBorderColor(config.ColorSelectedBoarder)
list.SetSelectable(true, false)
})
list.SetBlurFunc(func() {
list.SetBorderColor(config.ColorBluredBoarder)
list.SetSelectable(false, false)
})
pls, _ := client.GetPlaylists()
for i, pl := range pls {
cell := tview.NewTableCell(pl.Name).SetExpansion(1)
list.SetCell(i, 0, cell)
}
list.SetSelectedFunc(func(row, column int) {
obj.callback(pls[row])
})
obj.view = list
return obj
}
func (p *playlists) SetCallback(f func(playlist *subsonic.Playlist)) {
p.callback = f
}
func (p *playlists) Update() {
}
func (p *playlists) GetView() tview.Primitive {
return p.view
}

View file

@ -0,0 +1,81 @@
package views
import (
"fmt"
"time"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/delucks/go-subsonic"
"github.com/rivo/tview"
)
type queue struct {
view *tview.Table
playFunc func(index int)
currentSong int
songQueue []*subsonic.Child
}
func NewQueue() *queue {
table := tview.NewTable()
table.SetBackgroundColor(config.ColorBackground)
table.SetTitle("Queue [4]")
table.SetBorder(true)
table.SetFocusFunc(func() {
table.SetBorderColor(config.ColorSelectedBoarder)
})
table.SetBlurFunc(func() {
table.SetBorderColor(config.ColorBluredBoarder)
})
return &queue{
view: table,
currentSong: 0,
}
}
func (q *queue) SetPlayFunc(f func(index int)) {
q.playFunc = f
}
func (q *queue) drawQueue() {
q.view.Clear()
list := q.view
list.SetWrapSelection(true, false)
list.SetSelectable(true, false)
for i, song := range q.songQueue {
isCurrentSong := q.currentSong == i
isPlayed := i < q.currentSong
bgColor := config.ColorBackground
if isCurrentSong {
bgColor = config.ColorQueuePlayingBg
} else if isPlayed {
bgColor = config.ColorQueuePlayedBg
}
num := tview.NewTableCell(fmt.Sprintf("%d", i+1)).SetTextColor(config.ColorTextAccent).SetBackgroundColor(bgColor)
title := tview.NewTableCell(song.Title).SetMaxWidth(15).SetExpansion(2).SetBackgroundColor(bgColor)
artist := tview.NewTableCell(song.Artist).SetMaxWidth(15).SetExpansion(1).SetBackgroundColor(bgColor)
d := time.Second * time.Duration(song.Duration)
duration := tview.NewTableCell(d.String()).SetAlign(tview.AlignRight).SetExpansion(1).SetBackgroundColor(bgColor)
list.SetCell(i, 0, num)
list.SetCell(i, 1, title)
list.SetCell(i, 2, artist)
list.SetCell(i, 3, duration)
}
list.SetSelectedFunc(func(row, column int) {
q.currentSong = row
q.playFunc(row)
})
}
func (q *queue) Update(songs []*subsonic.Child, currentSong int) {
q.songQueue = songs
q.currentSong = currentSong
q.drawQueue()
}
func (q *queue) GetView() tview.Primitive {
return q.view
}

View file

@ -0,0 +1,98 @@
package views
import (
"fmt"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
var _ View = &statusLine{}
type statusLine struct {
view *tview.Flex
mode Statusmode
onUpdateFunc func()
onSearchFunc func(quary string)
}
type Statusmode int
const (
StatusModeLog Statusmode = iota
StatusModeSearch Statusmode = iota
)
func NewStatusLine() *statusLine {
status := tview.NewFlex()
status.SetBackgroundColor(config.ColorBackground)
// Default empty box
status.AddItem(EmptyBox, 0, 1, false)
return &statusLine{
view: status,
mode: StatusModeLog,
}
}
func (s *statusLine) SetSearchFunc(f func(quary string)) {
s.onSearchFunc = f
}
func (s *statusLine) Mode() Statusmode {
return s.mode
}
func (s *statusLine) Search() {
s.mode = StatusModeSearch
s.view.Clear()
label := "Search: "
_, _, w, _ := s.view.GetRect()
query := ""
inputField := tview.NewInputField()
inputField.
SetLabel(label).
SetFieldWidth(w - len(label)).
SetDoneFunc(func(key tcell.Key) {
if key == tcell.KeyEnter {
s.mode = StatusModeLog
s.onSearchFunc(query)
} else if key == tcell.KeyEsc {
s.mode = StatusModeLog
s.onSearchFunc("")
}
}).
SetChangedFunc(func(text string) {
query = text
})
inputField.Focus(nil)
inputField.SetBackgroundColor(config.ColorBackground)
inputField.SetFieldBackgroundColor(config.ColorBackground)
s.view.AddItem(inputField, 0, 1, true)
s.Update()
}
func (s *statusLine) SetOnUpdateFunc(f func()) {
s.onUpdateFunc = f
}
func (s *statusLine) Log(format string, a ...any) {
if s.mode != StatusModeLog {
return
}
str := fmt.Sprintf(format, a...)
s.view.Clear()
txt := tview.NewTextView().SetDynamicColors(true)
txt.SetBackgroundColor(config.ColorBackground)
txt.SetText(str)
s.view.AddItem(txt, 0, 1, false)
s.Update()
}
func (s *statusLine) GetView() tview.Primitive {
return s.view
}
func (s *statusLine) Update() {
s.onUpdateFunc()
}

View file

@ -0,0 +1,15 @@
package views
import (
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"github.com/rivo/tview"
)
type ViewEvent string
var EmptyBox tview.Primitive = tview.NewBox().SetBackgroundColor(config.ColorBackground)
type View interface {
GetView() tview.Primitive
Update()
}

42
main.go Normal file
View file

@ -0,0 +1,42 @@
package main
import (
"fmt"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"git.dayanhub.com/sagi/subsonic-tui/internal/playback"
"git.dayanhub.com/sagi/subsonic-tui/internal/tui"
)
func main() {
defer client.ArtCache.Destroy()
// Create Client
subsonicClient := client.NewClient(config.URL())
err := subsonicClient.Authenticate(config.Username(), config.Password())
if err != nil {
// We need to show Login...
login := tui.NewLogin()
err := login.Run()
if err != nil {
panic(err)
}
}
fmt.Println("Trying to login...")
subsonicClient = client.NewClient(config.URL())
err = subsonicClient.Authenticate(config.Username(), config.Password())
if err != nil {
panic(err)
}
// Saving config - will result in adding new defaults to the file
config.SaveConfig()
playbackCtl := playback.NewController(subsonicClient)
defer playbackCtl.Close()
tui := tui.NewPlayer(subsonicClient, playbackCtl)
if err := tui.Run(); err != nil {
panic(err)
}
}

1
vendor/github.com/creasty/defaults/.gitignore generated vendored Normal file
View file

@ -0,0 +1 @@
.DS_Store

22
vendor/github.com/creasty/defaults/LICENSE generated vendored Normal file
View file

@ -0,0 +1,22 @@
Copyright (c) 2017-present Yuki Iwanaga
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

29
vendor/github.com/creasty/defaults/Makefile generated vendored Normal file
View file

@ -0,0 +1,29 @@
SHELL := /bin/bash -eu -o pipefail
GO_TEST_FLAGS := -v
PACKAGE_DIRS := $(shell go list ./... 2> /dev/null | grep -v /vendor/)
SRC_FILES := $(shell find . -name '*.go' -not -path './vendor/*')
# Tasks
#-----------------------------------------------
.PHONY: lint
lint:
@gofmt -e -d -s $(SRC_FILES) | awk '{ e = 1; print $0 } END { if (e) exit(1) }'
@golangci-lint --disable errcheck,unused run
.PHONY: test
test: lint
@go test $(GO_TEST_FLAGS) $(PACKAGE_DIRS)
.PHONY: ci-test
ci-test: lint
@echo > coverage.txt
@for d in $(PACKAGE_DIRS); do \
go test -coverprofile=profile.out -covermode=atomic -race -v $$d; \
if [ -f profile.out ]; then \
cat profile.out >> coverage.txt; \
rm profile.out; \
fi; \
done

75
vendor/github.com/creasty/defaults/README.md generated vendored Normal file
View file

@ -0,0 +1,75 @@
defaults
========
[![CircleCI](https://circleci.com/gh/creasty/defaults/tree/master.svg?style=svg)](https://circleci.com/gh/creasty/defaults/tree/master)
[![codecov](https://codecov.io/gh/creasty/defaults/branch/master/graph/badge.svg)](https://codecov.io/gh/creasty/defaults)
[![GitHub release](https://img.shields.io/github/release/creasty/defaults.svg)](https://github.com/creasty/defaults/releases)
[![License](https://img.shields.io/github/license/creasty/defaults.svg)](./LICENSE)
Initialize structs with default values
- Supports almost all kind of types
- Scalar types
- `int/8/16/32/64`, `uint/8/16/32/64`, `float32/64`
- `uintptr`, `bool`, `string`
- Complex types
- `map`, `slice`, `struct`
- Nested types
- `map[K1]map[K2]Struct`, `[]map[K1]Struct[]`
- Aliased types
- `time.Duration`
- e.g., `type Enum string`
- Pointer types
- e.g., `*SampleStruct`, `*int`
- Recursively initializes fields in a struct
- Dynamically sets default values by [`defaults.Setter`](./setter.go) interface
- Preserves non-initial values from being reset with a default value
Usage
-----
```go
type Gender string
type Sample struct {
Name string `default:"John Smith"`
Age int `default:"27"`
Gender Gender `default:"m"`
Slice []string `default:"[]"`
SliceByJSON []int `default:"[1, 2, 3]"` // Supports JSON
Map map[string]int `default:"{}"`
MapByJSON map[string]int `default:"{\"foo\": 123}"`
MapOfStruct map[string]OtherStruct
MapOfPtrStruct map[string]*OtherStruct
MapOfStructWithTag map[string]OtherStruct `default:"{\"Key1\": {\"Foo\":123}}"`
Struct OtherStruct `default:"{}"`
StructPtr *OtherStruct `default:"{\"Foo\": 123}"`
NoTag OtherStruct // Recurses into a nested struct by default
OptOut OtherStruct `default:"-"` // Opt-out
}
type OtherStruct struct {
Hello string `default:"world"` // Tags in a nested struct also work
Foo int `default:"-"`
Random int `default:"-"`
}
// SetDefaults implements defaults.Setter interface
func (s *OtherStruct) SetDefaults() {
if defaults.CanUpdate(s.Random) { // Check if it's a zero value (recommended)
s.Random = rand.Int() // Set a dynamic value
}
}
```
```go
obj := &Sample{}
if err := defaults.Set(obj); err != nil {
panic(err)
}
```

244
vendor/github.com/creasty/defaults/defaults.go generated vendored Normal file
View file

@ -0,0 +1,244 @@
package defaults
import (
"encoding"
"encoding/json"
"errors"
"reflect"
"strconv"
"time"
)
var (
errInvalidType = errors.New("not a struct pointer")
)
const (
fieldName = "default"
)
// Set initializes members in a struct referenced by a pointer.
// Maps and slices are initialized by `make` and other primitive types are set with default values.
// `ptr` should be a struct pointer
func Set(ptr interface{}) error {
if reflect.TypeOf(ptr).Kind() != reflect.Ptr {
return errInvalidType
}
v := reflect.ValueOf(ptr).Elem()
t := v.Type()
if t.Kind() != reflect.Struct {
return errInvalidType
}
for i := 0; i < t.NumField(); i++ {
if defaultVal := t.Field(i).Tag.Get(fieldName); defaultVal != "-" {
if err := setField(v.Field(i), defaultVal); err != nil {
return err
}
}
}
callSetter(ptr)
return nil
}
// MustSet function is a wrapper of Set function
// It will call Set and panic if err not equals nil.
func MustSet(ptr interface{}) {
if err := Set(ptr); err != nil {
panic(err)
}
}
func setField(field reflect.Value, defaultVal string) error {
if !field.CanSet() {
return nil
}
if !shouldInitializeField(field, defaultVal) {
return nil
}
isInitial := isInitialValue(field)
if isInitial {
if unmarshalByInterface(field, defaultVal) {
return nil
}
switch field.Kind() {
case reflect.Bool:
if val, err := strconv.ParseBool(defaultVal); err == nil {
field.Set(reflect.ValueOf(val).Convert(field.Type()))
}
case reflect.Int:
if val, err := strconv.ParseInt(defaultVal, 0, strconv.IntSize); err == nil {
field.Set(reflect.ValueOf(int(val)).Convert(field.Type()))
}
case reflect.Int8:
if val, err := strconv.ParseInt(defaultVal, 0, 8); err == nil {
field.Set(reflect.ValueOf(int8(val)).Convert(field.Type()))
}
case reflect.Int16:
if val, err := strconv.ParseInt(defaultVal, 0, 16); err == nil {
field.Set(reflect.ValueOf(int16(val)).Convert(field.Type()))
}
case reflect.Int32:
if val, err := strconv.ParseInt(defaultVal, 0, 32); err == nil {
field.Set(reflect.ValueOf(int32(val)).Convert(field.Type()))
}
case reflect.Int64:
if val, err := time.ParseDuration(defaultVal); err == nil {
field.Set(reflect.ValueOf(val).Convert(field.Type()))
} else if val, err := strconv.ParseInt(defaultVal, 0, 64); err == nil {
field.Set(reflect.ValueOf(val).Convert(field.Type()))
}
case reflect.Uint:
if val, err := strconv.ParseUint(defaultVal, 0, strconv.IntSize); err == nil {
field.Set(reflect.ValueOf(uint(val)).Convert(field.Type()))
}
case reflect.Uint8:
if val, err := strconv.ParseUint(defaultVal, 0, 8); err == nil {
field.Set(reflect.ValueOf(uint8(val)).Convert(field.Type()))
}
case reflect.Uint16:
if val, err := strconv.ParseUint(defaultVal, 0, 16); err == nil {
field.Set(reflect.ValueOf(uint16(val)).Convert(field.Type()))
}
case reflect.Uint32:
if val, err := strconv.ParseUint(defaultVal, 0, 32); err == nil {
field.Set(reflect.ValueOf(uint32(val)).Convert(field.Type()))
}
case reflect.Uint64:
if val, err := strconv.ParseUint(defaultVal, 0, 64); err == nil {
field.Set(reflect.ValueOf(val).Convert(field.Type()))
}
case reflect.Uintptr:
if val, err := strconv.ParseUint(defaultVal, 0, strconv.IntSize); err == nil {
field.Set(reflect.ValueOf(uintptr(val)).Convert(field.Type()))
}
case reflect.Float32:
if val, err := strconv.ParseFloat(defaultVal, 32); err == nil {
field.Set(reflect.ValueOf(float32(val)).Convert(field.Type()))
}
case reflect.Float64:
if val, err := strconv.ParseFloat(defaultVal, 64); err == nil {
field.Set(reflect.ValueOf(val).Convert(field.Type()))
}
case reflect.String:
field.Set(reflect.ValueOf(defaultVal).Convert(field.Type()))
case reflect.Slice:
ref := reflect.New(field.Type())
ref.Elem().Set(reflect.MakeSlice(field.Type(), 0, 0))
if defaultVal != "" && defaultVal != "[]" {
if err := json.Unmarshal([]byte(defaultVal), ref.Interface()); err != nil {
return err
}
}
field.Set(ref.Elem().Convert(field.Type()))
case reflect.Map:
ref := reflect.New(field.Type())
ref.Elem().Set(reflect.MakeMap(field.Type()))
if defaultVal != "" && defaultVal != "{}" {
if err := json.Unmarshal([]byte(defaultVal), ref.Interface()); err != nil {
return err
}
}
field.Set(ref.Elem().Convert(field.Type()))
case reflect.Struct:
if defaultVal != "" && defaultVal != "{}" {
if err := json.Unmarshal([]byte(defaultVal), field.Addr().Interface()); err != nil {
return err
}
}
case reflect.Ptr:
field.Set(reflect.New(field.Type().Elem()))
}
}
switch field.Kind() {
case reflect.Ptr:
if isInitial || field.Elem().Kind() == reflect.Struct {
setField(field.Elem(), defaultVal)
callSetter(field.Interface())
}
case reflect.Struct:
if err := Set(field.Addr().Interface()); err != nil {
return err
}
case reflect.Slice:
for j := 0; j < field.Len(); j++ {
if err := setField(field.Index(j), defaultVal); err != nil {
return err
}
}
case reflect.Map:
for _, e := range field.MapKeys() {
var v = field.MapIndex(e)
switch v.Kind() {
case reflect.Ptr:
switch v.Elem().Kind() {
case reflect.Struct, reflect.Slice, reflect.Map:
if err := setField(v.Elem(), ""); err != nil {
return err
}
}
case reflect.Struct, reflect.Slice, reflect.Map:
ref := reflect.New(v.Type())
ref.Elem().Set(v)
if err := setField(ref.Elem(), ""); err != nil {
return err
}
field.SetMapIndex(e, ref.Elem().Convert(v.Type()))
}
}
}
return nil
}
func unmarshalByInterface(field reflect.Value, defaultVal string) bool {
asText, ok := field.Addr().Interface().(encoding.TextUnmarshaler)
if ok && defaultVal != "" {
// if field implements encode.TextUnmarshaler, try to use it before decode by kind
if err := asText.UnmarshalText([]byte(defaultVal)); err == nil {
return true
}
}
asJSON, ok := field.Addr().Interface().(json.Unmarshaler)
if ok && defaultVal != "" && defaultVal != "{}" && defaultVal != "[]" {
// if field implements json.Unmarshaler, try to use it before decode by kind
if err := asJSON.UnmarshalJSON([]byte(defaultVal)); err == nil {
return true
}
}
return false
}
func isInitialValue(field reflect.Value) bool {
return reflect.DeepEqual(reflect.Zero(field.Type()).Interface(), field.Interface())
}
func shouldInitializeField(field reflect.Value, tag string) bool {
switch field.Kind() {
case reflect.Struct:
return true
case reflect.Ptr:
if !field.IsNil() && field.Elem().Kind() == reflect.Struct {
return true
}
case reflect.Slice:
return field.Len() > 0 || tag != ""
case reflect.Map:
return field.Len() > 0 || tag != ""
}
return tag != ""
}
// CanUpdate returns true when the given value is an initial value of its type
func CanUpdate(v interface{}) bool {
return isInitialValue(reflect.ValueOf(v))
}

12
vendor/github.com/creasty/defaults/setter.go generated vendored Normal file
View file

@ -0,0 +1,12 @@
package defaults
// Setter is an interface for setting default values
type Setter interface {
SetDefaults()
}
func callSetter(v interface{}) {
if ds, ok := v.(Setter); ok {
ds.SetDefaults()
}
}

4
vendor/github.com/delucks/go-subsonic/.gitignore generated vendored Normal file
View file

@ -0,0 +1,4 @@
*.swp
.idea
subsonic-rest-api-1.16.1.xsd
build/

674
vendor/github.com/delucks/go-subsonic/LICENSE.txt generated vendored Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

156
vendor/github.com/delucks/go-subsonic/README.md generated vendored Normal file
View file

@ -0,0 +1,156 @@
# go-subsonic
[![GoDoc](https://godoc.org/github.com/delucks/go-subsonic?status.svg)](https://godoc.org/github.com/delucks/go-subsonic)
This is an API client library for Subsonic and Subsonic-compatible music servers. It is tested on Subsonic, Airsonic, and Navidrome.
# Testing
Tests for this library run live against instances of Subsonic-compatible servers. A docker-compose setup comes with this repo to run instances of Airsonic and Navidrome for testing purposes. To set up the test environment and run tests against the docker containers, run `test.sh`. This test runner does the following:
- Download CC-licensed sample music into `build/music`
- Set up a location for configuration for both servers in `build/data`
- Run `docker-compose up` to initialize both servers with the music & configuration directories as volumes
- Wait until the servers are up
- Run tests for both Subsonic and Navidrome
The tests for Subsonic run against the demo server, so please be mindful to exclude them from all but final test runs in respect for their server load. To manually tests for only one server type, use the `-run` argument to `go test` like so:
```
# Just Airsonic
go test . -test.v -run Airsonic
# Subsonic and Airsonic
go test . -test.v -run '(Sub|Air)sonic'
# Navidrome
go test . -test.v -run Navidrome
```
If you intend on testing with your own server, modify the top-level TestSubsonic, TestAirsonic, or TestNavidrome functions with your server's address and credentials. Please test this library with other Subsonic-compatible streaming servers, and file an issue if something is amiss!
# API Support
## System
- [x] ping (1.0.0)
- [x] getLicense (1.0.0)
## Browsing
- [x] getMusicFolders (1.0.0)
- [x] getIndexes (1.0.0)
- [x] getMusicDirectory
- [x] getGenres (1.9.0)
- [x] getArtists (1.8.0)
- [x] getArtist (1.8.0)
- [x] getAlbum (1.0.0)
- [x] getSong (1.8.0)
- [x] getArtistInfo (1.11.0)
- [x] getArtistInfo2 (1.11.0)
- [x] getAlbumInfo (1.14.0)
- [x] getAlbumInfo2 (1.14.0)
- [x] getSimilarSongs (1.11.0)
- [x] getSimilarSongs2 (1.11.0)
- [x] getTopSongs (1.13.0)
## Album/song lists
- [x] getAlbumList (1.2.0)
- [x] getAlbumList2 (1.8.0)
- [x] getRandomSongs (1.2.0)
- [x] getSongsByGenre (1.9.0)
- [x] getNowPlaying (1.0.0)
- [x] getStarred (1.8.0)
- [x] getStarred2 (1.8.0)
## Searching
- [x] search2 (1.4.0)
- [x] search3 (1.8.0)
## Playlists
- [x] getPlaylists (1.0.0)
- [x] getPlaylist (1.0.0)
- [x] createPlaylist (1.2.0)
- [x] updatePlaylist (1.8.0)
- [x] deletePlaylist (1.2.0)
## Media retrieval
- [x] stream (1.0.0)
- [x] download (1.0.0)
- [x] getCoverArt (1.0.0)
- [ ] getLyrics (1.2.0)
- [x] getAvatar (1.8.0)
## Media annotation
- [x] star (1.8.0)
- [x] unstar (1.8.0)
- [x] setRating (1.6.0)
- [x] scrobble (1.5.0)
## User management
- [x] getUser (1.3.0)
- [x] getUsers (1.8.0)
- [x] createUser (1.1.0)
- [x] updateUser (1.10.1)
- [x] deleteUser (1.3.0)
- [x] changePassword (1.1.0)
## Media library scanning
- [x] getScanStatus (1.15.0)
- [x] startScan (1.15.0)
## Bookmarks
- [ ] getBookmarks (1.9.0)
- [ ] createBookmark (1.9.0)
- [ ] deleteBookmark (1.9.0)
- [ ] getPlayQueue (1.12.0)
- [ ] savePlayQueue (1.12.0)
## Sharing
- [ ] getShares (1.6.0)
- [ ] createShare (1.6.0)
- [ ] updateShare (1.6.0)
- [ ] deleteShare (1.6.0)
## Podcast
- [ ] getPodcasts (1.6.0)
- [ ] getNewestPodcasts (1.13.0)
- [ ] refreshPodcasts (1.9.0)
- [ ] createPodcastChannel (1.9.0)
- [ ] deletePodcastChannel (1.9.0)
- [ ] deletePodcastEpisode (1.9.0)
- [ ] downloadPodcastEpisode (1.9.0)
## Jukebox
- [ ] jukeboxControl (1.2.0)
## Internet radio
- [ ] getInternetRadioStations (1.9.0)
- [ ] createInternetRadioStation (1.16.0)
- [ ] updateInternetRadioStation (1.16.0)
- [ ] deleteInternetRadioStation (1.16.0)
## Chat
- [ ] getChatMessages (1.2.0)
- [ ] addChatMessage (1.2.0)
## Out of Scope
Video endpoints are currently out of scope- please file an issue if you would like support for them. The deprecated "search" endpoint is unimplemented.
- [ ] hls.m3u8 (1.8.0)
- [ ] getVideos (1.8.0)
- [ ] getVideoInfo (1.14.0)
- [ ] getCaptions (1.14.0)
- [ ] search (1.0.0)

100
vendor/github.com/delucks/go-subsonic/annotation.go generated vendored Normal file
View file

@ -0,0 +1,100 @@
package subsonic
import (
"errors"
"fmt"
"net/url"
"strconv"
)
// StarParameters are used to identify songs, albums, and artists (or some subset of those) at the same time.
// subsonic.Star and subsonic.Unstar both use StarParameters to identify things to star.
type StarParameters struct {
SongIDs []string
AlbumIDs []string
ArtistIDs []string
}
// Star adds the star annotation to songs, albums, and artists.
func (s *Client) Star(parameters StarParameters) error {
params := url.Values{}
for _, song := range parameters.SongIDs {
params.Add("id", song)
}
for _, album := range parameters.AlbumIDs {
params.Add("albumId", album)
}
for _, artist := range parameters.ArtistIDs {
params.Add("artistId", artist)
}
_, err := s.getValues("star", params)
if err != nil {
return err
}
return nil
}
// Unstar removes the star annotation from songs, albums, and artists.
func (s *Client) Unstar(parameters StarParameters) error {
params := url.Values{}
for _, song := range parameters.SongIDs {
params.Add("id", song)
}
for _, album := range parameters.AlbumIDs {
params.Add("albumId", album)
}
for _, artist := range parameters.ArtistIDs {
params.Add("artistId", artist)
}
_, err := s.getValues("unstar", params)
if err != nil {
return err
}
return nil
}
// SetRating sets the rating of a music file.
func (s *Client) SetRating(id string, rating int) error {
if rating > 5 || rating < 0 {
return errors.New("Rating can only be in the range 0-5")
}
params := map[string]string{
"id": id,
"rating": fmt.Sprintf("%d", rating),
}
_, err := s.Get("setRating", params)
if err != nil {
return err
}
return nil
}
// Scrobble submits a song to last.fm if the user has configured their credentials to do so.
//
// Optional Parameters:
// time: (Since 1.8.0) The time (in milliseconds since 1 Jan 1970) at which the song was listened to.
// submission: Whether this is a "submission" (true) or a "now playing" (false) notification. Defaults to a submission.
func (s *Client) Scrobble(id string, parameters map[string]string) error {
params := map[string]string{
"id": id,
}
if scrobbleTime, ok := parameters["time"]; ok {
_, err := strconv.Atoi(scrobbleTime)
if err != nil {
return fmt.Errorf("%s is not a unix-style timestamp", scrobbleTime)
}
params["time"] = scrobbleTime
}
if submission, ok := parameters["submission"]; ok {
_, err := strconv.ParseBool(submission)
if err != nil {
return fmt.Errorf("%s is not boolean", submission)
}
params["submission"] = submission
}
_, err := s.Get("scrobble", params)
if err != nil {
return err
}
return nil
}

189
vendor/github.com/delucks/go-subsonic/browsing.go generated vendored Normal file
View file

@ -0,0 +1,189 @@
package subsonic
// GetMusicFolders returns all configured top-level music folders.
func (s *Client) GetMusicFolders() ([]*MusicFolder, error) {
resp, err := s.Get("getMusicFolders", nil)
if err != nil {
return nil, err
}
return resp.MusicFolders.MusicFolder, nil
}
// GetIndexes returns the index of entries by letter/number.
//
// Optional Parameters:
// musicFolderId: Only return songs in the music folder with the given ID. See getMusicFolders.
// ifModifiedSince: If specified, only return a result if the artist collection has changed since the given time (in milliseconds since 1 Jan 1970).
func (s *Client) GetIndexes(parameters map[string]string) (*Indexes, error) {
resp, err := s.Get("getIndexes", parameters)
if err != nil {
return nil, err
}
return resp.Indexes, nil
}
// GetMusicDirectory returns a listing of all files in a music directory. Typically used to get list of albums for an artist, or list of songs for an album.
// The ID can be an album, song, or artist - anything considered within the directory hierarchy of Subsonic.
func (s *Client) GetMusicDirectory(id string) (*Directory, error) {
resp, err := s.Get("getMusicDirectory", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.Directory, nil
}
// GetGenres returns all genres in the server.
func (s *Client) GetGenres() ([]*Genre, error) {
resp, err := s.Get("getGenres", nil)
if err != nil {
return nil, err
}
return resp.Genres.Genre, nil
}
// GetArtists returns all artists in the server.
//
// Optional Parameters:
// musicFolderId: Only return songs in the music folder with the given ID. See getMusicFolders.
func (s *Client) GetArtists(parameters map[string]string) (*ArtistsID3, error) {
resp, err := s.Get("getArtists", parameters)
if err != nil {
return nil, err
}
return resp.Artists, nil
}
// GetAlbum returns an Artist by ID.
func (s *Client) GetArtist(id string) (*ArtistID3, error) {
resp, err := s.Get("getArtist", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.Artist, nil
}
// GetAlbum returns an Album by ID.
func (s *Client) GetAlbum(id string) (*AlbumID3, error) {
resp, err := s.Get("getAlbum", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.Album, nil
}
// GetSong returns a Song by ID.
func (s *Client) GetSong(id string) (*Child, error) {
resp, err := s.Get("getSong", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.Song, nil
}
// GetArtistInfo returns biography, image links, and similar artists from last.fm.
//
// Optional Parameters:
// count: Max number of similar artists to return.
// includeNotPresent: Whether to return artists that are not present in the media library.
func (s *Client) GetArtistInfo(id string, parameters map[string]string) (*ArtistInfo, error) {
params := make(map[string]string)
params["id"] = id
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getArtistInfo", params)
if err != nil {
return nil, err
}
return resp.ArtistInfo, nil
}
// GetArtistInfo2 returns biography, image links, and similar artists like GetArtistInfo, but using id3 tags.
//
// Optional Parameters:
// count: Max number of similar artists to return.
// includeNotPresent: Whether to return artists that are not present in the media library.
func (s *Client) GetArtistInfo2(id string, parameters map[string]string) (*ArtistInfo2, error) {
params := make(map[string]string)
params["id"] = id
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getArtistInfo2", params)
if err != nil {
return nil, err
}
return resp.ArtistInfo2, nil
}
// GetAlbumInfo returns album notes, image data, etc using data from last.fm.
// This accepts both album and song IDs.
func (s *Client) GetAlbumInfo(id string) (*AlbumInfo, error) {
resp, err := s.Get("getAlbumInfo", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.AlbumInfo, nil
}
// GetAlbumInfo2 returns the same data as GetAlbumInfo, but organized by id3 tag.
// It only accepts album IDs.
func (s *Client) GetAlbumInfo2(id string) (*AlbumInfo, error) {
resp, err := s.Get("getAlbumInfo2", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.AlbumInfo, nil
}
// GetSimilarSongs finds similar songs to an album, track, or artist.
// This is mostly used for radio features. This accepts artist, album, or song IDs.
//
// Optional Parameters:
// count: Number of songs to return
func (s *Client) GetSimilarSongs(id string, parameters map[string]string) ([]*Child, error) {
params := make(map[string]string)
params["id"] = id
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getSimilarSongs", params)
if err != nil {
return nil, err
}
return resp.SimilarSongs.Song, nil
}
// GetSimilarSongs2 finds similar songs like GetSimilarSongs, but using id3 tags.
//
// Optional Parameters:
// count: Number of songs to return
func (s *Client) GetSimilarSongs2(id string, parameters map[string]string) ([]*Child, error) {
params := make(map[string]string)
params["id"] = id
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getSimilarSongs2", params)
if err != nil {
return nil, err
}
return resp.SimilarSongs2.Song, nil
}
// GetTopSongs returns the top songs for a given artist by name.
//
// Optional Parameters:
// count: Number of songs to return
func (s *Client) GetTopSongs(name string, parameters map[string]string) ([]*Child, error) {
params := make(map[string]string)
params["artist"] = name
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getTopSongs", params)
if err != nil {
return nil, err
}
return resp.TopSongs.Song, nil
}

171
vendor/github.com/delucks/go-subsonic/client.go generated vendored Normal file
View file

@ -0,0 +1,171 @@
// Package subsonic implements an API client library for Subsonic-compatible music streaming servers.
//
// This project handles communication with a remote *sonic server, but does not handle playback of media. The library user should be prepared to do something with the stream of audio in bytes, like decoding and playing that audio on a sound card.
// The list of API endpoints implemented is available on the project's github page.
//
// The API is divided between functions with no suffix, and functions that have a "2" suffix (or "3" in the case of Search3).
// Generally, things with "2" on the end are organized by file tags rather than folder structure. This is how you'd expect most music players to work and is recommended.
// The variants without a suffix organize the library by directory structure; artists are a directory, albums are children of that directory, songs (subsonic.Child) are children of albums.
// This has some disadvantages: possibly duplicating items with identical directory names, treating songs and albums in much the same fashion, and being more difficult to query consistently.
package subsonic
import (
"crypto/md5"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/url"
"path"
)
const (
supportedApiVersion = "1.8.0"
libraryVersion = "0.0.5"
)
type Client struct {
Client *http.Client
BaseUrl string
User string
ClientName string
PasswordAuth bool
password string
salt string
token string
}
func generateSalt() string {
var corpus = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// length is minimum 6, but let's use ten to start
b := make([]rune, 10)
for i := range b {
b[i] = corpus[rand.Intn(len(corpus))]
}
return string(b)
}
// Authenticate authenticates the current user with a provided password. The password is salted before transmission and requires Subsonic > 1.13.0.
func (s *Client) Authenticate(password string) error {
if s.PasswordAuth {
s.password = password
} else {
salt := generateSalt()
h := md5.New()
_, err := io.WriteString(h, password)
if err != nil {
return err
}
_, err = io.WriteString(h, salt)
if err != nil {
return err
}
s.salt = salt
s.token = fmt.Sprintf("%x", h.Sum(nil))
}
// Test authentication
// Don't use the s.Ping method because that always returns true as long as the servers is up.
resp, err := s.Get("ping", nil)
if err != nil {
return fmt.Errorf("Authentication failed: %s", err)
}
if resp.Error != nil {
return fmt.Errorf("Authentication failed: %s", resp.Error.Message)
}
return nil
}
// Request performs a HTTP request against the Subsonic server as the current user.
func (s *Client) Request(method string, endpoint string, params url.Values) (*http.Response, error) {
baseUrl, err := url.Parse(s.BaseUrl)
if err != nil {
return nil, err
}
baseUrl.Path = path.Join(baseUrl.Path, "/rest/", endpoint)
req, err := http.NewRequest(method, baseUrl.String(), nil)
if err != nil {
return nil, err
}
q := req.URL.Query()
q.Add("f", "xml")
q.Add("v", supportedApiVersion)
q.Add("c", s.ClientName)
q.Add("u", s.User)
if s.PasswordAuth {
q.Add("p", s.password)
} else {
q.Add("t", s.token)
q.Add("s", s.salt)
}
for key, values := range params {
for _, val := range values {
q.Add(key, val)
}
}
req.URL.RawQuery = q.Encode()
//log.Printf("%s %s", method, req.URL.String())
resp, err := s.Client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
// Get is a convenience interface to issue a GET request and parse the response body (99% of Subsonic API calls)
func (s *Client) Get(endpoint string, params map[string]string) (*Response, error) {
parameters := url.Values{}
for k, v := range params {
parameters.Add(k, v)
}
return s.getValues(endpoint, parameters)
}
// getValues is a convenience interface to issue a GET request and parse the response body. It supports multiple values by way of the url.Values argument.
func (s *Client) getValues(endpoint string, params url.Values) (*Response, error) {
response, err := s.Request("GET", endpoint, params)
if err != nil {
return nil, err
}
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
parsed := Response{}
err = xml.Unmarshal(responseBody, &parsed)
if err != nil {
return nil, err
}
if parsed.Error != nil {
return nil, fmt.Errorf("Error #%d: %s\n", parsed.Error.Code, parsed.Error.Message)
}
//log.Printf("%s: %s\n", endpoint, string(responseBody))
return &parsed, nil
}
// Ping is used to test connectivity with the server. It returns true if the server is up.
func (s *Client) Ping() bool {
_, err := s.Request("GET", "ping", nil)
if err != nil {
log.Println(err)
return false
}
return true
}
// GetLicense retrieves details about the software license. Subsonic requires a license after a 30-day trial, compatible applications have a perpetually valid license.
func (s *Client) GetLicense() (*License, error) {
resp, err := s.Get("getLicense", nil)
if err != nil {
return nil, err
}
return resp.License, nil
}

View file

@ -0,0 +1,26 @@
version: "3"
services:
navidrome:
image: deluan/navidrome:latest
user: 1000:1000 # should be owner of volumes
ports:
- "4533:4533"
restart: unless-stopped
environment:
# Put your config options customization here
ND_SCANINTERVAL: 1m
ND_LOGLEVEL: info
ND_SESSIONTIMEOUT: 24h
ND_BASEURL: ""
volumes:
- "./build/data:/data"
- "./build/music:/music:ro"
airsonic:
image: airsonic/airsonic:latest
user: 1000:1000
ports:
- "4040:4040"
restart: unless-stopped
volumes:
- "./build/data:/airsonic/data"
- "./build/music:/airsonic/music:ro"

175
vendor/github.com/delucks/go-subsonic/lists.go generated vendored Normal file
View file

@ -0,0 +1,175 @@
package subsonic
import (
"errors"
"fmt"
)
func validateListType(input string) bool {
validTypes := map[string]bool{
"random": true,
"newest": true,
"highest": true,
"frequent": true,
"recent": true,
"alphabeticalByName": true,
"alphabeticalByArtist": true,
"starred": true,
"byYear": true,
"byGenre": true,
}
_, ok := validTypes[input]
return ok
}
// GetAlbumList returns a list of random, newest, highest rated etc. albums. Similar to the album lists on the home page of the Subsonic web interface.
//
// Optional Parameters:
// size: The number of albums to return. Max 500, default 10.
// offset: The list offset. Useful if you for example want to page through the list of newest albums.
// fromYear: The first year in the range. If fromYear > toYear a reverse chronological list is returned.
// toYear: The last year in the range.
// genre: The name of the genre, e.g., "Rock".
// musicFolderId: (Since 1.11.0) Only return albums in the music folder with the given ID. See getMusicFolders.
//
// toYear and fromYear are required parameters when type == "byYear". genre is a required parameter when type == "byGenre".
func (s *Client) GetAlbumList(listType string, parameters map[string]string) ([]*Child, error) {
if !validateListType(listType) {
return nil, fmt.Errorf("List type %s is invalid, see http://www.subsonic.org/pages/api.jsp#getAlbumList", listType)
}
if listType == "byYear" {
_, ok := parameters["fromYear"]
if !ok {
return nil, errors.New("Required argument fromYear was not found when using GetAlbumList byYear")
}
_, ok = parameters["toYear"]
if !ok {
return nil, errors.New("Required argument toYear was not found when using GetAlbumList byYear")
}
} else if listType == "byGenre" {
_, ok := parameters["genre"]
if !ok {
return nil, errors.New("Required argument genre was not found when using GetAlbumList byGenre")
}
}
params := make(map[string]string)
params["type"] = listType
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getAlbumList", params)
if err != nil {
return nil, err
}
return resp.AlbumList.Album, nil
}
// GetAlbumList2 returns a list of albums like GetAlbumList, but organized according to id3 tags.
//
// Optional Parameters:
// size: The number of albums to return. Max 500, default 10.
// offset: The list offset. Useful if you for example want to page through the list of newest albums.
// fromYear: The first year in the range. If fromYear > toYear a reverse chronological list is returned.
// toYear: The last year in the range.
// genre: The name of the genre, e.g., "Rock".
// musicFolderId: (Since 1.11.0) Only return albums in the music folder with the given ID. See getMusicFolders.
//
// toYear and fromYear are required parameters when type == "byYear". genre is a required parameter when type == "byGenre".
func (s *Client) GetAlbumList2(listType string, parameters map[string]string) ([]*AlbumID3, error) {
if !validateListType(listType) {
return nil, fmt.Errorf("List type %s is invalid, see http://www.subsonic.org/pages/api.jsp#getAlbumList", listType)
}
if listType == "byYear" {
_, ok := parameters["fromYear"]
if !ok {
return nil, errors.New("Required argument fromYear was not found when using GetAlbumList2 byYear")
}
_, ok = parameters["toYear"]
if !ok {
return nil, errors.New("Required argument toYear was not found when using GetAlbumList2 byYear")
}
} else if listType == "byGenre" {
_, ok := parameters["genre"]
if !ok {
return nil, errors.New("Required argument genre was not found when using GetAlbumList2 byGenre")
}
}
params := make(map[string]string)
params["type"] = listType
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getAlbumList2", params)
if err != nil {
return nil, err
}
return resp.AlbumList2.Album, nil
}
// GetRandomSongs returns a randomly selected set of songs limited by the optional parameters.
//
// Optional Parameters:
// size: The maximum number of songs to return. Max 500, default 10.
// genre: Only returns songs belonging to this genre.
// fromYear: Only return songs published after or in this year.
// toYear: Only return songs published before or in this year.
// musicFolderId: Only return songs in the music folder with the given ID. See getMusicFolders.
func (s *Client) GetRandomSongs(parameters map[string]string) ([]*Child, error) {
resp, err := s.Get("getRandomSongs", parameters)
if err != nil {
return nil, err
}
return resp.RandomSongs.Song, nil
}
// GetSongsByGenre returns songs in a given genre name.
//
// Optional Parameters:
// count: The maximum number of songs to return. Max 500, default 10.
// offset: The offset. Useful if you want to page through the songs in a genre.
// musicFolderId: Only return songs in the music folder with the given ID. See getMusicFolders.
func (s *Client) GetSongsByGenre(name string, parameters map[string]string) ([]*Child, error) {
params := make(map[string]string)
params["genre"] = name
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("getSongsByGenre", params)
if err != nil {
return nil, err
}
return resp.SongsByGenre.Song, nil
}
// GetNowPlaying returns what is currently being played by all users.
func (s *Client) GetNowPlaying() ([]*NowPlayingEntry, error) {
resp, err := s.Get("getNowPlaying", nil)
if err != nil {
return nil, err
}
return resp.NowPlaying.Entry, nil
}
// GetStarred returns starred albums, artists, and songs.
//
// Optional Parameters:
// musicFolderId: Only return songs in the music folder with the given ID. See getMusicFolders.
func (s *Client) GetStarred(parameters map[string]string) (*Starred, error) {
resp, err := s.Get("getStarred", parameters)
if err != nil {
return nil, err
}
return resp.Starred, nil
}
// GetStarred2 returns starred albums, artists, and songs arranged by id3 tag.
//
// Optional Parameters:
// musicFolderId: Only return songs in the music folder with the given ID. See getMusicFolders.
func (s *Client) GetStarred2(parameters map[string]string) (*Starred2, error) {
resp, err := s.Get("getStarred2", parameters)
if err != nil {
return nil, err
}
return resp.Starred2, nil
}

679
vendor/github.com/delucks/go-subsonic/models.go generated vendored Normal file
View file

@ -0,0 +1,679 @@
package subsonic
/* This file was automatically generated from the xsd schema provided by Subsonic, then manually modified.
* http://www.subsonic.org/pages/inc/api/schema/subsonic-rest-api-1.16.1.xsd
* xsdgen -o xml.go -pkg subsonic -ns "http://subsonic.org/restapi" subsonic-rest-api-1.16.1.xsd
* Changes from the original include:
* - Adding missing name (value of xml element) for each genre
* - Capitalize "ID" in struct names and add missing ID fields.
* - Merge *With* variants of structs.
*/
import (
"bytes"
"encoding/xml"
"time"
)
// AlbumID3 is an album that's organized by music file tags.
type AlbumID3 struct {
ID string `xml:"id,attr"` // Manually added
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"` // Merged from AlbumWithSongsID3
Name string `xml:"name,attr"`
Artist string `xml:"artist,attr,omitempty"`
ArtistID string `xml:"artistId,attr,omitempty"`
CoverArt string `xml:"coverArt,attr,omitempty"`
SongCount int `xml:"songCount,attr"`
Duration int `xml:"duration,attr"`
PlayCount int64 `xml:"playCount,attr,omitempty"`
Created time.Time `xml:"created,attr"`
Starred time.Time `xml:"starred,attr,omitempty"`
Year int `xml:"year,attr,omitempty"`
Genre string `xml:"genre,attr,omitempty"`
}
// AlbumInfo is a collection of notes and links describing an album.
type AlbumInfo struct {
Notes string `xml:"http://subsonic.org/restapi notes,omitempty"`
MusicBrainzID string `xml:"http://subsonic.org/restapi musicBrainzId,omitempty"`
LastFmUrl string `xml:"http://subsonic.org/restapi lastFmUrl,omitempty"`
SmallImageUrl string `xml:"http://subsonic.org/restapi smallImageUrl,omitempty"`
MediumImageUrl string `xml:"http://subsonic.org/restapi mediumImageUrl,omitempty"`
LargeImageUrl string `xml:"http://subsonic.org/restapi largeImageUrl,omitempty"`
}
type albumList struct {
Album []*Child `xml:"http://subsonic.org/restapi album,omitempty"`
}
type albumList2 struct {
Album []*AlbumID3 `xml:"http://subsonic.org/restapi album,omitempty"`
}
// Artist is an artist from the server, organized in the folders pattern.
type Artist struct {
ID string `xml:"id,attr"`
Name string `xml:"name,attr"`
ArtistImageUrl string `xml:"artistImageUrl,attr,omitempty"`
Starred time.Time `xml:"starred,attr,omitempty"`
UserRating int `xml:"userRating,attr,omitempty"`
AverageRating float64 `xml:"averageRating,attr,omitempty"`
}
// ArtistID3 is an artist from the server, organized by ID3 tag.
type ArtistID3 struct {
ID string `xml:"id,attr"` // Manually added
Album []*AlbumID3 `xml:"http://subsonic.org/restapi album,omitempty"` // Merged with ArtistWithAlbumsID3
Name string `xml:"name,attr"`
CoverArt string `xml:"coverArt,attr,omitempty"`
ArtistImageUrl string `xml:"artistImageUrl,attr,omitempty"`
AlbumCount int `xml:"albumCount,attr"`
Starred time.Time `xml:"starred,attr,omitempty"`
}
// ArtistInfo is all auxillary information about an artist from GetArtistInfo.
type ArtistInfo struct {
SimilarArtist []*Artist `xml:"http://subsonic.org/restapi similarArtist,omitempty"`
Biography string `xml:"http://subsonic.org/restapi biography,omitempty"`
MusicBrainzID string `xml:"http://subsonic.org/restapi musicBrainzId,omitempty"`
LastFmUrl string `xml:"http://subsonic.org/restapi lastFmUrl,omitempty"`
SmallImageUrl string `xml:"http://subsonic.org/restapi smallImageUrl,omitempty"`
MediumImageUrl string `xml:"http://subsonic.org/restapi mediumImageUrl,omitempty"`
LargeImageUrl string `xml:"http://subsonic.org/restapi largeImageUrl,omitempty"`
}
// ArtistInfo2 is all auxillary information about an artist from GetArtistInfo2, with similar artists organized by ID3 tags.
type ArtistInfo2 struct {
SimilarArtist []*ArtistID3 `xml:"http://subsonic.org/restapi similarArtist,omitempty"`
Biography string `xml:"http://subsonic.org/restapi biography,omitempty"`
MusicBrainzID string `xml:"http://subsonic.org/restapi musicBrainzId,omitempty"`
LastFmUrl string `xml:"http://subsonic.org/restapi lastFmUrl,omitempty"`
SmallImageUrl string `xml:"http://subsonic.org/restapi smallImageUrl,omitempty"`
MediumImageUrl string `xml:"http://subsonic.org/restapi mediumImageUrl,omitempty"`
LargeImageUrl string `xml:"http://subsonic.org/restapi largeImageUrl,omitempty"`
}
// ArtistsID3 is an index of every artist on the server organized by ID3 tag, from getArtists.
type ArtistsID3 struct {
Index []*IndexID3 `xml:"http://subsonic.org/restapi index,omitempty"`
IgnoredArticles string `xml:"ignoredArticles,attr"`
}
type Bookmark struct {
Entry *Child `xml:"http://subsonic.org/restapi entry"`
Position int64 `xml:"position,attr"`
Username string `xml:"username,attr"`
Comment string `xml:"comment,attr,omitempty"`
Created time.Time `xml:"created,attr"`
Changed time.Time `xml:"changed,attr"`
}
func (t *Bookmark) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type T Bookmark
var layout struct {
*T
Created *xsdDateTime `xml:"created,attr"`
Changed *xsdDateTime `xml:"changed,attr"`
}
layout.T = (*T)(t)
layout.Created = (*xsdDateTime)(&layout.T.Created)
layout.Changed = (*xsdDateTime)(&layout.T.Changed)
return e.EncodeElement(layout, start)
}
func (t *Bookmark) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T Bookmark
var overlay struct {
*T
Created *xsdDateTime `xml:"created,attr"`
Changed *xsdDateTime `xml:"changed,attr"`
}
overlay.T = (*T)(t)
overlay.Created = (*xsdDateTime)(&overlay.T.Created)
overlay.Changed = (*xsdDateTime)(&overlay.T.Changed)
return d.DecodeElement(&overlay, &start)
}
type bookmarks struct {
Bookmark []*Bookmark `xml:"http://subsonic.org/restapi bookmark,omitempty"`
}
type ChatMessage struct {
Username string `xml:"username,attr"`
Time int64 `xml:"time,attr"`
Message string `xml:"message,attr"`
}
type chatMessages struct {
ChatMessage []*ChatMessage `xml:"http://subsonic.org/restapi chatMessage,omitempty"`
}
// Child is a song, or a generic entry in the hierarchical directory structure of the database.
// You can tell if Child is used as a song contextually based on what it was returned by, or if the IsDir boolean was set to true.
type Child struct {
ID string `xml:"id,attr"` // Manually added
Parent string `xml:"parent,attr,omitempty"`
IsDir bool `xml:"isDir,attr"`
Title string `xml:"title,attr"`
Album string `xml:"album,attr,omitempty"`
Artist string `xml:"artist,attr,omitempty"`
Track int `xml:"track,attr,omitempty"`
Year int `xml:"year,attr,omitempty"`
Genre string `xml:"genre,attr,omitempty"`
CoverArt string `xml:"coverArt,attr,omitempty"`
Size int64 `xml:"size,attr,omitempty"`
ContentType string `xml:"contentType,attr,omitempty"`
Suffix string `xml:"suffix,attr,omitempty"`
TranscodedContentType string `xml:"transcodedContentType,attr,omitempty"`
TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty"`
Duration int `xml:"duration,attr,omitempty"`
BitRate int `xml:"bitRate,attr,omitempty"`
Path string `xml:"path,attr,omitempty"`
IsVideo bool `xml:"isVideo,attr,omitempty"`
UserRating int `xml:"userRating,attr,omitempty"`
AverageRating float64 `xml:"averageRating,attr,omitempty"`
PlayCount int64 `xml:"playCount,attr,omitempty"`
DiscNumber int `xml:"discNumber,attr,omitempty"`
Created time.Time `xml:"created,attr,omitempty"`
Starred time.Time `xml:"starred,attr,omitempty"`
AlbumID string `xml:"albumId,attr,omitempty"`
ArtistID string `xml:"artistId,attr,omitempty"`
Type string `xml:"type,attr,omitempty"` // May be one of music, podcast, audiobook, video
BookmarkPosition int64 `xml:"bookmarkPosition,attr,omitempty"`
OriginalWidth int `xml:"originalWidth,attr,omitempty"`
OriginalHeight int `xml:"originalHeight,attr,omitempty"`
}
// Directory is an entry in the hierarchical folder structure organization of the server database.
type Directory struct {
ID string `xml:"id,attr"` // Manually added
Child []*Child `xml:"http://subsonic.org/restapi child,omitempty"`
Parent string `xml:"parent,attr,omitempty"`
Name string `xml:"name,attr"`
Starred time.Time `xml:"starred,attr,omitempty"`
UserRating int `xml:"userRating,attr,omitempty"`
AverageRating float64 `xml:"averageRating,attr,omitempty"`
PlayCount int64 `xml:"playCount,attr,omitempty"`
}
type Error struct {
Code int `xml:"code,attr"`
Message string `xml:"message,attr,omitempty"`
}
// Genre is a style tag for a collection of songs and albums.
type Genre struct {
Name string `xml:",chardata"` // Added manually
SongCount int `xml:"songCount,attr"`
AlbumCount int `xml:"albumCount,attr"`
}
type genres struct {
Genre []*Genre `xml:"http://subsonic.org/restapi genre,omitempty"`
}
// Index is a collection of artists that begin with the same first letter, along with that letter or category.
type Index struct {
Artist []*Artist `xml:"http://subsonic.org/restapi artist,omitempty"`
Name string `xml:"name,attr"`
}
// Index is a collection of artists by ID3 tag that begin with the same first letter, along with that letter or category.
type IndexID3 struct {
Artist []*ArtistID3 `xml:"http://subsonic.org/restapi artist,omitempty"`
Name string `xml:"name,attr"`
}
// Indexes is the full index of the database, returned by getIndex.
// It contains some Index structs for each letter of the DB, plus Child entries for individual tracks.
type Indexes struct {
Shortcut []*Artist `xml:"http://subsonic.org/restapi shortcut,omitempty"`
Index []*Index `xml:"http://subsonic.org/restapi index,omitempty"`
Child []*Child `xml:"http://subsonic.org/restapi child,omitempty"`
LastModified int64 `xml:"lastModified,attr"`
IgnoredArticles string `xml:"ignoredArticles,attr"`
}
type InternetRadioStation struct {
Name string `xml:"name,attr"`
StreamUrl string `xml:"streamUrl,attr"`
HomePageUrl string `xml:"homePageUrl,attr,omitempty"`
}
type internetRadioStations struct {
InternetRadioStation []*InternetRadioStation `xml:"http://subsonic.org/restapi internetRadioStation,omitempty"`
}
type JukeboxPlaylist struct {
Entry []*Child `xml:"http://subsonic.org/restapi entry,omitempty"`
CurrentIndex int `xml:"currentIndex,attr"`
Playing bool `xml:"playing,attr"`
Gain float32 `xml:"gain,attr"`
Position int `xml:"position,attr,omitempty"`
}
type JukeboxStatus struct {
CurrentIndex int `xml:"currentIndex,attr"`
Playing bool `xml:"playing,attr"`
Gain float32 `xml:"gain,attr"`
Position int `xml:"position,attr,omitempty"`
}
// License contains information about the Subsonic server's license validity and contact information in the case of a trial subscription.
type License struct {
Valid bool `xml:"valid,attr"`
Email string `xml:"email,attr,omitempty"`
LicenseExpires time.Time `xml:"licenseExpires,attr,omitempty"`
TrialExpires time.Time `xml:"trialExpires,attr,omitempty"`
}
type Lyrics struct {
Artist string `xml:"artist,attr,omitempty"`
Title string `xml:"title,attr,omitempty"`
}
// MusicFolder is a representation of a source of music files added to the server. It is identified primarily by the numeric ID.
type MusicFolder struct {
ID string `xml:"id,attr"`
Name string `xml:"name,attr,omitempty"`
}
type musicFolders struct {
MusicFolder []*MusicFolder `xml:"http://subsonic.org/restapi musicFolder,omitempty"`
}
type newestPodcasts struct {
Episode []*PodcastEpisode `xml:"http://subsonic.org/restapi episode,omitempty"`
}
type nowPlaying struct {
Entry []*NowPlayingEntry `xml:"http://subsonic.org/restapi entry,omitempty"`
}
// NowPlayingEntry is one individual stream coming from the server along with information about who was streaming it.
type NowPlayingEntry struct {
Username string `xml:"username,attr"`
MinutesAgo int `xml:"minutesAgo,attr"`
PlayerID int `xml:"playerId,attr"`
PlayerName string `xml:"playerName,attr,omitempty"`
Parent string `xml:"parent,attr,omitempty"`
IsDir bool `xml:"isDir,attr"`
Title string `xml:"title,attr"`
Album string `xml:"album,attr,omitempty"`
Artist string `xml:"artist,attr,omitempty"`
Track int `xml:"track,attr,omitempty"`
Year int `xml:"year,attr,omitempty"`
Genre string `xml:"genre,attr,omitempty"`
CoverArt string `xml:"coverArt,attr,omitempty"`
Size int64 `xml:"size,attr,omitempty"`
ContentType string `xml:"contentType,attr,omitempty"`
Suffix string `xml:"suffix,attr,omitempty"`
TranscodedContentType string `xml:"transcodedContentType,attr,omitempty"`
TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty"`
Duration int `xml:"duration,attr,omitempty"`
BitRate int `xml:"bitRate,attr,omitempty"`
Path string `xml:"path,attr,omitempty"`
IsVideo bool `xml:"isVideo,attr,omitempty"`
UserRating int `xml:"userRating,attr,omitempty"`
AverageRating float64 `xml:"averageRating,attr,omitempty"`
PlayCount int64 `xml:"playCount,attr,omitempty"`
DiscNumber int `xml:"discNumber,attr,omitempty"`
Created time.Time `xml:"created,attr,omitempty"`
Starred time.Time `xml:"starred,attr,omitempty"`
AlbumID string `xml:"albumId,attr,omitempty"`
ArtistID string `xml:"artistId,attr,omitempty"`
Type string `xml:"type,attr,omitempty"` // May be one of music, podcast, audiobook, video
BookmarkPosition int64 `xml:"bookmarkPosition,attr,omitempty"`
OriginalWidth int `xml:"originalWidth,attr,omitempty"`
OriginalHeight int `xml:"originalHeight,attr,omitempty"`
}
type PlayQueue struct {
Entry []*Child `xml:"http://subsonic.org/restapi entry,omitempty"`
Current int `xml:"current,attr,omitempty"`
Position int64 `xml:"position,attr,omitempty"`
Username string `xml:"username,attr"`
Changed time.Time `xml:"changed,attr"`
ChangedBy string `xml:"changedBy,attr"`
}
func (t *PlayQueue) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type T PlayQueue
var layout struct {
*T
Changed *xsdDateTime `xml:"changed,attr"`
}
layout.T = (*T)(t)
layout.Changed = (*xsdDateTime)(&layout.T.Changed)
return e.EncodeElement(layout, start)
}
func (t *PlayQueue) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T PlayQueue
var overlay struct {
*T
Changed *xsdDateTime `xml:"changed,attr"`
}
overlay.T = (*T)(t)
overlay.Changed = (*xsdDateTime)(&overlay.T.Changed)
return d.DecodeElement(&overlay, &start)
}
// Playlist is a collection of songs with metadata like a name, comment, and information about the total duration of the playlist.
type Playlist struct {
ID string `xml:"id,attr"` // Added manually
Entry []*Child `xml:"http://subsonic.org/restapi entry,omitempty"` // Merged from PlaylistWithSongs
AllowedUser []string `xml:"http://subsonic.org/restapi allowedUser,omitempty"`
Name string `xml:"name,attr"`
Comment string `xml:"comment,attr,omitempty"`
Owner string `xml:"owner,attr,omitempty"`
Public bool `xml:"public,attr,omitempty"`
SongCount int `xml:"songCount,attr"`
Duration int `xml:"duration,attr"`
Created time.Time `xml:"created,attr"`
Changed time.Time `xml:"changed,attr"`
CoverArt string `xml:"coverArt,attr,omitempty"`
}
type playlists struct {
Playlist []*Playlist `xml:"http://subsonic.org/restapi playlist,omitempty"`
}
type PodcastChannel struct {
Episode []*PodcastEpisode `xml:"http://subsonic.org/restapi episode,omitempty"`
Url string `xml:"url,attr"`
Title string `xml:"title,attr,omitempty"`
Description string `xml:"description,attr,omitempty"`
CoverArt string `xml:"coverArt,attr,omitempty"`
OriginalImageUrl string `xml:"originalImageUrl,attr,omitempty"`
Status string `xml:"status,attr"` // May be one of new, downloading, completed, error, deleted, skipped
ErrorMessage string `xml:"errorMessage,attr,omitempty"`
}
type PodcastEpisode struct {
StreamID string `xml:"streamId,attr,omitempty"`
ChannelID string `xml:"channelId,attr"`
Description string `xml:"description,attr,omitempty"`
Status string `xml:"status,attr"` // May be one of new, downloading, completed, error, deleted, skipped
PublishDate time.Time `xml:"publishDate,attr,omitempty"`
Parent string `xml:"parent,attr,omitempty"`
IsDir bool `xml:"isDir,attr"`
Title string `xml:"title,attr"`
Album string `xml:"album,attr,omitempty"`
Artist string `xml:"artist,attr,omitempty"`
Track int `xml:"track,attr,omitempty"`
Year int `xml:"year,attr,omitempty"`
Genre string `xml:"genre,attr,omitempty"`
CoverArt string `xml:"coverArt,attr,omitempty"`
Size int64 `xml:"size,attr,omitempty"`
ContentType string `xml:"contentType,attr,omitempty"`
Suffix string `xml:"suffix,attr,omitempty"`
TranscodedContentType string `xml:"transcodedContentType,attr,omitempty"`
TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty"`
Duration int `xml:"duration,attr,omitempty"`
BitRate int `xml:"bitRate,attr,omitempty"`
Path string `xml:"path,attr,omitempty"`
IsVideo bool `xml:"isVideo,attr,omitempty"`
UserRating int `xml:"userRating,attr,omitempty"`
AverageRating float64 `xml:"averageRating,attr,omitempty"`
PlayCount int64 `xml:"playCount,attr,omitempty"`
DiscNumber int `xml:"discNumber,attr,omitempty"`
Created time.Time `xml:"created,attr,omitempty"`
Starred time.Time `xml:"starred,attr,omitempty"`
AlbumID string `xml:"albumId,attr,omitempty"`
ArtistID string `xml:"artistId,attr,omitempty"`
Type string `xml:"type,attr,omitempty"` // May be one of music, podcast, audiobook, video
BookmarkPosition int64 `xml:"bookmarkPosition,attr,omitempty"`
OriginalWidth int `xml:"originalWidth,attr,omitempty"`
OriginalHeight int `xml:"originalHeight,attr,omitempty"`
}
func (t *PodcastEpisode) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type T PodcastEpisode
var layout struct {
*T
PublishDate *xsdDateTime `xml:"publishDate,attr,omitempty"`
Created *xsdDateTime `xml:"created,attr,omitempty"`
Starred *xsdDateTime `xml:"starred,attr,omitempty"`
}
layout.T = (*T)(t)
layout.PublishDate = (*xsdDateTime)(&layout.T.PublishDate)
layout.Created = (*xsdDateTime)(&layout.T.Created)
layout.Starred = (*xsdDateTime)(&layout.T.Starred)
return e.EncodeElement(layout, start)
}
func (t *PodcastEpisode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T PodcastEpisode
var overlay struct {
*T
PublishDate *xsdDateTime `xml:"publishDate,attr,omitempty"`
Created *xsdDateTime `xml:"created,attr,omitempty"`
Starred *xsdDateTime `xml:"starred,attr,omitempty"`
}
overlay.T = (*T)(t)
overlay.PublishDate = (*xsdDateTime)(&overlay.T.PublishDate)
overlay.Created = (*xsdDateTime)(&overlay.T.Created)
overlay.Starred = (*xsdDateTime)(&overlay.T.Starred)
return d.DecodeElement(&overlay, &start)
}
type podcasts struct {
Channel []*PodcastChannel `xml:"http://subsonic.org/restapi channel,omitempty"`
}
// Response is the main target for unmarshalling data from the API - everything within the "subsonic-response" key
type Response struct {
License *License `xml:"http://subsonic.org/restapi license"`
MusicFolders *musicFolders `xml:"http://subsonic.org/restapi musicFolders"`
Indexes *Indexes `xml:"http://subsonic.org/restapi indexes"`
Directory *Directory `xml:"http://subsonic.org/restapi directory"`
Genres *genres `xml:"http://subsonic.org/restapi genres"`
Artists *ArtistsID3 `xml:"http://subsonic.org/restapi artists"`
Artist *ArtistID3 `xml:"http://subsonic.org/restapi artist"`
Album *AlbumID3 `xml:"http://subsonic.org/restapi album"`
Song *Child `xml:"http://subsonic.org/restapi song"`
NowPlaying *nowPlaying `xml:"http://subsonic.org/restapi nowPlaying"`
SearchResult2 *SearchResult2 `xml:"http://subsonic.org/restapi searchResult2"`
SearchResult3 *SearchResult3 `xml:"http://subsonic.org/restapi searchResult3"`
Playlists *playlists `xml:"http://subsonic.org/restapi playlists"`
Playlist *Playlist `xml:"http://subsonic.org/restapi playlist"`
JukeboxStatus *JukeboxStatus `xml:"http://subsonic.org/restapi jukeboxStatus"`
JukeboxPlaylist *JukeboxPlaylist `xml:"http://subsonic.org/restapi jukeboxPlaylist"`
Users *users `xml:"http://subsonic.org/restapi users"`
User *User `xml:"http://subsonic.org/restapi user"`
ChatMessages *chatMessages `xml:"http://subsonic.org/restapi chatMessages"`
AlbumList *albumList `xml:"http://subsonic.org/restapi albumList"`
AlbumList2 *albumList2 `xml:"http://subsonic.org/restapi albumList2"`
RandomSongs *songs `xml:"http://subsonic.org/restapi randomSongs"`
SongsByGenre *songs `xml:"http://subsonic.org/restapi songsByGenre"`
Lyrics *Lyrics `xml:"http://subsonic.org/restapi lyrics"`
Podcasts *podcasts `xml:"http://subsonic.org/restapi podcasts"`
NewestPodcasts *newestPodcasts `xml:"http://subsonic.org/restapi newestPodcasts"`
InternetRadioStations *internetRadioStations `xml:"http://subsonic.org/restapi internetRadioStations"`
Bookmarks *bookmarks `xml:"http://subsonic.org/restapi bookmarks"`
PlayQueue *PlayQueue `xml:"http://subsonic.org/restapi playQueue"`
Shares *shares `xml:"http://subsonic.org/restapi shares"`
Starred *Starred `xml:"http://subsonic.org/restapi starred"`
Starred2 *Starred2 `xml:"http://subsonic.org/restapi starred2"`
AlbumInfo *AlbumInfo `xml:"http://subsonic.org/restapi albumInfo"`
ArtistInfo *ArtistInfo `xml:"http://subsonic.org/restapi artistInfo"`
ArtistInfo2 *ArtistInfo2 `xml:"http://subsonic.org/restapi artistInfo2"`
SimilarSongs *similarSongs `xml:"http://subsonic.org/restapi similarSongs"`
SimilarSongs2 *similarSongs2 `xml:"http://subsonic.org/restapi similarSongs2"`
TopSongs *topSongs `xml:"http://subsonic.org/restapi topSongs"`
ScanStatus *ScanStatus `xml:"http://subsonic.org/restapi scanStatus"`
Error *Error `xml:"http://subsonic.org/restapi error"`
Status string `xml:"status,attr"` // May be one of ok, failed
Version string `xml:"version,attr"` // Must match the pattern \d+\.\d+\.\d+
}
type ScanStatus struct {
Scanning bool `xml:"scanning,attr"`
Count int64 `xml:"count,attr,omitempty"`
}
// SearchResult2 is a collection of songs, albums, and artists related to a query.
type SearchResult2 struct {
Artist []*Artist `xml:"http://subsonic.org/restapi artist,omitempty"`
Album []*Child `xml:"http://subsonic.org/restapi album,omitempty"`
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
// SearchResult3 is a collection of songs, albums, and artists related to a query.
type SearchResult3 struct {
Artist []*ArtistID3 `xml:"http://subsonic.org/restapi artist,omitempty"`
Album []*AlbumID3 `xml:"http://subsonic.org/restapi album,omitempty"`
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
type Share struct {
Entry []*Child `xml:"http://subsonic.org/restapi entry,omitempty"`
Url string `xml:"url,attr"`
Description string `xml:"description,attr,omitempty"`
Username string `xml:"username,attr"`
Created time.Time `xml:"created,attr"`
Expires time.Time `xml:"expires,attr,omitempty"`
LastVisited time.Time `xml:"lastVisited,attr,omitempty"`
VisitCount int `xml:"visitCount,attr"`
}
func (t *Share) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type T Share
var layout struct {
*T
Created *xsdDateTime `xml:"created,attr"`
Expires *xsdDateTime `xml:"expires,attr,omitempty"`
LastVisited *xsdDateTime `xml:"lastVisited,attr,omitempty"`
}
layout.T = (*T)(t)
layout.Created = (*xsdDateTime)(&layout.T.Created)
layout.Expires = (*xsdDateTime)(&layout.T.Expires)
layout.LastVisited = (*xsdDateTime)(&layout.T.LastVisited)
return e.EncodeElement(layout, start)
}
func (t *Share) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T Share
var overlay struct {
*T
Created *xsdDateTime `xml:"created,attr"`
Expires *xsdDateTime `xml:"expires,attr,omitempty"`
LastVisited *xsdDateTime `xml:"lastVisited,attr,omitempty"`
}
overlay.T = (*T)(t)
overlay.Created = (*xsdDateTime)(&overlay.T.Created)
overlay.Expires = (*xsdDateTime)(&overlay.T.Expires)
overlay.LastVisited = (*xsdDateTime)(&overlay.T.LastVisited)
return d.DecodeElement(&overlay, &start)
}
type shares struct {
Share []*Share `xml:"http://subsonic.org/restapi share,omitempty"`
}
type similarSongs struct {
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
type similarSongs2 struct {
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
type songs struct {
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
// Starred is a collection of songs, albums, and artists annotated by a user as starred.
type Starred struct {
Artist []*Artist `xml:"http://subsonic.org/restapi artist,omitempty"`
Album []*Child `xml:"http://subsonic.org/restapi album,omitempty"`
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
// Starred2 is a collection of songs, albums, and artists organized by ID3 tags annotated by a user as starred.
type Starred2 struct {
Artist []*ArtistID3 `xml:"http://subsonic.org/restapi artist,omitempty"`
Album []*AlbumID3 `xml:"http://subsonic.org/restapi album,omitempty"`
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
type topSongs struct {
Song []*Child `xml:"http://subsonic.org/restapi song,omitempty"`
}
type User struct {
Folder []int `xml:"http://subsonic.org/restapi folder,omitempty"`
Username string `xml:"username,attr"`
Email string `xml:"email,attr,omitempty"`
ScrobblingEnabled bool `xml:"scrobblingEnabled,attr"`
MaxBitRate int `xml:"maxBitRate,attr,omitempty"`
AdminRole bool `xml:"adminRole,attr"`
SettingsRole bool `xml:"settingsRole,attr"`
DownloadRole bool `xml:"downloadRole,attr"`
UploadRole bool `xml:"uploadRole,attr"`
PlaylistRole bool `xml:"playlistRole,attr"`
CoverArtRole bool `xml:"coverArtRole,attr"`
CommentRole bool `xml:"commentRole,attr"`
PodcastRole bool `xml:"podcastRole,attr"`
StreamRole bool `xml:"streamRole,attr"`
JukeboxRole bool `xml:"jukeboxRole,attr"`
ShareRole bool `xml:"shareRole,attr"`
VideoConversionRole bool `xml:"videoConversionRole,attr"`
AvatarLastChanged time.Time `xml:"avatarLastChanged,attr,omitempty"`
}
func (t *User) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
type T User
var layout struct {
*T
AvatarLastChanged *xsdDateTime `xml:"avatarLastChanged,attr,omitempty"`
}
layout.T = (*T)(t)
layout.AvatarLastChanged = (*xsdDateTime)(&layout.T.AvatarLastChanged)
return e.EncodeElement(layout, start)
}
func (t *User) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T User
var overlay struct {
*T
AvatarLastChanged *xsdDateTime `xml:"avatarLastChanged,attr,omitempty"`
}
overlay.T = (*T)(t)
overlay.AvatarLastChanged = (*xsdDateTime)(&overlay.T.AvatarLastChanged)
return d.DecodeElement(&overlay, &start)
}
type users struct {
User []*User `xml:"http://subsonic.org/restapi user,omitempty"`
}
type xsdDateTime time.Time
func (t *xsdDateTime) UnmarshalText(text []byte) error {
return _unmarshalTime(text, (*time.Time)(t), "2006-01-02T15:04:05.999999999")
}
func (t xsdDateTime) MarshalText() ([]byte, error) {
return []byte((time.Time)(t).Format("2006-01-02T15:04:05.999999999")), nil
}
func (t xsdDateTime) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if (time.Time)(t).IsZero() {
return nil
}
m, err := t.MarshalText()
if err != nil {
return err
}
return e.EncodeElement(m, start)
}
func (t xsdDateTime) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
if (time.Time)(t).IsZero() {
return xml.Attr{}, nil
}
m, err := t.MarshalText()
return xml.Attr{Name: name, Value: string(m)}, err
}
func _unmarshalTime(text []byte, t *time.Time, format string) (err error) {
s := string(bytes.TrimSpace(text))
*t, err = time.Parse(format, s)
if _, ok := err.(*time.ParseError); ok {
*t, err = time.Parse(format+"Z07:00", s)
}
return err
}

76
vendor/github.com/delucks/go-subsonic/playlist.go generated vendored Normal file
View file

@ -0,0 +1,76 @@
package subsonic
import "errors"
// GetPlaylists returns all playlists a user is allowed to play.
//
// Optional Parameters:
// user: get playlists visible to this username rather than the current user. Must have admin permission.
func (s *Client) GetPlaylists(parameters map[string]string) ([]*Playlist, error) {
resp, err := s.Get("getPlaylists", parameters)
if err != nil {
return nil, err
}
return resp.Playlists.Playlist, nil
}
// GetPlaylist returns a listing of files in a saved playlist.
func (s *Client) GetPlaylist(id string) (*Playlist, error) {
resp, err := s.Get("getPlaylist", map[string]string{"id": id})
if err != nil {
return nil, err
}
return resp.Playlist, nil
}
// CreatePlaylist creates (or updates) a playlist.
//
// Optional Parameters:
// songId: ID of a song in the playlist. Use one songId parameter for each song in the playlist.
// Mutually Exclusive Parameters:
// playlistId: The playlist ID.
// name: The human-readable name of the playlist.
//
// This returns a Playlist object in Subsonic > 1.14.0, so it cannot consistently return a *Playlist
func (s *Client) CreatePlaylist(parameters map[string]string) error {
_, idPresent := parameters["playlistId"]
_, namePresent := parameters["name"]
if !(idPresent || namePresent) {
return errors.New("One of name or playlistId is mandatory, to create or update a playlist respectively")
}
_, err := s.Get("createPlaylist", parameters)
if err != nil {
return err
}
return nil
}
// UpdatePlaylist updates a playlist. Only the owner of a playlist is allowed to update it.
//
// Optional Parameters:
// name: The human-readable name of the playlist.
// comment: The playlist comment.
// public: true if the playlist should be visible to all users, false otherwise.
// songIdToAdd: Add this song with this ID to the playlist. Multiple parameters allowed.
// songIndexToRemove: Remove the song at this position in the playlist. Multiple parameters allowed.
func (s *Client) UpdatePlaylist(playlistId string, parameters map[string]string) error {
params := make(map[string]string)
for k, v := range parameters {
params[k] = v
}
params["playlistId"] = playlistId
_, err := s.Get("updatePlaylist", params)
if err != nil {
return err
}
return nil
}
// DeletePlaylist deletes a saved playlist.
func (s *Client) DeletePlaylist(playlistId string) error {
_, err := s.Get("deletePlaylist", map[string]string{"id": playlistId})
if err != nil {
return err
}
return nil
}

160
vendor/github.com/delucks/go-subsonic/retrieval.go generated vendored Normal file
View file

@ -0,0 +1,160 @@
package subsonic
import (
"encoding/xml"
"fmt"
"image"
"io"
"io/ioutil"
"net/url"
"strings"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
)
// Stream returns the contents of a song, optionally transcoded, from the server.
//
// Optional Parameters:
// maxBitRate: (Since 1.2.0) If specified, the server will attempt to limit the bitrate to this value, in kilobits per second. If set to zero, no limit is imposed.
// format: (Since 1.6.0) Specifies the preferred target format (e.g., "mp3" or "flv") in case there are multiple applicable transcodings. Starting with 1.9.0 you can use the special value "raw" to disable transcoding.
// timeOffset: Only applicable to video streaming. If specified, start streaming at the given offset (in seconds) into the video. Typically used to implement video skipping.
// size: (Since 1.6.0) Only applicable to video streaming. Requested video size specified as WxH, for instance "640x480".
// estimateContentLength: (Since 1.8.0). If set to "true", the Content-Length HTTP header will be set to an estimated value for transcoded or downsampled media.
// converted: (Since 1.14.0) Only applicable to video streaming. Subsonic can optimize videos for streaming by converting them to MP4. If a conversion exists for the video in question, then setting this parameter to "true" will cause the converted video to be returned instead of the original.
func (s *Client) Stream(id string, parameters map[string]string) (io.Reader, error) {
params := url.Values{}
params.Add("id", id)
for k, v := range parameters {
params.Add(k, v)
}
response, err := s.Request("GET", "stream", params)
if err != nil {
return nil, err
}
contentType := response.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "text/xml") || strings.HasPrefix(contentType, "application/xml") {
// An error was returned
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := Response{}
err = xml.Unmarshal(responseBody, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
err = fmt.Errorf("Error #%d: %s\n", resp.Error.Code, resp.Error.Message)
} else {
err = fmt.Errorf("An error occurred: %#v\n", resp)
}
return nil, err
}
return response.Body, nil
}
// Download returns a given media file. Similar to stream, but this method returns the original media data without transcoding or downsampling.
func (s *Client) Download(id string) (io.Reader, error) {
params := url.Values{}
params.Add("id", id)
response, err := s.Request("GET", "download", params)
if err != nil {
return nil, err
}
contentType := response.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "text/xml") || strings.HasPrefix(contentType, "application/xml") {
// An error was returned
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := Response{}
err = xml.Unmarshal(responseBody, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
err = fmt.Errorf("Error #%d: %s\n", resp.Error.Code, resp.Error.Message)
} else {
err = fmt.Errorf("An error occurred: %#v\n", resp)
}
return nil, err
}
return response.Body, nil
}
// GetCoverArt returns a cover art image for a song, album, or artist.
//
// Optional Parameters:
// size: If specified, scale image to this size.
func (s *Client) GetCoverArt(id string, parameters map[string]string) (image.Image, error) {
params := url.Values{}
params.Add("id", id)
if size, ok := parameters["size"]; ok {
params.Add("size", size)
}
response, err := s.Request("GET", "getCoverArt", params)
if err != nil {
return nil, err
}
contentType := response.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "text/xml") || strings.HasPrefix(contentType, "application/xml") {
// An error was returned
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := Response{}
err = xml.Unmarshal(responseBody, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
err = fmt.Errorf("Error #%d: %s\n", resp.Error.Code, resp.Error.Message)
} else {
err = fmt.Errorf("An error occurred: %#v\n", resp)
}
return nil, err
}
image, _, err := image.Decode(response.Body)
if err != nil {
return nil, err
}
return image, nil
}
// GetAvatar returns the avatar (personal image) for a user.
func (s *Client) GetAvatar(username string) (image.Image, error) {
params := url.Values{}
params.Add("username", username)
response, err := s.Request("GET", "getAvatar", params)
if err != nil {
return nil, err
}
contentType := response.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "text/xml") || strings.HasPrefix(contentType, "application/xml") {
// An error was returned
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := Response{}
err = xml.Unmarshal(responseBody, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
err = fmt.Errorf("Error #%d: %s\n", resp.Error.Code, resp.Error.Message)
} else {
err = fmt.Errorf("An error occurred: %#v\n", resp)
}
return nil, err
}
image, _, err := image.Decode(response.Body)
if err != nil {
return nil, err
}
return image, nil
}

19
vendor/github.com/delucks/go-subsonic/scanning.go generated vendored Normal file
View file

@ -0,0 +1,19 @@
package subsonic
// GetScanStatus returns the current status for media library scanning.
func (c *Client) GetScanStatus() (*ScanStatus, error) {
resp, err := c.Get("getScanStatus", nil)
if err != nil {
return nil, err
}
return resp.ScanStatus, nil
}
// StartScan initiates a rescan of the media libraries.
func (c *Client) StartScan() (*ScanStatus, error) {
resp, err := c.Get("startScan", nil)
if err != nil {
return nil, err
}
return resp.ScanStatus, nil
}

46
vendor/github.com/delucks/go-subsonic/search.go generated vendored Normal file
View file

@ -0,0 +1,46 @@
package subsonic
// Search2 returns albums, artists and songs matching the given search criteria. Supports paging through the result.
//
// Optional Parameters:
// artistCount: Maximum number of artists to return. (Default 20)
// artistOffset: Search result offset for artists. Used for paging.
// albumCount: Maximum number of albums to return. (Default 20)
// albumOffset: Search result offset for albums. Used for paging.
// songCount: Maximum number of songs to return. (Default 20)
// songOffset: Search result offset for songs. Used for paging.
// musicFolderId: (Since 1.12.0) Only return results from the music folder with the given ID. See getMusicFolders.
func (s *Client) Search2(query string, parameters map[string]string) (*SearchResult2, error) {
params := make(map[string]string)
params["query"] = query
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("search2", params)
if err != nil {
return nil, err
}
return resp.SearchResult2, nil
}
// Search3 returns albums, artists and songs matching the given search criteria like Search2, but organized according to id3 tags.
// Optional Parameters:
// artistCount: Maximum number of artists to return. (Default 20)
// artistOffset: Search result offset for artists. Used for paging.
// albumCount: Maximum number of albums to return. (Default 20)
// albumOffset: Search result offset for albums. Used for paging.
// songCount: Maximum number of songs to return. (Default 20)
// songOffset: Search result offset for songs. Used for paging.
// musicFolderId: (Since 1.12.0) Only return results from the music folder with the given ID. See getMusicFolders.
func (s *Client) Search3(query string, parameters map[string]string) (*SearchResult3, error) {
params := make(map[string]string)
params["query"] = query
for k, v := range parameters {
params[k] = v
}
resp, err := s.Get("search3", params)
if err != nil {
return nil, err
}
return resp.SearchResult3, nil
}

133
vendor/github.com/delucks/go-subsonic/test.sh generated vendored Normal file
View file

@ -0,0 +1,133 @@
#!/usr/bin/env bash
# This script performs automated testing of go-subsonic on Airsonic and Navidrome music servers.
# It wraps docker-compose to download a sample music library before creating instances of these servers,
# allowing the go-subsonic tests to run fully against the sample instances.
err() {
echo "$1" >&2
exit 1
}
log() {
SEV="$1"
shift
echo "$(date +%Y-%m-%d\ %T) - ${SEV^^} - $*" >&2
}
for dependency in curl docker-compose; do
hash "$dependency" 2>/dev/null || err "$dependency must be installed"
done
SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
NAVIDROME_PORT=4533
download_audionautix() {
# Audionautix Acoustic is a CC licensed album from Jason Shaw available from Free Music Archive.
# https://archive.org/details/Audionautix_Acoustic-9870
BASEURL="https://archive.org/download/Audionautix_Acoustic-9870/Jason_Shaw_-_"
TRACKS=("12_MORNINGS.ogg" "ACOUSTIC_BLUES.ogg" "FUNKY_JUNKY.ogg" "JENNYS_THEME.ogg" "LAZY_DAY.ogg" "MOUNTAIN_SUN.ogg" "ONE_FINE_DAY.ogg" "RIVER_MEDITATION.ogg" "ROCKY_TOP.ogg" "RUNNING_WATERS.ogg" "SERENITY.ogg" "SIDEWALK.ogg" "SNAPPY.ogg" "SOLO_ACOUSTIC_GUITAR.ogg" "SOUTH_OF_THE_BORDER.ogg" "TENNESEE_HAYRIDE.ogg" "THINGAMAJIG.ogg" "TRAVEL_LIGHT.ogg" "WHEELS.ogg" "WORDS.ogg")
DESTINATION="${SOURCE_DIR}/build/music/Jason Shaw/Audionautix"
mkdir -p "$DESTINATION"
for track in "${TRACKS[@]}"
do
if test -f "$DESTINATION/$track"
then
log info "Skipping download of Audionautix $track"
else
curl -L -o "$DESTINATION/$track" "${BASEURL}${track}"
fi
done
}
download_grabbag() {
# Grab Bag is a CC-licensed jazz album from Jahzzar available from Free Music Archive.
# https://archive.org/details/Grab_Bag-12446
BASEURL="https://archive.org/download/Grab_Bag-12446/"
DESTINATION="${SOURCE_DIR}/build/music/Jahzzar/Grab Bag"
TRACKS=("01_-_Dummy.ogg" "02_-_Candlelight.ogg" "03_-_Trust.ogg" "04_-_Guilty.ogg" "05_-_Storm.ogg")
mkdir -p "$DESTINATION"
for track in "${TRACKS[@]}"
do
if test -f "$DESTINATION/$track"
then
log info "Skipping download of Grab Bag $track"
else
curl -L -o "$DESTINATION/$track" "${BASEURL}${track}"
fi
done
}
download_fourseasons() {
# This is a CC-licensed recording of Vivaldi's The Four Seasons performed by John Harrison with the Wichita State University Chamber Players
# https://archive.org/details/The_Four_Seasons_Vivaldi-10361
BASEURL="https://archive.org/download/The_Four_Seasons_Vivaldi-10361/John_Harrison_with_the_Wichita_State_University_Chamber_Players_-_"
DESTINATION="${SOURCE_DIR}/build/music/Vivaldi/The Four Seasons"
TRACKS=("01_-_Spring_Mvt_1_Allegro.ogg" "02_-_Spring_Mvt_2_Largo.ogg" "03_-_Spring_Mvt_3_Allegro_pastorale.ogg" "04_-_Summer_Mvt_1_Allegro_non_molto.ogg" "05_-_Summer_Mvt_2_Adagio.ogg" "06_-_Summer_Mvt_3_Presto.ogg" "07_-_Autumn_Mvt_1_Allegro.ogg" "08_-_Autumn_Mvt_2_Adagio_molto.ogg" "09_-_Autumn_Mvt_3_Allegro.ogg" "10_-_Winter_Mvt_1_Allegro_non_molto.ogg" "11_-_Winter_Mvt_2_Largo.ogg" "12_-_Winter_Mvt_3_Allegro.ogg")
mkdir -p "$DESTINATION"
for track in "${TRACKS[@]}"
do
if test -f "$DESTINATION/$track"
then
log info "Skipping download of The Four Seasons $track"
else
curl -L -o "$DESTINATION/$track" "${BASEURL}${track}"
fi
done
}
download_sample_audio() {
download_audionautix
download_grabbag
download_fourseasons
}
configure_airsonic() {
cat << DOG > build/data/airsonic.properties
JWTKey=q7q8u331n25gkvgjiehutl3e4u
SettingsChanged=$(date +%s)000
# Try to force immediate library scan
LastScanned=0
IndexCreationInterval=1
# We want to use id3 tags for most tests
OrganizeByFolderStructure=false
DOG
}
create_navidrome_user() {
# navidrome does not ship with a built-in user, so we call the API to create a known user before test execution
curl -X POST -H "Content-Type: application/json" "http://localhost:${NAVIDROME_PORT}/auth/createAdmin" --data '{"username":"admin", "password":"admin"}'
echo
}
clear_data_dir() {
rm -rf ./build/data/*
}
main() {
log info "Downloading sample music into ./build/music"
download_sample_audio
# Create or restart the docker containers of Airsonic and Navidrome
if [[ $(docker-compose top) ]]
then
# If the current composition is running, restart it to pick up possible changes
log warn "Downing currently running docker containers"
docker-compose down
fi
log info "Removing excess data"
clear_data_dir
log info "Configuring Airsonic"
configure_airsonic # This must occur in the middle so settings aren't overwritten
log info "Bringing up containers"
docker-compose up -d
sleep 10
log info "Creating Navidrome administrator (admin/admin)"
create_navidrome_user
go test . -test.v -run 'Navidrome' -count=1
log info "Waiting 30 seconds total for Airsonic to scan the music library..."
sleep 20
go test . -test.v -run 'Airsonic' -count=1
}
main

104
vendor/github.com/delucks/go-subsonic/user.go generated vendored Normal file
View file

@ -0,0 +1,104 @@
package subsonic
// GetUser gets details about a given user, including which authorization roles and folder access it has. Can be used to enable/disable certain features in the client, such as jukebox control.
func (c *Client) GetUser(username string) (*User, error) {
resp, err := c.Get("getUser", map[string]string{"username": username})
if err != nil {
return nil, err
}
return resp.User, nil
}
// GetUsers gets details about all users, including which authorization roles and folder access they have. Only users with admin privileges are allowed to call this method.
func (c *Client) GetUsers() ([]*User, error) {
resp, err := c.Get("getUsers", nil)
if err != nil {
return nil, err
}
return resp.Users.User, nil
}
// CreateUser creates a new Subsonic user.
//
// Optional Parameters Default Description
// ldapAuthenticated false Whether the user is authenicated in LDAP.
// adminRole false Whether the user is administrator.
// settingsRole true Whether the user is allowed to change personal settings and password.
// streamRole true Whether the user is allowed to play files.
// jukeboxRole false Whether the user is allowed to play files in jukebox mode.
// downloadRole false Whether the user is allowed to download files.
// uploadRole false Whether the user is allowed to upload files.
// playlistRole false Whether the user is allowed to create and delete playlists. Since 1.8.0, changing this role has no effect.
// coverArtRole false Whether the user is allowed to change cover art and tags.
// commentRole false Whether the user is allowed to create and edit comments and ratings.
// podcastRole false Whether the user is allowed to administrate Podcasts.
// shareRole false (Since 1.8.0) Whether the user is allowed to share files with anyone.
// videoConversionRole false (Since 1.15.0) Whether the user is allowed to start video conversions.
// musicFolderId All (Since 1.12.0) IDs of the music folders the user is allowed access to. Include the parameter once for each folder.
func (c *Client) CreateUser(username, password, email string, parameters map[string]string) error {
params := make(map[string]string)
params["username"] = username
params["password"] = password
params["email"] = email
for k, v := range parameters {
params[k] = v
}
_, err := c.Get("createUser", params)
if err != nil {
return err
}
return nil
}
// UpdateUser modifies an existing Subsonic user.
//
// Optional Parameters:
// password The password of the user, either in clear text of hex-encoded.
// email The email address of the user.
// ldapAuthenticated Whether the user is authenicated in LDAP.
// adminRole Whether the user is administrator.
// settingsRole Whether the user is allowed to change personal settings and password.
// streamRole Whether the user is allowed to play files.
// jukeboxRole Whether the user is allowed to play files in jukebox mode.
// downloadRole Whether the user is allowed to download files.
// uploadRole Whether the user is allowed to upload files.
// coverArtRole Whether the user is allowed to change cover art and tags.
// commentRole Whether the user is allowed to create and edit comments and ratings.
// podcastRole Whether the user is allowed to administrate Podcasts.
// shareRole (Since 1.8.0) Whether the user is allowed to share files with anyone.
// videoConversionRole (Since 1.15.0) Whether the user is allowed to start video conversions.
// musicFolderId (Since 1.12.0) IDs of the music folders the user is allowed access to. Include the parameter once for each folder.
// maxBitRate (Since 1.13.0) The maximum bit rate (in Kbps) for the user. Audio streams of higher bit rates are automatically downsampled to this bit rate. Legal values: 0 (no limit), 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320.
func (c *Client) UpdateUser(username string, parameters map[string]string) error {
params := make(map[string]string)
params["username"] = username
for k, v := range parameters {
params[k] = v
}
_, err := c.Get("updateUser", params)
if err != nil {
return err
}
return nil
}
// DeleteUser deletes an existing Subsonic user.
func (s *Client) DeleteUser(username string) error {
_, err := s.Get("deleteUser", map[string]string{"username": username})
if err != nil {
return err
}
return nil
}
// ChangePassword changes the password of an existing Subsonic user, using the following parameters. You can only change your own password unless you have admin privileges.
func (c *Client) ChangePassword(username, password string) error {
_, err := c.Get("changePassword", map[string]string{
"username": username,
"password": password,
})
if err != nil {
return err
}
return nil
}

1
vendor/github.com/ebitengine/oto/v3/.clang-format generated vendored Normal file
View file

@ -0,0 +1 @@
CommentPragmas: '^go:build'

1
vendor/github.com/ebitengine/oto/v3/.gitattributes generated vendored Normal file
View file

@ -0,0 +1 @@
internal/oboe/** linguist-vendored

2
vendor/github.com/ebitengine/oto/v3/.gitignore generated vendored Normal file
View file

@ -0,0 +1,2 @@
.DS_Store
*~

201
vendor/github.com/ebitengine/oto/v3/LICENSE generated vendored Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

234
vendor/github.com/ebitengine/oto/v3/README.md generated vendored Normal file
View file

@ -0,0 +1,234 @@
# Oto (v3)
[![Go Reference](https://pkg.go.dev/badge/github.com/ebitengine/oto/v3.svg)](https://pkg.go.dev/github.com/ebitengine/oto/v3)
[![Build Status](https://github.com/ebitengine/oto/actions/workflows/test.yml/badge.svg)](https://github.com/ebitengine/oto/actions?query=workflow%3Atest)
A low-level library to play sound.
- [Oto (v3)](#oto-v3)
- [Platforms](#platforms)
- [Prerequisite](#prerequisite)
- [macOS](#macos)
- [iOS](#ios)
- [Linux](#linux)
- [FreeBSD, OpenBSD](#freebsd-openbsd)
- [Usage](#usage)
- [Playing sounds from memory](#playing-sounds-from-memory)
- [Playing sounds by file streaming](#playing-sounds-by-file-streaming)
- [Advanced usage](#advanced-usage)
- [Crosscompiling](#crosscompiling)
## Platforms
- Windows (no Cgo required!)
- macOS (no Cgo required!)
- Linux
- FreeBSD
- OpenBSD
- Android
- iOS
- WebAssembly
- Nintendo Switch
- Xbox
## Prerequisite
On some platforms you will need a C/C++ compiler in your path that Go can use.
- iOS: On newer macOS versions type `clang` on your terminal and a dialog with installation instructions will appear if you don't have it
- If you get an error with clang use xcode instead `xcode-select --install`
- Linux and other Unix systems: Should be installed by default, but if not try [GCC](https://gcc.gnu.org/) or [Clang](https://releases.llvm.org/download.html)
### macOS
Oto requires `AudioToolbox.framework`, but this is automatically linked.
### iOS
Oto requires these frameworks:
- `AVFoundation.framework`
- `AudioToolbox.framework`
Add them to "Linked Frameworks and Libraries" on your Xcode project.
### Linux
ALSA is required. On Ubuntu or Debian, run this command:
```sh
apt install libasound2-dev
```
On RedHat-based linux distributions, run:
```sh
dnf install alsa-lib-devel
```
In most cases this command must be run by root user or through `sudo` command.
### FreeBSD, OpenBSD
BSD systems are not tested well. If ALSA works, Oto should work.
## Usage
The two main components of Oto are a `Context` and `Players`. The context handles interactions with
the OS and audio drivers, and as such there can only be **one** context in your program.
From a context you can create any number of different players, where each player is given an `io.Reader` that
it reads bytes representing sounds from and plays.
Note that a single `io.Reader` must **not** be used by multiple players.
### Playing sounds from memory
The following is an example of loading and playing an MP3 file:
```go
package main
import (
"time"
"os"
"github.com/ebitengine/oto/v3"
"github.com/hajimehoshi/go-mp3"
)
func main() {
// Read the mp3 file into memory
fileBytes, err := os.ReadFile("./my-file.mp3")
if err != nil {
panic("reading my-file.mp3 failed: " + err.Error())
}
// Convert the pure bytes into a reader object that can be used with the mp3 decoder
fileBytesReader := bytes.NewReader(fileBytes)
// Decode file
decodedMp3, err := mp3.NewDecoder(fileBytesReader)
if err != nil {
panic("mp3.NewDecoder failed: " + err.Error())
}
// Prepare an Oto context (this will use your default audio device) that will
// play all our sounds. Its configuration can't be changed later.
op := &oto.NewContextOptions{}
// Usually 44100 or 48000. Other values might cause distortions in Oto
op.SampleRate = 44100
// Number of channels (aka locations) to play sounds from. Either 1 or 2.
// 1 is mono sound, and 2 is stereo (most speakers are stereo).
op.ChannelCount = 2
// Format of the source. go-mp3's format is signed 16bit integers.
op.Format = oto.FormatSignedInt16LE
// Remember that you should **not** create more than one context
otoCtx, readyChan, err := oto.NewContext(op)
if err != nil {
panic("oto.NewContext failed: " + err.Error())
}
// It might take a bit for the hardware audio devices to be ready, so we wait on the channel.
<-readyChan
// Create a new 'player' that will handle our sound. Paused by default.
player := otoCtx.NewPlayer(decodedMp3)
// Play starts playing the sound and returns without waiting for it (Play() is async).
player.Play()
// We can wait for the sound to finish playing using something like this
for player.IsPlaying() {
time.Sleep(time.Millisecond)
}
// Now that the sound finished playing, we can restart from the beginning (or go to any location in the sound) using seek
// newPos, err := player.(io.Seeker).Seek(0, io.SeekStart)
// if err != nil{
// panic("player.Seek failed: " + err.Error())
// }
// println("Player is now at position:", newPos)
// player.Play()
// If you don't want the player/sound anymore simply close
err = player.Close()
if err != nil {
panic("player.Close failed: " + err.Error())
}
}
```
### Playing sounds by file streaming
The above example loads the entire file into memory and then plays it. This is great for smaller files
but might be an issue if you are playing a long song since it would take too much memory and too long to load.
In such cases you might want to stream the file. Luckily this is very simple, just use `os.Open`:
```go
package main
import (
"bytes"
"os"
"time"
"github.com/hajimehoshi/go-mp3"
"github.com/hajimehoshi/oto/v3"
)
func main() {
// Open the file for reading. Do NOT close before you finish playing!
file, err := os.Open("./my-file.mp3")
if err != nil {
panic("opening my-file.mp3 failed: " + err.Error())
}
// Decode file. This process is done as the file plays so it won't
// load the whole thing into memory.
decodedMp3, err := mp3.NewDecoder(file)
if err != nil {
panic("mp3.NewDecoder failed: " + err.Error())
}
// Rest is the same...
// Close file only after you finish playing
file.Close()
}
```
The only thing to note about streaming is that the *file* object must be kept alive, otherwise
you might just play static.
To keep it alive not only must you be careful about when you close it, but you might need to keep a reference
to the original file object alive (by for example keeping it in a struct).
### Advanced usage
Players have their own internal audio data buffer, so while for example 200 bytes have been read from the `io.Reader` that
doesn't mean they were all played from the audio device.
Data is moved from io.Reader->internal buffer->audio device, and when the internal buffer moves data to the audio device
is not guaranteed, so there might be a small delay. The amount of data in the buffer can be retrieved
using `Player.UnplayedBufferSize()`.
The size of the underlying buffer of a player can also be set by type-asserting the player object:
```go
myPlayer.(oto.BufferSizeSetter).SetBufferSize(newBufferSize)
```
This works because players implement a `Player` interface and a `BufferSizeSetter` interface.
## Crosscompiling
Crosscompiling to macOS or Windows is as easy as setting `GOOS=darwin` or `GOOS=windows`, respectively.
To crosscompile for other platforms, make sure the libraries for the target architecture are installed, and set
`CGO_ENABLED=1` as Go disables [Cgo](https://golang.org/cmd/cgo/#hdr-Using_cgo_with_the_go_command) on crosscompiles by default.

95
vendor/github.com/ebitengine/oto/v3/api_darwin.go generated vendored Normal file
View file

@ -0,0 +1,95 @@
// Copyright 2022 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"unsafe"
"github.com/ebitengine/purego"
)
const (
avAudioSessionErrorCodeCannotStartPlaying = 0x21706c61 // '!pla'
avAudioSessionErrorCodeCannotInterruptOthers = 0x21696e74 // '!int'
avAudioSessionErrorCodeSiriIsRecording = 0x73697269 // 'siri'
)
const (
kAudioFormatLinearPCM = 0x6C70636D //'lpcm'
)
const (
kAudioFormatFlagIsFloat = 1 << 0 // 0x1
)
type _AudioStreamBasicDescription struct {
mSampleRate float64
mFormatID uint32
mFormatFlags uint32
mBytesPerPacket uint32
mFramesPerPacket uint32
mBytesPerFrame uint32
mChannelsPerFrame uint32
mBitsPerChannel uint32
mReserved uint32
}
type _AudioQueueRef uintptr
type _AudioTimeStamp uintptr
type _AudioStreamPacketDescription struct {
mStartOffset int64
mVariableFramesInPacket uint32
mDataByteSize uint32
}
type _AudioQueueBufferRef *_AudioQueueBuffer
type _AudioQueueBuffer struct {
mAudioDataBytesCapacity uint32
mAudioData uintptr // void*
mAudioDataByteSize uint32
mUserData uintptr // void*
mPacketDescriptionCapacity uint32
mPacketDescriptions *_AudioStreamPacketDescription
mPacketDescriptionCount uint32
}
type _AudioQueueOutputCallback func(inUserData unsafe.Pointer, inAQ _AudioQueueRef, inBuffer _AudioQueueBufferRef)
func initializeAPI() error {
toolbox, err := purego.Dlopen("/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox", purego.RTLD_LAZY|purego.RTLD_GLOBAL)
if err != nil {
return err
}
purego.RegisterLibFunc(&_AudioQueueNewOutput, toolbox, "AudioQueueNewOutput")
purego.RegisterLibFunc(&_AudioQueueAllocateBuffer, toolbox, "AudioQueueAllocateBuffer")
purego.RegisterLibFunc(&_AudioQueueEnqueueBuffer, toolbox, "AudioQueueEnqueueBuffer")
purego.RegisterLibFunc(&_AudioQueueStart, toolbox, "AudioQueueStart")
purego.RegisterLibFunc(&_AudioQueuePause, toolbox, "AudioQueuePause")
return nil
}
var _AudioQueueNewOutput func(inFormat *_AudioStreamBasicDescription, inCallbackProc _AudioQueueOutputCallback, inUserData unsafe.Pointer, inCallbackRunLoop uintptr, inCallbackRunLoopMod uintptr, inFlags uint32, outAQ *_AudioQueueRef) uintptr
var _AudioQueueAllocateBuffer func(inAQ _AudioQueueRef, inBufferByteSize uint32, outBuffer *_AudioQueueBufferRef) uintptr
var _AudioQueueEnqueueBuffer func(inAQ _AudioQueueRef, inBuffer _AudioQueueBufferRef, inNumPacketDescs uint32, inPackets []_AudioStreamPacketDescription) uintptr
var _AudioQueueStart func(inAQ _AudioQueueRef, inStartTime *_AudioTimeStamp) uintptr
var _AudioQueuePause func(inAQ _AudioQueueRef) uintptr

View file

@ -0,0 +1,479 @@
// Copyright 2022 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"fmt"
"runtime"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
var (
ole32 = windows.NewLazySystemDLL("ole32")
)
var (
procCoCreateInstance = ole32.NewProc("CoCreateInstance")
)
type _REFERENCE_TIME int64
var (
uuidIAudioClient2 = windows.GUID{0x726778cd, 0xf60a, 0x4eda, [...]byte{0x82, 0xde, 0xe4, 0x76, 0x10, 0xcd, 0x78, 0xaa}}
uuidIAudioRenderClient = windows.GUID{0xf294acfc, 0x3146, 0x4483, [...]byte{0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}}
uuidIMMDeviceEnumerator = windows.GUID{0xa95664d2, 0x9614, 0x4f35, [...]byte{0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}}
uuidMMDeviceEnumerator = windows.GUID{0xbcde0395, 0xe52f, 0x467c, [...]byte{0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e}}
)
const (
_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM = 0x80000000
_AUDCLNT_STREAMFLAGS_EVENTCALLBACK = 0x00040000
_AUDCLNT_STREAMFLAGS_NOPERSIST = 0x00080000
_COINIT_APARTMENTTHREADED = 0x2
_COINIT_MULTITHREADED = 0
_REFTIMES_PER_SEC = 10000000
_SPEAKER_FRONT_CENTER = 0x4
_SPEAKER_FRONT_LEFT = 0x1
_SPEAKER_FRONT_RIGHT = 0x2
_WAVE_FORMAT_EXTENSIBLE = 0xfffe
)
var (
_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = windows.GUID{0x00000003, 0x0000, 0x0010, [...]byte{0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}
_KSDATAFORMAT_SUBTYPE_PCM = windows.GUID{0x00000001, 0x0000, 0x0010, [...]byte{0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}
)
type _AUDCLNT_ERR uint32
const (
_AUDCLNT_E_DEVICE_INVALIDATED _AUDCLNT_ERR = 0x88890004
_AUDCLNT_E_NOT_INITIALIZED _AUDCLNT_ERR = 0x88890001
_AUDCLNT_E_RESOURCES_INVALIDATED _AUDCLNT_ERR = 0x88890026
)
func isAudclntErr(hresult uint32) bool {
return hresult&0xffff0000 == (1<<31)|(windows.FACILITY_AUDCLNT<<16)
}
func (e _AUDCLNT_ERR) Error() string {
switch e {
case _AUDCLNT_E_DEVICE_INVALIDATED:
return "AUDCLNT_E_DEVICE_INVALIDATED"
case _AUDCLNT_E_RESOURCES_INVALIDATED:
return "AUDCLNT_E_RESOURCES_INVALIDATED"
default:
return fmt.Sprintf("AUDCLNT_ERR(%d)", e)
}
}
type _AUDCLNT_SHAREMODE int32
const (
_AUDCLNT_SHAREMODE_SHARED _AUDCLNT_SHAREMODE = 0
_AUDCLNT_SHAREMODE_EXCLUSIVE _AUDCLNT_SHAREMODE = 1
)
type _AUDCLNT_STREAMOPTIONS int32
const (
_AUDCLNT_STREAMOPTIONS_NONE _AUDCLNT_STREAMOPTIONS = 0x0
_AUDCLNT_STREAMOPTIONS_RAW _AUDCLNT_STREAMOPTIONS = 0x1
_AUDCLNT_STREAMOPTIONS_MATCH_FORMAT _AUDCLNT_STREAMOPTIONS = 0x2
_AUDCLNT_STREAMOPTIONS_AMBISONICS _AUDCLNT_STREAMOPTIONS = 0x4
)
type _AUDIO_STREAM_CATEGORY int32
const (
_AudioCategory_Other _AUDIO_STREAM_CATEGORY = 0
_AudioCategory_ForegroundOnlyMedia _AUDIO_STREAM_CATEGORY = 1
_AudioCategory_BackgroundCapableMedia _AUDIO_STREAM_CATEGORY = 2
_AudioCategory_Communications _AUDIO_STREAM_CATEGORY = 3
_AudioCategory_Alerts _AUDIO_STREAM_CATEGORY = 4
_AudioCategory_SoundEffects _AUDIO_STREAM_CATEGORY = 5
_AudioCategory_GameEffects _AUDIO_STREAM_CATEGORY = 6
_AudioCategory_GameMedia _AUDIO_STREAM_CATEGORY = 7
_AudioCategory_GameChat _AUDIO_STREAM_CATEGORY = 8
_AudioCategory_Speech _AUDIO_STREAM_CATEGORY = 9
_AudioCategory_Movie _AUDIO_STREAM_CATEGORY = 10
_AudioCategory_Media _AUDIO_STREAM_CATEGORY = 11
)
type _CLSCTX int32
const (
_CLSCTX_INPROC_SERVER _CLSCTX = 0x00000001
_CLSCTX_INPROC_HANDLER _CLSCTX = 0x00000002
_CLSCTX_LOCAL_SERVER _CLSCTX = 0x00000004
_CLSCTX_REMOTE_SERVER _CLSCTX = 0x00000010
_CLSCTX_ALL = _CLSCTX_INPROC_SERVER | _CLSCTX_INPROC_HANDLER | _CLSCTX_LOCAL_SERVER | _CLSCTX_REMOTE_SERVER
)
type _EDataFlow int32
const (
eRender _EDataFlow = 0
)
type _ERole int32
const (
eConsole _ERole = 0
)
type _WIN32_ERR uint32
const (
_E_NOTFOUND _WIN32_ERR = 0x80070490
)
func isWin32Err(hresult uint32) bool {
return hresult&0xffff0000 == (1<<31)|(windows.FACILITY_WIN32<<16)
}
func (e _WIN32_ERR) Error() string {
switch e {
case _E_NOTFOUND:
return "E_NOTFOUND"
default:
return fmt.Sprintf("HRESULT(%d)", e)
}
}
type _AudioClientProperties struct {
cbSize uint32
bIsOffload int32
eCategory _AUDIO_STREAM_CATEGORY
Options _AUDCLNT_STREAMOPTIONS
}
type _PROPVARIANT struct {
// TODO: Implmeent this
}
type _WAVEFORMATEXTENSIBLE struct {
wFormatTag uint16
nChannels uint16
nSamplesPerSec uint32
nAvgBytesPerSec uint32
nBlockAlign uint16
wBitsPerSample uint16
cbSize uint16
Samples uint16 // union
dwChannelMask uint32
SubFormat windows.GUID
}
func _CoCreateInstance(rclsid *windows.GUID, pUnkOuter unsafe.Pointer, dwClsContext uint32, riid *windows.GUID) (unsafe.Pointer, error) {
var v unsafe.Pointer
r, _, _ := procCoCreateInstance.Call(uintptr(unsafe.Pointer(rclsid)), uintptr(pUnkOuter), uintptr(dwClsContext), uintptr(unsafe.Pointer(riid)), uintptr(unsafe.Pointer(&v)))
runtime.KeepAlive(rclsid)
runtime.KeepAlive(riid)
if uint32(r) != uint32(windows.S_OK) {
return nil, fmt.Errorf("oto: CoCreateInstance failed: HRESULT(%d)", uint32(r))
}
return v, nil
}
type _IAudioClient2 struct {
vtbl *_IAudioClient2_Vtbl
}
type _IAudioClient2_Vtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
Initialize uintptr
GetBufferSize uintptr
GetStreamLatency uintptr
GetCurrentPadding uintptr
IsFormatSupported uintptr
GetMixFormat uintptr
GetDevicePeriod uintptr
Start uintptr
Stop uintptr
Reset uintptr
SetEventHandle uintptr
GetService uintptr
IsOffloadCapable uintptr
SetClientProperties uintptr
GetBufferSizeLimits uintptr
}
func (i *_IAudioClient2) GetBufferSize() (uint32, error) {
var numBufferFrames uint32
r, _, _ := syscall.Syscall(i.vtbl.GetBufferSize, 2, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(&numBufferFrames)), 0)
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return 0, fmt.Errorf("oto: IAudioClient2::GetBufferSize failed: %w", _AUDCLNT_ERR(r))
}
return 0, fmt.Errorf("oto: IAudioClient2::GetBufferSize failed: HRESULT(%d)", uint32(r))
}
return numBufferFrames, nil
}
func (i *_IAudioClient2) GetCurrentPadding() (uint32, error) {
var numPaddingFrames uint32
r, _, _ := syscall.Syscall(i.vtbl.GetCurrentPadding, 2, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(&numPaddingFrames)), 0)
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return 0, fmt.Errorf("oto: IAudioClient2::GetCurrentPadding failed: %w", _AUDCLNT_ERR(r))
}
return 0, fmt.Errorf("oto: IAudioClient2::GetCurrentPadding failed: HRESULT(%d)", uint32(r))
}
return numPaddingFrames, nil
}
func (i *_IAudioClient2) GetDevicePeriod() (_REFERENCE_TIME, _REFERENCE_TIME, error) {
var defaultDevicePeriod _REFERENCE_TIME
var minimumDevicePeriod _REFERENCE_TIME
r, _, _ := syscall.Syscall(i.vtbl.GetDevicePeriod, 3, uintptr(unsafe.Pointer(i)),
uintptr(unsafe.Pointer(&defaultDevicePeriod)), uintptr(unsafe.Pointer(&minimumDevicePeriod)))
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return 0, 0, fmt.Errorf("oto: IAudioClient2::GetDevicePeriod failed: %w", _AUDCLNT_ERR(r))
}
return 0, 0, fmt.Errorf("oto: IAudioClient2::GetDevicePeriod failed: HRESULT(%d)", uint32(r))
}
return defaultDevicePeriod, minimumDevicePeriod, nil
}
func (i *_IAudioClient2) GetService(riid *windows.GUID) (unsafe.Pointer, error) {
var v unsafe.Pointer
r, _, _ := syscall.Syscall(i.vtbl.GetService, 3, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(riid)), uintptr(unsafe.Pointer(&v)))
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return nil, fmt.Errorf("oto: IAudioClient2::GetService failed: %w", _AUDCLNT_ERR(r))
}
return nil, fmt.Errorf("oto: IAudioClient2::GetService failed: HRESULT(%d)", uint32(r))
}
return v, nil
}
func (i *_IAudioClient2) Initialize(shareMode _AUDCLNT_SHAREMODE, streamFlags uint32, hnsBufferDuration _REFERENCE_TIME, hnsPeriodicity _REFERENCE_TIME, pFormat *_WAVEFORMATEXTENSIBLE, audioSessionGuid *windows.GUID) error {
var r uintptr
if unsafe.Sizeof(uintptr(0)) == 8 {
// 64bits
r, _, _ = syscall.Syscall9(i.vtbl.Initialize, 7, uintptr(unsafe.Pointer(i)),
uintptr(shareMode), uintptr(streamFlags), uintptr(hnsBufferDuration),
uintptr(hnsPeriodicity), uintptr(unsafe.Pointer(pFormat)), uintptr(unsafe.Pointer(audioSessionGuid)),
0, 0)
} else {
// 32bits
r, _, _ = syscall.Syscall9(i.vtbl.Initialize, 9, uintptr(unsafe.Pointer(i)),
uintptr(shareMode), uintptr(streamFlags), uintptr(hnsBufferDuration),
uintptr(hnsBufferDuration>>32), uintptr(hnsPeriodicity), uintptr(hnsPeriodicity>>32),
uintptr(unsafe.Pointer(pFormat)), uintptr(unsafe.Pointer(audioSessionGuid)))
}
runtime.KeepAlive(pFormat)
runtime.KeepAlive(audioSessionGuid)
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return fmt.Errorf("oto: IAudioClient2::Initialize failed: %w", _AUDCLNT_ERR(r))
}
return fmt.Errorf("oto: IAudioClient2::Initialize failed: HRESULT(%d)", uint32(r))
}
return nil
}
func (i *_IAudioClient2) IsFormatSupported(shareMode _AUDCLNT_SHAREMODE, pFormat *_WAVEFORMATEXTENSIBLE) (*_WAVEFORMATEXTENSIBLE, error) {
var closestMatch *_WAVEFORMATEXTENSIBLE
r, _, _ := syscall.Syscall6(i.vtbl.IsFormatSupported, 4, uintptr(unsafe.Pointer(i)),
uintptr(shareMode), uintptr(unsafe.Pointer(pFormat)), uintptr(unsafe.Pointer(&closestMatch)),
0, 0)
if uint32(r) != uint32(windows.S_OK) {
if uint32(r) == uint32(windows.S_FALSE) {
var r _WAVEFORMATEXTENSIBLE
if closestMatch != nil {
r = *closestMatch
windows.CoTaskMemFree(unsafe.Pointer(closestMatch))
}
return &r, nil
}
if isAudclntErr(uint32(r)) {
return nil, fmt.Errorf("oto: IAudioClient2::IsFormatSupported failed: %w", _AUDCLNT_ERR(r))
}
return nil, fmt.Errorf("oto: IAudioClient2::IsFormatSupported failed: HRESULT(%d)", uint32(r))
}
return nil, nil
}
func (i *_IAudioClient2) Release() uint32 {
r, _, _ := syscall.Syscall(i.vtbl.Release, 1, uintptr(unsafe.Pointer(i)), 0, 0)
return uint32(r)
}
func (i *_IAudioClient2) SetClientProperties(pProperties *_AudioClientProperties) error {
r, _, _ := syscall.Syscall(i.vtbl.SetClientProperties, 2, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(pProperties)), 0)
runtime.KeepAlive(pProperties)
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return fmt.Errorf("oto: IAudioClient2::SetClientProperties failed: %w", _AUDCLNT_ERR(r))
}
return fmt.Errorf("oto: IAudioClient2::SetClientProperties failed: HRESULT(%d)", uint32(r))
}
return nil
}
func (i *_IAudioClient2) SetEventHandle(eventHandle windows.Handle) error {
r, _, _ := syscall.Syscall(i.vtbl.SetEventHandle, 2, uintptr(unsafe.Pointer(i)), uintptr(eventHandle), 0)
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return fmt.Errorf("oto: IAudioClient2::SetEventHandle failed: %w", _AUDCLNT_ERR(r))
}
return fmt.Errorf("oto: IAudioClient2::SetEventHandle failed: HRESULT(%d)", uint32(r))
}
return nil
}
func (i *_IAudioClient2) Start() error {
r, _, _ := syscall.Syscall(i.vtbl.Start, 1, uintptr(unsafe.Pointer(i)), 0, 0)
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return fmt.Errorf("oto: IAudioClient2::Start failed: %w", _AUDCLNT_ERR(r))
}
return fmt.Errorf("oto: IAudioClient2::Start failed: HRESULT(%d)", uint32(r))
}
return nil
}
func (i *_IAudioClient2) Stop() (bool, error) {
r, _, _ := syscall.Syscall(i.vtbl.Stop, 1, uintptr(unsafe.Pointer(i)), 0, 0)
if uint32(r) != uint32(windows.S_OK) && uint32(r) != uint32(windows.S_FALSE) {
if isAudclntErr(uint32(r)) {
return false, fmt.Errorf("oto: IAudioClient2::Stop failed: %w", _AUDCLNT_ERR(r))
}
return false, fmt.Errorf("oto: IAudioClient2::Stop failed: HRESULT(%d)", uint32(r))
}
return uint32(r) == uint32(windows.S_OK), nil
}
type _IAudioRenderClient struct {
vtbl *_IAudioRenderClient_Vtbl
}
type _IAudioRenderClient_Vtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
GetBuffer uintptr
ReleaseBuffer uintptr
}
func (i *_IAudioRenderClient) GetBuffer(numFramesRequested uint32) (*byte, error) {
var data *byte
r, _, _ := syscall.Syscall(i.vtbl.GetBuffer, 3, uintptr(unsafe.Pointer(i)), uintptr(numFramesRequested), uintptr(unsafe.Pointer(&data)))
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return nil, fmt.Errorf("oto: IAudioRenderClient::GetBuffer failed: %w", _AUDCLNT_ERR(r))
}
return nil, fmt.Errorf("oto: IAudioRenderClient::GetBuffer failed: HRESULT(%d)", uint32(r))
}
return data, nil
}
func (i *_IAudioRenderClient) Release() uint32 {
r, _, _ := syscall.Syscall(i.vtbl.Release, 1, uintptr(unsafe.Pointer(i)), 0, 0)
return uint32(r)
}
func (i *_IAudioRenderClient) ReleaseBuffer(numFramesWritten uint32, dwFlags uint32) error {
r, _, _ := syscall.Syscall(i.vtbl.ReleaseBuffer, 3, uintptr(unsafe.Pointer(i)), uintptr(numFramesWritten), uintptr(dwFlags))
if uint32(r) != uint32(windows.S_OK) {
if isAudclntErr(uint32(r)) {
return fmt.Errorf("oto: IAudioRenderClient::ReleaseBuffer failed: %w", _AUDCLNT_ERR(r))
}
return fmt.Errorf("oto: IAudioRenderClient::ReleaseBuffer failed: HRESULT(%d)", uint32(r))
}
return nil
}
type _IMMDevice struct {
vtbl *_IMMDevice_Vtbl
}
type _IMMDevice_Vtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
Activate uintptr
OpenPropertyStore uintptr
GetId uintptr
GetState uintptr
}
func (i *_IMMDevice) Activate(iid *windows.GUID, dwClsCtx uint32, pActivationParams *_PROPVARIANT) (unsafe.Pointer, error) {
var v unsafe.Pointer
r, _, _ := syscall.Syscall6(i.vtbl.Activate, 5, uintptr(unsafe.Pointer(i)),
uintptr(unsafe.Pointer(iid)), uintptr(dwClsCtx), uintptr(unsafe.Pointer(pActivationParams)), uintptr(unsafe.Pointer(&v)), 0)
runtime.KeepAlive(iid)
runtime.KeepAlive(pActivationParams)
if uint32(r) != uint32(windows.S_OK) {
return nil, fmt.Errorf("oto: IMMDevice::Activate failed: HRESULT(%d)", uint32(r))
}
return v, nil
}
func (i *_IMMDevice) GetId() (string, error) {
var strId *uint16
r, _, _ := syscall.Syscall(i.vtbl.GetId, 2, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(&strId)), 0)
if uint32(r) != uint32(windows.S_OK) {
return "", fmt.Errorf("oto: IMMDevice::GetId failed: HRESULT(%d)", uint32(r))
}
return windows.UTF16PtrToString(strId), nil
}
func (i *_IMMDevice) Release() {
syscall.Syscall(i.vtbl.Release, 1, uintptr(unsafe.Pointer(i)), 0, 0)
}
type _IMMDeviceEnumerator struct {
vtbl *_IMMDeviceEnumerator_Vtbl
}
type _IMMDeviceEnumerator_Vtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
EnumAudioEndpoints uintptr
GetDefaultAudioEndpoint uintptr
GetDevice uintptr
RegisterEndpointNotificationCallback uintptr
UnregisterEndpointNotificationCallback uintptr
}
func (i *_IMMDeviceEnumerator) GetDefaultAudioEndPoint(dataFlow _EDataFlow, role _ERole) (*_IMMDevice, error) {
var endPoint *_IMMDevice
r, _, _ := syscall.Syscall6(i.vtbl.GetDefaultAudioEndpoint, 4, uintptr(unsafe.Pointer(i)),
uintptr(dataFlow), uintptr(role), uintptr(unsafe.Pointer(&endPoint)), 0, 0)
if uint32(r) != uint32(windows.S_OK) {
if isWin32Err(uint32(r)) {
return nil, fmt.Errorf("oto: IMMDeviceEnumerator::GetDefaultAudioEndPoint failed: %w", _E_NOTFOUND)
}
return nil, fmt.Errorf("oto: IMMDeviceEnumerator::GetDefaultAudioEndPoint failed: HRESULT(%d)", uint32(r))
}
return endPoint, nil
}
func (i *_IMMDeviceEnumerator) Release() {
syscall.Syscall(i.vtbl.Release, 1, uintptr(unsafe.Pointer(i)), 0, 0)
}

View file

@ -0,0 +1,174 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"fmt"
"runtime"
"unsafe"
"golang.org/x/sys/windows"
)
var (
winmm = windows.NewLazySystemDLL("winmm")
)
var (
procWaveOutOpen = winmm.NewProc("waveOutOpen")
procWaveOutClose = winmm.NewProc("waveOutClose")
procWaveOutPrepareHeader = winmm.NewProc("waveOutPrepareHeader")
procWaveOutUnprepareHeader = winmm.NewProc("waveOutUnprepareHeader")
procWaveOutWrite = winmm.NewProc("waveOutWrite")
)
type _WAVEHDR struct {
lpData uintptr
dwBufferLength uint32
dwBytesRecorded uint32
dwUser uintptr
dwFlags uint32
dwLoops uint32
lpNext uintptr
reserved uintptr
}
type _WAVEFORMATEX struct {
wFormatTag uint16
nChannels uint16
nSamplesPerSec uint32
nAvgBytesPerSec uint32
nBlockAlign uint16
wBitsPerSample uint16
cbSize uint16
}
const (
_WAVE_FORMAT_IEEE_FLOAT = 3
_WHDR_INQUEUE = 16
)
type _MMRESULT uint
const (
_MMSYSERR_NOERROR _MMRESULT = 0
_MMSYSERR_ERROR _MMRESULT = 1
_MMSYSERR_BADDEVICEID _MMRESULT = 2
_MMSYSERR_ALLOCATED _MMRESULT = 4
_MMSYSERR_INVALIDHANDLE _MMRESULT = 5
_MMSYSERR_NODRIVER _MMRESULT = 6
_MMSYSERR_NOMEM _MMRESULT = 7
_WAVERR_BADFORMAT _MMRESULT = 32
_WAVERR_STILLPLAYING _MMRESULT = 33
_WAVERR_UNPREPARED _MMRESULT = 34
_WAVERR_SYNC _MMRESULT = 35
)
func (m _MMRESULT) Error() string {
switch m {
case _MMSYSERR_NOERROR:
return "MMSYSERR_NOERROR"
case _MMSYSERR_ERROR:
return "MMSYSERR_ERROR"
case _MMSYSERR_BADDEVICEID:
return "MMSYSERR_BADDEVICEID"
case _MMSYSERR_ALLOCATED:
return "MMSYSERR_ALLOCATED"
case _MMSYSERR_INVALIDHANDLE:
return "MMSYSERR_INVALIDHANDLE"
case _MMSYSERR_NODRIVER:
return "MMSYSERR_NODRIVER"
case _MMSYSERR_NOMEM:
return "MMSYSERR_NOMEM"
case _WAVERR_BADFORMAT:
return "WAVERR_BADFORMAT"
case _WAVERR_STILLPLAYING:
return "WAVERR_STILLPLAYING"
case _WAVERR_UNPREPARED:
return "WAVERR_UNPREPARED"
case _WAVERR_SYNC:
return "WAVERR_SYNC"
}
return fmt.Sprintf("MMRESULT (%d)", m)
}
func waveOutOpen(f *_WAVEFORMATEX, callback uintptr) (uintptr, error) {
const (
waveMapper = 0xffffffff
callbackFunction = 0x30000
)
var w uintptr
var fdwOpen uintptr
if callback != 0 {
fdwOpen |= callbackFunction
}
r, _, e := procWaveOutOpen.Call(uintptr(unsafe.Pointer(&w)), waveMapper, uintptr(unsafe.Pointer(f)),
callback, 0, fdwOpen)
runtime.KeepAlive(f)
if _MMRESULT(r) != _MMSYSERR_NOERROR {
if e != nil && e != windows.ERROR_SUCCESS {
return 0, fmt.Errorf("oto: waveOutOpen failed: %w", e)
}
return 0, fmt.Errorf("oto: waveOutOpen failed: %w", _MMRESULT(r))
}
return w, nil
}
func waveOutClose(hwo uintptr) error {
r, _, e := procWaveOutClose.Call(hwo)
if _MMRESULT(r) != _MMSYSERR_NOERROR {
if e != nil && e != windows.ERROR_SUCCESS {
return fmt.Errorf("oto: waveOutClose failed: %w", e)
}
return fmt.Errorf("oto: waveOutClose failed: %w", _MMRESULT(r))
}
return nil
}
func waveOutPrepareHeader(hwo uintptr, pwh *_WAVEHDR) error {
r, _, e := procWaveOutPrepareHeader.Call(hwo, uintptr(unsafe.Pointer(pwh)), unsafe.Sizeof(_WAVEHDR{}))
runtime.KeepAlive(pwh)
if _MMRESULT(r) != _MMSYSERR_NOERROR {
if e != nil && e != windows.ERROR_SUCCESS {
return fmt.Errorf("oto: waveOutPrepareHeader failed: %w", e)
}
return fmt.Errorf("oto: waveOutPrepareHeader failed: %w", _MMRESULT(r))
}
return nil
}
func waveOutUnprepareHeader(hwo uintptr, pwh *_WAVEHDR) error {
r, _, e := procWaveOutUnprepareHeader.Call(hwo, uintptr(unsafe.Pointer(pwh)), unsafe.Sizeof(_WAVEHDR{}))
runtime.KeepAlive(pwh)
if _MMRESULT(r) != _MMSYSERR_NOERROR {
if e != nil && e != windows.ERROR_SUCCESS {
return fmt.Errorf("oto: waveOutUnprepareHeader failed: %w", e)
}
return fmt.Errorf("oto: waveOutUnprepareHeader failed: %w", _MMRESULT(r))
}
return nil
}
func waveOutWrite(hwo uintptr, pwh *_WAVEHDR) error {
r, _, e := procWaveOutWrite.Call(hwo, uintptr(unsafe.Pointer(pwh)), unsafe.Sizeof(_WAVEHDR{}))
runtime.KeepAlive(pwh)
if _MMRESULT(r) != _MMSYSERR_NOERROR {
if e != nil && e != windows.ERROR_SUCCESS {
return fmt.Errorf("oto: waveOutWrite failed: %w", e)
}
return fmt.Errorf("oto: waveOutWrite failed: %w", _MMRESULT(r))
}
return nil
}

181
vendor/github.com/ebitengine/oto/v3/context.go generated vendored Normal file
View file

@ -0,0 +1,181 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"fmt"
"io"
"sync"
"time"
"github.com/ebitengine/oto/v3/internal/mux"
)
var (
contextCreated bool
contextCreationMutex sync.Mutex
)
// Context is the main object in Oto. It interacts with the audio drivers.
//
// To play sound with Oto, first create a context. Then use the context to create
// an arbitrary number of players. Then use the players to play sound.
//
// Creating multiple contexts is NOT supported.
type Context struct {
context *context
}
// Format is the format of sources.
type Format int
const (
// FormatFloat32LE is the format of 32 bits floats little endian.
FormatFloat32LE Format = iota
// FormatUnsignedInt8 is the format of 8 bits integers.
FormatUnsignedInt8
//FormatSignedInt16LE is the format of 16 bits integers little endian.
FormatSignedInt16LE
)
// NewContextOptions represents options for NewContext.
type NewContextOptions struct {
// SampleRate specifies the number of samples that should be played during one second.
// Usual numbers are 44100 or 48000. One context has only one sample rate. You cannot play multiple audio
// sources with different sample rates at the same time.
SampleRate int
// ChannelCount specifies the number of channels. One channel is mono playback. Two
// channels are stereo playback. No other values are supported.
ChannelCount int
// Format specifies the format of sources.
Format Format
// BufferSize specifies a buffer size in the underlying device.
//
// If 0 is specified, the driver's default buffer size is used.
// Set BufferSize to adjust the buffer size if you want to adjust latency or reduce noises.
// Too big buffer size can increase the latency time.
// On the other hand, too small buffer size can cause glitch noises due to buffer shortage.
BufferSize time.Duration
}
// NewContext creates a new context with given options.
// A context creates and holds ready-to-use Player objects.
// NewContext returns a context, a channel that is closed when the context is ready, and an error if it exists.
//
// Creating multiple contexts is NOT supported.
func NewContext(options *NewContextOptions) (*Context, chan struct{}, error) {
contextCreationMutex.Lock()
defer contextCreationMutex.Unlock()
if contextCreated {
return nil, nil, fmt.Errorf("oto: context is already created")
}
contextCreated = true
var bufferSizeInBytes int
if options.BufferSize != 0 {
// The underying driver always uses 32bit floats.
bytesPerSample := options.ChannelCount * 4
bytesPerSecond := options.SampleRate * bytesPerSample
bufferSizeInBytes = int(int64(options.BufferSize) * int64(bytesPerSecond) / int64(time.Second))
bufferSizeInBytes = bufferSizeInBytes / bytesPerSample * bytesPerSample
}
ctx, ready, err := newContext(options.SampleRate, options.ChannelCount, mux.Format(options.Format), bufferSizeInBytes)
if err != nil {
return nil, nil, err
}
return &Context{context: ctx}, ready, nil
}
// NewPlayer creates a new, ready-to-use Player belonging to the Context.
// It is safe to create multiple players.
//
// The format of r is as follows:
//
// [data] = [sample 1] [sample 2] [sample 3] ...
// [sample *] = [channel 1] [channel 2] ...
// [channel *] = [byte 1] [byte 2] ...
//
// Byte ordering is little endian.
//
// A player has some amount of an underlying buffer.
// Read data from r is queued to the player's underlying buffer.
// The underlying buffer is consumed by its playing.
// Then, r's position and the current playing position don't necessarily match.
// If you want to clear the underlying buffer for some reasons e.g., you want to seek the position of r,
// call the player's Reset function.
//
// You cannot share r by multiple players.
//
// The returned player implements Player, BufferSizeSetter, and io.Seeker.
// You can modify the buffer size of a player by the SetBufferSize function.
// A small buffer size is useful if you want to play a real-time PCM for example.
// Note that the audio quality might be affected if you modify the buffer size.
//
// If r does not implement io.Seeker, the returned player's Seek returns an error.
//
// NewPlayer is concurrent-safe.
//
// All the functions of a Player returned by NewPlayer are concurrent-safe.
func (c *Context) NewPlayer(r io.Reader) *Player {
return &Player{
player: c.context.mux.NewPlayer(r),
}
}
// Suspend suspends the entire audio play.
//
// Suspend is concurrent-safe.
func (c *Context) Suspend() error {
return c.context.Suspend()
}
// Resume resumes the entire audio play, which was suspended by Suspend.
//
// Resume is concurrent-safe.
func (c *Context) Resume() error {
return c.context.Resume()
}
// Err returns the current error.
//
// Err is concurrent-safe.
func (c *Context) Err() error {
return c.context.Err()
}
type atomicError struct {
err error
m sync.Mutex
}
func (a *atomicError) TryStore(err error) {
a.m.Lock()
defer a.m.Unlock()
if a.err == nil {
a.err = err
}
}
func (a *atomicError) Load() error {
a.m.Lock()
defer a.m.Unlock()
return a.err
}

49
vendor/github.com/ebitengine/oto/v3/driver_android.go generated vendored Normal file
View file

@ -0,0 +1,49 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"github.com/ebitengine/oto/v3/internal/mux"
"github.com/ebitengine/oto/v3/internal/oboe"
)
type context struct {
mux *mux.Mux
}
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int) (*context, chan struct{}, error) {
ready := make(chan struct{})
close(ready)
c := &context{
mux: mux.New(sampleRate, channelCount, format),
}
if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, bufferSizeInBytes); err != nil {
return nil, nil, err
}
return c, ready, nil
}
func (c *context) Suspend() error {
return oboe.Suspend()
}
func (c *context) Resume() error {
return oboe.Resume()
}
func (c *context) Err() error {
return nil
}

263
vendor/github.com/ebitengine/oto/v3/driver_darwin.go generated vendored Normal file
View file

@ -0,0 +1,263 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"fmt"
"sync"
"time"
"unsafe"
"github.com/ebitengine/purego/objc"
"github.com/ebitengine/oto/v3/internal/mux"
)
const (
float32SizeInBytes = 4
bufferCount = 4
noErr = 0
)
func newAudioQueue(sampleRate, channelCount int, oneBufferSizeInBytes int) (_AudioQueueRef, []_AudioQueueBufferRef, error) {
desc := _AudioStreamBasicDescription{
mSampleRate: float64(sampleRate),
mFormatID: uint32(kAudioFormatLinearPCM),
mFormatFlags: uint32(kAudioFormatFlagIsFloat),
mBytesPerPacket: uint32(channelCount * float32SizeInBytes),
mFramesPerPacket: 1,
mBytesPerFrame: uint32(channelCount * float32SizeInBytes),
mChannelsPerFrame: uint32(channelCount),
mBitsPerChannel: uint32(8 * float32SizeInBytes),
}
var audioQueue _AudioQueueRef
if osstatus := _AudioQueueNewOutput(
&desc,
render,
nil,
0, //CFRunLoopRef
0, //CFStringRef
0,
&audioQueue); osstatus != noErr {
return 0, nil, fmt.Errorf("oto: AudioQueueNewFormat with StreamFormat failed: %d", osstatus)
}
bufs := make([]_AudioQueueBufferRef, 0, bufferCount)
for len(bufs) < cap(bufs) {
var buf _AudioQueueBufferRef
if osstatus := _AudioQueueAllocateBuffer(audioQueue, uint32(oneBufferSizeInBytes), &buf); osstatus != noErr {
return 0, nil, fmt.Errorf("oto: AudioQueueAllocateBuffer failed: %d", osstatus)
}
buf.mAudioDataByteSize = uint32(oneBufferSizeInBytes)
bufs = append(bufs, buf)
}
return audioQueue, bufs, nil
}
type context struct {
audioQueue _AudioQueueRef
unqueuedBuffers []_AudioQueueBufferRef
oneBufferSizeInBytes int
cond *sync.Cond
mux *mux.Mux
err atomicError
}
// TODO: Convert the error code correctly.
// See https://stackoverflow.com/questions/2196869/how-do-you-convert-an-iphone-osstatus-code-to-something-useful
var theContext *context
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int) (*context, chan struct{}, error) {
var oneBufferSizeInBytes int
if bufferSizeInBytes != 0 {
oneBufferSizeInBytes = bufferSizeInBytes / bufferCount
} else {
oneBufferSizeInBytes = defaultOneBufferSizeInBytes
}
bytesPerSample := channelCount * 4
oneBufferSizeInBytes = oneBufferSizeInBytes / bytesPerSample * bytesPerSample
ready := make(chan struct{})
c := &context{
cond: sync.NewCond(&sync.Mutex{}),
mux: mux.New(sampleRate, channelCount, format),
oneBufferSizeInBytes: oneBufferSizeInBytes,
}
theContext = c
if err := initializeAPI(); err != nil {
return nil, nil, err
}
go func() {
defer close(ready)
q, bs, err := newAudioQueue(sampleRate, channelCount, oneBufferSizeInBytes)
if err != nil {
c.err.TryStore(err)
return
}
c.audioQueue = q
c.unqueuedBuffers = bs
if err := setNotificationHandler(); err != nil {
c.err.TryStore(err)
return
}
var retryCount int
try:
if osstatus := _AudioQueueStart(c.audioQueue, nil); osstatus != noErr {
if osstatus == avAudioSessionErrorCodeCannotStartPlaying && retryCount < 100 {
// TODO: use sleepTime() after investigating when this error happens.
time.Sleep(10 * time.Millisecond)
retryCount++
goto try
}
c.err.TryStore(fmt.Errorf("oto: AudioQueueStart failed at newContext: %d", osstatus))
return
}
go c.loop()
}()
return c, ready, nil
}
func (c *context) wait() bool {
c.cond.L.Lock()
defer c.cond.L.Unlock()
for len(c.unqueuedBuffers) == 0 && c.err.Load() == nil {
c.cond.Wait()
}
return c.err.Load() == nil
}
func (c *context) loop() {
buf32 := make([]float32, c.oneBufferSizeInBytes/4)
for {
if !c.wait() {
return
}
c.appendBuffer(buf32)
}
}
func (c *context) appendBuffer(buf32 []float32) {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if c.err.Load() != nil {
return
}
buf := c.unqueuedBuffers[0]
copy(c.unqueuedBuffers, c.unqueuedBuffers[1:])
c.unqueuedBuffers = c.unqueuedBuffers[:len(c.unqueuedBuffers)-1]
c.mux.ReadFloat32s(buf32)
copy(unsafe.Slice((*float32)(unsafe.Pointer(buf.mAudioData)), buf.mAudioDataByteSize/float32SizeInBytes), buf32)
if osstatus := _AudioQueueEnqueueBuffer(c.audioQueue, buf, 0, nil); osstatus != noErr {
c.err.TryStore(fmt.Errorf("oto: AudioQueueEnqueueBuffer failed: %d", osstatus))
}
}
func (c *context) Suspend() error {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.err.Load(); err != nil {
return err.(error)
}
if osstatus := _AudioQueuePause(c.audioQueue); osstatus != noErr {
return fmt.Errorf("oto: AudioQueuePause failed: %d", osstatus)
}
return nil
}
func (c *context) Resume() error {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.err.Load(); err != nil {
return err.(error)
}
var retryCount int
try:
if osstatus := _AudioQueueStart(c.audioQueue, nil); osstatus != noErr {
if (osstatus == avAudioSessionErrorCodeCannotStartPlaying ||
osstatus == avAudioSessionErrorCodeCannotInterruptOthers) &&
retryCount < 30 {
// It is uncertain that this error is temporary or not. Then let's use exponential-time sleeping.
time.Sleep(sleepTime(retryCount))
retryCount++
goto try
}
if osstatus == avAudioSessionErrorCodeSiriIsRecording {
// As this error should be temporary, it should be OK to use a short time for sleep anytime.
time.Sleep(10 * time.Millisecond)
goto try
}
return fmt.Errorf("oto: AudioQueueStart failed at Resume: %d", osstatus)
}
return nil
}
func (c *context) Err() error {
if err := c.err.Load(); err != nil {
return err.(error)
}
return nil
}
func render(inUserData unsafe.Pointer, inAQ _AudioQueueRef, inBuffer _AudioQueueBufferRef) {
theContext.cond.L.Lock()
defer theContext.cond.L.Unlock()
theContext.unqueuedBuffers = append(theContext.unqueuedBuffers, inBuffer)
theContext.cond.Signal()
}
func setGlobalPause(self objc.ID, _cmd objc.SEL, notification objc.ID) {
theContext.Suspend()
}
func setGlobalResume(self objc.ID, _cmd objc.SEL, notification objc.ID) {
theContext.Resume()
}
func sleepTime(count int) time.Duration {
switch count {
case 0:
return 10 * time.Millisecond
case 1:
return 20 * time.Millisecond
case 2:
return 50 * time.Millisecond
default:
return 100 * time.Millisecond
}
}

30
vendor/github.com/ebitengine/oto/v3/driver_ios.go generated vendored Normal file
View file

@ -0,0 +1,30 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build darwin && ios
package oto
// 12288 seems necessary at least on iPod touch (7th).
// With 48000[Hz] stereo, the maximum delay is (12288*4[buffers] / 4 / 2)[samples] / 48000 [Hz] = 100[ms].
// '4' is float32 size in bytes. '2' is a number of channels for stereo.
const defaultOneBufferSizeInBytes = 12288
func setNotificationHandler() error {
// AVAudioSessionInterruptionNotification is not reliable on iOS. Rely on
// applicationWillResignActive and applicationDidBecomeActive instead. See
// https://stackoverflow.com/questions/24404463/ios-siri-not-available-does-not-return-avaudiosessioninterruptionoptionshouldre
return nil
}

141
vendor/github.com/ebitengine/oto/v3/driver_js.go generated vendored Normal file
View file

@ -0,0 +1,141 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"errors"
"runtime"
"syscall/js"
"unsafe"
"github.com/ebitengine/oto/v3/internal/mux"
)
type context struct {
audioContext js.Value
scriptProcessor js.Value
scriptProcessorCallback js.Func
ready bool
callbacks map[string]js.Func
mux *mux.Mux
}
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int) (*context, chan struct{}, error) {
ready := make(chan struct{})
class := js.Global().Get("AudioContext")
if !class.Truthy() {
class = js.Global().Get("webkitAudioContext")
}
if !class.Truthy() {
return nil, nil, errors.New("oto: AudioContext or webkitAudioContext was not found")
}
options := js.Global().Get("Object").New()
options.Set("sampleRate", sampleRate)
d := &context{
audioContext: class.New(options),
mux: mux.New(sampleRate, channelCount, format),
}
if bufferSizeInBytes == 0 {
// 4096 was not great at least on Safari 15.
bufferSizeInBytes = 8192 * channelCount
}
buf32 := make([]float32, bufferSizeInBytes/4)
chBuf32 := make([][]float32, channelCount)
for i := range chBuf32 {
chBuf32[i] = make([]float32, len(buf32)/channelCount)
}
// TODO: Use AudioWorklet if available.
sp := d.audioContext.Call("createScriptProcessor", bufferSizeInBytes/4/channelCount, 0, channelCount)
f := js.FuncOf(func(this js.Value, arguments []js.Value) any {
d.mux.ReadFloat32s(buf32)
for i := 0; i < channelCount; i++ {
for j := range chBuf32[i] {
chBuf32[i][j] = buf32[j*channelCount+i]
}
}
buf := arguments[0].Get("outputBuffer")
if buf.Get("copyToChannel").Truthy() {
for i := 0; i < channelCount; i++ {
buf.Call("copyToChannel", float32SliceToTypedArray(chBuf32[i]), i, 0)
}
} else {
// copyToChannel is not defined on Safari 11.
for i := 0; i < channelCount; i++ {
buf.Call("getChannelData", i).Call("set", float32SliceToTypedArray(chBuf32[i]))
}
}
return nil
})
sp.Call("addEventListener", "audioprocess", f)
d.scriptProcessor = sp
d.scriptProcessorCallback = f
sp.Call("connect", d.audioContext.Get("destination"))
setCallback := func(event string) js.Func {
var f js.Func
f = js.FuncOf(func(this js.Value, arguments []js.Value) any {
if !d.ready {
d.audioContext.Call("resume")
d.ready = true
close(ready)
}
js.Global().Get("document").Call("removeEventListener", event, f)
return nil
})
js.Global().Get("document").Call("addEventListener", event, f)
d.callbacks[event] = f
return f
}
// Browsers require user interaction to start the audio.
// https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio
d.callbacks = map[string]js.Func{}
setCallback("touchend")
setCallback("keyup")
setCallback("mouseup")
return d, ready, nil
}
func (c *context) Suspend() error {
c.audioContext.Call("suspend")
return nil
}
func (c *context) Resume() error {
c.audioContext.Call("resume")
return nil
}
func (c *context) Err() error {
return nil
}
func float32SliceToTypedArray(s []float32) js.Value {
bs := unsafe.Slice((*byte)(unsafe.Pointer(&s[0])), len(s)*4)
a := js.Global().Get("Uint8Array").New(len(bs))
js.CopyBytesToJS(a, bs)
runtime.KeepAlive(s)
buf := a.Get("buffer")
return js.Global().Get("Float32Array").New(buf, a.Get("byteOffset"), a.Get("byteLength").Int()/4)
}

78
vendor/github.com/ebitengine/oto/v3/driver_macos.go generated vendored Normal file
View file

@ -0,0 +1,78 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build darwin && !ios
package oto
import (
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
)
const defaultOneBufferSizeInBytes = 2048
// setNotificationHandler sets a handler for sleep/wake notifications.
func setNotificationHandler() error {
appkit, err := purego.Dlopen("/System/Library/Frameworks/AppKit.framework/Versions/Current/AppKit", purego.RTLD_GLOBAL)
if err != nil {
return err
}
// Create the Observer object
var class objc.Class
class, err = objc.RegisterClass("OtoNotificationObserver", objc.GetClass("NSObject"), nil, nil,
[]objc.MethodDef{
{
Cmd: objc.RegisterName("receiveSleepNote:"),
Fn: setGlobalPause,
},
{
Cmd: objc.RegisterName("receiveWakeNote:"),
Fn: setGlobalResume,
},
})
observer := objc.ID(class).Send(objc.RegisterName("new"))
notificationCenter := objc.ID(objc.GetClass("NSWorkspace")).Send(objc.RegisterName("sharedWorkspace")).Send(objc.RegisterName("notificationCenter"))
// Dlsym returns a pointer to the object so dereference it
s, err := purego.Dlsym(appkit, "NSWorkspaceWillSleepNotification")
if err != nil {
return err
}
notificationCenter.Send(objc.RegisterName("addObserver:selector:name:object:"),
observer,
objc.RegisterName("receiveSleepNote:"),
*(*uintptr)(unsafe.Pointer(s)),
0,
)
s, err = purego.Dlsym(appkit, "NSWorkspaceDidWakeNotification")
if err != nil {
return err
}
notificationCenter.Send(objc.RegisterName("addObserver:selector:name:object:"),
observer,
objc.RegisterName("receiveWakeNote:"),
*(*uintptr)(unsafe.Pointer(s)),
0,
)
return nil
}

View file

@ -0,0 +1,25 @@
// Copyright 2022 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build nintendosdk
// The actual implementaiton will be provided by -overlay.
#include <cstddef>
typedef void (*oto_OnReadCallbackType)(float *buf, size_t length);
extern "C" void oto_OpenAudio(int sample_rate, int channel_num,
oto_OnReadCallbackType on_read_callback,
int buffer_size_in_bytes) {}

View file

@ -0,0 +1,74 @@
// Copyright 2022 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build nintendosdk
package oto
// #cgo !darwin LDFLAGS: -Wl,-unresolved-symbols=ignore-all
// #cgo darwin LDFLAGS: -Wl,-undefined,dynamic_lookup
//
// typedef void (*oto_OnReadCallbackType)(float* buf, size_t length);
//
// void oto_OpenAudio(int sample_rate, int channel_num, oto_OnReadCallbackType on_read_callback, int buffer_size_in_bytes);
//
// void oto_OnReadCallback(float* buf, size_t length);
// static void oto_OpenProxy(int sample_rate, int channel_num, int buffer_size_in_bytes) {
// oto_OpenAudio(sample_rate, channel_num, oto_OnReadCallback, buffer_size_in_bytes);
// }
import "C"
import (
"unsafe"
"github.com/ebitengine/oto/v3/internal/mux"
)
//export oto_OnReadCallback
func oto_OnReadCallback(buf *C.float, length C.size_t) {
theContext.mux.ReadFloat32s(unsafe.Slice((*float32)(unsafe.Pointer(buf)), length))
}
type context struct {
mux *mux.Mux
}
var theContext *context
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int) (*context, chan struct{}, error) {
ready := make(chan struct{})
close(ready)
c := &context{
mux: mux.New(sampleRate, channelCount, format),
}
theContext = c
C.oto_OpenProxy(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes))
return c, ready, nil
}
func (c *context) Suspend() error {
// Do nothing so far.
return nil
}
func (c *context) Resume() error {
// Do nothing so far.
return nil
}
func (c *context) Err() error {
return nil
}

278
vendor/github.com/ebitengine/oto/v3/driver_unix.go generated vendored Normal file
View file

@ -0,0 +1,278 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !android && !darwin && !js && !windows && !nintendosdk
package oto
// #cgo pkg-config: alsa
//
// #include <alsa/asoundlib.h>
import "C"
import (
"fmt"
"strings"
"sync"
"unsafe"
"github.com/ebitengine/oto/v3/internal/mux"
)
type context struct {
channelCount int
suspended bool
handle *C.snd_pcm_t
cond *sync.Cond
mux *mux.Mux
err atomicError
ready chan struct{}
}
var theContext *context
func alsaError(name string, err C.int) error {
return fmt.Errorf("oto: ALSA error at %s: %s", name, C.GoString(C.snd_strerror(err)))
}
func deviceCandidates() []string {
const getAllDevices = -1
cPCMInterfaceName := C.CString("pcm")
defer C.free(unsafe.Pointer(cPCMInterfaceName))
var hints *unsafe.Pointer
err := C.snd_device_name_hint(getAllDevices, cPCMInterfaceName, &hints)
if err != 0 {
return []string{"default", "plug:default"}
}
defer C.snd_device_name_free_hint(hints)
var devices []string
cIoHintName := C.CString("IOID")
defer C.free(unsafe.Pointer(cIoHintName))
cNameHintName := C.CString("NAME")
defer C.free(unsafe.Pointer(cNameHintName))
for it := hints; *it != nil; it = (*unsafe.Pointer)(unsafe.Pointer(uintptr(unsafe.Pointer(it)) + unsafe.Sizeof(uintptr(0)))) {
io := C.snd_device_name_get_hint(*it, cIoHintName)
defer func() {
if io != nil {
C.free(unsafe.Pointer(io))
}
}()
if C.GoString(io) == "Input" {
continue
}
name := C.snd_device_name_get_hint(*it, cNameHintName)
defer func() {
if name != nil {
C.free(unsafe.Pointer(name))
}
}()
if name == nil {
continue
}
goName := C.GoString(name)
if goName == "null" {
continue
}
if goName == "default" {
continue
}
devices = append(devices, goName)
}
devices = append([]string{"default", "plug:default"}, devices...)
return devices
}
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int) (*context, chan struct{}, error) {
c := &context{
channelCount: channelCount,
cond: sync.NewCond(&sync.Mutex{}),
mux: mux.New(sampleRate, channelCount, format),
ready: make(chan struct{}),
}
theContext = c
go func() {
defer close(c.ready)
// Open a default ALSA audio device for blocking stream playback
type openError struct {
device string
err C.int
}
var openErrs []openError
var found bool
for _, name := range deviceCandidates() {
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
if err := C.snd_pcm_open(&c.handle, cname, C.SND_PCM_STREAM_PLAYBACK, 0); err < 0 {
openErrs = append(openErrs, openError{
device: name,
err: err,
})
continue
}
found = true
break
}
if !found {
var msgs []string
for _, e := range openErrs {
msgs = append(msgs, fmt.Sprintf("%q: %s", e.device, C.GoString(C.snd_strerror(e.err))))
}
c.err.TryStore(fmt.Errorf("oto: ALSA error at snd_pcm_open: %s", strings.Join(msgs, ", ")))
return
}
// TODO: Should snd_pcm_hw_params_set_periods be called explicitly?
const periods = 2
var periodSize C.snd_pcm_uframes_t
if bufferSizeInBytes != 0 {
periodSize = C.snd_pcm_uframes_t(bufferSizeInBytes / (channelCount * 4 * periods))
} else {
periodSize = C.snd_pcm_uframes_t(1024)
}
bufferSize := periodSize * periods
if err := c.alsaPcmHwParams(sampleRate, channelCount, &bufferSize, &periodSize); err != nil {
c.err.TryStore(err)
return
}
go func() {
buf32 := make([]float32, int(periodSize)*channelCount)
for {
if !c.readAndWrite(buf32) {
return
}
}
}()
}()
return c, c.ready, nil
}
func (c *context) alsaPcmHwParams(sampleRate, channelCount int, bufferSize, periodSize *C.snd_pcm_uframes_t) error {
var params *C.snd_pcm_hw_params_t
C.snd_pcm_hw_params_malloc(&params)
defer C.free(unsafe.Pointer(params))
if err := C.snd_pcm_hw_params_any(c.handle, params); err < 0 {
return alsaError("snd_pcm_hw_params_any", err)
}
if err := C.snd_pcm_hw_params_set_access(c.handle, params, C.SND_PCM_ACCESS_RW_INTERLEAVED); err < 0 {
return alsaError("snd_pcm_hw_params_set_access", err)
}
if err := C.snd_pcm_hw_params_set_format(c.handle, params, C.SND_PCM_FORMAT_FLOAT_LE); err < 0 {
return alsaError("snd_pcm_hw_params_set_format", err)
}
if err := C.snd_pcm_hw_params_set_channels(c.handle, params, C.unsigned(channelCount)); err < 0 {
return alsaError("snd_pcm_hw_params_set_channels", err)
}
if err := C.snd_pcm_hw_params_set_rate_resample(c.handle, params, 1); err < 0 {
return alsaError("snd_pcm_hw_params_set_rate_resample", err)
}
sr := C.unsigned(sampleRate)
if err := C.snd_pcm_hw_params_set_rate_near(c.handle, params, &sr, nil); err < 0 {
return alsaError("snd_pcm_hw_params_set_rate_near", err)
}
if err := C.snd_pcm_hw_params_set_buffer_size_near(c.handle, params, bufferSize); err < 0 {
return alsaError("snd_pcm_hw_params_set_buffer_size_near", err)
}
if err := C.snd_pcm_hw_params_set_period_size_near(c.handle, params, periodSize, nil); err < 0 {
return alsaError("snd_pcm_hw_params_set_period_size_near", err)
}
if err := C.snd_pcm_hw_params(c.handle, params); err < 0 {
return alsaError("snd_pcm_hw_params", err)
}
return nil
}
func (c *context) readAndWrite(buf32 []float32) bool {
c.cond.L.Lock()
defer c.cond.L.Unlock()
for c.suspended && c.err.Load() == nil {
c.cond.Wait()
}
if c.err.Load() != nil {
return false
}
c.mux.ReadFloat32s(buf32)
for len(buf32) > 0 {
n := C.snd_pcm_writei(c.handle, unsafe.Pointer(&buf32[0]), C.snd_pcm_uframes_t(len(buf32)/c.channelCount))
if n < 0 {
n = C.long(C.snd_pcm_recover(c.handle, C.int(n), 1))
}
if n < 0 {
c.err.TryStore(alsaError("snd_pcm_writei or snd_pcm_recover", C.int(n)))
return false
}
buf32 = buf32[int(n)*c.channelCount:]
}
return true
}
func (c *context) Suspend() error {
<-c.ready
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.err.Load(); err != nil {
return err.(error)
}
c.suspended = true
// Do not use snd_pcm_pause as not all devices support this.
// Do not use snd_pcm_drop as this might hang (https://github.com/libsdl-org/SDL/blob/a5c610b0a3857d3138f3f3da1f6dc3172c5ea4a8/src/audio/alsa/SDL_alsa_audio.c#L478).
return nil
}
func (c *context) Resume() error {
<-c.ready
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.err.Load(); err != nil {
return err.(error)
}
c.suspended = false
c.cond.Signal()
return nil
}
func (c *context) Err() error {
if err := c.err.Load(); err != nil {
return err.(error)
}
return nil
}

View file

@ -0,0 +1,470 @@
// Copyright 2022 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"errors"
"fmt"
"runtime"
"sync"
"syscall"
"time"
"unsafe"
"golang.org/x/sys/windows"
"github.com/ebitengine/oto/v3/internal/mux"
)
type comThread struct {
funcCh chan func()
}
func newCOMThread() (*comThread, error) {
funcCh := make(chan func())
errCh := make(chan error)
go func() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// S_FALSE is returned when CoInitializeEx is nested. This is a successful case.
if err := windows.CoInitializeEx(0, windows.COINIT_MULTITHREADED); err != nil && !errors.Is(err, syscall.Errno(windows.S_FALSE)) {
errCh <- err
}
// CoUninitialize should be called even when CoInitializeEx returns S_FALSE.
defer windows.CoUninitialize()
close(errCh)
for f := range funcCh {
f()
}
}()
if err := <-errCh; err != nil {
return nil, err
}
return &comThread{
funcCh: funcCh,
}, nil
}
func (c *comThread) Run(f func()) {
ch := make(chan struct{})
c.funcCh <- func() {
f()
close(ch)
}
<-ch
}
type wasapiContext struct {
sampleRate int
channelCount int
mux *mux.Mux
bufferSizeInBytes int
comThread *comThread
err atomicError
suspended bool
suspendedCond *sync.Cond
sampleReadyEvent windows.Handle
client *_IAudioClient2
bufferFrames uint32
renderClient *_IAudioRenderClient
currentDeviceID string
enumerator *_IMMDeviceEnumerator
buf []float32
m sync.Mutex
}
var (
errDeviceSwitched = errors.New("oto: device switched")
errFormatNotSupported = errors.New("oto: the specified format is not supported (there is the closest format instead)")
)
func newWASAPIContext(sampleRate, channelCount int, mux *mux.Mux, bufferSizeInBytes int) (context *wasapiContext, ferr error) {
t, err := newCOMThread()
if err != nil {
return nil, err
}
c := &wasapiContext{
sampleRate: sampleRate,
channelCount: channelCount,
mux: mux,
bufferSizeInBytes: bufferSizeInBytes,
comThread: t,
suspendedCond: sync.NewCond(&sync.Mutex{}),
}
ev, err := windows.CreateEventEx(nil, nil, 0, windows.EVENT_ALL_ACCESS)
if err != nil {
return nil, err
}
defer func() {
if ferr != nil {
windows.CloseHandle(ev)
}
}()
c.sampleReadyEvent = ev
if err := c.start(); err != nil {
return nil, err
}
return c, nil
}
func (c *wasapiContext) isDeviceSwitched() (bool, error) {
// If the audio is suspended, do nothing.
if c.isSuspended() {
return false, nil
}
var switched bool
var cerr error
c.comThread.Run(func() {
device, err := c.enumerator.GetDefaultAudioEndPoint(eRender, eConsole)
if err != nil {
cerr = err
return
}
defer device.Release()
id, err := device.GetId()
if err != nil {
cerr = err
return
}
if c.currentDeviceID == id {
return
}
switched = true
})
return switched, cerr
}
func (c *wasapiContext) start() error {
var cerr error
c.comThread.Run(func() {
if err := c.startOnCOMThread(); err != nil {
cerr = err
return
}
})
if cerr != nil {
return cerr
}
go func() {
if err := c.loop(); err != nil {
if !errors.Is(err, _AUDCLNT_E_DEVICE_INVALIDATED) && !errors.Is(err, _AUDCLNT_E_RESOURCES_INVALIDATED) && !errors.Is(err, errDeviceSwitched) {
c.err.TryStore(err)
return
}
if err := c.restart(); err != nil {
c.err.TryStore(err)
return
}
}
}()
return nil
}
func (c *wasapiContext) startOnCOMThread() (ferr error) {
if c.enumerator == nil {
e, err := _CoCreateInstance(&uuidMMDeviceEnumerator, nil, uint32(_CLSCTX_ALL), &uuidIMMDeviceEnumerator)
if err != nil {
return err
}
c.enumerator = (*_IMMDeviceEnumerator)(e)
defer func() {
if ferr != nil {
c.enumerator.Release()
c.enumerator = nil
}
}()
}
device, err := c.enumerator.GetDefaultAudioEndPoint(eRender, eConsole)
if err != nil {
if errors.Is(err, _E_NOTFOUND) {
return errDeviceNotFound
}
return err
}
defer device.Release()
id, err := device.GetId()
if err != nil {
return err
}
c.currentDeviceID = id
if c.client != nil {
c.client.Release()
c.client = nil
}
client, err := device.Activate(&uuidIAudioClient2, uint32(_CLSCTX_ALL), nil)
if err != nil {
return err
}
c.client = (*_IAudioClient2)(client)
if err := c.client.SetClientProperties(&_AudioClientProperties{
cbSize: uint32(unsafe.Sizeof(_AudioClientProperties{})),
bIsOffload: 0, // false
eCategory: _AudioCategory_Other, // In the example, AudioCategory_ForegroundOnlyMedia was used, but this value is deprecated.
}); err != nil {
return err
}
// Check the format is supported by WASAPI.
// Stereo with 48000 [Hz] is likely supported, but mono and/or other sample rates are unlikely supported.
// Fallback to WinMM in this case anyway.
const bitsPerSample = 32
nBlockAlign := c.channelCount * bitsPerSample / 8
var channelMask uint32
switch c.channelCount {
case 1:
channelMask = _SPEAKER_FRONT_CENTER
case 2:
channelMask = _SPEAKER_FRONT_LEFT | _SPEAKER_FRONT_RIGHT
}
f := &_WAVEFORMATEXTENSIBLE{
wFormatTag: _WAVE_FORMAT_EXTENSIBLE,
nChannels: uint16(c.channelCount),
nSamplesPerSec: uint32(c.sampleRate),
nAvgBytesPerSec: uint32(c.sampleRate * nBlockAlign),
nBlockAlign: uint16(nBlockAlign),
wBitsPerSample: bitsPerSample,
cbSize: 0x16,
Samples: bitsPerSample,
dwChannelMask: channelMask,
SubFormat: _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT,
}
var bufferSizeIn100ns _REFERENCE_TIME
if c.bufferSizeInBytes != 0 {
bufferSizeInFrames := int64(c.bufferSizeInBytes) / int64(nBlockAlign)
bufferSizeIn100ns = _REFERENCE_TIME(1e7 * bufferSizeInFrames / int64(c.sampleRate))
} else {
// The default buffer size can be too small and might cause glitch noises.
// Specify 50[ms] as the buffer size.
bufferSizeIn100ns = _REFERENCE_TIME(50 * time.Millisecond / 100)
}
// Even if the sample rate and/or the number of channels are not supported by the audio driver,
// AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM should convert the sample rate automatically (#215).
if err := c.client.Initialize(_AUDCLNT_SHAREMODE_SHARED,
_AUDCLNT_STREAMFLAGS_EVENTCALLBACK|_AUDCLNT_STREAMFLAGS_NOPERSIST|_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
bufferSizeIn100ns, 0, f, nil); err != nil {
return err
}
frames, err := c.client.GetBufferSize()
if err != nil {
return err
}
c.bufferFrames = frames
if c.renderClient != nil {
c.renderClient.Release()
c.renderClient = nil
}
renderClient, err := c.client.GetService(&uuidIAudioRenderClient)
if err != nil {
return err
}
c.renderClient = (*_IAudioRenderClient)(renderClient)
if err := c.client.SetEventHandle(c.sampleReadyEvent); err != nil {
return err
}
// TODO: Should some errors be allowed? See WASAPIManager.cpp in the official example SimpleWASAPIPlaySound.
if err := c.client.Start(); err != nil {
return err
}
return nil
}
func (c *wasapiContext) loop() error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// S_FALSE is returned when CoInitializeEx is nested. This is a successful case.
if err := windows.CoInitializeEx(0, windows.COINIT_MULTITHREADED); err != nil && !errors.Is(err, syscall.Errno(windows.S_FALSE)) {
_, _ = c.client.Stop()
return err
}
// CoUninitialize should be called even when CoInitializeEx returns S_FALSE.
defer windows.CoUninitialize()
if err := c.loopOnRenderThread(); err != nil {
_, _ = c.client.Stop()
return err
}
return nil
}
func (c *wasapiContext) loopOnRenderThread() error {
last := time.Now()
for {
c.suspendedCond.L.Lock()
for c.suspended {
c.suspendedCond.Wait()
}
c.suspendedCond.L.Unlock()
evt, err := windows.WaitForSingleObject(c.sampleReadyEvent, windows.INFINITE)
if err != nil {
return err
}
if evt != windows.WAIT_OBJECT_0 {
return fmt.Errorf("oto: WaitForSingleObject failed: returned value: %d", evt)
}
if err := c.writeOnRenderThread(); err != nil {
return err
}
// Checking the current default audio device might be an expensive operation.
// Check this repeatedly but with some time interval.
if now := time.Now(); now.Sub(last) >= 500*time.Millisecond {
switched, err := c.isDeviceSwitched()
if err != nil {
return err
}
if switched {
return errDeviceSwitched
}
last = now
}
}
}
func (c *wasapiContext) writeOnRenderThread() error {
c.m.Lock()
defer c.m.Unlock()
paddingFrames, err := c.client.GetCurrentPadding()
if err != nil {
return err
}
frames := c.bufferFrames - paddingFrames
if frames <= 0 {
return nil
}
// Get the destination buffer.
dstBuf, err := c.renderClient.GetBuffer(frames)
if err != nil {
return err
}
// Calculate the buffer size.
if buflen := int(frames) * c.channelCount; cap(c.buf) < buflen {
c.buf = make([]float32, buflen)
} else {
c.buf = c.buf[:buflen]
}
// Read the buffer from the players.
c.mux.ReadFloat32s(c.buf)
// Copy the read buf to the destination buffer.
copy(unsafe.Slice((*float32)(unsafe.Pointer(dstBuf)), len(c.buf)), c.buf)
// Release the buffer.
if err := c.renderClient.ReleaseBuffer(frames, 0); err != nil {
return err
}
c.buf = c.buf[:0]
return nil
}
func (c *wasapiContext) Suspend() error {
c.suspendedCond.L.Lock()
c.suspended = true
c.suspendedCond.L.Unlock()
c.suspendedCond.Signal()
return nil
}
func (c *wasapiContext) Resume() error {
c.suspendedCond.L.Lock()
c.suspended = false
c.suspendedCond.L.Unlock()
c.suspendedCond.Signal()
return nil
}
func (c *wasapiContext) isSuspended() bool {
c.suspendedCond.L.Lock()
defer c.suspendedCond.L.Unlock()
return c.suspended
}
func (c *wasapiContext) Err() error {
return c.err.Load()
}
func (c *wasapiContext) restart() error {
// Probably the driver is missing temporarily e.g. plugging out the headset.
// Recreate the device.
retry:
c.suspendedCond.L.Lock()
for c.suspended {
c.suspendedCond.Wait()
}
c.suspendedCond.L.Unlock()
if err := c.start(); err != nil {
// When a device is switched, the new device might not support the desired format,
// or all the audio devices might be disconnected.
// Instead of aborting this context, let's wait for the next device switch.
if !errors.Is(err, errFormatNotSupported) && !errors.Is(err, errDeviceNotFound) {
return err
}
// Just read the buffer and discard it. Then, retry to search the device.
var buf32 [4096]float32
sleep := time.Duration(float64(time.Second) * float64(len(buf32)) / float64(c.channelCount) / float64(c.sampleRate))
c.mux.ReadFloat32s(buf32[:])
time.Sleep(sleep)
goto retry
}
return nil
}

163
vendor/github.com/ebitengine/oto/v3/driver_windows.go generated vendored Normal file
View file

@ -0,0 +1,163 @@
// Copyright 2022 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"errors"
"fmt"
"time"
"github.com/ebitengine/oto/v3/internal/mux"
)
var errDeviceNotFound = errors.New("oto: device not found")
type context struct {
sampleRate int
channelCount int
mux *mux.Mux
wasapiContext *wasapiContext
winmmContext *winmmContext
nullContext *nullContext
ready chan struct{}
err atomicError
}
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int) (*context, chan struct{}, error) {
ctx := &context{
sampleRate: sampleRate,
channelCount: channelCount,
mux: mux.New(sampleRate, channelCount, format),
ready: make(chan struct{}),
}
// Initializing drivers might take some time. Do this asynchronously.
go func() {
defer close(ctx.ready)
xc, err0 := newWASAPIContext(sampleRate, channelCount, ctx.mux, bufferSizeInBytes)
if err0 == nil {
ctx.wasapiContext = xc
return
}
wc, err1 := newWinMMContext(sampleRate, channelCount, ctx.mux, bufferSizeInBytes)
if err1 == nil {
ctx.winmmContext = wc
return
}
if errors.Is(err0, errDeviceNotFound) && errors.Is(err1, errDeviceNotFound) {
ctx.nullContext = newNullContext(sampleRate, channelCount, ctx.mux)
return
}
ctx.err.TryStore(fmt.Errorf("oto: initialization failed: WASAPI: %v, WinMM: %v", err0, err1))
}()
return ctx, ctx.ready, nil
}
func (c *context) Suspend() error {
<-c.ready
if c.wasapiContext != nil {
return c.wasapiContext.Suspend()
}
if c.winmmContext != nil {
return c.winmmContext.Suspend()
}
if c.nullContext != nil {
return c.nullContext.Suspend()
}
return nil
}
func (c *context) Resume() error {
<-c.ready
if c.wasapiContext != nil {
return c.wasapiContext.Resume()
}
if c.winmmContext != nil {
return c.winmmContext.Resume()
}
if c.nullContext != nil {
return c.nullContext.Resume()
}
return nil
}
func (c *context) Err() error {
if err := c.err.Load(); err != nil {
return err
}
select {
case <-c.ready:
default:
return nil
}
if c.wasapiContext != nil {
return c.wasapiContext.Err()
}
if c.winmmContext != nil {
return c.winmmContext.Err()
}
if c.nullContext != nil {
return c.nullContext.Err()
}
return nil
}
type nullContext struct {
suspended bool
}
func newNullContext(sampleRate int, channelCount int, mux *mux.Mux) *nullContext {
c := &nullContext{}
go c.loop(sampleRate, channelCount, mux)
return c
}
func (c *nullContext) loop(sampleRate int, channelCount int, mux *mux.Mux) {
var buf32 [4096]float32
sleep := time.Duration(float64(time.Second) * float64(len(buf32)) / float64(channelCount) / float64(sampleRate))
for {
if c.suspended {
time.Sleep(time.Second)
continue
}
mux.ReadFloat32s(buf32[:])
time.Sleep(sleep)
}
}
func (c *nullContext) Suspend() error {
c.suspended = true
return nil
}
func (c *nullContext) Resume() error {
c.suspended = false
return nil
}
func (*nullContext) Err() error {
return nil
}

View file

@ -0,0 +1,297 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oto
import (
"errors"
"fmt"
"sync"
"time"
"unsafe"
"golang.org/x/sys/windows"
"github.com/ebitengine/oto/v3/internal/mux"
)
// Avoid goroutines on Windows (hajimehoshi/ebiten#1768).
// Apparently, switching contexts might take longer than other platforms.
const defaultHeaderBufferSize = 4096
type header struct {
waveOut uintptr
buffer []float32
waveHdr *_WAVEHDR
}
func newHeader(waveOut uintptr, bufferSizeInBytes int) (*header, error) {
h := &header{
waveOut: waveOut,
buffer: make([]float32, bufferSizeInBytes/4),
}
h.waveHdr = &_WAVEHDR{
lpData: uintptr(unsafe.Pointer(&h.buffer[0])),
dwBufferLength: uint32(bufferSizeInBytes),
}
if err := waveOutPrepareHeader(waveOut, h.waveHdr); err != nil {
return nil, err
}
return h, nil
}
func (h *header) Write(data []float32) error {
copy(h.buffer, data)
if err := waveOutWrite(h.waveOut, h.waveHdr); err != nil {
return err
}
return nil
}
func (h *header) IsQueued() bool {
return h.waveHdr.dwFlags&_WHDR_INQUEUE != 0
}
func (h *header) Close() error {
return waveOutUnprepareHeader(h.waveOut, h.waveHdr)
}
type winmmContext struct {
sampleRate int
channelCount int
bufferSizeInBytes int
waveOut uintptr
headers []*header
buf32 []float32
mux *mux.Mux
err atomicError
loopEndCh chan error
cond *sync.Cond
suspended bool
suspendedCond *sync.Cond
}
var theWinMMContext *winmmContext
func newWinMMContext(sampleRate, channelCount int, mux *mux.Mux, bufferSizeInBytes int) (*winmmContext, error) {
// winmm.dll is not available on Xbox.
if err := winmm.Load(); err != nil {
return nil, fmt.Errorf("oto: loading winmm.dll failed: %w", err)
}
c := &winmmContext{
sampleRate: sampleRate,
channelCount: channelCount,
bufferSizeInBytes: bufferSizeInBytes,
mux: mux,
cond: sync.NewCond(&sync.Mutex{}),
suspendedCond: sync.NewCond(&sync.Mutex{}),
}
theWinMMContext = c
if err := c.start(); err != nil {
return nil, err
}
return c, nil
}
func (c *winmmContext) start() error {
const bitsPerSample = 32
nBlockAlign := c.channelCount * bitsPerSample / 8
f := &_WAVEFORMATEX{
wFormatTag: _WAVE_FORMAT_IEEE_FLOAT,
nChannels: uint16(c.channelCount),
nSamplesPerSec: uint32(c.sampleRate),
nAvgBytesPerSec: uint32(c.sampleRate * nBlockAlign),
nBlockAlign: uint16(nBlockAlign),
wBitsPerSample: bitsPerSample,
}
// TOOD: What about using an event instead of a callback? PortAudio and other libraries do that.
w, err := waveOutOpen(f, waveOutOpenCallback)
if errors.Is(err, windows.ERROR_NOT_FOUND) {
// This can happen when no device is found (#77).
return errDeviceNotFound
}
if errors.Is(err, _MMSYSERR_BADDEVICEID) {
// This can happen when no device is found (hajimehoshi/ebiten#2316).
return errDeviceNotFound
}
if err != nil {
return err
}
headerBufferSize := defaultHeaderBufferSize
if c.bufferSizeInBytes != 0 {
headerBufferSize = c.bufferSizeInBytes
}
c.waveOut = w
c.headers = make([]*header, 0, 6)
for len(c.headers) < cap(c.headers) {
h, err := newHeader(c.waveOut, headerBufferSize)
if err != nil {
return err
}
c.headers = append(c.headers, h)
}
c.buf32 = make([]float32, headerBufferSize/4)
go c.loop()
return nil
}
func (c *winmmContext) Suspend() error {
c.suspendedCond.L.Lock()
c.suspended = true
c.suspendedCond.L.Unlock()
c.suspendedCond.Signal()
return nil
}
func (c *winmmContext) Resume() (ferr error) {
c.suspendedCond.L.Lock()
c.suspended = false
c.suspendedCond.L.Unlock()
c.suspendedCond.Signal()
return nil
}
func (c *winmmContext) Err() error {
if err := c.err.Load(); err != nil {
return err.(error)
}
return nil
}
func (c *winmmContext) isHeaderAvailable() bool {
for _, h := range c.headers {
if !h.IsQueued() {
return true
}
}
return false
}
var waveOutOpenCallback = windows.NewCallback(func(hwo, uMsg, dwInstance, dwParam1, dwParam2 uintptr) uintptr {
// Queuing a header in this callback might not work especially when a headset is connected or disconnected.
// Just signal the condition vairable and don't do other things.
const womDone = 0x3bd
if uMsg != womDone {
return 0
}
theWinMMContext.cond.Signal()
return 0
})
func (c *winmmContext) waitUntilHeaderAvailable() bool {
c.cond.L.Lock()
defer c.cond.L.Unlock()
for !c.isHeaderAvailable() && c.err.Load() == nil && c.loopEndCh == nil {
c.cond.Wait()
}
return c.err.Load() == nil && c.loopEndCh == nil
}
func (c *winmmContext) loop() {
defer func() {
if err := c.closeLoop(); err != nil {
c.err.TryStore(err)
}
}()
for {
c.suspendedCond.L.Lock()
for c.suspended {
c.suspendedCond.Wait()
}
c.suspendedCond.L.Unlock()
if !c.waitUntilHeaderAvailable() {
return
}
c.appendBuffers()
}
}
func (c *winmmContext) closeLoop() (ferr error) {
c.cond.L.Lock()
defer c.cond.L.Unlock()
defer func() {
if c.loopEndCh != nil {
if ferr != nil {
c.loopEndCh <- ferr
ferr = nil
}
close(c.loopEndCh)
c.loopEndCh = nil
}
}()
for _, h := range c.headers {
if err := h.Close(); err != nil {
return err
}
}
c.headers = nil
if err := waveOutClose(c.waveOut); err != nil {
return err
}
c.waveOut = 0
return nil
}
func (c *winmmContext) appendBuffers() {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if c.err.Load() != nil {
return
}
c.mux.ReadFloat32s(c.buf32)
for _, h := range c.headers {
if h.IsQueued() {
continue
}
if err := h.Write(c.buf32); err != nil {
switch {
case errors.Is(err, _MMSYSERR_NOMEM):
continue
case errors.Is(err, _MMSYSERR_NODRIVER):
sleep := time.Duration(float64(time.Second) * float64(len(c.buf32)) / float64(c.channelCount) / float64(c.sampleRate))
time.Sleep(sleep)
return
case errors.Is(err, windows.ERROR_NOT_FOUND):
// This error can happen when e.g. a new HDMI connection is detected (#51).
// TODO: Retry later.
}
c.err.TryStore(fmt.Errorf("oto: Queueing the header failed: %v", err))
}
return
}
}

560
vendor/github.com/ebitengine/oto/v3/internal/mux/mux.go generated vendored Normal file
View file

@ -0,0 +1,560 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package mux offers APIs for a low-level multiplexer of audio players.
// Usually you don't have to use this.
package mux
import (
"errors"
"fmt"
"io"
"math"
"runtime"
"sync"
"time"
)
// Format must sync with oto's Format.
type Format int
const (
FormatFloat32LE Format = iota
FormatUnsignedInt8
FormatSignedInt16LE
)
func (f Format) ByteLength() int {
switch f {
case FormatFloat32LE:
return 4
case FormatUnsignedInt8:
return 1
case FormatSignedInt16LE:
return 2
}
panic(fmt.Sprintf("mux: unexpected format: %d", f))
}
// Mux is a low-level multiplexer of audio players.
type Mux struct {
sampleRate int
channelCount int
format Format
players map[*playerImpl]struct{}
buf []float32
cond *sync.Cond
}
// New creates a new Mux.
func New(sampleRate int, channelCount int, format Format) *Mux {
m := &Mux{
sampleRate: sampleRate,
channelCount: channelCount,
format: format,
cond: sync.NewCond(&sync.Mutex{}),
}
go m.loop()
return m
}
func (m *Mux) shouldWait() bool {
for p := range m.players {
if p.canReadSourceToBuffer() {
return false
}
}
return true
}
func (m *Mux) wait() {
m.cond.L.Lock()
defer m.cond.L.Unlock()
for m.shouldWait() {
m.cond.Wait()
}
}
func (m *Mux) loop() {
var players []*playerImpl
for {
m.wait()
m.cond.L.Lock()
for i := range players {
players[i] = nil
}
players = players[:0]
for p := range m.players {
players = append(players, p)
}
m.cond.L.Unlock()
allZero := true
for _, p := range players {
n := p.readSourceToBuffer()
if n != 0 {
allZero = false
}
}
// Sleeping is necessary especially on browsers.
// Sometimes a player continues to read 0 bytes from the source and this loop can be a busy loop in such case.
if allZero {
time.Sleep(time.Millisecond)
}
}
}
func (m *Mux) addPlayer(player *playerImpl) {
m.cond.L.Lock()
defer m.cond.L.Unlock()
if m.players == nil {
m.players = map[*playerImpl]struct{}{}
}
m.players[player] = struct{}{}
m.cond.Signal()
}
func (m *Mux) removePlayer(player *playerImpl) {
m.cond.L.Lock()
defer m.cond.L.Unlock()
delete(m.players, player)
m.cond.Signal()
}
// ReadFloat32s fills buf with the multiplexed data of the players as float32 values.
func (m *Mux) ReadFloat32s(buf []float32) {
m.cond.L.Lock()
players := make([]*playerImpl, 0, len(m.players))
for p := range m.players {
players = append(players, p)
}
m.cond.L.Unlock()
for i := range buf {
buf[i] = 0
}
for _, p := range players {
p.readBufferAndAdd(buf)
}
m.cond.Signal()
}
type Player struct {
p *playerImpl
}
type playerState int
const (
playerPaused playerState = iota
playerPlay
playerClosed
)
type playerImpl struct {
mux *Mux
src io.Reader
prevVolume float64
volume float64
err error
state playerState
tmpbuf []byte
buf []byte
eof bool
bufferSize int
m sync.Mutex
}
func (m *Mux) NewPlayer(src io.Reader) *Player {
pl := &Player{
p: &playerImpl{
mux: m,
src: src,
prevVolume: 1,
volume: 1,
bufferSize: m.defaultBufferSize(),
},
}
runtime.SetFinalizer(pl, (*Player).Close)
return pl
}
func (p *Player) Err() error {
return p.p.Err()
}
func (p *playerImpl) Err() error {
p.m.Lock()
defer p.m.Unlock()
return p.err
}
func (p *Player) Play() {
p.p.Play()
}
func (p *playerImpl) Play() {
// Goroutines don't work effiently on Windows. Avoid using them (hajimehoshi/ebiten#1768).
if runtime.GOOS == "windows" {
p.m.Lock()
defer p.m.Unlock()
p.playImpl()
} else {
ch := make(chan struct{})
go func() {
p.m.Lock()
defer p.m.Unlock()
close(ch)
p.playImpl()
}()
<-ch
}
}
func (p *Player) SetBufferSize(bufferSize int) {
p.p.setBufferSize(bufferSize)
}
func (p *playerImpl) setBufferSize(bufferSize int) {
p.m.Lock()
defer p.m.Unlock()
orig := p.bufferSize
p.bufferSize = bufferSize
if bufferSize == 0 {
p.bufferSize = p.mux.defaultBufferSize()
}
if orig != p.bufferSize {
p.tmpbuf = nil
}
}
func (p *playerImpl) ensureTmpBuf() []byte {
if p.tmpbuf == nil {
p.tmpbuf = make([]byte, p.bufferSize)
}
return p.tmpbuf
}
// read reads the source to buf.
// read unlocks the mutex temporarily and locks when reading finishes.
// This avoids locking during an external function call Read (#188).
//
// When read is called, the mutex m must be locked.
func (p *playerImpl) read(buf []byte) (int, error) {
p.m.Unlock()
defer p.m.Lock()
return p.src.Read(buf)
}
// addToPlayers adds p to the players set.
//
// When addToPlayers is called, the mutex m must be locked.
func (p *playerImpl) addToPlayers() {
p.m.Unlock()
defer p.m.Lock()
p.mux.addPlayer(p)
}
// removeFromPlayers removes p from the players set.
//
// When removeFromPlayers is called, the mutex m must be locked.
func (p *playerImpl) removeFromPlayers() {
p.m.Unlock()
defer p.m.Lock()
p.mux.removePlayer(p)
}
func (p *playerImpl) playImpl() {
if p.err != nil {
return
}
if p.state != playerPaused {
return
}
p.state = playerPlay
if !p.eof {
buf := p.ensureTmpBuf()
for len(p.buf) < p.bufferSize {
n, err := p.read(buf)
if err != nil && err != io.EOF {
p.setErrorImpl(err)
return
}
p.buf = append(p.buf, buf[:n]...)
if err == io.EOF {
p.eof = true
break
}
}
}
if p.eof && len(p.buf) == 0 {
p.state = playerPaused
}
p.addToPlayers()
}
func (p *Player) Pause() {
p.p.Pause()
}
func (p *playerImpl) Pause() {
p.m.Lock()
defer p.m.Unlock()
if p.state != playerPlay {
return
}
p.state = playerPaused
}
func (p *Player) Seek(offset int64, whence int) (int64, error) {
return p.p.Seek(offset, whence)
}
func (p *playerImpl) Seek(offset int64, whence int) (int64, error) {
p.m.Lock()
defer p.m.Unlock()
// If a player is playing, keep playing even after this seeking.
if p.state == playerPlay {
defer p.playImpl()
}
// Reset the internal buffer.
p.resetImpl()
// Check if the source implements io.Seeker.
s, ok := p.src.(io.Seeker)
if !ok {
return 0, errors.New("mux: the source must implement io.Seeker")
}
return s.Seek(offset, whence)
}
func (p *Player) Reset() {
p.p.Reset()
}
func (p *playerImpl) Reset() {
p.m.Lock()
defer p.m.Unlock()
p.resetImpl()
}
func (p *playerImpl) resetImpl() {
if p.state == playerClosed {
return
}
p.state = playerPaused
p.buf = p.buf[:0]
p.eof = false
}
func (p *Player) IsPlaying() bool {
return p.p.IsPlaying()
}
func (p *playerImpl) IsPlaying() bool {
p.m.Lock()
defer p.m.Unlock()
return p.state == playerPlay
}
func (p *Player) Volume() float64 {
return p.p.Volume()
}
func (p *playerImpl) Volume() float64 {
p.m.Lock()
defer p.m.Unlock()
return p.volume
}
func (p *Player) SetVolume(volume float64) {
p.p.SetVolume(volume)
}
func (p *playerImpl) SetVolume(volume float64) {
p.m.Lock()
defer p.m.Unlock()
p.volume = volume
if p.state != playerPlay {
p.prevVolume = volume
}
}
func (p *Player) BufferedSize() int {
return p.p.BufferedSize()
}
func (p *playerImpl) BufferedSize() int {
p.m.Lock()
defer p.m.Unlock()
return len(p.buf)
}
func (p *Player) Close() error {
runtime.SetFinalizer(p, nil)
return p.p.Close()
}
func (p *playerImpl) Close() error {
p.m.Lock()
defer p.m.Unlock()
return p.closeImpl()
}
func (p *playerImpl) closeImpl() error {
p.removeFromPlayers()
if p.state == playerClosed {
return p.err
}
p.state = playerClosed
p.buf = nil
return p.err
}
func (p *playerImpl) readBufferAndAdd(buf []float32) int {
p.m.Lock()
defer p.m.Unlock()
if p.state != playerPlay {
return 0
}
format := p.mux.format
bitDepthInBytes := format.ByteLength()
n := len(p.buf) / bitDepthInBytes
if n > len(buf) {
n = len(buf)
}
prevVolume := float32(p.prevVolume)
volume := float32(p.volume)
channelCount := p.mux.channelCount
rateDenom := float32(n / channelCount)
src := p.buf[:n*bitDepthInBytes]
for i := 0; i < n; i++ {
var v float32
switch format {
case FormatFloat32LE:
v = math.Float32frombits(uint32(src[4*i]) | uint32(src[4*i+1])<<8 | uint32(src[4*i+2])<<16 | uint32(src[4*i+3])<<24)
case FormatUnsignedInt8:
v8 := src[i]
v = float32(v8-(1<<7)) / (1 << 7)
case FormatSignedInt16LE:
v16 := int16(src[2*i]) | (int16(src[2*i+1]) << 8)
v = float32(v16) / (1 << 15)
default:
panic(fmt.Sprintf("mux: unexpected format: %d", format))
}
if volume == prevVolume {
buf[i] += v * volume
} else {
rate := float32(i/channelCount) / rateDenom
if rate > 1 {
rate = 1
}
buf[i] += v * (volume*rate + prevVolume*(1-rate))
}
}
p.prevVolume = p.volume
copy(p.buf, p.buf[n*bitDepthInBytes:])
p.buf = p.buf[:len(p.buf)-n*bitDepthInBytes]
if p.eof && len(p.buf) == 0 {
p.state = playerPaused
}
return n
}
func (p *playerImpl) canReadSourceToBuffer() bool {
p.m.Lock()
defer p.m.Unlock()
if p.eof {
return false
}
return len(p.buf) < p.bufferSize
}
func (p *playerImpl) readSourceToBuffer() int {
p.m.Lock()
defer p.m.Unlock()
if p.err != nil {
return 0
}
if p.state == playerClosed {
return 0
}
if len(p.buf) >= p.bufferSize {
return 0
}
buf := p.ensureTmpBuf()
n, err := p.read(buf)
if err != nil && err != io.EOF {
p.setErrorImpl(err)
return 0
}
p.buf = append(p.buf, buf[:n]...)
if err == io.EOF {
p.eof = true
if len(p.buf) == 0 {
p.state = playerPaused
}
}
return n
}
func (p *playerImpl) setErrorImpl(err error) {
p.err = err
p.closeImpl()
}
// TODO: The term 'buffer' is confusing. Name each buffer with good terms.
// defaultBufferSize returns the default size of the buffer for the audio source.
// This buffer is used when unreading on pausing the player.
func (m *Mux) defaultBufferSize() int {
bytesPerSample := m.channelCount * m.format.ByteLength()
s := m.sampleRate * bytesPerSample / 2 // 0.5[s]
// Align s in multiples of bytes per sample, or a buffer could have extra bytes.
return s / bytesPerSample * bytesPerSample
}

View file

@ -0,0 +1,2 @@
DisableFormat: true
SortIncludes: false

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,54 @@
# Oboe [![Build CI](https://github.com/google/oboe/workflows/Build%20CI/badge.svg)](https://github.com/google/oboe/actions)
[![Introduction to Oboe video](docs/images/getting-started-video.jpg)](https://www.youtube.com/watch?v=csfHAbr5ilI&list=PLWz5rJ2EKKc_duWv9IPNvx9YBudNMmLSa)
Oboe is a C++ library which makes it easy to build high-performance audio apps on Android. It was created primarily to allow developers to target a simplified API that works across multiple API levels back to API level 16 (Jelly Bean).
## Features
- Compatible with API 16 onwards - runs on 99% of Android devices
- Chooses the audio API (OpenSL ES on API 16+ or AAudio on API 27+) which will give the best audio performance on the target Android device
- Automatic latency tuning
- Modern C++ allowing you to write clean, elegant code
- Workarounds for some known issues
- [Used by popular apps and frameworks](https://github.com/google/oboe/wiki/AppsUsingOboe)
## Documentation
- [Getting Started Guide](docs/GettingStarted.md)
- [Full Guide to Oboe](docs/FullGuide.md)
- [API reference](https://google.github.io/oboe)
- [Tech Notes](docs/notes/)
- [History of Audio features/bugs by Android version](docs/AndroidAudioHistory.md)
- [Migration guide for apps using OpenSL ES](docs/OpenSLESMigration.md)
- [Frequently Asked Questions](docs/FAQ.md) (FAQ)
- [Our roadmap](https://github.com/google/oboe/milestones) - Vote on a feature/issue by adding a thumbs up to the first comment.
### Community
- Reddit: [r/androidaudiodev](https://www.reddit.com/r/androidaudiodev/)
- StackOverflow: [#oboe](https://stackoverflow.com/questions/tagged/oboe)
## Testing
- [**OboeTester** app for measuring latency, glitches, etc.](apps/OboeTester/docs)
- [Oboe unit tests](tests)
## Videos
- [Getting started with Oboe](https://www.youtube.com/playlist?list=PLWz5rJ2EKKc_duWv9IPNvx9YBudNMmLSa)
- [Low Latency Audio - Because Your Ears Are Worth It](https://www.youtube.com/watch?v=8vOf_fDtur4) (Android Dev Summit '18)
- [Winning on Android](https://www.youtube.com/watch?v=tWBojmBpS74) - How to optimize an Android audio app. (ADC '18)
## Sample code and apps
- Sample apps can be found in the [samples directory](samples).
- A complete "effects processor" app called FXLab can be found in the [apps/fxlab folder](apps/fxlab).
- Also check out the [Rhythm Game codelab](https://developer.android.com/codelabs/musicalgame-using-oboe?hl=en#0).
### Third party sample code
- [Ableton Link integration demo](https://github.com/jbloit/AndroidLinkAudio) (author: jbloit)
## Contributing
We would love to receive your pull requests. Before we can though, please read the [contributing](CONTRIBUTING.md) guidelines.
## Version history
View the [releases page](../../releases).
## License
[LICENSE](LICENSE)

View file

@ -0,0 +1,191 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "binding_android.h"
#include "_cgo_export.h"
#include "oboe_oboe_Oboe_android.h"
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
namespace {
class Player;
class Stream : public oboe::AudioStreamDataCallback {
public:
// GetInstance returns the instance of Stream. Only one Stream object is used
// in one process. It is because multiple streams can be problematic in both
// AAudio and OpenSL (#1656, #1660).
static Stream &GetInstance();
const char *Play(int sample_rate, int channel_num, int buffer_size_in_bytes);
const char *Pause();
const char *Resume();
const char *Close();
const char *AppendBuffer(float *buf, size_t len);
oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboe_stream,
void *audio_data,
int32_t num_frames) override;
private:
Stream();
void Loop(int num_frames);
int sample_rate_ = 0;
int channel_num_ = 0;
std::shared_ptr<oboe::AudioStream> stream_;
// All the member variables other than the thread must be initialized before
// the thread.
std::vector<float> buf_;
std::mutex mutex_;
std::condition_variable cond_;
std::unique_ptr<std::thread> thread_;
};
Stream &Stream::GetInstance() {
static Stream *stream = new Stream();
return *stream;
}
const char *Stream::Play(int sample_rate, int channel_num,
int buffer_size_in_bytes) {
sample_rate_ = sample_rate;
channel_num_ = channel_num;
if (!stream_) {
oboe::AudioStreamBuilder builder;
builder.setDirection(oboe::Direction::Output)
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
->setSharingMode(oboe::SharingMode::Shared)
->setFormat(oboe::AudioFormat::Float)
->setChannelCount(channel_num_)
->setSampleRate(sample_rate_)
->setDataCallback(this);
if (buffer_size_in_bytes) {
int buffer_size_in_frames = buffer_size_in_bytes / channel_num / 4;
builder.setBufferCapacityInFrames(buffer_size_in_frames);
}
oboe::Result result = builder.openStream(stream_);
if (result != oboe::Result::OK) {
return oboe::convertToText(result);
}
}
if (stream_->getSharingMode() != oboe::SharingMode::Shared) {
return "oboe::SharingMode::Shared is not available";
}
int num_frames = stream_->getBufferSizeInFrames();
thread_ =
std::make_unique<std::thread>([this, num_frames]() { Loop(num_frames); });
// What if the buffer size is not enough?
if (oboe::Result result = stream_->start(); result != oboe::Result::OK) {
return oboe::convertToText(result);
}
return nullptr;
}
const char *Stream::Pause() {
if (!stream_) {
return nullptr;
}
if (oboe::Result result = stream_->pause(); result != oboe::Result::OK) {
return oboe::convertToText(result);
}
return nullptr;
}
const char *Stream::Resume() {
if (!stream_) {
return "Play is not called yet at Resume";
}
if (oboe::Result result = stream_->start(); result != oboe::Result::OK) {
return oboe::convertToText(result);
}
return nullptr;
}
const char *Stream::Close() {
// Nobody calls this so far.
if (!stream_) {
return nullptr;
}
if (oboe::Result result = stream_->stop(); result != oboe::Result::OK) {
return oboe::convertToText(result);
}
if (oboe::Result result = stream_->close(); result != oboe::Result::OK) {
return oboe::convertToText(result);
}
stream_.reset();
return nullptr;
}
oboe::DataCallbackResult Stream::onAudioReady(oboe::AudioStream *oboe_stream,
void *audio_data,
int32_t num_frames) {
size_t num = num_frames * channel_num_;
// TODO: Do not use a lock in onAudioReady.
// https://google.github.io/oboe/reference/classoboe_1_1_audio_stream_data_callback.html#ad8a3a9f609df5fd3a5d885cbe1b2204d
{
std::unique_lock<std::mutex> lock{mutex_};
cond_.wait(lock, [this, num] { return buf_.size() >= num; });
std::copy(buf_.begin(), buf_.begin() + num,
reinterpret_cast<float *>(audio_data));
buf_.erase(buf_.begin(), buf_.begin() + num);
cond_.notify_one();
}
return oboe::DataCallbackResult::Continue;
}
Stream::Stream() = default;
void Stream::Loop(int num_frames) {
std::vector<float> tmp(num_frames * channel_num_ * 3);
for (;;) {
{
std::unique_lock<std::mutex> lock{mutex_};
cond_.wait(lock, [this, &tmp] { return buf_.size() < tmp.size(); });
}
oto_oboe_read(&tmp[0], tmp.size());
{
std::lock_guard<std::mutex> lock{mutex_};
buf_.insert(buf_.end(), tmp.begin(), tmp.end());
cond_.notify_one();
}
}
}
} // namespace
extern "C" {
const char *oto_oboe_Play(int sample_rate, int channel_num,
int buffer_size_in_bytes) {
return Stream::GetInstance().Play(sample_rate, channel_num,
buffer_size_in_bytes);
}
const char *oto_oboe_Suspend() { return Stream::GetInstance().Pause(); }
const char *oto_oboe_Resume() { return Stream::GetInstance().Resume(); }
} // extern "C"

View file

@ -0,0 +1,60 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oboe
// Disable AAudio (hajimehoshi/ebiten#1634).
// AAudio doesn't care about plugging in/out of a headphone.
// See https://github.com/google/oboe/wiki/TechNote_Disconnect
// #cgo CXXFLAGS: -std=c++17 -DOBOE_ENABLE_AAUDIO=0
// #cgo LDFLAGS: -llog -lOpenSLES -static-libstdc++
//
// #include "binding_android.h"
import "C"
import (
"fmt"
"unsafe"
)
var theReadFunc func(buf []float32)
func Play(sampleRate int, channelCount int, readFunc func(buf []float32), bufferSizeInBytes int) error {
// Play can invoke the callback. Set the callback before Play.
theReadFunc = readFunc
if msg := C.oto_oboe_Play(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)); msg != nil {
return fmt.Errorf("oboe: Play failed: %s", C.GoString(msg))
}
return nil
}
func Suspend() error {
if msg := C.oto_oboe_Suspend(); msg != nil {
return fmt.Errorf("oboe: Suspend failed: %s", C.GoString(msg))
}
return nil
}
func Resume() error {
if msg := C.oto_oboe_Resume(); msg != nil {
return fmt.Errorf("oboe: Resume failed: %s", C.GoString(msg))
}
return nil
}
//export oto_oboe_read
func oto_oboe_read(buf *C.float, len C.size_t) {
theReadFunc(unsafe.Slice((*float32)(unsafe.Pointer(buf)), len))
}

View file

@ -0,0 +1,37 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OBOE_ANDROID_H_
#define OBOE_ANDROID_H_
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef uintptr_t PlayerID;
const char *oto_oboe_Play(int sample_rate, int channel_num,
int buffer_size_in_bytes);
const char *oto_oboe_Suspend();
const char *oto_oboe_Resume();
#ifdef __cplusplus
}
#endif
#endif // OBOE_ANDROID_H_

View file

@ -0,0 +1,17 @@
// Copyright 2021 The Oto Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:generate go run gen.go
package oboe

View file

@ -0,0 +1,179 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_AAUDIO_EXTENSIONS_H
#define OBOE_AAUDIO_EXTENSIONS_H
#include <dlfcn.h>
#include <stdint.h>
#include <sys/system_properties.h>
#include "oboe_common_OboeDebug_android.h"
#include "oboe_oboe_Oboe_android.h"
#include "oboe_aaudio_AAudioLoader_android.h"
namespace oboe {
#define LIB_AAUDIO_NAME "libaaudio.so"
#define FUNCTION_IS_MMAP "AAudioStream_isMMapUsed"
#define FUNCTION_SET_MMAP_POLICY "AAudio_setMMapPolicy"
#define FUNCTION_GET_MMAP_POLICY "AAudio_getMMapPolicy"
#define AAUDIO_ERROR_UNAVAILABLE static_cast<aaudio_result_t>(Result::ErrorUnavailable)
typedef struct AAudioStreamStruct AAudioStream;
/**
* Call some AAudio test routines that are not part of the normal API.
*/
class AAudioExtensions {
public:
AAudioExtensions() {
int32_t policy = getIntegerProperty("aaudio.mmap_policy", 0);
mMMapSupported = isPolicyEnabled(policy);
policy = getIntegerProperty("aaudio.mmap_exclusive_policy", 0);
mMMapExclusiveSupported = isPolicyEnabled(policy);
}
static bool isPolicyEnabled(int32_t policy) {
return (policy == AAUDIO_POLICY_AUTO || policy == AAUDIO_POLICY_ALWAYS);
}
static AAudioExtensions &getInstance() {
static AAudioExtensions instance;
return instance;
}
bool isMMapUsed(oboe::AudioStream *oboeStream) {
AAudioStream *aaudioStream = (AAudioStream *) oboeStream->getUnderlyingStream();
return isMMapUsed(aaudioStream);
}
bool isMMapUsed(AAudioStream *aaudioStream) {
if (loadSymbols()) return false;
if (mAAudioStream_isMMap == nullptr) return false;
return mAAudioStream_isMMap(aaudioStream);
}
/**
* Controls whether the MMAP data path can be selected when opening a stream.
* It has no effect after the stream has been opened.
* It only affects the application that calls it. Other apps are not affected.
*
* @param enabled
* @return 0 or a negative error code
*/
int32_t setMMapEnabled(bool enabled) {
if (loadSymbols()) return AAUDIO_ERROR_UNAVAILABLE;
if (mAAudio_setMMapPolicy == nullptr) return false;
return mAAudio_setMMapPolicy(enabled ? AAUDIO_POLICY_AUTO : AAUDIO_POLICY_NEVER);
}
bool isMMapEnabled() {
if (loadSymbols()) return false;
if (mAAudio_getMMapPolicy == nullptr) return false;
int32_t policy = mAAudio_getMMapPolicy();
return isPolicyEnabled(policy);
}
bool isMMapSupported() {
return mMMapSupported;
}
bool isMMapExclusiveSupported() {
return mMMapExclusiveSupported;
}
private:
enum {
AAUDIO_POLICY_NEVER = 1,
AAUDIO_POLICY_AUTO,
AAUDIO_POLICY_ALWAYS
};
typedef int32_t aaudio_policy_t;
int getIntegerProperty(const char *name, int defaultValue) {
int result = defaultValue;
char valueText[PROP_VALUE_MAX] = {0};
if (__system_property_get(name, valueText) != 0) {
result = atoi(valueText);
}
return result;
}
/**
* Load the function pointers.
* This can be called multiple times.
* It should only be called from one thread.
*
* @return 0 if successful or negative error.
*/
aaudio_result_t loadSymbols() {
if (mAAudio_getMMapPolicy != nullptr) {
return 0;
}
AAudioLoader *libLoader = AAudioLoader::getInstance();
int openResult = libLoader->open();
if (openResult != 0) {
LOGD("%s() could not open " LIB_AAUDIO_NAME, __func__);
return AAUDIO_ERROR_UNAVAILABLE;
}
void *libHandle = AAudioLoader::getInstance()->getLibHandle();
if (libHandle == nullptr) {
LOGE("%s() could not find " LIB_AAUDIO_NAME, __func__);
return AAUDIO_ERROR_UNAVAILABLE;
}
mAAudioStream_isMMap = (bool (*)(AAudioStream *stream))
dlsym(libHandle, FUNCTION_IS_MMAP);
if (mAAudioStream_isMMap == nullptr) {
LOGI("%s() could not find " FUNCTION_IS_MMAP, __func__);
return AAUDIO_ERROR_UNAVAILABLE;
}
mAAudio_setMMapPolicy = (int32_t (*)(aaudio_policy_t policy))
dlsym(libHandle, FUNCTION_SET_MMAP_POLICY);
if (mAAudio_setMMapPolicy == nullptr) {
LOGI("%s() could not find " FUNCTION_SET_MMAP_POLICY, __func__);
return AAUDIO_ERROR_UNAVAILABLE;
}
mAAudio_getMMapPolicy = (aaudio_policy_t (*)())
dlsym(libHandle, FUNCTION_GET_MMAP_POLICY);
if (mAAudio_getMMapPolicy == nullptr) {
LOGI("%s() could not find " FUNCTION_GET_MMAP_POLICY, __func__);
return AAUDIO_ERROR_UNAVAILABLE;
}
return 0;
}
bool mMMapSupported = false;
bool mMMapExclusiveSupported = false;
bool (*mAAudioStream_isMMap)(AAudioStream *stream) = nullptr;
int32_t (*mAAudio_setMMapPolicy)(aaudio_policy_t policy) = nullptr;
aaudio_policy_t (*mAAudio_getMMapPolicy)() = nullptr;
};
} // namespace oboe
#endif //OBOE_AAUDIO_EXTENSIONS_H

View file

@ -0,0 +1,450 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <dlfcn.h>
#include "oboe_oboe_Utilities_android.h"
#include "oboe_common_OboeDebug_android.h"
#include "oboe_aaudio_AAudioLoader_android.h"
#define LIB_AAUDIO_NAME "libaaudio.so"
namespace oboe {
AAudioLoader::~AAudioLoader() {
// Issue 360: thread_local variables with non-trivial destructors
// will cause segfaults if the containing library is dlclose()ed on
// devices running M or newer, or devices before M when using a static STL.
// The simple workaround is to not call dlclose.
// https://github.com/android/ndk/wiki/Changelog-r22#known-issues
//
// The libaaudio and libaaudioclient do not use thread_local.
// But, to be safe, we should avoid dlclose() if possible.
// Because AAudioLoader is a static Singleton, we can safely skip
// calling dlclose() without causing a resource leak.
LOGI("%s() dlclose(%s) not called, OK", __func__, LIB_AAUDIO_NAME);
}
AAudioLoader* AAudioLoader::getInstance() {
static AAudioLoader instance;
return &instance;
}
int AAudioLoader::open() {
if (mLibHandle != nullptr) {
return 0;
}
// Use RTLD_NOW to avoid the unpredictable behavior that RTLD_LAZY can cause.
// Also resolving all the links now will prevent a run-time penalty later.
mLibHandle = dlopen(LIB_AAUDIO_NAME, RTLD_NOW);
if (mLibHandle == nullptr) {
LOGI("AAudioLoader::open() could not find " LIB_AAUDIO_NAME);
return -1; // TODO review return code
} else {
LOGD("AAudioLoader(): dlopen(%s) returned %p", LIB_AAUDIO_NAME, mLibHandle);
}
// Load all the function pointers.
createStreamBuilder = load_I_PPB("AAudio_createStreamBuilder");
builder_openStream = load_I_PBPPS("AAudioStreamBuilder_openStream");
builder_setChannelCount = load_V_PBI("AAudioStreamBuilder_setChannelCount");
if (builder_setChannelCount == nullptr) {
// Use old deprecated alias if needed.
builder_setChannelCount = load_V_PBI("AAudioStreamBuilder_setSamplesPerFrame");
}
builder_setBufferCapacityInFrames = load_V_PBI("AAudioStreamBuilder_setBufferCapacityInFrames");
builder_setDeviceId = load_V_PBI("AAudioStreamBuilder_setDeviceId");
builder_setDirection = load_V_PBI("AAudioStreamBuilder_setDirection");
builder_setFormat = load_V_PBI("AAudioStreamBuilder_setFormat");
builder_setFramesPerDataCallback = load_V_PBI("AAudioStreamBuilder_setFramesPerDataCallback");
builder_setSharingMode = load_V_PBI("AAudioStreamBuilder_setSharingMode");
builder_setPerformanceMode = load_V_PBI("AAudioStreamBuilder_setPerformanceMode");
builder_setSampleRate = load_V_PBI("AAudioStreamBuilder_setSampleRate");
if (getSdkVersion() >= __ANDROID_API_P__){
builder_setUsage = load_V_PBI("AAudioStreamBuilder_setUsage");
builder_setContentType = load_V_PBI("AAudioStreamBuilder_setContentType");
builder_setInputPreset = load_V_PBI("AAudioStreamBuilder_setInputPreset");
builder_setSessionId = load_V_PBI("AAudioStreamBuilder_setSessionId");
}
if (getSdkVersion() >= __ANDROID_API_S__){
builder_setPackageName = load_V_PBCPH("AAudioStreamBuilder_setPackageName");
builder_setAttributionTag = load_V_PBCPH("AAudioStreamBuilder_setAttributionTag");
}
if (getSdkVersion() >= __ANDROID_API_S_V2__) {
builder_setChannelMask = load_V_PBU("AAudioStreamBuilder_setChannelMask");
}
builder_delete = load_I_PB("AAudioStreamBuilder_delete");
builder_setDataCallback = load_V_PBPDPV("AAudioStreamBuilder_setDataCallback");
builder_setErrorCallback = load_V_PBPEPV("AAudioStreamBuilder_setErrorCallback");
stream_read = load_I_PSPVIL("AAudioStream_read");
stream_write = load_I_PSCPVIL("AAudioStream_write");
stream_waitForStateChange = load_I_PSTPTL("AAudioStream_waitForStateChange");
stream_getTimestamp = load_I_PSKPLPL("AAudioStream_getTimestamp");
stream_getChannelCount = load_I_PS("AAudioStream_getChannelCount");
if (stream_getChannelCount == nullptr) {
// Use old alias if needed.
stream_getChannelCount = load_I_PS("AAudioStream_getSamplesPerFrame");
}
stream_close = load_I_PS("AAudioStream_close");
stream_getBufferSize = load_I_PS("AAudioStream_getBufferSizeInFrames");
stream_getDeviceId = load_I_PS("AAudioStream_getDeviceId");
stream_getBufferCapacity = load_I_PS("AAudioStream_getBufferCapacityInFrames");
stream_getFormat = load_F_PS("AAudioStream_getFormat");
stream_getFramesPerBurst = load_I_PS("AAudioStream_getFramesPerBurst");
stream_getFramesRead = load_L_PS("AAudioStream_getFramesRead");
stream_getFramesWritten = load_L_PS("AAudioStream_getFramesWritten");
stream_getPerformanceMode = load_I_PS("AAudioStream_getPerformanceMode");
stream_getSampleRate = load_I_PS("AAudioStream_getSampleRate");
stream_getSharingMode = load_I_PS("AAudioStream_getSharingMode");
stream_getState = load_I_PS("AAudioStream_getState");
stream_getXRunCount = load_I_PS("AAudioStream_getXRunCount");
stream_requestStart = load_I_PS("AAudioStream_requestStart");
stream_requestPause = load_I_PS("AAudioStream_requestPause");
stream_requestFlush = load_I_PS("AAudioStream_requestFlush");
stream_requestStop = load_I_PS("AAudioStream_requestStop");
stream_setBufferSize = load_I_PSI("AAudioStream_setBufferSizeInFrames");
convertResultToText = load_CPH_I("AAudio_convertResultToText");
if (getSdkVersion() >= __ANDROID_API_P__){
stream_getUsage = load_I_PS("AAudioStream_getUsage");
stream_getContentType = load_I_PS("AAudioStream_getContentType");
stream_getInputPreset = load_I_PS("AAudioStream_getInputPreset");
stream_getSessionId = load_I_PS("AAudioStream_getSessionId");
}
if (getSdkVersion() >= __ANDROID_API_S_V2__) {
stream_getChannelMask = load_U_PS("AAudioStream_getChannelMask");
}
return 0;
}
static void AAudioLoader_check(void *proc, const char *functionName) {
if (proc == nullptr) {
LOGW("AAudioLoader could not find %s", functionName);
}
}
AAudioLoader::signature_I_PPB AAudioLoader::load_I_PPB(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PPB>(proc);
}
AAudioLoader::signature_CPH_I AAudioLoader::load_CPH_I(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_CPH_I>(proc);
}
AAudioLoader::signature_V_PBI AAudioLoader::load_V_PBI(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_V_PBI>(proc);
}
AAudioLoader::signature_V_PBCPH AAudioLoader::load_V_PBCPH(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_V_PBCPH>(proc);
}
AAudioLoader::signature_V_PBPDPV AAudioLoader::load_V_PBPDPV(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_V_PBPDPV>(proc);
}
AAudioLoader::signature_V_PBPEPV AAudioLoader::load_V_PBPEPV(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_V_PBPEPV>(proc);
}
AAudioLoader::signature_I_PSI AAudioLoader::load_I_PSI(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PSI>(proc);
}
AAudioLoader::signature_I_PS AAudioLoader::load_I_PS(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PS>(proc);
}
AAudioLoader::signature_L_PS AAudioLoader::load_L_PS(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_L_PS>(proc);
}
AAudioLoader::signature_F_PS AAudioLoader::load_F_PS(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_F_PS>(proc);
}
AAudioLoader::signature_B_PS AAudioLoader::load_B_PS(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_B_PS>(proc);
}
AAudioLoader::signature_I_PB AAudioLoader::load_I_PB(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PB>(proc);
}
AAudioLoader::signature_I_PBPPS AAudioLoader::load_I_PBPPS(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PBPPS>(proc);
}
AAudioLoader::signature_I_PSCPVIL AAudioLoader::load_I_PSCPVIL(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PSCPVIL>(proc);
}
AAudioLoader::signature_I_PSPVIL AAudioLoader::load_I_PSPVIL(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PSPVIL>(proc);
}
AAudioLoader::signature_I_PSTPTL AAudioLoader::load_I_PSTPTL(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PSTPTL>(proc);
}
AAudioLoader::signature_I_PSKPLPL AAudioLoader::load_I_PSKPLPL(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_I_PSKPLPL>(proc);
}
AAudioLoader::signature_V_PBU AAudioLoader::load_V_PBU(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_V_PBU>(proc);
}
AAudioLoader::signature_U_PS AAudioLoader::load_U_PS(const char *functionName) {
void *proc = dlsym(mLibHandle, functionName);
AAudioLoader_check(proc, functionName);
return reinterpret_cast<signature_U_PS>(proc);
}
// Ensure that all AAudio primitive data types are int32_t
#define ASSERT_INT32(type) static_assert(std::is_same<int32_t, type>::value, \
#type" must be int32_t")
// Ensure that all AAudio primitive data types are uint32_t
#define ASSERT_UINT32(type) static_assert(std::is_same<uint32_t, type>::value, \
#type" must be uint32_t")
#define ERRMSG "Oboe constants must match AAudio constants."
// These asserts help verify that the Oboe definitions match the equivalent AAudio definitions.
// This code is in this .cpp file so it only gets tested once.
#ifdef AAUDIO_AAUDIO_H
ASSERT_INT32(aaudio_stream_state_t);
ASSERT_INT32(aaudio_direction_t);
ASSERT_INT32(aaudio_format_t);
ASSERT_INT32(aaudio_data_callback_result_t);
ASSERT_INT32(aaudio_result_t);
ASSERT_INT32(aaudio_sharing_mode_t);
ASSERT_INT32(aaudio_performance_mode_t);
static_assert((int32_t)StreamState::Uninitialized == AAUDIO_STREAM_STATE_UNINITIALIZED, ERRMSG);
static_assert((int32_t)StreamState::Unknown == AAUDIO_STREAM_STATE_UNKNOWN, ERRMSG);
static_assert((int32_t)StreamState::Open == AAUDIO_STREAM_STATE_OPEN, ERRMSG);
static_assert((int32_t)StreamState::Starting == AAUDIO_STREAM_STATE_STARTING, ERRMSG);
static_assert((int32_t)StreamState::Started == AAUDIO_STREAM_STATE_STARTED, ERRMSG);
static_assert((int32_t)StreamState::Pausing == AAUDIO_STREAM_STATE_PAUSING, ERRMSG);
static_assert((int32_t)StreamState::Paused == AAUDIO_STREAM_STATE_PAUSED, ERRMSG);
static_assert((int32_t)StreamState::Flushing == AAUDIO_STREAM_STATE_FLUSHING, ERRMSG);
static_assert((int32_t)StreamState::Flushed == AAUDIO_STREAM_STATE_FLUSHED, ERRMSG);
static_assert((int32_t)StreamState::Stopping == AAUDIO_STREAM_STATE_STOPPING, ERRMSG);
static_assert((int32_t)StreamState::Stopped == AAUDIO_STREAM_STATE_STOPPED, ERRMSG);
static_assert((int32_t)StreamState::Closing == AAUDIO_STREAM_STATE_CLOSING, ERRMSG);
static_assert((int32_t)StreamState::Closed == AAUDIO_STREAM_STATE_CLOSED, ERRMSG);
static_assert((int32_t)StreamState::Disconnected == AAUDIO_STREAM_STATE_DISCONNECTED, ERRMSG);
static_assert((int32_t)Direction::Output == AAUDIO_DIRECTION_OUTPUT, ERRMSG);
static_assert((int32_t)Direction::Input == AAUDIO_DIRECTION_INPUT, ERRMSG);
static_assert((int32_t)AudioFormat::Invalid == AAUDIO_FORMAT_INVALID, ERRMSG);
static_assert((int32_t)AudioFormat::Unspecified == AAUDIO_FORMAT_UNSPECIFIED, ERRMSG);
static_assert((int32_t)AudioFormat::I16 == AAUDIO_FORMAT_PCM_I16, ERRMSG);
static_assert((int32_t)AudioFormat::Float == AAUDIO_FORMAT_PCM_FLOAT, ERRMSG);
static_assert((int32_t)DataCallbackResult::Continue == AAUDIO_CALLBACK_RESULT_CONTINUE, ERRMSG);
static_assert((int32_t)DataCallbackResult::Stop == AAUDIO_CALLBACK_RESULT_STOP, ERRMSG);
static_assert((int32_t)Result::OK == AAUDIO_OK, ERRMSG);
static_assert((int32_t)Result::ErrorBase == AAUDIO_ERROR_BASE, ERRMSG);
static_assert((int32_t)Result::ErrorDisconnected == AAUDIO_ERROR_DISCONNECTED, ERRMSG);
static_assert((int32_t)Result::ErrorIllegalArgument == AAUDIO_ERROR_ILLEGAL_ARGUMENT, ERRMSG);
static_assert((int32_t)Result::ErrorInternal == AAUDIO_ERROR_INTERNAL, ERRMSG);
static_assert((int32_t)Result::ErrorInvalidState == AAUDIO_ERROR_INVALID_STATE, ERRMSG);
static_assert((int32_t)Result::ErrorInvalidHandle == AAUDIO_ERROR_INVALID_HANDLE, ERRMSG);
static_assert((int32_t)Result::ErrorUnimplemented == AAUDIO_ERROR_UNIMPLEMENTED, ERRMSG);
static_assert((int32_t)Result::ErrorUnavailable == AAUDIO_ERROR_UNAVAILABLE, ERRMSG);
static_assert((int32_t)Result::ErrorNoFreeHandles == AAUDIO_ERROR_NO_FREE_HANDLES, ERRMSG);
static_assert((int32_t)Result::ErrorNoMemory == AAUDIO_ERROR_NO_MEMORY, ERRMSG);
static_assert((int32_t)Result::ErrorNull == AAUDIO_ERROR_NULL, ERRMSG);
static_assert((int32_t)Result::ErrorTimeout == AAUDIO_ERROR_TIMEOUT, ERRMSG);
static_assert((int32_t)Result::ErrorWouldBlock == AAUDIO_ERROR_WOULD_BLOCK, ERRMSG);
static_assert((int32_t)Result::ErrorInvalidFormat == AAUDIO_ERROR_INVALID_FORMAT, ERRMSG);
static_assert((int32_t)Result::ErrorOutOfRange == AAUDIO_ERROR_OUT_OF_RANGE, ERRMSG);
static_assert((int32_t)Result::ErrorNoService == AAUDIO_ERROR_NO_SERVICE, ERRMSG);
static_assert((int32_t)Result::ErrorInvalidRate == AAUDIO_ERROR_INVALID_RATE, ERRMSG);
static_assert((int32_t)SharingMode::Exclusive == AAUDIO_SHARING_MODE_EXCLUSIVE, ERRMSG);
static_assert((int32_t)SharingMode::Shared == AAUDIO_SHARING_MODE_SHARED, ERRMSG);
static_assert((int32_t)PerformanceMode::None == AAUDIO_PERFORMANCE_MODE_NONE, ERRMSG);
static_assert((int32_t)PerformanceMode::PowerSaving
== AAUDIO_PERFORMANCE_MODE_POWER_SAVING, ERRMSG);
static_assert((int32_t)PerformanceMode::LowLatency
== AAUDIO_PERFORMANCE_MODE_LOW_LATENCY, ERRMSG);
// The aaudio_ usage, content and input_preset types were added in NDK 17,
// which is the first version to support Android Pie (API 28).
#if __NDK_MAJOR__ >= 17
ASSERT_INT32(aaudio_usage_t);
ASSERT_INT32(aaudio_content_type_t);
ASSERT_INT32(aaudio_input_preset_t);
static_assert((int32_t)Usage::Media == AAUDIO_USAGE_MEDIA, ERRMSG);
static_assert((int32_t)Usage::VoiceCommunication == AAUDIO_USAGE_VOICE_COMMUNICATION, ERRMSG);
static_assert((int32_t)Usage::VoiceCommunicationSignalling
== AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING, ERRMSG);
static_assert((int32_t)Usage::Alarm == AAUDIO_USAGE_ALARM, ERRMSG);
static_assert((int32_t)Usage::Notification == AAUDIO_USAGE_NOTIFICATION, ERRMSG);
static_assert((int32_t)Usage::NotificationRingtone == AAUDIO_USAGE_NOTIFICATION_RINGTONE, ERRMSG);
static_assert((int32_t)Usage::NotificationEvent == AAUDIO_USAGE_NOTIFICATION_EVENT, ERRMSG);
static_assert((int32_t)Usage::AssistanceAccessibility == AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY, ERRMSG);
static_assert((int32_t)Usage::AssistanceNavigationGuidance
== AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE, ERRMSG);
static_assert((int32_t)Usage::AssistanceSonification == AAUDIO_USAGE_ASSISTANCE_SONIFICATION, ERRMSG);
static_assert((int32_t)Usage::Game == AAUDIO_USAGE_GAME, ERRMSG);
static_assert((int32_t)Usage::Assistant == AAUDIO_USAGE_ASSISTANT, ERRMSG);
static_assert((int32_t)ContentType::Speech == AAUDIO_CONTENT_TYPE_SPEECH, ERRMSG);
static_assert((int32_t)ContentType::Music == AAUDIO_CONTENT_TYPE_MUSIC, ERRMSG);
static_assert((int32_t)ContentType::Movie == AAUDIO_CONTENT_TYPE_MOVIE, ERRMSG);
static_assert((int32_t)ContentType::Sonification == AAUDIO_CONTENT_TYPE_SONIFICATION, ERRMSG);
static_assert((int32_t)InputPreset::Generic == AAUDIO_INPUT_PRESET_GENERIC, ERRMSG);
static_assert((int32_t)InputPreset::Camcorder == AAUDIO_INPUT_PRESET_CAMCORDER, ERRMSG);
static_assert((int32_t)InputPreset::VoiceRecognition == AAUDIO_INPUT_PRESET_VOICE_RECOGNITION, ERRMSG);
static_assert((int32_t)InputPreset::VoiceCommunication
== AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION, ERRMSG);
static_assert((int32_t)InputPreset::Unprocessed == AAUDIO_INPUT_PRESET_UNPROCESSED, ERRMSG);
static_assert((int32_t)SessionId::None == AAUDIO_SESSION_ID_NONE, ERRMSG);
static_assert((int32_t)SessionId::Allocate == AAUDIO_SESSION_ID_ALLOCATE, ERRMSG);
#endif // __NDK_MAJOR__ >= 17
// The aaudio channel masks were added in NDK 24,
// which is the first version to support Android SC_V2 (API 32).
#if __NDK_MAJOR__ >= 24
ASSERT_UINT32(aaudio_channel_mask_t);
static_assert((uint32_t)ChannelMask::FrontLeft == AAUDIO_CHANNEL_FRONT_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontRight == AAUDIO_CHANNEL_FRONT_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontCenter == AAUDIO_CHANNEL_FRONT_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::LowFrequency == AAUDIO_CHANNEL_LOW_FREQUENCY, ERRMSG);
static_assert((uint32_t)ChannelMask::BackLeft == AAUDIO_CHANNEL_BACK_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::BackRight == AAUDIO_CHANNEL_BACK_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontLeftOfCenter == AAUDIO_CHANNEL_FRONT_LEFT_OF_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontRightOfCenter == AAUDIO_CHANNEL_FRONT_RIGHT_OF_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::BackCenter == AAUDIO_CHANNEL_BACK_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::SideLeft == AAUDIO_CHANNEL_SIDE_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::SideRight == AAUDIO_CHANNEL_SIDE_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::TopCenter == AAUDIO_CHANNEL_TOP_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::TopFrontLeft == AAUDIO_CHANNEL_TOP_FRONT_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::TopFrontCenter == AAUDIO_CHANNEL_TOP_FRONT_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::TopFrontRight == AAUDIO_CHANNEL_TOP_FRONT_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::TopBackLeft == AAUDIO_CHANNEL_TOP_BACK_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::TopBackCenter == AAUDIO_CHANNEL_TOP_BACK_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::TopBackRight == AAUDIO_CHANNEL_TOP_BACK_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::TopSideLeft == AAUDIO_CHANNEL_TOP_SIDE_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::TopSideRight == AAUDIO_CHANNEL_TOP_SIDE_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::BottomFrontLeft == AAUDIO_CHANNEL_BOTTOM_FRONT_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::BottomFrontCenter == AAUDIO_CHANNEL_BOTTOM_FRONT_CENTER, ERRMSG);
static_assert((uint32_t)ChannelMask::BottomFrontRight == AAUDIO_CHANNEL_BOTTOM_FRONT_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::LowFrequency2 == AAUDIO_CHANNEL_LOW_FREQUENCY_2, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontWideLeft == AAUDIO_CHANNEL_FRONT_WIDE_LEFT, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontWideRight == AAUDIO_CHANNEL_FRONT_WIDE_RIGHT, ERRMSG);
static_assert((uint32_t)ChannelMask::Mono == AAUDIO_CHANNEL_MONO, ERRMSG);
static_assert((uint32_t)ChannelMask::Stereo == AAUDIO_CHANNEL_STEREO, ERRMSG);
static_assert((uint32_t)ChannelMask::CM2Point1 == AAUDIO_CHANNEL_2POINT1, ERRMSG);
static_assert((uint32_t)ChannelMask::Tri == AAUDIO_CHANNEL_TRI, ERRMSG);
static_assert((uint32_t)ChannelMask::TriBack == AAUDIO_CHANNEL_TRI_BACK, ERRMSG);
static_assert((uint32_t)ChannelMask::CM3Point1 == AAUDIO_CHANNEL_3POINT1, ERRMSG);
static_assert((uint32_t)ChannelMask::CM2Point0Point2 == AAUDIO_CHANNEL_2POINT0POINT2, ERRMSG);
static_assert((uint32_t)ChannelMask::CM2Point1Point2 == AAUDIO_CHANNEL_2POINT1POINT2, ERRMSG);
static_assert((uint32_t)ChannelMask::CM3Point0Point2 == AAUDIO_CHANNEL_3POINT0POINT2, ERRMSG);
static_assert((uint32_t)ChannelMask::CM3Point1Point2 == AAUDIO_CHANNEL_3POINT1POINT2, ERRMSG);
static_assert((uint32_t)ChannelMask::Quad == AAUDIO_CHANNEL_QUAD, ERRMSG);
static_assert((uint32_t)ChannelMask::QuadSide == AAUDIO_CHANNEL_QUAD_SIDE, ERRMSG);
static_assert((uint32_t)ChannelMask::Surround == AAUDIO_CHANNEL_SURROUND, ERRMSG);
static_assert((uint32_t)ChannelMask::Penta == AAUDIO_CHANNEL_PENTA, ERRMSG);
static_assert((uint32_t)ChannelMask::CM5Point1 == AAUDIO_CHANNEL_5POINT1, ERRMSG);
static_assert((uint32_t)ChannelMask::CM5Point1Side == AAUDIO_CHANNEL_5POINT1_SIDE, ERRMSG);
static_assert((uint32_t)ChannelMask::CM6Point1 == AAUDIO_CHANNEL_6POINT1, ERRMSG);
static_assert((uint32_t)ChannelMask::CM7Point1 == AAUDIO_CHANNEL_7POINT1, ERRMSG);
static_assert((uint32_t)ChannelMask::CM5Point1Point2 == AAUDIO_CHANNEL_5POINT1POINT2, ERRMSG);
static_assert((uint32_t)ChannelMask::CM5Point1Point4 == AAUDIO_CHANNEL_5POINT1POINT4, ERRMSG);
static_assert((uint32_t)ChannelMask::CM7Point1Point2 == AAUDIO_CHANNEL_7POINT1POINT2, ERRMSG);
static_assert((uint32_t)ChannelMask::CM7Point1Point4 == AAUDIO_CHANNEL_7POINT1POINT4, ERRMSG);
static_assert((uint32_t)ChannelMask::CM9Point1Point4 == AAUDIO_CHANNEL_9POINT1POINT4, ERRMSG);
static_assert((uint32_t)ChannelMask::CM9Point1Point6 == AAUDIO_CHANNEL_9POINT1POINT6, ERRMSG);
static_assert((uint32_t)ChannelMask::FrontBack == AAUDIO_CHANNEL_FRONT_BACK, ERRMSG);
#endif
#endif // AAUDIO_AAUDIO_H
} // namespace oboe

View file

@ -0,0 +1,263 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_AAUDIO_LOADER_H_
#define OBOE_AAUDIO_LOADER_H_
#include <unistd.h>
#include "oboe_oboe_Definitions_android.h"
// If the NDK is before O then define this in your build
// so that AAudio.h will not be included.
#ifdef OBOE_NO_INCLUDE_AAUDIO
// Define missing types from AAudio.h
typedef int32_t aaudio_stream_state_t;
typedef int32_t aaudio_direction_t;
typedef int32_t aaudio_format_t;
typedef int32_t aaudio_data_callback_result_t;
typedef int32_t aaudio_result_t;
typedef int32_t aaudio_sharing_mode_t;
typedef int32_t aaudio_performance_mode_t;
typedef struct AAudioStreamStruct AAudioStream;
typedef struct AAudioStreamBuilderStruct AAudioStreamBuilder;
typedef aaudio_data_callback_result_t (*AAudioStream_dataCallback)(
AAudioStream *stream,
void *userData,
void *audioData,
int32_t numFrames);
typedef void (*AAudioStream_errorCallback)(
AAudioStream *stream,
void *userData,
aaudio_result_t error);
// These were defined in P
typedef int32_t aaudio_usage_t;
typedef int32_t aaudio_content_type_t;
typedef int32_t aaudio_input_preset_t;
typedef int32_t aaudio_session_id_t;
// There are a few definitions used by Oboe.
#define AAUDIO_OK static_cast<aaudio_result_t>(Result::OK)
#define AAUDIO_ERROR_TIMEOUT static_cast<aaudio_result_t>(Result::ErrorTimeout)
#define AAUDIO_STREAM_STATE_STARTING static_cast<aaudio_stream_state_t>(StreamState::Starting)
#define AAUDIO_STREAM_STATE_STARTED static_cast<aaudio_stream_state_t>(StreamState::Started)
#else
#include <aaudio/AAudio.h>
#endif
#ifndef __NDK_MAJOR__
#define __NDK_MAJOR__ 0
#endif
#if __NDK_MAJOR__ < 24
// Defined in SC_V2
typedef uint32_t aaudio_channel_mask_t;
#endif
#ifndef __ANDROID_API_S__
#define __ANDROID_API_S__ 31
#endif
#ifndef __ANDROID_API_S_V2__
#define __ANDROID_API_S_V2__ 32
#endif
namespace oboe {
/**
* The AAudio API was not available in early versions of Android.
* To avoid linker errors, we dynamically link with the functions by name using dlsym().
* On older versions this linkage will safely fail.
*/
class AAudioLoader {
public:
// Use signatures for common functions.
// Key to letter abbreviations.
// S = Stream
// B = Builder
// I = int32_t
// L = int64_t
// T = sTate
// K = clocKid_t
// P = Pointer to following data type
// C = Const prefix
// H = cHar
// U = uint32_t
typedef int32_t (*signature_I_PPB)(AAudioStreamBuilder **builder);
typedef const char * (*signature_CPH_I)(int32_t);
typedef int32_t (*signature_I_PBPPS)(AAudioStreamBuilder *,
AAudioStream **stream); // AAudioStreamBuilder_open()
typedef int32_t (*signature_I_PB)(AAudioStreamBuilder *); // AAudioStreamBuilder_delete()
// AAudioStreamBuilder_setSampleRate()
typedef void (*signature_V_PBI)(AAudioStreamBuilder *, int32_t);
// AAudioStreamBuilder_setChannelMask()
typedef void (*signature_V_PBU)(AAudioStreamBuilder *, uint32_t);
typedef void (*signature_V_PBCPH)(AAudioStreamBuilder *, const char *);
typedef int32_t (*signature_I_PS)(AAudioStream *); // AAudioStream_getSampleRate()
typedef int64_t (*signature_L_PS)(AAudioStream *); // AAudioStream_getFramesRead()
// AAudioStream_setBufferSizeInFrames()
typedef int32_t (*signature_I_PSI)(AAudioStream *, int32_t);
typedef void (*signature_V_PBPDPV)(AAudioStreamBuilder *,
AAudioStream_dataCallback,
void *);
typedef void (*signature_V_PBPEPV)(AAudioStreamBuilder *,
AAudioStream_errorCallback,
void *);
typedef aaudio_format_t (*signature_F_PS)(AAudioStream *stream);
typedef int32_t (*signature_I_PSPVIL)(AAudioStream *, void *, int32_t, int64_t);
typedef int32_t (*signature_I_PSCPVIL)(AAudioStream *, const void *, int32_t, int64_t);
typedef int32_t (*signature_I_PSTPTL)(AAudioStream *,
aaudio_stream_state_t,
aaudio_stream_state_t *,
int64_t);
typedef int32_t (*signature_I_PSKPLPL)(AAudioStream *, clockid_t, int64_t *, int64_t *);
typedef bool (*signature_B_PS)(AAudioStream *);
typedef uint32_t (*signature_U_PS)(AAudioStream *);
static AAudioLoader* getInstance(); // singleton
/**
* Open the AAudio shared library and load the function pointers.
* This can be called multiple times.
* It should only be called from one thread.
*
* The destructor will clean up after the open.
*
* @return 0 if successful or negative error.
*/
int open();
void *getLibHandle() const { return mLibHandle; }
// Function pointers into the AAudio shared library.
signature_I_PPB createStreamBuilder = nullptr;
signature_I_PBPPS builder_openStream = nullptr;
signature_V_PBI builder_setBufferCapacityInFrames = nullptr;
signature_V_PBI builder_setChannelCount = nullptr;
signature_V_PBI builder_setDeviceId = nullptr;
signature_V_PBI builder_setDirection = nullptr;
signature_V_PBI builder_setFormat = nullptr;
signature_V_PBI builder_setFramesPerDataCallback = nullptr;
signature_V_PBI builder_setPerformanceMode = nullptr;
signature_V_PBI builder_setSampleRate = nullptr;
signature_V_PBI builder_setSharingMode = nullptr;
signature_V_PBU builder_setChannelMask = nullptr;
signature_V_PBI builder_setUsage = nullptr;
signature_V_PBI builder_setContentType = nullptr;
signature_V_PBI builder_setInputPreset = nullptr;
signature_V_PBI builder_setSessionId = nullptr;
signature_V_PBCPH builder_setPackageName = nullptr;
signature_V_PBCPH builder_setAttributionTag = nullptr;
signature_V_PBPDPV builder_setDataCallback = nullptr;
signature_V_PBPEPV builder_setErrorCallback = nullptr;
signature_I_PB builder_delete = nullptr;
signature_F_PS stream_getFormat = nullptr;
signature_I_PSPVIL stream_read = nullptr;
signature_I_PSCPVIL stream_write = nullptr;
signature_I_PSTPTL stream_waitForStateChange = nullptr;
signature_I_PSKPLPL stream_getTimestamp = nullptr;
signature_I_PS stream_close = nullptr;
signature_I_PS stream_getChannelCount = nullptr;
signature_I_PS stream_getDeviceId = nullptr;
signature_I_PS stream_getBufferSize = nullptr;
signature_I_PS stream_getBufferCapacity = nullptr;
signature_I_PS stream_getFramesPerBurst = nullptr;
signature_I_PS stream_getState = nullptr;
signature_I_PS stream_getPerformanceMode = nullptr;
signature_I_PS stream_getSampleRate = nullptr;
signature_I_PS stream_getSharingMode = nullptr;
signature_I_PS stream_getXRunCount = nullptr;
signature_I_PSI stream_setBufferSize = nullptr;
signature_I_PS stream_requestStart = nullptr;
signature_I_PS stream_requestPause = nullptr;
signature_I_PS stream_requestFlush = nullptr;
signature_I_PS stream_requestStop = nullptr;
signature_L_PS stream_getFramesRead = nullptr;
signature_L_PS stream_getFramesWritten = nullptr;
signature_CPH_I convertResultToText = nullptr;
signature_I_PS stream_getUsage = nullptr;
signature_I_PS stream_getContentType = nullptr;
signature_I_PS stream_getInputPreset = nullptr;
signature_I_PS stream_getSessionId = nullptr;
signature_U_PS stream_getChannelMask = nullptr;
private:
AAudioLoader() {}
~AAudioLoader();
// Load function pointers for specific signatures.
signature_I_PPB load_I_PPB(const char *name);
signature_CPH_I load_CPH_I(const char *name);
signature_V_PBI load_V_PBI(const char *name);
signature_V_PBCPH load_V_PBCPH(const char *name);
signature_V_PBPDPV load_V_PBPDPV(const char *name);
signature_V_PBPEPV load_V_PBPEPV(const char *name);
signature_I_PB load_I_PB(const char *name);
signature_I_PBPPS load_I_PBPPS(const char *name);
signature_I_PS load_I_PS(const char *name);
signature_L_PS load_L_PS(const char *name);
signature_F_PS load_F_PS(const char *name);
signature_B_PS load_B_PS(const char *name);
signature_I_PSI load_I_PSI(const char *name);
signature_I_PSPVIL load_I_PSPVIL(const char *name);
signature_I_PSCPVIL load_I_PSCPVIL(const char *name);
signature_I_PSTPTL load_I_PSTPTL(const char *name);
signature_I_PSKPLPL load_I_PSKPLPL(const char *name);
signature_V_PBU load_V_PBU(const char *name);
signature_U_PS load_U_PS(const char *name);
void *mLibHandle = nullptr;
};
} // namespace oboe
#endif //OBOE_AAUDIO_LOADER_H_

View file

@ -0,0 +1,729 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <stdint.h>
#include <stdlib.h>
#include "oboe_aaudio_AAudioLoader_android.h"
#include "oboe_aaudio_AudioStreamAAudio_android.h"
#include "oboe_common_AudioClock_android.h"
#include "oboe_common_OboeDebug_android.h"
#include "oboe_oboe_Utilities_android.h"
#include "oboe_aaudio_AAudioExtensions_android.h"
#ifdef __ANDROID__
#include <sys/system_properties.h>
#include "oboe_common_QuirksManager_android.h"
#endif
#ifndef OBOE_FIX_FORCE_STARTING_TO_STARTED
// Workaround state problems in AAudio
// TODO Which versions does this occur in? Verify fixed in Q.
#define OBOE_FIX_FORCE_STARTING_TO_STARTED 1
#endif // OBOE_FIX_FORCE_STARTING_TO_STARTED
using namespace oboe;
AAudioLoader *AudioStreamAAudio::mLibLoader = nullptr;
// 'C' wrapper for the data callback method
static aaudio_data_callback_result_t oboe_aaudio_data_callback_proc(
AAudioStream *stream,
void *userData,
void *audioData,
int32_t numFrames) {
AudioStreamAAudio *oboeStream = reinterpret_cast<AudioStreamAAudio*>(userData);
if (oboeStream != nullptr) {
return static_cast<aaudio_data_callback_result_t>(
oboeStream->callOnAudioReady(stream, audioData, numFrames));
} else {
return static_cast<aaudio_data_callback_result_t>(DataCallbackResult::Stop);
}
}
// This runs in its own thread.
// Only one of these threads will be launched from internalErrorCallback().
// It calls app error callbacks from a static function in case the stream gets deleted.
static void oboe_aaudio_error_thread_proc(AudioStreamAAudio *oboeStream,
Result error) {
LOGD("%s(,%d) - entering >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", __func__, error);
AudioStreamErrorCallback *errorCallback = oboeStream->getErrorCallback();
if (errorCallback == nullptr) return; // should be impossible
bool isErrorHandled = errorCallback->onError(oboeStream, error);
if (!isErrorHandled) {
oboeStream->requestStop();
errorCallback->onErrorBeforeClose(oboeStream, error);
oboeStream->close();
// Warning, oboeStream may get deleted by this callback.
errorCallback->onErrorAfterClose(oboeStream, error);
}
LOGD("%s() - exiting <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", __func__);
}
// This runs in its own thread.
// Only one of these threads will be launched from internalErrorCallback().
// Prevents deletion of the stream if the app is using AudioStreamBuilder::openSharedStream()
static void oboe_aaudio_error_thread_proc_shared(std::shared_ptr<AudioStream> sharedStream,
Result error) {
AudioStreamAAudio *oboeStream = reinterpret_cast<AudioStreamAAudio*>(sharedStream.get());
oboe_aaudio_error_thread_proc(oboeStream, error);
}
namespace oboe {
/*
* Create a stream that uses Oboe Audio API.
*/
AudioStreamAAudio::AudioStreamAAudio(const AudioStreamBuilder &builder)
: AudioStream(builder)
, mAAudioStream(nullptr) {
mCallbackThreadEnabled.store(false);
mLibLoader = AAudioLoader::getInstance();
}
bool AudioStreamAAudio::isSupported() {
mLibLoader = AAudioLoader::getInstance();
int openResult = mLibLoader->open();
return openResult == 0;
}
// Static method for the error callback.
// We use a method so we can access protected methods on the stream.
// Launch a thread to handle the error.
// That other thread can safely stop, close and delete the stream.
void AudioStreamAAudio::internalErrorCallback(
AAudioStream *stream,
void *userData,
aaudio_result_t error) {
oboe::Result oboeResult = static_cast<Result>(error);
AudioStreamAAudio *oboeStream = reinterpret_cast<AudioStreamAAudio*>(userData);
// Coerce the error code if needed to workaround a regression in RQ1A that caused
// the wrong code to be passed when headsets plugged in. See b/173928197.
if (OboeGlobals::areWorkaroundsEnabled()
&& getSdkVersion() == __ANDROID_API_R__
&& oboeResult == oboe::Result::ErrorTimeout) {
oboeResult = oboe::Result::ErrorDisconnected;
LOGD("%s() ErrorTimeout changed to ErrorDisconnected to fix b/173928197", __func__);
}
oboeStream->mErrorCallbackResult = oboeResult;
// Prevents deletion of the stream if the app is using AudioStreamBuilder::openStream(shared_ptr)
std::shared_ptr<AudioStream> sharedStream = oboeStream->lockWeakThis();
// These checks should be enough because we assume that the stream close()
// will join() any active callback threads and will not allow new callbacks.
if (oboeStream->wasErrorCallbackCalled()) { // block extra error callbacks
LOGE("%s() multiple error callbacks called!", __func__);
} else if (stream != oboeStream->getUnderlyingStream()) {
LOGW("%s() stream already closed or closing", __func__); // might happen if there are bugs
} else if (sharedStream) {
// Handle error on a separate thread using shared pointer.
std::thread t(oboe_aaudio_error_thread_proc_shared, sharedStream, oboeResult);
t.detach();
} else {
// Handle error on a separate thread.
std::thread t(oboe_aaudio_error_thread_proc, oboeStream, oboeResult);
t.detach();
}
}
void AudioStreamAAudio::logUnsupportedAttributes() {
int sdkVersion = getSdkVersion();
// These attributes are not supported pre Android "P"
if (sdkVersion < __ANDROID_API_P__) {
if (mUsage != Usage::Media) {
LOGW("Usage [AudioStreamBuilder::setUsage()] "
"is not supported on AAudio streams running on pre-Android P versions.");
}
if (mContentType != ContentType::Music) {
LOGW("ContentType [AudioStreamBuilder::setContentType()] "
"is not supported on AAudio streams running on pre-Android P versions.");
}
if (mSessionId != SessionId::None) {
LOGW("SessionId [AudioStreamBuilder::setSessionId()] "
"is not supported on AAudio streams running on pre-Android P versions.");
}
}
}
Result AudioStreamAAudio::open() {
Result result = Result::OK;
if (mAAudioStream != nullptr) {
return Result::ErrorInvalidState;
}
result = AudioStream::open();
if (result != Result::OK) {
return result;
}
AAudioStreamBuilder *aaudioBuilder;
result = static_cast<Result>(mLibLoader->createStreamBuilder(&aaudioBuilder));
if (result != Result::OK) {
return result;
}
// Do not set INPUT capacity below 4096 because that prevents us from getting a FAST track
// when using the Legacy data path.
// If the app requests > 4096 then we allow it but we are less likely to get LowLatency.
// See internal bug b/80308183 for more details.
// Fixed in Q but let's still clip the capacity because high input capacity
// does not increase latency.
int32_t capacity = mBufferCapacityInFrames;
constexpr int kCapacityRequiredForFastLegacyTrack = 4096; // matches value in AudioFinger
if (OboeGlobals::areWorkaroundsEnabled()
&& mDirection == oboe::Direction::Input
&& capacity != oboe::Unspecified
&& capacity < kCapacityRequiredForFastLegacyTrack
&& mPerformanceMode == oboe::PerformanceMode::LowLatency) {
capacity = kCapacityRequiredForFastLegacyTrack;
LOGD("AudioStreamAAudio.open() capacity changed from %d to %d for lower latency",
static_cast<int>(mBufferCapacityInFrames), capacity);
}
mLibLoader->builder_setBufferCapacityInFrames(aaudioBuilder, capacity);
// Channel mask was added in SC_V2. Given the corresponding channel count of selected channel
// mask may be different from selected channel count, the last set value will be respected.
// If channel count is set after channel mask, the previously set channel mask will be cleared.
// If channel mask is set after channel count, the channel count will be automatically
// calculated from selected channel mask. In that case, only set channel mask when the API
// is available and the channel mask is specified.
if (mLibLoader->builder_setChannelMask != nullptr && mChannelMask != ChannelMask::Unspecified) {
mLibLoader->builder_setChannelMask(aaudioBuilder,
static_cast<aaudio_channel_mask_t>(mChannelMask));
} else {
mLibLoader->builder_setChannelCount(aaudioBuilder, mChannelCount);
}
mLibLoader->builder_setDeviceId(aaudioBuilder, mDeviceId);
mLibLoader->builder_setDirection(aaudioBuilder, static_cast<aaudio_direction_t>(mDirection));
mLibLoader->builder_setFormat(aaudioBuilder, static_cast<aaudio_format_t>(mFormat));
mLibLoader->builder_setSampleRate(aaudioBuilder, mSampleRate);
mLibLoader->builder_setSharingMode(aaudioBuilder,
static_cast<aaudio_sharing_mode_t>(mSharingMode));
mLibLoader->builder_setPerformanceMode(aaudioBuilder,
static_cast<aaudio_performance_mode_t>(mPerformanceMode));
// These were added in P so we have to check for the function pointer.
if (mLibLoader->builder_setUsage != nullptr) {
mLibLoader->builder_setUsage(aaudioBuilder,
static_cast<aaudio_usage_t>(mUsage));
}
if (mLibLoader->builder_setContentType != nullptr) {
mLibLoader->builder_setContentType(aaudioBuilder,
static_cast<aaudio_content_type_t>(mContentType));
}
if (mLibLoader->builder_setInputPreset != nullptr) {
aaudio_input_preset_t inputPreset = mInputPreset;
if (getSdkVersion() <= __ANDROID_API_P__ && inputPreset == InputPreset::VoicePerformance) {
LOGD("InputPreset::VoicePerformance not supported before Q. Using VoiceRecognition.");
inputPreset = InputPreset::VoiceRecognition; // most similar preset
}
mLibLoader->builder_setInputPreset(aaudioBuilder,
static_cast<aaudio_input_preset_t>(inputPreset));
}
if (mLibLoader->builder_setSessionId != nullptr) {
mLibLoader->builder_setSessionId(aaudioBuilder,
static_cast<aaudio_session_id_t>(mSessionId));
}
// These were added in S so we have to check for the function pointer.
if (mLibLoader->builder_setPackageName != nullptr && !mPackageName.empty()) {
mLibLoader->builder_setPackageName(aaudioBuilder,
mPackageName.c_str());
}
if (mLibLoader->builder_setAttributionTag != nullptr && !mAttributionTag.empty()) {
mLibLoader->builder_setAttributionTag(aaudioBuilder,
mAttributionTag.c_str());
}
if (isDataCallbackSpecified()) {
mLibLoader->builder_setDataCallback(aaudioBuilder, oboe_aaudio_data_callback_proc, this);
mLibLoader->builder_setFramesPerDataCallback(aaudioBuilder, getFramesPerDataCallback());
if (!isErrorCallbackSpecified()) {
// The app did not specify a callback so we should specify
// our own so the stream gets closed and stopped.
mErrorCallback = &mDefaultErrorCallback;
}
mLibLoader->builder_setErrorCallback(aaudioBuilder, internalErrorCallback, this);
}
// Else if the data callback is not being used then the write method will return an error
// and the app can stop and close the stream.
// ============= OPEN THE STREAM ================
{
AAudioStream *stream = nullptr;
result = static_cast<Result>(mLibLoader->builder_openStream(aaudioBuilder, &stream));
mAAudioStream.store(stream);
}
if (result != Result::OK) {
// Warn developer because ErrorInternal is not very informative.
if (result == Result::ErrorInternal && mDirection == Direction::Input) {
LOGW("AudioStreamAAudio.open() may have failed due to lack of "
"audio recording permission.");
}
goto error2;
}
// Query and cache the stream properties
mDeviceId = mLibLoader->stream_getDeviceId(mAAudioStream);
mChannelCount = mLibLoader->stream_getChannelCount(mAAudioStream);
mSampleRate = mLibLoader->stream_getSampleRate(mAAudioStream);
mFormat = static_cast<AudioFormat>(mLibLoader->stream_getFormat(mAAudioStream));
mSharingMode = static_cast<SharingMode>(mLibLoader->stream_getSharingMode(mAAudioStream));
mPerformanceMode = static_cast<PerformanceMode>(
mLibLoader->stream_getPerformanceMode(mAAudioStream));
mBufferCapacityInFrames = mLibLoader->stream_getBufferCapacity(mAAudioStream);
mBufferSizeInFrames = mLibLoader->stream_getBufferSize(mAAudioStream);
mFramesPerBurst = mLibLoader->stream_getFramesPerBurst(mAAudioStream);
// These were added in P so we have to check for the function pointer.
if (mLibLoader->stream_getUsage != nullptr) {
mUsage = static_cast<Usage>(mLibLoader->stream_getUsage(mAAudioStream));
}
if (mLibLoader->stream_getContentType != nullptr) {
mContentType = static_cast<ContentType>(mLibLoader->stream_getContentType(mAAudioStream));
}
if (mLibLoader->stream_getInputPreset != nullptr) {
mInputPreset = static_cast<InputPreset>(mLibLoader->stream_getInputPreset(mAAudioStream));
}
if (mLibLoader->stream_getSessionId != nullptr) {
mSessionId = static_cast<SessionId>(mLibLoader->stream_getSessionId(mAAudioStream));
} else {
mSessionId = SessionId::None;
}
if (mLibLoader->stream_getChannelMask != nullptr) {
mChannelMask = static_cast<ChannelMask>(mLibLoader->stream_getChannelMask(mAAudioStream));
}
LOGD("AudioStreamAAudio.open() format=%d, sampleRate=%d, capacity = %d",
static_cast<int>(mFormat), static_cast<int>(mSampleRate),
static_cast<int>(mBufferCapacityInFrames));
calculateDefaultDelayBeforeCloseMillis();
error2:
mLibLoader->builder_delete(aaudioBuilder);
LOGD("AudioStreamAAudio.open: AAudioStream_Open() returned %s",
mLibLoader->convertResultToText(static_cast<aaudio_result_t>(result)));
return result;
}
Result AudioStreamAAudio::close() {
// Prevent two threads from closing the stream at the same time and crashing.
// This could occur, for example, if an application called close() at the same
// time that an onError callback was being executed because of a disconnect.
std::lock_guard<std::mutex> lock(mLock);
AudioStream::close();
AAudioStream *stream = nullptr;
{
// Wait for any methods using mAAudioStream to finish.
std::unique_lock<std::shared_mutex> lock2(mAAudioStreamLock);
// Closing will delete *mAAudioStream so we need to null out the pointer atomically.
stream = mAAudioStream.exchange(nullptr);
}
if (stream != nullptr) {
if (OboeGlobals::areWorkaroundsEnabled()) {
// Make sure we are really stopped. Do it under mLock
// so another thread cannot call requestStart() right before the close.
requestStop_l(stream);
sleepBeforeClose();
}
return static_cast<Result>(mLibLoader->stream_close(stream));
} else {
return Result::ErrorClosed;
}
}
static void oboe_stop_thread_proc(AudioStream *oboeStream) {
if (oboeStream != nullptr) {
oboeStream->requestStop();
}
}
void AudioStreamAAudio::launchStopThread() {
// Prevent multiple stop threads from being launched.
if (mStopThreadAllowed.exchange(false)) {
// Stop this stream on a separate thread
std::thread t(oboe_stop_thread_proc, this);
t.detach();
}
}
DataCallbackResult AudioStreamAAudio::callOnAudioReady(AAudioStream * /*stream*/,
void *audioData,
int32_t numFrames) {
DataCallbackResult result = fireDataCallback(audioData, numFrames);
if (result == DataCallbackResult::Continue) {
return result;
} else {
if (result == DataCallbackResult::Stop) {
LOGD("Oboe callback returned DataCallbackResult::Stop");
} else {
LOGE("Oboe callback returned unexpected value = %d", result);
}
// Returning Stop caused various problems before S. See #1230
if (OboeGlobals::areWorkaroundsEnabled() && getSdkVersion() <= __ANDROID_API_R__) {
launchStopThread();
return DataCallbackResult::Continue;
} else {
return DataCallbackResult::Stop; // OK >= API_S
}
}
}
Result AudioStreamAAudio::requestStart() {
std::lock_guard<std::mutex> lock(mLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
// Avoid state machine errors in O_MR1.
if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
if (state == StreamState::Starting || state == StreamState::Started) {
// WARNING: On P, AAudio is returning ErrorInvalidState for Output and OK for Input.
return Result::OK;
}
}
if (isDataCallbackSpecified()) {
setDataCallbackEnabled(true);
}
mStopThreadAllowed = true;
return static_cast<Result>(mLibLoader->stream_requestStart(stream));
} else {
return Result::ErrorClosed;
}
}
Result AudioStreamAAudio::requestPause() {
std::lock_guard<std::mutex> lock(mLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
// Avoid state machine errors in O_MR1.
if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
if (state == StreamState::Pausing || state == StreamState::Paused) {
return Result::OK;
}
}
return static_cast<Result>(mLibLoader->stream_requestPause(stream));
} else {
return Result::ErrorClosed;
}
}
Result AudioStreamAAudio::requestFlush() {
std::lock_guard<std::mutex> lock(mLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
// Avoid state machine errors in O_MR1.
if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
if (state == StreamState::Flushing || state == StreamState::Flushed) {
return Result::OK;
}
}
return static_cast<Result>(mLibLoader->stream_requestFlush(stream));
} else {
return Result::ErrorClosed;
}
}
Result AudioStreamAAudio::requestStop() {
std::lock_guard<std::mutex> lock(mLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
return requestStop_l(stream);
} else {
return Result::ErrorClosed;
}
}
// Call under mLock
Result AudioStreamAAudio::requestStop_l(AAudioStream *stream) {
// Avoid state machine errors in O_MR1.
if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
StreamState state = static_cast<StreamState>(mLibLoader->stream_getState(stream));
if (state == StreamState::Stopping || state == StreamState::Stopped) {
return Result::OK;
}
}
return static_cast<Result>(mLibLoader->stream_requestStop(stream));
}
ResultWithValue<int32_t> AudioStreamAAudio::write(const void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
int32_t result = mLibLoader->stream_write(mAAudioStream, buffer,
numFrames, timeoutNanoseconds);
return ResultWithValue<int32_t>::createBasedOnSign(result);
} else {
return ResultWithValue<int32_t>(Result::ErrorClosed);
}
}
ResultWithValue<int32_t> AudioStreamAAudio::read(void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
int32_t result = mLibLoader->stream_read(mAAudioStream, buffer,
numFrames, timeoutNanoseconds);
return ResultWithValue<int32_t>::createBasedOnSign(result);
} else {
return ResultWithValue<int32_t>(Result::ErrorClosed);
}
}
// AAudioStream_waitForStateChange() can crash if it is waiting on a stream and that stream
// is closed from another thread. We do not want to lock the stream for the duration of the call.
// So we call AAudioStream_waitForStateChange() with a timeout of zero so that it will not block.
// Then we can do our own sleep with the lock unlocked.
Result AudioStreamAAudio::waitForStateChange(StreamState currentState,
StreamState *nextState,
int64_t timeoutNanoseconds) {
Result oboeResult = Result::ErrorTimeout;
int64_t sleepTimeNanos = 20 * kNanosPerMillisecond; // arbitrary
aaudio_stream_state_t currentAAudioState = static_cast<aaudio_stream_state_t>(currentState);
aaudio_result_t result = AAUDIO_OK;
int64_t timeLeftNanos = timeoutNanoseconds;
mLock.lock();
while (true) {
// Do we still have an AAudio stream? If not then stream must have been closed.
AAudioStream *stream = mAAudioStream.load();
if (stream == nullptr) {
if (nextState != nullptr) {
*nextState = StreamState::Closed;
}
oboeResult = Result::ErrorClosed;
break;
}
// Update and query state change with no blocking.
aaudio_stream_state_t aaudioNextState;
result = mLibLoader->stream_waitForStateChange(
mAAudioStream,
currentAAudioState,
&aaudioNextState,
0); // timeout=0 for non-blocking
// AAudio will return AAUDIO_ERROR_TIMEOUT if timeout=0 and the state does not change.
if (result != AAUDIO_OK && result != AAUDIO_ERROR_TIMEOUT) {
oboeResult = static_cast<Result>(result);
break;
}
#if OBOE_FIX_FORCE_STARTING_TO_STARTED
if (OboeGlobals::areWorkaroundsEnabled()
&& aaudioNextState == static_cast<aaudio_stream_state_t >(StreamState::Starting)) {
aaudioNextState = static_cast<aaudio_stream_state_t >(StreamState::Started);
}
#endif // OBOE_FIX_FORCE_STARTING_TO_STARTED
if (nextState != nullptr) {
*nextState = static_cast<StreamState>(aaudioNextState);
}
if (currentAAudioState != aaudioNextState) { // state changed?
oboeResult = Result::OK;
break;
}
// Did we timeout or did user ask for non-blocking?
if (timeLeftNanos <= 0) {
break;
}
// No change yet so sleep.
mLock.unlock(); // Don't sleep while locked.
if (sleepTimeNanos > timeLeftNanos) {
sleepTimeNanos = timeLeftNanos; // last little bit
}
AudioClock::sleepForNanos(sleepTimeNanos);
timeLeftNanos -= sleepTimeNanos;
mLock.lock();
}
mLock.unlock();
return oboeResult;
}
ResultWithValue<int32_t> AudioStreamAAudio::setBufferSizeInFrames(int32_t requestedFrames) {
int32_t adjustedFrames = requestedFrames;
if (adjustedFrames > mBufferCapacityInFrames) {
adjustedFrames = mBufferCapacityInFrames;
}
// This calls getBufferSize() so avoid recursive lock.
adjustedFrames = QuirksManager::getInstance().clipBufferSize(*this, adjustedFrames);
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
int32_t newBufferSize = mLibLoader->stream_setBufferSize(mAAudioStream, adjustedFrames);
// Cache the result if it's valid
if (newBufferSize > 0) mBufferSizeInFrames = newBufferSize;
return ResultWithValue<int32_t>::createBasedOnSign(newBufferSize);
} else {
return ResultWithValue<int32_t>(Result::ErrorClosed);
}
}
StreamState AudioStreamAAudio::getState() {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
aaudio_stream_state_t aaudioState = mLibLoader->stream_getState(stream);
#if OBOE_FIX_FORCE_STARTING_TO_STARTED
if (OboeGlobals::areWorkaroundsEnabled()
&& aaudioState == AAUDIO_STREAM_STATE_STARTING) {
aaudioState = AAUDIO_STREAM_STATE_STARTED;
}
#endif // OBOE_FIX_FORCE_STARTING_TO_STARTED
return static_cast<StreamState>(aaudioState);
} else {
return StreamState::Closed;
}
}
int32_t AudioStreamAAudio::getBufferSizeInFrames() {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
mBufferSizeInFrames = mLibLoader->stream_getBufferSize(stream);
}
return mBufferSizeInFrames;
}
void AudioStreamAAudio::updateFramesRead() {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
// Set to 1 for debugging race condition #1180 with mAAudioStream.
// See also DEBUG_CLOSE_RACE in OboeTester.
// This was left in the code so that we could test the fix again easily in the future.
// We could not trigger the race condition without adding these get calls and the sleeps.
#define DEBUG_CLOSE_RACE 0
#if DEBUG_CLOSE_RACE
// This is used when testing race conditions with close().
// See DEBUG_CLOSE_RACE in OboeTester
AudioClock::sleepForNanos(400 * kNanosPerMillisecond);
#endif // DEBUG_CLOSE_RACE
if (stream != nullptr) {
mFramesRead = mLibLoader->stream_getFramesRead(stream);
}
}
void AudioStreamAAudio::updateFramesWritten() {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
mFramesWritten = mLibLoader->stream_getFramesWritten(stream);
}
}
ResultWithValue<int32_t> AudioStreamAAudio::getXRunCount() {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
return ResultWithValue<int32_t>::createBasedOnSign(mLibLoader->stream_getXRunCount(stream));
} else {
return ResultWithValue<int32_t>(Result::ErrorNull);
}
}
Result AudioStreamAAudio::getTimestamp(clockid_t clockId,
int64_t *framePosition,
int64_t *timeNanoseconds) {
if (getState() != StreamState::Started) {
return Result::ErrorInvalidState;
}
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
return static_cast<Result>(mLibLoader->stream_getTimestamp(stream, clockId,
framePosition, timeNanoseconds));
} else {
return Result::ErrorNull;
}
}
ResultWithValue<double> AudioStreamAAudio::calculateLatencyMillis() {
// Get the time that a known audio frame was presented.
int64_t hardwareFrameIndex;
int64_t hardwareFrameHardwareTime;
auto result = getTimestamp(CLOCK_MONOTONIC,
&hardwareFrameIndex,
&hardwareFrameHardwareTime);
if (result != oboe::Result::OK) {
return ResultWithValue<double>(static_cast<Result>(result));
}
// Get counter closest to the app.
bool isOutput = (getDirection() == oboe::Direction::Output);
int64_t appFrameIndex = isOutput ? getFramesWritten() : getFramesRead();
// Assume that the next frame will be processed at the current time
using namespace std::chrono;
int64_t appFrameAppTime =
duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count();
// Calculate the number of frames between app and hardware
int64_t frameIndexDelta = appFrameIndex - hardwareFrameIndex;
// Calculate the time which the next frame will be or was presented
int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / getSampleRate();
int64_t appFrameHardwareTime = hardwareFrameHardwareTime + frameTimeDelta;
// The current latency is the difference in time between when the current frame is at
// the app and when it is at the hardware.
double latencyNanos = static_cast<double>(isOutput
? (appFrameHardwareTime - appFrameAppTime) // hardware is later
: (appFrameAppTime - appFrameHardwareTime)); // hardware is earlier
double latencyMillis = latencyNanos / kNanosPerMillisecond;
return ResultWithValue<double>(latencyMillis);
}
bool AudioStreamAAudio::isMMapUsed() {
std::shared_lock<std::shared_mutex> lock(mAAudioStreamLock);
AAudioStream *stream = mAAudioStream.load();
if (stream != nullptr) {
return AAudioExtensions::getInstance().isMMapUsed(stream);
} else {
return false;
}
}
} // namespace oboe

View file

@ -0,0 +1,142 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_STREAM_AAUDIO_H_
#define OBOE_STREAM_AAUDIO_H_
#include <atomic>
#include <shared_mutex>
#include <mutex>
#include <thread>
#include "oboe_oboe_AudioStreamBuilder_android.h"
#include "oboe_oboe_AudioStream_android.h"
#include "oboe_oboe_Definitions_android.h"
#include "oboe_aaudio_AAudioLoader_android.h"
namespace oboe {
/**
* Implementation of OboeStream that uses AAudio.
*
* Do not create this class directly.
* Use an OboeStreamBuilder to create one.
*/
class AudioStreamAAudio : public AudioStream {
public:
AudioStreamAAudio();
explicit AudioStreamAAudio(const AudioStreamBuilder &builder);
virtual ~AudioStreamAAudio() = default;
/**
*
* @return true if AAudio is supported on this device.
*/
static bool isSupported();
// These functions override methods in AudioStream.
// See AudioStream for documentation.
Result open() override;
Result close() override;
Result requestStart() override;
Result requestPause() override;
Result requestFlush() override;
Result requestStop() override;
ResultWithValue<int32_t> write(const void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) override;
ResultWithValue<int32_t> read(void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) override;
ResultWithValue<int32_t> setBufferSizeInFrames(int32_t requestedFrames) override;
int32_t getBufferSizeInFrames() override;
ResultWithValue<int32_t> getXRunCount() override;
bool isXRunCountSupported() const override { return true; }
ResultWithValue<double> calculateLatencyMillis() override;
Result waitForStateChange(StreamState currentState,
StreamState *nextState,
int64_t timeoutNanoseconds) override;
Result getTimestamp(clockid_t clockId,
int64_t *framePosition,
int64_t *timeNanoseconds) override;
StreamState getState() override;
AudioApi getAudioApi() const override {
return AudioApi::AAudio;
}
DataCallbackResult callOnAudioReady(AAudioStream *stream,
void *audioData,
int32_t numFrames);
bool isMMapUsed();
protected:
static void internalErrorCallback(
AAudioStream *stream,
void *userData,
aaudio_result_t error);
void *getUnderlyingStream() const override {
return mAAudioStream.load();
}
void updateFramesRead() override;
void updateFramesWritten() override;
void logUnsupportedAttributes();
private:
// Must call under mLock. And stream must NOT be nullptr.
Result requestStop_l(AAudioStream *stream);
/**
* Launch a thread that will stop the stream.
*/
void launchStopThread();
public:
int32_t getMDelayBeforeCloseMillis() const;
void setDelayBeforeCloseMillis(int32_t mDelayBeforeCloseMillis);
private:
std::atomic<bool> mCallbackThreadEnabled;
std::atomic<bool> mStopThreadAllowed{false};
// pointer to the underlying 'C' AAudio stream, valid if open, null if closed
std::atomic<AAudioStream *> mAAudioStream{nullptr};
std::shared_mutex mAAudioStreamLock; // to protect mAAudioStream while closing
static AAudioLoader *mLibLoader;
// We may not use this but it is so small that it is not worth allocating dynamically.
AudioStreamErrorCallback mDefaultErrorCallback;
};
} // namespace oboe
#endif // OBOE_STREAM_AAUDIO_H_

View file

@ -0,0 +1,75 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_AUDIO_CLOCK_H
#define OBOE_AUDIO_CLOCK_H
#include <sys/types.h>
#include <ctime>
#include "oboe_oboe_Definitions_android.h"
namespace oboe {
// TODO: Move this class into the public headers because it is useful when calculating stream latency
class AudioClock {
public:
static int64_t getNanoseconds(clockid_t clockId = CLOCK_MONOTONIC) {
struct timespec time;
int result = clock_gettime(clockId, &time);
if (result < 0) {
return result;
}
return (time.tv_sec * kNanosPerSecond) + time.tv_nsec;
}
/**
* Sleep until the specified time.
*
* @param nanoTime time to wake up
* @param clockId CLOCK_MONOTONIC is default
* @return 0 or a negative error, eg. -EINTR
*/
static int sleepUntilNanoTime(int64_t nanoTime, clockid_t clockId = CLOCK_MONOTONIC) {
struct timespec time;
time.tv_sec = nanoTime / kNanosPerSecond;
time.tv_nsec = nanoTime - (time.tv_sec * kNanosPerSecond);
return 0 - clock_nanosleep(clockId, TIMER_ABSTIME, &time, NULL);
}
/**
* Sleep for the specified number of nanoseconds in real-time.
* Return immediately with 0 if a negative nanoseconds is specified.
*
* @param nanoseconds time to sleep
* @param clockId CLOCK_REALTIME is default
* @return 0 or a negative error, eg. -EINTR
*/
static int sleepForNanos(int64_t nanoseconds, clockid_t clockId = CLOCK_REALTIME) {
if (nanoseconds > 0) {
struct timespec time;
time.tv_sec = nanoseconds / kNanosPerSecond;
time.tv_nsec = nanoseconds - (time.tv_sec * kNanosPerSecond);
return 0 - clock_nanosleep(clockId, 0, &time, NULL);
}
return 0;
}
};
} // namespace oboe
#endif //OBOE_AUDIO_CLOCK_H

View file

@ -0,0 +1,38 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "oboe_common_AudioSourceCaller_android.h"
using namespace oboe;
using namespace flowgraph;
int32_t AudioSourceCaller::onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) {
AudioStreamDataCallback *callback = mStream->getDataCallback();
int32_t result = 0;
int32_t numFrames = numBytes / mStream->getBytesPerFrame();
if (callback != nullptr) {
DataCallbackResult callbackResult = callback->onAudioReady(mStream, buffer, numFrames);
// onAudioReady() does not return the number of bytes processed so we have to assume all.
result = (callbackResult == DataCallbackResult::Continue)
? numBytes
: -1;
} else {
auto readResult = mStream->read(buffer, numFrames, mTimeoutNanos);
if (!readResult) return (int32_t) readResult.error();
result = readResult.value() * mStream->getBytesPerFrame();
}
return result;
}

View file

@ -0,0 +1,83 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_AUDIO_SOURCE_CALLER_H
#define OBOE_AUDIO_SOURCE_CALLER_H
#include "oboe_common_OboeDebug_android.h"
#include "oboe_oboe_Oboe_android.h"
#include "oboe_flowgraph_FlowGraphNode_android.h"
#include "oboe_common_FixedBlockReader_android.h"
namespace oboe {
class AudioStreamCallback;
class AudioStream;
/**
* For output streams that use a callback, call the application for more data.
* For input streams that do not use a callback, read from the stream.
*/
class AudioSourceCaller : public flowgraph::FlowGraphSource, public FixedBlockProcessor {
public:
AudioSourceCaller(int32_t channelCount, int32_t framesPerCallback, int32_t bytesPerSample)
: FlowGraphSource(channelCount)
, mBlockReader(*this) {
mBlockReader.open(channelCount * framesPerCallback * bytesPerSample);
}
/**
* Set the stream to use as a source of data.
* @param stream
*/
void setStream(oboe::AudioStream *stream) {
mStream = stream;
}
oboe::AudioStream *getStream() {
return mStream;
}
/**
* Timeout value to use when calling audioStream->read().
* @param timeoutNanos Zero for no timeout or time in nanoseconds.
*/
void setTimeoutNanos(int64_t timeoutNanos) {
mTimeoutNanos = timeoutNanos;
}
int64_t getTimeoutNanos() const {
return mTimeoutNanos;
}
/**
* Called internally for block size adaptation.
* @param buffer
* @param numBytes
* @return
*/
int32_t onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) override;
protected:
oboe::AudioStream *mStream = nullptr;
int64_t mTimeoutNanos = 0;
FixedBlockReader mBlockReader;
};
}
#endif //OBOE_AUDIO_SOURCE_CALLER_H

View file

@ -0,0 +1,224 @@
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include "oboe_aaudio_AAudioExtensions_android.h"
#include "oboe_aaudio_AudioStreamAAudio_android.h"
#include "oboe_common_FilterAudioStream_android.h"
#include "oboe_common_OboeDebug_android.h"
#include "oboe_oboe_Oboe_android.h"
#include "oboe_oboe_AudioStreamBuilder_android.h"
#include "oboe_opensles_AudioInputStreamOpenSLES_android.h"
#include "oboe_opensles_AudioOutputStreamOpenSLES_android.h"
#include "oboe_opensles_AudioStreamOpenSLES_android.h"
#include "oboe_common_QuirksManager_android.h"
bool oboe::OboeGlobals::mWorkaroundsEnabled = true;
namespace oboe {
/**
* The following default values are used when oboe does not have any better way of determining the optimal values
* for an audio stream. This can happen when:
*
* - Client is creating a stream on API < 26 (OpenSLES) but has not supplied the optimal sample
* rate and/or frames per burst
* - Client is creating a stream on API 16 (OpenSLES) where AudioManager.PROPERTY_OUTPUT_* values
* are not available
*/
int32_t DefaultStreamValues::SampleRate = 48000; // Common rate for mobile audio and video
int32_t DefaultStreamValues::FramesPerBurst = 192; // 4 msec at 48000 Hz
int32_t DefaultStreamValues::ChannelCount = 2; // Stereo
constexpr int kBufferSizeInBurstsForLowLatencyStreams = 2;
#ifndef OBOE_ENABLE_AAUDIO
// Set OBOE_ENABLE_AAUDIO to 0 if you want to disable the AAudio API.
// This might be useful if you want to force all the unit tests to use OpenSL ES.
#define OBOE_ENABLE_AAUDIO 1
#endif
bool AudioStreamBuilder::isAAudioSupported() {
return AudioStreamAAudio::isSupported() && OBOE_ENABLE_AAUDIO;
}
bool AudioStreamBuilder::isAAudioRecommended() {
// See https://github.com/google/oboe/issues/40,
// AAudio may not be stable on Android O, depending on how it is used.
// To be safe, use AAudio only on O_MR1 and above.
return (getSdkVersion() >= __ANDROID_API_O_MR1__) && isAAudioSupported();
}
AudioStream *AudioStreamBuilder::build() {
AudioStream *stream = nullptr;
if (isAAudioRecommended() && mAudioApi != AudioApi::OpenSLES) {
stream = new AudioStreamAAudio(*this);
} else if (isAAudioSupported() && mAudioApi == AudioApi::AAudio) {
stream = new AudioStreamAAudio(*this);
LOGE("Creating AAudio stream on 8.0 because it was specified. This is error prone.");
} else {
if (getDirection() == oboe::Direction::Output) {
stream = new AudioOutputStreamOpenSLES(*this);
} else if (getDirection() == oboe::Direction::Input) {
stream = new AudioInputStreamOpenSLES(*this);
}
}
return stream;
}
bool AudioStreamBuilder::isCompatible(AudioStreamBase &other) {
return (getSampleRate() == oboe::Unspecified || getSampleRate() == other.getSampleRate())
&& (getFormat() == (AudioFormat)oboe::Unspecified || getFormat() == other.getFormat())
&& (getFramesPerDataCallback() == oboe::Unspecified || getFramesPerDataCallback() == other.getFramesPerDataCallback())
&& (getChannelCount() == oboe::Unspecified || getChannelCount() == other.getChannelCount());
}
Result AudioStreamBuilder::openStream(AudioStream **streamPP) {
auto result = isValidConfig();
if (result != Result::OK) {
LOGW("%s() invalid config %d", __func__, result);
return result;
}
LOGI("%s() %s -------- %s --------",
__func__, getDirection() == Direction::Input ? "INPUT" : "OUTPUT", getVersionText());
if (streamPP == nullptr) {
return Result::ErrorNull;
}
*streamPP = nullptr;
AudioStream *streamP = nullptr;
// Maybe make a FilterInputStream.
AudioStreamBuilder childBuilder(*this);
// Check need for conversion and modify childBuilder for optimal stream.
bool conversionNeeded = QuirksManager::getInstance().isConversionNeeded(*this, childBuilder);
// Do we need to make a child stream and convert.
if (conversionNeeded) {
AudioStream *tempStream;
result = childBuilder.openStream(&tempStream);
if (result != Result::OK) {
return result;
}
if (isCompatible(*tempStream)) {
// The child stream would work as the requested stream so we can just use it directly.
*streamPP = tempStream;
return result;
} else {
AudioStreamBuilder parentBuilder = *this;
// Build a stream that is as close as possible to the childStream.
if (getFormat() == oboe::AudioFormat::Unspecified) {
parentBuilder.setFormat(tempStream->getFormat());
}
if (getChannelCount() == oboe::Unspecified) {
parentBuilder.setChannelCount(tempStream->getChannelCount());
}
if (getSampleRate() == oboe::Unspecified) {
parentBuilder.setSampleRate(tempStream->getSampleRate());
}
if (getFramesPerDataCallback() == oboe::Unspecified) {
parentBuilder.setFramesPerCallback(tempStream->getFramesPerDataCallback());
}
// Use childStream in a FilterAudioStream.
LOGI("%s() create a FilterAudioStream for data conversion.", __func__);
FilterAudioStream *filterStream = new FilterAudioStream(parentBuilder, tempStream);
result = filterStream->configureFlowGraph();
if (result != Result::OK) {
filterStream->close();
delete filterStream;
// Just open streamP the old way.
} else {
streamP = static_cast<AudioStream *>(filterStream);
}
}
}
if (streamP == nullptr) {
streamP = build();
if (streamP == nullptr) {
return Result::ErrorNull;
}
}
// If MMAP has a problem in this case then disable it temporarily.
bool wasMMapOriginallyEnabled = AAudioExtensions::getInstance().isMMapEnabled();
bool wasMMapTemporarilyDisabled = false;
if (wasMMapOriginallyEnabled) {
bool isMMapSafe = QuirksManager::getInstance().isMMapSafe(childBuilder);
if (!isMMapSafe) {
AAudioExtensions::getInstance().setMMapEnabled(false);
wasMMapTemporarilyDisabled = true;
}
}
result = streamP->open();
if (wasMMapTemporarilyDisabled) {
AAudioExtensions::getInstance().setMMapEnabled(wasMMapOriginallyEnabled); // restore original
}
if (result == Result::OK) {
int32_t optimalBufferSize = -1;
// Use a reasonable default buffer size.
if (streamP->getDirection() == Direction::Input) {
// For input, small size does not improve latency because the stream is usually
// run close to empty. And a low size can result in XRuns so always use the maximum.
optimalBufferSize = streamP->getBufferCapacityInFrames();
} else if (streamP->getPerformanceMode() == PerformanceMode::LowLatency
&& streamP->getDirection() == Direction::Output) { // Output check is redundant.
optimalBufferSize = streamP->getFramesPerBurst() *
kBufferSizeInBurstsForLowLatencyStreams;
}
if (optimalBufferSize >= 0) {
auto setBufferResult = streamP->setBufferSizeInFrames(optimalBufferSize);
if (!setBufferResult) {
LOGW("Failed to setBufferSizeInFrames(%d). Error was %s",
optimalBufferSize,
convertToText(setBufferResult.error()));
}
}
*streamPP = streamP;
} else {
delete streamP;
}
return result;
}
Result AudioStreamBuilder::openManagedStream(oboe::ManagedStream &stream) {
stream.reset();
AudioStream *streamptr;
auto result = openStream(&streamptr);
stream.reset(streamptr);
return result;
}
Result AudioStreamBuilder::openStream(std::shared_ptr<AudioStream> &sharedStream) {
sharedStream.reset();
AudioStream *streamptr;
auto result = openStream(&streamptr);
if (result == Result::OK) {
sharedStream.reset(streamptr);
// Save a weak_ptr in the stream for use with callbacks.
streamptr->setWeakThis(sharedStream);
}
return result;
}
} // namespace oboe

View file

@ -0,0 +1,208 @@
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include <pthread.h>
#include <thread>
#include "oboe_oboe_AudioStream_android.h"
#include "oboe_common_OboeDebug_android.h"
#include "oboe_common_AudioClock_android.h"
#include "oboe_oboe_Utilities_android.h"
namespace oboe {
/*
* AudioStream
*/
AudioStream::AudioStream(const AudioStreamBuilder &builder)
: AudioStreamBase(builder) {
}
Result AudioStream::close() {
// Update local counters so they can be read after the close.
updateFramesWritten();
updateFramesRead();
return Result::OK;
}
// Call this from fireDataCallback() if you want to monitor CPU scheduler.
void AudioStream::checkScheduler() {
int scheduler = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK; // for current thread
if (scheduler != mPreviousScheduler) {
LOGD("AudioStream::%s() scheduler = %s", __func__,
((scheduler == SCHED_FIFO) ? "SCHED_FIFO" :
((scheduler == SCHED_OTHER) ? "SCHED_OTHER" :
((scheduler == SCHED_RR) ? "SCHED_RR" : "UNKNOWN")))
);
mPreviousScheduler = scheduler;
}
}
DataCallbackResult AudioStream::fireDataCallback(void *audioData, int32_t numFrames) {
if (!isDataCallbackEnabled()) {
LOGW("AudioStream::%s() called with data callback disabled!", __func__);
return DataCallbackResult::Stop; // Should not be getting called
}
DataCallbackResult result;
if (mDataCallback) {
result = mDataCallback->onAudioReady(this, audioData, numFrames);
} else {
result = onDefaultCallback(audioData, numFrames);
}
// On Oreo, we might get called after returning stop.
// So block that here.
setDataCallbackEnabled(result == DataCallbackResult::Continue);
return result;
}
Result AudioStream::waitForStateTransition(StreamState startingState,
StreamState endingState,
int64_t timeoutNanoseconds)
{
StreamState state;
{
std::lock_guard<std::mutex> lock(mLock);
state = getState();
if (state == StreamState::Closed) {
return Result::ErrorClosed;
} else if (state == StreamState::Disconnected) {
return Result::ErrorDisconnected;
}
}
StreamState nextState = state;
// TODO Should this be a while()?!
if (state == startingState && state != endingState) {
Result result = waitForStateChange(state, &nextState, timeoutNanoseconds);
if (result != Result::OK) {
return result;
}
}
if (nextState != endingState) {
return Result::ErrorInvalidState;
} else {
return Result::OK;
}
}
Result AudioStream::start(int64_t timeoutNanoseconds)
{
Result result = requestStart();
if (result != Result::OK) return result;
if (timeoutNanoseconds <= 0) return result;
return waitForStateTransition(StreamState::Starting,
StreamState::Started, timeoutNanoseconds);
}
Result AudioStream::pause(int64_t timeoutNanoseconds)
{
Result result = requestPause();
if (result != Result::OK) return result;
if (timeoutNanoseconds <= 0) return result;
return waitForStateTransition(StreamState::Pausing,
StreamState::Paused, timeoutNanoseconds);
}
Result AudioStream::flush(int64_t timeoutNanoseconds)
{
Result result = requestFlush();
if (result != Result::OK) return result;
if (timeoutNanoseconds <= 0) return result;
return waitForStateTransition(StreamState::Flushing,
StreamState::Flushed, timeoutNanoseconds);
}
Result AudioStream::stop(int64_t timeoutNanoseconds)
{
Result result = requestStop();
if (result != Result::OK) return result;
if (timeoutNanoseconds <= 0) return result;
return waitForStateTransition(StreamState::Stopping,
StreamState::Stopped, timeoutNanoseconds);
}
int32_t AudioStream::getBytesPerSample() const {
return convertFormatToSizeInBytes(mFormat);
}
int64_t AudioStream::getFramesRead() {
updateFramesRead();
return mFramesRead;
}
int64_t AudioStream::getFramesWritten() {
updateFramesWritten();
return mFramesWritten;
}
ResultWithValue<int32_t> AudioStream::getAvailableFrames() {
int64_t readCounter = getFramesRead();
if (readCounter < 0) return ResultWithValue<int32_t>::createBasedOnSign(readCounter);
int64_t writeCounter = getFramesWritten();
if (writeCounter < 0) return ResultWithValue<int32_t>::createBasedOnSign(writeCounter);
int32_t framesAvailable = writeCounter - readCounter;
return ResultWithValue<int32_t>(framesAvailable);
}
ResultWithValue<int32_t> AudioStream::waitForAvailableFrames(int32_t numFrames,
int64_t timeoutNanoseconds) {
if (numFrames == 0) return Result::OK;
if (numFrames < 0) return Result::ErrorOutOfRange;
int64_t framesAvailable = 0;
int64_t burstInNanos = getFramesPerBurst() * kNanosPerSecond / getSampleRate();
bool ready = false;
int64_t deadline = AudioClock::getNanoseconds() + timeoutNanoseconds;
do {
ResultWithValue<int32_t> result = getAvailableFrames();
if (!result) return result;
framesAvailable = result.value();
ready = (framesAvailable >= numFrames);
if (!ready) {
int64_t now = AudioClock::getNanoseconds();
if (now > deadline) break;
AudioClock::sleepForNanos(burstInNanos);
}
} while (!ready);
return (!ready)
? ResultWithValue<int32_t>(Result::ErrorTimeout)
: ResultWithValue<int32_t>(framesAvailable);
}
ResultWithValue<FrameTimestamp> AudioStream::getTimestamp(clockid_t clockId) {
FrameTimestamp frame;
Result result = getTimestamp(clockId, &frame.position, &frame.timestamp);
if (result == Result::OK){
return ResultWithValue<FrameTimestamp>(frame);
} else {
return ResultWithValue<FrameTimestamp>(static_cast<Result>(result));
}
}
void AudioStream::calculateDefaultDelayBeforeCloseMillis() {
// Calculate delay time before close based on burst duration.
// Start with a burst duration then add 1 msec as a safety margin.
mDelayBeforeCloseMillis = std::max(kMinDelayBeforeCloseMillis,
1 + ((mFramesPerBurst * 1000) / getSampleRate()));
LOGD("calculateDefaultDelayBeforeCloseMillis() default = %d",
static_cast<int>(mDelayBeforeCloseMillis));
}
} // namespace oboe

View file

@ -0,0 +1,267 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "oboe_common_OboeDebug_android.h"
#include "oboe_common_DataConversionFlowGraph_android.h"
#include "oboe_common_SourceFloatCaller_android.h"
#include "oboe_common_SourceI16Caller_android.h"
#include "oboe_common_SourceI24Caller_android.h"
#include "oboe_common_SourceI32Caller_android.h"
#include "oboe_flowgraph_ClipToRange_android.h"
#include "oboe_flowgraph_MonoToMultiConverter_android.h"
#include "oboe_flowgraph_MultiToMonoConverter_android.h"
#include "oboe_flowgraph_RampLinear_android.h"
#include "oboe_flowgraph_SinkFloat_android.h"
#include "oboe_flowgraph_SinkI16_android.h"
#include "oboe_flowgraph_SinkI24_android.h"
#include "oboe_flowgraph_SinkI32_android.h"
#include "oboe_flowgraph_SourceFloat_android.h"
#include "oboe_flowgraph_SourceI16_android.h"
#include "oboe_flowgraph_SourceI24_android.h"
#include "oboe_flowgraph_SourceI32_android.h"
#include "oboe_flowgraph_SampleRateConverter_android.h"
using namespace oboe;
using namespace flowgraph;
using namespace resampler;
void DataConversionFlowGraph::setSource(const void *buffer, int32_t numFrames) {
mSource->setData(buffer, numFrames);
}
static MultiChannelResampler::Quality convertOboeSRQualityToMCR(SampleRateConversionQuality quality) {
switch (quality) {
case SampleRateConversionQuality::Fastest:
return MultiChannelResampler::Quality::Fastest;
case SampleRateConversionQuality::Low:
return MultiChannelResampler::Quality::Low;
default:
case SampleRateConversionQuality::Medium:
return MultiChannelResampler::Quality::Medium;
case SampleRateConversionQuality::High:
return MultiChannelResampler::Quality::High;
case SampleRateConversionQuality::Best:
return MultiChannelResampler::Quality::Best;
}
}
// Chain together multiple processors.
// Callback Output
// Use SourceCaller that calls original app callback from the flowgraph.
// The child callback from FilteredAudioStream read()s from the flowgraph.
// Callback Input
// Child callback from FilteredAudioStream writes()s to the flowgraph.
// The output of the flowgraph goes through a BlockWriter to the app callback.
// Blocking Write
// Write buffer is set on an AudioSource.
// Data is pulled through the graph and written to the child stream.
// Blocking Read
// Reads in a loop from the flowgraph Sink to fill the read buffer.
// A SourceCaller then does a blocking read from the child Stream.
//
Result DataConversionFlowGraph::configure(AudioStream *sourceStream, AudioStream *sinkStream) {
FlowGraphPortFloatOutput *lastOutput = nullptr;
bool isOutput = sourceStream->getDirection() == Direction::Output;
bool isInput = !isOutput;
mFilterStream = isOutput ? sourceStream : sinkStream;
AudioFormat sourceFormat = sourceStream->getFormat();
int32_t sourceChannelCount = sourceStream->getChannelCount();
int32_t sourceSampleRate = sourceStream->getSampleRate();
int32_t sourceFramesPerCallback = sourceStream->getFramesPerDataCallback();
AudioFormat sinkFormat = sinkStream->getFormat();
int32_t sinkChannelCount = sinkStream->getChannelCount();
int32_t sinkSampleRate = sinkStream->getSampleRate();
int32_t sinkFramesPerCallback = sinkStream->getFramesPerDataCallback();
LOGI("%s() flowgraph converts channels: %d to %d, format: %d to %d"
", rate: %d to %d, cbsize: %d to %d, qual = %d",
__func__,
sourceChannelCount, sinkChannelCount,
sourceFormat, sinkFormat,
sourceSampleRate, sinkSampleRate,
sourceFramesPerCallback, sinkFramesPerCallback,
sourceStream->getSampleRateConversionQuality());
// Source
// IF OUTPUT and using a callback then call back to the app using a SourceCaller.
// OR IF INPUT and NOT using a callback then read from the child stream using a SourceCaller.
bool isDataCallbackSpecified = sourceStream->isDataCallbackSpecified();
if ((isDataCallbackSpecified && isOutput)
|| (!isDataCallbackSpecified && isInput)) {
int32_t actualSourceFramesPerCallback = (sourceFramesPerCallback == kUnspecified)
? sourceStream->getFramesPerBurst()
: sourceFramesPerCallback;
switch (sourceFormat) {
case AudioFormat::Float:
mSourceCaller = std::make_unique<SourceFloatCaller>(sourceChannelCount,
actualSourceFramesPerCallback);
break;
case AudioFormat::I16:
mSourceCaller = std::make_unique<SourceI16Caller>(sourceChannelCount,
actualSourceFramesPerCallback);
break;
case AudioFormat::I24:
mSourceCaller = std::make_unique<SourceI24Caller>(sourceChannelCount,
actualSourceFramesPerCallback);
break;
case AudioFormat::I32:
mSourceCaller = std::make_unique<SourceI32Caller>(sourceChannelCount,
actualSourceFramesPerCallback);
break;
default:
LOGE("%s() Unsupported source caller format = %d", __func__, sourceFormat);
return Result::ErrorIllegalArgument;
}
mSourceCaller->setStream(sourceStream);
lastOutput = &mSourceCaller->output;
} else {
// IF OUTPUT and NOT using a callback then write to the child stream using a BlockWriter.
// OR IF INPUT and using a callback then write to the app using a BlockWriter.
switch (sourceFormat) {
case AudioFormat::Float:
mSource = std::make_unique<SourceFloat>(sourceChannelCount);
break;
case AudioFormat::I16:
mSource = std::make_unique<SourceI16>(sourceChannelCount);
break;
case AudioFormat::I24:
mSource = std::make_unique<SourceI24>(sourceChannelCount);
break;
case AudioFormat::I32:
mSource = std::make_unique<SourceI32>(sourceChannelCount);
break;
default:
LOGE("%s() Unsupported source format = %d", __func__, sourceFormat);
return Result::ErrorIllegalArgument;
}
if (isInput) {
int32_t actualSinkFramesPerCallback = (sinkFramesPerCallback == kUnspecified)
? sinkStream->getFramesPerBurst()
: sinkFramesPerCallback;
// The BlockWriter is after the Sink so use the SinkStream size.
mBlockWriter.open(actualSinkFramesPerCallback * sinkStream->getBytesPerFrame());
mAppBuffer = std::make_unique<uint8_t[]>(
kDefaultBufferSize * sinkStream->getBytesPerFrame());
}
lastOutput = &mSource->output;
}
// If we are going to reduce the number of channels then do it before the
// sample rate converter.
if (sourceChannelCount > sinkChannelCount) {
if (sinkChannelCount == 1) {
mMultiToMonoConverter = std::make_unique<MultiToMonoConverter>(sourceChannelCount);
lastOutput->connect(&mMultiToMonoConverter->input);
lastOutput = &mMultiToMonoConverter->output;
} else {
mChannelCountConverter = std::make_unique<ChannelCountConverter>(
sourceChannelCount,
sinkChannelCount);
lastOutput->connect(&mChannelCountConverter->input);
lastOutput = &mChannelCountConverter->output;
}
}
// Sample Rate conversion
if (sourceSampleRate != sinkSampleRate) {
// Create a resampler to do the math.
mResampler.reset(MultiChannelResampler::make(lastOutput->getSamplesPerFrame(),
sourceSampleRate,
sinkSampleRate,
convertOboeSRQualityToMCR(
sourceStream->getSampleRateConversionQuality())));
// Make a flowgraph node that uses the resampler.
mRateConverter = std::make_unique<SampleRateConverter>(lastOutput->getSamplesPerFrame(),
*mResampler.get());
lastOutput->connect(&mRateConverter->input);
lastOutput = &mRateConverter->output;
}
// Expand the number of channels if required.
if (sourceChannelCount < sinkChannelCount) {
if (sourceChannelCount == 1) {
mMonoToMultiConverter = std::make_unique<MonoToMultiConverter>(sinkChannelCount);
lastOutput->connect(&mMonoToMultiConverter->input);
lastOutput = &mMonoToMultiConverter->output;
} else {
mChannelCountConverter = std::make_unique<ChannelCountConverter>(
sourceChannelCount,
sinkChannelCount);
lastOutput->connect(&mChannelCountConverter->input);
lastOutput = &mChannelCountConverter->output;
}
}
// Sink
switch (sinkFormat) {
case AudioFormat::Float:
mSink = std::make_unique<SinkFloat>(sinkChannelCount);
break;
case AudioFormat::I16:
mSink = std::make_unique<SinkI16>(sinkChannelCount);
break;
case AudioFormat::I24:
mSink = std::make_unique<SinkI24>(sinkChannelCount);
break;
case AudioFormat::I32:
mSink = std::make_unique<SinkI32>(sinkChannelCount);
break;
default:
LOGE("%s() Unsupported sink format = %d", __func__, sinkFormat);
return Result::ErrorIllegalArgument;;
}
lastOutput->connect(&mSink->input);
return Result::OK;
}
int32_t DataConversionFlowGraph::read(void *buffer, int32_t numFrames, int64_t timeoutNanos) {
if (mSourceCaller) {
mSourceCaller->setTimeoutNanos(timeoutNanos);
}
int32_t numRead = mSink->read(buffer, numFrames);
return numRead;
}
// This is similar to pushing data through the flowgraph.
int32_t DataConversionFlowGraph::write(void *inputBuffer, int32_t numFrames) {
// Put the data from the input at the head of the flowgraph.
mSource->setData(inputBuffer, numFrames);
while (true) {
// Pull and read some data in app format into a small buffer.
int32_t framesRead = mSink->read(mAppBuffer.get(), flowgraph::kDefaultBufferSize);
if (framesRead <= 0) break;
// Write to a block adapter, which will call the destination whenever it has enough data.
int32_t bytesRead = mBlockWriter.write(mAppBuffer.get(),
framesRead * mFilterStream->getBytesPerFrame());
if (bytesRead < 0) return bytesRead; // TODO review
}
return numFrames;
}
int32_t DataConversionFlowGraph::onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) {
int32_t numFrames = numBytes / mFilterStream->getBytesPerFrame();
mCallbackResult = mFilterStream->getDataCallback()->onAudioReady(mFilterStream, buffer, numFrames);
// TODO handle STOP from callback, process data remaining in the block adapter
return numBytes;
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_OBOE_FLOW_GRAPH_H
#define OBOE_OBOE_FLOW_GRAPH_H
#include <memory>
#include <stdint.h>
#include <sys/types.h>
#include "oboe_flowgraph_ChannelCountConverter_android.h"
#include "oboe_flowgraph_MonoToMultiConverter_android.h"
#include "oboe_flowgraph_MultiToMonoConverter_android.h"
#include "oboe_flowgraph_SampleRateConverter_android.h"
#include "oboe_oboe_Definitions_android.h"
#include "oboe_common_AudioSourceCaller_android.h"
#include "oboe_common_FixedBlockWriter_android.h"
namespace oboe {
class AudioStream;
class AudioSourceCaller;
/**
* Convert PCM channels, format and sample rate for optimal latency.
*/
class DataConversionFlowGraph : public FixedBlockProcessor {
public:
DataConversionFlowGraph()
: mBlockWriter(*this) {}
void setSource(const void *buffer, int32_t numFrames);
/** Connect several modules together to convert from source to sink.
* This should only be called once for each instance.
*
* @param sourceFormat
* @param sourceChannelCount
* @param sinkFormat
* @param sinkChannelCount
* @return
*/
oboe::Result configure(oboe::AudioStream *sourceStream, oboe::AudioStream *sinkStream);
int32_t read(void *buffer, int32_t numFrames, int64_t timeoutNanos);
int32_t write(void *buffer, int32_t numFrames);
int32_t onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) override;
DataCallbackResult getDataCallbackResult() {
return mCallbackResult;
}
private:
std::unique_ptr<flowgraph::FlowGraphSourceBuffered> mSource;
std::unique_ptr<AudioSourceCaller> mSourceCaller;
std::unique_ptr<flowgraph::MonoToMultiConverter> mMonoToMultiConverter;
std::unique_ptr<flowgraph::MultiToMonoConverter> mMultiToMonoConverter;
std::unique_ptr<flowgraph::ChannelCountConverter> mChannelCountConverter;
std::unique_ptr<resampler::MultiChannelResampler> mResampler;
std::unique_ptr<flowgraph::SampleRateConverter> mRateConverter;
std::unique_ptr<flowgraph::FlowGraphSink> mSink;
FixedBlockWriter mBlockWriter;
DataCallbackResult mCallbackResult = DataCallbackResult::Continue;
AudioStream *mFilterStream = nullptr;
std::unique_ptr<uint8_t[]> mAppBuffer;
};
}
#endif //OBOE_OBOE_FLOW_GRAPH_H

View file

@ -0,0 +1,106 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "oboe_common_OboeDebug_android.h"
#include "oboe_common_FilterAudioStream_android.h"
using namespace oboe;
using namespace flowgraph;
// Output callback uses FixedBlockReader::read()
// <= SourceFloatCaller::onProcess()
// <=== DataConversionFlowGraph::read()
// <== FilterAudioStream::onAudioReady()
//
// Output blocking uses no block adapter because AAudio can accept
// writes of any size. It uses DataConversionFlowGraph::read() <== FilterAudioStream::write() <= app
//
// Input callback uses FixedBlockWriter::write()
// <= DataConversionFlowGraph::write()
// <= FilterAudioStream::onAudioReady()
//
// Input blocking uses FixedBlockReader::read() // TODO may not need block adapter
// <= SourceFloatCaller::onProcess()
// <=== SinkFloat::read()
// <= DataConversionFlowGraph::read()
// <== FilterAudioStream::read()
// <= app
Result FilterAudioStream::configureFlowGraph() {
mFlowGraph = std::make_unique<DataConversionFlowGraph>();
bool isOutput = getDirection() == Direction::Output;
AudioStream *sourceStream = isOutput ? this : mChildStream.get();
AudioStream *sinkStream = isOutput ? mChildStream.get() : this;
mRateScaler = ((double) getSampleRate()) / mChildStream->getSampleRate();
return mFlowGraph->configure(sourceStream, sinkStream);
}
// Put the data to be written at the source end of the flowgraph.
// Then read (pull) the data from the flowgraph and write it to the
// child stream.
ResultWithValue<int32_t> FilterAudioStream::write(const void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) {
int32_t framesWritten = 0;
mFlowGraph->setSource(buffer, numFrames);
while (true) {
int32_t numRead = mFlowGraph->read(mBlockingBuffer.get(),
getFramesPerBurst(),
timeoutNanoseconds);
if (numRead < 0) {
return ResultWithValue<int32_t>::createBasedOnSign(numRead);
}
if (numRead == 0) {
break; // finished processing the source buffer
}
auto writeResult = mChildStream->write(mBlockingBuffer.get(),
numRead,
timeoutNanoseconds);
if (!writeResult) {
return writeResult;
}
framesWritten += writeResult.value();
}
return ResultWithValue<int32_t>::createBasedOnSign(framesWritten);
}
// Read (pull) the data we want from the sink end of the flowgraph.
// The necessary data will be read from the child stream using a flowgraph callback.
ResultWithValue<int32_t> FilterAudioStream::read(void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) {
int32_t framesRead = mFlowGraph->read(buffer, numFrames, timeoutNanoseconds);
return ResultWithValue<int32_t>::createBasedOnSign(framesRead);
}
DataCallbackResult FilterAudioStream::onAudioReady(AudioStream *oboeStream,
void *audioData,
int32_t numFrames) {
int32_t framesProcessed;
if (oboeStream->getDirection() == Direction::Output) {
framesProcessed = mFlowGraph->read(audioData, numFrames, 0 /* timeout */);
} else {
framesProcessed = mFlowGraph->write(audioData, numFrames);
}
return (framesProcessed < numFrames)
? DataCallbackResult::Stop
: mFlowGraph->getDataCallbackResult();
}

View file

@ -0,0 +1,223 @@
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OBOE_FILTER_AUDIO_STREAM_H
#define OBOE_FILTER_AUDIO_STREAM_H
#include <memory>
#include "oboe_oboe_AudioStream_android.h"
#include "oboe_common_DataConversionFlowGraph_android.h"
namespace oboe {
/**
* An AudioStream that wraps another AudioStream and provides audio data conversion.
* Operations may include channel conversion, data format conversion and/or sample rate conversion.
*/
class FilterAudioStream : public AudioStream, AudioStreamCallback {
public:
/**
* Construct an `AudioStream` using the given `AudioStreamBuilder` and a child AudioStream.
*
* This should only be called internally by AudioStreamBuilder.
* Ownership of childStream will be passed to this object.
*
* @param builder containing all the stream's attributes
*/
FilterAudioStream(const AudioStreamBuilder &builder, AudioStream *childStream)
: AudioStream(builder)
, mChildStream(childStream) {
// Intercept the callback if used.
if (builder.isErrorCallbackSpecified()) {
mErrorCallback = mChildStream->swapErrorCallback(this);
}
if (builder.isDataCallbackSpecified()) {
mDataCallback = mChildStream->swapDataCallback(this);
} else {
const int size = childStream->getFramesPerBurst() * childStream->getBytesPerFrame();
mBlockingBuffer = std::make_unique<uint8_t[]>(size);
}
// Copy parameters that may not match builder.
mBufferCapacityInFrames = mChildStream->getBufferCapacityInFrames();
mPerformanceMode = mChildStream->getPerformanceMode();
mInputPreset = mChildStream->getInputPreset();
mFramesPerBurst = mChildStream->getFramesPerBurst();
mDeviceId = mChildStream->getDeviceId();
}
virtual ~FilterAudioStream() = default;
AudioStream *getChildStream() const {
return mChildStream.get();
}
Result configureFlowGraph();
// Close child and parent.
Result close() override {
const Result result1 = mChildStream->close();
const Result result2 = AudioStream::close();
return (result1 != Result::OK ? result1 : result2);
}
/**
* Start the stream asynchronously. Returns immediately (does not block). Equivalent to calling
* `start(0)`.
*/
Result requestStart() override {
return mChildStream->requestStart();
}
/**
* Pause the stream asynchronously. Returns immediately (does not block). Equivalent to calling
* `pause(0)`.
*/
Result requestPause() override {
return mChildStream->requestPause();
}
/**
* Flush the stream asynchronously. Returns immediately (does not block). Equivalent to calling
* `flush(0)`.
*/
Result requestFlush() override {
return mChildStream->requestFlush();
}
/**
* Stop the stream asynchronously. Returns immediately (does not block). Equivalent to calling
* `stop(0)`.
*/
Result requestStop() override {
return mChildStream->requestStop();
}
ResultWithValue<int32_t> read(void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) override;
ResultWithValue<int32_t> write(const void *buffer,
int32_t numFrames,
int64_t timeoutNanoseconds) override;
StreamState getState() override {
return mChildStream->getState();
}
Result waitForStateChange(
StreamState inputState,
StreamState *nextState,
int64_t timeoutNanoseconds) override {
return mChildStream->waitForStateChange(inputState, nextState, timeoutNanoseconds);
}
bool isXRunCountSupported() const override {
return mChildStream->isXRunCountSupported();
}
AudioApi getAudioApi() const override {
return mChildStream->getAudioApi();
}
void updateFramesWritten() override {
// TODO for output, just count local writes?
mFramesWritten = static_cast<int64_t>(mChildStream->getFramesWritten() * mRateScaler);
}
void updateFramesRead() override {
// TODO for input, just count local reads?
mFramesRead = static_cast<int64_t>(mChildStream->getFramesRead() * mRateScaler);
}
void *getUnderlyingStream() const override {
return mChildStream->getUnderlyingStream();
}
ResultWithValue<int32_t> setBufferSizeInFrames(int32_t requestedFrames) override {
return mChildStream->setBufferSizeInFrames(requestedFrames);
}
int32_t getBufferSizeInFrames() override {
mBufferSizeInFrames = mChildStream->getBufferSizeInFrames();
return mBufferSizeInFrames;
}
ResultWithValue<int32_t> getXRunCount() override {
return mChildStream->getXRunCount();
}
ResultWithValue<double> calculateLatencyMillis() override {
// This will automatically include the latency of the flowgraph?
return mChildStream->calculateLatencyMillis();
}
Result getTimestamp(clockid_t clockId,
int64_t *framePosition,
int64_t *timeNanoseconds) override {
int64_t childPosition = 0;
Result result = mChildStream->getTimestamp(clockId, &childPosition, timeNanoseconds);
// It is OK if framePosition is null.
if (framePosition) {
*framePosition = childPosition * mRateScaler;
}
return result;
}
DataCallbackResult onAudioReady(AudioStream *oboeStream,
void *audioData,
int32_t numFrames) override;
bool onError(AudioStream * /*audioStream*/, Result error) override {
if (mErrorCallback != nullptr) {
return mErrorCallback->onError(this, error);
}
return false;
}
void onErrorBeforeClose(AudioStream * /*oboeStream*/, Result error) override {
if (mErrorCallback != nullptr) {
mErrorCallback->onErrorBeforeClose(this, error);
}
}
void onErrorAfterClose(AudioStream * /*oboeStream*/, Result error) override {
// Close this parent stream because the callback will only close the child.
AudioStream::close();
if (mErrorCallback != nullptr) {
mErrorCallback->onErrorAfterClose(this, error);
}
}
/**
* @return last result passed from an error callback
*/
oboe::Result getLastErrorCallbackResult() const override {
return mChildStream->getLastErrorCallbackResult();
}
private:
std::unique_ptr<AudioStream> mChildStream; // this stream wraps the child stream
std::unique_ptr<DataConversionFlowGraph> mFlowGraph; // for converting data
std::unique_ptr<uint8_t[]> mBlockingBuffer; // temp buffer for write()
double mRateScaler = 1.0; // ratio parent/child sample rates
};
} // oboe
#endif //OBOE_FILTER_AUDIO_STREAM_H

View file

@ -0,0 +1,38 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include "oboe_common_FixedBlockAdapter_android.h"
FixedBlockAdapter::~FixedBlockAdapter() {
}
int32_t FixedBlockAdapter::open(int32_t bytesPerFixedBlock)
{
mSize = bytesPerFixedBlock;
mStorage = std::make_unique<uint8_t[]>(bytesPerFixedBlock);
mPosition = 0;
return 0;
}
int32_t FixedBlockAdapter::close()
{
mStorage.reset(nullptr);
mSize = 0;
mPosition = 0;
return 0;
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AAUDIO_FIXED_BLOCK_ADAPTER_H
#define AAUDIO_FIXED_BLOCK_ADAPTER_H
#include <memory>
#include <stdint.h>
#include <sys/types.h>
/**
* Interface for a class that needs fixed-size blocks.
*/
class FixedBlockProcessor {
public:
virtual ~FixedBlockProcessor() = default;
/**
*
* @param buffer Pointer to first byte of data.
* @param numBytes This will be a fixed size specified in FixedBlockAdapter::open().
* @return Number of bytes processed or a negative error code.
*/
virtual int32_t onProcessFixedBlock(uint8_t *buffer, int32_t numBytes) = 0;
};
/**
* Base class for a variable-to-fixed-size block adapter.
*/
class FixedBlockAdapter
{
public:
FixedBlockAdapter(FixedBlockProcessor &fixedBlockProcessor)
: mFixedBlockProcessor(fixedBlockProcessor) {}
virtual ~FixedBlockAdapter();
/**
* Allocate internal resources needed for buffering data.
*/
virtual int32_t open(int32_t bytesPerFixedBlock);
/**
* Free internal resources.
*/
int32_t close();
protected:
FixedBlockProcessor &mFixedBlockProcessor;
std::unique_ptr<uint8_t[]> mStorage; // Store data here while assembling buffers.
int32_t mSize = 0; // Size in bytes of the fixed size buffer.
int32_t mPosition = 0; // Offset of the last byte read or written.
};
#endif /* AAUDIO_FIXED_BLOCK_ADAPTER_H */

View file

@ -0,0 +1,73 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <memory.h>
#include "oboe_common_FixedBlockAdapter_android.h"
#include "oboe_common_FixedBlockReader_android.h"
FixedBlockReader::FixedBlockReader(FixedBlockProcessor &fixedBlockProcessor)
: FixedBlockAdapter(fixedBlockProcessor) {
mPosition = mSize;
}
int32_t FixedBlockReader::open(int32_t bytesPerFixedBlock) {
int32_t result = FixedBlockAdapter::open(bytesPerFixedBlock);
mPosition = 0;
mValid = 0;
return result;
}
int32_t FixedBlockReader::readFromStorage(uint8_t *buffer, int32_t numBytes) {
int32_t bytesToRead = numBytes;
int32_t dataAvailable = mValid - mPosition;
if (bytesToRead > dataAvailable) {
bytesToRead = dataAvailable;
}
memcpy(buffer, mStorage.get() + mPosition, bytesToRead);
mPosition += bytesToRead;
return bytesToRead;
}
int32_t FixedBlockReader::read(uint8_t *buffer, int32_t numBytes) {
int32_t bytesRead;
int32_t bytesLeft = numBytes;
while(bytesLeft > 0) {
if (mPosition < mValid) {
// Use up bytes currently in storage.
bytesRead = readFromStorage(buffer, bytesLeft);
buffer += bytesRead;
bytesLeft -= bytesRead;
} else if (bytesLeft >= mSize) {
// Nothing in storage. Read through if enough for a complete block.
bytesRead = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
if (bytesRead < 0) return bytesRead;
buffer += bytesRead;
bytesLeft -= bytesRead;
} else {
// Just need a partial block so we have to reload storage.
bytesRead = mFixedBlockProcessor.onProcessFixedBlock(mStorage.get(), mSize);
if (bytesRead < 0) return bytesRead;
mPosition = 0;
mValid = bytesRead;
if (bytesRead == 0) break;
}
}
return numBytes - bytesLeft;
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AAUDIO_FIXED_BLOCK_READER_H
#define AAUDIO_FIXED_BLOCK_READER_H
#include <stdint.h>
#include "oboe_common_FixedBlockAdapter_android.h"
/**
* Read from a fixed-size block to a variable sized block.
*
* This can be used to convert a pull data flow from fixed sized buffers to variable sized buffers.
* An example would be an audio output callback that reads from the app.
*/
class FixedBlockReader : public FixedBlockAdapter
{
public:
FixedBlockReader(FixedBlockProcessor &fixedBlockProcessor);
virtual ~FixedBlockReader() = default;
int32_t open(int32_t bytesPerFixedBlock) override;
/**
* Read into a variable sized block.
*
* Note that if the fixed-sized blocks must be aligned, then the variable-sized blocks
* must have the same alignment.
* For example, if the fixed-size blocks must be a multiple of 8, then the variable-sized
* blocks must also be a multiple of 8.
*
* @param buffer
* @param numBytes
* @return Number of bytes read or a negative error code.
*/
int32_t read(uint8_t *buffer, int32_t numBytes);
private:
int32_t readFromStorage(uint8_t *buffer, int32_t numBytes);
int32_t mValid = 0; // Number of valid bytes in mStorage.
};
#endif /* AAUDIO_FIXED_BLOCK_READER_H */

View file

@ -0,0 +1,73 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <memory.h>
#include "oboe_common_FixedBlockAdapter_android.h"
#include "oboe_common_FixedBlockWriter_android.h"
FixedBlockWriter::FixedBlockWriter(FixedBlockProcessor &fixedBlockProcessor)
: FixedBlockAdapter(fixedBlockProcessor) {}
int32_t FixedBlockWriter::writeToStorage(uint8_t *buffer, int32_t numBytes) {
int32_t bytesToStore = numBytes;
int32_t roomAvailable = mSize - mPosition;
if (bytesToStore > roomAvailable) {
bytesToStore = roomAvailable;
}
memcpy(mStorage.get() + mPosition, buffer, bytesToStore);
mPosition += bytesToStore;
return bytesToStore;
}
int32_t FixedBlockWriter::write(uint8_t *buffer, int32_t numBytes) {
int32_t bytesLeft = numBytes;
// If we already have data in storage then add to it.
if (mPosition > 0) {
int32_t bytesWritten = writeToStorage(buffer, bytesLeft);
buffer += bytesWritten;
bytesLeft -= bytesWritten;
// If storage full then flush it out
if (mPosition == mSize) {
bytesWritten = mFixedBlockProcessor.onProcessFixedBlock(mStorage.get(), mSize);
if (bytesWritten < 0) return bytesWritten;
mPosition = 0;
if (bytesWritten < mSize) {
// Only some of the data was written! This should not happen.
return -1;
}
}
}
// Write through if enough for a complete block.
while(bytesLeft > mSize) {
int32_t bytesWritten = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
if (bytesWritten < 0) return bytesWritten;
buffer += bytesWritten;
bytesLeft -= bytesWritten;
}
// Save any remaining partial blocks for next time.
if (bytesLeft > 0) {
int32_t bytesWritten = writeToStorage(buffer, bytesLeft);
bytesLeft -= bytesWritten;
}
return numBytes - bytesLeft;
}

Some files were not shown because too many files have changed in this diff Show more