Removed many unnecessary files and started changing pypo to use setuptools

This commit is contained in:
Duncan Sommerville 2014-12-17 16:22:40 -05:00
parent 144923c353
commit 97805ad271
169 changed files with 5 additions and 8620 deletions

View file

@ -0,0 +1,10 @@
This tool was born out of a collaboration between Open Broadcast
and Sourcefabric. The authors of the code are:
Original Authors:
Jonas Ohrstrom <jonas@digris.ch>
Paul Baranowski <paul.baranowski@sourcefabric.org>
James Moon <james.moon@sourcefabric.org>
Almost a complete refactor/rewrite by: Martin Konecny <martin.konecny@gmail.com>

View file

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

View file

View file

@ -0,0 +1,48 @@
#!/bin/bash -e
debug="f"
showhelp () {
echo "Usage: airtime-liquidsoap [options]
--help|-h Displays usage information.
--debug|-d Print error messages to console"
}
set -- $(getopt -l help,debug "hd" "$@")
while [ $# -gt 0 ]
do
case "$1" in
(-h|--help) showhelp; exit 0;;
(-d|--debug) debug="t";;
(--) shift; break;;
(-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
(*) break;;
esac
shift
done
virtualenv_bin="/usr/lib/airtime/airtime_virtualenv/bin/"
. ${virtualenv_bin}activate
export HOME="/var/tmp/airtime/pypo/"
api_client_path="/usr/lib/airtime/"
if [ $debug = "t" ]; then
ls_path="/usr/bin/airtime-liquidsoap --verbose -f"
else
ls_path="/usr/bin/airtime-liquidsoap --verbose -f -d"
fi
ls_param="/usr/lib/airtime/pypo/bin/liquidsoap_scripts/ls_script.liq"
export PYTHONPATH=${api_client_path}
SCRIPT=`readlink -f $0`
# Absolute directory this script is in
SCRIPTPATH=`dirname $SCRIPT`
cd $SCRIPTPATH/liquidsoap_scripts
python generate_liquidsoap_cfg.py
exec ${ls_path} ${ls_param} 2>&1
# EOF

View file

@ -0,0 +1,94 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: airtime-liquidsoap
# Required-Start: $local_fs $remote_fs $network $syslog $all
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Liquidsoap daemon
### END INIT INFO
USERID=WEB_USER
GROUPID=WEB_USER
NAME="Liquidsoap Playout Engine"
DAEMON=/usr/lib/airtime/pypo/bin/airtime-liquidsoap
PIDFILE=/var/run/airtime/airtime-liquidsoap.pid
EXEC='/usr/bin/airtime-liquidsoap'
start () {
mkdir -p /var/log/airtime/pypo-liquidsoap
chown $USERID:$GROUPID /var/log/airtime/pypo-liquidsoap
chown $USERID:$GROUPID /etc/airtime
touch /etc/airtime/liquidsoap.cfg
chown $USERID:$GROUPID /etc/airtime/liquidsoap.cfg
touch $PIDFILE
chown $USERID:$GROUPID $PIDFILE
#start-stop-daemon --start --quiet --chuid $USERID:$GROUPID \
#--pidfile $PIDFILE --nicelevel -15 --startas $DAEMON
start-stop-daemon --start --quiet --chuid $USERID:$GROUPID \
--startas $DAEMON --exec $EXEC
}
stop () {
timeout --version >/dev/null 2>&1
RESULT="$?"
#send term signal after 10 seconds
if [ "$RESULT" = "0" ]; then
timeout -s9 10s /usr/lib/airtime/airtime_virtualenv/bin/python \
/usr/lib/airtime/pypo/bin/liquidsoap_scripts/liquidsoap_prepare_terminate.py
else
#some earlier versions of Ubuntu (Lucid) had a different timeout
#command that takes different input parameters.
timeout 10 /usr/lib/airtime/airtime_virtualenv/bin/python \
/usr/lib/airtime/pypo/bin/liquidsoap_scripts/liquidsoap_prepare_terminate.py
fi
# Send TERM after 5 seconds, wait at most 30 seconds.
#start-stop-daemon --stop --oknodo --retry=TERM/10/KILL/5 --quiet --pidfile $PIDFILE
start-stop-daemon --stop --oknodo --retry=TERM/10/KILL/5 --quiet --exec $EXEC
rm -f $PIDFILE
sleep 2
}
case "${1:-''}" in
'stop')
echo -n "Stopping $NAME: "
stop
echo "Done."
;;
'start')
echo -n "Starting $NAME: "
start
echo "Done."
;;
'restart')
echo -n "Restarting $NAME: "
stop
start
echo "Done."
;;
'status')
if [ -f "$PIDFILE" ]; then
pid=`cat $PIDFILE`
if [ -d "/proc/$pid" ]; then
echo "$NAME is running"
exit 0
fi
fi
echo "$NAME is not running"
exit 1
;;
*) # no parameter specified
echo "Usage: $SELF start|stop|restart|status"
exit 1
;;
esac

View file

@ -0,0 +1,31 @@
#!/bin/bash
virtualenv_bin="/usr/lib/airtime/airtime_virtualenv/bin/"
. ${virtualenv_bin}activate
# Absolute path to this script
SCRIPT=`readlink -f $0`
# Absolute directory this script is in
pypo_path=`dirname $SCRIPT`
api_client_path="/usr/lib/airtime/"
pypo_script="pypocli.py"
cd ${pypo_path}
set +e
cat /etc/default/locale | grep -i "LANG=.*UTF-\?8"
set -e
if [ "$?" != "0" ]; then
echo "non UTF-8 default locale found in /etc/default/locale." > /var/log/airtime/pypo/error.log
exit 1
fi
export HOME="/var/tmp/airtime/pypo/"
export PYTHONPATH=${api_client_path}:$PYTHONPATH
export LC_ALL=`cat /etc/default/locale | grep "LANG=" | cut -d= -f2 | tr -d "\n\""`
export TERM=xterm
exec python ${pypo_path}/${pypo_script} > /var/log/airtime/pypo/py-interpreter.log 2>&1
# EOF

View file

@ -0,0 +1,61 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: airtime-playout
# Required-Start: $local_fs $remote_fs $network $syslog $all
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Manage airtime-playout daemon
### END INIT INFO
USERID=WEB_USER
NAME="Airtime Scheduler"
DAEMON=/usr/lib/airtime/pypo/bin/airtime-playout
PIDFILE=/var/run/airtime/airtime-playout.pid
start () {
mkdir -p /var/log/airtime/pypo
start-stop-daemon --start --background --quiet --chuid $USERID:$USERID \
--make-pidfile --pidfile $PIDFILE --startas $DAEMON
}
stop () {
# Send TERM after 5 seconds, wait at most 30 seconds.
start-stop-daemon --stop --oknodo --retry TERM/5/0/30 --quiet --pidfile $PIDFILE
rm -f $PIDFILE
}
case "${1:-''}" in
'start')
# start commands here
echo -n "Starting $NAME: "
start
echo "Done."
;;
'stop')
# stop commands here
echo -n "Stopping $NAME: "
stop
echo "Done."
;;
'restart')
# restart commands here
echo -n "Restarting $NAME: "
stop
start
echo "Done."
;;
'status')
# status commands here
/usr/bin/airtime-check-system
;;
*) # no parameter specified
echo "Usage: $SELF start|stop|restart|status"
exit 1
;;
esac

View file

@ -0,0 +1,6 @@
FILE = "file"
EVENT = "event"
STREAM_BUFFER_START = "stream_buffer_start"
STREAM_OUTPUT_START = "stream_output_start"
STREAM_BUFFER_END = "stream_buffer_end"
STREAM_OUTPUT_END = "stream_output_end"

View file

@ -0,0 +1,68 @@
if bitrate == 24 then
if stereo then
ignore(output_stereo(%aac(bitrate = 24, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 24, channels = 1), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_stereo(%aac(bitrate = 32, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 32, channels = 1), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_stereo(%aac(bitrate = 48, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 48, channels = 1), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_stereo(%aac(bitrate = 64, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 64, channels = 1), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_stereo(%aac(bitrate = 96, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 96, channels = 1), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_stereo(%aac(bitrate = 128, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 128, channels = 1), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_stereo(%aac(bitrate = 160, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 160, channels = 1), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_stereo(%aac(bitrate = 192, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 192, channels = 1), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_stereo(%aac(bitrate = 224, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 224, channels = 1), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_stereo(%aac(bitrate = 256, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 256, channels = 1), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_stereo(%aac(bitrate = 320, channels = 2), !source))
else
ignore(output_mono(%aac(bitrate = 320, channels = 1), mean(!source)))
end
end

View file

@ -0,0 +1,68 @@
if bitrate == 24 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 24, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 24, channels = 1), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 32, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 32, channels = 1), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 48, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 48, channels = 1), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 64, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 64, channels = 1), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 96, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 96, channels = 1), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 128, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 128, channels = 1), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 160, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 160, channels = 1), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 192, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 192, channels = 1), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 224, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 224, channels = 1), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 256, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 256, channels = 1), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_stereo(%aacplus(bitrate = 320, channels = 2), !source))
else
ignore(output_mono(%aacplus(bitrate = 320, channels = 1), mean(!source)))
end
end

View file

@ -0,0 +1,11 @@
/var/log/airtime/pypo-liquidsoap/ls_script.log {
compress
rotate 10
size 1000k
missingok
notifempty
sharedscripts
postrotate
start-stop-daemon --stop --signal USR1 --quiet --pidfile /var/run/airtime/airtime-liquidsoap.pid
endscript
}

View file

