pax_global_header 0000666 0000000 0000000 00000000064 13232411367 0014514 g ustar 00root root 0000000 0000000 52 comment=df8ef0e2bcb4b9d5061ad9dd9435d77d761703a0
nageru-1.6.4/ 0000775 0000000 0000000 00000000000 13232411367 0013005 5 ustar 00root root 0000000 0000000 nageru-1.6.4/.gitignore 0000664 0000000 0000000 00000000276 13232411367 0015002 0 ustar 00root root 0000000 0000000 *.d
*.o
*.pb.h
*.pb.cc
*.moc.cpp
ui_aboutdialog.h
ui_audio_expanded_view.h
ui_audio_miniview.h
ui_display.h
ui_input_mapping.h
ui_mainwindow.h
ui_midi_mapping.h
nageru
benchmark_audio_mixer
nageru-1.6.4/.gitmodules 0000664 0000000 0000000 00000000104 13232411367 0015155 0 ustar 00root root 0000000 0000000 [submodule "bmusb"]
path = bmusb
url = http://git.sesse.net/bmusb
nageru-1.6.4/COPYING 0000664 0000000 0000000 00000104513 13232411367 0014044 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
nageru-1.6.4/Makefile 0000664 0000000 0000000 00000010423 13232411367 0014445 0 ustar 00root root 0000000 0000000 CXX=g++
PROTOC=protoc
INSTALL=install
EMBEDDED_BMUSB=no
PKG_MODULES := Qt5Core Qt5Gui Qt5Widgets Qt5OpenGLExtensions Qt5OpenGL Qt5PrintSupport libusb-1.0 movit luajit libmicrohttpd epoxy x264 protobuf libpci
CXXFLAGS ?= -O2 -g -Wall # Will be overridden by environment.
CXXFLAGS += -std=gnu++11 -fPIC $(shell pkg-config --cflags $(PKG_MODULES)) -pthread -DMOVIT_SHADER_DIR=\"$(shell pkg-config --variable=shaderdir movit)\" -Idecklink/
ifeq ($(EMBEDDED_BMUSB),yes)
CPPFLAGS += -Ibmusb/
else
PKG_MODULES += bmusb
endif
LDLIBS=$(shell pkg-config --libs $(PKG_MODULES)) -pthread -lva -lva-drm -lva-x11 -lX11 -lavformat -lavcodec -lavutil -lswscale -lavresample -lzita-resampler -lasound -ldl -lqcustomplot
# Qt objects
OBJS_WITH_MOC = glwidget.o mainwindow.o vumeter.o lrameter.o compression_reduction_meter.o correlation_meter.o aboutdialog.o analyzer.o input_mapping_dialog.o midi_mapping_dialog.o nonlinear_fader.o
OBJS += $(OBJS_WITH_MOC)
OBJS += $(OBJS_WITH_MOC:.o=.moc.o) ellipsis_label.moc.o clickable_label.moc.o
OBJS += context_menus.o vu_common.o piecewise_interpolator.o main.o
OBJS += midi_mapper.o midi_mapping.pb.o
# Mixer objects
AUDIO_MIXER_OBJS = audio_mixer.o alsa_input.o alsa_pool.o ebu_r128_proc.o stereocompressor.o resampling_queue.o flags.o correlation_measurer.o filter.o input_mapping.o state.pb.o
OBJS += chroma_subsampler.o v210_converter.o mixer.o basic_stats.o metrics.o pbo_frame_allocator.o context.o ref_counted_frame.o theme.o httpd.o flags.o image_input.o alsa_output.o disk_space_estimator.o print_latency.o timecode_renderer.o tweaked_inputs.o $(AUDIO_MIXER_OBJS)
# Streaming and encoding objects
OBJS += quicksync_encoder.o x264_encoder.o x264_dynamic.o x264_speed_control.o video_encoder.o metacube2.o mux.o audio_encoder.o ffmpeg_raii.o ffmpeg_util.o
# DeckLink
OBJS += decklink_capture.o decklink_util.o decklink_output.o decklink/DeckLinkAPIDispatch.o
KAERU_OBJS = kaeru.o x264_encoder.o mux.o basic_stats.o metrics.o flags.o audio_encoder.o x264_speed_control.o print_latency.o x264_dynamic.o ffmpeg_raii.o ref_counted_frame.o ffmpeg_capture.o ffmpeg_util.o httpd.o metacube2.o
# bmusb
ifeq ($(EMBEDDED_BMUSB),yes)
OBJS += bmusb/bmusb.o bmusb/fake_capture.o
KAERU_OBJS += bmusb/bmusb.o
endif
# FFmpeg input
OBJS += ffmpeg_capture.o
# Benchmark program.
BM_OBJS = benchmark_audio_mixer.o $(AUDIO_MIXER_OBJS) flags.o metrics.o
%.o: %.cpp
$(CXX) -MMD -MP $(CPPFLAGS) $(CXXFLAGS) -o $@ -c $<
%.o: %.cc
$(CXX) -MMD -MP $(CPPFLAGS) $(CXXFLAGS) -o $@ -c $<
%.pb.cc %.pb.h : %.proto
$(PROTOC) --cpp_out=. $<
%.h: %.ui
uic $< -o $@
%.moc.cpp: %.h
moc $< -o $@
all: nageru kaeru benchmark_audio_mixer
nageru: $(OBJS)
$(CXX) -o $@ $^ $(LDFLAGS) $(LDLIBS)
kaeru: $(KAERU_OBJS)
$(CXX) -o $@ $^ $(LDFLAGS) $(LDLIBS)
benchmark_audio_mixer: $(BM_OBJS)
$(CXX) -o $@ $^ $(LDFLAGS) $(LDLIBS)
# Extra dependencies that need to be generated.
aboutdialog.o: ui_aboutdialog.h
analyzer.o: ui_analyzer.h
alsa_pool.o: state.pb.h
audio_mixer.o: state.pb.h
input_mapping.o: state.pb.h
input_mapping_dialog.o: ui_input_mapping.h
mainwindow.o: ui_mainwindow.h ui_display.h ui_audio_miniview.h ui_audio_expanded_view.h ui_midi_mapping.h
mainwindow.o: midi_mapping.pb.h
midi_mapper.o: midi_mapping.pb.h
midi_mapping_dialog.o: ui_midi_mapping.h midi_mapping.pb.h
DEPS=$(OBJS:.o=.d) $(BM_OBJS:.o=.d) $(KAERU_OBJS:.o=.d)
-include $(DEPS)
clean:
$(RM) $(OBJS) $(BM_OBJS) $(KAERU_OBJS) $(DEPS) nageru benchmark_audio_mixer ui_aboutdialog.h ui_analyzer.h ui_mainwindow.h ui_display.h ui_about.h ui_audio_miniview.h ui_audio_expanded_view.h ui_input_mapping.h ui_midi_mapping.h chain-*.frag *.dot *.pb.cc *.pb.h $(OBJS_WITH_MOC:.o=.moc.cpp) ellipsis_label.moc.cpp clickable_label.moc.cpp
PREFIX=/usr/local
install:
$(INSTALL) -m 755 -o root -g root -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/share/nageru
$(INSTALL) -m 755 -o root -g root nageru $(DESTDIR)$(PREFIX)/bin/nageru
$(INSTALL) -m 755 -o root -g root kaeru $(DESTDIR)$(PREFIX)/bin/kaeru
$(INSTALL) -m 644 -o root -g root theme.lua $(DESTDIR)$(PREFIX)/share/nageru/theme.lua
$(INSTALL) -m 644 -o root -g root simple.lua $(DESTDIR)$(PREFIX)/share/nageru/simple.lua
$(INSTALL) -m 644 -o root -g root bg.jpeg $(DESTDIR)$(PREFIX)/share/nageru/bg.jpeg
$(INSTALL) -m 644 -o root -g root akai_midimix.midimapping $(DESTDIR)$(PREFIX)/share/nageru/akai_midimix.midimapping
nageru-1.6.4/NEWS 0000664 0000000 0000000 00000025323 13232411367 0013511 0 ustar 00root root 0000000 0000000 Nageru 1.6.4, January 25th, 2018
- Fix compilation with the upcoming FFmpeg 3.5.
- Switch to LuaJIT for the theme engine, which is faster.
- Various bugfixes and smaller optimizations.
Nageru 1.6.3, November 8th, 2017
- Add quick-cut keys (Q, W, E, etc.) below the preview keys.
Since it's easy to hit these by accident and put up a signal
you didn't want, they are disabled by default (they can be
enabled in the video menu, or with the command line flag
--quick-cut-keys).
- Rework the x264 speedcontrol presets to better match newer
x264 versions.
- Add an option for changing the HTTP port (--http-port).
- Various smaller bug and integration fixes.
Nageru 1.6.2, July 16th, 2017
- Various smaller Kaeru fixes, mostly around metrics. Also,
you can now adjust the x264 bitrate in Kaeru (in 100 kbit/sec
increments) by sending SIGUSR1 (higher) or SIGUSR2 (lower).
Nageru 1.6.1, July 9th, 2017
- Add native export of Prometheus metrics.
- Rework the frame queue drop algorithm. The new one should handle tricky
situations much better, especially when a card is drifting very slowly
against the master timer.
- Add Kaeru, an experimental transcoding tool based on Nageru code.
Kaeru can run headless on a server without a GPU to transcode a
Nageru stream into a lower-bitrate one, replacing VLC.
- Work around a bug in some versions of NVIDIA's OpenGL drivers that would
crash Nageru after about three hours (fix in cooperation with Movit).
- Fix a crash with i965-va-driver 1.8.x.
- Reduce mutex contention in certain critical places, causing lower tail
latency in the mixer.
Nageru 1.6.0, May 29th, 2017
- Add support for having videos (from file or from URL) as a separate
input channels, albeit with some limitations. Apart from the obvious use of
looping pause clips or similar, this can be used to integrate with CasparCG;
see the manual for more details.
- Add a frame analyzer (accessible from the Video menu) containing an
RGB histogram and a color dropped tool. This is useful in calibrating
video chains by playing back a known signal. Note that this adds a
dependency on QCustomPlot.
- Allow overriding Y'CbCr input interpretation, for inputs that don't
use the correct settings. Also, Rec. 601 is now used by default instead
of Rec. 709 for SD resolutions.
- Support other sample rates than 48000 Hz from bmusb.
Nageru 1.5.0, April 5th, 2017
- Support for low-latency HDMI/SDI output in addition to (or instead of) the
stream. This currently only works with DeckLink cards, not bmusb. See the
manual for more information.
- Support changing the resolution from the command line, instead of locking
everything to 1280x720.
- The A/V sync code has been rewritten to be more in line with Fons
Adriaensen's original paper. It handles several cases much better,
in particular when trying to match 59.94 and 60 Hz sources to each other.
However, it might occasionally need a few extra seconds on startup to
lock properly if startup is slow.
- Add support for using x264 for the disk recording. This makes it possible,
among other things, to run Nageru on a machine entirely without VA-API
support.
- Support for 10-bit Y'CbCr, both on input and output. (Output requires
x264 disk recording, as Quick Sync Video does not support 10-bit H.264.)
This requires compute shader support, and is in general a little bit
slower on input and output, due to the extra amount of data being shuffled
around. Intermediate precision is 16-bit floating-point or better,
as before.
- Enable input mode autodetection for DeckLink cards that support it.
(bmusb mode has always been autodetected.)
- Add functionality to add a time code to the stream; useful for debugging
latency.
- The live display is now both more performant and of higher image quality.
- Fix a long-standing issue where the preview displays would be too bright
when using an NVIDIA GPU. (This did not affect the finished stream.)
- Many other bugfixes and small improvements.
Nageru 1.4.2, November 24th, 2016
- Fix a thread race that would sometimes cause x264 streaming to go awry.
Nageru 1.4.1, November 6th, 2016
- Various bugfixes.
Nageru 1.4.0, October 26th, 2016
- Support for multichannel (or more accurately, multi-bus) audio,
choosable from the UI or using the --multichannel command-line
flag. In multichannel mode, you can take in inputs from multiple
different sources (or different channels on the same source, for
multichannel sound cards), apply effects to them separately and then
mix them together. This includes both audio from the video cards
as well as ALSA inputs, including hotplug. Ola Gundelsby contributed
invaluable feedback on this feature throughout the entire
development cycle.
- Support for having MIDI controllers control various aspects of the
audio UI, with relatively flexible mapping. Note that different
MIDI controllers can vary significantly in what protocol they speak,
so Nageru will not necessarily work with all. (The primary testing
controller has been the Akai MIDImix, and a pre-made mapping for
that is included. The Korg nanoKONTROL2 has also been tested and
works, but it requires some Korg-specific SysEx commands to make
the buttons and lights work.)
- Add a disk space indicator to the main window.
- Various bugfixes. In particular, an issue where the audio would pitch
up sharply after a series of many dropped frames has been fixed.
Nageru 1.3.4, August 2nd, 2016
- Various bugfixes.
Nageru 1.3.3, July 27th, 2016
- Various changes to make distribution packaging easier; in particular,
theme data can be picked up from /usr/local/share/nageru.
- Fix various FFmpeg deprecation warnings, now that we need FFmpeg
3.1 for other reasons anyway.
Nageru 1.3.2, July 23rd, 2016
- Allow limited hotplugging (unplugging and replugging) of USB cards.
You can use the new command-line option --num-fake-cards (-C) to add
fake cards that show only a single color and that will be replaced
by real cards as you plug them in; you can also unplug cards and have
them be replaced by fake cards. Fake cards can also be used for testing
Nageru without actually having any video cards available.
- Add Metacube timestamping of every keyframe, for easier detection of
streams not keeping up. Works with the new timestamp feature of
Cubemap 1.3.1. Will be ignored (save for some logging) in older
Cubemap versions.
- The included default theme has been reworked and cleaned up to be
more understandable and extensible.
- Add more command-line options for initial audio setup.
Nageru 1.3.1, July 1st, 2016
- Various display bugfixes.
Nageru 1.3.0, June 26th, 2016
- It is now possible, given enough CPU power (e.g., a quad-core Haswell or
faster desktop CPU), to output a stream that is suitable for streaming
directly to end users without further transcoding. In particular, this
includes support for encoding the network stream with x264 (the stream
saved to disk is still done using Quick Sync), for Metacube framing (for
streaming to the Cubemap reflector), and for choosing the network stream
mux. For more information, see the README.
- Add a flag (--disable-alsa-output) to disable ALSA monitoring output.
- Do texture uploads from the main thread instead of from separate threads;
may or may not improve stability with NVIDIA's proprietary drivers.
- When beginning a new video segment, the shutdown of the old encoder
is now done in a background thread, in order to not disturb the external
stream. The audio still goes into a somewhat random stream, though.
- You can now override the default stream-to-card mapping with --map-signal=
on the command line.
- Nageru now tries to lock itself into RAM if it has the permissions to do
so, for better realtime behavior. (Writing the stream to disk tends to
fill the buffer cache, eventually paging less-used parts of Nageru out.)
- Various fixes for deadlocks, memory leaks, and many other errors.
Nageru 1.2.1, April 15th, 2016
- Images are now updated from disk about every second, so that it is possible
to update e.g. overlays during streaming, although somewhat slowly.
- Fix support for PNG images.
- You can now send SIGHUP to start a new cut instead of using the menu.
- Added a --help option.
- Various tweaks to OpenGL fence handling.
Nageru 1.2.0, April 6th, 2016
- Support for Blackmagic's PCI and Thunderbolt cards, using the official
(closed-source) Blackmagic drivers. (You do not need the SDK installed, though.)
You can use PCI and USB cards pretty much interchangeably.
- Much more stable handling of frame queues on non-master cards. In particular,
you can have a master card on 50 Hz and another card on 60 Hz without getting
lots of warning messages and a 10+ frame latency on the second card.
- Many new options in the right click menu on cards: Adjustable video inputs,
adjustable audio inputs, adjustable resolutions, ability to select card for
master clock.
- Add support for starting with almost all audio processing turned off
(--flat-audio).
- The UI now marks inputs with red or green to mark them as participating in
the live or preview signal, respectively. Red takes priority. (Actually,
it merely asks the theme for a color for each input; the theme contains
the logic.)
- Add support for uncompressed video instead of H.264 on the HTTP server,
while still storing H.264 to files (--http-uncompressed-video). Note that
depending on your client, this might not actually be more CPU efficient
even on localhost, so be sure to check.
- Add a simpler, less featureful theme (simple.lua) that should be easier to
understand for beginners. Themes are now also choosable with -t on the command
line.
- Too many bugfixes and small tweaks to list. In particular, many memory leaks
in the streaming part have been identified and fixed.
Nageru 1.1.0, February 24th, 2016
- Support doing the H.264 encoding on a different graphics device from the one
doing the mixing. In particular, this makes it possible to use Nageru on an
NVIDIA GPU while still encoding H.264 video using Intel Quick Sync (NVENC
is not supported yet) -- it is less efficient since the data needs to be read
back via the CPU, but the NVIDIA cards and drivers are so much faster that it
doesn't really matter. Tested on a GTX 950 with the proprietary drivers.
- In the included example theme, fix fading to/from deinterlaced sources.
- Various smaller compilation, distribution and documentation fixes.
Nageru 1.0.0, January 30th, 2016
- Initial release.
nageru-1.6.4/Nageru-Grafana.json 0000664 0000000 0000000 00000124020 13232411367 0016455 0 ustar 00root root 0000000 0000000 {
"__inputs": [
{
"name": "DS_EXAMPLE",
"label": "example",
"description": "",
"type": "datasource",
"pluginId": "prometheus",
"pluginName": "Prometheus"
}
],
"__requires": [
{
"type": "grafana",
"id": "grafana",
"name": "Grafana",
"version": "4.3.2"
},
{
"type": "panel",
"id": "graph",
"name": "Graph",
"version": ""
},
{
"type": "panel",
"id": "heatmap",
"name": "Heatmap",
"version": ""
},
{
"type": "datasource",
"id": "prometheus",
"name": "Prometheus",
"version": "1.0.0"
},
{
"type": "panel",
"id": "singlestat",
"name": "Singlestat",
"version": ""
}
],
"annotations": {
"list": []
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"hideControls": false,
"id": null,
"links": [],
"refresh": "30s",
"rows": [
{
"collapse": false,
"height": 156,
"panels": [
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "${DS_EXAMPLE}",
"format": "s",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"id": 37,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"repeat": null,
"span": 2,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "",
"targets": [
{
"expr": "time() - nageru_start_time_seconds{instance=~\"$instance\"}",
"format": "time_series",
"hide": false,
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 240
}
],
"thresholds": "",
"title": "Nageru uptime",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "${DS_EXAMPLE}",
"format": "dtdurations",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"id": 6,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"repeat": null,
"span": 2,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "instance",
"targets": [
{
"expr": "nageru_disk_free_bytes / ignoring(destination) deriv(nageru_mux_written_bytes{destination=\"files_total\",instance=~\"$instance\"}[10m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 240
}
],
"thresholds": "",
"title": "Disk space remaining",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "${DS_EXAMPLE}",
"format": "none",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"id": 11,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"span": 2,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": true
},
"tableColumn": "",
"targets": [
{
"expr": "nageru_num_connected_clients{instance=~\"$instance\"}",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 240
}
],
"thresholds": "",
"title": "Connected clients",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "${DS_EXAMPLE}",
"format": "none",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"id": 46,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"span": 2,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": true
},
"tableColumn": "",
"targets": [
{
"expr": "sum(nageru_input_has_signal_bool{cardtype=\"ffmpeg\",instance=~\"$instance\"})",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "",
"metric": "",
"refId": "A",
"step": 240
}
],
"thresholds": "",
"title": "Connected FFmpeg inputs",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": false,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"datasource": "${DS_EXAMPLE}",
"decimals": 1,
"format": "none",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"id": 7,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": " LU",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"span": 2,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": true
},
"tableColumn": "",
"targets": [
{
"expr": "nageru_audio_loudness_integrated_lufs{instance=~\"$instance\"} + 23",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 240
}
],
"thresholds": "",
"title": "Overall audio level",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 0,
"id": 18,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": false,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 2,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "nageru_audio_correlation{instance=~\"$instance\"}",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 60
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Audio correlation",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": "",
"logBase": 1,
"max": "1",
"min": "-1",
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": "instance",
"repeatIteration": null,
"repeatRowId": null,
"showTitle": true,
"title": "$instance",
"titleSize": "h6"
},
{
"collapse": false,
"height": "250px",
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 1,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 6,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "rate(nageru_decklink_output_completed_frames{status!=\"completed\",instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Output frames {{status}}",
"refId": "A",
"step": 20
},
{
"expr": "sum(rate(nageru_input_dropped_frames_error{instance=~\"$instance\"}[1m])) without (cardtype)",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Error frames card {{card}}",
"refId": "B",
"step": 20
},
{
"expr": "rate(nageru_quick_sync_stalled_frames{instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Quick Sync stalled frames",
"refId": "C",
"step": 20
},
{
"expr": "rate(nageru_x264_dropped_frames{instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "x264 dropped frames",
"refId": "D",
"step": 20
},
{
"expr": "rate(nageru_x264_speedcontrol_idle_frames{instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "x264 speedcontrol idle frames",
"refId": "E",
"step": 20
},
{
"expr": "rate(nageru_x264_speedcontrol_late_frames{instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "x264 speedcontrol late frames",
"refId": "F",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Potential performance problems",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 27,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 6,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "sum(rate(nageru_input_queue_duped_frames{instance=~\"$instance\"}[1m])) without (cardtype)",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Duplicated frames (queue starvation) card {{card}}",
"metric": "",
"refId": "A",
"step": 20
},
{
"expr": "sum(rate(nageru_input_dropped_frames_jitter{instance=~\"$instance\"}[1m])) without (cardtype)",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Dropped frames card {{card}}",
"refId": "B",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Queue events",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "Dashboard Row",
"titleSize": "h6"
},
{
"collapse": false,
"height": 249,
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 12,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 6,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "8 * rate(nageru_mux_stream_bytes{destination=\"http\",instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "{{stream}}",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Stream bitrates",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bps",
"label": null,
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 13,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 6,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "8 * rate(nageru_mux_stream_bytes{destination=\"current_file\",instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "{{stream}}",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Disk bitrates",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bps",
"label": null,
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "Dashboard Row",
"titleSize": "h6"
},
{
"collapse": false,
"height": 247,
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 19,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "90-percentile",
"fillBelowTo": "10-percentile",
"lines": false
},
{
"alias": "10-percentile",
"lines": false
},
{
"alias": "Average",
"fill": 0
}
],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "histogram_quantile(0.9, rate(nageru_x264_crf_bucket{instance=~\"$instance\"}[1m]))",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "90-percentile",
"refId": "B",
"step": 30
},
{
"expr": "histogram_quantile(0.1, rate(nageru_x264_crf_bucket{instance=~\"$instance\"}[1m]))",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "10-percentile",
"refId": "A",
"step": 30
},
{
"expr": "rate(nageru_x264_crf_sum{instance=~\"$instance\"}[1m]) / rate(nageru_x264_crf_count{instance=~\"$instance\"}[1m])",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Average",
"refId": "C",
"step": 30
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "x264 average CRF (lower is better)",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"cards": {
"cardPadding": null,
"cardRound": null
},
"color": {
"cardColor": "#b4ff00",
"colorScale": "sqrt",
"colorScheme": "interpolateOranges",
"exponent": 0.5,
"mode": "spectrum"
},
"dataFormat": "timeseries",
"heatmap": {},
"highlightCards": true,
"id": 55,
"links": [],
"span": 4,
"targets": [
{
"expr": "rate(nageru_x264_speedcontrol_preset_used_frames_bucket{instance=~\"$instance\"}[1m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 30
}
],
"title": "x264 speed control chosen preset",
"tooltip": {
"show": true,
"showHistogram": false
},
"type": "heatmap",
"xAxis": {
"show": true
},
"xBucketNumber": null,
"xBucketSize": "",
"yAxis": {
"decimals": null,
"format": "short",
"logBase": 1,
"max": "26",
"min": "0",
"show": true,
"splitFactor": null
},
"yBucketNumber": null,
"yBucketSize": 1
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 62,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "nageru_x264_speedcontrol_buffer_available_seconds{instance=~\"$instance\"} / nageru_x264_speedcontrol_buffer_size_seconds{instance=~\"$instance\"}",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "x264 speed control buffer available",
"refId": "A",
"step": 30
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "x264 buffer space available",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "percentunit",
"label": "",
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "Dashboard Row",
"titleSize": "h6"
},
{
"collapse": false,
"height": 264,
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 0,
"id": 2,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": false,
"sideWidth": null,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"repeat": "card",
"seriesOverrides": [
{
"alias": "90-percentile",
"fillBelowTo": "10-percentile",
"lines": false
},
{
"alias": "10-percentile",
"lines": false
}
],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "nageru_latency_seconds{measuring_point=\"decklink_output\",frame_type=\"total\",quantile=\"0.9\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}",
"format": "time_series",
"hide": false,
"interval": "",
"intervalFactor": 2,
"legendFormat": "90-percentile",
"metric": "",
"refId": "A",
"step": 30
},
{
"expr": "nageru_latency_seconds{measuring_point=\"decklink_output\",frame_type=\"total\",quantile=\"0.1\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "10-percentile",
"refId": "B",
"step": 30
},
{
"expr": "sum(\n rate(nageru_latency_seconds_sum{measuring_point=\"decklink_output\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}[1m])\n) without (frame_type) / sum(\n rate(nageru_latency_seconds_count{measuring_point=\"decklink_output\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}[1m])\n) without (frame_type)",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Average",
"refId": "C",
"step": 30
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "HDMI/SDI latency, card $card",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "dtdurations",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 1,
"id": 14,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "nageru_memory_used_bytes{instance=~\"$instance\"}",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Used",
"refId": "A",
"step": 30
},
{
"expr": "nageru_memory_locked_limit_bytes{instance=~\"$instance\"}",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Max locked",
"refId": "B",
"step": 30
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Memory usage",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"label": "",
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_EXAMPLE}",
"fill": 0,
"id": 20,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": false,
"sideWidth": null,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"repeat": "card",
"seriesOverrides": [
{
"alias": "90-percentile",
"fillBelowTo": "10-percentile",
"lines": false
},
{
"alias": "10-percentile",
"lines": false
}
],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "nageru_latency_seconds{measuring_point=\"mixer\",frame_type=\"total\",quantile=\"0.9\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}",
"format": "time_series",
"hide": false,
"interval": "",
"intervalFactor": 2,
"legendFormat": "90-percentile",
"metric": "",
"refId": "A",
"step": 30
},
{
"expr": "nageru_latency_seconds{measuring_point=\"mixer\",frame_type=\"total\",quantile=\"0.1\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "10-percentile",
"refId": "B",
"step": 30
},
{
"expr": "sum(\n rate(nageru_latency_seconds_sum{measuring_point=\"mixer\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}[1m])\n) without (frame_type) / sum(\n rate(nageru_latency_seconds_count{measuring_point=\"mixer\",frame_age=\"0\",card=\"$card\",instance=~\"$instance\"}[1m])\n) without (frame_type)",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "Average",
"refId": "C",
"step": 30
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Mixer latency, card $card",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "dtdurations",
"label": "",
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "Dashboard Row",
"titleSize": "h6"
}
],
"schemaVersion": 14,
"style": "dark",
"tags": [],
"templating": {
"list": [
{
"allValue": null,
"current": {},
"datasource": "${DS_EXAMPLE}",
"hide": 0,
"includeAll": true,
"label": null,
"multi": false,
"name": "instance",
"options": [],
"query": "nageru_latency_seconds{measuring_point=\"mixer\"}",
"refresh": 1,
"regex": "/.*instance=\"([^\"]+)\".*/",
"sort": 1,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {},
"datasource": "${DS_EXAMPLE}",
"hide": 0,
"includeAll": true,
"label": null,
"multi": false,
"name": "card",
"options": [],
"query": "nageru_latency_seconds{measuring_point=\"mixer\"}",
"refresh": 1,
"regex": "/.*card=\"(\\d+)\".*/",
"sort": 3,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-3h",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "browser",
"title": "Nageru",
"version": 42
}
nageru-1.6.4/README 0000664 0000000 0000000 00000024143 13232411367 0013671 0 ustar 00root root 0000000 0000000 Nageru is a live video mixer, based around the standard M/E workflow.
Features:
- High performance on modest hardware (720p60 with two input streams
on my Thinkpad X240[1]); almost all pixel processing is done on the GPU.
- High output quality; Lanczos3 scaling, subpixel precision everywhere,
white balance adjustment, mix of 16- and 32-bit floating point
for intermediate calculations, dithered output, optional 10-bit input
and output support.
- Proper sound support: Syncing of multiple unrelated sources through
high-quality resampling, multichannel mixing with separate effects
per-bus, cue out for headphones, dynamic range compression,
three-band graphical EQ (pluss a fixed low-cut), level meters conforming
to EBU R128, automation via MIDI controllers.
- Theme engine encapsulating the design demands of each individual
event; Lua code is responsible for setting up the pixel processing
pipelines, running transitions etc., so that the visual look is
consistent between operators.
- Comprehensive monitoring through Prometheus metrics.
[1] For reference, that is: Core i7 4600U (dualcore 2.10GHz, clocks down
to 800 MHz after 30 seconds due to thermal constraints), Intel HD Graphics
4400 (ie., without the extra L4 cache from Iris Pro), single-channel DDR3 RAM
(so 12.8 GB/sec theoretical memory bandwidth, shared between CPU and GPU).
Nageru is in beta stage. It currently needs:
- An Intel processor with Intel Quick Sync, or otherwise some hardware
H.264 encoder exposed through VA-API. Note that you can use VA-API over
DRM instead of X11, to use a non-Intel GPU for rendering but still use
Quick Sync (by giving e.g. “--va-display /dev/dri/renderD128”).
- Two or more Blackmagic USB3 or PCI cards, either HDMI or SDI.
The PCI cards need Blackmagic's own drivers installed. The USB3 cards
are driven through the “bmusb” driver, using libusb-1.0. If you want
zerocopy USB, you need libusb 1.0.21 or newer, as well as a recent
kernel (4.6.0 or newer). Zerocopy USB helps not only for performance,
but also for stability. You need at least version 0.7.0.
- Movit, my GPU-based video filter library (https://movit.sesse.net).
You will need at least version 1.5.2.
- Qt 5.5 or newer for the GUI.
- QCustomPlot for the histogram display in the frame analyzer.
- libmicrohttpd for the embedded web server.
- x264 for encoding high-quality video suitable for streaming to end users.
- ffmpeg for muxing, and for encoding audio. You will need at least
version 3.1.
- Working OpenGL; Movit works with almost any modern OpenGL implementation.
Nageru has been tested with Intel on Mesa (you want 11.2 or newer, due
to critical stability bugfixes), and with NVIDIA's proprietary drivers.
AMD's proprietary drivers (fglrx) are known not to work due to driver bugs;
I am in contact with AMD to try to get this resolved.
- libzita-resampler, for resampling sound sources so that they are in sync
between sources, and also for oversampling for the peak meter.
- LuaJIT, for driving the theme engine.
- libpci, for printing friendly PCI device names in an error message.
If on Debian stretch or something similar, you can install everything you need
with:
apt install qtbase5-dev libqt5opengl5-dev qt5-default libqcustomplot-dev \
pkg-config libmicrohttpd-dev libusb-1.0-0-dev libluajit-5.1-dev \
libzita-resampler-dev libva-dev libavcodec-dev libavformat-dev \
libswscale-dev libavresample-dev libmovit-dev libegl1-mesa-dev \
libasound2-dev libx264-dev libbmusb-dev protobuf-compiler \
libprotobuf-dev libpci-dev
Exceptions as of July 2017:
- You will need Movit from unstable; stretch only has 1.4.0.
- You will need bmusb from unstable; stretch only has 0.5.4.
The patches/ directory contains a patch that helps zita-resampler performance.
It is meant for upstream, but was not in at the time Nageru was released.
It is taken to be by Steinar H. Gunderson (ie., my ex-work
email), and under the same license as zita-resampler itself.
To start it, just hook up your equipment, type “make” and then “./nageru”.
It is strongly recommended to have the rights to run at real-time priority;
it will make the USB3 threads do so, which will make them a lot more stable.
(A reasonable hack for testing is probably just to run it as root using sudo,
although you might not want to do that in production.) Note also that if you
are running a desktop compositor, it will steal significant amounts of GPU
performance. The same goes for PulseAudio.
Nageru will open a HTTP server at port 9095, where you can extract a live
H264+PCM signal in nut mux (e.g. http://127.0.0.1:9095/stream.nut).
It is probably too high bitrate (~25 Mbit/sec depending on content) to send to
users, but you can easily send it around in your internal network and then
transcode it in e.g. VLC. A copy of the stream (separately muxed) will also
be saved live to local disk.
If you have a fast CPU (typically a quadcore desktop; most laptops will spend
most of their CPU on running Nageru itself), you can use x264 for the outgoing
stream instead of Quick Sync; it is much better quality for the same bitrate,
and also has proper bitrate controls. Simply add --http-x264-video on the
command line. (You may also need to add something like "--x264-preset veryfast",
since the default "medium" preset might be too CPU-intensive, but YMMV.)
The stream saved to disk will still be the Quick Sync-encoded stream, as it is
typically higher bitrate and thus also higher quality. Note that if you add
".metacube" at the end of the URL (e.g. "http://127.0.0.1:9095/stream.ts.metacube"),
you will get a stream suitable for streaming through the Cubemap video reflector
(cubemap.sesse.net). A typical example would be:
./nageru --http-x264-video --x264-preset veryfast --x264-tune film \
--http-mux mp4 --http-audio-codec libfdk_aac --http-audio-bitrate 128
If you are comfortable with using all your remaining CPU power on the machine
for x264, try --x264-speedcontrol, which will try to adjust the preset
dynamically for maximum quality, at the expense of somewhat higher delay.
See --help for more information on options in general.
The name “Nageru” is a play on the Japanese verb 投げる (nageru), which means
to throw or cast. (I also later learned that it could mean to face defeat or
give up, but that's not the intended meaning.)
Nageru's home page is at https://nageru.sesse.net/, where you can also find
contact information and link to the latest version.
Legalese: TL;DR: Everything is GPLv3-or-newer compatible, and see
Intel's copyright license at quicksync_encoder.h.
Nageru is Copyright (C) 2015 Steinar H. Gunderson .
Portions Copyright (C) 2003 Rune Holm.
Portions Copyright (C) 2010-2015 Fons Adriaensen .
Portions Copyright (C) 2012-2015 Fons Adriaensen .
Portions Copyright (C) 2008-2015 Fons Adriaensen .
Portions Copyright (c) 2007-2013 Intel Corporation. All Rights Reserved.
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 .
Portions of quicksync_encoder.h and quicksync_encoder.cpp:
Copyright (c) 2007-2013 Intel Corporation. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sub license, 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 (including the
next paragraph) 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 NON-INFRINGEMENT.
IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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.
All files in decklink/:
Copyright (c) 2009 Blackmagic Design
Copyright (c) 2015 Blackmagic Design
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
nageru-1.6.4/aboutdialog.cpp 0000664 0000000 0000000 00000000413 13232411367 0016001 0 ustar 00root root 0000000 0000000 #include "aboutdialog.h"
#include
#include "ui_aboutdialog.h"
using namespace std;
AboutDialog::AboutDialog()
: ui(new Ui::AboutDialog)
{
ui->setupUi(this);
connect(ui->button_box, &QDialogButtonBox::accepted, [this]{ this->close(); });
}
nageru-1.6.4/aboutdialog.h 0000664 0000000 0000000 00000000456 13232411367 0015455 0 ustar 00root root 0000000 0000000 #ifndef _ABOUTDIALOG_H
#define _ABOUTDIALOG_H 1
#include
#include
class QObject;
namespace Ui {
class AboutDialog;
} // namespace Ui
class AboutDialog : public QDialog
{
Q_OBJECT
public:
AboutDialog();
private:
Ui::AboutDialog *ui;
};
#endif // !defined(_ABOUTDIALOG_H)
nageru-1.6.4/akai_midimix.midimapping 0000664 0000000 0000000 00000013510 13232411367 0017652 0 ustar 00root root 0000000 0000000 # Example mapping for the Akai MIDImix. This one is written by hand,
# and serves as a simple example of the basic features. The MIDImix
# doesn't have a ton of controls, so not everything is mapped up,
# and some "wrong" mappings need to be done; in particular, we've set up
# two controller banks and switch between them with the BANK LEFT and
# BANK RIGHT buttons (which are normally meant to switch between channels
# 1–8 and 9–16, as I understand it).
#
# The mappings for the 270° pots on each bus are:
#
# Bank 1: Treble, mid, bass
# Bank 2: Gain, compressor threshold, (globals)
#
# The “(globals)” here are only for use on the two rightmost buses:
# The third pot on bus 7 controls the lo-cut cutoff, and the pot on
# bus 8 controls the limiter threshold.
#
# The mute button controls muting (obviously) for that bus, and the solo
# button (accessible by holding the global solo button and pressing the
# mute button for the bus) is abused for toggling auto gain staging.
#
# The REC ARM button for each bus is abused to be a “has peaked” meter;
# pressing it will reset the measurement.
#
# Finally, the faders work pretty much as you'd expect; each bus' fader
# is connected to the volume for that bus, and the master fader is
# connected to the global makeup gain.
num_controller_banks: 2
treble_bank: 0
mid_bank: 0
bass_bank: 0
gain_bank: 1
compressor_threshold_bank: 1
locut_bank: 1
limiter_threshold_bank: 1
# Bus 1. We also store the master controller here.
bus_mapping {
treble {
controller_number: 16
}
mid {
controller_number: 17
}
bass {
controller_number: 18
}
gain {
controller_number: 16
}
compressor_threshold {
controller_number: 17
}
fader {
controller_number: 19
}
toggle_mute {
note_number: 1
}
toggle_auto_gain_staging {
note_number: 2
}
clear_peak {
note_number: 3
}
# Master.
makeup_gain {
controller_number: 62
}
select_bank_1 {
note_number: 25 # Bank left.
}
select_bank_2 {
note_number: 26 # Bank right.
}
# Lights.
is_muted {
note_number: 1
}
auto_gain_staging_is_on {
note_number: 2
}
has_peaked {
note_number: 3
}
# Global lights.
bank_1_is_selected {
note_number: 25
}
bank_2_is_selected {
note_number: 26
}
}
# Bus 2.
bus_mapping {
treble {
controller_number: 20
}
mid {
controller_number: 21
}
bass {
controller_number: 22
}
gain {
controller_number: 20
}
compressor_threshold {
controller_number: 21
}
fader {
controller_number: 23
}
toggle_mute {
note_number: 4
}
toggle_auto_gain_staging {
note_number: 5
}
clear_peak {
note_number: 6
}
# Lights.
is_muted {
note_number: 4
}
auto_gain_staging_is_on {
note_number: 5
}
has_peaked {
note_number: 6
}
}
# Bus 3.
bus_mapping {
treble {
controller_number: 24
}
mid {
controller_number: 25
}
bass {
controller_number: 26
}
gain {
controller_number: 24
}
compressor_threshold {
controller_number: 25
}
fader {
controller_number: 27
}
toggle_mute {
note_number: 7
}
toggle_auto_gain_staging {
note_number: 8
}
clear_peak {
note_number: 9
}
# Lights.
is_muted {
note_number: 7
}
auto_gain_staging_is_on {
note_number: 8
}
has_peaked {
note_number: 9
}
}
# Bus 4.
bus_mapping {
treble {
controller_number: 28
}
mid {
controller_number: 29
}
bass {
controller_number: 30
}
gain {
controller_number: 28
}
compressor_threshold {
controller_number: 29
}
fader {
controller_number: 31
}
toggle_mute {
note_number: 10
}
toggle_auto_gain_staging {
note_number: 11
}
clear_peak {
note_number: 12
}
# Lights.
is_muted {
note_number: 10
}
auto_gain_staging_is_on {
note_number: 11
}
has_peaked {
note_number: 12
}
}
# Bus 5. Note the discontinuity in the controller numbers,
# but not in the note numbers.
bus_mapping {
treble {
controller_number: 46
}
mid {
controller_number: 47
}
bass {
controller_number: 48
}
gain {
controller_number: 46
}
compressor_threshold {
controller_number: 47
}
fader {
controller_number: 49
}
toggle_mute {
note_number: 13
}
toggle_auto_gain_staging {
note_number: 14
}
clear_peak {
note_number: 15
}
# Lights.
is_muted {
note_number: 13
}
auto_gain_staging_is_on {
note_number: 14
}
has_peaked {
note_number: 15
}
}
# Bus 6.
bus_mapping {
treble {
controller_number: 50
}
mid {
controller_number: 51
}
bass {
controller_number: 52
}
gain {
controller_number: 50
}
compressor_threshold {
controller_number: 51
}
fader {
controller_number: 53
}
toggle_mute {
note_number: 16
}
toggle_auto_gain_staging {
note_number: 17
}
clear_peak {
note_number: 18
}
# Lights.
is_muted {
note_number: 16
}
auto_gain_staging_is_on {
note_number: 17
}
has_peaked {
note_number: 18
}
}
# Bus 7.
bus_mapping {
treble {
controller_number: 54
}
mid {
controller_number: 55
}
bass {
controller_number: 56
}
gain {
controller_number: 54
}
compressor_threshold {
controller_number: 55
}
fader {
controller_number: 57
}
toggle_mute {
note_number: 19
}
toggle_auto_gain_staging {
note_number: 20
}
clear_peak {
note_number: 21
}
# Lights.
is_muted {
note_number: 19
}
auto_gain_staging_is_on {
note_number: 20
}
has_peaked {
note_number: 21
}
# Global controllers.
locut {
controller_number: 56
}
}
# Bus 8.
bus_mapping {
treble {
controller_number: 58
}
mid {
controller_number: 59
}
bass {
controller_number: 60
}
gain {
controller_number: 58
}
compressor_threshold {
controller_number: 59
}
fader {
controller_number: 61
}
toggle_mute {
note_number: 22
}
toggle_auto_gain_staging {
note_number: 23
}
clear_peak {
note_number: 24
}
# Lights.
is_muted {
note_number: 22
}
auto_gain_staging_is_on {
note_number: 23
}
has_peaked {
note_number: 24
}
# Global controllers.
limiter_threshold {
controller_number: 60
}
}
nageru-1.6.4/alsa_input.cpp 0000664 0000000 0000000 00000023542 13232411367 0015656 0 ustar 00root root 0000000 0000000 #include "alsa_input.h"
#include
#include
#include
#include
#include
#include
#include "alsa_pool.h"
#include "bmusb/bmusb.h"
#include "timebase.h"
using namespace std;
using namespace std::chrono;
using namespace std::placeholders;
#define RETURN_ON_ERROR(msg, expr) do { \
int err = (expr); \
if (err < 0) { \
fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
if (err == -ENODEV) return CaptureEndReason::DEVICE_GONE; \
return CaptureEndReason::OTHER_ERROR; \
} \
} while (false)
#define RETURN_FALSE_ON_ERROR(msg, expr) do { \
int err = (expr); \
if (err < 0) { \
fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
return false; \
} \
} while (false)
#define WARN_ON_ERROR(msg, expr) do { \
int err = (expr); \
if (err < 0) { \
fprintf(stderr, "[%s] " msg ": %s\n", device.c_str(), snd_strerror(err)); \
} \
} while (false)
ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
: device(device),
sample_rate(sample_rate),
num_channels(num_channels),
audio_callback(audio_callback),
parent_pool(parent_pool),
internal_dev_index(internal_dev_index)
{
}
bool ALSAInput::open_device()
{
RETURN_FALSE_ON_ERROR("snd_pcm_open()", snd_pcm_open(&pcm_handle, device.c_str(), SND_PCM_STREAM_CAPTURE, 0));
// Set format.
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
if (!set_base_params(device.c_str(), pcm_handle, hw_params, &sample_rate)) {
return false;
}
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_channels()", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
// Fragment size of 64 samples (about 1 ms at 48 kHz; a frame at 60
// fps/48 kHz is 800 samples.) We ask for 64 such periods in our buffer
// (~85 ms buffer); more than that, and our jitter is probably so high
// that the resampling queue can't keep up anyway.
// The entire thing with periods and such is a bit mysterious to me;
// seemingly I can get 96 frames at a time with no problems even if
// the period size is 64 frames. And if I set num_periods to e.g. 1,
// I can't have a big buffer.
num_periods = 16;
int dir = 0;
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_periods_near()", snd_pcm_hw_params_set_periods_near(pcm_handle, hw_params, &num_periods, &dir));
period_size = 64;
dir = 0;
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_period_size_near()", snd_pcm_hw_params_set_period_size_near(pcm_handle, hw_params, &period_size, &dir));
buffer_frames = 64 * 64;
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_set_buffer_size_near()", snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hw_params, &buffer_frames));
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
//snd_pcm_hw_params_free(hw_params);
// Figure out which format the card actually chose.
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_current()", snd_pcm_hw_params_current(pcm_handle, hw_params));
snd_pcm_format_t chosen_format;
RETURN_FALSE_ON_ERROR("snd_pcm_hw_params_get_format()", snd_pcm_hw_params_get_format(hw_params, &chosen_format));
audio_format.num_channels = num_channels;
audio_format.bits_per_sample = 0;
switch (chosen_format) {
case SND_PCM_FORMAT_S16_LE:
audio_format.bits_per_sample = 16;
break;
case SND_PCM_FORMAT_S24_LE:
audio_format.bits_per_sample = 24;
break;
case SND_PCM_FORMAT_S32_LE:
audio_format.bits_per_sample = 32;
break;
default:
assert(false);
}
audio_format.sample_rate = sample_rate;
//printf("num_periods=%u period_size=%u buffer_frames=%u sample_rate=%u bits_per_sample=%d\n",
// num_periods, unsigned(period_size), unsigned(buffer_frames), sample_rate, audio_format.bits_per_sample);
buffer.reset(new uint8_t[buffer_frames * num_channels * audio_format.bits_per_sample / 8]);
snd_pcm_sw_params_t *sw_params;
snd_pcm_sw_params_alloca(&sw_params);
RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
RETURN_FALSE_ON_ERROR("snd_pcm_sw_params_set_start_threshold", snd_pcm_sw_params_set_start_threshold(pcm_handle, sw_params, num_periods * period_size / 2));
RETURN_FALSE_ON_ERROR("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
RETURN_FALSE_ON_ERROR("snd_pcm_nonblock()", snd_pcm_nonblock(pcm_handle, 1));
RETURN_FALSE_ON_ERROR("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
return true;
}
bool ALSAInput::set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate)
{
int err;
err = snd_pcm_hw_params_any(pcm_handle, hw_params);
if (err < 0) {
fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err));
return false;
}
err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
if (err < 0) {
fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err));
return false;
}
snd_pcm_format_mask_t *format_mask;
snd_pcm_format_mask_alloca(&format_mask);
snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE);
snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE);
snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE);
err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask);
if (err < 0) {
fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err));
return false;
}
err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0);
if (err < 0) {
fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err));
return false;
}
return true;
}
ALSAInput::~ALSAInput()
{
if (pcm_handle) {
WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
}
}
void ALSAInput::start_capture_thread()
{
should_quit.unquit();
capture_thread = thread(&ALSAInput::capture_thread_func, this);
}
void ALSAInput::stop_capture_thread()
{
should_quit.quit();
capture_thread.join();
}
void ALSAInput::capture_thread_func()
{
parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
// If the device hasn't been opened already, we need to do so
// before we can capture.
while (!should_quit.should_quit() && pcm_handle == nullptr) {
if (!open_device()) {
fprintf(stderr, "[%s] Waiting one second and trying again...\n",
device.c_str());
should_quit.sleep_for(seconds(1));
}
}
if (should_quit.should_quit()) {
// Don't call free_card(); that would be a deadlock.
if (pcm_handle) {
WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
}
pcm_handle = nullptr;
return;
}
// Do the actual capture. (Termination condition within loop.)
for ( ;; ) {
switch (do_capture()) {
case CaptureEndReason::REQUESTED_QUIT:
// Don't call free_card(); that would be a deadlock.
WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
pcm_handle = nullptr;
return;
case CaptureEndReason::DEVICE_GONE:
parent_pool->free_card(internal_dev_index);
WARN_ON_ERROR("snd_pcm_close()", snd_pcm_close(pcm_handle));
pcm_handle = nullptr;
return;
case CaptureEndReason::OTHER_ERROR:
parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
fprintf(stderr, "[%s] Sleeping one second and restarting capture...\n",
device.c_str());
should_quit.sleep_for(seconds(1));
break;
}
}
}
ALSAInput::CaptureEndReason ALSAInput::do_capture()
{
parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
RETURN_ON_ERROR("snd_pcm_start()", snd_pcm_start(pcm_handle));
parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
uint64_t num_frames_output = 0;
while (!should_quit.should_quit()) {
int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
if (ret == 0) continue; // Timeout.
if (ret == -EPIPE) {
fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
snd_pcm_prepare(pcm_handle);
snd_pcm_start(pcm_handle);
continue;
}
RETURN_ON_ERROR("snd_pcm_wait()", ret);
snd_pcm_sframes_t frames = snd_pcm_readi(pcm_handle, buffer.get(), buffer_frames);
if (frames == -EPIPE) {
fprintf(stderr, "[%s] ALSA overrun\n", device.c_str());
snd_pcm_prepare(pcm_handle);
snd_pcm_start(pcm_handle);
continue;
}
if (frames == 0) {
fprintf(stderr, "snd_pcm_readi() returned 0\n");
break;
}
RETURN_ON_ERROR("snd_pcm_readi()", frames);
const int64_t prev_pts = frames_to_pts(num_frames_output);
const int64_t pts = frames_to_pts(num_frames_output + frames);
const steady_clock::time_point now = steady_clock::now();
bool success;
do {
if (should_quit.should_quit()) return CaptureEndReason::REQUESTED_QUIT;
success = audio_callback(buffer.get(), frames, audio_format, pts - prev_pts, now);
} while (!success);
num_frames_output += frames;
}
return CaptureEndReason::REQUESTED_QUIT;
}
int64_t ALSAInput::frames_to_pts(uint64_t n) const
{
return (n * TIMEBASE) / sample_rate;
}
nageru-1.6.4/alsa_input.h 0000664 0000000 0000000 00000005013 13232411367 0015314 0 ustar 00root root 0000000 0000000 #ifndef _ALSA_INPUT_H
#define _ALSA_INPUT_H 1
// ALSA sound input, running in a separate thread and sending audio back
// in callbacks.
//
// Note: “frame” here generally refers to the ALSA definition of frame,
// which is a set of samples, exactly one for each channel. The only exception
// is in frame_length, where it means the TIMEBASE length of the buffer
// as a whole, since that's what AudioMixer::add_audio() wants.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "bmusb/bmusb.h"
#include "quittable_sleeper.h"
class ALSAPool;
class ALSAInput {
public:
typedef std::function audio_callback_t;
ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index);
~ALSAInput();
// If not called before start_capture_thread(), the capture thread
// will call it until it succeeds.
bool open_device();
// Not valid before the device has been successfully opened.
// NOTE: Might very well be different from the sample rate given to the
// constructor, since the card might not support the one you wanted.
unsigned get_sample_rate() const { return sample_rate; }
void start_capture_thread();
void stop_capture_thread();
// Set access, sample rate and format parameters on the given ALSA PCM handle.
// Returns the computed parameter set and the chosen sample rate. Note that
// sample_rate is an in/out parameter; you send in the desired rate,
// and ALSA picks one as close to that as possible.
static bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate);
private:
void capture_thread_func();
int64_t frames_to_pts(uint64_t n) const;
enum class CaptureEndReason {
REQUESTED_QUIT,
DEVICE_GONE,
OTHER_ERROR
};
CaptureEndReason do_capture();
std::string device;
unsigned sample_rate, num_channels, num_periods;
snd_pcm_uframes_t period_size;
snd_pcm_uframes_t buffer_frames;
bmusb::AudioFormat audio_format;
audio_callback_t audio_callback;
snd_pcm_t *pcm_handle = nullptr;
std::thread capture_thread;
QuittableSleeper should_quit;
std::unique_ptr buffer;
ALSAPool *parent_pool;
unsigned internal_dev_index;
};
#endif // !defined(_ALSA_INPUT_H)
nageru-1.6.4/alsa_output.cpp 0000664 0000000 0000000 00000006764 13232411367 0016066 0 ustar 00root root 0000000 0000000 #include "alsa_output.h"
#include
#include
#include
#include
#include
using namespace std;
namespace {
void die_on_error(const char *func_name, int err)
{
if (err < 0) {
fprintf(stderr, "%s: %s\n", func_name, snd_strerror(err));
exit(1);
}
}
} // namespace
ALSAOutput::ALSAOutput(int sample_rate, int num_channels)
: sample_rate(sample_rate), num_channels(num_channels)
{
die_on_error("snd_pcm_open()", snd_pcm_open(&pcm_handle, "default", SND_PCM_STREAM_PLAYBACK, 0));
// Set format.
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
die_on_error("snd_pcm_hw_params_any()", snd_pcm_hw_params_any(pcm_handle, hw_params));
die_on_error("snd_pcm_hw_params_set_access()", snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED));
die_on_error("snd_pcm_hw_params_set_format()", snd_pcm_hw_params_set_format(pcm_handle, hw_params, SND_PCM_FORMAT_FLOAT_LE));
die_on_error("snd_pcm_hw_params_set_rate()", snd_pcm_hw_params_set_rate(pcm_handle, hw_params, sample_rate, 0));
die_on_error("snd_pcm_hw_params_set_channels", snd_pcm_hw_params_set_channels(pcm_handle, hw_params, num_channels));
// Fragment size of 512 samples. (A frame at 60 fps/48 kHz is 800 samples.)
// We ask for 16 such periods (~170 ms buffer).
unsigned int num_periods = 16;
int dir = 0;
die_on_error("snd_pcm_hw_params_set_periods_near()", snd_pcm_hw_params_set_periods_near(pcm_handle, hw_params, &num_periods, &dir));
period_size = 512;
dir = 0;
die_on_error("snd_pcm_hw_params_set_period_size_near()", snd_pcm_hw_params_set_period_size_near(pcm_handle, hw_params, &period_size, &dir));
die_on_error("snd_pcm_hw_params()", snd_pcm_hw_params(pcm_handle, hw_params));
//snd_pcm_hw_params_free(hw_params);
snd_pcm_sw_params_t *sw_params;
snd_pcm_sw_params_alloca(&sw_params);
die_on_error("snd_pcm_sw_params_current()", snd_pcm_sw_params_current(pcm_handle, sw_params));
die_on_error("snd_pcm_sw_params_set_start_threshold", snd_pcm_sw_params_set_start_threshold(pcm_handle, sw_params, num_periods * period_size / 2));
die_on_error("snd_pcm_sw_params()", snd_pcm_sw_params(pcm_handle, sw_params));
die_on_error("snd_pcm_nonblock", snd_pcm_nonblock(pcm_handle, 1));
die_on_error("snd_pcm_prepare()", snd_pcm_prepare(pcm_handle));
}
void ALSAOutput::write(const vector &samples)
{
buffer.insert(buffer.end(), samples.begin(), samples.end());
try_again:
int periods_to_write = buffer.size() / (period_size * num_channels);
if (periods_to_write == 0) {
return;
}
int ret = snd_pcm_writei(pcm_handle, buffer.data(), periods_to_write * period_size);
if (ret == -EPIPE) {
fprintf(stderr, "warning: snd_pcm_writei() reported underrun\n");
snd_pcm_recover(pcm_handle, ret, 1);
goto try_again;
} else if (ret == -EAGAIN) {
ret = 0;
} else if (ret < 0) {
fprintf(stderr, "error: snd_pcm_writei() returned '%s'\n", snd_strerror(ret));
exit(1);
} else if (ret > 0) {
buffer.erase(buffer.begin(), buffer.begin() + ret * num_channels);
}
if (buffer.size() >= period_size * num_channels) { // Still more to write.
if (ret == 0) {
if (buffer.size() >= period_size * num_channels * 8) {
// OK, almost 100 ms. Giving up.
fprintf(stderr, "warning: ALSA overrun, dropping some audio (%d ms)\n",
int(buffer.size() * 1000 / (num_channels * sample_rate)));
buffer.clear();
}
} else if (ret > 0) {
// Not a completely failure (effectively a short write),
// possibly due to a signal.
goto try_again;
}
}
}
nageru-1.6.4/alsa_output.h 0000664 0000000 0000000 00000001271 13232411367 0015517 0 ustar 00root root 0000000 0000000 #ifndef _ALSA_OUTPUT_H
#define _ALSA_OUTPUT_H 1
// Extremely minimalistic ALSA output. Will not resample to fit
// sound card clock, will not care much about over- or underflows
// (so it will not block), will not care about A/V sync.
//
// This means that if you run it for long enough, clocks will
// probably drift out of sync enough to make a little pop.
#include
#include
class ALSAOutput {
public:
ALSAOutput(int sample_rate, int num_channels);
void write(const std::vector &samples);
private:
snd_pcm_t *pcm_handle;
std::vector buffer;
snd_pcm_uframes_t period_size;
int sample_rate, num_channels;
};
#endif // !defined(_ALSA_OUTPUT_H)
nageru-1.6.4/alsa_pool.cpp 0000664 0000000 0000000 00000036331 13232411367 0015470 0 ustar 00root root 0000000 0000000 #include "alsa_pool.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "alsa_input.h"
#include "audio_mixer.h"
#include "defs.h"
#include "input_mapping.h"
#include "state.pb.h"
using namespace std;
using namespace std::placeholders;
ALSAPool::ALSAPool()
{
should_quit_fd = eventfd(/*initval=*/0, /*flags=*/0);
assert(should_quit_fd != -1);
}
ALSAPool::~ALSAPool()
{
for (Device &device : devices) {
if (device.input != nullptr) {
device.input->stop_capture_thread();
}
}
should_quit = true;
const uint64_t one = 1;
if (write(should_quit_fd, &one, sizeof(one)) != sizeof(one)) {
perror("write(should_quit_fd)");
exit(1);
}
inotify_thread.join();
while (retry_threads_running > 0) {
this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
std::vector ALSAPool::get_devices()
{
lock_guard lock(mu);
for (Device &device : devices) {
device.held = true;
}
return devices;
}
void ALSAPool::hold_device(unsigned index)
{
lock_guard lock(mu);
assert(index < devices.size());
devices[index].held = true;
}
void ALSAPool::release_device(unsigned index)
{
lock_guard lock(mu);
if (index < devices.size()) {
devices[index].held = false;
}
}
void ALSAPool::enumerate_devices()
{
// Enumerate all cards.
for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) {
char address[256];
snprintf(address, sizeof(address), "hw:%d", card_index);
snd_ctl_t *ctl;
int err = snd_ctl_open(&ctl, address, 0);
if (err < 0) {
printf("%s: %s\n", address, snd_strerror(err));
continue;
}
unique_ptr ctl_closer(ctl, snd_ctl_close);
// Enumerate all devices on this card.
for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
probe_device_with_retry(card_index, dev_index);
}
}
}
void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
{
char address[256];
snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
lock_guard lock(add_device_mutex);
if (add_device_tries_left.count(address)) {
// Some thread is already busy retrying this,
// so just reset its count.
add_device_tries_left[address] = num_retries;
return;
}
// Try (while still holding the lock) to add the device synchronously.
ProbeResult result = probe_device_once(card_index, dev_index);
if (result == ProbeResult::SUCCESS) {
return;
} else if (result == ProbeResult::FAILURE) {
return;
}
assert(result == ProbeResult::DEFER);
// Add failed for whatever reason (probably just that the device
// isn't up yet. Set up a count so that nobody else starts a thread,
// then start it ourselves.
fprintf(stderr, "Trying %s again in one second...\n", address);
add_device_tries_left[address] = num_retries;
++retry_threads_running;
thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
}
void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
{
char address[256];
snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
char thread_name[16];
snprintf(thread_name, sizeof(thread_name), "Reprobe_hw:%d,%d", card_index, dev_index);
pthread_setname_np(pthread_self(), thread_name);
for ( ;; ) { // Termination condition within the loop.
sleep(1);
// See if there are any retries left.
lock_guard lock(add_device_mutex);
if (should_quit ||
!add_device_tries_left.count(address) ||
add_device_tries_left[address] == 0) {
add_device_tries_left.erase(address);
fprintf(stderr, "Giving up probe of %s.\n", address);
break;
}
// Seemingly there were. Give it a try (we still hold the mutex).
ProbeResult result = probe_device_once(card_index, dev_index);
if (result == ProbeResult::SUCCESS) {
add_device_tries_left.erase(address);
fprintf(stderr, "Probe of %s succeeded.\n", address);
break;
} else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
add_device_tries_left.erase(address);
fprintf(stderr, "Giving up probe of %s.\n", address);
break;
}
// Failed again.
assert(result == ProbeResult::DEFER);
fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
address, add_device_tries_left[address]);
}
--retry_threads_running;
}
ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
{
char address[256];
snprintf(address, sizeof(address), "hw:%d", card_index);
snd_ctl_t *ctl;
int err = snd_ctl_open(&ctl, address, 0);
if (err < 0) {
printf("%s: %s\n", address, snd_strerror(err));
return ALSAPool::ProbeResult::DEFER;
}
unique_ptr ctl_closer(ctl, snd_ctl_close);
snd_pcm_info_t *pcm_info;
snd_pcm_info_alloca(&pcm_info);
snd_pcm_info_set_device(pcm_info, dev_index);
snd_pcm_info_set_subdevice(pcm_info, 0);
snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
// Not available for capture.
printf("%s: Not available for capture.\n", address);
return ALSAPool::ProbeResult::DEFER;
}
snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
unsigned num_channels = 0;
// Find all channel maps for this device, and pick out the one
// with the most channels.
snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE);
if (cmaps != nullptr) {
for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) {
num_channels = max(num_channels, (*ptr)->map.channels);
}
snd_pcm_free_chmaps(cmaps);
}
if (num_channels == 0) {
// Device had no channel maps. We need to open it to query.
// TODO: Do this asynchronously.
snd_pcm_t *pcm_handle;
int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
if (err < 0) {
printf("%s: %s\n", address, snd_strerror(err));
return ALSAPool::ProbeResult::DEFER;
}
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
unsigned sample_rate;
if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
snd_pcm_close(pcm_handle);
return ALSAPool::ProbeResult::DEFER;
}
err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
if (err < 0) {
fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
address, snd_strerror(err));
snd_pcm_close(pcm_handle);
return ALSAPool::ProbeResult::DEFER;
}
snd_pcm_close(pcm_handle);
}
if (num_channels == 0) {
printf("%s: No channel maps with channels\n", address);
return ALSAPool::ProbeResult::FAILURE;
}
snd_ctl_card_info_t *card_info;
snd_ctl_card_info_alloca(&card_info);
snd_ctl_card_info(ctl, card_info);
string name = snd_ctl_card_info_get_name(card_info);
string info = snd_pcm_info_get_name(pcm_info);
unsigned internal_dev_index;
string display_name;
{
lock_guard lock(mu);
internal_dev_index = find_free_device_index(name, info, num_channels, address);
devices[internal_dev_index].address = address;
devices[internal_dev_index].name = name;
devices[internal_dev_index].info = info;
devices[internal_dev_index].num_channels = num_channels;
// Note: Purposefully does not overwrite held.
display_name = devices[internal_dev_index].display_name();
}
fprintf(stderr, "%s: Probed successfully.\n", address);
reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card).
DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index};
global_audio_mixer->set_display_name(spec, display_name);
global_audio_mixer->trigger_state_changed_callback();
return ALSAPool::ProbeResult::SUCCESS;
}
void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index)
{
char address[256];
snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
for (unsigned i = 0; i < devices.size(); ++i) {
if (devices[i].state != Device::State::EMPTY &&
devices[i].state != Device::State::DEAD &&
devices[i].address == address) {
free_card(i);
}
}
}
void ALSAPool::init()
{
inotify_thread = thread(&ALSAPool::inotify_thread_func, this);
enumerate_devices();
}
void ALSAPool::inotify_thread_func()
{
pthread_setname_np(pthread_self(), "ALSA_Hotplug");
int inotify_fd = inotify_init();
if (inotify_fd == -1) {
perror("inotify_init()");
fprintf(stderr, "No hotplug of ALSA devices available.\n");
return;
}
int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
if (watch_fd == -1) {
perror("inotify_add_watch()");
fprintf(stderr, "No hotplug of ALSA devices available.\n");
close(inotify_fd);
return;
}
int size = sizeof(inotify_event) + NAME_MAX + 1;
unique_ptr buf(new char[size]);
while (!should_quit) {
pollfd fds[2];
fds[0].fd = inotify_fd;
fds[0].events = POLLIN;
fds[0].revents = 0;
fds[1].fd = should_quit_fd;
fds[1].events = POLLIN;
fds[1].revents = 0;
int ret = poll(fds, 2, -1);
if (ret == -1) {
if (errno == EINTR) {
continue;
} else {
perror("poll(inotify_fd)");
return;
}
}
if (ret == 0) {
continue;
}
if (fds[1].revents) break; // should_quit_fd asserted.
ret = read(inotify_fd, buf.get(), size);
if (ret == -1) {
if (errno == EINTR) {
continue;
} else {
perror("read(inotify_fd)");
close(watch_fd);
close(inotify_fd);
return;
}
}
if (ret < int(sizeof(inotify_event))) {
fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
int(ret));
close(watch_fd);
close(inotify_fd);
return;
}
for (int i = 0; i < ret; ) {
const inotify_event *event = reinterpret_cast(&buf[i]);
i += sizeof(inotify_event) + event->len;
if (event->mask & IN_Q_OVERFLOW) {
fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
continue;
}
unsigned card, device;
char type;
if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
printf("Deleted capture device: Card %u, device %u\n", card, device);
unplug_device(card, device);
}
if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
printf("Adding capture device: Card %u, device %u\n", card, device);
probe_device_with_retry(card, device);
}
}
}
}
close(watch_fd);
close(inotify_fd);
close(should_quit_fd);
}
void ALSAPool::reset_device(unsigned index)
{
lock_guard lock(mu);
Device *device = &devices[index];
if (inputs[index] != nullptr) {
inputs[index]->stop_capture_thread();
}
if (!device->held) {
inputs[index].reset();
} else {
// TODO: Put on a background thread instead of locking?
auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4, _5);
inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
inputs[index]->start_capture_thread();
}
device->input = inputs[index].get();
}
unsigned ALSAPool::get_capture_frequency(unsigned index)
{
lock_guard lock(mu);
assert(devices[index].held);
if (devices[index].input)
return devices[index].input->get_sample_rate();
else
return OUTPUT_FREQUENCY;
}
ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
{
lock_guard lock(mu);
assert(devices[index].held);
return devices[index].state;
}
void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
{
{
lock_guard lock(mu);
devices[index].state = state;
}
DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
bool silence = (state != ALSAPool::Device::State::RUNNING);
while (!global_audio_mixer->silence_card(spec, silence))
;
global_audio_mixer->trigger_state_changed_callback();
}
unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address)
{
// First try to find an exact match on a dead card.
for (unsigned i = 0; i < devices.size(); ++i) {
if (devices[i].state == Device::State::DEAD &&
devices[i].address == address &&
devices[i].name == name &&
devices[i].info == info &&
devices[i].num_channels == num_channels) {
devices[i].state = Device::State::READY;
return i;
}
}
// Then try to find a match on everything but the address
// (probably that devices were plugged back in a different order).
// If we have two cards that are equal, this might get them mixed up,
// but we don't have anything better.
for (unsigned i = 0; i < devices.size(); ++i) {
if (devices[i].state == Device::State::DEAD &&
devices[i].name == name &&
devices[i].info == info &&
devices[i].num_channels == num_channels) {
devices[i].state = Device::State::READY;
return i;
}
}
// OK, so we didn't find a match; see if there are any empty slots.
for (unsigned i = 0; i < devices.size(); ++i) {
if (devices[i].state == Device::State::EMPTY) {
devices[i].state = Device::State::READY;
devices[i].held = false;
return i;
}
}
// Failing that, we just insert the new device at the end.
Device new_dev;
new_dev.state = Device::State::READY;
new_dev.held = false;
devices.push_back(new_dev);
inputs.emplace_back(nullptr);
return devices.size() - 1;
}
unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels)
{
lock_guard lock(mu);
// See if there are any empty slots. If not, insert one at the end.
vector::iterator free_device =
find_if(devices.begin(), devices.end(),
[](const Device &device) { return device.state == Device::State::EMPTY; });
if (free_device == devices.end()) {
devices.push_back(Device());
inputs.emplace_back(nullptr);
free_device = devices.end() - 1;
}
free_device->state = Device::State::DEAD;
free_device->name = name;
free_device->info = info;
free_device->num_channels = num_channels;
free_device->held = true;
return distance(devices.begin(), free_device);
}
void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized)
{
lock_guard lock(mu);
assert(index < devices.size());
assert(devices[index].held);
serialized->set_type(DeviceSpecProto::ALSA_INPUT);
serialized->set_index(index);
serialized->set_display_name(devices[index].display_name());
serialized->set_alsa_name(devices[index].name);
serialized->set_alsa_info(devices[index].info);
serialized->set_num_channels(devices[index].num_channels);
serialized->set_address(devices[index].address);
}
void ALSAPool::free_card(unsigned index)
{
DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
while (!global_audio_mixer->silence_card(spec, true))
;
{
lock_guard lock(mu);
if (devices[index].held) {
devices[index].state = Device::State::DEAD;
} else {
devices[index].state = Device::State::EMPTY;
inputs[index].reset();
}
while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
devices.pop_back();
inputs.pop_back();
}
}
global_audio_mixer->trigger_state_changed_callback();
}
nageru-1.6.4/alsa_pool.h 0000664 0000000 0000000 00000012676 13232411367 0015143 0 ustar 00root root 0000000 0000000 #ifndef _ALSA_POOL_H
#define _ALSA_POOL_H 1
#include
#include
#include
#include
#include
#include
#include
class ALSAInput;
class DeviceSpecProto;
// The class dealing with the collective of all ALSA cards in the system.
// In particular, it deals with enumeration of cards, and hotplug of new ones.
class ALSAPool {
public:
ALSAPool();
~ALSAPool();
struct Device {
enum class State {
// There is no card here. (There probably used to be one,
// but it got removed.) We don't insert a card before
// we've actually probed it, ie., we know whether it
// can be captured from at all, and what its name is.
EMPTY,
// This card is ready for capture, as far as we know.
// (It could still be used by someone else; we don't know
// until we try to open it.)
READY,
// We are trying to start capture from this card, but we are not
// streaming yet. Note that this could in theory go on forever,
// if the card is in use by some other process; in the UI,
// we will show this state as “(busy)”.
STARTING,
// The card is capturing and sending data. If there's a fatal error,
// it could go back to STARTING, or it could go to DEAD
// (depending on the error).
RUNNING,
// The card is gone (e.g., unplugged). However, since there's
// still a bus using it, we can't just remove the entry.
// If the card comes back (ie., a new card is plugged in,
// and we believe it has the same configuration), it could be
// installed in place of this card, and then presumably be put
// back into STARTING or RUNNING.
DEAD
} state = State::EMPTY;
std::string address; // E.g. “hw:0,0”.
std::string name, info;
unsigned num_channels;
ALSAInput *input = nullptr; // nullptr iff EMPTY or DEAD.
// Whether the AudioMixer is interested in this card or not.
// “Interested” could mean either of two things: Either it is part of
// a bus mapping, or it is in the process of enumerating devices
// (to show to the user). A card that is _not_ held can disappear
// at any given time as a result of an error or hotplug event;
// a card that is held will go to the DEAD state instead.
bool held = false;
std::string display_name() const { return name + " (" + info + ")"; }
};
void init();
// Get the list of all current devices. Note that this will implicitly mark
// all of the returned devices as held, since the input mapping UI needs
// some kind of stability when the user is to choose. Thus, when you are done
// with the list and have set a new mapping, you must go through all the devices
// you don't want and release them using release_device().
std::vector get_devices();
void hold_device(unsigned index);
void release_device(unsigned index); // Note: index is allowed to go out of bounds.
// If device is held, start or restart capture. If device is not held,
// stop capture if it isn't already.
void reset_device(unsigned index);
// Note: The card must be held. Returns OUTPUT_FREQUENCY if the card is in EMPTY or DEAD.
unsigned get_capture_frequency(unsigned index);
// Note: The card must be held.
Device::State get_card_state(unsigned index);
// Only for ALSAInput.
void set_card_state(unsigned index, Device::State state);
// Just a short form for taking and then moving the card to
// EMPTY or DEAD state. Only for ALSAInput and for internal use.
void free_card(unsigned index);
// Create a new card, mark it immediately as DEAD and hold it.
// Returns the new index.
unsigned create_dead_card(const std::string &name, const std::string &info, unsigned num_channels);
// Make a protobuf representation of the given card, so that it can be
// matched against at a later stage. For AudioMixer only.
// The given card must be held.
void serialize_device(unsigned index, DeviceSpecProto *serialized);
private:
mutable std::mutex mu;
std::vector devices; // Under mu.
std::vector> inputs; // Under mu, corresponds 1:1 to devices.
// Keyed on device address (e.g. “hw:0,0”). If there's an entry here,
// it means we already have a thread doing retries, so we shouldn't
// start a new one.
std::unordered_map add_device_tries_left; // Under add_device_mutex.
std::mutex add_device_mutex;
static constexpr int num_retries = 10;
void inotify_thread_func();
void enumerate_devices();
// Try to add an input at the given card/device. If it succeeds, return
// synchronously. If not, fire off a background thread to try up to
// times.
void probe_device_with_retry(unsigned card_index, unsigned dev_index);
void probe_device_retry_thread_func(unsigned card_index, unsigned dev_index);
enum class ProbeResult {
SUCCESS,
DEFER,
FAILURE
};
ProbeResult probe_device_once(unsigned card_index, unsigned dev_index);
void unplug_device(unsigned card_index, unsigned dev_index);
// Must be called with held. Will allocate a new entry if needed.
// The returned entry will be set to READY state.
unsigned find_free_device_index(const std::string &name,
const std::string &info,
unsigned num_channels,
const std::string &address);
std::atomic should_quit{false};
int should_quit_fd;
std::thread inotify_thread;
std::atomic retry_threads_running{0};
friend class ALSAInput;
};
#endif // !defined(_ALSA_POOL_H)
nageru-1.6.4/analyzer.cpp 0000664 0000000 0000000 00000030077 13232411367 0015345 0 ustar 00root root 0000000 0000000 #include "analyzer.h"
#include
#include
#include
#include
#include
#include
#include
#include "context.h"
#include "flags.h"
#include "mixer.h"
#include "ui_analyzer.h"
// QCustomPlot includes qopenglfunctions.h, which #undefs all of the epoxy
// definitions (ugh) and doesn't put back any others (ugh). Add the ones we
// need back.
#define glBindBuffer epoxy_glBindBuffer
#define glBindFramebuffer epoxy_glBindFramebuffer
#define glBufferData epoxy_glBufferData
#define glDeleteBuffers epoxy_glDeleteBuffers
#define glDisable epoxy_glDisable
#define glGenBuffers epoxy_glGenBuffers
#define glGetError epoxy_glGetError
#define glReadPixels epoxy_glReadPixels
#define glUnmapBuffer epoxy_glUnmapBuffer
#define glWaitSync epoxy_glWaitSync
using namespace std;
Analyzer::Analyzer()
: ui(new Ui::Analyzer),
grabbed_image(global_flags.width, global_flags.height, QImage::Format_ARGB32_Premultiplied)
{
ui->setupUi(this);
surface = create_surface(QSurfaceFormat::defaultFormat());
context = create_context(surface);
if (!make_current(context, surface)) {
printf("oops\n");
exit(1);
}
grab_timer.setSingleShot(true);
connect(&grab_timer, &QTimer::timeout, bind(&Analyzer::grab_clicked, this));
ui->input_box->addItem("Live", Mixer::OUTPUT_LIVE);
ui->input_box->addItem("Preview", Mixer::OUTPUT_PREVIEW);
unsigned num_channels = global_mixer->get_num_channels();
for (unsigned channel_idx = 0; channel_idx < num_channels; ++channel_idx) {
Mixer::Output channel = static_cast(Mixer::OUTPUT_INPUT0 + channel_idx);
string name = global_mixer->get_channel_name(channel);
ui->input_box->addItem(QString::fromStdString(name), channel);
}
ui->grab_frequency_box->addItem("Never", 0);
ui->grab_frequency_box->addItem("100 ms", 100);
ui->grab_frequency_box->addItem("1 sec", 1000);
ui->grab_frequency_box->addItem("10 sec", 10000);
ui->grab_frequency_box->setCurrentIndex(2);
connect(ui->grab_btn, &QPushButton::clicked, bind(&Analyzer::grab_clicked, this));
connect(ui->input_box, static_cast(&QComboBox::currentIndexChanged), bind(&Analyzer::signal_changed, this));
signal_changed();
ui->grabbed_frame_label->installEventFilter(this);
glGenBuffers(1, &pbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pbo);
glBufferData(GL_PIXEL_PACK_BUFFER_ARB, global_flags.width * global_flags.height * 4, nullptr, GL_STREAM_READ);
ui->histogram->xAxis->setVisible(true);
ui->histogram->yAxis->setVisible(false);
ui->histogram->xAxis->setRange(0, 255);
}
Analyzer::~Analyzer()
{
delete_context(context);
delete surface;
}
void Analyzer::update_channel_name(Mixer::Output output, const string &name)
{
if (output >= Mixer::OUTPUT_INPUT0) {
int index = (output - Mixer::OUTPUT_INPUT0) + 2;
ui->input_box->setItemText(index, QString::fromStdString(name));
}
}
void Analyzer::mixer_shutting_down()
{
ui->display->shutdown();
if (!make_current(context, surface)) {
printf("oops\n");
exit(1);
}
glDeleteBuffers(1, &pbo);
check_error();
if (resource_pool != nullptr) {
resource_pool->clean_context();
}
}
void Analyzer::grab_clicked()
{
Mixer::Output channel = static_cast(ui->input_box->currentData().value());
if (!make_current(context, surface)) {
printf("oops\n");
exit(1);
}
Mixer::DisplayFrame frame;
if (!global_mixer->get_display_frame(channel, &frame)) {
// Not ready yet.
return;
}
// Set up an FBO to render into.
if (resource_pool == nullptr) {
resource_pool = frame.chain->get_resource_pool();
} else {
assert(resource_pool == frame.chain->get_resource_pool());
}
GLuint fbo_tex = resource_pool->create_2d_texture(GL_RGBA8, global_flags.width, global_flags.height);
check_error();
GLuint fbo = resource_pool->create_fbo(fbo_tex);
check_error();
glWaitSync(frame.ready_fence.get(), /*flags=*/0, GL_TIMEOUT_IGNORED);
check_error();
frame.setup_chain();
check_error();
glDisable(GL_FRAMEBUFFER_SRGB);
check_error();
frame.chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
check_error();
// Read back to memory.
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
check_error();
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
check_error();
glReadPixels(0, 0, global_flags.width, global_flags.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, BUFFER_OFFSET(0));
check_error();
unsigned char *buf = (unsigned char *)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
check_error();
size_t pitch = global_flags.width * 4;
for (int y = 0; y < global_flags.height; ++y) {
memcpy(grabbed_image.scanLine(global_flags.height - y - 1), buf + y * pitch, pitch);
}
{
char buf[256];
snprintf(buf, sizeof(buf), "Grabbed frame (%dx%d)", global_flags.width, global_flags.height);
ui->grabbed_frame_sublabel->setText(buf);
}
QPixmap pixmap;
pixmap.convertFromImage(grabbed_image);
ui->grabbed_frame_label->setPixmap(pixmap);
int r_hist[256] = {0}, g_hist[256] = {0}, b_hist[256] = {0};
const unsigned char *ptr = buf;
for (int i = 0; i < global_flags.height * global_flags.width; ++i) {
uint8_t b = *ptr++;
uint8_t g = *ptr++;
uint8_t r = *ptr++;
++ptr;
++r_hist[r];
++g_hist[g];
++b_hist[b];
}
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
check_error();
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
check_error();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
check_error();
QVector r_vec(256), g_vec(256), b_vec(256), x_vec(256);
double max = 0.0;
for (unsigned i = 0; i < 256; ++i) {
x_vec[i] = i;
r_vec[i] = log(r_hist[i] + 1.0);
g_vec[i] = log(g_hist[i] + 1.0);
b_vec[i] = log(b_hist[i] + 1.0);
max = std::max(max, r_vec[i]);
max = std::max(max, g_vec[i]);
max = std::max(max, b_vec[i]);
}
ui->histogram->clearGraphs();
ui->histogram->addGraph();
ui->histogram->graph(0)->setData(x_vec, r_vec);
ui->histogram->graph(0)->setPen(QPen(Qt::red));
ui->histogram->graph(0)->setBrush(QBrush(QColor(255, 127, 127, 80)));
ui->histogram->addGraph();
ui->histogram->graph(1)->setData(x_vec, g_vec);
ui->histogram->graph(1)->setPen(QPen(Qt::green));
ui->histogram->graph(1)->setBrush(QBrush(QColor(127, 255, 127, 80)));
ui->histogram->addGraph();
ui->histogram->graph(2)->setData(x_vec, b_vec);
ui->histogram->graph(2)->setPen(QPen(Qt::blue));
ui->histogram->graph(2)->setBrush(QBrush(QColor(127, 127, 255, 80)));
ui->histogram->xAxis->setVisible(true);
ui->histogram->yAxis->setVisible(false);
ui->histogram->xAxis->setRange(0, 255);
ui->histogram->yAxis->setRange(0, max);
ui->histogram->replot();
resource_pool->release_2d_texture(fbo_tex);
check_error();
resource_pool->release_fbo(fbo);
check_error();
if (last_x >= 0 && last_y >= 0) {
grab_pixel(last_x, last_y);
}
if (isVisible()) {
grab_timer.stop();
// Set up the next autograb if configured.
int delay = ui->grab_frequency_box->currentData().toInt(nullptr);
if (delay > 0) {
grab_timer.start(delay);
}
}
}
void Analyzer::signal_changed()
{
Mixer::Output channel = static_cast(ui->input_box->currentData().value());
ui->display->set_output(channel);
grab_clicked();
}
bool Analyzer::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::MouseMove && watched->isWidgetType()) {
const QMouseEvent *mouse_event = (QMouseEvent *)event;
last_x = mouse_event->x();
last_y = mouse_event->y();
grab_pixel(mouse_event->x(), mouse_event->y());
}
if (event->type() == QEvent::Leave && watched->isWidgetType()) {
last_x = last_y = -1;
ui->coord_label->setText("Selected coordinate (x,y): (none)");
ui->red_label->setText(u8"—");
ui->green_label->setText(u8"—");
ui->blue_label->setText(u8"—");
ui->hex_label->setText(u8"#—");
}
return false;
}
void Analyzer::grab_pixel(int x, int y)
{
const QPixmap *pixmap = ui->grabbed_frame_label->pixmap();
if (pixmap != nullptr) {
x = lrint(x * double(pixmap->width()) / ui->grabbed_frame_label->width());
y = lrint(y * double(pixmap->height()) / ui->grabbed_frame_label->height());
x = std::min(x, pixmap->width() - 1);
y = std::min(y, pixmap->height() - 1);
char buf[256];
snprintf(buf, sizeof(buf), "Selected coordinate (x,y): (%d,%d)", x, y);
ui->coord_label->setText(buf);
QRgb pixel = grabbed_image.pixel(x, y);
ui->red_label->setText(QString::fromStdString(to_string(qRed(pixel))));
ui->green_label->setText(QString::fromStdString(to_string(qGreen(pixel))));
ui->blue_label->setText(QString::fromStdString(to_string(qBlue(pixel))));
snprintf(buf, sizeof(buf), "#%02x%02x%02x", qRed(pixel), qGreen(pixel), qBlue(pixel));
ui->hex_label->setText(buf);
}
}
void Analyzer::resizeEvent(QResizeEvent* event)
{
QMainWindow::resizeEvent(event);
// Ask for a relayout, but only after the event loop is done doing relayout
// on everything else.
QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
}
void Analyzer::showEvent(QShowEvent *event)
{
grab_clicked();
}
void Analyzer::relayout()
{
double aspect = double(global_flags.width) / global_flags.height;
// Left pane (2/5 of the width).
{
int width = ui->left_pane->geometry().width();
int height = ui->left_pane->geometry().height();
// Figure out how much space everything that's non-responsive needs.
int remaining_height = height - ui->left_pane->spacing() * (ui->left_pane->count() - 1);
remaining_height -= ui->input_box->geometry().height();
ui->left_pane->setStretch(2, ui->grab_btn->geometry().height());
remaining_height -= ui->grab_btn->geometry().height();
ui->left_pane->setStretch(3, ui->grab_btn->geometry().height());
remaining_height -= ui->histogram_label->geometry().height();
ui->left_pane->setStretch(5, ui->histogram_label->geometry().height());
// The histogram's minimumHeight returns 0, so let's set a reasonable minimum for it.
int min_histogram_height = 50;
remaining_height -= min_histogram_height;
// Allocate so that the display is 16:9, if possible.
unsigned wanted_display_height = width / aspect;
unsigned display_height;
unsigned margin = 0;
if (remaining_height >= int(wanted_display_height)) {
display_height = wanted_display_height;
} else {
display_height = remaining_height;
int display_width = lrint(display_height * aspect);
margin = (width - display_width) / 2;
}
ui->left_pane->setStretch(1, display_height);
ui->display_left_spacer->changeSize(margin, 1);
ui->display_right_spacer->changeSize(margin, 1);
remaining_height -= display_height;
// Figure out if we can do the histogram at 16:9.
remaining_height += min_histogram_height;
unsigned histogram_height;
if (remaining_height >= int(wanted_display_height)) {
histogram_height = wanted_display_height;
} else {
histogram_height = remaining_height;
}
remaining_height -= histogram_height;
ui->left_pane->setStretch(4, histogram_height);
ui->left_pane->setStretch(0, remaining_height / 2);
ui->left_pane->setStretch(6, remaining_height / 2);
}
// Right pane (remaining 3/5 of the width).
{
int width = ui->right_pane->geometry().width();
int height = ui->right_pane->geometry().height();
// Figure out how much space everything that's non-responsive needs.
int remaining_height = height - ui->right_pane->spacing() * (ui->right_pane->count() - 1);
remaining_height -= ui->grabbed_frame_sublabel->geometry().height();
remaining_height -= ui->coord_label->geometry().height();
remaining_height -= ui->color_hbox->geometry().height();
// Allocate so that the display is 16:9, if possible.
unsigned wanted_display_height = width / aspect;
unsigned display_height;
unsigned margin = 0;
if (remaining_height >= int(wanted_display_height)) {
display_height = wanted_display_height;
} else {
display_height = remaining_height;
int display_width = lrint(display_height * aspect);
margin = (width - display_width) / 2;
}
ui->right_pane->setStretch(1, display_height);
ui->grabbed_frame_left_spacer->changeSize(margin, 1);
ui->grabbed_frame_right_spacer->changeSize(margin, 1);
remaining_height -= display_height;
if (remaining_height < 0) remaining_height = 0;
ui->right_pane->setStretch(0, remaining_height / 2);
ui->right_pane->setStretch(5, remaining_height / 2);
}
}
nageru-1.6.4/analyzer.h 0000664 0000000 0000000 00000002032 13232411367 0015000 0 ustar 00root root 0000000 0000000 #ifndef _ANALYZER_H
#define _ANALYZER_H 1
#include
#include
#include
#include
#include
#include
#include "mixer.h"
class QObject;
class QOpenGLContext;
class QSurface;
namespace Ui {
class Analyzer;
} // namespace Ui
namespace movit {
class ResourcePool;
} // namespace movit
class Analyzer : public QMainWindow
{
Q_OBJECT
public:
Analyzer();
~Analyzer();
void update_channel_name(Mixer::Output output, const std::string &name);
void mixer_shutting_down();
public slots:
void relayout();
private:
void grab_clicked();
void signal_changed();
void grab_pixel(int x, int y);
bool eventFilter(QObject *watched, QEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void showEvent(QShowEvent *event) override;
Ui::Analyzer *ui;
QSurface *surface;
QOpenGLContext *context;
GLuint pbo;
movit::ResourcePool *resource_pool = nullptr;
QImage grabbed_image;
QTimer grab_timer;
int last_x = -1, last_y = -1;
};
#endif // !defined(_ANALYZER_H)
nageru-1.6.4/audio_encoder.cpp 0000664 0000000 0000000 00000012770 13232411367 0016320 0 ustar 00root root 0000000 0000000 #include "audio_encoder.h"
extern "C" {
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
}
#include
#include
#include
#include
#include
#include
#include
#include "defs.h"
#include "mux.h"
#include "timebase.h"
using namespace std;
AudioEncoder::AudioEncoder(const string &codec_name, int bit_rate, const AVOutputFormat *oformat)
{
AVCodec *codec = avcodec_find_encoder_by_name(codec_name.c_str());
if (codec == nullptr) {
fprintf(stderr, "ERROR: Could not find codec '%s'\n", codec_name.c_str());
exit(1);
}
ctx = avcodec_alloc_context3(codec);
ctx->bit_rate = bit_rate;
ctx->sample_rate = OUTPUT_FREQUENCY;
ctx->sample_fmt = codec->sample_fmts[0];
ctx->channels = 2;
ctx->channel_layout = AV_CH_LAYOUT_STEREO;
ctx->time_base = AVRational{1, TIMEBASE};
if (oformat->flags & AVFMT_GLOBALHEADER) {
ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
if (avcodec_open2(ctx, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec '%s'\n", codec_name.c_str());
exit(1);
}
resampler = avresample_alloc_context();
if (resampler == nullptr) {
fprintf(stderr, "Allocating resampler failed.\n");
exit(1);
}
av_opt_set_int(resampler, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
av_opt_set_int(resampler, "in_sample_rate", OUTPUT_FREQUENCY, 0);
av_opt_set_int(resampler, "out_sample_rate", OUTPUT_FREQUENCY, 0);
av_opt_set_int(resampler, "in_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
av_opt_set_int(resampler, "out_sample_fmt", ctx->sample_fmt, 0);
if (avresample_open(resampler) < 0) {
fprintf(stderr, "Could not open resample context.\n");
exit(1);
}
audio_frame = av_frame_alloc();
}
AudioEncoder::~AudioEncoder()
{
av_frame_free(&audio_frame);
avresample_free(&resampler);
avcodec_free_context(&ctx);
}
void AudioEncoder::encode_audio(const vector &audio, int64_t audio_pts)
{
if (ctx->frame_size == 0) {
// No queueing needed.
assert(audio_queue.empty());
assert(audio.size() % 2 == 0);
encode_audio_one_frame(&audio[0], audio.size() / 2, audio_pts);
return;
}
int64_t sample_offset = audio_queue.size();
audio_queue.insert(audio_queue.end(), audio.begin(), audio.end());
size_t sample_num;
for (sample_num = 0;
sample_num + ctx->frame_size * 2 <= audio_queue.size();
sample_num += ctx->frame_size * 2) {
int64_t adjusted_audio_pts = audio_pts + (int64_t(sample_num) - sample_offset) * TIMEBASE / (OUTPUT_FREQUENCY * 2);
encode_audio_one_frame(&audio_queue[sample_num],
ctx->frame_size,
adjusted_audio_pts);
}
audio_queue.erase(audio_queue.begin(), audio_queue.begin() + sample_num);
last_pts = audio_pts + audio.size() * TIMEBASE / (OUTPUT_FREQUENCY * 2);
}
void AudioEncoder::encode_audio_one_frame(const float *audio, size_t num_samples, int64_t audio_pts)
{
audio_frame->pts = audio_pts;
audio_frame->nb_samples = num_samples;
audio_frame->channel_layout = AV_CH_LAYOUT_STEREO;
audio_frame->format = ctx->sample_fmt;
audio_frame->sample_rate = OUTPUT_FREQUENCY;
if (av_samples_alloc(audio_frame->data, nullptr, 2, num_samples, ctx->sample_fmt, 0) < 0) {
fprintf(stderr, "Could not allocate %ld samples.\n", num_samples);
exit(1);
}
if (avresample_convert(resampler, audio_frame->data, 0, num_samples,
(uint8_t **)&audio, 0, num_samples) < 0) {
fprintf(stderr, "Audio conversion failed.\n");
exit(1);
}
int err = avcodec_send_frame(ctx, audio_frame);
if (err < 0) {
fprintf(stderr, "avcodec_send_frame() failed with error %d\n", err);
exit(1);
}
for ( ;; ) { // Termination condition within loop.
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = nullptr;
pkt.size = 0;
int err = avcodec_receive_packet(ctx, &pkt);
if (err == 0) {
pkt.stream_index = 1;
pkt.flags = 0;
for (Mux *mux : muxes) {
mux->add_packet(pkt, pkt.pts, pkt.dts);
}
av_packet_unref(&pkt);
} else if (err == AVERROR(EAGAIN)) {
break;
} else {
fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
exit(1);
}
}
av_freep(&audio_frame->data[0]);
av_frame_unref(audio_frame);
}
void AudioEncoder::encode_last_audio()
{
if (!audio_queue.empty()) {
// Last frame can be whatever size we want.
assert(audio_queue.size() % 2 == 0);
encode_audio_one_frame(&audio_queue[0], audio_queue.size() / 2, last_pts);
audio_queue.clear();
}
if (ctx->codec->capabilities & AV_CODEC_CAP_DELAY) {
// Collect any delayed frames.
for ( ;; ) {
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = nullptr;
pkt.size = 0;
int err = avcodec_receive_packet(ctx, &pkt);
if (err == 0) {
pkt.stream_index = 1;
pkt.flags = 0;
for (Mux *mux : muxes) {
mux->add_packet(pkt, pkt.pts, pkt.dts);
}
av_packet_unref(&pkt);
} else if (err == AVERROR_EOF) {
break;
} else {
fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
exit(1);
}
}
}
}
AVCodecParametersWithDeleter AudioEncoder::get_codec_parameters()
{
AVCodecParameters *codecpar = avcodec_parameters_alloc();
avcodec_parameters_from_context(codecpar, ctx);
return AVCodecParametersWithDeleter(codecpar);
}
nageru-1.6.4/audio_encoder.h 0000664 0000000 0000000 00000002143 13232411367 0015756 0 ustar 00root root 0000000 0000000 // A class to encode audio (using ffmpeg) and send it to a Mux.
#ifndef _AUDIO_ENCODER_H
#define _AUDIO_ENCODER_H 1
#include
#include
#include
#include
extern "C" {
#include
#include
#include
#include
}
#include "ffmpeg_raii.h"
class Mux;
class AudioEncoder {
public:
AudioEncoder(const std::string &codec_name, int bit_rate, const AVOutputFormat *oformat);
~AudioEncoder();
void add_mux(Mux *mux) { // Does not take ownership.
muxes.push_back(mux);
}
void encode_audio(const std::vector &audio, int64_t audio_pts);
void encode_last_audio();
AVCodecParametersWithDeleter get_codec_parameters();
private:
void encode_audio_one_frame(const float *audio, size_t num_samples, int64_t audio_pts);
std::vector audio_queue;
int64_t last_pts = 0; // The first pts after all audio we've encoded.
AVCodecContext *ctx;
AVAudioResampleContext *resampler;
AVFrame *audio_frame = nullptr;
std::vector muxes;
};
#endif // !defined(_AUDIO_ENCODER_H)
nageru-1.6.4/audio_mixer.cpp 0000664 0000000 0000000 00000117660 13232411367 0016031 0 ustar 00root root 0000000 0000000 #include "audio_mixer.h"
#include
#include
#include
#include
#ifdef __SSE2__
#include
#endif
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "db.h"
#include "flags.h"
#include "metrics.h"
#include "state.pb.h"
#include "timebase.h"
using namespace bmusb;
using namespace std;
using namespace std::chrono;
using namespace std::placeholders;
namespace {
// TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
// (usually including multiple channels at a time).
void convert_fixed16_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
const uint8_t *src, size_t in_channel, size_t in_num_channels,
size_t num_samples)
{
assert(in_channel < in_num_channels);
assert(out_channel < out_num_channels);
src += in_channel * 2;
dst += out_channel;
for (size_t i = 0; i < num_samples; ++i) {
int16_t s = le16toh(*(int16_t *)src);
*dst = s * (1.0f / 32768.0f);
src += 2 * in_num_channels;
dst += out_num_channels;
}
}
void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
const uint8_t *src, size_t in_channel, size_t in_num_channels,
size_t num_samples)
{
assert(in_channel < in_num_channels);
assert(out_channel < out_num_channels);
src += in_channel * 3;
dst += out_channel;
for (size_t i = 0; i < num_samples; ++i) {
uint32_t s1 = src[0];
uint32_t s2 = src[1];
uint32_t s3 = src[2];
uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
*dst = int(s) * (1.0f / 2147483648.0f);
src += 3 * in_num_channels;
dst += out_num_channels;
}
}
void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
const uint8_t *src, size_t in_channel, size_t in_num_channels,
size_t num_samples)
{
assert(in_channel < in_num_channels);
assert(out_channel < out_num_channels);
src += in_channel * 4;
dst += out_channel;
for (size_t i = 0; i < num_samples; ++i) {
int32_t s = le32toh(*(int32_t *)src);
*dst = s * (1.0f / 2147483648.0f);
src += 4 * in_num_channels;
dst += out_num_channels;
}
}
float find_peak_plain(const float *samples, size_t num_samples) __attribute__((unused));
float find_peak_plain(const float *samples, size_t num_samples)
{
float m = fabs(samples[0]);
for (size_t i = 1; i < num_samples; ++i) {
m = max(m, fabs(samples[i]));
}
return m;
}
#ifdef __SSE__
static inline float horizontal_max(__m128 m)
{
__m128 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 0, 3, 2));
m = _mm_max_ps(m, tmp);
tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 3, 0, 1));
m = _mm_max_ps(m, tmp);
return _mm_cvtss_f32(m);
}
float find_peak(const float *samples, size_t num_samples)
{
const __m128 abs_mask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffu));
__m128 m = _mm_setzero_ps();
for (size_t i = 0; i < (num_samples & ~3); i += 4) {
__m128 x = _mm_loadu_ps(samples + i);
x = _mm_and_ps(x, abs_mask);
m = _mm_max_ps(m, x);
}
float result = horizontal_max(m);
for (size_t i = (num_samples & ~3); i < num_samples; ++i) {
result = max(result, fabs(samples[i]));
}
#if 0
// Self-test. We should be bit-exact the same.
float reference_result = find_peak_plain(samples, num_samples);
if (result != reference_result) {
fprintf(stderr, "Error: Peak is %f [%f %f %f %f]; should be %f.\n",
result,
_mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(0, 0, 0, 0))),
_mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1))),
_mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2))),
_mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(3, 3, 3, 3))),
reference_result);
abort();
}
#endif
return result;
}
#else
float find_peak(const float *samples, size_t num_samples)
{
return find_peak_plain(samples, num_samples);
}
#endif
void deinterleave_samples(const vector &in, vector *out_l, vector *out_r)
{
size_t num_samples = in.size() / 2;
out_l->resize(num_samples);
out_r->resize(num_samples);
const float *inptr = in.data();
float *lptr = &(*out_l)[0];
float *rptr = &(*out_r)[0];
for (size_t i = 0; i < num_samples; ++i) {
*lptr++ = *inptr++;
*rptr++ = *inptr++;
}
}
} // namespace
AudioMixer::AudioMixer(unsigned num_cards)
: num_cards(num_cards),
limiter(OUTPUT_FREQUENCY),
correlation(OUTPUT_FREQUENCY)
{
for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) {
locut[bus_index].init(FILTER_HPF, 2);
eq[bus_index][EQ_BAND_BASS].init(FILTER_LOW_SHELF, 1);
// Note: EQ_BAND_MID isn't used (see comments in apply_eq()).
eq[bus_index][EQ_BAND_TREBLE].init(FILTER_HIGH_SHELF, 1);
compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
set_bus_settings(bus_index, get_default_bus_settings());
}
set_limiter_enabled(global_flags.limiter_enabled);
set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
r128.init(2, OUTPUT_FREQUENCY);
r128.integr_start();
// hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
// and there's a limit to how important the peak meter is.
peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
global_audio_mixer = this;
alsa_pool.init();
if (!global_flags.input_mapping_filename.empty()) {
// Must happen after ALSAPool is initialized, as it needs to know the card list.
current_mapping_mode = MappingMode::MULTICHANNEL;
InputMapping new_input_mapping;
if (!load_input_mapping_from_file(get_devices(),
global_flags.input_mapping_filename,
&new_input_mapping)) {
fprintf(stderr, "Failed to load input mapping from '%s', exiting.\n",
global_flags.input_mapping_filename.c_str());
exit(1);
}
set_input_mapping(new_input_mapping);
} else {
set_simple_input(/*card_index=*/0);
if (global_flags.multichannel_mapping_mode) {
current_mapping_mode = MappingMode::MULTICHANNEL;
}
}
global_metrics.add("audio_loudness_short_lufs", &metric_audio_loudness_short_lufs, Metrics::TYPE_GAUGE);
global_metrics.add("audio_loudness_integrated_lufs", &metric_audio_loudness_integrated_lufs, Metrics::TYPE_GAUGE);
global_metrics.add("audio_loudness_range_low_lufs", &metric_audio_loudness_range_low_lufs, Metrics::TYPE_GAUGE);
global_metrics.add("audio_loudness_range_high_lufs", &metric_audio_loudness_range_high_lufs, Metrics::TYPE_GAUGE);
global_metrics.add("audio_peak_dbfs", &metric_audio_peak_dbfs, Metrics::TYPE_GAUGE);
global_metrics.add("audio_final_makeup_gain_db", &metric_audio_final_makeup_gain_db, Metrics::TYPE_GAUGE);
global_metrics.add("audio_correlation", &metric_audio_correlation, Metrics::TYPE_GAUGE);
}
void AudioMixer::reset_resampler(DeviceSpec device_spec)
{
lock_guard lock(audio_mutex);
reset_resampler_mutex_held(device_spec);
}
void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec)
{
AudioDevice *device = find_audio_device(device_spec);
if (device->interesting_channels.empty()) {
device->resampling_queue.reset();
} else {
// TODO: ResamplingQueue should probably take the full device spec.
// (It's only used for console output, though.)
device->resampling_queue.reset(new ResamplingQueue(
device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size(),
global_flags.audio_queue_length_ms * 0.001));
}
}
bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length, steady_clock::time_point frame_time)
{
AudioDevice *device = find_audio_device(device_spec);
unique_lock lock(audio_mutex, defer_lock);
if (!lock.try_lock_for(chrono::milliseconds(10))) {
return false;
}
if (device->resampling_queue == nullptr) {
// No buses use this device; throw it away.
return true;
}
unsigned num_channels = device->interesting_channels.size();
assert(num_channels > 0);
// Convert the audio to fp32.
unique_ptr audio(new float[num_samples * num_channels]);
unsigned channel_index = 0;
for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
switch (audio_format.bits_per_sample) {
case 0:
assert(num_samples == 0);
break;
case 16:
convert_fixed16_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
break;
case 24:
convert_fixed24_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
break;
case 32:
convert_fixed32_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
break;
default:
fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
assert(false);
}
}
// If we changed frequency since last frame, we'll need to reset the resampler.
if (audio_format.sample_rate != device->capture_frequency) {
device->capture_frequency = audio_format.sample_rate;
reset_resampler_mutex_held(device_spec);
}
// Now add it.
device->resampling_queue->add_input_samples(frame_time, audio.get(), num_samples, ResamplingQueue::ADJUST_RATE);
return true;
}
bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
{
AudioDevice *device = find_audio_device(device_spec);
unique_lock lock(audio_mutex, defer_lock);
if (!lock.try_lock_for(chrono::milliseconds(10))) {
return false;
}
if (device->resampling_queue == nullptr) {
// No buses use this device; throw it away.
return true;
}
unsigned num_channels = device->interesting_channels.size();
assert(num_channels > 0);
vector silence(samples_per_frame * num_channels, 0.0f);
for (unsigned i = 0; i < num_frames; ++i) {
device->resampling_queue->add_input_samples(steady_clock::now(), silence.data(), samples_per_frame, ResamplingQueue::DO_NOT_ADJUST_RATE);
}
return true;
}
bool AudioMixer::silence_card(DeviceSpec device_spec, bool silence)
{
AudioDevice *device = find_audio_device(device_spec);
unique_lock lock(audio_mutex, defer_lock);
if (!lock.try_lock_for(chrono::milliseconds(10))) {
return false;
}
if (device->silenced && !silence) {
reset_resampler_mutex_held(device_spec);
}
device->silenced = silence;
return true;
}
AudioMixer::BusSettings AudioMixer::get_default_bus_settings()
{
BusSettings settings;
settings.fader_volume_db = 0.0f;
settings.muted = false;
settings.locut_enabled = global_flags.locut_enabled;
for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
settings.eq_level_db[band_index] = 0.0f;
}
settings.gain_staging_db = global_flags.initial_gain_staging_db;
settings.level_compressor_enabled = global_flags.gain_staging_auto;
settings.compressor_threshold_dbfs = ref_level_dbfs - 12.0f; // -12 dB.
settings.compressor_enabled = global_flags.compressor_enabled;
return settings;
}
AudioMixer::BusSettings AudioMixer::get_bus_settings(unsigned bus_index) const
{
lock_guard lock(audio_mutex);
BusSettings settings;
settings.fader_volume_db = fader_volume_db[bus_index];
settings.muted = mute[bus_index];
settings.locut_enabled = locut_enabled[bus_index];
for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
settings.eq_level_db[band_index] = eq_level_db[bus_index][band_index];
}
settings.gain_staging_db = gain_staging_db[bus_index];
settings.level_compressor_enabled = level_compressor_enabled[bus_index];
settings.compressor_threshold_dbfs = compressor_threshold_dbfs[bus_index];
settings.compressor_enabled = compressor_enabled[bus_index];
return settings;
}
void AudioMixer::set_bus_settings(unsigned bus_index, const AudioMixer::BusSettings &settings)
{
lock_guard lock(audio_mutex);
fader_volume_db[bus_index] = settings.fader_volume_db;
mute[bus_index] = settings.muted;
locut_enabled[bus_index] = settings.locut_enabled;
for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
eq_level_db[bus_index][band_index] = settings.eq_level_db[band_index];
}
gain_staging_db[bus_index] = settings.gain_staging_db;
last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
level_compressor_enabled[bus_index] = settings.level_compressor_enabled;
compressor_threshold_dbfs[bus_index] = settings.compressor_threshold_dbfs;
compressor_enabled[bus_index] = settings.compressor_enabled;
}
AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
{
switch (device.type) {
case InputSourceType::CAPTURE_CARD:
return &video_cards[device.index];
case InputSourceType::ALSA_INPUT:
return &alsa_inputs[device.index];
case InputSourceType::SILENCE:
default:
assert(false);
}
return nullptr;
}
// Get a pointer to the given channel from the given device.
// The channel must be picked out earlier and resampled.
void AudioMixer::find_sample_src_from_device(const map> &samples_card, DeviceSpec device_spec, int source_channel, const float **srcptr, unsigned *stride)
{
static float zero = 0.0f;
if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
*srcptr = &zero;
*stride = 0;
return;
}
AudioDevice *device = find_audio_device(device_spec);
assert(device->interesting_channels.count(source_channel) != 0);
unsigned channel_index = 0;
for (int channel : device->interesting_channels) {
if (channel == source_channel) break;
++channel_index;
}
assert(channel_index < device->interesting_channels.size());
const auto it = samples_card.find(device_spec);
assert(it != samples_card.end());
*srcptr = &(it->second)[channel_index];
*stride = device->interesting_channels.size();
}
// TODO: Can be SSSE3-optimized if need be.
void AudioMixer::fill_audio_bus(const map> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
{
if (bus.device.type == InputSourceType::SILENCE) {
memset(output, 0, num_samples * 2 * sizeof(*output));
} else {
assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
bus.device.type == InputSourceType::ALSA_INPUT);
const float *lsrc, *rsrc;
unsigned lstride, rstride;
float *dptr = output;
find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
for (unsigned i = 0; i < num_samples; ++i) {
*dptr++ = *lsrc;
*dptr++ = *rsrc;
lsrc += lstride;
rsrc += rstride;
}
}
}
vector AudioMixer::get_active_devices() const
{
vector ret;
for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
if (!find_audio_device(device_spec)->interesting_channels.empty()) {
ret.push_back(device_spec);
}
}
for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
if (!find_audio_device(device_spec)->interesting_channels.empty()) {
ret.push_back(device_spec);
}
}
return ret;
}
namespace {
void apply_gain(float db, float last_db, vector *samples)
{
if (fabs(db - last_db) < 1e-3) {
// Constant over this frame.
const float gain = from_db(db);
for (size_t i = 0; i < samples->size(); ++i) {
(*samples)[i] *= gain;
}
} else {
// We need to do a fade.
unsigned num_samples = samples->size() / 2;
float gain = from_db(last_db);
const float gain_inc = pow(from_db(db - last_db), 1.0 / num_samples);
for (size_t i = 0; i < num_samples; ++i) {
(*samples)[i * 2 + 0] *= gain;
(*samples)[i * 2 + 1] *= gain;
gain *= gain_inc;
}
}
}
} // namespace
vector AudioMixer::get_output(steady_clock::time_point ts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
{
map> samples_card;
vector samples_bus;
lock_guard lock(audio_mutex);
// Pick out all the interesting channels from all the cards.
for (const DeviceSpec &device_spec : get_active_devices()) {
AudioDevice *device = find_audio_device(device_spec);
samples_card[device_spec].resize(num_samples * device->interesting_channels.size());
if (device->silenced) {
memset(&samples_card[device_spec][0], 0, samples_card[device_spec].size() * sizeof(float));
} else {
device->resampling_queue->get_output_samples(
ts,
&samples_card[device_spec][0],
num_samples,
rate_adjustment_policy);
}
}
vector samples_out, left, right;
samples_out.resize(num_samples * 2);
samples_bus.resize(num_samples * 2);
for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
apply_eq(bus_index, &samples_bus);
{
lock_guard lock(compressor_mutex);
// Apply a level compressor to get the general level right.
// Basically, if it's over about -40 dBFS, we squeeze it down to that level
// (or more precisely, near it, since we don't use infinite ratio),
// then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
// entirely arbitrary, but from practical tests with speech, it seems to
// put ut around -23 LUFS, so it's a reasonable starting point for later use.
if (level_compressor_enabled[bus_index]) {
float threshold = 0.01f; // -40 dBFS.
float ratio = 20.0f;
float attack_time = 0.5f;
float release_time = 20.0f;
float makeup_gain = from_db(ref_level_dbfs - (-40.0f)); // +26 dB.
level_compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain);
} else {
// Just apply the gain we already had.
float db = gain_staging_db[bus_index];
float last_db = last_gain_staging_db[bus_index];
apply_gain(db, last_db, &samples_bus);
}
last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
#if 0
printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
level_compressor.get_level(), to_db(level_compressor.get_level()),
level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
#endif
// The real compressor.
if (compressor_enabled[bus_index]) {
float threshold = from_db(compressor_threshold_dbfs[bus_index]);
float ratio = 20.0f;
float attack_time = 0.005f;
float release_time = 0.040f;
float makeup_gain = 2.0f; // +6 dB.
compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
// compressor_att = compressor.get_attenuation();
}
}
add_bus_to_master(bus_index, samples_bus, &samples_out);
deinterleave_samples(samples_bus, &left, &right);
measure_bus_levels(bus_index, left, right);
}
{
lock_guard lock(compressor_mutex);
// Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
// Note that since ratio is not infinite, we could go slightly higher than this.
if (limiter_enabled) {
float threshold = from_db(limiter_threshold_dbfs);
float ratio = 30.0f;
float attack_time = 0.0f; // Instant.
float release_time = 0.020f;
float makeup_gain = 1.0f; // 0 dB.
limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
// limiter_att = limiter.get_attenuation();
}
// printf("limiter=%+5.1f compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
}
// At this point, we are most likely close to +0 LU (at least if the
// faders sum to 0 dB and the compressors are on), but all of our
// measurements have been on raw sample values, not R128 values.
// So we have a final makeup gain to get us to +0 LU; the gain
// adjustments required should be relatively small, and also, the
// offset shouldn't change much (only if the type of audio changes
// significantly). Thus, we shoot for updating this value basically
// “whenever we process buffers”, since the R128 calculation isn't exactly
// something we get out per-sample.
//
// Note that there's a feedback loop here, so we choose a very slow filter
// (half-time of 30 seconds).
double target_loudness_factor, alpha;
double loudness_lu = r128.loudness_M() - ref_level_lufs;
target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
// If we're outside +/- 5 LU (after correction), we don't count it as
// a normal signal (probably silence) and don't change the
// correction factor; just apply what we already have.
if (fabs(loudness_lu) >= 5.0 || !final_makeup_gain_auto) {
alpha = 0.0;
} else {
// Formula adapted from
// https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
const double half_time_s = 30.0;
const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
}
{
lock_guard lock(compressor_mutex);
double m = final_makeup_gain;
for (size_t i = 0; i < samples_out.size(); i += 2) {
samples_out[i + 0] *= m;
samples_out[i + 1] *= m;
m += (target_loudness_factor - m) * alpha;
}
final_makeup_gain = m;
}
update_meters(samples_out);
return samples_out;
}
namespace {
void apply_filter_fade(StereoFilter *filter, float *data, unsigned num_samples, float cutoff_hz, float db, float last_db)
{
// A granularity of 32 samples is an okay tradeoff between speed and
// smoothness; recalculating the filters is pretty expensive, so it's
// good that we don't do this all the time.
static constexpr unsigned filter_granularity_samples = 32;
const float cutoff_linear = cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY;
if (fabs(db - last_db) < 1e-3) {
// Constant over this frame.
if (fabs(db) > 0.01f) {
filter->render(data, num_samples, cutoff_linear, 0.5f, db / 40.0f);
}
} else {
// We need to do a fade. (Rounding up avoids division by zero.)
unsigned num_blocks = (num_samples + filter_granularity_samples - 1) / filter_granularity_samples;
const float inc_db_norm = (db - last_db) / 40.0f / num_blocks;
float db_norm = db / 40.0f;
for (size_t i = 0; i < num_samples; i += filter_granularity_samples) {
size_t samples_this_block = std::min(num_samples - i, filter_granularity_samples);
filter->render(data + i * 2, samples_this_block, cutoff_linear, 0.5f, db_norm);
db_norm += inc_db_norm;
}
}
}
} // namespace
void AudioMixer::apply_eq(unsigned bus_index, vector *samples_bus)
{
constexpr float bass_freq_hz = 200.0f;
constexpr float treble_freq_hz = 4700.0f;
// Cut away everything under 120 Hz (or whatever the cutoff is);
// we don't need it for voice, and it will reduce headroom
// and confuse the compressor. (In particular, any hums at 50 or 60 Hz
// should be dampened.)
if (locut_enabled[bus_index]) {
locut[bus_index].render(samples_bus->data(), samples_bus->size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
}
// Apply the rest of the EQ. Since we only have a simple three-band EQ,
// we can implement it with two shelf filters. We use a simple gain to
// set the mid-level filter, and then offset the low and high bands
// from that if we need to. (We could perhaps have folded the gain into
// the next part, but it's so cheap that the trouble isn't worth it.)
//
// If any part of the EQ has changed appreciably since last frame,
// we fade smoothly during the course of this frame.
const float bass_db = eq_level_db[bus_index][EQ_BAND_BASS];
const float mid_db = eq_level_db[bus_index][EQ_BAND_MID];
const float treble_db = eq_level_db[bus_index][EQ_BAND_TREBLE];
const float last_bass_db = last_eq_level_db[bus_index][EQ_BAND_BASS];
const float last_mid_db = last_eq_level_db[bus_index][EQ_BAND_MID];
const float last_treble_db = last_eq_level_db[bus_index][EQ_BAND_TREBLE];
assert(samples_bus->size() % 2 == 0);
const unsigned num_samples = samples_bus->size() / 2;
apply_gain(mid_db, last_mid_db, samples_bus);
apply_filter_fade(&eq[bus_index][EQ_BAND_BASS], samples_bus->data(), num_samples, bass_freq_hz, bass_db - mid_db, last_bass_db - last_mid_db);
apply_filter_fade(&eq[bus_index][EQ_BAND_TREBLE], samples_bus->data(), num_samples, treble_freq_hz, treble_db - mid_db, last_treble_db - last_mid_db);
last_eq_level_db[bus_index][EQ_BAND_BASS] = bass_db;
last_eq_level_db[bus_index][EQ_BAND_MID] = mid_db;
last_eq_level_db[bus_index][EQ_BAND_TREBLE] = treble_db;
}
void AudioMixer::add_bus_to_master(unsigned bus_index, const vector &samples_bus, vector *samples_out)
{
assert(samples_bus.size() == samples_out->size());
assert(samples_bus.size() % 2 == 0);
unsigned num_samples = samples_bus.size() / 2;
const float new_volume_db = mute[bus_index] ? -90.0f : fader_volume_db[bus_index].load();
if (fabs(new_volume_db - last_fader_volume_db[bus_index]) > 1e-3) {
// The volume has changed; do a fade over the course of this frame.
// (We might have some numerical issues here, but it seems to sound OK.)
// For the purpose of fading here, the silence floor is set to -90 dB
// (the fader only goes to -84).
float old_volume = from_db(max(last_fader_volume_db[bus_index], -90.0f));
float volume = from_db(max(new_volume_db, -90.0f));
float volume_inc = pow(volume / old_volume, 1.0 / num_samples);
volume = old_volume;
if (bus_index == 0) {
for (unsigned i = 0; i < num_samples; ++i) {
(*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
(*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
volume *= volume_inc;
}
} else {
for (unsigned i = 0; i < num_samples; ++i) {
(*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
(*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
volume *= volume_inc;
}
}
} else if (new_volume_db > -90.0f) {
float volume = from_db(new_volume_db);
if (bus_index == 0) {
for (unsigned i = 0; i < num_samples; ++i) {
(*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
(*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
}
} else {
for (unsigned i = 0; i < num_samples; ++i) {
(*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
(*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
}
}
}
last_fader_volume_db[bus_index] = new_volume_db;
}
void AudioMixer::measure_bus_levels(unsigned bus_index, const vector &left, const vector &right)
{
assert(left.size() == right.size());
const float volume = mute[bus_index] ? 0.0f : from_db(fader_volume_db[bus_index]);
const float peak_levels[2] = {
find_peak(left.data(), left.size()) * volume,
find_peak(right.data(), right.size()) * volume
};
for (unsigned channel = 0; channel < 2; ++channel) {
// Compute the current value, including hold and falloff.
// The constants are borrowed from zita-mu1 by Fons Adriaensen.
static constexpr float hold_sec = 0.5f;
static constexpr float falloff_db_sec = 15.0f; // dB/sec falloff after hold.
float current_peak;
PeakHistory &history = peak_history[bus_index][channel];
history.historic_peak = max(history.historic_peak, peak_levels[channel]);
if (history.age_seconds < hold_sec) {
current_peak = history.last_peak;
} else {
current_peak = history.last_peak * from_db(-falloff_db_sec * (history.age_seconds - hold_sec));
}
// See if we have a new peak to replace the old (possibly falling) one.
if (peak_levels[channel] > current_peak) {
history.last_peak = peak_levels[channel];
history.age_seconds = 0.0f; // Not 100% correct, but more than good enough given our frame sizes.
current_peak = peak_levels[channel];
} else {
history.age_seconds += float(left.size()) / OUTPUT_FREQUENCY;
}
history.current_level = peak_levels[channel];
history.current_peak = current_peak;
}
}
void AudioMixer::update_meters(const vector &samples)
{
// Upsample 4x to find interpolated peak.
peak_resampler.inp_data = const_cast(samples.data());
peak_resampler.inp_count = samples.size() / 2;
vector interpolated_samples;
interpolated_samples.resize(samples.size());
{
lock_guard lock(audio_measure_mutex);
while (peak_resampler.inp_count > 0) { // About four iterations.
peak_resampler.out_data = &interpolated_samples[0];
peak_resampler.out_count = interpolated_samples.size() / 2;
peak_resampler.process();
size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
peak = max(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
peak_resampler.out_data = nullptr;
}
}
// Find R128 levels and L/R correlation.
vector left, right;
deinterleave_samples(samples, &left, &right);
float *ptrs[] = { left.data(), right.data() };
{
lock_guard lock(audio_measure_mutex);
r128.process(left.size(), ptrs);
correlation.process_samples(samples);
}
send_audio_level_callback();
}
void AudioMixer::reset_meters()
{
lock_guard lock(audio_measure_mutex);
peak_resampler.reset();
peak = 0.0f;
r128.reset();
r128.integr_start();
correlation.reset();
}
void AudioMixer::send_audio_level_callback()
{
if (audio_level_callback == nullptr) {
return;
}
lock_guard lock(audio_measure_mutex);
double loudness_s = r128.loudness_S();
double loudness_i = r128.integrated();
double loudness_range_low = r128.range_min();
double loudness_range_high = r128.range_max();
metric_audio_loudness_short_lufs = loudness_s;
metric_audio_loudness_integrated_lufs = loudness_i;
metric_audio_loudness_range_low_lufs = loudness_range_low;
metric_audio_loudness_range_high_lufs = loudness_range_high;
metric_audio_peak_dbfs = to_db(peak);
metric_audio_final_makeup_gain_db = to_db(final_makeup_gain);
metric_audio_correlation = correlation.get_correlation();
vector bus_levels;
bus_levels.resize(input_mapping.buses.size());
{
lock_guard lock(compressor_mutex);
for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
BusLevel &levels = bus_levels[bus_index];
BusMetrics &metrics = bus_metrics[bus_index];
levels.current_level_dbfs[0] = metrics.current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level);
levels.current_level_dbfs[1] = metrics.current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level);
levels.peak_level_dbfs[0] = metrics.peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak);
levels.peak_level_dbfs[1] = metrics.peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak);
levels.historic_peak_dbfs = metrics.historic_peak_dbfs = to_db(
max(peak_history[bus_index][0].historic_peak,
peak_history[bus_index][1].historic_peak));
levels.gain_staging_db = metrics.gain_staging_db = gain_staging_db[bus_index];
if (compressor_enabled[bus_index]) {
levels.compressor_attenuation_db = metrics.compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation());
} else {
levels.compressor_attenuation_db = 0.0;
metrics.compressor_attenuation_db = 0.0 / 0.0;
}
}
}
audio_level_callback(loudness_s, to_db(peak), bus_levels,
loudness_i, loudness_range_low, loudness_range_high,
to_db(final_makeup_gain),
correlation.get_correlation());
}
map AudioMixer::get_devices()
{
lock_guard lock(audio_mutex);
map devices;
for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
const AudioDevice *device = &video_cards[card_index];
DeviceInfo info;
info.display_name = device->display_name;
info.num_channels = 8;
devices.insert(make_pair(spec, info));
}
vector available_alsa_devices = alsa_pool.get_devices();
for (unsigned card_index = 0; card_index < available_alsa_devices.size(); ++card_index) {
const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index };
const ALSAPool::Device &device = available_alsa_devices[card_index];
DeviceInfo info;
info.display_name = device.display_name();
info.num_channels = device.num_channels;
info.alsa_name = device.name;
info.alsa_info = device.info;
info.alsa_address = device.address;
devices.insert(make_pair(spec, info));
}
return devices;
}
void AudioMixer::set_display_name(DeviceSpec device_spec, const string &name)
{
AudioDevice *device = find_audio_device(device_spec);
lock_guard lock(audio_mutex);
device->display_name = name;
}
void AudioMixer::serialize_device(DeviceSpec device_spec, DeviceSpecProto *device_spec_proto)
{
lock_guard lock(audio_mutex);
switch (device_spec.type) {
case InputSourceType::SILENCE:
device_spec_proto->set_type(DeviceSpecProto::SILENCE);
break;
case InputSourceType::CAPTURE_CARD:
device_spec_proto->set_type(DeviceSpecProto::CAPTURE_CARD);
device_spec_proto->set_index(device_spec.index);
device_spec_proto->set_display_name(video_cards[device_spec.index].display_name);
break;
case InputSourceType::ALSA_INPUT:
alsa_pool.serialize_device(device_spec.index, device_spec_proto);
break;
}
}
void AudioMixer::set_simple_input(unsigned card_index)
{
InputMapping new_input_mapping;
InputMapping::Bus input;
input.name = "Main";
input.device.type = InputSourceType::CAPTURE_CARD;
input.device.index = card_index;
input.source_channel[0] = 0;
input.source_channel[1] = 1;
new_input_mapping.buses.push_back(input);
lock_guard lock(audio_mutex);
current_mapping_mode = MappingMode::SIMPLE;
set_input_mapping_lock_held(new_input_mapping);
fader_volume_db[0] = 0.0f;
}
unsigned AudioMixer::get_simple_input() const
{
lock_guard lock(audio_mutex);
if (input_mapping.buses.size() == 1 &&
input_mapping.buses[0].device.type == InputSourceType::CAPTURE_CARD &&
input_mapping.buses[0].source_channel[0] == 0 &&
input_mapping.buses[0].source_channel[1] == 1) {
return input_mapping.buses[0].device.index;
} else {
return numeric_limits::max();
}
}
void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
{
lock_guard lock(audio_mutex);
set_input_mapping_lock_held(new_input_mapping);
current_mapping_mode = MappingMode::MULTICHANNEL;
}
AudioMixer::MappingMode AudioMixer::get_mapping_mode() const
{
lock_guard lock(audio_mutex);
return current_mapping_mode;
}
void AudioMixer::set_input_mapping_lock_held(const InputMapping &new_input_mapping)
{
map> interesting_channels;
for (const InputMapping::Bus &bus : new_input_mapping.buses) {
if (bus.device.type == InputSourceType::CAPTURE_CARD ||
bus.device.type == InputSourceType::ALSA_INPUT) {
for (unsigned channel = 0; channel < 2; ++channel) {
if (bus.source_channel[channel] != -1) {
interesting_channels[bus.device].insert(bus.source_channel[channel]);
}
}
}
}
// Kill all the old metrics, and set up new ones.
for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
BusMetrics &metrics = bus_metrics[bus_index];
vector> labels_left = metrics.labels;
labels_left.emplace_back("channel", "left");
vector> labels_right = metrics.labels;
labels_right.emplace_back("channel", "right");
global_metrics.remove("bus_current_level_dbfs", labels_left);
global_metrics.remove("bus_current_level_dbfs", labels_right);
global_metrics.remove("bus_peak_level_dbfs", labels_left);
global_metrics.remove("bus_peak_level_dbfs", labels_right);
global_metrics.remove("bus_historic_peak_dbfs", metrics.labels);
global_metrics.remove("bus_gain_staging_db", metrics.labels);
global_metrics.remove("bus_compressor_attenuation_db", metrics.labels);
}
bus_metrics.reset(new BusMetrics[new_input_mapping.buses.size()]);
for (unsigned bus_index = 0; bus_index < new_input_mapping.buses.size(); ++bus_index) {
const InputMapping::Bus &bus = new_input_mapping.buses[bus_index];
BusMetrics &metrics = bus_metrics[bus_index];
char bus_index_str[16], source_index_str[16], source_channels_str[64];
snprintf(bus_index_str, sizeof(bus_index_str), "%u", bus_index);
snprintf(source_index_str, sizeof(source_index_str), "%u", bus.device.index);
snprintf(source_channels_str, sizeof(source_channels_str), "%d:%d", bus.source_channel[0], bus.source_channel[1]);
vector> labels;
metrics.labels.emplace_back("index", bus_index_str);
metrics.labels.emplace_back("name", bus.name);
if (bus.device.type == InputSourceType::SILENCE) {
metrics.labels.emplace_back("source_type", "silence");
} else if (bus.device.type == InputSourceType::CAPTURE_CARD) {
metrics.labels.emplace_back("source_type", "capture_card");
} else if (bus.device.type == InputSourceType::ALSA_INPUT) {
metrics.labels.emplace_back("source_type", "alsa_input");
} else {
assert(false);
}
metrics.labels.emplace_back("source_index", source_index_str);
metrics.labels.emplace_back("source_channels", source_channels_str);
vector> labels_left = metrics.labels;
labels_left.emplace_back("channel", "left");
vector> labels_right = metrics.labels;
labels_right.emplace_back("channel", "right");
global_metrics.add("bus_current_level_dbfs", labels_left, &metrics.current_level_dbfs[0], Metrics::TYPE_GAUGE);
global_metrics.add("bus_current_level_dbfs", labels_right, &metrics.current_level_dbfs[1], Metrics::TYPE_GAUGE);
global_metrics.add("bus_peak_level_dbfs", labels_left, &metrics.peak_level_dbfs[0], Metrics::TYPE_GAUGE);
global_metrics.add("bus_peak_level_dbfs", labels_right, &metrics.peak_level_dbfs[1], Metrics::TYPE_GAUGE);
global_metrics.add("bus_historic_peak_dbfs", metrics.labels, &metrics.historic_peak_dbfs, Metrics::TYPE_GAUGE);
global_metrics.add("bus_gain_staging_db", metrics.labels, &metrics.gain_staging_db, Metrics::TYPE_GAUGE);
global_metrics.add("bus_compressor_attenuation_db", metrics.labels, &metrics.compressor_attenuation_db, Metrics::TYPE_GAUGE);
}
// Reset resamplers for all cards that don't have the exact same state as before.
for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
AudioDevice *device = find_audio_device(device_spec);
if (device->interesting_channels != interesting_channels[device_spec]) {
device->interesting_channels = interesting_channels[device_spec];
reset_resampler_mutex_held(device_spec);
}
}
for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
AudioDevice *device = find_audio_device(device_spec);
if (interesting_channels[device_spec].empty()) {
alsa_pool.release_device(card_index);
} else {
alsa_pool.hold_device(card_index);
}
if (device->interesting_channels != interesting_channels[device_spec]) {
device->interesting_channels = interesting_channels[device_spec];
alsa_pool.reset_device(device_spec.index);
reset_resampler_mutex_held(device_spec);
}
}
input_mapping = new_input_mapping;
}
InputMapping AudioMixer::get_input_mapping() const
{
lock_guard lock(audio_mutex);
return input_mapping;
}
unsigned AudioMixer::num_buses() const
{
lock_guard lock(audio_mutex);
return input_mapping.buses.size();
}
void AudioMixer::reset_peak(unsigned bus_index)
{
lock_guard lock(audio_mutex);
for (unsigned channel = 0; channel < 2; ++channel) {
PeakHistory &history = peak_history[bus_index][channel];
history.current_level = 0.0f;
history.historic_peak = 0.0f;
history.current_peak = 0.0f;
history.last_peak = 0.0f;
history.age_seconds = 0.0f;
}
}
AudioMixer *global_audio_mixer = nullptr;
nageru-1.6.4/audio_mixer.h 0000664 0000000 0000000 00000034305 13232411367 0015470 0 ustar 00root root 0000000 0000000 #ifndef _AUDIO_MIXER_H
#define _AUDIO_MIXER_H 1
// The audio mixer, dealing with extracting the right signals from
// each capture card, resampling signals so that they are in sync,
// processing them with effects (if desired), and then mixing them
// all together into one final audio signal.
//
// All operations on AudioMixer (except destruction) are thread-safe.
#include
#include
#include
#include
#include
#include
#include