@ -0,0 +1,24 @@
if bitrate == 24 then
ignore(output_stereo(%fdkaac(bitrate = 24, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 32 then
ignore(output_stereo(%fdkaac(bitrate = 32, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 48 then
ignore(output_stereo(%fdkaac(bitrate = 48, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 64 then
ignore(output_stereo(%fdkaac(bitrate = 64, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 96 then
ignore(output_stereo(%fdkaac(bitrate = 96, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 128 then
ignore(output_stereo(%fdkaac(bitrate = 128, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 160 then
ignore(output_stereo(%fdkaac(bitrate = 160, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 192 then
ignore(output_stereo(%fdkaac(bitrate = 192, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 224 then
ignore(output_stereo(%fdkaac(bitrate = 224, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 256 then
ignore(output_stereo(%fdkaac(bitrate = 256, aot="mpeg4_he_aac_v2"), !source))
elsif bitrate == 320 then
ignore(output_stereo(%fdkaac(bitrate = 320, aot="mpeg4_he_aac_v2"), !source))
end

View file

@ -0,0 +1,48 @@
import logging
import sys
import time
import traceback
from api_clients.api_client import AirtimeApiClient
def generate_liquidsoap_config(ss):
data = ss['msg']
fh = open('/etc/airtime/liquidsoap.cfg', 'w')
fh.write("################################################\n")
fh.write("# THIS FILE IS AUTO GENERATED. DO NOT CHANGE!! #\n")
fh.write("################################################\n")
for d in data:
key = d['keyname']
str_buffer = d[u'keyname'] + " = "
if d[u'type'] == 'string':
val = '"%s"' % d['value']
else:
val = d[u'value']
val = val if len(val) > 0 else "0"
str_buffer = "%s = %s\n" % (key, val)
fh.write(str_buffer.encode('utf-8'))
fh.write('log_file = "/var/log/airtime/pypo-liquidsoap/<script>.log"\n')
fh.close()
logging.basicConfig(format='%(message)s')
attempts = 0
max_attempts = 10
successful = False
while not successful:
try:
ac = AirtimeApiClient(logging.getLogger())
ss = ac.get_stream_setting()
generate_liquidsoap_config(ss)
successful = True
except Exception, e:
if attempts == max_attempts:
print "Unable to connect to the Airtime server."
logging.error(str(e))
logging.error("traceback: %s", traceback.format_exc())
sys.exit(1)
else:
time.sleep(3)
attempts += 1

View file

@ -0,0 +1,268 @@
# Decoders, enabled when the binary is detected and the os is not Win32.
%ifdef add_decoder
# Enable external Musepack decoder. Requires the
# mpcdec binary in the path. Does not work on
# Win32.
# @category Liquidsoap
def enable_external_mpc_decoder() =
# A list of know extensions and content-type for Musepack.
# Values from http://en.wikipedia.org/wiki/Musepack
mpc_mimes = [ "audio/x-musepack", "audio/musepack" ]
mpc_filexts = [ "mpc", "mp+", "mpp" ]
def test_mpc(file) =
def get_channels(file) =
int_of_string(
list.hd(
get_process_lines("mpcdec -i #{quote(file)} 2>&1 \
| grep channels | cut -d' ' -f 2")))
end
# Get the file's mime
mime = get_mime(file)
# Test mime
if list.mem(mime,mpc_mimes) then
get_channels(file)
else
# Otherwise test file extension
ret = string.extract(pattern='\.(.+)$',file)
if list.length(ret) != 0 then
ext = ret["1"]
if list.mem(ext,mpc_filexts) then
get_channels(file)
else
0
end
else
get_channels(file)
end
end
end
if test_process("which mpcdec") then
log(level=3,"Found mpcdec binary: enabling musepack external decoder.")
mpcdec_p = fun(f) -> "mpcdec #{quote(f)} - 2>/dev/null"
add_oblivious_decoder(name="MPCDEC",description="Decode files using the mpcdec \
musepack decoder binary",test=test_mpc,mpcdec_p)
else
log(level=3,"Did not find mpcdec binary: musepack decoder disabled.")
end
end
# Enable external FLAC decoders. Requires flac binary
# in the path for audio decoding and metaflac binary for
# metadata. Does not work on Win32. Default: disabled.
# Please note that built-in support for FLAC is available
# in liquidsoap if compiled and should be preferred over
# the external decoder.
# @category Liquidsoap
def enable_external_flac_decoder() =
if test_process("which flac") then
log(level=3,"Found flac binary: enabling flac external decoder.")
flac_p = "flac -d -c - 2>/dev/null"
def test_flac(file) =
if test_process("which metaflac") then
channels = list.hd(get_process_lines("metaflac \
--show-channels #{quote(file)} \
2>/dev/null"))
# If the value is not an int, this returns 0 and we are ok :)
int_of_string(channels)
else
if string.match(pattern="flac",file) then
# We do not know the number of audio channels
# so setting to -1
(-1)
else
# All tests failed: no audio decodable using flac..
0
end
end
end
add_decoder(name="EXTERNAL_FLAC",description="Decode files using the flac \
decoder binary.", test=test_flac,flac_p)
else
log(level=3,"Did not find flac binary: flac decoder disabled.")
end
if test_process("which metaflac") then
log(level=3,"Found metaflac binary: enabling flac external metadata \
resolver.")
def flac_meta(file)
ret = get_process_lines("metaflac --export-tags-to=- \
#{quote(file)} 2>/dev/null")
ret = list.map(string.split(separator="="),ret)
# Could be made better..
def f(l',l)=
if list.length(l) >= 2 then
list.append([(list.hd(l),list.nth(l,1))],l')
else
if list.length(l) >= 1 then
list.append([(list.hd(l),"")],l')
else
l'
end
end
end
list.fold(f,[],ret)
end
add_metadata_resolver("EXTERNAL_FLAC",flac_meta)
else
log(level=3,"Did not find metaflac binary: flac metadata resolver disabled.")
end
end
%endif
%ifdef add_oblivious_decoder
# Enable or disable external FAAD (AAC/AAC+/M4A) decoders.
# Requires faad binary in the path for audio decoding and
# metaflac binary for metadata. Does not work on Win32.
# Please note that built-in support for faad is available
# in liquidsoap if compiled and should be preferred over
# the external decoder.
# @category Liquidsoap
def enable_external_faad_decoder() =
# A list of know extensions and content-type for AAC.
# Values from http://en.wikipedia.org/wiki/Advanced_Audio_Coding
# TODO: can we register a setting for that ??
aac_mimes =
["audio/aac", "audio/aacp", "audio/3gpp", "audio/3gpp2", "audio/mp4",
"audio/MP4A-LATM", "audio/mpeg4-generic", "audio/x-hx-aac-adts"]
aac_filexts = ["m4a", "m4b", "m4p", "m4v",
"m4r", "3gp", "mp4", "aac"]
# Faad is not very selective so
# We are checking only file that
# end with a known extension or mime type
def faad_test(file) =
# Get the file's mime
mime = get_mime(file)
# Test mime
if list.mem(mime,aac_mimes) then
true
else
# Otherwise test file extension
ret = string.extract(pattern='\.(.+)$',file)
if list.length(ret) != 0 then
ext = ret["1"]
list.mem(ext,aac_filexts)
else
false
end
end
end
if test_process("which faad") then
log(level=3,"Found faad binary: enabling external faad decoder and \
metadata resolver.")
faad_p = (fun (f) -> "faad -w #{quote(f)} 2>/dev/null")
def test_faad(file) =
if faad_test(file) then
channels = list.hd(get_process_lines("faad -i #{quote(file)} 2>&1 | \
grep 'ch,'"))
ret = string.extract(pattern=", (\d) ch,",channels)
ret =
if list.length(ret) == 0 then
# If we pass the faad_test, chances are
# high that the file will contain aac audio data..
"-1"
else
ret["1"]
end
int_of_string(default=(-1),ret)
else
0
end
end
add_oblivious_decoder(name="EXTERNAL_FAAD",description="Decode files using \
the faad binary.", test=test_faad, faad_p)
def faad_meta(file) =
if faad_test(file) then
ret = get_process_lines("faad -i \
#{quote(file)} 2>&1")
# Yea, this is ugly programming (again) !
def get_meta(l,s)=
ret = string.extract(pattern="^(\w+):\s(.+)$",s)
if list.length(ret) > 0 then
list.append([(ret["1"],ret["2"])],l)
else
l
end
end
list.fold(get_meta,[],ret)
else
[]
end
end
add_metadata_resolver("EXTERNAL_FAAD",faad_meta)
else
log(level=3,"Did not find faad binary: faad decoder disabled.")
end
end
%endif
# Standard function for displaying metadata.
# Shows artist and title, using "Unknown" when a field is empty.
# @param m Metadata packet to be displayed.
# @category String
def string_of_metadata(m)
artist = m["artist"]
title = m["title"]
artist = if ""==artist then "Unknown" else artist end
title = if ""==title then "Unknown" else title end
"#{artist} -- #{title}"
end
# Use X On Screen Display to display metadata info.
# @param ~color Color of the text.
# @param ~position Position of the text (top|middle|bottom).
# @param ~font Font used (xfontsel is your friend...)
# @param ~display Function used to display a metadata packet.
# @category Source / Track Processing
def osd_metadata(~color="green",~position="top",
~font="-*-courier-*-r-*-*-*-240-*-*-*-*-*-*",
~display=string_of_metadata,
s)
osd = 'osd_cat -p #{position} --font #{quote(font)}'
^ ' --color #{color}'
def feedback(m)
system("echo #{quote(display(m))} | #{osd} &")
end
on_metadata(feedback,s)
end
# Use notify to display metadata info.
# @param ~urgency Urgency (low|normal|critical).
# @param ~icon Icon filename or stock icon to display.
# @param ~time Timeout in milliseconds.
# @param ~display Function used to display a metadata packet.
# @param ~title Title of the notification message.
# @category Source / Track Processing
def notify_metadata(~urgency="low",~icon="stock_smiley-22",~time=3000,
~display=string_of_metadata,
~title="Liquidsoap: new track",s)
send = 'notify-send -i #{icon} -u #{urgency}'
^ ' -t #{time} #{quote(title)} '
on_metadata(fun (m) -> system(send^quote(display(m))),s)
end
%ifdef input.external
# Stream data from mplayer
# @category Source / Input
# @param s data URI.
# @param ~restart restart on exit.
# @param ~restart_on_error restart on exit with error.
# @param ~buffer Duration of the pre-buffered data.
# @param ~max Maximum duration of the buffered data.
# @category Source / Input
def input.mplayer(~id="input.mplayer",
~restart=true,~restart_on_error=false,
~buffer=0.2,~max=10.,s) =
input.external(id=id,restart=restart,
restart_on_error=restart_on_error,
buffer=buffer,max=max,
"mplayer -really-quiet -ao pcm:file=/dev/stdout \
-vc null -vo null #{quote(s)} 2>/dev/null")
end
%endif

View file

@ -0,0 +1,113 @@
# BIG TODO:
# - Check for errors
# - Unregister radio and streams
# Register a radio on Liquidsoap Flows.
# @category Liquidsoap
# @param ~radio Name of the radio.
# @param ~website URL of the website of the radio.
# @param ~description Description of the radio.
# @param ~genre Genre of the radio (rock or rap or etc.).
# @param ~streams List of streams for the radio described by \
# a pair of strings consisting of the format of the stream \
# and the url of the stream. The format should be \
# of the form "ogg/128k" consisting of the codec and \
# the bitrate, separated by "/".
def register_flow(~server="",~user="default",~password="default",
~email="",~radio,~website,~description,~genre,
~streams,s)
# If the server is "", we get the server from sf.net
server =
if server == "" then
server = http.get("http://savonet.sourceforge.net/flows_server")
html_status = snd(fst(fst(fst(server))))
if html_status == 200 then
snd(server)
else
# If sf is down, we use the hardcoded server
"http://savonet.rastageeks.org/liqflows.py"
end
else
server
end
log(level=4,"Flows server: #{server}")
# Initial variables
ping_period = 600. # Pinging period in seconds
# Fix default parameters
# and set request function.
base_params = [("v", "0.0"),
("user",user),
("password",password),
("email",email),
("radio",radio)]
def request(~cmd,~params) =
log = log(label=radio)
log(level=4,"Processing command #{cmd} with arguments:")
def log_arg(x) =
label = fst(x)
value = snd(x)
log(level=4," #{label}: #{value}")
end
list.iter(log_arg,params)
cmd = url.encode(cmd)
params = list.append(base_params,params)
def f(z) =
x = fst(z)
y = url.encode(snd(z))
"#{x}=#{y}"
end
params = string.concat(separator="&",list.map(f,params))
url = "#{server}?cmd=#{cmd}&#{params}"
# TODO: do something with errors!
answer = http.get(url)
x = fst(answer)
status = fst(x)
y = fst(status)
protocol = fst(y)
code = snd(y)
desc = snd(status)
headers = snd(x)
data = snd(answer)
log(level=4,"Response status: #{protocol} #{code} #{desc}")
log(level=4,"Response headers:")
list.iter(log_arg,headers)
log(level=4,"Response content: #{data}")
end
# Register radio
params = [("radio_website",website),
("radio_description",description),
("radio_genre",genre)]
request(cmd="add radio",params=params)
# Ping
def ping() =
ignore(request(cmd="ping radio",params=[]))
ping_period
end
add_timeout(fast=false,ping_period,ping)
# Register streams
def register_stream(format_url)
format = fst(format_url);
url = snd(format_url);
params = [("stream_format",format),("stream_url",url)]
request(cmd="add stream",params=params)
end
request(cmd="clear streams",params=[])
list.iter(register_stream,streams)
# Metadata update
def metadata(m) =
artist = m["artist"]
title = m["title"]
params = [("m_title",title),("m_artist",artist)]
request(cmd="metadata",params=params)
end
on_metadata(metadata,s)
end

View file

@ -0,0 +1,34 @@
%ifdef input.gstreamer.video
# Stream from a video4linux 2 input device, such as a webcam.
# @category Source / Input
# @param ~id Force the value of the source ID.
# @param ~clock_safe Force the use of the dedicated v4l clock.
# @param ~device V4L2 device to use.
def input.v4l2(~id="",~clock_safe=true,~device="/dev/video0")
pipeline = "v4l2src device=#{device}"
input.gstreamer.video(id=id, clock_safe=clock_safe, pipeline=pipeline)
end
# Stream from a video4linux 2 input device, such as a webcam.
# @category Source / Input
# @param ~id Force the value of the source ID.
# @param ~clock_safe Force the use of the dedicated v4l clock.
# @param ~device V4L2 device to use.
def input.v4l2_with_audio(~id="",~clock_safe=true,~device="/dev/video0")
audio_pipeline = "autoaudiosrc"
video_pipeline = "v4l2src device=#{device}"
input.gstreamer.audio_video(id=id, clock_safe=clock_safe, audio_pipeline=audio_pipeline, video_pipeline=video_pipeline)
end
def gstreamer.encode_x264_avi(fname, source)
output.gstreamer.video(pipeline="videoconvert ! x264enc ! avimux ! filesink location=\"#{fname}\"", source)
end
def gstreamer.encode_jpeg_avi(fname, source)
output.gstreamer.video(pipeline="videoconvert ! jpegenc ! avimux ! filesink location=\"#{fname}\"", source)
end
def gstreamer.encode_mp3(fname, source)
output.gstreamer.audio(pipeline="audioconvert ! lamemp3enc ! filesink location=\"#{fname}\"", source)
end
%endif

View file

@ -0,0 +1,37 @@
# Set of HTTP utils.
%include "http_codes.liq"
# Create a HTTP response string
# @category Interaction
# @param ~protocol HTTP protocol used.
# @param ~code Response code.
# @param ~headers Response headers.
# @param ~data Response data
def http_response(~protocol="HTTP/1.1",
~code=200,
~headers=[],
~data="") =
status = http_codes[string_of(code)]
# Set content-length and connection: close
headers =
list.append(headers,
[("Content-Length", "#{string.length(data)}"),
("Connection", "close")])
headers = list.map(fun (x) -> "#{fst(x)}: #{snd(x)}",headers)
headers = string.concat(separator="\r\n",headers)
# If no headers are provided, we should avoid
# having an empty line for them. Therefore, we also
# conditionally add the final \r\n here.
headers =
if headers != "" then
"#{headers}\r\n"
else
headers
end
"#{protocol} #{code} #{status}\r\n\
#{headers}\
\r\n\
#{data}"
end

View file

@ -0,0 +1,304 @@
# List of HTTP codes. Stolen from en.wikipedia.org..
# List of HTTP response codes and statuses.
# @category Interaction
def http_codes = [
("100","Continue"),
#This means that the server has received the request headers, and that the client
#should proceed to send the request body (in the case of a request for which a
#body needs to be sent; for example, a POST request). If the request body is
#large, sending it to a server when a request has already been rejected based
#upon inappropriate headers is inefficient. To have a server check if the request
#could be accepted based on the request's headers alone, a client must send
#Expect: 100-continue as a header in its initial request and check if a 100
#Continue status code is received in response before continuing (or receive 417
#Expectation Failed and not continue).
("101","Switching Protocols"),
#This means the requester has asked the server to switch protocols and the server
#is acknowledging that it will do so.
("102","Processing"),
#As a WebDAV request may contain many sub-requests involving file operations, it
#may take a long time to complete the request. This code indicates that the
#server has received and is processing the request, but no response is available
#yet. This prevents the client from timing out and assuming the request was
#lost.
("122","Request-URI too long"),
#This is a non-standard IE7-only code which means the URI is longer than a
#maximum of 2083 characters. (See code 414.),
#2xx Success
#This class of status codes indicates the action requested by the client was
#received, understood, accepted and processed successfully.
("200","OK"),
#Standard response for successful HTTP requests. The actual response will depend
#on the request method used. In a GET request, the response will contain an
#entity corresponding to the requested resource. In a POST request the response
#will contain an entity describing or containing the result of the action.
("201","Created"),
#The request has been fulfilled and resulted in a new resource being created.
("202","Accepted"),
#The request has been accepted for processing, but the processing has not been
#completed. The request might or might not eventually be acted upon, as it might
#be disallowed when processing actually takes place.
("203","Non-Authoritative Information"),
#The server successfully processed the request, but is returning information that
#may be from another source.
("204","No Content"),
#The server successfully processed the request, but is not returning any
#content.
("205","Reset Content"),
#The server successfully processed the request, but is not returning any content.
#Unlike a 204 response, this response requires that the requester reset the
#document view.
("206","Partial Content"),
#The server is delivering only part of the resource due to a range header sent by
#the client. The range header is used by tools like wget to enable resuming of
#interrupted downloads, or split a download into multiple simultaneous
#streams.
("207","Multi-Status"),
#The message body that follows is an XML message and can contain a number of
#separate response codes, depending on how many sub-requests were made.
("226","IM Used"),
#The server has fulfilled a GET request for the resource, and the response is a
#representation of the result of one or more instance-manipulations applied to
#the current instance.
#3xx Redirection
#The client must take additional action to complete the request.
#This class of status code indicates that further action needs to be taken by the
#user agent in order to fulfil the request. The action required may be carried
#out by the user agent without interaction with the user if and only if the
#method used in the second request is GET or HEAD. A user agent should not
#automatically redirect a request more than five times, since such redirections
#usually indicate an infinite loop.
("300","Multiple Choices"),
#Indicates multiple options for the resource that the client may follow. It, for
#instance, could be used to present different format options for video, list
#files with different extensions, or word sense disambiguation.
("301","Moved Permanently"),
#This and all future requests should be directed to the given URI.
("302","Found"),
#This is an example of industrial practice contradicting the standard.
#HTTP/1.0 specification (RFC 1945) required the client to perform a temporary
#redirect (the original describing phrase was "Moved Temporarily"), but
#popular browsers implemented 302 with the functionality of a 303 See Other.
#Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the
#two behaviours. However, the majority of Web applications and frameworks
#still[as of?] use the 302 status code as if it were the 303.[citation needed]
("303","See Other"),
#The response to the request can be found under another URI using a GET method.
#When received in response to a POST (or PUT/DELETE), it should be assumed that
#the server has received the data and the redirect should be issued with a
#separate GET message.
("304","Not Modified"),
#Indicates the resource has not been modified since last requested. Typically,
#the HTTP client provides a header like the If-Modified-Since header to provide a
#time against which to compare. Using this saves bandwidth and reprocessing on
#both the server and client, as only the header data must be sent and received in
#comparison to the entirety of the page being re-processed by the server, then
#sent again using more bandwidth of the server and client.
("305","Use Proxy"),
#Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly
#handle responses with this status code, primarily for security reasons.
("306","Switch Proxy"),
#No longer used.
("307","Temporary Redirect"),
#In this occasion, the request should be repeated with another URI, but future
#requests can still use the original URI. In contrast to 303, the request
#method should not be changed when reissuing the original request. For instance,
#a POST request must be repeated using another POST request.
#4xx Client Error
#The 4xx class of status code is intended for cases in which the client seems to
#have erred. Except when responding to a HEAD request, the server should include
#an entity containing an explanation of the error situation, and whether it is a
#temporary or permanent condition. These status codes are applicable to any
#request method. User agents should display any included entity to the user.
#These are typically the most common error codes encountered while online.
("400","Bad Request"),
#The request cannot be fulfilled due to bad syntax.
("401","Unauthorized"),
#Similar to 403 Forbidden, but specifically for use when authentication is
#possible but has failed or not yet been provided. The response must include a
#WWW-Authenticate header field containing a challenge applicable to the requested
#resource. See Basic access authentication and Digest access authentication.
("402","Payment Required"),
#Reserved for future use. The original intention was that this code might be
#used as part of some form of digital cash or micropayment scheme, but that has
#not happened, and this code is not usually used. As an example of its use,
#however, Apple's MobileMe service generates a 402 error ("httpStatusCode:402" in
#the Mac OS X Console log) if the MobileMe account is delinquent.
("403","Forbidden"),
#The request was a legal request, but the server is refusing to respond to it.
#Unlike a 401 Unauthorized response, authenticating will make no difference.
("404","Not Found"),
#The requested resource could not be found but may be available again in the
#future. Subsequent requests by the client are permissible.
("405","Method Not Allowed"),
#A request was made of a resource using a request method not supported by that
#resource; for example, using GET on a form which requires data to be
#presented via POST, or using PUT on a read-only resource.
("406","Not Acceptable"),
#The requested resource is only capable of generating content not acceptable
#according to the Accept headers sent in the request.
("407","Proxy Authentication Required"),
("408","Request Timeout"),
#The server timed out waiting for the request. According to W3 HTTP
#specifications: "The client did not produce a request within the time that the
#server was prepared to wait. The client MAY repeat the request without
#modifications at any later time."
("409","Conflict"),
#Indicates that the request could not be processed because of conflict in the
#request, such as an edit conflict.
("410","Gone"),
#Indicates that the resource requested is no longer available and will not be
#available again. This should be used when a resource has been intentionally
#removed and the resource should be purged. Upon receiving a 410 status code, the
#client should not request the resource again in the future. Clients such as
#search engines should remove the resource from their indices. Most use cases do
#not require clients and search engines to purge the resource, and a "404 Not
#Found" may be used instead.
("411","Length Required"),
#The request did not specify the length of its content, which is required by the
#requested resource.
("412","Precondition Failed"),
#The server does not meet one of the preconditions that the requester put on the
#request.
("413","Request Entity Too Large"),
#The request is larger than the server is willing or able to process.
("414","Request-URI Too Long"),
#The URI provided was too long for the server to process.
("415","Unsupported Media Type"),
#The request entity has a media type which the server or resource does not
#support. For example, the client uploads an image as image/svg+xml, but the
#server requires that images use a different format.
("416","Requested Range Not Satisfiable"),
#The client has asked for a portion of the file, but the server cannot supply
#that portion. For example, if the client asked for a part of the file that
#lies beyond the end of the file.
("417","Expectation Failed"),
#The server cannot meet the requirements of the Expect request-header field.
("418","I'm a teapot"),
#This code was defined in 1998 as one of the traditional IETF April Fools' jokes,
#in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be
#implemented by actual HTTP servers.
("422","Unprocessable Entity"),
#The request was well-formed but was unable to be followed due to semantic
#errors.
("423","Locked"),
#The resource that is being accessed is locked.
("424","Failed Dependency"),
#The request failed due to failure of a previous request (e.g. a PROPPATCH).
("425","Unordered Collection"),
#Defined in drafts of "WebDAV Advanced Collections Protocol", but not present
#in "Web Distributed Authoring and Versioning (WebDAV) Ordered Collections
#Protocol".
("426","Upgrade Required"),
#The client should switch to a different protocol such as TLS/1.0.
("444","No Response"),
#A Nginx HTTP server extension. The server returns no information to the client
#and closes the connection (useful as a deterrent for malware).
("449","Retry With"),
#A Microsoft extension. The request should be retried after performing the
#appropriate action.
("450","Blocked by Windows Parental Controls"),
#A Microsoft extension. This error is given when Windows Parental Controls are
#turned on and are blocking access to the given webpage.
("499","Client Closed Request"),
#An Nginx HTTP server extension. This code is introduced to log the case when the
#connection is closed by client while HTTP server is processing its request,
#making server unable to send the HTTP header back.
#5xx Server Error
#The server failed to fulfill an apparently valid request.
#Response status codes beginning with the digit "5" indicate cases in which the
#server is aware that it has encountered an error or is otherwise incapable of
#performing the request. Except when responding to a HEAD request, the server
#should include an entity containing an explanation of the error situation, and
#indicate whether it is a temporary or permanent condition. Likewise, user agents
#should display any included entity to the user. These response codes are
#applicable to any request method.
("500","Internal Server Error"),
#A generic error message, given when no more specific message is suitable.
("501","Not Implemented"),
#The server either does not recognise the request method, or it lacks the ability
#to fulfill the request.
("502","Bad Gateway"),
#The server was acting as a gateway or proxy and received an invalid response
#from the upstream server.
("503","Service Unavailable"),
#The server is currently unavailable (because it is overloaded or down for
#maintenance). Generally, this is a temporary state.
("504","Gateway Timeout"),
#The server was acting as a gateway or proxy and did not receive a timely
#response from the upstream server.
("505","HTTP Version Not Supported"),
#The server does not support the HTTP protocol version used in the request.
("506","Variant Also Negotiates"),
#Transparent content negotiation for the request results in a circular
#reference.
("507","Insufficient Storage"),
("509","Bandwidth Limit Exceeded"),
#This status code, while used by many servers, is not specified in any RFCs.
("510","Not Extended")
#Further extensions to the request are required for the server to fulfill it.
]
end

View file

@ -0,0 +1,125 @@
%ifdef input.lastfm
# Utility to compose last.fm URIs.
# @category String
# @param ~user Lastfm user
# @param ~password Lastfm password
# @param ~discovery Allow lastfm suggestions
# @param radio URI, e.g. user/toots5446/playlist, globaltags/rocksteady.
def lastfm.uri(~user="",~password="",~discovery=false,
radio="globaltags/creative-commons")
auth = if user == "" then "" else "#{user}:#{password}@" end
discovery = if discovery == true then "1" else "0" end
"lastfm://#{auth}#{radio}?discovery=#{discovery}"
end
# Submit metadata to libre.fm using the audioscrobbler protocol.
# @category Interaction
# @param ~source Source for tracks. Should be one of: "broadcast", "user", "recommendation" or "unknown". Since liquidsoap is intented for radio broadcasting, this is the default. Sources other than user don't need duration to be set.
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
def librefm.submit(~user,~password,~source="broadcast",~length=false,m) =
audioscrobbler.submit(user=user,password=password,
source=source,length=length,
host="turtle.libre.fm",port=80,
m)
end
# Submit metadata to lastfm.fm using the audioscrobbler protocol.
# @category Interaction
# @param ~source Source for tracks. Should be one of: "broadcast", "user", "recommendation" or "unknown". Since liquidsoap is intented for radio broadcasting, this is the default. Sources other than user don't need duration to be set.
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
def lastfm.submit(~user,~password,~source="broadcast",~length=false,m) =
audioscrobbler.submit(user=user,password=password,
source=source,length=length,
host="post.audioscrobbler.com",port=80,
m)
end
# Submit metadata to libre.fm using the audioscrobbler protocol (nowplaying mode).
# @category Interaction
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
def librefm.nowplaying(~user,~password,~length=false,m) =
audioscrobbler.nowplaying(user=user,password=password,length=length,
host="turtle.libre.fm",port=80,
m)
end
# Submit metadata to lastfm.fm using the audioscrobbler protocol (nowplaying mode).
# @category Interaction
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
def lastfm.nowplaying(~user,~password,~length=false,m) =
audioscrobbler.nowplaying(user=user,password=password,length=length,
host="post.audioscrobbler.com",port=80,
m)
end
# Submit songs using audioscrobbler, respecting the full protocol:
# First signal song as now playing when starting, and
# then submit song when it ends.
# @category Interaction
# @param ~source Source for tracks. Should be one of: "broadcast", "user", "recommendation" or "unknown". Since liquidsoap is intented for radio broadcasting, this is the default. Sources other than user don't need duration to be set.
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
# @param ~delay Submit song when there is only this delay left, in seconds.
# @param ~force If remaining time is null, the song will be assumed to be skipped or cuted, and not submitted. Set to zero to disable this behaviour.
def audioscrobbler.submit.full(
~user,~password,
~host="post.audioscrobbler.com",~port=80,
~source="broadcast",~length=false,
~delay=10.,~force=false,s) =
f = audioscrobbler.nowplaying(
user=user,password=password,
host=host,port=port,length=length)
s = on_metadata(f,s)
f = fun (rem,m) ->
# Avoid skipped songs
if rem > 0. or force then
audioscrobbler.submit(
user=user,password=password,
host=host,port=port,length=length,
source=source,m)
else
log(label="audioscrobbler.submit.full",
level=4,"Remaining time null: \
will not submit song (song skipped ?)")
end
on_end(delay=delay,f,s)
end
# Submit songs to librefm using audioscrobbler, respecting the full protocol:
# First signal song as now playing when starting, and
# then submit song when it ends.
# @category Interaction
# @param ~source Source for tracks. Should be one of: "broadcast", "user", "recommendation" or "unknown". Since liquidsoap is intented for radio broadcasting, this is the default. Sources other than user don't need duration to be set.
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
# @param ~delay Submit song when there is only this delay left, in seconds. If remaining time is less than this value, the song will be assumed to be skipped or cuted, and not submitted. Set to zero to disable this behaviour.
# @param ~force If remaining time is null, the song will be assumed to be skipped or cuted, and not submitted. Set to zero to disable this behaviour.
def librefm.submit.full(
~user,~password,
~source="broadcast",~length=false,
~delay=10.,~force=false,s) =
audioscrobbler.submit.full(
user=user,password=password,
source=source,length=length,
host="turtle.libre.fm",port=80,
delay=delay,force=force,s)
end
# Submit songs to lastfm using audioscrobbler, respecting the full protocol:
# First signal song as now playing when starting, and
# then submit song when it ends.
# @category Interaction
# @param ~source Source for tracks. Should be one of: "broadcast", "user", "recommendation" or "unknown". Since liquidsoap is intented for radio broadcasting, this is the default. Sources other than user don't need duration to be set.
# @param ~length Try to submit length information. This operation can be CPU intensive. Value forced to true when used with the "user" source type.
# @param ~delay Submit song when there is only this delay left, in seconds. If remaining time is less than this value, the song will be assumed to be skipped or cuted, and not submitted. Set to zero to disable this behaviour.
# @param ~force If remaining time is null, the song will be assumed to be skipped or cuted, and not submitted. Set to zero to disable this behaviour.
def lastfm.submit.full(
~user,~password,
~source="broadcast",~length=false,
~delay=10.,~force=false,s) =
audioscrobbler.submit.full(
user=user,password=password,
source=source,length=length,
host="post.audioscrobbler.com",port=80,
delay=delay,force=force,s)
end
%endif

View file

@ -0,0 +1,8 @@
%include "utils.liq"
%include "externals.liq"
%include "shoutcast.liq"
%include "lastfm.liq"
%include "flows.liq"
%include "http.liq"
%include "video_text.liq"
%include "gstreamer.liq"

View file

@ -0,0 +1,46 @@
%ifdef output.icecast
# Output to shoutcast.
# @category Source / Output
# @param ~id Output's ID
# @param ~start Start output threads on operator initialization.
# @param ~user User for shout source connection. Useful only in special cases, like with per-mountpoint users.
# @param ~icy_reset Reset shoutcast source buffer upon connecting (necessary for NSV).
# @param ~dumpfile Dump stream to file, for debugging purpose. Disabled if empty.
# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped.
# @param ~on_start Callback executed when outputting starts.
# @param ~on_stop Callback executed when outputting stops.
# @param ~on_error Callback executed when an error happens. If returned value is positive, connection wll be tried again after this amount of time (in seconds).
# @param ~on_connect Callback executed when connection starts.
# @param ~on_disconnect Callback executed when connection stops.
# @param ~icy_metadata Send new metadata using the ICY protocol. One of: "guess", "true", "false"
# @param ~format Format, e.g. "audio/ogg". When empty, the encoder is used to guess.
# @param e Endoding format. For shoutcast, should be mp3 or AAC(+).
# @param s The source to output
def output.shoutcast(
~id="output.shoutcast",~start=true,
~host="localhost",~port=8000,
~user="source",~password="hackme",
~genre="Misc",~url="http://savonet.sf.net/",
~name="Liquidsoap Radio!",~public=true, ~format="",
~dumpfile="", ~icy_metadata="guess",
~on_connect={()}, ~on_disconnect={()},
~aim="",~icq="",~irc="",~icy_reset=true,
~fallible=false,~on_start={()},~on_stop={()},
~on_error=fun(_)->3., e,s) =
icy_reset = if icy_reset then "1" else "0" end
headers = [("icy-aim",aim),("icy-irc",irc),
("icy-icq",icq),("icy-reset",icy_reset)]
output.icecast(
e, format=format,
id=id, headers=headers,
start=start,icy_metadata=icy_metadata,
on_connect=on_connect, on_disconnect=on_disconnect,
host=host, port=port, user=user, password=password,
genre=genre, url=url, description="UNUSED",
public=public, dumpfile=dumpfile,encoding="ISO-8859-1",
name=name, mount="/", protocol="icy",on_error=on_error,
fallible=fallible,on_start=on_start,on_stop=on_stop,
s)
end
%endif

View file

@ -0,0 +1,729 @@
# Turn a source into an infaillible source.
# by adding blank when the source is not available.
# @param s the source to turn infaillible
# @category Source / Track Processing
def mksafe(~id="mksafe",s)
fallback(id=id,track_sensitive=false,[s,blank(id="safe_blank")])
end
# Alias for the <code>l[k]</code> notation.
# @category List
# @param a Key to look for
# @param l List of pairs (key,value)
def list.assoc(a,l)
l[a]
end
# list.mem_assoc(key,l) returns true if l contains a pair
# (key,value)
# @category List
# @param a Key to look for
# @param l List of pairs (key,value)
def list.mem_assoc(a,l)
def f(cur, el) =
if not cur then
fst(el) == a
else
cur
end
end
list.fold(f, false, l)
end
# Remove a pair from an associative list
# @category List
# @param a Key of pair to be removed
# @param l List of pairs (key,value)
def list.remove_assoc(a,l)
list.remove((a,list.assoc(a,l)),l)
end
# Rewrite metadata on the fly using a list of (target,rules).
# @category Source / Track Processing
# @param l \
# List of (target,value) rewriting rules.
# @param ~insert_missing \
# Treat track beginnings without metadata as having empty ones. \
# The operational order is: \
# create empty if needed, map and strip if enabled.
# @param ~update \
# Only update metadata. \
# If false, only returned values will be set as metadata.
# @param ~strip \
# Completly remove empty metadata. \
# Operates on both empty values and empty metadata chunk.
def rewrite_metadata(l,~insert_missing=true,
~update=true,~strip=false,
s)
# We don't need to return all values, since
# map_metadata only update returned values.
# So, we simply apply all rewrite rules !
def map(m)
def apply(x)
label = fst(x)
value = snd(x)
(label,value % m)
end
list.map(apply,l)
end
map_metadata(map,insert_missing=insert_missing,
update=update,strip=strip,s)
end
# Add a skip function to a source
# when it does not have one
# by default
# @category Interaction
# @param s The source to attach the command to.
def add_skip_command(s) =
# A command to skip
def skip(_) =
source.skip(s)
"Done!"
end
# Register the command:
server.register(namespace="#{source.id(s)}",
usage="skip",
description="Skip the current song.",
"skip",skip)
end
# Removes all metadata coming from a source
# @category Source / Track Processing
def drop_metadata(s)
map_metadata(fun(_)->[],update=false,strip=true,insert_missing=false,s)
end
# Merge all tracks from a source, provided that it does not fail
# @category Source / Track Processing
def merge_tracks(s)
sequence(merge=true,[s])
end
# Default inputs and outpus
#
# They are called "prefered" but it's not a user preference,
# just a view of what's generally preferable among the available
# modules.
# It is important that input and output preferences are in the
# same order: the chosen I/O should work in the same clock, we don't
# want an ALSA input and OSS output. The only exception is AO:
# it is the default output after dummy, so the input will be a dummy
# when AO is used for output.
output.prefered=output.dummy
%ifdef output.ao
output.prefered=output.ao
%endif
%ifdef output.alsa
output.prefered=output.alsa
%endif
%ifdef output.oss
output.prefered=output.oss
%endif
%ifdef output.portaudio
output.prefered = output.portaudio
%endif
%ifdef output.pulseaudio
output.prefered=output.pulseaudio
%endif
# Output to local audio card using the first available driver in
# pulseaudio, portaudio, oss, alsa, ao, dummy.
# @category Source / Output
def output.prefered(~id="",~fallible=false,
~on_start={()},~on_stop={()},~start=true,s)
output.prefered(id=id,fallible=fallible,
start=start,on_start=on_start,on_stop=on_stop,
s)
end
def in(~id="",~start=true,~on_start={()},~on_stop={()},~fallible=false)
blank(id=id)
end
%ifdef input.alsa
in = input.alsa
%endif
%ifdef input.oss
in = input.oss
%endif
%ifdef input.portaudio
in = input.portaudio
%endif
%ifdef input.pulseaudio
in = input.pulseaudio
%endif
# Create a source from the first available input driver in
# pulseaudio, portaudio, oss, alsa, blank.
# @category Source / Input
def in(~id="",~start=true,~on_start={()},~on_stop={()},~fallible=false)
in(id=id,start=start,on_start=on_start,on_stop=on_stop,fallible=fallible)
end
# Output a stream using the 'output.prefered' operator. The input source does
# not need to be infallible, blank will just be played during failures.
# @param s the source to output
# @category Source / Output
def out(s)
output.prefered(mksafe(s))
end
# Special track insensitive fallback that always skips current song before switching.
# @category Source / Track Processing
# @param ~input The input source
# @param f The fallback source
def fallback.skip(~input,f)
def transition(a,b) =
source.skip(a)
# This eats the last remaining frame from a
sequence([a,b])
end
fallback(track_sensitive=false,transitions=[transition,transition],[input,f])
end
# Compress and normalize, producing a more uniform and "full" sound.
# @category Source / Sound Processing
# @param s The input source.
def nrj(s)
compress(threshold=-15.,ratio=3.,gain=3.,normalize(s))
end
# Multiband-compression.
# @category Source / Sound Processing
# @param s The input source.
def sky(s)
# 3-band crossover
low = filter.iir.eq.low(frequency = 168.)
mh = filter.iir.eq.high(frequency = 100.)
mid = filter.iir.eq.low(frequency = 1800.)
high = filter.iir.eq.high(frequency = 1366.)
# Add back
add(normalize = false,
[ compress(attack = 100., release = 200., threshold = -20.,
ratio = 6., gain = 6.7, knee = 0.3,
low(s)),
compress(attack = 100., release = 200., threshold = -20.,
ratio = 6., gain = 6.7, knee = 0.3,
mid(mh(s))),
compress(attack = 100., release = 200., threshold = -20.,
ratio = 6., gain = 6.7, knee = 0.3,
high(s))
])
end
# Simple crossfade.
# @category Source / Track Processing
# @param ~start_next Duration in seconds of the crossed end of track.
# @param ~fade_in Duration of the fade in for next track.
# @param ~fade_out Duration of the fade out for previous track.
# @param ~conservative Always prepare for a premature end-of-track.
# @param s The source to use.
def crossfade(~id="",~conservative=true,
~start_next=5.,~fade_in=3.,~fade_out=3.,
s)
s = fade.in(duration=fade_in,s)
s = fade.out(duration=fade_out,s)
fader = fun (a,b) -> add(normalize=false,[b,a])
cross(id=id,conservative=conservative,duration=start_next,fader,s)
end
# Append speech-synthesized tracks reading the metadata.
# @category Source / Track Processing
# @param ~pattern Pattern to use
# @param s The source to use
def say_metadata
p = 'say:$(if $(artist),"It was $(artist)$(if $(title),\", $(title)\").")'
fun (s,~pattern=p) ->
append(s,fun (m) -> request.queue(queue=[request.create(pattern % m)],
interactive=false))
end
%ifdef soundtouch
# Increases the pitch, making voices sound like on helium.
# @category Source / Sound Processing
# @param s The input source.
def helium(s)
soundtouch(pitch=1.5,s)
end
%endif
# Return true if process exited with 0 code. Command should return quickly.
# @category System
# @param command Command to test
def test_process(command)
lines =
get_process_lines("(" ^ command ^ " >/dev/null 2>&1 && echo 0) || echo 1")
if list.length(lines) == 0 then
false
else
"0" == list.hd(lines)
end
end
# Split an url of the form foo?arg=bar&arg2=bar2
# into ("foo",[("arg","bar"),("arg2","bar2")]).
# @category String
# @param uri Url to split
def url.split(uri) =
ret = string.extract(pattern="([^\?]*)\?(.*)",uri)
args = ret["2"]
if args != "" then
l = string.split(separator="&",args)
def f(x) =
ret = string.split(separator="=",x)
(url.decode(list.nth(ret,0)),
url.decode(list.nth(ret,1)))
end
l = list.map(f,l)
(ret["1"],l)
else
(uri,[])
end
end
# Register a server/telnet command to update a source's metadata. Returns
# a new source, which will receive the updated metadata. The command has
# the following format: insert key1="val1",key2="val2",...
# @category Source / Track Processing
# @param ~id Force the value of the source ID.
def server.insert_metadata(~id="",s) =
x = insert_metadata(id=id,s)
insert = fst(x)
s = snd(x)
def insert(s) =
l = string.split(separator='([^=]+\s*=\s*"(\\"|[^"])*")\s*,\s*',s)
def f(l,x) =
sub = fun (s) -> string.replace(pattern='\\"',fun (_) -> '"',s)
if x != "" then
ret = string.extract(pattern='([^=]+)\s*=\s*"((?:\\"|[^"])*)"',x)
if ret["1"] != "" then
list.append(l,[(ret["1"],
sub(ret["2"]))])
else
l
end
else
l
end
end
meta = list.fold(f,[],l)
if meta != [] then
insert(meta)
"Done"
else
"Syntax error or no metadata given. \
Use key1=\"val1\",key2=\"val2\",.."
end
end
id = source.id(s)
server.register(namespace="#{id}",
description="Insert a metadata chunk.",
usage="insert key1=\"val1\",key2=\"val2\",..",
"insert",insert)
s
end
# Register a command that outputs the RMS of the returned source.
# @category Source / Visualization
# @param ~id Force the value of the source ID.
def server.rms(~id="",s) =
x = rms(id=id,s)
rms = fst(x)
s = snd(x)
id = source.id(s)
def rms(_) =
rms = rms()
"#{rms}"
end
server.register(namespace="#{id}",
description="Return the current RMS of the source.",
usage="rms",
"rms",rms)
s
end
# Read some value from standard input (console).
# @category System
# @param ~hide Hide typed characters (for passwords).
def read(~hide=false)
if hide then
system("stty -echo")
end
s = list.hd(get_process_lines("read BLA && echo $BLA"))
if hide then
system("stty echo")
end
print("")
s
end
# Dummy implementation of file.mime
# @category System
def file.mime_default(_)
""
end
%ifdef file.mime
# Alias of file.mime (because it is available)
# @category System
def file.mime_default(file)
file.mime(file)
end
%endif
# Generic mime test. First try to use file.mime if it exist.
# Otherwise try to get the value using the file binary.
# Returns "" (empty string) if no value can be find.
# @category System
# @param file The file to test
def get_mime(file) =
def file_method(file) =
if test_process("which file") then
list.hd(get_process_lines("file -b --mime-type \
#{quote(file)}"))
else
""
end
end
# First try mime method
ret = file.mime_default(file)
if ret != "" then
ret
else
# Now try file method
file_method(file)
end
end
# Remove low frequencies often produced by microphones.
# @category Source / Sound Processing
# @param s The input source.
def mic_filter(s)
filter(freq=200.,q=1.,mode="high",s)
end
# Creates a source that fails to produce anything.
# @category Source / Input
def fail(~id="")
fallback(id=id,[])
end
# Creates a source that plays only one track of the input source.
# @category Source / Track Processing
# @param s The input source.
def once(s)
sequence([s,fail()])
end
# Crossfade between tracks, taking the respective volume levels into account in
# the choice of the transition.
# @category Source / Track Processing
# @param ~start_next Crossing duration, if any.
# @param ~fade_in Fade-in duration, if any.
# @param ~fade_out Fade-out duration, if any.
# @param ~width Width of the volume analysis window.
# @param ~conservative Always prepare for a premature end-of-track.
# @param ~default Transition used when no rule applies \
# (default: sequence).
# @param ~high Value, in dB, for loud sound level.
# @param ~medium Value, in dB, for medium sound level.
# @param ~margin Margin to detect sources that have too different \
# sound level for crossing.
# @param s The input source.
def smart_crossfade (~start_next=5.,~fade_in=3.,~fade_out=3.,
~default=(fun (a,b) -> sequence([a, b])),
~high=-15., ~medium=-32., ~margin=4.,
~width=2.,~conservative=true,s)
fade.out = fade.out(type="sin",duration=fade_out)
fade.in = fade.in(type="sin",duration=fade_in)
add = fun (a,b) -> add(normalize=false,[b, a])
log = log(label="smart_crossfade")
def transition(a,b,ma,mb,sa,sb)
list.iter(fun(x)-> log(level=4,"Before: #{x}"),ma)
list.iter(fun(x)-> log(level=4,"After : #{x}"),mb)
if
# If A and B are not too loud and close, fully cross-fade them.
a <= medium and b <= medium and abs(a - b) <= margin
then
log("Old <= medium, new <= medium and |old-new| <= margin.")
log("Old and new source are not too loud and close.")
log("Transition: crossed, fade-in, fade-out.")
add(fade.out(sa),fade.in(sb))
elsif
# If B is significantly louder than A, only fade-out A.
# We don't want to fade almost silent things, ask for >medium.
b >= a + margin and a >= medium and b <= high
then
log("new >= old + margin, old >= medium and new <= high.")
log("New source is significantly louder than old one.")
log("Transition: crossed, fade-out.")
add(fade.out(sa),sb)
elsif
# Opposite as the previous one.
a >= b + margin and b >= medium and a <= high
then
log("old >= new + margin, new >= medium and old <= high")
log("Old source is significantly louder than new one.")
log("Transition: crossed, fade-in.")
add(sa,fade.in(sb))
elsif
# Do not fade if it's already very low.
b >= a + margin and a <= medium and b <= high
then
log("new >= old + margin, old <= medium and new <= high.")
log("Do not fade if it's already very low.")
log("Transition: crossed, no fade.")
add(sa,sb)
# What to do with a loud end and a quiet beginning ?
# A good idea is to use a jingle to separate the two tracks,
# but that's another story.
else
# Otherwise, A and B are just too loud to overlap nicely,
# or the difference between them is too large and overlapping would
# completely mask one of them.
log("No transition: using default.")
default(sa, sb)
end
end
smart_cross(width=width, duration=start_next, conservative=conservative,
transition,s)
end
# Custom playlist source written using the script language.
# Will read directory or playlist, play all files and stop.
# Returns a pair @(reload,source)@ where @reload@ is a function
# of type @(?uri:string)->unit@ used to reload the source and @source@
# is the actual source. The reload function can optionally be called
# with a new playlist URI. Otherwise, it reloads the previous URI.
# @category Source / Input
# @param ~id Force the value of the source ID.
# @param ~random Randomize playlist content
# @param ~on_done Function to execute when the playlist is finished
# @param uri Playlist URI
def playlist.reloadable(~id="",~random=false,~on_done={()},uri)
# A reference to the playlist
playlist = ref []
# A reference to the uri
playlist_uri = ref uri
# A reference to know if the source
# has been stopped
has_stopped = ref false
# The next function
def next () =
file =
if list.length(!playlist) > 0 then
ret = list.hd(!playlist)
playlist := list.tl(!playlist)
ret
else
# Playlist finished
if not !has_stopped then
on_done ()
end
has_stopped := true
""
end
request.create(file)
end
# Instanciate the source
source = request.dynamic(id=id,next)
# Get its id.
id = source.id(source)
# The load function
def load_playlist () =
files =
if test_process("test -d #{quote(!playlist_uri)}") then
log(label=id,"playlist is a directory.")
get_process_lines("find #{quote(!playlist_uri)} -type f | sort")
else
playlist = request.create.raw(!playlist_uri)
result =
if request.resolve(playlist) then
playlist = request.filename(playlist)
files = playlist.parse(playlist)
def file_request(el) =
meta = fst(el)
file = snd(el)
s = list.fold(fun (cur, el) ->
"#{cur},#{fst(el)}=#{string.escape(snd(el))}", "", meta)
if s == "" then
file
else
"annotate:#{s}:#{file}"
end
end
list.map(file_request,files)
else
log(label=id,"Couldn't read playlist: request resolution failed.")
[]
end
request.destroy(playlist)
result
end
if random then
playlist := list.sort(fun (x,y) -> int_of_float(random.float()), files)
else
playlist := files
end
end
# The reload function
def reload(~uri="") =
if uri != "" then
playlist_uri := uri
end
log(label=id,"Reloading playlist with URI #{!playlist_uri}")
has_stopped := false
load_playlist()
end
# Load the playlist
load_playlist()
# Return
(reload,source)
end
# Custom playlist source written using the script language.
# Will read directory or playlist, play all files and stop
# @category Source / Input
# @param ~id Force the value of the source ID.
# @param ~random Randomize playlist content
# @param ~on_done Function to execute when the playlist is finished
# @param uri Playlist URI
def playlist.once(~id="",~random=false,~on_done={()},uri)
snd(playlist.reloadable(id=id,random=random,on_done=on_done,uri))
end
# Mixes two streams, with faded transitions between the state when only the
# normal stream is available and when the special stream gets added on top of
# it.
# @category Source / Track Processing
# @param ~delay Delay before starting the special source.
# @param ~p Portion of amplitude of the normal source in the mix.
# @param ~normal The normal source, which could be called the carrier too.
# @param ~special The special source.
def smooth_add(~delay=0.5,~p=0.2,~normal,~special)
d = delay
fade.final = fade.final(duration=d*2.)
fade.initial = fade.initial(duration=d*2.)
q = 1. - p
c = amplify
fallback(track_sensitive=false,
[special,normal],
transitions=[
fun(normal,special)->
add(normalize=false,
[c(p,normal),
c(q,fade.final(type="sin",normal)),
sequence([blank(duration=d),c(q,special)])]),
fun(special,normal)->
add(normalize=false,
[c(p,normal),
c(q,fade.initial(type="sin",normal))])
])
end
# Restrict a source to play only when a predicate is true.
# @category Source / Track Processing
# @param pred The predicate, typically a time interval such as \
# <code>{10h-10h30}</code>.
def at(pred,s)
switch([(pred,s)])
end
# Execute a given action when a predicate is true.
# This will be run in background.
# @category System
# @param ~freq Frequency for checking the predicate, in seconds.
# @param ~pred Predicate indicating when to execute the function, \
# typically a time interval such as <code>{10h-10h30}</code>.
# @param f Function to execute when the predicate is true.
def exec_at(~freq=1.,~pred,f)
def check()
if pred() then
f()
end
freq
end
add_timeout(freq,check)
end
# Register the replaygain protocol.
# @category Liquidsoap
def replaygain_protocol(arg,delay)
# The extraction program
extract_replaygain = "#{configure.libdir}/extract-replaygain"
x = get_process_lines("#{extract_replaygain} #{quote(arg)}")
if list.hd(x) != "" then
["annotate:replay_gain=\"#{list.hd(x)}\":#{arg}"]
else
[arg]
end
end
add_protocol("replay_gain", replaygain_protocol)
# Enable replay gain metadata resolver. This resolver will
# process any file decoded by liquidsoap and add a replay_gain
# metadata when this value could be computed. For a finer-grained
# replay gain processing, use the replay_gain protocol.
# @category Liquidsoap
# @param ~extract_replaygain The extraction program
def enable_replaygain_metadata(
~extract_replaygain="#{configure.libdir}/extract-replaygain")
def replaygain_metadata(file)
x = get_process_lines("#{extract_replaygain} \
#{quote(file)}")
if list.hd(x) != "" then
[("replay_gain",list.hd(x))]
else
[]
end
end
add_metadata_resolver("replay_gain", replaygain_metadata)
end
# Assign a new clock to the given source (and to other time-dependent
# sources) and return the source. It is a conveniency wrapper around
# clock.assign_new(), allowing more concise scripts in some cases.
# @category Liquidsoap
# @param ~sync Do not synchronize the clock on regular wallclock time, \
# but try to run as fast as possible (CPU burning mode).
def clock(~sync=true,~id="",s)
clock.assign_new(sync=sync,id=id,[s])
s
end
# Create a log of clock times for all the clocks initially present.
# The log is in a simple format which you can directly use with gnuplot.
# @category Liquidsoap
# @param ~interval Polling interval.
# @param ~delay Delay before setting up the clock logger. This should \
# be used to ensure that the logger starts only after \
# the clocks are created.
# @param unlabeled Path of the log file.
def log_clocks(~delay=0.,~interval=1.,logfile)
# Get the current clocks
clocks = list.map(fst,get_clock_status())
# Column headers
system("echo \# #{string.concat(separator=' ',clocks)} > #{(logfile:string)}")
def report()
status = get_clock_status()
status = list.map(fun (x) -> (fst(x),string_of(snd(x))), status)
status = list.map(fun (c) -> status[c], clocks)
system("echo #{string.concat(separator=' ',status)} >> #{logfile}")
interval
end
if delay<=0. then
add_timeout(interval,report)
else
add_timeout(delay,{add_timeout(interval,report) (-1.)})
end
end

View file

@ -0,0 +1,45 @@
%ifdef video.add_text.gd
# Add a scrolling line of text on video frames.
# @category Source / Video Processing
# @param ~id Force the value of the source ID.
# @param ~color Text color (in 0xRRGGBB format).
# @param ~cycle Cycle text.
# @param ~font Path to ttf font file.
# @param ~metadata Change text on a particular metadata \
# (empty string means disabled).
# @param ~size Font size.
# @param ~speed Speed in pixels per second (0 means no scrolling).
# @param ~x x offset (negative means from right).
# @param ~y y offset (negative means from bottom).
# @param text Text to display.
def video.add_text(~id="",~color=16777215,~cycle=true,
~font=configure.default_font,
~metadata="",~size=18,~speed=70,~x=-1,~y=-5,
text,source)
video.add_text.gd(id=id,color=color,cycle=cycle,font=font,metadata=metadata,
size=size,speed=speed,x=x,y=y,text,source)
end
%endif
%ifdef video.add_text.sdl
# Add a scrolling line of text on video frames.
# @category Source / Video Processing
# @param ~id Force the value of the source ID.
# @param ~color Text color (in 0xRRGGBB format).
# @param ~cycle Cycle text.
# @param ~font Path to ttf font file.
# @param ~metadata Change text on a particular metadata \
# (empty string means disabled).
# @param ~size Font size.
# @param ~speed Speed in pixels per second (0 means no scrolling).
# @param ~x x offset (negative means from right).
# @param ~y y offset (negative means from bottom).
# @param text Text to display.
def video.add_text(~id="",~color=16777215,~cycle=true,
~font=configure.default_font,
~metadata="",~size=18,~speed=70,~x=-1,~y=-5,
text,source)
video.add_text.sdl(id=id,color=color,cycle=cycle,font=font,metadata=metadata,
size=size,speed=speed,x=x,y=y,text,source)
end
%endif

View file

@ -0,0 +1,69 @@
###########################################
# Liquidsoap config file #
###########################################
###########################################
# Output settings #
###########################################
output_sound_device = false
output_sound_device_type = "ALSA"
s1_output = "icecast"
s2_output = "icecast"
s3_output = "icecast"
s1_enable = true
s2_enable = false
s3_enable = false
s1_type = "ogg"
s2_type = "ogg"
s3_type = "mp3"
s1_bitrate = 128
s2_bitrate = 128
s3_bitrate = 160
###########################################
# Logging settings #
###########################################
log_file = "/var/log/airtime/pypo-liquidsoap/<script>.log"
#log_level = 3
###########################################
# Icecast Stream settings #
###########################################
s1_host = "127.0.0.1"
s2_host = "127.0.0.1"
s3_host = "127.0.0.1"
s1_port = 8000
s2_port = 8000
s3_port = 8000
s1_user = ""
s2_user = ""
s3_user = ""
s1_pass = "hackme"
s2_pass = "hackme"
s3_pass = "hackme"
# Icecast mountpoint names
s1_mount = "airtime_128.ogg"
s2_mount = "airtime_128.ogg"
s3_mount = "airtime_160.mp3"
# Webstream metadata settings
s1_url = "http://airtime.sourcefabric.org"
s2_url = "http://airtime.sourcefabric.org"
s3_url = "http://airtime.sourcefabric.org"
s1_description = "Airtime Radio! stream1"
s2_description = "Airtime Radio! stream2"
s3_description = "Airtime Radio! stream3"
s1_genre = "genre"
s2_genre = "genre"
s3_genre = "genre"
# Audio stream metadata for vorbis/ogg is disabled by default
# due to a number of client media players that disconnect
# when the metadata changes to a new track. Some versions of
# mplayer and VLC have this problem. Enable this option at your
# own risk!
icecast_vorbis_metadata = false

View file

@ -0,0 +1,21 @@
from api_clients import *
import sys
api_clients = api_client.AirtimeApiClient()
dj_type = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
source_type = ''
if dj_type == '--master':
source_type = 'master'
elif dj_type == '--dj':
source_type = 'dj'
response = api_clients.check_live_stream_auth(username, password, source_type)
if 'msg' in response:
print response['msg']
else:
print False

View file

@ -0,0 +1,19 @@
from configobj import ConfigObj
import telnetlib
import sys
try:
config = ConfigObj('/etc/airtime/pypo.cfg')
LS_HOST = config['ls_host']
LS_PORT = config['ls_port']
tn = telnetlib.Telnet(LS_HOST, LS_PORT)
tn.write("master_harbor.stop\n")
tn.write("live_dj_harbor.stop\n")
tn.write('exit\n')
tn.read_all()
except Exception, e:
print 'Error loading config file: %s' % e
sys.exit()

View file

@ -0,0 +1,413 @@
def notify(m)
command = "/usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh --media-id=#{m['schedule_table_id']} &"
log(command)
system(command)
end
def notify_queue(m)
f = !dynamic_metadata_callback
ignore(f(m))
notify(m)
end
def notify_stream(m)
json_str = string.replace(pattern="\n",(fun (s) -> ""), json_of(m))
#if a string has a single apostrophe in it, let's comment it out by ending the string before right before it
#escaping the apostrophe, and then starting a new string right after it. This is why we use 3 apostrophes.
json_str = string.replace(pattern="'",(fun (s) -> "'\''"), json_str)
command = "/usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh --webstream='#{json_str}' --media-id=#{!current_dyn_id} &"
if !current_dyn_id != "-1" then
log(command)
system(command)
end
end
# A function applied to each metadata chunk
def append_title(m) =
log("Using stream_format #{!stream_metadata_type}")
if list.mem_assoc("mapped", m) then
#protection against applying this function twice. It shouldn't be happening
#and bug file with Liquidsoap.
m
else
if !stream_metadata_type == 1 then
[("title", "#{!show_name} - #{m['artist']} - #{m['title']}"), ("mapped", "true")]
elsif !stream_metadata_type == 2 then
[("title", "#{!station_name} - #{!show_name}"), ("mapped", "true")]
else
[("title", "#{m['artist']} - #{m['title']}"), ("mapped", "true")]
end
end
end
def crossfade_airtime(s)
#duration is automatically overwritten by metadata fields passed in
#with audio
s = fade.in(type="log", duration=0., s)
s = fade.out(type="log", duration=0., s)
fader = fun (a,b) -> add(normalize=false,[b,a])
cross(fader,s)
end
def transition(a,b) =
log("transition called...")
add(normalize=false,
[ sequence([ blank(duration=0.01),
fade.initial(duration=!default_dj_fade, b) ]),
fade.final(duration=!default_dj_fade, a) ])
end
# we need this function for special transition case(from default to queue)
# we don't want the trasition fade to have effect on the first song that would
# be played siwtching out of the default(silent) source
def transition_default(a,b) =
log("transition called...")
if !just_switched then
just_switched := false
add(normalize=false,
[ sequence([ blank(duration=0.01),
fade.initial(duration=!default_dj_fade, b) ]),
fade.final(duration=!default_dj_fade, a) ])
else
just_switched := false
b
end
end
# Define a transition that fades out the
# old source, adds a single, and then
# plays the new source
def to_live(old,new) =
# Fade out old source
old = fade.final(old)
# Compose this in sequence with
# the new source
sequence([old,new])
end
def output_to(output_type, type, bitrate, host, port, pass, mount_point, url, description, genre, user, s, stream, connected, name, channels) =
source = ref s
def on_error(msg)
connected := "false"
command = "/usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh --error='#{msg}' --stream-id=#{stream} --time=#{!time} &"
system(command)
log(command)
5.
end
def on_connect()
connected := "true"
command = "/usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh --connect --stream-id=#{stream} --time=#{!time} &"
system(command)
log(command)
end
stereo = (channels == "stereo")
if output_type == "icecast" then
user_ref = ref user
if user == "" then
user_ref := "source"
end
output_mono = output.icecast(host = host,
port = port,
password = pass,
mount = mount_point,
fallible = true,
url = url,
description = description,
name = name,
genre = genre,
user = !user_ref,
on_error = on_error,
on_connect = on_connect)
output_stereo = output.icecast(host = host,
port = port,
password = pass,
mount = mount_point,
fallible = true,
url = url,
description = description,
name = name,
genre = genre,
user = !user_ref,
on_error = on_error,
on_connect = on_connect)
if type == "mp3" then
%include "mp3.liq"
end
if type == "ogg" then
%include "ogg.liq"
end
%ifencoder %opus
if type == "opus" then
%include "opus.liq"
end
%endif
%ifencoder %aac
if type == "aac" then
%include "aac.liq"
end
%endif
%ifencoder %aacplus
if type == "aacplus" then
%include "aacplus.liq"
end
%endif
%ifencoder %fdkaac
if type == "fdkaac" then
%include "fdkaac.liq"
end
%endif
else
user_ref = ref user
if user == "" then
user_ref := "source"
end
output_mono = output.shoutcast(id = "shoutcast_stream_#{stream}",
host = host,
port = port,
password = pass,
fallible = true,
url = url,
genre = genre,
name = description,
user = !user_ref,
on_error = on_error,
on_connect = on_connect)
output_stereo = output.shoutcast(id = "shoutcast_stream_#{stream}",
host = host,
port = port,
password = pass,
fallible = true,
url = url,
genre = genre,
name = description,
user = !user_ref,
on_error = on_error,
on_connect = on_connect)
if type == "mp3" then
%include "mp3.liq"
end
%ifencoder %aac
if type == "aac" then
%include "aac.liq"
end
%endif
%ifencoder %aacplus
if type == "aacplus" then
%include "aacplus.liq"
end
%endif
end
end
# Add a skip function to a source
# when it does not have one
# by default
#def add_skip_command(s)
# # A command to skip
# def skip(_)
# # get playing (active) queue and flush it
# l = list.hd(server.execute("queue.secondary_queue"))
# l = string.split(separator=" ",l)
# list.iter(fun (rid) -> ignore(server.execute("queue.remove #{rid}")), l)
#
# l = list.hd(server.execute("queue.primary_queue"))
# l = string.split(separator=" ", l)
# if list.length(l) > 0 then
# source.skip(s)
# "Skipped"
# else
# "Not skipped"
# end
# end
# # Register the command:
# server.register(namespace="source",
# usage="skip",
# description="Skip the current song.",
# "skip",fun(s) -> begin log("source.skip") skip(s) end)
#end
def clear_queue(s)
source.skip(s)
end
def set_dynamic_source_id(id) =
current_dyn_id := id
string_of(!current_dyn_id)
end
def get_dynamic_source_id() =
string_of(!current_dyn_id)
end
#cc-4633
# NOTE
# A few values are hardcoded and may be dependent:
# - the delay in gracetime is linked with the buffer duration of input.http
# (delay should be a bit less than buffer)
# - crossing duration should be less than buffer length
# (at best, a higher duration will be ineffective)
# HTTP input with "restart" command that waits for "stop" to be effected
# before "start" command is issued. Optionally it takes a new URL to play,
# which makes it a convenient replacement for "url".
# In the future, this may become a core feature of the HTTP input.
# TODO If we stop and restart quickly several times in a row,
# the data bursts accumulate and create buffer overflow.
# Flushing the buffer on restart could be a good idea, but
# it would also create an interruptions while the buffer is
# refilling... on the other hand, this would avoid having to
# fade using both cross() and switch().
def input.http_restart(~id,~initial_url="http://dummy/url")
source = audio_to_stereo(input.http(buffer=5.,max=15.,id=id,autostart=false,initial_url))
def stopped()
"stopped" == list.hd(server.execute("#{id}.status"))
end
server.register(namespace=id,
"restart",
usage="restart [url]",
fun (url) -> begin
if url != "" then
log(string_of(server.execute("#{id}.url #{url}")))
end
log(string_of(server.execute("#{id}.stop")))
add_timeout(0.5,
{ if stopped() then
log(string_of(server.execute("#{id}.start"))) ;
(-1.)
else 0.5 end})
"OK"
end)
# Dummy output should be useless if HTTP stream is meant
# to be listened to immediately. Otherwise, apply it.
#
# output.dummy(fallible=true,source)
source
end
# Transitions between URL changes in HTTP streams.
def cross_http(~debug=true,~http_input_id,source)
id = http_input_id
last_url = ref ""
change = ref false
def on_m(m)
notify_stream(m)
changed = m["source_url"] != !last_url
log("URL now #{m['source_url']} (change: #{changed})")
if changed then
if !last_url != "" then change := true end
last_url := m["source_url"]
end
end
# We use both metadata and status to know about the current URL.
# Using only metadata may be more precise is crazy corner cases,
# but it's also asking too much: the metadata may not pass through
# before the crosser is instantiated.
# Using only status in crosser misses some info, eg. on first URL.
source = on_metadata(on_m,source)
cross_d = 3.
def crosser(a,b)
url = list.hd(server.execute('#{id}.url'))
status = list.hd(server.execute('#{id}.status'))
on_m([("source_url",url)])
if debug then
log("New track inside HTTP stream")
log(" status: #{status}")
log(" need to cross: #{!change}")
log(" remaining #{source.remaining(a)} sec before, \
#{source.remaining(b)} sec after")
end
if !change then
change := false
# In principle one should avoid crossing on a live stream
# it'd be okay to do it here (eg. use add instead of sequence)
# because it's only once per URL, but be cautious.
sequence([fade.out(duration=cross_d,a),fade.in(b)])
else
# This is done on tracks inside a single stream.
# Do NOT cross here or you'll gradually empty the buffer!
sequence([a,b])
end
end
# Setting conservative=true would mess with the delayed switch below
cross(duration=cross_d,conservative=false,crosser,source)
end
# Custom fallback between http and default source with fading of
# beginning and end of HTTP stream.
# It does not take potential URL changes into account, as long as
# they do not interrupt streaming (thanks to the HTTP buffer).
def http_fallback(~http_input_id,~http,~default)
id = http_input_id
# We use a custom switching predicate to trigger switching (and thus,
# transitions) before the end of a track (rather, end of HTTP stream).
# It is complexified because we don't want to trigger switching when
# HTTP disconnects for just an instant, when changing URL: for that
# we use gracetime below.
def gracetime(~delay=3.,f)
last_true = ref 0.
{ if f() then
last_true := gettimeofday()
true
else
gettimeofday() < !last_true+delay
end }
end
def connected()
status = list.hd(server.execute("#{id}.status"))
not(list.mem(status,["polling","stopped"]))
end
connected = gracetime(connected)
def to_live(a,b) =
log("TRANSITION to live")
add(normalize=false,
[fade.initial(b),fade.final(a)])
end
def to_static(a,b) =
log("TRANSITION to static")
sequence([fade.out(a),fade.initial(b)])
end
switch(
track_sensitive=false,
transitions=[to_live,to_static],
[(# make sure it is connected, and not buffering
{connected() and source.is_ready(http) and !webstream_enabled}, http),
({true},default)])
end

View file

@ -0,0 +1,404 @@
%include "/etc/airtime/liquidsoap.cfg"
set("log.file.path", log_file)
set("server.telnet", true)
set("server.telnet.port", 1234)
set("init.daemon.pidfile.path", "/var/run/airtime/airtime-liquidsoap.pid")
%include "library/pervasives.liq"
#Dynamic source list
#dyn_sources = ref []
webstream_enabled = ref false
time = ref string_of(gettimeofday())
#live stream setup
set("harbor.bind_addr", "0.0.0.0")
current_dyn_id = ref '-1'
pypo_data = ref '0'
stream_metadata_type = ref 0
default_dj_fade = ref 0.
station_name = ref ''
show_name = ref ''
dynamic_metadata_callback = ref fun (s) -> begin () end
s1_connected = ref ''
s2_connected = ref ''
s3_connected = ref ''
s1_namespace = ref ''
s2_namespace = ref ''
s3_namespace = ref ''
just_switched = ref false
%include "ls_lib.liq"
sources = ref []
source_id = ref 0
def create_source()
l = request.equeue(id="s#{!source_id}", length=0.5)
l = audio_to_stereo(id="queue_src", l)
l = cue_cut(l)
l = amplify(1., override="replay_gain", l)
# the crossfade function controls fade in/out
l = crossfade_airtime(l)
l = on_metadata(notify_queue, l)
sources := list.append([l], !sources)
server.register(namespace="queues",
"s#{!source_id}_skip",
fun (s) -> begin log("queues.s#{!source_id}_skip")
clear_queue(l)
"Done"
end)
source_id := !source_id + 1
end
create_source()
create_source()
create_source()
create_source()
create_source()
create_source()
create_source()
create_source()
queue = add(!sources, normalize=false)
pair = insert_metadata(queue)
dynamic_metadata_callback := fst(pair)
queue = snd(pair)
output.dummy(fallible=true, queue)
http = input.http_restart(id="http")
http = cross_http(http_input_id="http",http)
output.dummy(fallible=true, http)
stream_queue = http_fallback(http_input_id="http", http=http, default=queue)
stream_queue = map_metadata(update=false, append_title, stream_queue)
ignore(output.dummy(stream_queue, fallible=true))
server.register(namespace="vars",
"pypo_data",
fun (s) -> begin log("vars.pypo_data") pypo_data := s "Done" end)
server.register(namespace="vars",
"stream_metadata_type",
fun (s) -> begin log("vars.stream_metadata_type") stream_metadata_type := int_of_string(s) s end)
server.register(namespace="vars",
"show_name",
fun (s) -> begin log("vars.show_name") show_name := s s end)
server.register(namespace="vars",
"station_name",
fun (s) -> begin log("vars.station_name") station_name := s s end)
server.register(namespace="vars",
"bootup_time",
fun (s) -> begin log("vars.bootup_time") time := s s end)
server.register(namespace="streams",
"connection_status",
fun (s) -> begin log("streams.connection_status") "1:#{!s1_connected},2:#{!s2_connected},3:#{!s3_connected}" end)
server.register(namespace="vars",
"default_dj_fade",
fun (s) -> begin log("vars.default_dj_fade") default_dj_fade := float_of_string(s) s end)
server.register(namespace="dynamic_source",
description="Enable webstream output",
usage='start',
"output_start",
fun (s) -> begin log("dynamic_source.output_start")
notify([("schedule_table_id", !current_dyn_id)])
webstream_enabled := true "enabled" end)
server.register(namespace="dynamic_source",
description="Enable webstream output",
usage='stop',
"output_stop",
fun (s) -> begin log("dynamic_source.output_stop") webstream_enabled := false "disabled" end)
server.register(namespace="dynamic_source",
description="Set the streams cc_schedule row id",
usage="id <id>",
"id",
fun (s) -> begin log("dynamic_source.id") set_dynamic_source_id(s) end)
server.register(namespace="dynamic_source",
description="Get the streams cc_schedule row id",
usage="get_id",
"get_id",
fun (s) -> begin log("dynamic_source.get_id") get_dynamic_source_id() end)
#server.register(namespace="dynamic_source",
# description="Start a new dynamic source.",
# usage="start <uri>",
# "read_start",
# fun (uri) -> begin log("dynamic_source.read_start") begin_stream_read(uri) end)
#server.register(namespace="dynamic_source",
# description="Stop a dynamic source.",
# usage="stop <id>",
# "read_stop",
# fun (s) -> begin log("dynamic_source.read_stop") stop_stream_read(s) end)
#server.register(namespace="dynamic_source",
# description="Stop a dynamic source.",
# usage="stop <id>",
# "read_stop_all",
# fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source_all() end)
default = amplify(id="silence_src", 0.00001, noise())
ref_off_air_meta = ref off_air_meta
if !ref_off_air_meta == "" then
ref_off_air_meta := "Airtime - offline"
end
default = rewrite_metadata([("title", !ref_off_air_meta)], default)
ignore(output.dummy(default, fallible=true))
master_dj_enabled = ref false
live_dj_enabled = ref false
scheduled_play_enabled = ref false
def make_master_dj_available()
master_dj_enabled := true
end
def make_master_dj_unavailable()
master_dj_enabled := false
end
def make_live_dj_available()
live_dj_enabled := true
end
def make_live_dj_unavailable()
live_dj_enabled := false
end
def make_scheduled_play_available()
scheduled_play_enabled := true
just_switched := true
end
def make_scheduled_play_unavailable()
scheduled_play_enabled := false
end
def update_source_status(sourcename, status) =
command = "/usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh --source-name=#{sourcename} --source-status=#{status} &"
system(command)
log(command)
end
def live_dj_connect(header) =
update_source_status("live_dj", true)
end
def live_dj_disconnect() =
update_source_status("live_dj", false)
end
def master_dj_connect(header) =
update_source_status("master_dj", true)
end
def master_dj_disconnect() =
update_source_status("master_dj", false)
end
#auth function for live stream
def check_master_dj_client(user,password) =
log("master connected")
#get the output of the php script
ret = get_process_lines("python /usr/lib/airtime/pypo/bin/liquidsoap_scripts/liquidsoap_auth.py --master #{user} #{password}")
#ret has now the value of the live client (dj1,dj2, or djx), or "ERROR"/"unknown" ...
ret = list.hd(ret)
#return true to let the client transmit data, or false to tell harbor to decline
ret == "True"
end
def check_dj_client(user,password) =
log("live dj connected")
#get the output of the php script
ret = get_process_lines("python /usr/lib/airtime/pypo/bin/liquidsoap_scripts/liquidsoap_auth.py --dj #{user} #{password}")
#ret has now the value of the live client (dj1,dj2, or djx), or "ERROR"/"unknown" ...
hd = list.hd(ret)
log("Live DJ authenticated: #{hd}")
hd == "True"
end
s = switch(id="schedule_noise_switch",
track_sensitive=false,
transitions=[transition_default, transition],
[({!scheduled_play_enabled}, stream_queue), ({true}, default)]
)
s = if dj_live_stream_port != 0 and dj_live_stream_mp != "" then
dj_live =
audio_to_stereo(
input.harbor(id="live_dj_harbor",
dj_live_stream_mp,
port=dj_live_stream_port,
auth=check_dj_client,
max=40.,
on_connect=live_dj_connect,
on_disconnect=live_dj_disconnect))
ignore(output.dummy(dj_live, fallible=true))
switch(id="show_schedule_noise_switch",
track_sensitive=false,
transitions=[transition, transition],
[({!live_dj_enabled}, dj_live), ({true}, s)]
)
else
s
end
s = if master_live_stream_port != 0 and master_live_stream_mp != "" then
master_dj =
audio_to_stereo(
input.harbor(id="master_harbor",
master_live_stream_mp,
port=master_live_stream_port,
auth=check_master_dj_client,
max=40.,
on_connect=master_dj_connect,
on_disconnect=master_dj_disconnect))
ignore(output.dummy(master_dj, fallible=true))
switch(id="master_show_schedule_noise_switch",
track_sensitive=false,
transitions=[transition, transition],
[({!master_dj_enabled}, master_dj), ({true}, s)]
)
else
s
end
# Attach a skip command to the source s:
#add_skip_command(s)
server.register(namespace="streams",
description="Stop Master DJ source.",
usage="master_dj_stop",
"master_dj_stop",
fun (s) -> begin log("streams.master_dj_stop") make_master_dj_unavailable() "Done." end)
server.register(namespace="streams",
description="Start Master DJ source.",
usage="master_dj_start",
"master_dj_start",
fun (s) -> begin log("streams.master_dj_start") make_master_dj_available() "Done." end)
server.register(namespace="streams",
description="Stop Live DJ source.",
usage="live_dj_stop",
"live_dj_stop",
fun (s) -> begin log("streams.live_dj_stop") make_live_dj_unavailable() "Done." end)
server.register(namespace="streams",
description="Start Live DJ source.",
usage="live_dj_start",
"live_dj_start",
fun (s) -> begin log("streams.live_dj_start") make_live_dj_available() "Done." end)
server.register(namespace="streams",
description="Stop Scheduled Play source.",
usage="scheduled_play_stop",
"scheduled_play_stop",
fun (s) -> begin log("streams.scheduled_play_stop") make_scheduled_play_unavailable() "Done." end)
server.register(namespace="streams",
description="Start Scheduled Play source.",
usage="scheduled_play_start",
"scheduled_play_start",
fun (s) -> begin log("streams.scheduled_play_start") make_scheduled_play_available() "Done." end)
if output_sound_device then
success = ref false
log(output_sound_device_type)
%ifdef output.alsa
if output_sound_device_type == "ALSA" then
ignore(output.alsa(s))
success := true
end
%endif
%ifdef output.ao
if output_sound_device_type == "AO" then
ignore(output.ao(s))
success := true
end
%endif
%ifdef output.oss
if output_sound_device_type == "OSS" then
ignore(output.oss(s))
success := true
end
%endif
%ifdef output.portaudio
if output_sound_device_type == "Portaudio" then
ignore(output.portaudio(s))
success := true
end
%endif
%ifdef output.pulseaudio
if output_sound_device_type == "Pulseaudio" then
ignore(output.pulseaudio(s))
success := true
end
%endif
if (!success == false) then
ignore(output.prefered(s))
end
end
if s1_enable == true then
if s1_output == 'shoutcast' then
s1_namespace := "shoutcast_stream_1"
else
s1_namespace := s1_mount
end
server.register(namespace=!s1_namespace, "connected", fun (s) -> begin log("#{!s1_namespace}.connected") !s1_connected end)
output_to(s1_output, s1_type, s1_bitrate, s1_host, s1_port, s1_pass,
s1_mount, s1_url, s1_description, s1_genre, s1_user, s, "1",
s1_connected, s1_name, s1_channels)
end
if s2_enable == true then
if s2_output == 'shoutcast' then
s2_namespace := "shoutcast_stream_2"
else
s2_namespace := s2_mount
end
server.register(namespace=!s2_namespace, "connected", fun (s) -> begin log("#{!s2_namespace}.connected") !s2_connected end)
output_to(s2_output, s2_type, s2_bitrate, s2_host, s2_port, s2_pass,
s2_mount, s2_url, s2_description, s2_genre, s2_user, s, "2",
s2_connected, s2_name, s2_channels)
end
if s3_enable == true then
if s3_output == 'shoutcast' then
s3_namespace := "shoutcast_stream_3"
else
s3_namespace := s3_mount
end
server.register(namespace=!s3_namespace, "connected", fun (s) -> begin log("#{!s3_namespace}.connected") !s3_connected end)
output_to(s3_output, s3_type, s3_bitrate, s3_host, s3_port, s3_pass,
s3_mount, s3_url, s3_name, s3_genre, s3_user, s, "3",
s3_connected, s3_description, s3_channels)
end
command = "/usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh --liquidsoap-started &"
log(command)
system(command)

View file

@ -0,0 +1,68 @@
if bitrate == 24 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 24, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 24, stereo = false), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 32, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 32, stereo = false), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 48, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 48, stereo = false), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 64, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 64, stereo = false), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 96, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 96, stereo = false), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 128, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 128, stereo = false), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 160, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 160, stereo = false), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 192, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 192, stereo = false), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 224, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 224, stereo = false), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 256, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 256, stereo = false), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_stereo(%mp3(bitrate = 320, stereo = true), !source))
else
ignore(output_mono(%mp3(bitrate = 320, stereo = false), mean(!source)))
end
end

View file

@ -0,0 +1,14 @@
#!/bin/bash
############################################
# just a wrapper to call the notifyer #
# needed here to keep dirs/configs clean #
# and maybe to set user-rights #
############################################
# Absolute path to this script
SCRIPT=`readlink -f $0`
# Absolute path this script is in
SCRIPTPATH=`dirname $SCRIPT`
cd ${SCRIPTPATH}/../
timeout --signal=KILL 45 python pyponotify.py "$@"

View file

@ -0,0 +1,60 @@
if not icecast_vorbis_metadata then
source := add(normalize=false, [amplify(0.00001, noise()), !source])
end
if bitrate == 24 or bitrate == 32 or bitrate == 48 then
if stereo then
ignore(output_stereo(%vorbis(quality=-0.1, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=-0.1, channels = 1), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_stereo(%vorbis(quality=0, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0, channels = 1), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.2, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.2, channels = 1), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.4, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.4, channels = 1), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.5, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.5, channels = 1), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.6, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.6, channels = 1), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.7, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.7, channels = 1), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.8, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.8, channels = 1), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_stereo(%vorbis(quality=0.9, channels = 2), !source))
else
ignore(output_mono(%vorbis(quality=0.9, channels = 1), mean(!source)))
end
end

View file

@ -0,0 +1,68 @@
if bitrate == 24 then
if stereo then
ignore(output_stereo(%opus(bitrate = 24, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 24, channels = 1), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_stereo(%opus(bitrate = 32, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 32, channels = 1), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_stereo(%opus(bitrate = 48, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 48, channels = 1), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_stereo(%opus(bitrate = 64, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 64, channels = 1), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_stereo(%opus(bitrate = 96, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 96, channels = 1), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_stereo(%opus(bitrate = 128, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 128, channels = 1), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_stereo(%opus(bitrate = 160, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 160, channels = 1), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_stereo(%opus(bitrate = 192, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 192, channels = 1), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_stereo(%opus(bitrate = 224, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 224, channels = 1), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_stereo(%opus(bitrate = 256, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 256, channels = 1), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_stereo(%opus(bitrate = 320, channels = 2), !source))
else
ignore(output_mono(%opus(bitrate = 320, channels = 1), mean(!source)))
end
end

View file

@ -0,0 +1,162 @@
from threading import Thread
import urllib2
import xml.dom.minidom
import base64
from datetime import datetime
import traceback
import logging
import time
from api_clients import api_client
class ListenerStat(Thread):
HTTP_REQUEST_TIMEOUT = 30 # 30 second HTTP request timeout
def __init__(self, logger=None):
Thread.__init__(self)
self.api_client = api_client.AirtimeApiClient()
if logger is None:
self.logger = logging.getLogger()
else:
self.logger = logger
def get_node_text(self, nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
def get_stream_parameters(self):
#[{"user":"", "password":"", "url":"", "port":""},{},{}]
return self.api_client.get_stream_parameters()
def get_stream_server_xml(self, ip, url, is_shoutcast=False):
encoded = base64.b64encode("%(admin_user)s:%(admin_pass)s" % ip)
header = {"Authorization":"Basic %s" % encoded}
if is_shoutcast:
#user agent is required for shoutcast auth, otherwise it returns 404.
user_agent = "Mozilla/5.0 (Linux; rv:22.0) Gecko/20130405 Firefox/22.0"
header["User-Agent"] = user_agent
req = urllib2.Request(
#assuming that the icecast stats path is /admin/stats.xml
#need to fix this
url=url,
headers=header)
f = urllib2.urlopen(req, timeout=ListenerStat.HTTP_REQUEST_TIMEOUT)
document = f.read()
return document
def get_icecast_stats(self, ip):
url = 'http://%(host)s:%(port)s/admin/stats.xml' % ip
document = self.get_stream_server_xml(ip, url)
dom = xml.dom.minidom.parseString(document)
sources = dom.getElementsByTagName("source")
mount_stats = None
for s in sources:
#drop the leading '/' character
mount_name = s.getAttribute("mount")[1:]
if mount_name == ip["mount"]:
timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
listeners = s.getElementsByTagName("listeners")
num_listeners = 0
if len(listeners):
num_listeners = self.get_node_text(listeners[0].childNodes)
mount_stats = {"timestamp":timestamp, \
"num_listeners": num_listeners, \
"mount_name": mount_name}
return mount_stats
def get_shoutcast_stats(self, ip):
url = 'http://%(host)s:%(port)s/admin.cgi?sid=1&mode=viewxml' % ip
document = self.get_stream_server_xml(ip, url, is_shoutcast=True)
dom = xml.dom.minidom.parseString(document)
current_listeners = dom.getElementsByTagName("CURRENTLISTENERS")
timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
num_listeners = 0
if len(current_listeners):
num_listeners = self.get_node_text(current_listeners[0].childNodes)
mount_stats = {"timestamp":timestamp, \
"num_listeners": num_listeners, \
"mount_name": "shoutcast"}
return mount_stats
def get_stream_stats(self, stream_parameters):
stats = []
#iterate over stream_parameters which is a list of dicts. Each dict
#represents one Airtime stream (currently this limit is 3).
#Note that there can be optimizations done, since if all three
#streams are the same server, we will still initiate 3 separate
#connections
for k, v in stream_parameters.items():
if v["enable"] == 'true':
try:
if v["output"] == "icecast":
mount_stats = self.get_icecast_stats(v)
if mount_stats: stats.append(mount_stats)
else:
stats.append(self.get_shoutcast_stats(v))
self.update_listener_stat_error(v["mount"], 'OK')
except Exception, e:
try:
self.update_listener_stat_error(v["mount"], str(e))
except Exception, e:
self.logger.error('Exception: %s', e)
return stats
def push_stream_stats(self, stats):
self.api_client.push_stream_stats(stats)
def update_listener_stat_error(self, stream_id, error):
keyname = '%s_listener_stat_error' % stream_id
data = {keyname: error}
self.api_client.update_stream_setting_table(data)
def run(self):
#Wake up every 120 seconds and gather icecast statistics. Note that we
#are currently querying the server every 2 minutes for list of
#mountpoints as well. We could remove this query if we hooked into
#rabbitmq events, and listened for these changes instead.
while True:
try:
stream_parameters = self.get_stream_parameters()
stats = self.get_stream_stats(stream_parameters["stream_params"])
if stats:
self.push_stream_stats(stats)
except Exception, e:
self.logger.error('Exception: %s', e)
time.sleep(120)
if __name__ == "__main__":
# create logger
logger = logging.getLogger('std_out')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
#ch = logging.StreamHandler()
#ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)s - %(levelname)s - %(message)s')
# add formatter to ch
#ch.setFormatter(formatter)
# add ch to logger
#logger.addHandler(ch)
ls = ListenerStat(logger)
ls.run()

View file

@ -0,0 +1,58 @@
[loggers]
keys=root,fetch,push,recorder,message_h
[handlers]
keys=pypo,recorder,message_h
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=pypo
[logger_fetch]
level=DEBUG
handlers=pypo
qualname=fetch
propagate=0
[logger_push]
level=DEBUG
handlers=pypo
qualname=push
propagate=0
[logger_recorder]
level=DEBUG
handlers=recorder
qualname=recorder
propagate=0
[logger_message_h]
level=DEBUG
handlers=message_h
qualname=message_h
propagate=0
[handler_pypo]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("/var/log/airtime/pypo/pypo.log", 'a', 5000000, 10,)
[handler_recorder]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("/var/log/airtime/pypo/show-recorder.log", 'a', 1000000, 5,)
[handler_message_h]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("/var/log/airtime/pypo/message-handler.log", 'a', 1000000, 5,)
[formatter_simpleFormatter]
format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s
datefmt=

View file

View file

@ -0,0 +1,161 @@
from subprocess import Popen, PIPE
import re
import os
import sys
import shutil
import tempfile
import logging
logger = logging.getLogger()
def get_process_output(command):
"""
Run subprocess and return stdout
"""
logger.debug(command)
p = Popen(command, stdout=PIPE, stderr=PIPE)
return p.communicate()[0].strip()
def run_process(command):
"""
Run subprocess and return "return code"
"""
p = Popen(command, stdout=PIPE, stderr=PIPE)
return os.waitpid(p.pid, 0)[1]
def get_mime_type(file_path):
"""
Attempts to get the mime type but will return prematurely if the process
takes longer than 5 seconds. Note that this function should only be called
for files which do not have a mp3/ogg/flac extension.
"""
command = ['timeout', '5', 'file', '-b', '--mime-type', file_path]
return get_process_output(command)
def duplicate_file(file_path):
"""
Makes a duplicate of the file and returns the path of this duplicate file.
"""
fsrc = open(file_path, 'r')
fdst = tempfile.NamedTemporaryFile(delete=False)
logger.info("Copying %s to %s" % (file_path, fdst.name))
shutil.copyfileobj(fsrc, fdst)
fsrc.close()
fdst.close()
return fdst.name
def get_file_type(file_path):
file_type = None
if re.search(r'mp3$', file_path, re.IGNORECASE):
file_type = 'mp3'
elif re.search(r'og(g|a)$', file_path, re.IGNORECASE):
file_type = 'vorbis'
elif re.search(r'm4a$', file_path, re.IGNORECASE):
file_type = 'mp4'
elif re.search(r'flac$', file_path, re.IGNORECASE):
file_type = 'flac'
else:
mime_type = get_mime_type(file_path)
if 'mpeg' in mime_type:
file_type = 'mp3'
elif 'ogg' in mime_type:
file_type = 'vorbis'
elif 'mp4' in mime_type:
file_type = 'mp4'
elif 'flac' in mime_type:
file_type = 'flac'
return file_type
def calculate_replay_gain(file_path):
"""
This function accepts files of type mp3/ogg/flac and returns a calculated
ReplayGain value in dB.
If the value cannot be calculated for some reason, then we default to 0
(Unity Gain).
http://wiki.hydrogenaudio.org/index.php?title=ReplayGain_1.0_specification
"""
try:
"""
Making a duplicate is required because the ReplayGain extraction utilities we use
make unwanted modifications to the file.
"""
search = None
temp_file_path = duplicate_file(file_path)
file_type = get_file_type(file_path)
nice_level = '19'
if file_type:
if file_type == 'mp3':
if run_process(['which', 'mp3gain']) == 0:
command = ['nice', '-n', nice_level, 'mp3gain', '-q', temp_file_path]
out = get_process_output(command)
search = re.search(r'Recommended "Track" dB change: (.*)', \
out)
else:
logger.warn("mp3gain not found")
elif file_type == 'vorbis':
if run_process(['which', 'ogginfo']) == 0 and \
run_process(['which', 'vorbisgain']) == 0:
command = ['nice', '-n', nice_level, 'vorbisgain', '-q', '-f', temp_file_path]
run_process(command)
out = get_process_output(['ogginfo', temp_file_path])
search = re.search(r'REPLAYGAIN_TRACK_GAIN=(.*) dB', out)
else:
logger.warn("vorbisgain/ogginfo not found")
elif file_type == 'mp4':
if run_process(['which', 'aacgain']) == 0:
command = ['nice', '-n', nice_level, 'aacgain', '-q', temp_file_path]
out = get_process_output(command)
search = re.search(r'Recommended "Track" dB change: (.*)', \
out)
else:
logger.warn("aacgain not found")
elif file_type == 'flac':
if run_process(['which', 'metaflac']) == 0:
command = ['nice', '-n', nice_level, 'metaflac', \
'--add-replay-gain', temp_file_path]
run_process(command)
command = ['nice', '-n', nice_level, 'metaflac', \
'--show-tag=REPLAYGAIN_TRACK_GAIN', \
temp_file_path]
out = get_process_output(command)
search = re.search(r'REPLAYGAIN_TRACK_GAIN=(.*) dB', out)
else: logger.warn("metaflac not found")
except Exception, e:
logger.error(str(e))
finally:
#no longer need the temp, file simply remove it.
try: os.remove(temp_file_path)
except: pass
replay_gain = 0
if search:
matches = search.groups()
if len(matches) == 1:
replay_gain = matches[0]
else:
logger.warn("Received more than 1 match in: '%s'" % str(matches))
return replay_gain
# Example of running from command line:
# python replay_gain.py /path/to/filename.mp3
if __name__ == "__main__":
print calculate_replay_gain(sys.argv[1])

View file

@ -0,0 +1,86 @@
from threading import Thread
import traceback
import os
import time
import logging
from media.update import replaygain
class ReplayGainUpdater(Thread):
"""
The purpose of the class is to query the server for a list of files which
do not have a ReplayGain value calculated. This class will iterate over the
list, calculate the values, update the server and repeat the process until
the server reports there are no files left.
This class will see heavy activity right after a 2.1->2.2 upgrade since 2.2
introduces ReplayGain normalization. A fresh install of Airtime 2.2 will
see this class not used at all since a file imported in 2.2 will
automatically have its ReplayGain value calculated.
"""
@staticmethod
def start_reply_gain(apc):
me = ReplayGainUpdater(apc)
me.daemon = True
me.start()
def __init__(self,apc):
Thread.__init__(self)
self.api_client = apc
self.logger = logging.getLogger()
def main(self):
raw_response = self.api_client.list_all_watched_dirs()
if 'dirs' not in raw_response:
self.logger.error("Could not get a list of watched directories \
with a dirs attribute. Printing full request:")
self.logger.error( raw_response )
return
directories = raw_response['dirs']
for dir_id, dir_path in directories.iteritems():
try:
# keep getting few rows at a time for current music_dir (stor
# or watched folder).
total = 0
while True:
# return a list of pairs where the first value is the
# file's database row id and the second value is the
# filepath
files = self.api_client.get_files_without_replay_gain_value(dir_id)
processed_data = []
for f in files:
full_path = os.path.join(dir_path, f['fp'])
processed_data.append((f['id'], replaygain.calculate_replay_gain(full_path)))
total += 1
try:
if len(processed_data):
self.api_client.update_replay_gain_values(processed_data)
except Exception as e:
self.logger.error(e)
self.logger.debug(traceback.format_exc())
if len(files) == 0: break
self.logger.info("Processed: %d songs" % total)
except Exception, e:
self.logger.error(e)
self.logger.debug(traceback.format_exc())
def run(self):
while True:
try:
self.logger.info("Running replaygain updater")
self.main()
# Sleep for 5 minutes in case new files have been added
except Exception, e:
self.logger.error('ReplayGainUpdater Exception: %s', traceback.format_exc())
self.logger.error(e)
time.sleep(60 * 5)
if __name__ == "__main__":
rgu = ReplayGainUpdater()
rgu.main()

View file

@ -0,0 +1,94 @@
from threading import Thread
import traceback
import time
import subprocess
import json
class SilanAnalyzer(Thread):
"""
The purpose of the class is to query the server for a list of files which
do not have a Silan value calculated. This class will iterate over the
list calculate the values, update the server and repeat the process until
the server reports there are no files left.
"""
@staticmethod
def start_silan(apc, logger):
me = SilanAnalyzer(apc, logger)
me.start()
def __init__(self, apc, logger):
Thread.__init__(self)
self.api_client = apc
self.logger = logger
def main(self):
while True:
# keep getting few rows at a time for current music_dir (stor
# or watched folder).
total = 0
# return a list of pairs where the first value is the
# file's database row id and the second value is the
# filepath
files = self.api_client.get_files_without_silan_value()
total_files = len(files)
if total_files == 0: return
processed_data = []
for f in files:
full_path = f['fp']
# silence detect(set default queue in and out)
try:
data = {}
command = ['nice', '-n', '19', 'silan', '-b', '-f', 'JSON', full_path]
try:
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
comm = proc.communicate()
if len(comm):
out = comm[0].strip('\r\n')
info = json.loads(out)
try: data['length'] = str('{0:f}'.format(info['file duration']))
except: pass
try: data['cuein'] = str('{0:f}'.format(info['sound'][0][0]))
except: pass
try: data['cueout'] = str('{0:f}'.format(info['sound'][-1][1]))
except: pass
except Exception, e:
self.logger.warn(str(command))
self.logger.warn(e)
processed_data.append((f['id'], data))
total += 1
if total % 5 == 0:
self.logger.info("Total %s / %s files has been processed.." % (total, total_files))
except Exception, e:
self.logger.error(e)
self.logger.error(traceback.format_exc())
try:
self.api_client.update_cue_values_by_silan(processed_data)
except Exception ,e:
self.logger.error(e)
self.logger.error(traceback.format_exc())
self.logger.info("Processed: %d songs" % total)
def run(self):
while True:
try:
self.logger.info("Running Silan analyzer")
self.main()
except Exception, e:
self.logger.error('Silan Analyzer Exception: %s', traceback.format_exc())
self.logger.error(e)
self.logger.info("Sleeping for 5...")
time.sleep(60 * 5)
if __name__ == "__main__":
from api_clients import api_client
import logging
logging.basicConfig(level=logging.DEBUG)
api_client = api_client.AirtimeApiClient()
SilanAnalyzer.start_silan(api_client, logging)

View file

@ -0,0 +1,28 @@
[loggers]
keys=root,notify
[handlers]
keys=notify
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=notify
[logger_notify]
level=DEBUG
handlers=notify
qualname=notify
propagate=0
[handler_notify]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("/var/log/airtime/pypo/notify.log", 'a', 1000000, 5,)
[formatter_simpleFormatter]
format=%(asctime)s %(levelname)s - [%(filename)s : %(funcName)s() : line %(lineno)d] - %(message)s
datefmt=

View file

@ -0,0 +1,17 @@
import re
def version_cmp(version1, version2):
def normalize(v):
return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")]
return cmp(normalize(version1), normalize(version2))
def date_interval_to_seconds(interval):
"""
Convert timedelta object into int representing the number of seconds. If
number of seconds is less than 0, then return 0.
"""
seconds = (interval.microseconds + \
(interval.seconds + interval.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
return seconds

View file

@ -0,0 +1,85 @@
############################################
# pypo - configuration #
############################################
# Set the type of client you are using.
# Currently supported types:
# 1) "obp" = Open Broadcast Platform
# 2) "airtime"
#
api_client = "airtime"
############################################
# Cache Directories #
# *include* trailing slash !! #
############################################
cache_dir = '/var/tmp/airtime/pypo/cache/'
file_dir = '/var/tmp/airtime/pypo/files/'
tmp_dir = '/var/tmp/airtime/pypo/tmp/'
############################################
# Setup Directories #
# Do *not* include trailing slash !! #
############################################
cache_base_dir = '/var/tmp/airtime/pypo'
bin_dir = '/usr/lib/airtime/pypo'
log_base_dir = '/var/log/airtime'
pypo_log_dir = '/var/log/airtime/pypo'
liquidsoap_log_dir = '/var/log/airtime/pypo-liquidsoap'
############################################
# Liquidsoap settings #
############################################
ls_host = '127.0.0.1'
ls_port = '1234'
############################################
# RabbitMQ settings #
############################################
rabbitmq_host = 'localhost'
rabbitmq_user = 'guest'
rabbitmq_password = 'guest'
rabbitmq_vhost = '/'
############################################
# pypo preferences #
############################################
# Poll interval in seconds.
#
# This will rarely need to be changed because any schedule changes are
# automatically sent to pypo immediately.
#
# This is how often the poll script downloads new schedules and files from the
# server in the event that no changes are made to the schedule.
#
poll_interval = 3600 # in seconds.
# Push interval in seconds.
#
# This is how often the push script checks whether it has something new to
# push to liquidsoap.
#
# It's hard to imagine a situation where this should be more than 1 second.
#
push_interval = 1 # in seconds
# 'pre' or 'otf'. 'pre' cues while playlist preparation
# while 'otf' (on the fly) cues while loading into ls
# (needs the post_processor patch)
cue_style = 'pre'
############################################
# Recorded Audio settings #
############################################
record_bitrate = 256
record_samplerate = 44100
record_channels = 2
record_sample_size = 16
#can be either ogg|mp3, mp3 recording requires installation of the package "lame"
record_file_type = 'ogg'
# base path to store recordered shows at
base_recorded_files = '/var/tmp/airtime/show-recorder/'

View file

@ -0,0 +1,299 @@
"""
Python part of radio playout (pypo)
"""
from optparse import OptionParser
from datetime import datetime
import telnetlib
import time
import sys
import signal
import logging
import locale
import os
import re
from Queue import Queue
from threading import Lock
from pypopush import PypoPush
from pypofetch import PypoFetch
from pypofile import PypoFile
from recorder import Recorder
from listenerstat import ListenerStat
from pypomessagehandler import PypoMessageHandler
from pypoliquidsoap import PypoLiquidsoap
from timeout import ls_timeout
from media.update.replaygainupdater import ReplayGainUpdater
from media.update.silananalyzer import SilanAnalyzer
from configobj import ConfigObj
# custom imports
from api_clients import api_client
from std_err_override import LogWriter
import pure
# Set up command-line options
parser = OptionParser()
# help screen / info
usage = "%prog [options]" + " - python playout system"
parser = OptionParser(usage=usage)
# Options
parser.add_option("-v", "--compat",
help="Check compatibility with server API version",
default=False,
action="store_true",
dest="check_compat")
parser.add_option("-t", "--test",
help="Do a test to make sure everything is working properly.",
default=False,
action="store_true",
dest="test")
parser.add_option("-b",
"--cleanup",
help="Cleanup",
default=False,
action="store_true",
dest="cleanup")
parser.add_option("-c",
"--check",
help="Check the cached schedule and exit",
default=False,
action="store_true",
dest="check")
# parse options
(options, args) = parser.parse_args()
LIQUIDSOAP_MIN_VERSION = "1.1.1"
#need to wait for Python 2.7 for this..
#logging.captureWarnings(True)
# configure logging
try:
logging.config.fileConfig("logging.cfg")
logger = logging.getLogger()
LogWriter.override_std_err(logger)
except Exception, e:
print "Couldn't configure logging"
sys.exit(1)
def configure_locale():
"""
Silly hacks to force Python 2.x to run in UTF-8 mode. Not portable at all,
however serves our purpose at the moment.
More information available here:
http://stackoverflow.com/questions/3828723/why-we-need-sys-setdefaultencodingutf-8-in-a-py-script
"""
logger.debug("Before %s", locale.nl_langinfo(locale.CODESET))
current_locale = locale.getlocale()
if current_locale[1] is None:
logger.debug("No locale currently set. Attempting to get default locale.")
default_locale = locale.getdefaultlocale()
if default_locale[1] is None:
logger.debug("No default locale exists. Let's try loading from \
/etc/default/locale")
if os.path.exists("/etc/default/locale"):
locale_config = ConfigObj('/etc/default/locale')
lang = locale_config.get('LANG')
new_locale = lang
else:
logger.error("/etc/default/locale could not be found! Please \
run 'sudo update-locale' from command-line.")
sys.exit(1)
else:
new_locale = default_locale
logger.info("New locale set to: %s", \
locale.setlocale(locale.LC_ALL, new_locale))
reload(sys)
sys.setdefaultencoding("UTF-8")
current_locale_encoding = locale.getlocale()[1].lower()
logger.debug("sys default encoding %s", sys.getdefaultencoding())
logger.debug("After %s", locale.nl_langinfo(locale.CODESET))
if current_locale_encoding not in ['utf-8', 'utf8']:
logger.error("Need a UTF-8 locale. Currently '%s'. Exiting..." % \
current_locale_encoding)
sys.exit(1)
configure_locale()
# loading config file
try:
config = ConfigObj('/etc/airtime/airtime.conf')
except Exception, e:
logger.error('Error loading config file: %s', e)
sys.exit(1)
class Global:
def __init__(self, api_client):
self.api_client = api_client
def selfcheck(self):
return self.api_client.is_server_compatible()
def test_api(self):
self.api_client.test()
def keyboardInterruptHandler(signum, frame):
logger = logging.getLogger()
logger.info('\nKeyboard Interrupt\n')
sys.exit(0)
@ls_timeout
def liquidsoap_get_info(telnet_lock, host, port, logger):
logger.debug("Checking to see if Liquidsoap is running")
try:
telnet_lock.acquire()
tn = telnetlib.Telnet(host, port)
msg = "version\n"
tn.write(msg)
tn.write("exit\n")
response = tn.read_all()
except Exception, e:
logger.error(str(e))
return None
finally:
telnet_lock.release()
return get_liquidsoap_version(response)
def get_liquidsoap_version(version_string):
m = re.match(r"Liquidsoap (\d+.\d+.\d+)", version_string)
if m:
return m.group(1)
else:
return None
if m:
current_version = m.group(1)
return pure.version_cmp(current_version, LIQUIDSOAP_MIN_VERSION) >= 0
return False
def liquidsoap_startup_test():
liquidsoap_version_string = \
liquidsoap_get_info(telnet_lock, ls_host, ls_port, logger)
while not liquidsoap_version_string:
logger.warning("Liquidsoap doesn't appear to be running!, " + \
"Sleeping and trying again")
time.sleep(1)
liquidsoap_version_string = \
liquidsoap_get_info(telnet_lock, ls_host, ls_port, logger)
while pure.version_cmp(liquidsoap_version_string, LIQUIDSOAP_MIN_VERSION) < 0:
logger.warning("Liquidsoap is running but in incorrect version! " + \
"Make sure you have at least Liquidsoap %s installed" % LIQUIDSOAP_MIN_VERSION)
time.sleep(1)
liquidsoap_version_string = \
liquidsoap_get_info(telnet_lock, ls_host, ls_port, logger)
logger.info("Liquidsoap version string found %s" % liquidsoap_version_string)
if __name__ == '__main__':
logger.info('###########################################')
logger.info('# *** pypo *** #')
logger.info('# Liquidsoap Scheduled Playout System #')
logger.info('###########################################')
#Although all of our calculations are in UTC, it is useful to know what timezone
#the local machine is, so that we have a reference for what time the actual
#log entries were made
logger.info("Timezone: %s" % str(time.tzname))
logger.info("UTC time: %s" % str(datetime.utcnow()))
signal.signal(signal.SIGINT, keyboardInterruptHandler)
api_client = api_client.AirtimeApiClient()
g = Global(api_client)
while not g.selfcheck():
time.sleep(5)
success = False
while not success:
try:
api_client.register_component('pypo')
success = True
except Exception, e:
logger.error(str(e))
time.sleep(10)
telnet_lock = Lock()
ls_host = config['pypo']['ls_host']
ls_port = config['pypo']['ls_port']
liquidsoap_startup_test()
if options.test:
g.test_api()
sys.exit(0)
ReplayGainUpdater.start_reply_gain(api_client)
SilanAnalyzer.start_silan(api_client, logger)
pypoFetch_q = Queue()
recorder_q = Queue()
pypoPush_q = Queue()
pypo_liquidsoap = PypoLiquidsoap(logger, telnet_lock,\
ls_host, ls_port)
"""
This queue is shared between pypo-fetch and pypo-file, where pypo-file
is the consumer. Pypo-fetch will send every schedule it gets to pypo-file
and pypo will parse this schedule to determine which file has the highest
priority, and retrieve it.
"""
media_q = Queue()
# Pass only the configuration sections needed; PypoMessageHandler only needs rabbitmq settings
pmh = PypoMessageHandler(pypoFetch_q, recorder_q, config['rabbitmq'])
pmh.daemon = True
pmh.start()
pfile = PypoFile(media_q, config['pypo'])
pfile.daemon = True
pfile.start()
pf = PypoFetch(pypoFetch_q, pypoPush_q, media_q, telnet_lock, pypo_liquidsoap, config['pypo'])
pf.daemon = True
pf.start()
pp = PypoPush(pypoPush_q, telnet_lock, pypo_liquidsoap, config['pypo'])
pp.daemon = True
pp.start()
recorder = Recorder(recorder_q)
recorder.daemon = True
recorder.start()
stat = ListenerStat()
stat.daemon = True
stat.start()
pf.join()
logger.info("System exit")

View file

@ -0,0 +1,593 @@
# -*- coding: utf-8 -*-
import os
import sys
import time
import logging.config
import json
import telnetlib
import copy
import subprocess
import signal
from datetime import datetime
import traceback
import pure
from Queue import Empty
from threading import Thread
from subprocess import Popen, PIPE
from api_clients import api_client
from std_err_override import LogWriter
from timeout import ls_timeout
# configure logging
logging_cfg = os.path.join(os.path.dirname(__file__), "logging.cfg")
logging.config.fileConfig(logging_cfg)
logger = logging.getLogger()
LogWriter.override_std_err(logger)
def keyboardInterruptHandler(signum, frame):
logger = logging.getLogger()
logger.info('\nKeyboard Interrupt\n')
sys.exit(0)
signal.signal(signal.SIGINT, keyboardInterruptHandler)
#need to wait for Python 2.7 for this..
#logging.captureWarnings(True)
POLL_INTERVAL = 1800
class PypoFetch(Thread):
def __init__(self, pypoFetch_q, pypoPush_q, media_q, telnet_lock, pypo_liquidsoap, config):
Thread.__init__(self)
#Hacky...
PypoFetch.ref = self
self.api_client = api_client.AirtimeApiClient()
self.fetch_queue = pypoFetch_q
self.push_queue = pypoPush_q
self.media_prepare_queue = media_q
self.last_update_schedule_timestamp = time.time()
self.config = config
self.listener_timeout = POLL_INTERVAL
self.telnet_lock = telnet_lock
self.logger = logging.getLogger()
self.pypo_liquidsoap = pypo_liquidsoap
self.cache_dir = os.path.join(config["cache_dir"], "scheduler")
self.logger.debug("Cache dir %s", self.cache_dir)
try:
if not os.path.isdir(dir):
"""
We get here if path does not exist, or path does exist but
is a file. We are not handling the second case, but don't
think we actually care about handling it.
"""
self.logger.debug("Cache dir does not exist. Creating...")
os.makedirs(dir)
except Exception, e:
pass
self.schedule_data = []
self.logger.info("PypoFetch: init complete")
"""
Handle a message from RabbitMQ, put it into our yucky global var.
Hopefully there is a better way to do this.
"""
def handle_message(self, message):
try:
self.logger.info("Received event from Pypo Message Handler: %s" % message)
m = json.loads(message)
command = m['event_type']
self.logger.info("Handling command: " + command)
if command == 'update_schedule':
self.schedule_data = m['schedule']
self.process_schedule(self.schedule_data)
elif command == 'reset_liquidsoap_bootstrap':
self.set_bootstrap_variables()
elif command == 'update_stream_setting':
self.logger.info("Updating stream setting...")
self.regenerate_liquidsoap_conf(m['setting'])
elif command == 'update_stream_format':
self.logger.info("Updating stream format...")
self.update_liquidsoap_stream_format(m['stream_format'])
elif command == 'update_station_name':
self.logger.info("Updating station name...")
self.update_liquidsoap_station_name(m['station_name'])
elif command == 'update_transition_fade':
self.logger.info("Updating transition_fade...")
self.update_liquidsoap_transition_fade(m['transition_fade'])
elif command == 'switch_source':
self.logger.info("switch_on_source show command received...")
self.pypo_liquidsoap.\
get_telnet_dispatcher().\
switch_source(m['sourcename'], m['status'])
elif command == 'disconnect_source':
self.logger.info("disconnect_on_source show command received...")
self.pypo_liquidsoap.get_telnet_dispatcher().\
disconnect_source(m['sourcename'])
else:
self.logger.info("Unknown command: %s" % command)
# update timeout value
if command == 'update_schedule':
self.listener_timeout = POLL_INTERVAL
else:
self.listener_timeout = self.last_update_schedule_timestamp - time.time() + POLL_INTERVAL
if self.listener_timeout < 0:
self.listener_timeout = 0
self.logger.info("New timeout: %s" % self.listener_timeout)
except Exception, e:
top = traceback.format_exc()
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", top)
self.logger.error("Exception in handling Message Handler message: %s", e)
def switch_source_temp(self, sourcename, status):
self.logger.debug('Switching source: %s to "%s" status', sourcename, status)
command = "streams."
if sourcename == "master_dj":
command += "master_dj_"
elif sourcename == "live_dj":
command += "live_dj_"
elif sourcename == "scheduled_play":
command += "scheduled_play_"
if status == "on":
command += "start\n"
else:
command += "stop\n"
return command
"""
Initialize Liquidsoap environment
"""
def set_bootstrap_variables(self):
self.logger.debug('Getting information needed on bootstrap from Airtime')
try:
info = self.api_client.get_bootstrap_info()
except Exception, e:
self.logger.error('Unable to get bootstrap info.. Exiting pypo...')
self.logger.error(str(e))
self.logger.debug('info:%s', info)
commands = []
for k, v in info['switch_status'].iteritems():
commands.append(self.switch_source_temp(k, v))
stream_format = info['stream_label']
station_name = info['station_name']
fade = info['transition_fade']
commands.append(('vars.stream_metadata_type %s\n' % stream_format).encode('utf-8'))
commands.append(('vars.station_name %s\n' % station_name).encode('utf-8'))
commands.append(('vars.default_dj_fade %s\n' % fade).encode('utf-8'))
self.pypo_liquidsoap.get_telnet_dispatcher().telnet_send(commands)
self.pypo_liquidsoap.clear_all_queues()
self.pypo_liquidsoap.clear_queue_tracker()
def restart_liquidsoap(self):
try:
"""do not block - if we receive the lock then good - no other thread
will try communicating with Liquidsoap. If we don't receive, it may
mean some thread blocked and is still holding the lock. Restarting
Liquidsoap will cause that thread to release the lock as an Exception
will be thrown."""
self.telnet_lock.acquire(False)
self.logger.info("Restarting Liquidsoap")
subprocess.call('/etc/init.d/airtime-liquidsoap restart', shell=True, close_fds=True)
#Wait here and poll Liquidsoap until it has started up
self.logger.info("Waiting for Liquidsoap to start")
while True:
try:
tn = telnetlib.Telnet(self.config['ls_host'], self.config['ls_port'])
tn.write("exit\n")
tn.read_all()
self.logger.info("Liquidsoap is up and running")
break
except Exception, e:
#sleep 0.5 seconds and try again
time.sleep(0.5)
except Exception, e:
self.logger.error(e)
finally:
if self.telnet_lock.locked():
self.telnet_lock.release()
"""
TODO: This function needs to be way shorter, and refactored :/ - MK
"""
def regenerate_liquidsoap_conf(self, setting):
existing = {}
setting = sorted(setting.items())
try:
fh = open('/etc/airtime/liquidsoap.cfg', 'r')
except IOError, e:
#file does not exist
self.restart_liquidsoap()
return
self.logger.info("Reading existing config...")
# read existing conf file and build dict
while True:
line = fh.readline()
# empty line means EOF
if not line:
break
line = line.strip()
if not len(line) or line[0] == "#":
continue
try:
key, value = line.split('=', 1)
except ValueError:
continue
key = key.strip()
value = value.strip()
value = value.replace('"', '')
if value == '' or value == "0":
value = ''
existing[key] = value
fh.close()
# dict flag for any change in config
change = {}
# this flag is to detect disable -> disable change
# in that case, we don't want to restart even if there are changes.
state_change_restart = {}
#restart flag
restart = False
self.logger.info("Looking for changes...")
# look for changes
for k, s in setting:
if "output_sound_device" in s[u'keyname'] or "icecast_vorbis_metadata" in s[u'keyname']:
dump, stream = s[u'keyname'].split('_', 1)
state_change_restart[stream] = False
# This is the case where restart is required no matter what
if (existing[s[u'keyname']] != str(s[u'value'])):
self.logger.info("'Need-to-restart' state detected for %s...", s[u'keyname'])
restart = True;
elif "master_live_stream_port" in s[u'keyname'] or "master_live_stream_mp" in s[u'keyname'] or "dj_live_stream_port" in s[u'keyname'] or "dj_live_stream_mp" in s[u'keyname'] or "off_air_meta" in s[u'keyname']:
if (existing[s[u'keyname']] != s[u'value']):
self.logger.info("'Need-to-restart' state detected for %s...", s[u'keyname'])
restart = True;
else:
stream, dump = s[u'keyname'].split('_', 1)
if "_output" in s[u'keyname']:
if (existing[s[u'keyname']] != s[u'value']):
self.logger.info("'Need-to-restart' state detected for %s...", s[u'keyname'])
restart = True;
state_change_restart[stream] = True
elif (s[u'value'] != 'disabled'):
state_change_restart[stream] = True
else:
state_change_restart[stream] = False
else:
# setting inital value
if stream not in change:
change[stream] = False
if not (s[u'value'] == existing[s[u'keyname']]):
self.logger.info("Keyname: %s, Current value: %s, New Value: %s", s[u'keyname'], existing[s[u'keyname']], s[u'value'])
change[stream] = True
# set flag change for sound_device alway True
self.logger.info("Change:%s, State_Change:%s...", change, state_change_restart)
for k, v in state_change_restart.items():
if k == "sound_device" and v:
restart = True
elif v and change[k]:
self.logger.info("'Need-to-restart' state detected for %s...", k)
restart = True
# rewrite
if restart:
self.restart_liquidsoap()
else:
self.logger.info("No change detected in setting...")
self.update_liquidsoap_connection_status()
@ls_timeout
def update_liquidsoap_connection_status(self):
"""
updates the status of Liquidsoap connection to the streaming server
This function updates the bootup time variable in Liquidsoap script
"""
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.config['ls_host'], self.config['ls_port'])
# update the boot up time of Liquidsoap. Since Liquidsoap is not restarting,
# we are manually adjusting the bootup time variable so the status msg will get
# updated.
current_time = time.time()
boot_up_time_command = "vars.bootup_time " + str(current_time) + "\n"
self.logger.info(boot_up_time_command)
tn.write(boot_up_time_command)
connection_status = "streams.connection_status\n"
self.logger.info(connection_status)
tn.write(connection_status)
tn.write('exit\n')
output = tn.read_all()
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
output_list = output.split("\r\n")
stream_info = output_list[2]
# streamin info is in the form of:
# eg. s1:true,2:true,3:false
streams = stream_info.split(",")
self.logger.info(streams)
fake_time = current_time + 1
for s in streams:
info = s.split(':')
stream_id = info[0]
status = info[1]
if(status == "true"):
self.api_client.notify_liquidsoap_status("OK", stream_id, str(fake_time))
@ls_timeout
def update_liquidsoap_stream_format(self, stream_format):
# Push stream metadata to liquidsoap
# TODO: THIS LIQUIDSOAP STUFF NEEDS TO BE MOVED TO PYPO-PUSH!!!
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.config['ls_host'], self.config['ls_port'])
command = ('vars.stream_metadata_type %s\n' % stream_format).encode('utf-8')
self.logger.info(command)
tn.write(command)
tn.write('exit\n')
tn.read_all()
except Exception, e:
self.logger.error("Exception %s", e)
finally:
self.telnet_lock.release()
@ls_timeout
def update_liquidsoap_transition_fade(self, fade):
# Push stream metadata to liquidsoap
# TODO: THIS LIQUIDSOAP STUFF NEEDS TO BE MOVED TO PYPO-PUSH!!!
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.config['ls_host'], self.config['ls_port'])
command = ('vars.default_dj_fade %s\n' % fade).encode('utf-8')
self.logger.info(command)
tn.write(command)
tn.write('exit\n')
tn.read_all()
except Exception, e:
self.logger.error("Exception %s", e)
finally:
self.telnet_lock.release()
@ls_timeout
def update_liquidsoap_station_name(self, station_name):
# Push stream metadata to liquidsoap
# TODO: THIS LIQUIDSOAP STUFF NEEDS TO BE MOVED TO PYPO-PUSH!!!
try:
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.config['ls_host'], self.config['ls_port'])
command = ('vars.station_name %s\n' % station_name).encode('utf-8')
self.logger.info(command)
tn.write(command)
tn.write('exit\n')
tn.read_all()
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
except Exception, e:
self.logger.error("Exception %s", e)
"""
Process the schedule
- Reads the scheduled entries of a given range (actual time +/- "prepare_ahead" / "cache_for")
- Saves a serialized file of the schedule
- playlists are prepared. (brought to liquidsoap format) and, if not mounted via nsf, files are copied
to the cache dir (Folder-structure: cache/YYYY-MM-DD-hh-mm-ss)
- runs the cleanup routine, to get rid of unused cached files
"""
def process_schedule(self, schedule_data):
self.last_update_schedule_timestamp = time.time()
self.logger.debug(schedule_data)
media = schedule_data["media"]
media_filtered = {}
# Download all the media and put playlists in liquidsoap "annotate" format
try:
"""
Make sure cache_dir exists
"""
download_dir = self.cache_dir
try:
os.makedirs(download_dir)
except Exception, e:
pass
media_copy = {}
for key in media:
media_item = media[key]
if (media_item['type'] == 'file'):
self.sanity_check_media_item(media_item)
fileExt = os.path.splitext(media_item['uri'])[1]
dst = os.path.join(download_dir, unicode(media_item['id']) + fileExt)
media_item['dst'] = dst
media_item['file_ready'] = False
media_filtered[key] = media_item
media_item['start'] = datetime.strptime(media_item['start'],
"%Y-%m-%d-%H-%M-%S")
media_item['end'] = datetime.strptime(media_item['end'],
"%Y-%m-%d-%H-%M-%S")
media_copy[key] = media_item
self.media_prepare_queue.put(copy.copy(media_filtered))
except Exception, e: self.logger.error("%s", e)
# Send the data to pypo-push
self.logger.debug("Pushing to pypo-push")
self.push_queue.put(media_copy)
# cleanup
try: self.cache_cleanup(media)
except Exception, e: self.logger.error("%s", e)
#do basic validation of file parameters. Useful for debugging
#purposes
def sanity_check_media_item(self, media_item):
start = datetime.strptime(media_item['start'], "%Y-%m-%d-%H-%M-%S")
end = datetime.strptime(media_item['end'], "%Y-%m-%d-%H-%M-%S")
length1 = pure.date_interval_to_seconds(end - start)
length2 = media_item['cue_out'] - media_item['cue_in']
if abs(length2 - length1) > 1:
self.logger.error("end - start length: %s", length1)
self.logger.error("cue_out - cue_in length: %s", length2)
self.logger.error("Two lengths are not equal!!!")
def is_file_opened(self, path):
#Capture stderr to avoid polluting py-interpreter.log
proc = Popen(["lsof", path], stdout=PIPE, stderr=PIPE)
out = proc.communicate()[0].strip()
return bool(out)
def cache_cleanup(self, media):
"""
Get list of all files in the cache dir and remove them if they aren't being used anymore.
Input dict() media, lists all files that are scheduled or currently playing. Not being in this
dict() means the file is safe to remove.
"""
cached_file_set = set(os.listdir(self.cache_dir))
scheduled_file_set = set()
for mkey in media:
media_item = media[mkey]
if media_item['type'] == 'file':
fileExt = os.path.splitext(media_item['uri'])[1]
scheduled_file_set.add(unicode(media_item["id"]) + fileExt)
expired_files = cached_file_set - scheduled_file_set
self.logger.debug("Files to remove " + str(expired_files))
for f in expired_files:
try:
path = os.path.join(self.cache_dir, f)
self.logger.debug("Removing %s" % path)
#check if this file is opened (sometimes Liquidsoap is still
#playing the file due to our knowledge of the track length
#being incorrect!)
if not self.is_file_opened(path):
os.remove(path)
self.logger.info("File '%s' removed" % path)
else:
self.logger.info("File '%s' not removed. Still busy!" % path)
except Exception, e:
self.logger.error("Problem removing file '%s'" % f)
self.logger.error(traceback.format_exc())
def manual_schedule_fetch(self):
success, self.schedule_data = self.api_client.get_schedule()
if success:
self.process_schedule(self.schedule_data)
return success
def persistent_manual_schedule_fetch(self, max_attempts=1):
success = False
num_attempts = 0
while not success and num_attempts < max_attempts:
success = self.manual_schedule_fetch()
num_attempts += 1
return success
def main(self):
#Make sure all Liquidsoap queues are empty. This is important in the
#case where we've just restarted the pypo scheduler, but Liquidsoap still
#is playing tracks. In this case let's just restart everything from scratch
#so that we can repopulate our dictionary that keeps track of what
#Liquidsoap is playing much more easily.
self.pypo_liquidsoap.clear_all_queues()
self.set_bootstrap_variables()
# Bootstrap: since we are just starting up, we need to grab the
# most recent schedule. After that we fetch the schedule every 30
# minutes or wait for schedule updates to get pushed.
success = self.persistent_manual_schedule_fetch(max_attempts=5)
if success:
self.logger.info("Bootstrap schedule received: %s", self.schedule_data)
loops = 1
while True:
self.logger.info("Loop #%s", loops)
try:
"""
our simple_queue.get() requires a timeout, in which case we
fetch the Airtime schedule manually. It is important to fetch
the schedule periodically because if we didn't, we would only
get schedule updates via RabbitMq if the user was constantly
using the Airtime interface.
If the user is not using the interface, RabbitMq messages are not
sent, and we will have very stale (or non-existent!) data about the
schedule.
Currently we are checking every POLL_INTERVAL seconds
"""
message = self.fetch_queue.get(block=True, timeout=self.listener_timeout)
self.handle_message(message)
except Empty, e:
self.logger.info("Queue timeout. Fetching schedule manually")
self.persistent_manual_schedule_fetch(max_attempts=5)
except Exception, e:
top = traceback.format_exc()
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", top)
loops += 1
def run(self):
"""
Entry point of the thread
"""
self.main()

View file

@ -0,0 +1,146 @@
# -*- coding: utf-8 -*-
from threading import Thread
from Queue import Empty
import logging
import shutil
import os
import sys
import stat
from std_err_override import LogWriter
# configure logging
logging.config.fileConfig("logging.cfg")
logger = logging.getLogger()
LogWriter.override_std_err(logger)
#need to wait for Python 2.7 for this..
#logging.captureWarnings(True)
class PypoFile(Thread):
def __init__(self, schedule_queue, config):
Thread.__init__(self)
self.logger = logging.getLogger()
self.media_queue = schedule_queue
self.media = None
self.cache_dir = os.path.join(config["cache_dir"], "scheduler")
def copy_file(self, media_item):
"""
Copy media_item from local library directory to local cache directory.
"""
src = media_item['uri']
dst = media_item['dst']
try:
src_size = os.path.getsize(src)
except Exception, e:
self.logger.error("Could not get size of source file: %s", src)
return
dst_exists = True
try:
dst_size = os.path.getsize(dst)
except Exception, e:
dst_exists = False
do_copy = False
if dst_exists:
if src_size != dst_size:
do_copy = True
else:
self.logger.debug("file %s already exists in local cache as %s, skipping copying..." % (src, dst))
else:
do_copy = True
media_item['file_ready'] = not do_copy
if do_copy:
self.logger.debug("copying from %s to local cache %s" % (src, dst))
try:
"""
copy will overwrite dst if it already exists
"""
shutil.copy(src, dst)
#make file world readable
os.chmod(dst, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
media_item['file_ready'] = True
except Exception, e:
self.logger.error("Could not copy from %s to %s" % (src, dst))
self.logger.error(e)
def get_highest_priority_media_item(self, schedule):
"""
Get highest priority media_item in the queue. Currently the highest
priority is decided by how close the start time is to "now".
"""
if schedule is None or len(schedule) == 0:
return None
sorted_keys = sorted(schedule.keys())
if len(sorted_keys) == 0:
return None
highest_priority = sorted_keys[0]
media_item = schedule[highest_priority]
self.logger.debug("Highest priority item: %s" % highest_priority)
"""
Remove this media_item from the dictionary. On the next iteration
(from the main function) we won't consider it for prioritization
anymore. If on the next iteration we have received a new schedule,
it is very possible we will have to deal with the same media_items
again. In this situation, the worst possible case is that we try to
copy the file again and realize we already have it (thus aborting the copy).
"""
del schedule[highest_priority]
return media_item
def main(self):
while True:
try:
if self.media is None or len(self.media) == 0:
"""
We have no schedule, so we have nothing else to do. Let's
do a blocked wait on the queue
"""
self.media = self.media_queue.get(block=True)
else:
"""
We have a schedule we need to process, but we also want
to check if a newer schedule is available. In this case
do a non-blocking queue.get and in either case (we get something
or we don't), get back to work on preparing getting files.
"""
try:
self.media = self.media_queue.get_nowait()
except Empty, e:
pass
media_item = self.get_highest_priority_media_item(self.media)
if media_item is not None:
self.copy_file(media_item)
except Exception, e:
import traceback
top = traceback.format_exc()
self.logger.error(str(e))
self.logger.error(top)
raise
def run(self):
"""
Entry point of the thread
"""
self.main()

View file

@ -0,0 +1,89 @@
from threading import Thread
from collections import deque
from datetime import datetime
import traceback
import sys
import time
from Queue import Empty
import signal
def keyboardInterruptHandler(signum, frame):
logger = logging.getLogger()
logger.info('\nKeyboard Interrupt\n')
sys.exit(0)
signal.signal(signal.SIGINT, keyboardInterruptHandler)
class PypoLiqQueue(Thread):
def __init__(self, q, pypo_liquidsoap, logger):
Thread.__init__(self)
self.queue = q
self.logger = logger
self.pypo_liquidsoap = pypo_liquidsoap
def main(self):
time_until_next_play = None
schedule_deque = deque()
media_schedule = None
while True:
try:
if time_until_next_play is None:
self.logger.info("waiting indefinitely for schedule")
media_schedule = self.queue.get(block=True)
else:
self.logger.info("waiting %ss until next scheduled item" % \
time_until_next_play)
media_schedule = self.queue.get(block=True, \
timeout=time_until_next_play)
except Empty, e:
#Time to push a scheduled item.
media_item = schedule_deque.popleft()
self.pypo_liquidsoap.play(media_item)
if len(schedule_deque):
time_until_next_play = \
self.date_interval_to_seconds(
schedule_deque[0]['start'] - datetime.utcnow())
if time_until_next_play < 0:
time_until_next_play = 0
else:
time_until_next_play = None
else:
self.logger.info("New schedule received: %s", media_schedule)
#new schedule received. Replace old one with this.
schedule_deque.clear()
keys = sorted(media_schedule.keys())
for i in keys:
schedule_deque.append(media_schedule[i])
if len(keys):
time_until_next_play = self.date_interval_to_seconds(
media_schedule[keys[0]]['start'] -
datetime.utcnow())
else:
time_until_next_play = None
def date_interval_to_seconds(self, interval):
"""
Convert timedelta object into int representing the number of seconds. If
number of seconds is less than 0, then return 0.
"""
seconds = (interval.microseconds + \
(interval.seconds + interval.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
if seconds < 0: seconds = 0
return seconds
def run(self):
try: self.main()
except Exception, e:
self.logger.error('PypoLiqQueue Exception: %s', traceback.format_exc())

View file

@ -0,0 +1,239 @@
from pypofetch import PypoFetch
from telnetliquidsoap import TelnetLiquidsoap
from datetime import datetime
from datetime import timedelta
import eventtypes
import time
class PypoLiquidsoap():
def __init__(self, logger, telnet_lock, host, port):
self.logger = logger
self.liq_queue_tracker = {
"s0": None,
"s1": None,
"s2": None,
"s3": None,
}
self.telnet_liquidsoap = TelnetLiquidsoap(telnet_lock, \
logger,\
host,\
port,\
self.liq_queue_tracker.keys())
def get_telnet_dispatcher(self):
return self.telnet_liquidsoap
def play(self, media_item):
if media_item["type"] == eventtypes.FILE:
self.handle_file_type(media_item)
elif media_item["type"] == eventtypes.EVENT:
self.handle_event_type(media_item)
elif media_item["type"] == eventtypes.STREAM_BUFFER_START:
self.telnet_liquidsoap.start_web_stream_buffer(media_item)
elif media_item["type"] == eventtypes.STREAM_OUTPUT_START:
if media_item['row_id'] != self.telnet_liquidsoap.current_prebuffering_stream_id:
#this is called if the stream wasn't scheduled sufficiently ahead of time
#so that the prebuffering stage could take effect. Let's do the prebuffering now.
self.telnet_liquidsoap.start_web_stream_buffer(media_item)
self.telnet_liquidsoap.start_web_stream(media_item)
elif media_item['type'] == eventtypes.STREAM_BUFFER_END:
self.telnet_liquidsoap.stop_web_stream_buffer()
elif media_item['type'] == eventtypes.STREAM_OUTPUT_END:
self.telnet_liquidsoap.stop_web_stream_output()
else: raise UnknownMediaItemType(str(media_item))
def handle_file_type(self, media_item):
"""
Wait maximum 5 seconds (50 iterations) for file to become ready,
otherwise give up on it.
"""
iter_num = 0
while not media_item['file_ready'] and iter_num < 50:
time.sleep(0.1)
iter_num += 1
if media_item['file_ready']:
available_queue = self.find_available_queue()
try:
self.telnet_liquidsoap.queue_push(available_queue, media_item)
self.liq_queue_tracker[available_queue] = media_item
except Exception as e:
self.logger.error(e)
raise
else:
self.logger.warn("File %s did not become ready in less than 5 seconds. Skipping...", media_item['dst'])
def handle_event_type(self, media_item):
if media_item['event_type'] == "kick_out":
self.telnet_liquidsoap.disconnect_source("live_dj")
elif media_item['event_type'] == "switch_off":
self.telnet_liquidsoap.switch_source("live_dj", "off")
def is_media_item_finished(self, media_item):
if media_item is None:
return True
else:
return datetime.utcnow() > media_item['end']
def find_available_queue(self):
available_queue = None
for i in self.liq_queue_tracker:
mi = self.liq_queue_tracker[i]
if mi == None or self.is_media_item_finished(mi):
#queue "i" is available. Push to this queue
available_queue = i
if available_queue == None:
raise NoQueueAvailableException()
return available_queue
def verify_correct_present_media(self, scheduled_now):
#verify whether Liquidsoap is currently playing the correct files.
#if we find an item that Liquidsoap is not playing, then push it
#into one of Liquidsoap's queues. If Liquidsoap is already playing
#it do nothing. If Liquidsoap is playing a track that isn't in
#currently_playing then stop it.
#Check for Liquidsoap media we should source.skip
#get liquidsoap items for each queue. Since each queue can only have one
#item, we should have a max of 8 items.
#2013-03-21-22-56-00_0: {
#id: 1,
#type: "stream_output_start",
#row_id: 41,
#uri: "http://stream2.radioblackout.org:80/blackout.ogg",
#start: "2013-03-21-22-56-00",
#end: "2013-03-21-23-26-00",
#show_name: "Untitled Show",
#independent_event: true
#},
try:
scheduled_now_files = \
filter(lambda x: x["type"] == eventtypes.FILE, scheduled_now)
scheduled_now_webstream = \
filter(lambda x: x["type"] == eventtypes.STREAM_OUTPUT_START, \
scheduled_now)
schedule_ids = set(map(lambda x: x["row_id"], scheduled_now_files))
row_id_map = {}
liq_queue_ids = set()
for i in self.liq_queue_tracker:
mi = self.liq_queue_tracker[i]
if not self.is_media_item_finished(mi):
liq_queue_ids.add(mi["row_id"])
row_id_map[mi["row_id"]] = mi
to_be_removed = set()
to_be_added = set()
#Iterate over the new files, and compare them to currently scheduled
#tracks. If already in liquidsoap queue still need to make sure they don't
#have different attributes
#if replay gain changes, it shouldn't change the amplification of the currently playing song
for i in scheduled_now_files:
if i["row_id"] in row_id_map:
mi = row_id_map[i["row_id"]]
correct = mi['start'] == i['start'] and \
mi['end'] == i['end'] and \
mi['row_id'] == i['row_id']
if not correct:
#need to re-add
self.logger.info("Track %s found to have new attr." % i)
to_be_removed.add(i["row_id"])
to_be_added.add(i["row_id"])
to_be_removed.update(liq_queue_ids - schedule_ids)
to_be_added.update(schedule_ids - liq_queue_ids)
if to_be_removed:
self.logger.info("Need to remove items from Liquidsoap: %s" % \
to_be_removed)
#remove files from Liquidsoap's queue
for i in self.liq_queue_tracker:
mi = self.liq_queue_tracker[i]
if mi is not None and mi["row_id"] in to_be_removed:
self.stop(i)
if to_be_added:
self.logger.info("Need to add items to Liquidsoap *now*: %s" % \
to_be_added)
for i in scheduled_now_files:
if i["row_id"] in to_be_added:
self.modify_cue_point(i)
self.play(i)
#handle webstreams
current_stream_id = self.telnet_liquidsoap.get_current_stream_id()
if scheduled_now_webstream:
if int(current_stream_id) != int(scheduled_now_webstream[0]["row_id"]):
self.play(scheduled_now_webstream[0])
elif current_stream_id != "-1":
#something is playing and it shouldn't be.
self.telnet_liquidsoap.stop_web_stream_buffer()
self.telnet_liquidsoap.stop_web_stream_output()
except KeyError as e:
self.logger.error("Error: Malformed event in schedule. " + str(e))
def stop(self, queue):
self.telnet_liquidsoap.queue_remove(queue)
self.liq_queue_tracker[queue] = None
def is_file(self, media_item):
return media_item["type"] == eventtypes.FILE
def clear_queue_tracker(self):
for i in self.liq_queue_tracker.keys():
self.liq_queue_tracker[i] = None
def modify_cue_point(self, link):
assert self.is_file(link)
tnow = datetime.utcnow()
link_start = link['start']
diff_td = tnow - link_start
diff_sec = self.date_interval_to_seconds(diff_td)
if diff_sec > 0:
self.logger.debug("media item was supposed to start %s ago. Preparing to start..", diff_sec)
original_cue_in_td = timedelta(seconds=float(link['cue_in']))
link['cue_in'] = self.date_interval_to_seconds(original_cue_in_td) + diff_sec
def date_interval_to_seconds(self, interval):
"""
Convert timedelta object into int representing the number of seconds. If
number of seconds is less than 0, then return 0.
"""
seconds = (interval.microseconds + \
(interval.seconds + interval.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
if seconds < 0: seconds = 0
return seconds
def clear_all_queues(self):
self.telnet_liquidsoap.queue_clear_all()
class UnknownMediaItemType(Exception):
pass
class NoQueueAvailableException(Exception):
pass

View file

@ -0,0 +1,140 @@
# -*- coding: utf-8 -*-
import logging
import traceback
import sys
from threading import Thread
import time
# For RabbitMQ
from kombu.connection import BrokerConnection
from kombu.messaging import Exchange, Queue
from kombu.simple import SimpleQueue
from amqplib.client_0_8.exceptions import AMQPConnectionException
import json
from std_err_override import LogWriter
# configure logging
logging.config.fileConfig("logging.cfg")
logger = logging.getLogger('message_h')
LogWriter.override_std_err(logger)
#need to wait for Python 2.7 for this..
#logging.captureWarnings(True)
class PypoMessageHandler(Thread):
def __init__(self, pq, rq, config):
Thread.__init__(self)
self.logger = logging.getLogger('message_h')
self.pypo_queue = pq
self.recorder_queue = rq
self.config = config
def init_rabbit_mq(self):
self.logger.info("Initializing RabbitMQ stuff")
try:
schedule_exchange = Exchange("airtime-pypo", "direct", durable=True, auto_delete=True)
schedule_queue = Queue("pypo-fetch", exchange=schedule_exchange, key="foo")
connection = BrokerConnection(self.config["host"], \
self.config["user"], \
self.config["password"], \
self.config["vhost"])
channel = connection.channel()
self.simple_queue = SimpleQueue(channel, schedule_queue)
except Exception, e:
self.logger.error(e)
return False
return True
"""
Handle a message from RabbitMQ, put it into our yucky global var.
Hopefully there is a better way to do this.
"""
def handle_message(self, message):
try:
self.logger.info("Received event from RabbitMQ: %s" % message)
m = json.loads(message)
command = m['event_type']
self.logger.info("Handling command: " + command)
if command == 'update_schedule':
self.logger.info("Updating schdule...")
self.pypo_queue.put(message)
elif command == 'reset_liquidsoap_bootstrap':
self.logger.info("Resetting bootstrap vars...")
self.pypo_queue.put(message)
elif command == 'update_stream_setting':
self.logger.info("Updating stream setting...")
self.pypo_queue.put(message)
elif command == 'update_stream_format':
self.logger.info("Updating stream format...")
self.pypo_queue.put(message)
elif command == 'update_station_name':
self.logger.info("Updating station name...")
self.pypo_queue.put(message)
elif command == 'switch_source':
self.logger.info("switch_source command received...")
self.pypo_queue.put(message)
elif command == 'update_transition_fade':
self.logger.info("Updating trasition fade...")
self.pypo_queue.put(message)
elif command == 'disconnect_source':
self.logger.info("disconnect_source command received...")
self.pypo_queue.put(message)
elif command == 'update_recorder_schedule':
self.recorder_queue.put(message)
elif command == 'cancel_recording':
self.recorder_queue.put(message)
else:
self.logger.info("Unknown command: %s" % command)
except Exception, e:
self.logger.error("Exception in handling RabbitMQ message: %s", e)
def main(self):
while not self.init_rabbit_mq():
self.logger.error("Error connecting to RabbitMQ Server. Trying again in few seconds")
time.sleep(5)
loops = 1
while True:
self.logger.info("Loop #%s", loops)
try:
message = self.simple_queue.get(block=True)
self.handle_message(message.payload)
# ACK the message to take it off the queue
message.ack()
except (IOError, AttributeError, AMQPConnectionException), e:
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", traceback.format_exc())
while not self.init_rabbit_mq():
self.logger.error("Error connecting to RabbitMQ Server. Trying again in few seconds")
time.sleep(5)
except Exception, e:
"""
sleep 5 seconds so that we don't spin inside this
while loop and eat all the CPU
"""
time.sleep(5)
"""
There is a problem with the RabbitMq messenger service. Let's
log the error and get the schedule via HTTP polling
"""
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", traceback.format_exc())
loops += 1
"""
Main loop of the thread:
Wait for schedule updates from RabbitMQ, but in case there arent any,
poll the server to get the upcoming schedule.
"""
def run(self):
while True:
self.main()

View file

@ -0,0 +1,139 @@
# -*- coding: utf-8 -*-
import traceback
"""
Python part of radio playout (pypo)
This function acts as a gateway between liquidsoap and the server API.
Mainly used to tell the platform what pypo/liquidsoap does.
Main case:
- whenever LS starts playing a new track, its on_metadata callback calls
a function in ls (notify(m)) which then calls the python script here
with the currently starting filename as parameter
- this python script takes this parameter, tries to extract the actual
media id from it, and then calls back to the API to tell about it about it.
"""
from optparse import OptionParser
import sys
import logging.config
import json
# additional modules (should be checked)
from configobj import ConfigObj
# custom imports
#from util import *
from api_clients import *
from std_err_override import LogWriter
# help screeen / info
usage = "%prog [options]" + " - notification gateway"
parser = OptionParser(usage=usage)
# Options
parser.add_option("-d", "--data", help="Pass JSON data from Liquidsoap into this script.", metavar="data")
parser.add_option("-m", "--media-id", help="ID of the file that is currently playing.", metavar="media_id")
parser.add_option("-e", "--error", action="store", dest="error", type="string", help="Liquidsoap error msg.", metavar="error_msg")
parser.add_option("-s", "--stream-id", help="ID stream", metavar="stream_id")
parser.add_option("-c", "--connect", help="Liquidsoap connected", action="store_true", metavar="connect")
parser.add_option("-t", "--time", help="Liquidsoap boot up time", action="store", dest="time", metavar="time", type="string")
parser.add_option("-x", "--source-name", help="source connection name", metavar="source_name")
parser.add_option("-y", "--source-status", help="source connection status", metavar="source_status")
parser.add_option("-w", "--webstream", help="JSON metadata associated with webstream", metavar="json_data")
parser.add_option("-n", "--liquidsoap-started", help="notify liquidsoap started", metavar="json_data", action="store_true", default=False)
# parse options
(options, args) = parser.parse_args()
# configure logging
logging.config.fileConfig("notify_logging.cfg")
logger = logging.getLogger('notify')
LogWriter.override_std_err(logger)
#need to wait for Python 2.7 for this..
#logging.captureWarnings(True)
# loading config file
try:
config = ConfigObj('/etc/airtime/pypo.cfg')
except Exception, e:
logger.error('Error loading config file: %s', e)
sys.exit()
class Notify:
def __init__(self):
self.api_client = api_client.AirtimeApiClient(logger=logger)
def notify_liquidsoap_started(self):
logger.debug("Notifying server that Liquidsoap has started")
self.api_client.notify_liquidsoap_started()
def notify_media_start_playing(self, media_id):
logger.debug('#################################################')
logger.debug('# Calling server to update about what\'s playing #')
logger.debug('#################################################')
response = self.api_client.notify_media_item_start_playing(media_id)
logger.debug("Response: " + json.dumps(response))
# @pram time: time that LS started
def notify_liquidsoap_status(self, msg, stream_id, time):
logger.debug('#################################################')
logger.debug('# Calling server to update liquidsoap status #')
logger.debug('#################################################')
logger.debug('msg = ' + str(msg))
response = self.api_client.notify_liquidsoap_status(msg, stream_id, time)
logger.debug("Response: " + json.dumps(response))
def notify_source_status(self, source_name, status):
logger.debug('#################################################')
logger.debug('# Calling server to update source status #')
logger.debug('#################################################')
logger.debug('msg = ' + str(source_name) + ' : ' + str(status))
response = self.api_client.notify_source_status(source_name, status)
logger.debug("Response: " + json.dumps(response))
def notify_webstream_data(self, data, media_id):
logger.debug('#################################################')
logger.debug('# Calling server to update webstream data #')
logger.debug('#################################################')
response = self.api_client.notify_webstream_data(data, media_id)
logger.debug("Response: " + json.dumps(response))
def run_with_options(self, options):
if options.error and options.stream_id:
self.notify_liquidsoap_status(options.error, options.stream_id, options.time)
elif options.connect and options.stream_id:
self.notify_liquidsoap_status("OK", options.stream_id, options.time)
elif options.source_name and options.source_status:
self.notify_source_status(options.source_name, options.source_status)
elif options.webstream:
self.notify_webstream_data(options.webstream, options.media_id)
elif options.media_id:
self.notify_media_start_playing(options.media_id)
elif options.liquidsoap_started:
self.notify_liquidsoap_started()
else:
logger.debug("Unrecognized option in options(%s). Doing nothing" \
% str(options))
if __name__ == '__main__':
print
print '#########################################'
print '# *** pypo *** #'
print '# pypo notification gateway #'
print '#########################################'
# initialize
try:
n = Notify()
n.run_with_options(options)
except Exception as e:
print( traceback.format_exc() )

View file

@ -0,0 +1,162 @@
# -*- coding: utf-8 -*-
from datetime import datetime
from datetime import timedelta
from configobj import ConfigObj
import sys
import time
import logging.config
import telnetlib
import calendar
import math
import traceback
import os
from pypofetch import PypoFetch
from pypoliqqueue import PypoLiqQueue
from Queue import Empty, Queue
from threading import Thread
from api_clients import api_client
from std_err_override import LogWriter
from timeout import ls_timeout
# configure logging
logging_cfg = os.path.join(os.path.dirname(__file__), "logging.cfg")
logging.config.fileConfig(logging_cfg)
logger = logging.getLogger()
LogWriter.override_std_err(logger)
#need to wait for Python 2.7 for this..
#logging.captureWarnings(True)
PUSH_INTERVAL = 2
def is_stream(media_item):
return media_item['type'] == 'stream_output_start'
def is_file(media_item):
return media_item['type'] == 'file'
class PypoPush(Thread):
def __init__(self, q, telnet_lock, pypo_liquidsoap, config):
Thread.__init__(self)
self.api_client = api_client.AirtimeApiClient()
self.queue = q
self.telnet_lock = telnet_lock
self.config = config
self.pushed_objects = {}
self.logger = logging.getLogger('push')
self.current_prebuffering_stream_id = None
self.queue_id = 0
self.future_scheduled_queue = Queue()
self.pypo_liquidsoap = pypo_liquidsoap
self.plq = PypoLiqQueue(self.future_scheduled_queue, \
self.pypo_liquidsoap, \
self.logger)
self.plq.daemon = True
self.plq.start()
def main(self):
loops = 0
heartbeat_period = math.floor(30 / PUSH_INTERVAL)
media_schedule = None
while True:
try:
media_schedule = self.queue.get(block=True)
except Exception, e:
self.logger.error(str(e))
raise
else:
self.logger.debug(media_schedule)
#separate media_schedule list into currently_playing and
#scheduled_for_future lists
currently_playing, scheduled_for_future = \
self.separate_present_future(media_schedule)
self.pypo_liquidsoap.verify_correct_present_media(currently_playing)
self.future_scheduled_queue.put(scheduled_for_future)
if loops % heartbeat_period == 0:
self.logger.info("heartbeat")
loops = 0
loops += 1
def separate_present_future(self, media_schedule):
tnow = datetime.utcnow()
present = []
future = {}
sorted_keys = sorted(media_schedule.keys())
for mkey in sorted_keys:
media_item = media_schedule[mkey]
diff_td = tnow - media_item['start']
diff_sec = self.date_interval_to_seconds(diff_td)
if diff_sec >= 0:
present.append(media_item)
else:
future[mkey] = media_item
return present, future
def date_interval_to_seconds(self, interval):
"""
Convert timedelta object into int representing the number of seconds. If
number of seconds is less than 0, then return 0.
"""
seconds = (interval.microseconds + \
(interval.seconds + interval.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
return seconds
@ls_timeout
def stop_web_stream_all(self):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.config['LS_HOST'], self.config['LS_PORT'])
#msg = 'dynamic_source.read_stop_all xxx\n'
msg = 'http.stop\n'
self.logger.debug(msg)
tn.write(msg)
msg = 'dynamic_source.output_stop\n'
self.logger.debug(msg)
tn.write(msg)
msg = 'dynamic_source.id -1\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
def run(self):
while True:
try: self.main()
except Exception, e:
top = traceback.format_exc()
self.logger.error('Pypo Push Exception: %s', top)
time.sleep(5)

View file

@ -0,0 +1,354 @@
# -*- coding: utf-8 -*-
import logging
import json
import time
import datetime
import os
import sys
import pytz
import signal
import math
import traceback
import re
from configobj import ConfigObj
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
from subprocess import Popen
from subprocess import PIPE
from threading import Thread
import mutagen
from api_clients import api_client as apc
def api_client(logger):
"""
api_client returns the correct instance of AirtimeApiClient. Although there is only one
instance to choose from at the moment.
"""
return apc.AirtimeApiClient(logger)
# loading config file
try:
config = ConfigObj('/etc/airtime/pypo.cfg')
except Exception, e:
print ('Error loading config file: %s', e)
sys.exit()
# TODO : add docstrings everywhere in this module
def getDateTimeObj(time):
# TODO : clean up for this function later.
# - use tuples to parse result from split (instead of indices)
# - perhaps validate the input before doing dangerous casts?
# - rename this function to follow the standard convention
# - rename time to something else so that the module name does not get
# shadowed
# - add docstring to document all behaviour of this function
timeinfo = time.split(" ")
date = [ int(x) for x in timeinfo[0].split("-") ]
my_time = [ int(x) for x in timeinfo[1].split(":") ]
return datetime.datetime(date[0], date[1], date[2], my_time[0], my_time[1], my_time[2], 0, None)
PUSH_INTERVAL = 2
class ShowRecorder(Thread):
def __init__ (self, show_instance, show_name, filelength, start_time):
Thread.__init__(self)
self.logger = logging.getLogger('recorder')
self.api_client = api_client(self.logger)
self.filelength = filelength
self.start_time = start_time
self.show_instance = show_instance
self.show_name = show_name
self.p = None
def record_show(self):
length = str(self.filelength)
filename = self.start_time
filename = filename.replace(" ", "-")
if config["record_file_type"] in ["mp3", "ogg"]:
filetype = config["record_file_type"]
else:
filetype = "ogg";
joined_path = os.path.join(config["base_recorded_files"], filename)
filepath = "%s.%s" % (joined_path, filetype)
br = config["record_bitrate"]
sr = config["record_samplerate"]
c = config["record_channels"]
ss = config["record_sample_size"]
#-f:16,2,44100
#-b:256
command = "ecasound -f:%s,%s,%s -i alsa -o %s,%s000 -t:%s" % \
(ss, c, sr, filepath, br, length)
args = command.split(" ")
self.logger.info("starting record")
self.logger.info("command " + command)
self.p = Popen(args,stdout=PIPE)
#blocks at the following line until the child process
#quits
self.p.wait()
outmsgs = self.p.stdout.readlines()
for msg in outmsgs:
m = re.search('^ERROR',msg)
if not m == None:
self.logger.info('Recording error is found: %s', outmsgs)
self.logger.info("finishing record, return code %s", self.p.returncode)
code = self.p.returncode
self.p = None
return code, filepath
def cancel_recording(self):
#send signal interrupt (2)
self.logger.info("Show manually cancelled!")
if (self.p is not None):
self.p.send_signal(signal.SIGINT)
#if self.p is defined, then the child process ecasound is recording
def is_recording(self):
return (self.p is not None)
def upload_file(self, filepath):
filename = os.path.split(filepath)[1]
# Register the streaming http handlers with urllib2
register_openers()
# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({"file": open(filepath, "rb"), 'name': filename, 'show_instance': self.show_instance})
self.api_client.upload_recorded_show(datagen, headers)
def set_metadata_and_save(self, filepath):
"""
Writes song to 'filepath'. Uses metadata from:
self.start_time, self.show_name, self.show_instance
"""
try:
full_date, full_time = self.start_time.split(" ",1)
# No idea why we translated - to : before
#full_time = full_time.replace(":","-")
self.logger.info("time: %s" % full_time)
artist = "Airtime Show Recorder"
#set some metadata for our file daemon
recorded_file = mutagen.File(filepath, easy = True)
recorded_file['artist'] = artist
recorded_file['date'] = full_date
recorded_file['title'] = "%s-%s-%s" % (self.show_name,
full_date, full_time)
#You cannot pass ints into the metadata of a file. Even tracknumber needs to be a string
recorded_file['tracknumber'] = unicode(self.show_instance)
recorded_file.save()
except Exception, e:
top = traceback.format_exc()
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", top)
def run(self):
code, filepath = self.record_show()
if code == 0:
try:
self.logger.info("Preparing to upload %s" % filepath)
self.set_metadata_and_save(filepath)
self.upload_file(filepath)
os.remove(filepath)
except Exception, e:
self.logger.error(e)
else:
self.logger.info("problem recording show")
os.remove(filepath)
class Recorder(Thread):
def __init__(self, q):
Thread.__init__(self)
self.logger = logging.getLogger('recorder')
self.api_client = api_client(self.logger)
self.sr = None
self.shows_to_record = {}
self.server_timezone = ''
self.queue = q
self.loops = 0
self.logger.info("RecorderFetch: init complete")
success = False
while not success:
try:
self.api_client.register_component('show-recorder')
success = True
except Exception, e:
self.logger.error(str(e))
time.sleep(10)
def handle_message(self):
if not self.queue.empty():
message = self.queue.get()
msg = json.loads(message)
command = msg["event_type"]
self.logger.info("Received msg from Pypo Message Handler: %s", msg)
if command == 'cancel_recording':
if self.currently_recording():
self.cancel_recording()
else:
self.process_recorder_schedule(msg)
self.loops = 0
if self.shows_to_record:
self.start_record()
def process_recorder_schedule(self, m):
self.logger.info("Parsing recording show schedules...")
temp_shows_to_record = {}
shows = m['shows']
for show in shows:
show_starts = getDateTimeObj(show[u'starts'])
show_end = getDateTimeObj(show[u'ends'])
time_delta = show_end - show_starts
temp_shows_to_record[show[u'starts']] = [time_delta,
show[u'instance_id'], show[u'name'], m['server_timezone']]
self.shows_to_record = temp_shows_to_record
def get_time_till_next_show(self):
if len(self.shows_to_record) != 0:
tnow = datetime.datetime.utcnow()
sorted_show_keys = sorted(self.shows_to_record.keys())
start_time = sorted_show_keys[0]
next_show = getDateTimeObj(start_time)
delta = next_show - tnow
s = '%s.%s' % (delta.seconds, delta.microseconds)
out = float(s)
if out < 5:
self.logger.debug("Shows %s", self.shows_to_record)
self.logger.debug("Next show %s", next_show)
self.logger.debug("Now %s", tnow)
return out
def cancel_recording(self):
self.sr.cancel_recording()
self.sr = None
def currently_recording(self):
if self.sr is not None and self.sr.is_recording():
return True
else:
return False
def start_record(self):
if len(self.shows_to_record) == 0: return None
try:
delta = self.get_time_till_next_show()
if delta < 5:
self.logger.debug("sleeping %s seconds until show", delta)
time.sleep(delta)
sorted_show_keys = sorted(self.shows_to_record.keys())
start_time = sorted_show_keys[0]
show_length = self.shows_to_record[start_time][0]
show_instance = self.shows_to_record[start_time][1]
show_name = self.shows_to_record[start_time][2]
server_timezone = self.shows_to_record[start_time][3]
T = pytz.timezone(server_timezone)
start_time_on_UTC = getDateTimeObj(start_time)
start_time_on_server = start_time_on_UTC.replace(tzinfo=pytz.utc).astimezone(T)
start_time_formatted = '%(year)d-%(month)02d-%(day)02d %(hour)02d:%(min)02d:%(sec)02d' % \
{'year': start_time_on_server.year, 'month': start_time_on_server.month, 'day': start_time_on_server.day, \
'hour': start_time_on_server.hour, 'min': start_time_on_server.minute, 'sec': start_time_on_server.second}
seconds_waiting = 0
#avoiding CC-5299
while(True):
if self.currently_recording():
self.logger.info("Previous record not finished, sleeping 100ms")
seconds_waiting = seconds_waiting + 0.1
time.sleep(0.1)
else:
show_length_seconds = show_length.seconds - seconds_waiting
self.sr = ShowRecorder(show_instance, show_name, show_length_seconds, start_time_formatted)
self.sr.start()
break
#remove show from shows to record.
del self.shows_to_record[start_time]
#self.time_till_next_show = self.get_time_till_next_show()
except Exception, e :
top = traceback.format_exc()
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", top)
def run(self):
"""
Main loop of the thread:
Wait for schedule updates from RabbitMQ, but in case there arent any,
poll the server to get the upcoming schedule.
"""
try:
self.logger.info("Started...")
# Bootstrap: since we are just starting up, we need to grab the
# most recent schedule. After that we can just wait for updates.
try:
temp = self.api_client.get_shows_to_record()
if temp is not None:
self.process_recorder_schedule(temp)
self.logger.info("Bootstrap recorder schedule received: %s", temp)
except Exception, e:
self.logger.error( traceback.format_exc() )
self.logger.error(e)
self.logger.info("Bootstrap complete: got initial copy of the schedule")
self.loops = 0
heartbeat_period = math.floor(30 / PUSH_INTERVAL)
while True:
if self.loops * PUSH_INTERVAL > 3600:
self.loops = 0
"""
Fetch recorder schedule
"""
try:
temp = self.api_client.get_shows_to_record()
if temp is not None:
self.process_recorder_schedule(temp)
self.logger.info("updated recorder schedule received: %s", temp)
except Exception, e:
self.logger.error( traceback.format_exc() )
self.logger.error(e)
try: self.handle_message()
except Exception, e:
self.logger.error( traceback.format_exc() )
self.logger.error('Pypo Recorder Exception: %s', e)
time.sleep(PUSH_INTERVAL)
self.loops += 1
except Exception, e :
top = traceback.format_exc()
self.logger.error('Exception: %s', e)
self.logger.error("traceback: %s", top)

View file

@ -0,0 +1,310 @@
import telnetlib
from timeout import ls_timeout
def create_liquidsoap_annotation(media):
# We need liq_start_next value in the annotate. That is the value that controls overlap duration of crossfade.
return ('annotate:media_id="%s",liq_start_next="0",liq_fade_in="%s",' + \
'liq_fade_out="%s",liq_cue_in="%s",liq_cue_out="%s",' + \
'schedule_table_id="%s",replay_gain="%s dB":%s') % \
(media['id'],
float(media['fade_in']) / 1000,
float(media['fade_out']) / 1000,
float(media['cue_in']),
float(media['cue_out']),
media['row_id'],
media['replay_gain'],
media['dst'])
class TelnetLiquidsoap:
def __init__(self, telnet_lock, logger, ls_host, ls_port, queues):
self.telnet_lock = telnet_lock
self.ls_host = ls_host
self.ls_port = ls_port
self.logger = logger
self.queues = queues
self.current_prebuffering_stream_id = None
def __connect(self):
return telnetlib.Telnet(self.ls_host, self.ls_port)
def __is_empty(self, queue_id):
return True
tn = self.__connect()
msg = '%s.queue\nexit\n' % queue_id
tn.write(msg)
output = tn.read_all().splitlines()
if len(output) == 3:
return len(output[0]) == 0
else:
raise Exception("Unexpected list length returned: %s" % output)
@ls_timeout
def queue_clear_all(self):
try:
self.telnet_lock.acquire()
tn = self.__connect()
for i in self.queues:
msg = 'queues.%s_skip\n' % i
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
except Exception:
raise
finally:
self.telnet_lock.release()
@ls_timeout
def queue_remove(self, queue_id):
try:
self.telnet_lock.acquire()
tn = self.__connect()
msg = 'queues.%s_skip\n' % queue_id
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
except Exception:
raise
finally:
self.telnet_lock.release()
@ls_timeout
def queue_push(self, queue_id, media_item):
try:
self.telnet_lock.acquire()
if not self.__is_empty(queue_id):
raise QueueNotEmptyException()
tn = self.__connect()
annotation = create_liquidsoap_annotation(media_item)
msg = '%s.push %s\n' % (queue_id, annotation.encode('utf-8'))
self.logger.debug(msg)
tn.write(msg)
show_name = media_item['show_name']
msg = 'vars.show_name %s\n' % show_name.encode('utf-8')
tn.write(msg)
self.logger.debug(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
except Exception:
raise
finally:
self.telnet_lock.release()
@ls_timeout
def stop_web_stream_buffer(self):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
#dynamic_source.stop http://87.230.101.24:80/top100station.mp3
msg = 'http.stop\n'
self.logger.debug(msg)
tn.write(msg)
msg = 'dynamic_source.id -1\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
@ls_timeout
def stop_web_stream_output(self):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
#dynamic_source.stop http://87.230.101.24:80/top100station.mp3
msg = 'dynamic_source.output_stop\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
@ls_timeout
def start_web_stream(self, media_item):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
#TODO: DO we need this?
msg = 'streams.scheduled_play_start\n'
tn.write(msg)
msg = 'dynamic_source.output_start\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
self.current_prebuffering_stream_id = None
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
@ls_timeout
def start_web_stream_buffer(self, media_item):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
msg = 'dynamic_source.id %s\n' % media_item['row_id']
self.logger.debug(msg)
tn.write(msg)
msg = 'http.restart %s\n' % media_item['uri'].encode('latin-1')
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
self.logger.debug(tn.read_all())
self.current_prebuffering_stream_id = media_item['row_id']
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
@ls_timeout
def get_current_stream_id(self):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
msg = 'dynamic_source.get_id\n'
self.logger.debug(msg)
tn.write(msg)
tn.write("exit\n")
stream_id = tn.read_all().splitlines()[0]
self.logger.debug("stream_id: %s" % stream_id)
return stream_id
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
@ls_timeout
def disconnect_source(self, sourcename):
self.logger.debug('Disconnecting source: %s', sourcename)
command = ""
if(sourcename == "master_dj"):
command += "master_harbor.kick\n"
elif(sourcename == "live_dj"):
command += "live_dj_harbor.kick\n"
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
self.logger.info(command)
tn.write(command)
tn.write('exit\n')
tn.read_all()
except Exception, e:
self.logger.error(traceback.format_exc())
finally:
self.telnet_lock.release()
@ls_timeout
def telnet_send(self, commands):
try:
self.telnet_lock.acquire()
tn = telnetlib.Telnet(self.ls_host, self.ls_port)
for i in commands:
self.logger.info(i)
tn.write(i)
tn.write('exit\n')
tn.read_all()
except Exception, e:
self.logger.error(str(e))
finally:
self.telnet_lock.release()
def switch_source(self, sourcename, status):
self.logger.debug('Switching source: %s to "%s" status', sourcename, status)
command = "streams."
if sourcename == "master_dj":
command += "master_dj_"
elif sourcename == "live_dj":
command += "live_dj_"
elif sourcename == "scheduled_play":
command += "scheduled_play_"
if status == "on":
command += "start\n"
else:
command += "stop\n"
self.telnet_send([command])
class DummyTelnetLiquidsoap:
def __init__(self, telnet_lock, logger):
self.telnet_lock = telnet_lock
self.liquidsoap_mock_queues = {}
self.logger = logger
for i in range(4):
self.liquidsoap_mock_queues["s"+str(i)] = []
@ls_timeout
def queue_push(self, queue_id, media_item):
try:
self.telnet_lock.acquire()
self.logger.info("Pushing %s to queue %s" % (media_item, queue_id))
from datetime import datetime
print "Time now: %s" % datetime.utcnow()
annotation = create_liquidsoap_annotation(media_item)
self.liquidsoap_mock_queues[queue_id].append(annotation)
except Exception:
raise
finally:
self.telnet_lock.release()
@ls_timeout
def queue_remove(self, queue_id):
try:
self.telnet_lock.acquire()
self.logger.info("Purging queue %s" % queue_id)
from datetime import datetime
print "Time now: %s" % datetime.utcnow()
except Exception:
raise
finally:
self.telnet_lock.release()
class QueueNotEmptyException(Exception):
pass

View file

@ -0,0 +1,98 @@
from pypoliqqueue import PypoLiqQueue
from telnetliquidsoap import DummyTelnetLiquidsoap, TelnetLiquidsoap
from Queue import Queue
from threading import Lock
import sys
import signal
import logging
from datetime import datetime
from datetime import timedelta
def keyboardInterruptHandler(signum, frame):
logger = logging.getLogger()
logger.info('\nKeyboard Interrupt\n')
sys.exit(0)
signal.signal(signal.SIGINT, keyboardInterruptHandler)
# configure logging
format = '%(levelname)s - %(pathname)s - %(lineno)s - %(asctime)s - %(message)s'
logging.basicConfig(level=logging.DEBUG, format=format)
logging.captureWarnings(True)
telnet_lock = Lock()
pypoPush_q = Queue()
pypoLiq_q = Queue()
liq_queue_tracker = {
"s0": None,
"s1": None,
"s2": None,
"s3": None,
}
#dummy_telnet_liquidsoap = DummyTelnetLiquidsoap(telnet_lock, logging)
dummy_telnet_liquidsoap = TelnetLiquidsoap(telnet_lock, logging, \
"localhost", \
1234)
plq = PypoLiqQueue(pypoLiq_q, telnet_lock, logging, liq_queue_tracker, \
dummy_telnet_liquidsoap)
plq.daemon = True
plq.start()
print "Time now: %s" % datetime.utcnow()
media_schedule = {}
start_dt = datetime.utcnow() + timedelta(seconds=1)
end_dt = datetime.utcnow() + timedelta(seconds=6)
media_schedule[start_dt] = {"id": 5, \
"type":"file", \
"row_id":9, \
"uri":"", \
"dst":"/home/martin/Music/ipod/Hot Chocolate - You Sexy Thing.mp3", \
"fade_in":0, \
"fade_out":0, \
"cue_in":0, \
"cue_out":300, \
"start": start_dt, \
"end": end_dt, \
"show_name":"Untitled", \
"replay_gain": 0, \
"independent_event": True \
}
start_dt = datetime.utcnow() + timedelta(seconds=2)
end_dt = datetime.utcnow() + timedelta(seconds=6)
media_schedule[start_dt] = {"id": 5, \
"type":"file", \
"row_id":9, \
"uri":"", \
"dst":"/home/martin/Music/ipod/Good Charlotte - bloody valentine.mp3", \
"fade_in":0, \
"fade_out":0, \
"cue_in":0, \
"cue_out":300, \
"start": start_dt, \
"end": end_dt, \
"show_name":"Untitled", \
"replay_gain": 0, \
"independent_event": True \
}
pypoLiq_q.put(media_schedule)
plq.join()

View file

@ -0,0 +1,18 @@
#!/bin/bash
which py.test
pytest_exist=$?
if [ "$pytest_exist" != "0" ]; then
echo "Need to have py.test installed. Exiting..."
exit 1
fi
SCRIPT=`readlink -f $0`
# Absolute directory this script is in
SCRIPTPATH=`dirname $SCRIPT`
export PYTHONPATH=$PYTHONPATH:$SCRIPTPATH/..:$SCRIPTPATH/../..
py.test

View file

@ -0,0 +1,26 @@
from pypopush import PypoPush
from threading import Lock
from Queue import Queue
import datetime
pypoPush_q = Queue()
telnet_lock = Lock()
pp = PypoPush(pypoPush_q, telnet_lock)
def test_modify_cue_in():
link = pp.modify_first_link_cue_point([])
assert len(link) == 0
min_ago = datetime.datetime.utcnow() - datetime.timedelta(minutes = 1)
link = [{"start":min_ago.strftime("%Y-%m-%d-%H-%M-%S"),
"cue_in":"0", "cue_out":"30"}]
link = pp.modify_first_link_cue_point(link)
assert len(link) == 0
link = [{"start":min_ago.strftime("%Y-%m-%d-%H-%M-%S"),
"cue_in":"0", "cue_out":"70"}]
link = pp.modify_first_link_cue_point(link)
assert len(link) == 1

View file

@ -0,0 +1,38 @@
import threading
import pypofetch
def __timeout(func, timeout_duration, default, args, kwargs):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
self.result = func(*args, **kwargs)
first_attempt = True
while True:
it = InterruptableThread()
it.start()
if not first_attempt:
timeout_duration = timeout_duration * 2
it.join(timeout_duration)
if it.isAlive():
"""Restart Liquidsoap and try the command one more time. If it
fails again then there is something critically wrong..."""
if first_attempt:
#restart liquidsoap
pypofetch.PypoFetch.ref.restart_liquidsoap()
else:
raise Exception("Thread did not terminate")
else:
return it.result
first_attempt = False
def ls_timeout(f, timeout=15, default=None):
def new_f(*args, **kwargs):
return __timeout(f, timeout, default, args, kwargs)
return new_f