Commit be058841 authored by Mikhail Karpenko's avatar Mikhail Karpenko

Add unmodified sources from elphel353 project

parents
html/*
attic/*
/.project
/.cproject
/.pydevproject
/.externalToolBuilders
/.settings
.directory
generated*
sysroots
bitbake-logs
/temp/
*.o
*.cgi
bitbake-logs
.depend
/image
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:
{project} Copyright (C) {year} {fullname}
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>.
# Runs 'make', 'make install', and 'make clean' in specified subdirectories
SUBDIRS := src
INSTALLDIRS = $(SUBDIRS:%=install-%)
CLEANDIRS = $(SUBDIRS:%=clean-%)
#TARGETDIR=$(DESTDIR)/www/pages
all: $(SUBDIRS)
@echo "make all top"
$(SUBDIRS):
$(MAKE) -C $@
install: $(INSTALLDIRS)
@echo "make install top"
$(INSTALLDIRS):
$(MAKE) -C $(@:install-%=%) install
clean: $(CLEANDIRS)
@echo "make clean top"
$(CLEANDIRS):
$(MAKE) -C $(@:clean-%=%) clean
.PHONY: all install clean $(SUBDIRS) $(INSTALLDIRS) $(CLEANDIRS)
# elphel-apps-astreamer
#!/bin/bash
args="$@"
while (( "$#" )); do
shift
done
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "Launching bitbake $args"
cd $DIR/../../poky
. ./oe-init-build-env
bitbake $args | sed -u 's@| @@'
exit 0
AXIS_USABLE_LIBS = UCLIBC GLIBC
AXIS_AUTO_DEPEND = yes
-include $(AXIS_TOP_DIR)/tools/build/Rules.axis
INSTALL ?= install_elinux
INSTALL_PATH = $(prefix)/usr/local
INCDIR = $(AXIS_KERNEL_DIR)/include
LDFLAGS = -Wl -s -L$(prefix)/lib -lpthread -lasound
CXXFLAGS = -Wall -O2 -I$(INCDIR)
STREAMER_OBJS = main.o streamer.o audio.o video.o socket.o rtsp.o rtp_stream.o helpers.o parameters.o
SRCS = main.cpp streamer.cpp audio.cpp video.cpp socket.cpp rtsp.cpp rtp_stream.cpp helpers.cpp parameters.cpp
PROG = str
all: dependency $(PROG)
clean:
rm -f *.o *.ver *.mp *~ core* $(PROG)
$(PROG): $(STREAMER_OBJS)
$(CXX) $(LDFLAGS) -o $@ $(STREAMER_OBJS) -lpthread -asound
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
#install: $(PROG)
install: clean $(PROG)
$(INSTALL) $(PROG) $(INSTALL_PATH)/bin/$(PROG)
configsubs:
#include "audio.h"
#include "helper.h"
#include <iostream>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <asm/elphel/c313a.h>
#include "parameters.h"
#undef AUDIO_DEBUG
//#define AUDIO_DEBUG
#undef AUDIO_DEBUG_2
//#define AUDIO_DEBUG_2
#ifdef AUDIO_DEBUG
#define D(a) a
#else
#define D(a)
#endif
#ifdef AUDIO_DEBUG_2
#define D2(a) a
#else
#define D2(a)
#endif
//#define SAMPLE_TIME 50 // in milliseconds
#define SAMPLE_TIME 20 // in milliseconds
#define BUFFER_TIME 1000 // in milliseconds
using namespace std;
Audio::Audio(bool enable, int sample_rate, int channels) {
//cerr << "Audio::Audio()" << endl;
snd_pcm_hw_params_t *hw_params;
snd_pcm_sw_params_t *sw_params;
_present = false;
stream_name = "audio";
// normalize audio settings
if(sample_rate == 0) sample_rate = SAMPLE_RATE;
if(sample_rate > 48000) sample_rate = 48000;
if(sample_rate < 11025) sample_rate = 11025;
_sample_rate = sample_rate;
if(channels == 0) channels = SAMPLE_CHANNELS;
if(channels < 1) channels = 1;
if(channels > 2) channels = 2;
_channels = channels;
_volume = 65535;
_volume *= 90;
_volume /= 100;
SSRC = 10;
// here sbuffer_len in samples, not bytes
sbuffer_len = _sample_rate * SAMPLE_TIME;
sbuffer_len /= 1000;
sbuffer_len -= sbuffer_len % 2;
D( cerr << "sbuffer_len == " << sbuffer_len << endl;)
_ptype = 97;
sbuffer = NULL;
if(enable) {
// open ALSA for capturing
int err;
sbuffer = new short[sbuffer_len * 2 * _channels];
bool init_ok = false;
while(true) {
if((err = snd_pcm_open(&capture_handle, "default", SND_PCM_STREAM_CAPTURE, 0)) < 0)
break;
snd_pcm_hw_params_alloca(&hw_params);
if((err = snd_pcm_hw_params_any(capture_handle, hw_params)) < 0)
break;
if((err = snd_pcm_hw_params_set_access(capture_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
break;
if((err = snd_pcm_hw_params_set_format(capture_handle, hw_params, SND_PCM_FORMAT_S16_BE)) < 0)
break;
unsigned int t = _sample_rate;
if((err = snd_pcm_hw_params_set_rate_near(capture_handle, hw_params, &t, 0)) < 0)
break;
unsigned int period_time = SAMPLE_TIME * 1000;
if((err = snd_pcm_hw_params_set_period_time_near(capture_handle, hw_params, &period_time, 0)) < 0)
break;
D( cerr << "period_time == " << period_time << endl;)
unsigned int buffer_time = BUFFER_TIME * 1000;
if((err = snd_pcm_hw_params_set_buffer_time_near(capture_handle, hw_params, &buffer_time, 0)) < 0)
break;
D( cerr << "buffer_time == " << buffer_time << endl;)
_sample_rate = t;
if((err = snd_pcm_hw_params_set_channels(capture_handle, hw_params, _channels)) < 0)
break;
if((err = snd_pcm_hw_params(capture_handle, hw_params)) < 0)
break;
snd_pcm_sw_params_alloca(&sw_params);
if((err = snd_pcm_sw_params_current(capture_handle, sw_params)) < 0)
break;
if((err = snd_pcm_sw_params_set_tstamp_mode(capture_handle, sw_params, SND_PCM_TSTAMP_ENABLE)) < 0)
break;
if((err = snd_pcm_sw_params(capture_handle, sw_params)) < 0)
break;
// if((err = snd_pcm_prepare(capture_handle)) < 0)
// break;
init_ok = true;
break;
}
if(init_ok) {
D( cerr << endl << "Audio init: ok; with sample rate: " << _sample_rate << "; and channels: " << _channels << endl;)
// cerr << endl << "Audio init: ok; with sample rate: " << _sample_rate << "; and channels: " << _channels << endl;
_present = true;
_play = false;
set_volume(_volume);
// create thread...
init_pthread((void *)this);
} else {
D( cerr << "Audio: init FAIL!" << endl;)
// cerr << "Audio: init FAIL!" << endl;
_present = false;
}
}
}
Audio::~Audio(void) {
//cerr << "Audio::~Audio()" << endl;
if(_present) {
snd_pcm_drop(capture_handle);
snd_pcm_close(capture_handle);
snd_config_update_free_global();
//cerr << "--------------->> close audio" << endl;
}
if(sbuffer != NULL)
delete[] sbuffer;
}
void Audio::set_capture_volume(int nvolume) {
if(_present == false)
return;
// int err;
snd_mixer_t *mixer;
snd_mixer_elem_t *elem;
snd_mixer_selem_id_t *sid;
// allocated at stack, so can't free it!
snd_mixer_selem_id_alloca(&sid);
snd_mixer_open(&mixer, 0);
snd_mixer_attach(mixer, "default");
snd_mixer_selem_register(mixer, NULL, NULL);
snd_mixer_load(mixer);
for(elem = snd_mixer_first_elem(mixer); elem; elem = snd_mixer_elem_next(elem)) {
snd_mixer_selem_get_id(elem, sid);
if(!snd_mixer_selem_is_active(elem))
continue;
// set volume at percents for capture elements
snd_mixer_elem_t *selem = snd_mixer_find_selem(mixer, sid);
if(selem == NULL) {
break;
}
long volume_min = 0;
long volume_max = 0;
if(snd_mixer_selem_get_capture_volume_range(selem, &volume_min, &volume_max) == 0) {
// set volume only for capture
if(nvolume > 65535)
nvolume = 65535;
if(nvolume < 0)
nvolume = 0;
long long vol_new = volume_max;
vol_new *= nvolume;
vol_new /= 65535;
long vol = 0;
snd_mixer_selem_get_capture_volume(selem, SND_MIXER_SCHN_FRONT_LEFT, &vol);
snd_mixer_selem_set_capture_volume_all(selem, vol_new);
D( cerr << "element " << snd_mixer_selem_id_get_name(sid) << " - OLD min vol == " << volume_min << "; max vol == " << volume_max << "; volume == " << vol << endl;)
D( snd_mixer_selem_get_capture_volume(selem, SND_MIXER_SCHN_FRONT_LEFT, &vol);)
D( cerr << "element " << snd_mixer_selem_id_get_name(sid) << " - NEW min vol == " << volume_min << "; max vol == " << volume_max << "; volume == " << vol << endl;)
}
}
_volume = nvolume;
snd_mixer_close(mixer);
}
void Audio::Start(string ip, long port, int ttl) {
if(!_present)
return;
D( cerr << "Audio ---> Start !!!" << endl;)
//cerr << "Audio ---> Start !!!" << endl;
//is_first = true;
timestamp_rtcp = 0;
f_tv.tv_sec = 0;
f_tv.tv_usec = 0;
snd_pcm_prepare(capture_handle);
snd_pcm_reset(capture_handle);
//cerr << "Audio ---> Start !!! - done" << endl;
// get FPGA/sys time delta
Parameters *params = Parameters::instance();
unsigned long write_data[6];
write_data[0] = FRAMEPARS_GETFPGATIME;
write_data[1] = 0;
params->write(write_data, sizeof(unsigned long) * 2);
struct timeval tv_1;
tv_1.tv_sec = params->getGPValue(G_SECONDS);
tv_1.tv_usec = params->getGPValue(G_MICROSECONDS);
struct timeval tv_sys;
gettimeofday(&tv_sys, NULL);
params->write(write_data, sizeof(unsigned long) * 2);
struct timeval tv_2;
tv_2.tv_sec = params->getGPValue(G_SECONDS);
tv_2.tv_usec = params->getGPValue(G_MICROSECONDS);
unsigned long delta = tv_2.tv_sec - tv_1.tv_sec;
delta *= 1000000;
delta += tv_2.tv_usec;
delta -= tv_1.tv_usec;
delta /= 2;
struct timeval tv_fpga;
tv_fpga.tv_sec = tv_1.tv_sec;
tv_fpga.tv_usec = tv_1.tv_usec + delta;
tv_fpga.tv_sec += tv_fpga.tv_usec / 1000000;
tv_fpga.tv_usec = tv_fpga.tv_usec % 1000000;
bool fpga_gt = false;
if(tv_fpga.tv_sec > tv_sys.tv_sec)
fpga_gt = true;
if (tv_fpga.tv_sec == tv_sys.tv_sec)
if(tv_fpga.tv_usec > tv_sys.tv_usec)
fpga_gt = true;
struct timeval *tv_b = &tv_sys;
struct timeval *tv_s = &tv_fpga;
if(fpga_gt) {
tv_b = &tv_fpga;
tv_s = &tv_sys;
}
delta_fpga_sys = 0;
delta_fpga_sys = tv_b->tv_sec - tv_s->tv_sec;
delta_fpga_sys *= 1000000;
delta_fpga_sys += tv_b->tv_usec;
delta_fpga_sys -= tv_s->tv_usec;
if(fpga_gt)
delta_fpga_sys = -delta_fpga_sys;
//fprintf(stderr, "first time == %d:%06d; second time == %d:%06d\n", tv_1.tv_sec, tv_1.tv_usec, tv_2.tv_sec, tv_2.tv_usec);
//fprintf(stderr, "FPGA time == %d:%06d; system time == %d:%06d\n", tv_fpga.tv_sec, tv_fpga.tv_usec, tv_sys.tv_sec, tv_sys.tv_usec);
//fprintf(stderr, "times delta == %06d\n\n", delta_fpga_sys);
RTP_Stream::Start(ip, port, ttl);
}
void Audio::Stop(void) {
if(!_present)
return;
// cerr << "Audio ---> Stop !!!" << endl;
D( cerr << "Audio ---> Stop !!!" << endl;)
RTP_Stream::Stop();
f_tv.tv_sec = 0;
f_tv.tv_usec = 0;
}
long Audio::process(void) {
// static timeval ts_old = {0, 0};
long ret = 0;
snd_pcm_status_t *status;
snd_pcm_status_alloca(&status);
snd_timestamp_t ts;
unsigned long avail;
//bool first = true;
for(int i = 0; i < 4; i++) {
snd_pcm_status(capture_handle, status);
long slen = snd_pcm_readi(capture_handle, sbuffer, sbuffer_len);
if(slen > 0) {
// update statistics for RTCP
avail = (unsigned long)snd_pcm_status_get_avail(status);
if(avail > 0) {
snd_pcm_status_get_tstamp(status, &ts);
timestamp = timestamp_rtcp;
timestamp += avail;
if(timestamp > 0xFFFFFFFF)
timestamp &= 0xFFFFFFFF;
f_tv.tv_sec = ts.tv_sec;
f_tv.tv_usec = ts.tv_usec;
// correct A time to V time for RTCP sync packets
f_tv.tv_sec -= 1;
f_tv.tv_usec += 1000000;
f_tv.tv_sec -= delta_fpga_sys / 1000000;
f_tv.tv_usec -= delta_fpga_sys % 1000000;
f_tv.tv_sec += f_tv.tv_usec / 1000000;
f_tv.tv_usec = f_tv.tv_usec % 1000000;
/*
if(is_first) {
struct timeval tv;
gettimeofday(&tv, NULL);
is_first = false;
fprintf(stderr, "AUDIO first with time: %d:%06d at: %d:%06d\n", f_tv.tv_sec, f_tv.tv_usec, tv.tv_sec, tv.tv_usec);
sec = f_tv.tv_sec;
} else {
if(sec != f_tv.tv_sec) {
sec = f_tv.tv_sec;
}
}
*/
}
/*
snd_pcm_status(capture_handle, status);
snd_pcm_status_get_tstamp(status, &ts);
avail = (unsigned long)snd_pcm_status_get_avail(status);
struct timeval tv_real;
gettimeofday(&tv_real, NULL);
struct timeval t_delta = {0, 0};
if(ts_old.tv_sec != 0 && ts_old.tv_usec != 0) {
long td = ts.tv_sec - ts_old.tv_sec;
td *= 1000000;
td += ts.tv_usec;
td -= ts_old.tv_usec;
t_delta.tv_sec = td / 1000000;
t_delta.tv_usec = td % 1000000;
}
fprintf(stderr, "status timestamp == %d:%06d at %d:%06d; delta == %d:%06d, slen == %d; avail == %d\n", ts.tv_sec, ts.tv_usec, tv_real.tv_sec, tv_real.tv_usec, t_delta.tv_sec, t_delta.tv_usec, slen, avail);
ts_old = ts;
*/
// --==--
ret += slen;
process_send(slen);
// check again what buffer is not empty
snd_pcm_status(capture_handle, status);
avail = (unsigned long)snd_pcm_status_get_avail(status);
//c++;
if(avail >= (unsigned long)sbuffer_len) {
//cerr << "process() again - available " << avail << " samples" << endl;
continue;
}
//if(c != 0)
//cerr << "process " << c << " times" << endl;
return ret;
}
if(slen < 0) {
cerr << "audio process(): slen < 0" << endl;
break;
}
if(slen == 0) {
cerr << "audio process(): slen == 0" << endl;
break;
}
}
return ret;
}
long Audio::process_send(long sample_len) {
static unsigned short packet_num = 0;
unsigned short pnum;
void *m = (void *)sbuffer;
int i;
long offset = 0;
#define LEN 1200
static unsigned char *d = NULL;
if(d == NULL) {
d = (unsigned char *)malloc(LEN + 20);
}
int to_send = sample_len * 2 * _channels;
int size = to_send;
long count = 0;
uint32_t ts;
for(;;) {
if(to_send == 0)
break;
if(to_send > LEN) {
i = LEN;
to_send -= i;
} else {
i = to_send;
to_send = 0;
}
ts = htonl(timestamp_rtcp);
uint32_t ts_delta = i / 2;
ts_delta /= _channels;
timestamp_rtcp += ts_delta;
if(timestamp_rtcp > 0xFFFFFFFF)
timestamp_rtcp &= 0xFFFFFFFF;
//
packet_num++;
pnum = htons(packet_num);
count += i;
// fill RTP header
d[0] = 0x80;
if(count >= size)
d[1] = _ptype + 0x80;
else
d[1] = _ptype;
memcpy((void *)&d[2], (void *)&pnum, 2);
memcpy((void *)&d[4], (void *)&ts, 4);
memcpy((void *)&d[8], (void *)&SSRC, 4);
// fill data
memcpy((void *)&d[12], (void *)((char *)m + offset), i);
offset += i;
// send packet
rtp_packets++;
rtp_octets += i; // data + MJPEG header
rtp_socket->send((void *)d, i + 12);
}
return sample_len;
}
#ifndef _AUDIO__H_
#define _AUDIO__H_
#include <string>
#define __cplusplus 1
#include <alsa/asoundlib.h>
#include <pthread.h>
#include "rtp_stream.h"
using namespace std;
#define SAMPLE_RATE 44100
#define SAMPLE_CHANNELS 2
class Audio : public RTP_Stream {
public:
Audio(bool enable, int sample_rate = SAMPLE_RATE, int channels = SAMPLE_CHANNELS);
virtual ~Audio(void);
long sample_rate(void) { return _sample_rate; };
long channels(void) { return _channels; };
bool present(void) { return _present; };
long volume(void) { return _volume; };
void set_volume(long volume) { set_capture_volume(volume); }
void Start(string ip, long port, int ttl = -1);
void Stop(void);
protected:
int fd;
snd_pcm_t *capture_handle;
short *sbuffer;
long sbuffer_len;
bool _present;
long _sample_rate;
long _channels;
long _volume;
long capture(void);
long process(void);
long process_send(long sample_len);
void set_capture_volume(int volume);
uint64_t timestamp_rtcp;
long delta_fpga_sys; // A/V clocks delta for RTCP
bool is_first;
bool is_first2;
};
//extern Audio *audio;
#endif // _AUDIO__H_
#ifndef __H_HELPER__
#define __H_HELPER__
#include <sys/time.h>
inline long time_delta_us(const struct timeval &tv_1, const struct timeval &tv_2) {
long tu = tv_1.tv_usec;
if(tv_1.tv_sec != tv_2.tv_sec)
tu += (tv_1.tv_sec - tv_2.tv_sec) * 1000000;
tu -= tv_2.tv_usec;
return tu;
}
inline struct timeval time_plus(struct timeval tv_1, const struct timeval &tv_2) {
tv_1.tv_sec += tv_2.tv_sec;
tv_1.tv_usec += tv_2.tv_usec;
if(tv_1.tv_usec >= 1000000) {
tv_1.tv_sec++;
tv_1.tv_usec -= 1000000;
}
return tv_1;
}
inline struct timeval time_minus(struct timeval tv_1, const struct timeval &tv_2) {
tv_1.tv_sec -= tv_2.tv_sec;
tv_1.tv_usec += 1000000;
tv_1.tv_usec -= tv_2.tv_usec;
if(tv_1.tv_usec >= 1000000) {
tv_1.tv_usec -= 1000000;
} else {
tv_1.tv_sec--;
}
return tv_1;
}
#endif
#include "helpers.h"
#include <iostream>
using namespace std;
bool String::split(const string &str, char delimiter, string &left, string &right) {
left = "";
right = "";
int i = str.find(delimiter);
//cerr << "_______" << endl;
//cerr << "delimiter == |" << delimiter << "|, i == " << i << endl;
if(i > 0 && i < (int)str.length()) {
const char *c = str.c_str();
//cerr <<
left.insert(0, c, i);
right.insert(0, &c[i + 1], str.length() - i - 1);
return true;
} else
left = str;
return false;
}
list<string> String::split_to_list(string str, char delimiter) {
list<string> l;
if((str.c_str())[str.length() - 1] != delimiter)
str += delimiter;
const char *c = str.c_str();
int j = 0;
for(int i = 0; c[i]; i++) {
if(c[i] == delimiter) {
string a;
a.insert(0, &c[j], i - j);
j = i + 1;
l.push_back(a);
}
}
return l;
}
map<string, string> String::split_list_to_map(const list<string> &l, char delimiter) {
map<string, string> m;
for(list<string>::const_iterator it = l.begin(); it != l.end(); it++) {
int i = (*it).find(delimiter);
if(i > 0 && i < (int)(*it).length()) {
const char *c = (*it).c_str();
string n, v;
n.insert(0, c, i);
v.insert(0, &c[i + 1], (*it).length() - i - 1);
m[n] = v;
}
}
return m;
}
#ifndef _HELPERS__H_
#define _HELPERS__H_
#include <string>
#include <list>
#include <map>
using namespace std;
class String {
public:
static bool split(const string &str, char delimiter, string &left, string &right);
static list<string> split_to_list(string str, char delimiter);
static map<string, string> split_list_to_map(const list<string> &l, char delimiter);
};
#endif // _HELPERS__H_
#include <iostream>
#include <string>
#include <map>
#include "streamer.h"
using namespace std;
#include <unistd.h>
#include <linux/sysctl.h>
int main(int argc, char *argv[]) {
string opt;
map<string, string> args;
for(int i = 1; i < argc; i++) {
if(argv[i][0] == '-' && argv[i][1] != '\0') {
if(opt != "")
args[opt] = "";
opt = &argv[i][1];
continue;
} else {
if(opt != "") {
args[opt] = argv[i];
opt = "";
}
}
}
if(opt != "")
args[opt] = "";
for(map<string, string>::iterator it = args.begin(); it != args.end(); it++) {
cerr << "|" << (*it).first << "| == |" << (*it).second << "|" << endl;
}
Streamer *streamer = new Streamer(args);
streamer->Main();
return 0;
}
#include "parameters.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <asm/elphel/c313a.h>
#include <iostream>
#include "streamer.h"
using namespace std;
#undef PARAMETERS_DEBUG
//#define PARAMETERS_DEBUG
#ifdef PARAMETERS_DEBUG
#define D(a) a
#else
#define D(a)
#endif
Parameters *Parameters::_parameters = NULL;
Parameters::Parameters(void) {
fd_fparmsall = open("/dev/frameparsall", O_RDWR);
if(fd_fparmsall < 0)
throw("can't open /dev/frameparsall");
//! now try to mmap
frameParsAll = (struct framepars_all_t *) mmap(0, sizeof (struct framepars_all_t) , PROT_READ | PROT_WRITE , MAP_SHARED, fd_fparmsall, 0);
if((int)frameParsAll == -1)
throw("Error in mmap /dev/frameparsall");
framePars = frameParsAll->framePars;
globalPars = frameParsAll->globalPars;
}
Parameters::~Parameters(void) {
if(fd_fparmsall > 0)
close(fd_fparmsall);
}
/**
* @brief Read either G_* parameter (these are 'regular' values defined by number) or P_* parameter
* (it can be read for up to 6 frames ahead, but current interface only allows to read last/current value)
* @param GPNumber parameter number (as defined in c313a.h), G_* parameters have numbers above FRAMEPAR_GLOBALS, P_* - below)
* @return parameter value
*/
unsigned long Parameters::getGPValue(unsigned long GPNumber) {
return (GPNumber >= FRAMEPAR_GLOBALS) ? GLOBALPARS(GPNumber) : framePars[GLOBALPARS(G_THIS_FRAME) & PARS_FRAMES_MASK].pars[GPNumber];
}
/**
* @brief Set value of the specified global (G_*) parameter
* @param GNumber - parameter number (as defined in c313a.h)
* @param value - value to set
*/
void Parameters::setGValue(unsigned long GNumber, unsigned long value) {
GLOBALPARS(GNumber) = value;
}
unsigned long Parameters::getFrameValue(unsigned long FPNumber) {
return framePars[GLOBALPARS(G_THIS_FRAME) & PARS_FRAMES_MASK].pars[FPNumber];
}
bool Parameters::daemon_enabled(void) {
return((getFrameValue(P_DAEMON_EN) & (1 << DAEMON_BIT_STREAMER)) != 0);
}
void Parameters::setPValue(unsigned long *val_array, int count) {
/*
long target_frame = params->getGPValue(G_THIS_FRAME) + FRAMES_AHEAD_FPS;
write_data[0] = FRAMEPARS_SETFRAME;
write_data[1] = target_frame; /// wait then for that frame to be available on the output plus 2 frames for fps to be stable
write_data[2] = P_FP1000SLIM;
write_data[3] = (unsigned long)fps * 1000;
write_data[4] = P_FPSFLAGS;
write_data[5] = 3;
*/
// long rslt = write(fd_fparmsall, write_data, sizeof(write_data));
this->write(val_array, sizeof(unsigned long) * count);
}
//------------------------------------------------------------------------------
#ifndef _PARS__H_
#define _PARS__H_
#include <sys/types.h>
#include <unistd.h>
#include <string>
using namespace std;
#include <asm/elphel/c313a.h>
//#define FRAMES_AHEAD_FPS 3 /// number of video frames ahead of current to frite FPS limit
//#define FRAMES_SKIP_FPS 3 /// number of video frames to wait after target so circbuf will have at least 2 frames with new fps for calculation
class Parameters {
public:
/*
enum vevent {
VEVENT0,
DAEMON_DISABLED,
FPS_CHANGE,
SIZE_CHANGE
};
*/
inline static Parameters *instance(void) {
if(_parameters == NULL)
_parameters = new Parameters();
return _parameters;
}
~Parameters(void);
// unsigned long get
/// interface to global camera parameters
unsigned long getGPValue(unsigned long GPNumber);
void setGValue(unsigned long GNumber, unsigned long value);
unsigned long getFrameValue(unsigned long FPNumber);
int write(unsigned long *data, int length) { return ::write(fd_fparmsall, (void *)data, length); }
off_t lseek(off_t offset, int whence) { return ::lseek(fd_fparmsall, offset, whence); }
bool daemon_enabled(void);
void setPValue(unsigned long *val_array, int count);
protected:
static Parameters *_parameters;
Parameters(void);
struct framepars_all_t *frameParsAll;
struct framepars_t *framePars;
unsigned long *globalPars;
int fd_fparmsall;
};
//extern Video *video;
#endif // _VIDEO__H_
#include <arpa/inet.h>
#include <iostream>
#include "rtp_stream.h"
#include "helper.h"
using namespace std;
#define CNAME "elphel353"
#undef RTP_DEBUG
//#define RTP_DEBUG
#ifdef RTP_DEBUG
#define D(a) a
#else
#define D(a)
#endif
RTP_Stream::RTP_Stream(void) {
_play = false;
pthread_mutex_init(&pthm_flow, NULL);
stream_name = "unknown";
rtp_socket = NULL;
rtcp_socket = NULL;
sem_init(&sem_play, 0, 0);
pth_id = -1;
}
RTP_Stream::~RTP_Stream() {
//cerr << "RTP_Stream::~RTP_Stream() for stream " << stream_name << endl;
if(pth_id >= 0)
pthread_cancel(pth);
if(rtp_socket != NULL)
delete rtp_socket;
if(rtcp_socket != NULL)
delete rtcp_socket;
sem_destroy(&sem_play);
pthread_mutex_destroy(&pthm_flow);
}
void RTP_Stream::init_pthread(void *__this) {
pthread_attr_t tattr;
pthread_attr_init(&tattr);
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
pth_id = pthread_create(&pth, &tattr, RTP_Stream::pthread_f, (void *)__this);
}
void *RTP_Stream::pthread_f(void *_this) {
RTP_Stream *__this = (RTP_Stream *)_this;
return __this->thread();
}
void RTP_Stream::Start(string ip, int port, int ttl) {
D( cerr << " new " << stream_name << " UDP socket at port: " << port << endl;)
pthread_mutex_lock(&pthm_flow);
if(!_play) {
rtp_socket = new Socket(ip, port, Socket::TYPE_UDP, ttl);
rtcp_socket = new Socket(ip, port + 1, Socket::TYPE_UDP, ttl);
rtp_packets = 0;
rtp_octets = 0;
rtcp_tv.tv_sec = 0;
rtcp_tv.tv_usec = 0;
// rtcp_delay = 2500000; // in usec
// rtcp_delay = 1250000; // in usec
rtcp_delay = 2000000; // in usec
_play = true;
/// unlock semaphore - 'play' event
sem_post(&sem_play);
}
pthread_mutex_unlock(&pthm_flow);
}
void RTP_Stream::Stop(void) {
D( cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ <<endl;)
//cerr << "RTP_Stream::Stop() for stream " << stream_name << " - begin" << endl;
pthread_mutex_lock(&pthm_flow);
if(_play) {
//cerr << "RTP_Stream::Stop() for stream " << stream_name << " - in progress" << endl;
/// reset semaphore
sem_init(&sem_play, 0, 0);
_play = false;
// delete rtcp_socket;
if(rtp_socket != NULL) {
delete rtp_socket;
rtp_socket = NULL;
}
if(rtcp_socket != NULL) {
delete rtcp_socket;
rtcp_socket = NULL;
}
}
pthread_mutex_unlock(&pthm_flow);
//cerr << "RTP_Stream::Stop() for stream " << stream_name << " - end" << endl;
}
/**
* @brief Thread that invokes the video (and audio too) frame acquisition/ transmission
* In the current implementation video process() is blocking, but may be made
* non-blocking again later (through poll()). In addition to bool result
* (false if no frames are available, there are now long process(), with
* additional <0 result for the video frame change/stream shut down detected
* in Video class.
* @return never
*/
void *RTP_Stream::thread(void) {
D( cerr << "RTP_Stream::thread(void)" <<endl;)
for(;;) {
pthread_mutex_lock(&pthm_flow);
if(_play) {
long f = process();
if(f > 0)
rtcp();
// process() and rtcp() use sockets
pthread_mutex_unlock(&pthm_flow);
if(f < 0) {
D( cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__<< "process exception detected: " << f << endl;)
// cerr << "Stop() from thread for stream " << stream_name << endl;
Stop();
}
} else { /// wait for 'play' event semaphore
pthread_mutex_unlock(&pthm_flow);
sem_wait(&sem_play);
}
}
return NULL;
}
void RTP_Stream::rtcp(void) {
// check time for next one RTCP...
if(f_tv.tv_sec == 0 && f_tv.tv_usec == 0)
return;
long td = time_delta_us(f_tv, rtcp_tv);
if(td < 0) {
rtcp_tv = f_tv;
return;
}
if(td < rtcp_delay)
return;
rtcp_tv = f_tv;
rtcp_send_sdes();
rtcp_send_sr();
}
void RTP_Stream::rtcp_send_sr(void) {
char packet[8 + 20]; // by RTP RFC 3550, for SR RTCP packet needed 8 + 20 bytes
int packet_len = sizeof(packet);
uint16_t us;
uint32_t ul;
// RTCP header
packet[0] = 0x81;
packet[1] = 200; // SR
us = htons(((packet_len) / 4) - 1);
memcpy((void *)&packet[2], (void *)&us, 2);
memcpy((void *)&packet[4], (void *)&SSRC, 4);
// NTP timestamp is a fixed point 32.32 format time
ul = htonl(f_tv.tv_sec);
memcpy((void *)&packet[8], (void *)&ul, 4);
double d = f_tv.tv_usec;
d /= 1000000.0;
d *= 65536.0;
d *= 4096.0;
uint32_t f = (uint32_t)d;
if(f > 0x0FFFFFFF)
f = 0x0FFFFFFF;
f <<= 4;
ul = htonl(f);
memcpy((void *)&packet[12], (void *)&ul, 4);
ul = htonl(timestamp);
memcpy((void *)&packet[16], (void *)&ul, 4);
ul = htonl(rtp_packets);
memcpy((void *)&packet[20], (void *)&ul, 4);
ul = htonl(rtp_octets);
memcpy((void *)&packet[24], (void *)&ul, 4);
rtcp_socket->send(packet, packet_len);
}
void RTP_Stream::rtcp_send_sdes(void) {
char packet[8 + 4 + 128]; // by RTP RFC 3550, for SDES RTCP packet needed 8 + 4 + ... bytes,
// so get additional 128 bytes for 126 CNAME field
int packet_len = 0;
int padding=0;
uint16_t us;
const char *cname = CNAME;
int cname_len = strlen(cname);
bzero((void *)packet, 140); //8+4+128
// RTCP header
packet[0] = 0x81;
packet[1] = 202;
memcpy((void *)&packet[4], (void *)&SSRC, 4);
packet_len += 8;
// SDES fields
packet[8] = 0x01;
memcpy((void *)&packet[10], (void *)cname, cname_len);
packet_len += 2; // + cname_len;
// calculate common length SDES
padding=(cname_len+2)%4;
if(padding)
cname_len += (4-padding);
packet[9] = cname_len;
// each chunk MUST be terminated by one or more null octets(RFC3350)
packet_len += (cname_len+4);
us = htons((packet_len / 4) - 1);
memcpy((void *)&packet[2], (void *)&us, 2);
rtcp_socket->send(packet, packet_len);
}
#ifndef __H_RTP_STREAM__
#define __H_RTP_STREAM__
#include <sys/time.h>
#include <string>
#include <pthread.h>
#include <semaphore.h>
#include "socket.h"
#include <stdint.h>
using namespace std;
extern int fd_stream;
class RTP_Stream {
public:
RTP_Stream(void);
virtual ~RTP_Stream();
int ptype(void) { return _ptype; };
virtual void Start(string ip, int port, int ttl = -1);
virtual void Stop(void);
protected:
void init_pthread(void *__this);
pthread_t pth;
int pth_id;
static void *pthread_f(void *_this);
void *thread(void);
pthread_mutex_t pthm_flow;
// virtual bool process(void) = 0;
virtual long process(void) = 0;
int _ptype;
bool _play;
/// semaphore to wait 'play' event
sem_t sem_play;
Socket *rtp_socket;
Socket *rtcp_socket;
unsigned short packet_num;
unsigned long SSRC;
struct timeval f_tv;
struct timeval rtcp_tv; // time of last SR
long rtcp_delay;
unsigned long timestamp;
unsigned long rtp_packets;
unsigned long rtp_octets;
void rtcp(void);
void rtcp_send_sr(void);
void rtcp_send_sdes(void);
string stream_name;
};
#endif //__H_RTP_STREAM__
#include "rtsp.h"
#include "helpers.h"
#include "parameters.h"
#include <string.h>
#include <vector>
using namespace std;
#undef RTSP_DEBUG
#undef RTSP_DEBUG_2
//#define RTSP_DEBUG
//#define RTSP_DEBUG_2
#ifdef RTSP_DEBUG
#define D(a) a
#else
#define D(a)
#endif
#ifdef RTSP_DEBUG_2
#define D2(a) a
#else
#define D2(a)
#endif
#define RTSP_SIGN "rtsp://"
#define RTSP_PORT_1 554
#define RTSP_PORT_2 8554
//#define RTSP_PORT_3 7070
// TODO
_Request::_Request(const string &request) {
string s;
int prev = 0;
int i = 0;
int len = request.length();
const char *c = request.c_str();
bool first = true;
string name, value;
while(i < len) {
s = "";
for(; i < len && c[i] != '\n' && c[i] != '\r' && c[i] != '\0'; i++);
if(c[i] == '\n' || c[i] == '\r') {
if(i == prev) {
i++;
prev = i;
continue;
}
s.insert(0, request, prev, i - prev);
// cerr << "prev == " << prev << "; i == " << i << ";--> " << "\trequest string: \"" << s << "\"" << endl;
if(first) {
int x = s.find(" ");
method.insert(0, s, 0, x);
int y = s.find(" ", x + 1);
uri.insert(0, s, x + 1, y - x - 1);
// cerr << "method == |" << method << "|; uri == |" << uri << "|" << endl;
first = false;
} else {
name = "";
value = "";
int x = s.find(": ");
name.insert(0, s, 0, x);
value.insert(0, s, x + 2, s.length() - x - 1);
fields[name] = value;
// cerr << "pair: name == |" << name << "|; value == |" << value << "|" << endl;
}
}
if(c[i] == '\0')
break;
i++;
prev = i;
}
}
void _Responce::add_field(const string &name, const string &value) {
fields[name] = value;
}
void _Responce::add_include(const string &_include) {
include = _include;
}
string _Responce::serialize() {
string rez;
switch(_status) {
case STATUS_OK:
rez = "RTSP/1.0 200 OK\r\n";
break;
case STATUS_BUSY:
rez = "RTSP/1.0 455 Server is busy\r\n";
break;
case STATUS_EMPTY:
rez = "";
return rez;
}
for(map<string, string>::iterator it = fields.begin(); it != fields.end(); it++) {
rez += (*it).first + ": " + (*it).second + "\r\n";
}
rez += "\r\n";
if(include.length() != 0) {
rez += include;
}
return rez;
}
RTSP_Server::RTSP_Server(int (*h)(void *, RTSP_Server *, RTSP_Server::event), void *handler_data, Session *_session) {
socket_main_1 = NULL;
socket_main_2 = NULL;
// socket_main_3 = NULL;
handler_f = h;
this->handler_data = handler_data;
session = _session;
// _busy = NULL;
}
void RTSP_Server::main(void) {
list<Socket *> s;
// create listen socket...
// once opened socket to listen can be closed and reopen again by Socket's implementation:
// opened port assigned to process id and is keeped all time while process is alive
// so, keep this socket
if(socket_main_1 == NULL) {
socket_main_1 = new Socket("", RTSP_PORT_1);
socket_main_1->listen(2);
}
if(socket_main_2 == NULL) {
socket_main_2 = new Socket("", RTSP_PORT_2);
socket_main_2->listen(2);
}
/*
if(socket_main_3 == NULL) {
socket_main_3 = new Socket("", RTSP_PORT_3);
socket_main_3->listen(2);
}
*/
/*
if(socket_main == NULL) {
// socket_main = new Socket("", 554);
//cerr << "create socket to listen port" << endl;
socket_main = new Socket("", RTSP_PORT);
// Socket *socket_1 = new Socket("", 554);
// Socket *socket_2 = new Socket("", 8554);
// Socket *socket_3 = new Socket("", 7070);
socket_main->listen(2);
} else {
//cerr << "main socket already exist" << endl;
}
*/
s.push_back(socket_main_1);
s.push_back(socket_main_2);
// s.push_back(socket_main_3);
D(static int count = 0;)
bool to_poll = true;
// Parameters *params = Parameters::instance();
while(true) {
if(to_poll) {
int poll_rez = Socket::poll(s, 500);
D( {if(count < 5) {
cerr << "poll..." << endl;
count++;
}
});
// TODO here:
// if client connected - check for changes of all possible parameters
// if client not connected - check only about enable/disable bit to prevent overhead
if(handler(PARAMS_WAS_CHANGED)) {
// stop all sessions, and restart streamer
handler(RESET);
break;
}
if(poll_rez == 0) {
/// poll was finished with timeout, not socket event
to_poll = true;
continue;
}
}
to_poll = true;
for(list<Socket *>::iterator it = s.begin(); it != s.end(); it++) {
Socket::state state = (*it)->state_refresh();
if(state == Socket::STATE_IN || state == Socket::STATE_DISCONNECT) {
D2(cerr << endl << "something happen on the socket!" << endl;)
if(*it == socket_main_1 || *it == socket_main_2) {// || *it == socket_main_3) {
// Socket *in = socket_main->accept();
Socket *in = (*it)->accept();
if(in) {
in->set_so_keepalive(1);
D2(cerr << "processed - s.push_back(in)" << endl;)
D2(fprintf(stderr, "added : 0x%08X\n", in);)
s.push_back(in);
}
} else {
// check for remove closed socket !
D2(cerr << "was with non-main socket" << endl;)
if(!process(*it)) {
D2(cerr << "process failed - remove it!" << endl;)
D2(fprintf(stderr, "delete: 0x%08X\n", *it);)
delete *it;
s.remove(*it);
// check about counters etc...
to_poll = false;
break;
}
}
}
}
}
// stop all - by TEARDOWN command
for(list<Socket *>::iterator it = s.begin(); it != s.end(); it++) {
// keep the 'main' i.e. server socket
if(*it != socket_main_1 && *it != socket_main_2) {// && *it != socket_main_3) {
D2(fprintf(stderr, "delete: 0x%08X\n", *it);)
delete *it;
}
}
// reset sockets IDs and state
// _busy = NULL;
active_sockets.erase(active_sockets.begin(), active_sockets.end());
}
bool RTSP_Server::process_teardown(Socket *s) {
// if(!session->rtp_out.multicast)
// _busy = s;
for(list<Socket *>::iterator it = active_sockets.begin(); it != active_sockets.end(); it++)
if(*it == s) {
// if(*it != socket_main)
// delete *it;
active_sockets.erase(it);
return true;
}
return false;
}
bool RTSP_Server::process_play(Socket *s, bool add) {
// discard unicast client if client already exist
if(!session->rtp_out.multicast)
if(active_sockets.size() != 0)
return false;
if(add)
active_sockets.push_back(s);
return true;
}
bool RTSP_Server::process(Socket *s) {
string req;
_Request *request;
_Responce *responce = NULL;
bool r = true;
_Responce::status status = _Responce::STATUS_EMPTY;
D(cerr << "RTSP_Server::process()" << endl;)
bool to_teardown = false;
// recv failed - socket error - should close socket and check teardown
if(!s->recv(req))
to_teardown = true;
// empty request mean connection closed (behavior of Socket)
if(req == "")
to_teardown = true;
// decrement active clients, and stop stream if no clients
if(to_teardown) {
if(process_teardown(s))
handler(TEARDOWN);
return false;
}
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " part_REQUEST: " << endl << "\"" << req << "\"" << endl;)
// check for partial request...
part_of_request += req;
req = part_of_request;
const char *c = req.c_str();
string end;
int e = req.length();
e -= 4;
if(e <= 0)
e = 0;
for(int i = req.length() - 1; i >= e; i--) {
end += c[i];
}
if(end.find("\n\n") != 0 && end.find("\n\r\n\r") != 0) {
return true;
} else {
part_of_request = "";
}
// process...
request = new _Request(req);
Parameters *params = Parameters::instance();
responce = new _Responce();
// responce->add_field("CSeq", (*request->get_fields().find("CSeq")).second);
responce->add_field("CSeq", (request->get_fields())["CSeq"]);
if(request->get_method() == "OPTIONS") {
if(params->daemon_enabled()) {
status = _Responce::STATUS_OK;
responce->add_field("Public", "DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
// check transport...
if(!session->rtp_out.multicast)
session->rtp_out.ip = s->source_ip();
} else {
status = _Responce::STATUS_BUSY;
}
}
if(request->get_method() == "DESCRIBE") {
if(params->daemon_enabled() && process_play(s, false)) {
handler(DESCRIBE); /// Streamer should update session data (width, height, fps)
status = _Responce::STATUS_OK;
char buf[8];
string sdp = make_sdp(request->get_uri());
responce->add_field("Content-Type", "application/sdp");
sprintf(buf, "%d", (int)sdp.length());
responce->add_field("Content-Length", buf);
responce->add_include(sdp);
} else {
status = _Responce::STATUS_BUSY;
}
}
if(request->get_method() == "SETUP") {
if(params->daemon_enabled() && process_play(s, false)) {
status = _Responce::STATUS_OK;
// TODO: random session number
responce->add_field("Session", "47112344");
// responce->add_field("Transport", make_transport((*request->get_fields().find("Transport")).second));
responce->add_field("Transport", make_transport(request->get_fields()["Transport"]));
} else {
status = _Responce::STATUS_BUSY;
}
}
if(request->get_method() == "TEARDOWN") {
status = _Responce::STATUS_OK;
process_teardown(s);
handler(TEARDOWN);
}
if(request->get_method() == "PLAY") {
if(params->daemon_enabled() && (process_play(s))) {
status = _Responce::STATUS_OK;
handler(PLAY);
} else {
status = _Responce::STATUS_BUSY;
}
}
if(request->get_method() == "PAUSE") {
status = _Responce::STATUS_OK;
handler(PAUSE);
}
delete request;
responce->set_status(status);
D( cerr << "\tRESPONSE: " << endl << "\"" << responce->serialize() << "\"" << endl;)
r = s->send(responce->serialize());
delete responce;
return r;
}
string RTSP_Server::make_sdp(string uri) {
char buf[256];
D(cerr << "make SDP" << endl;)
// make video description
// m = - port + PAYLOAD
string rez;
///*
rez += "m=video ";
sprintf(buf, "%d", session->rtp_out.port_video);
if(session->process_audio == false) {
if(session->rtp_out.multicast) {
rez += buf;
} else {
rez += "0";
}
} else {
rez += buf;
}
rez += " RTP/AVP ";
sprintf(buf, "%d", session->video.type);
rez += buf;
rez += "\r\n"; // port
if(session->rtp_out.multicast) {
rez += "a=type:multicast\r\n";
rez += "c=IN IP4 " + session->rtp_out.ip + "/" + session->rtp_out.ttl + "\r\n"; // IP + TTL
} else {
rez += "a=type:unicast\r\n";
rez += "c=IN IP4 0.0.0.0\r\n"; // IP + TTL
}
sprintf(buf, "%.4f", session->video.fps);
// rez += "a=framerate:";
// rez += buf;
rez += "\r\na=x-framerate:";
rez += buf;
//cerr << "x-framerate == " << buf << endl;
if(session->video.width > 0) {
sprintf(buf, "%d", session->video.width);
// rez += "\r\na=width:";
// rez += buf;
rez += "\r\na=x-width:";
rez += buf;
}
if(session->video.height > 0) {
sprintf(buf, "%d", session->video.height);
// rez += "\r\na=height:";
// rez += buf;
rez += "\r\na=x-height:";
rez += buf;
}
if(session->video.width > 0 && session->video.height > 0) {
sprintf(buf, "%d,%d", session->video.width, session->video.height);
rez += "\r\na=x-dimensions:";
rez += buf;
}
rez += "\r\n";
//*/
// make audio description, if present
if(session->process_audio) {
// sprintf(buf, "m=audio %d RTP/AVP %d\r\n", atoi(session->rtp_out.port.c_str()) + 2, session->audio.type);
sprintf(buf, "m=audio %d RTP/AVP %d\r\n", session->rtp_out.port_audio, session->audio.type);
rez += buf;
sprintf(buf, "a=rtpmap:%d L16/%d/%d\r\n", session->audio.type, session->audio.sample_rate, session->audio.channels);
//cerr << "SDP: " << buf << endl;
rez += buf;
}
/*
if(session->rtp_out.multicast) {
rez += "a=type:multicast\r\n";
rez += "c=IN IP4 " + session->rtp_out.ip + "/" + session->rtp_out.ttl + "\r\n"; // IP + TTL
} else {
rez += "a=type:unicast\r\n";
rez += "c=IN IP4 0.0.0.0\r\n"; // IP + TTL
}
*/
rez += "a=control:" + uri + "\r\n";
D(cerr << "make SDP - ok!" << endl;)
return rez;
}
string RTSP_Server::make_transport(string req) {
if(req == "")
return "";
map<string, string> m = String::split_list_to_map(String::split_to_list(req, ';'), '=');
string client_port = m["client_port"];
int port_req = session->rtp_out.port_video;
//D(cerr << "client_port == " << client_port << endl;)
if(client_port != "") {
string first, second;
String::split(client_port, '-', first, second);
port_req = atol(first.c_str());
//D(cerr << "client_port == |" << client_port << "|; first == |" << first << "|; second == |" << "|" << endl;)
// session->rtp_out.port = first;
}
if(!session->rtp_out.multicast) {
if(!session->process_audio) {
session->rtp_out.port_video = port_req;
}
}
string rez = "RTP/AVP;";
char buf[128];
sprintf(buf, "%d", port_req);
if(session->rtp_out.multicast)
rez += "multicast;destination=" + session->rtp_out.ip + ";port=" + buf;
else
rez += "unicast;destination=" + session->rtp_out.ip + ";server_port=" + buf;
if(session->process_audio) {
sprintf(buf, "-%d", port_req + 1);
// rez += "-";
// long p = atol(session->rtp_out.port.c_str());
// p++;
// sprintf(buf, "%d", p);
rez += buf;
}
if(session->rtp_out.multicast)
rez += ";ttl=" + session->rtp_out.ttl;
// rez += "destination=" + transport.ip + ";port=" + transport.port;
// if(transport.multicast)
// rez += ";ttl=" + transport.ttl;
return rez;
}
RTSP_Server::~RTSP_Server() {
// cerr << "destroy RTSP_Server object" << endl;
// delete socket_main;
// if (request) delete request;
// if (responce) delete responce;
}
#ifndef _RTSP_H_
#define _RTSP_H_
//#include "types.h"
#include "session.h"
#include "socket.h"
#include <map>
#include <list>
#include <string>
#include <iostream>
using namespace std;
class _Request {
public:
_Request(const string &req);
inline const string &get_method(void) {
return method;
}
inline const string &get_uri(void) {
return uri;
}
inline map<string, string> &get_fields(void) {
return fields;
}
protected:
string method;
string uri;
map<string, string> fields;
};
class _Responce {
public:
enum status {STATUS_EMPTY, STATUS_BUSY, STATUS_OK};
_Responce():_status(STATUS_EMPTY) {};
inline void set_status(status st) {
_status = st;
}
void add_field(const string &name, const string &value);
void add_include(const string &include);
string serialize(void);
protected:
status _status;
map<string, string> fields;
string include;
};
class RTSP_Server {
public:
enum event {
EMPTY,
DESCRIBE,
PLAY,
PAUSE,
TEARDOWN,
PARAMS_WAS_CHANGED,
RESET
// IS_DAEMON_ENABLED
};
// if transport == NULL - wait for set_transport(), when client connected and ask DESCRIBE
RTSP_Server(int (*h)(void *, RTSP_Server *, RTSP_Server::event), void *handler_data, Session *_session = NULL);
~RTSP_Server();
// deprecated
void main(void);
protected:
bool process(Socket *s);
string make_sdp(string uri);
string make_transport(string req);
Session *session;
// socket to accept requests
// Socket *socket_main;
int (*handler_f)(void *, RTSP_Server *, RTSP_Server::event);
void *handler_data;
int handler(RTSP_Server::event event) {
return handler_f(handler_data, this, event);
}
// keep Sockets of clients to identify them and block second client in unicast mode
list<Socket *> active_sockets;
bool process_teardown(Socket *s);
bool process_play(Socket *s, bool add = true); // if secons argument is false - just check what server not busy
// void *_busy; // pointer to Socket of client, what use current unicast stream
string part_of_request;
// thread...
// RTP *rtp;
Socket *socket_main_1;
Socket *socket_main_2;
// Socket *socket_main_3;
};
#endif // _RTSP_H_
#ifndef _SESSION__H_
#define _SESSION__H_
#include <string>
using namespace std;
#define VIDEO_MJPEG "MJPG"
struct transport_t {
string ip;
bool ip_custom; // true, if user set IP by himself, otherwise false
unsigned long ip_cached; // cashed IP to check parameter
// string port;
int port_video;
int port_audio;
bool process_audio;
bool multicast;
string ttl;
};
struct video_t {
int type; // == "", if not present
double fps; // == 0, if unspecified
int width;
int height;
int fps_scale; // 0,1 - no scale, 2 - scale 2x etc...
};
struct audio_t {
int type;
int sample_rate;
int channels;
int volume; // for inner use only - from 0 to 65535 - current audio capture volume
};
class Session {
public:
string id;
struct transport_t rtp_in;
struct transport_t rtp_out;
struct video_t video;
struct audio_t audio;
bool process_audio;
};
#endif // _SESSION__H_
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/poll.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>
using namespace std;
#include "socket.h"
#include "helpers.h"
#undef RTSP_DEBUG
#undef RTSP_DEBUG_2
#ifdef RTSP_DEBUG
#define D(a) a
#else
#define D(a)
#endif
#ifdef RTSP_DEBUG_2
#define D2(a) a
#else
#define D2(a)
#endif
#define BUF_SIZE 2048
TCP_Client::TCP_Client(bool enable_exception) {
ex = enable_exception;
fd = -1;
}
TCP_Client::~TCP_Client() {
disconnect();
}
void TCP_Client::connect(string ip, string port) {
if((fd = ::socket(PF_INET, SOCK_STREAM, 0)) == -1) {
cerr << "fail socket()" << endl;
throw(false);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(::atol(port.c_str()));
addr.sin_addr.s_addr = ::inet_addr(ip.c_str());
if(::connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
cerr << "fail connect() to " << ip << ":" << port << endl;
throw(false);
}
// TODO: we must use size as MTU for interface... and also - checking for not single frames...
buf = (char *)malloc(1500);
}
void TCP_Client::disconnect(void) {
if(fd > 0) {
::close(fd);
free(buf);
buf = NULL;
}
fd = -1;
}
void TCP_Client::send(const string *data, int opt) {
if(::send(fd, data->c_str(), data->length(), opt) < 0) {
cerr << "fail to send(const string *)" << endl;
throw(false);
}
}
void TCP_Client::send(const string data, int opt) {
int er;
if(::send(fd, data.c_str(), data.length(), opt) < 0) {
er = errno;
cerr << "fail to send(const string): " << strerror(er) << endl;
throw(false);
}
}
void TCP_Client::send(void *data, int len, int opt) {
if(::send(fd, data, len, opt) < 0) {
cerr << "fail to send(void *, len)" << endl;
throw(false);
}
}
void TCP_Client::recv(string &r, int opt) {
int l, er;
if((l = ::recv(fd, buf, BUF_SIZE - 1, opt)) > 0) {
buf[l] = '\0';
r = buf;
} else {
er = errno;
cerr << "fail to recv(string &): " << strerror(er) << endl;
throw (false);
}
}
/*
* Socket class...
*/
unsigned long Socket::ip_to_number(string ip) {
string left;
string right;
unsigned long rez = 0;
while(String::split(ip, '.', left, right)) {
rez += atol(left.c_str());
rez <<= 8;
ip = right;
}
return rez;
}
bool Socket::_is_multicast(string ip) {
bool rez = true;
unsigned long a_min = ip_to_number("224.0.0.0");
unsigned long a_max = ip_to_number("239.255.255.255");
if(a_min > a_max) {
unsigned long a = a_min;
a_min = a_max;
a_max = a;
}
unsigned long a_ip = ip_to_number(ip.c_str());
if(a_ip > a_max)
rez = false;
if(a_ip < a_min)
rez = false;
return rez;
}
struct in_addr Socket::mcast_from_local(void) {
int _fd;
int reuse = 1;
_fd = socket(AF_INET, SOCK_DGRAM, 0);
setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse));
struct ifreq ifr;
struct sockaddr_in *sin;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, "eth0");
struct ifconf ifc;
ifc.ifc_len = 1;
ifc.ifc_req = &ifr;
ioctl(_fd, SIOCGIFADDR, &ifr);
close(_fd);
sin = (struct sockaddr_in *)(ifr.ifr_addr.sa_data - 2);
sin->sin_addr.s_addr &= (0xFFFFFF0F);
sin->sin_addr.s_addr |= (0x000000E0);
return sin->sin_addr;
}
/// use ttl parameter only with UDP sockets
Socket::Socket(string _ip, int _port, stype _type, int ttl) {
ip = _ip;
port = _port;
is_multicast = false;
D(cerr << "new socket..." << endl;)
_state = STATE_EMPTY;
int t = 0;
type = _type;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = PF_INET;
addr.sin_port = htons(port);
switch(type) {
case TYPE_TCP: {
fd = socket(PF_INET, SOCK_STREAM, 0);
int flag = 1;
setsockopt(fd, IPPROTO_IP, SO_REUSEADDR, &flag, sizeof(flag));
if(ip != "")
addr.sin_addr.s_addr = inet_addr(ip.c_str());
else
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(ttl>0)
setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
t = bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
D( int er = errno;)
D( cerr << "TCP ::bind() == " << t; if(t != 0) cerr << "; errno == " << strerror(er); cerr << endl;)
break;
}
case TYPE_UDP: {
fd = socket(PF_INET, SOCK_DGRAM, 0);
struct sockaddr_in saddr;
memset(&saddr, 0, sizeof(struct sockaddr_in));
saddr.sin_family = PF_INET;
saddr.sin_port = htons(0);
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
::bind(fd, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in));
addr.sin_addr.s_addr = inet_addr(ip.c_str());
t = ::connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
D( cerr << "::connect() == " << t << endl;)
if((is_multicast = _is_multicast(ip)) == true) {
struct ip_mreqn multiaddr;
multiaddr.imr_multiaddr.s_addr = inet_addr(ip.c_str());
multiaddr.imr_address.s_addr = htonl(INADDR_ANY);
multiaddr.imr_ifindex = 0;
setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &multiaddr, sizeof(struct sockaddr_in));
}
// check TTL
if(ttl > 0) {
//cerr << "try to set TTL to value == " << ttl << endl;
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
}
break;
}
default:
break;
}
}
Socket::Socket(int _fd, string _ip, int _port, stype _t) {
_state = STATE_EMPTY;
fd =_fd;
ip = _ip;
port = _port;
type = _t;
D( cerr << "socket: ip == " << ip << "; port == " << port << endl;)
}
Socket::~Socket() {
close(fd);
}
int Socket::poll(list<Socket *> &s, int timeout) {
struct pollfd *pfd;
ssize_t s_size = s.size();
D2(cerr << "Socket::poll()..." << endl;)
pfd = (struct pollfd *)malloc(sizeof(struct pollfd) * s_size);
memset(pfd, 0, sizeof(struct pollfd) * s_size);
int i = 0;
D2(cerr << "socket.fd == ";)
for(list<Socket *>::iterator it = s.begin(); it != s.end(); it++, i++) {
pfd[i].fd = (*it)->fd;
D2(cerr << pfd[i].fd << "; ";)
// pfd[i].events = 0xFFFF;
pfd[i].events = POLLIN;
pfd[i].revents = 0x00;
}
D2(cerr << endl;)
int p = ::poll(pfd, s_size, timeout);
i = 0;
for(list<Socket *>::iterator it = s.begin(); it != s.end(); it++, i++) {
(*it)->_state = STATE_EMPTY;
D2(cerr << "revents == " << pfd[i].revents << "; POLLIN == " << POLLIN << endl;)
if(pfd[i].revents & POLLIN) {
(*it)->_state = STATE_IN;
D2(cerr << "STATE_IN; fd == " << (*it)->fd << "; revents == " << pfd[i].revents << endl;)
}
if(pfd[i].revents & POLLHUP) {
// if(pfd[i].revents & POLLHUP || pfd[i].revents & POLLERR) {
(*it)->_state = STATE_DISCONNECT;
//D2(cerr << "STATE_DISCONNECT; fd == " << (*it)->fd << "; revents == " << pfd[i].revents << endl;)
cerr << "STATE_DISCONNECT; fd == " << (*it)->fd << "; revents == " << pfd[i].revents << endl;
}
}
free((void *)pfd);
return p;
}
void Socket::listen(int in) {
long sock_flags;
sock_flags = fcntl(fd, F_GETFL);
sock_flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, sock_flags);
int l = ::listen(fd, in);
D(cerr << "listen() == " << l << endl;)
l++;
}
Socket *Socket::accept(void) {
int _fd;
struct sockaddr_in addr;
socklen_t addr_len = 0;
long sock_flags;
Socket *s;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr_len = sizeof(struct sockaddr_in);
_fd = ::accept(fd, (struct sockaddr *)&addr, &addr_len);
if(_fd < 0)
return NULL;
sock_flags = fcntl(_fd, F_GETFL);
sock_flags |= O_NONBLOCK;
fcntl(_fd, F_SETFL, sock_flags);
D(cerr << "accept == " << _fd << "; addr_len == " << addr_len << endl;)
s = new Socket(_fd, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), type);
return s;
}
void Socket::set_so_keepalive(int val) {
int keepalive = val;
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
}
bool Socket::recv(string &rez) {
rez = "???";
char buf[1501];
int l = 0;
buf[0] = '\0';
if((l = ::recv(fd, buf, 1500, MSG_NOSIGNAL | MSG_DONTWAIT)) > 0) {
buf[l] = '\0';
rez = buf;
D(cerr << "read - ok!"<< endl;)
return true;
} else {
if(l == 0) {
rez = "";
return true;
}
}
rez = "";
return false;
}
bool Socket::send(void *data, int len) {
return (::send(fd, data, len, MSG_NOSIGNAL | MSG_DONTWAIT) > 0);
}
bool Socket::send(const string *data) {
if(::send(fd, data->c_str(), data->length(), 0) > 0)
return true;
return false;
}
bool Socket::send(const string data) {
if(::send(fd, data.c_str(), data.length(), MSG_NOSIGNAL | MSG_DONTWAIT) > 0)
return true;
return false;
}
uint16_t in_chksum(const uint16_t *addr, register uint32_t len) {
int32_t nleft = len;
const uint16_t *w = addr;
uint16_t answer;
int32_t sum = 0;
while(nleft > 1) {
sum += *w++;
nleft -= 2;
}
if(nleft == 1)
sum += htons(*(uint8_t *)w << 8);
sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* truncate to 16 bits */
return answer;
}
bool Socket::send2v(void **v_ptr, int *v_len) {
struct iovec iov[2];
int iovcnt = sizeof(iov) / sizeof(struct iovec);
iov[0].iov_base = v_ptr[0];
iov[0].iov_len = v_len[0];
iov[1].iov_base = v_ptr[1];
iov[1].iov_len = v_len[1];
if(::writev(fd, iov, iovcnt))
return true;
return false;
}
bool Socket::send3v(void **v_ptr, int *v_len) {
struct iovec iov[3];
int iovcnt = sizeof(iov) / sizeof(struct iovec);
iov[0].iov_base = v_ptr[0];
iov[0].iov_len = v_len[0];
iov[1].iov_base = v_ptr[1];
iov[1].iov_len = v_len[1];
iov[2].iov_base = v_ptr[2];
iov[2].iov_len = v_len[2];
if(::writev(fd, iov, iovcnt))
return true;
return false;
}
#ifndef _SOCKETS_H_
#define _SOCKETS_H_
#include <string>
#include <list>
#include <sys/socket.h>
using namespace std;
class TCP_Client {
public:
TCP_Client(bool enable_exception);
~TCP_Client();
void connect(string ip, string port);
void disconnect(void);
void send(const string *data, int opt = 0);
void send(const string data, int opt = 0);
void send(void *data, int len, int opt = 0);
void recv(string &r, int opt = 0);
protected:
bool ex;
int fd;
char *buf;
};
class Socket {
public:
enum stype {TYPE_TCP, TYPE_UDP};
enum state {STATE_EMPTY, STATE_IN, STATE_DISCONNECT};
Socket(string ip, int port, stype _t = TYPE_TCP, int ttl = 64);
~Socket();
bool recv(string &rez);
bool send(void *data, int len);
bool send(const string *data);
bool send(const string data);
bool send2v(void **v_ptr, int *v_len);
bool send3v(void **v_ptr, int *v_len);
static int poll(list<Socket *> &s, int timeout = -1);
void listen(int in);
Socket *accept(void);
// bool connect(void);
void set_so_keepalive(int val = 1);
inline state state_refresh(void) {
state st = _state;
_state = STATE_EMPTY;
return st;
}
int get_fd(void) { return fd;};
int fd;
string source_ip(void) {
return ip;
}
static struct in_addr mcast_from_local(void);
protected:
Socket(int _fd, string _ip, int _port, stype _t);
string ip;
int port;
stype type;
// int fd;
state _state;
int ttl;
unsigned short ip_id;
bool _is_multicast(string ip);
unsigned long ip_to_number(string ip);
bool is_multicast;
/*
struct sockaddr_ll s_ll;
struct msghdr msg;
struct udphdr udp_hdr;
struct iphdr ip_hdr;
*/
};
#endif
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "streamer.h"
#include "helpers.h"
#include "socket.h"
#include <iostream>
using namespace std;
#undef RTSP_DEBUG
//#define RTSP_DEBUG
#undef RTSP_DEBUG_2
//#define RTSP_DEBUG_2
#ifdef RTSP_DEBUG
#define D(a) a
#else
#define D(a)
#endif
#ifdef RTSP_DEBUG_2
#define D2(a) a
#else
#define D2(a)
#endif
Streamer *Streamer::_streamer = NULL;
Streamer::Streamer(const map<string, string> &_args) {
if(_streamer != NULL)
throw("can't make an another instance of streamer");
else
_streamer = this;
session = new Session();
args = _args;
audio = NULL;
session->process_audio = false;
session->audio.sample_rate = 0;
session->audio.channels = 0;
session->rtp_out.ip_custom = false;
session->rtp_out.ip_cached = 0;
session->video.fps_scale = 1;
audio_init();
video = new Video();
if(opt_present("f")) {
float fps = 0;
fps = atof(args["f"].c_str());
if(fps < 0.1)
fps = 0;
D( cout << "use fps: " << fps << endl;)
video->fps(fps);
}
rtsp_server = NULL;
connected_count = 0;
}
void Streamer::audio_init(void) {
if(audio != NULL) {
D( cerr << "delete audio" << endl;)
delete audio;
}
D( cout << "audio_enabled == " << session->process_audio << endl;)
audio = new Audio(session->process_audio, session->audio.sample_rate, session->audio.channels);
if(audio->present() && session->process_audio) {
session->process_audio = true;
session->audio.type = audio->ptype();
session->audio.sample_rate = audio->sample_rate();
session->audio.channels = audio->channels();
} else {
session->process_audio = false;
session->audio.type = -1;
session->audio.sample_rate = 0;
session->audio.channels = 0;
}
}
Streamer::~Streamer(void) {
delete video;
delete audio;
}
int Streamer::f_handler(void *ptr, RTSP_Server *rtsp_server, RTSP_Server::event event) {
Streamer *__this = (Streamer *)ptr;
return __this->handler(rtsp_server, event);
}
int Streamer::update_settings(bool apply) {
D( cerr << "update_settings" << endl;)
// check settings, normalize its, return 1 if was changed
// update settings at application if apply = 1 and parameters change isn't on-fly safe, update parameters always
#define _CAN_BE_CHANGED 11
unsigned long changes_array[2 * (_CAN_BE_CHANGED + 1)];
int changes_array_i = 2;
bool params_update = false;
// update application settings
// if(connected_count == 0) {
// don't change "on the fly" if someone already connected - like mcast clients
Parameters *params = Parameters::instance();
// multicast parameters
// - multicast ip
// new values
bool result = false;
//----------------
// frame skip, or FPS scale
int frames_skip = params->getGPValue(P_STROP_FRAMES_SKIP);
if(frames_skip < 0 || frames_skip > 0xFFFF) {
if(frames_skip < 0)
frames_skip = 0;
if(frames_skip < 0xFFFF)
frames_skip = 0xFFFF;
changes_array[changes_array_i + 0] = P_STROP_FRAMES_SKIP;
changes_array[changes_array_i + 1] = (unsigned long)frames_skip;
changes_array_i += 2;
params_update = true;
}
frames_skip += 1; // convert to fps_scale format;
if(frames_skip != session->video.fps_scale) {
if(apply)
session->video.fps_scale = frames_skip;
//cerr << "session->video.fps_scale = " << session->video.fps_scale << endl;
result = true;
}
//----------------
// transport parameters
bool transport_was_changed = false;
bool param_multicast = params->getGPValue(P_STROP_MCAST_EN);
if(param_multicast || session->rtp_out.multicast) {
// multicast/unicast
if(param_multicast != session->rtp_out.multicast) {
if(apply)
session->rtp_out.multicast = param_multicast;
transport_was_changed = true;
}
// IP
unsigned long ip = params->getGPValue(P_STROP_MCAST_IP);
bool ip_was_changed = false;
// switch custom/default IP
if((ip == 0) && session->rtp_out.ip_custom)
ip_was_changed = true;
if((ip != 0) && !session->rtp_out.ip_custom)
ip_was_changed = true;
// change of custom IP
if((ip != 0) && session->rtp_out.ip_custom)
if(ip != session->rtp_out.ip_cached)
ip_was_changed = true;
if(ip_was_changed) {
if(ip != 0) {
struct in_addr a;
uint32_t a_min = ntohl(inet_addr("224.0.0.0"));
uint32_t a_max = ntohl(inet_addr("239.255.255.255"));
if(a_min > a_max) {
uint32_t a = a_min;
a_min = a_max;
a_max = a;
}
if(ip < a_min)
ip = a_min;
if(ip > a_max)
ip = a_max;
a.s_addr = htonl(ip);
D( cerr << "multicast ip asked: " << inet_ntoa(a) << endl;)
if(apply) {
session->rtp_out.ip_cached = ip;
session->rtp_out.ip_custom = true;
session->rtp_out.ip = inet_ntoa(a);
changes_array[changes_array_i + 0] = P_STROP_MCAST_IP;
changes_array[changes_array_i + 1] = ip;
changes_array_i += 2;
}
} else {
struct in_addr a = Socket::mcast_from_local();
D( cerr << "multicast ip generated: " << inet_ntoa(a) << endl;)
if(apply) {
session->rtp_out.ip_custom = false;
session->rtp_out.ip = inet_ntoa(a);
}
}
transport_was_changed = true;
}
D( if(apply))
D( cerr << "actual multicast IP: " << session->rtp_out.ip << endl;)
// port
int port = params->getGPValue(P_STROP_MCAST_PORT);
if(port != session->rtp_out.port_video) {
if(port < 1024)
port = 1024;
if(port > 65532)
port = 65532;
if(apply) {
session->rtp_out.port_video = port;
session->rtp_out.port_audio = port + 2;
changes_array[changes_array_i + 0] = P_STROP_MCAST_PORT;
changes_array[changes_array_i + 1] = session->rtp_out.port_video;
changes_array_i += 2;
}
transport_was_changed = true;
}
// ttl
int ttl = params->getGPValue(P_STROP_MCAST_TTL);
if(ttl != atoi(session->rtp_out.ttl.c_str())) {
if(ttl < 1)
ttl = 1;
if(ttl > 15)
ttl = 15;
if(apply) {
char buf[8];
sprintf(buf, "%d", ttl);
session->rtp_out.ttl = buf;
changes_array[changes_array_i + 0] = P_STROP_MCAST_TTL;
changes_array[changes_array_i + 1] = ttl;
changes_array_i += 2;
}
transport_was_changed = true;
}
}
if(transport_was_changed)
params_update = true;
//-----------------
// audio parameters
bool audio_was_changed = false;
bool audio_proc = true;
bool f_audio_rate = false;
bool f_audio_channels = false;
// - enabled/disabled
if(params->getGPValue(P_STROP_AUDIO_EN) == 0)
audio_proc = false;
int audio_rate = params->getGPValue(P_STROP_AUDIO_RATE);
int audio_channels = params->getGPValue(P_STROP_AUDIO_CHANNEL);
if(audio_proc != session->process_audio)
audio_was_changed = true;
if(audio_rate != session->audio.sample_rate)
f_audio_rate = true;
if(audio_channels != session->audio.channels)
f_audio_channels = true;
if((audio_proc || session->process_audio) && (f_audio_rate || f_audio_channels))
audio_was_changed = true;
if(apply) {
bool audio_restarted = false;
if(audio_was_changed) {
session->process_audio = audio_proc;
session->audio.sample_rate = audio_rate;
session->audio.channels = audio_channels;
D2( cerr << "Audio was changed. Should restart it" << endl;)
audio_init();
audio_restarted = true;
// if audio enable was asked, check what soundcard really is connected
if(audio_proc) {
if(!audio->present()) {
session->process_audio = false;
changes_array[changes_array_i + 0] = P_STROP_AUDIO_EN;
changes_array[changes_array_i + 1] = 0;
changes_array_i += 2;
}
}
if(f_audio_rate) {
changes_array[changes_array_i + 0] = P_STROP_AUDIO_RATE;
changes_array[changes_array_i + 1] = session->audio.sample_rate;
changes_array_i += 2;
}
if(f_audio_channels) {
changes_array[changes_array_i + 0] = P_STROP_AUDIO_CHANNEL;
changes_array[changes_array_i + 1] = session->audio.channels;
changes_array_i += 2;
}
}
// was started before new client - must reinit audio
if(!audio_restarted && session->process_audio)
audio_init();
}
result = result || audio_was_changed || transport_was_changed;
// apply volume if audio is enabled, and volume was changed
if(session->process_audio) {
if(audio->present()) {
// check volume
long volume = audio->volume();
int audio_volume = params->getGPValue(P_AUDIO_CAPTURE_VOLUME);
// and apply it
if(audio_volume != volume) {
audio->set_volume(audio_volume);
changes_array[changes_array_i + 0] = P_AUDIO_CAPTURE_VOLUME;
changes_array[changes_array_i + 1] = audio->volume();
changes_array_i += 2;
params_update = true;
}
}
}
// update array of changes
// set frame to update
if(apply || params_update) {
changes_array[0] = FRAMEPARS_SETFRAME;
changes_array[1] = params->getGPValue(G_THIS_FRAME) + 1;
params->setPValue(changes_array, changes_array_i);
}
//------------------------------
// update current image settings
// if(apply) {
// here - create new function from where update all settings
struct video_desc_t video_desc = video->get_current_desc();
if(video_desc.valid) {
session->video.width = video_desc.width;
session->video.height = video_desc.height;
session->video.fps = video_desc.fps;
session->video.fps /= session->video.fps_scale;
}
session->video.type = video->ptype();
// }
if(result)
return 1;
return 0;
}
int Streamer::handler(RTSP_Server *rtsp_server, RTSP_Server::event event) {
static bool _play = false;
D( cerr << "event: running= " << running << " ";)
switch(event) {
case RTSP_Server::DESCRIBE: /// Update frame size, fps before starting new stream (generating SDP file)
update_settings(true);
break;
case RTSP_Server::PARAMS_WAS_CHANGED: /// Update frame size, fps before starting new stream (generating SDP file)
return (update_settings(false) || !(Parameters::instance()->daemon_enabled()));
case RTSP_Server::PLAY:
D( cerr << "==PLAY==";)
if(connected_count == 0) {
int ttl = -1;
if(session->rtp_out.multicast)
ttl = atoi(session->rtp_out.ttl.c_str());
video->Start(session->rtp_out.ip, session->rtp_out.port_video, session->video.fps_scale, ttl);
if(audio != NULL)
audio->Start(session->rtp_out.ip, session->rtp_out.port_audio, ttl);
}
connected_count++;
_play = true;
running = true;
break;
case RTSP_Server::PAUSE:
D( cerr << "PAUSE";)
connected_count--;
if(connected_count <= 0) {
video->Stop();
if(audio != NULL)
audio->Stop();
connected_count = 0;
_play = false;
running = false;
}
break;
case RTSP_Server::TEARDOWN:
D( cerr << "TEARDOWN";)
if(!running) {
D( cerr << " was not running";)
break;
}
connected_count--;
if(connected_count <= 0) {
video->Stop();
if(audio != NULL)
audio->Stop();
connected_count = 0;
_play = false;
running = false;
}
break;
case RTSP_Server::RESET:
D( cerr << "RESET";)
if(!running) {
D( cerr << " was not running";)
break;
}
video->Stop();
if(audio != NULL)
audio->Stop();
connected_count = 0;
_play = false;
running = false;
break;
/*
case RTSP_Server::IS_DAEMON_ENABLED:
D( cerr << "IS_DAEMON_ENABLED video->isDaemonEnabled(-1)=" << video->isDaemonEnabled(-1) << endl;)
return video->isDaemonEnabled(-1);
break;
*/
default:
D( cerr << "unknown == " << event;)
break;
}
D( cerr << endl;)
return 0;
}
void Streamer::Main(void) {
D( cerr << "start Main" << endl;)
string def_mcast = "232.1.1.1";
int def_port = 20020;
string def_ttl = "2";
session->rtp_out.ip_cached = 0;
session->rtp_out.ip_custom = true;
session->rtp_out.ip = "0";
session->rtp_out.port_video = def_port;
session->rtp_out.port_audio = def_port + 2;
session->rtp_out.ttl = def_ttl;
rtsp_server = NULL;
while(true) {
/// Check if the streamer is enabled, restart loop after waiting
if(!video->waitDaemonEnabled(-1)) {
sched_yield();
continue; /// may use particular bit instead of the "default" -1
}
update_settings(true);
/// Got here if is and was enabled (may use more actions instead of just "continue"
// start RTSP server
D2( cerr << "start server" << endl;)
if(rtsp_server == NULL)
rtsp_server = new RTSP_Server(Streamer::f_handler, (void *)this, session);
rtsp_server->main();
D2( cerr << "server was stopped" << endl;)
D2( cerr << "stop video" << endl;)
video->Stop();
D2( cerr << "stop audio" << endl;)
if(audio != NULL) {
audio->Stop();
// free audio resource - other app can use soundcard
D2( cerr << "delete audio" << endl;)
delete audio;
audio = NULL;
}
}
}
#ifndef __H_STREAMER__
#define __H_STREAMER__
#include <string>
#include <map>
#include "video.h"
#include "audio.h"
#include "rtsp.h"
using namespace std;
class Streamer {
public:
Streamer(const map<string, string> &args);
~Streamer();
void Main(void);
bool opt_present(string name) {
if(args.find(name) != args.end())
return true;
return false;
}
static Streamer *instance(void) {
return _streamer;
}
protected:
static Streamer *_streamer;
static int f_handler(void *ptr, RTSP_Server *rtsp_server, RTSP_Server::event event);
int handler(RTSP_Server *rtsp_server, RTSP_Server::event event);
int update_settings(bool apply = false);
map<string, string> args;
RTSP_Server *rtsp_server;
Session *session;
Audio *audio;
Video *video;
bool running;
int connected_count;
void audio_init(void);
};
#endif // __H_STREAMER__
#include "video.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <asm/elphel/c313a.h>
#include <iostream>
#include "streamer.h"
using namespace std;
#undef VIDEO_DEBUG
#undef VIDEO_DEBUG_2 // for timestamp monitoring
#undef VIDEO_DEBUG_3 // for FPS monitoring
//#define VIDEO_DEBUG
//#define VIDEO_DEBUG_2 // for timestamp monitoring
//#define VIDEO_DEBUG_3 // for FPS monitoring
#ifdef VIDEO_DEBUG
#define D(a) a
#else
#define D(a)
#endif
#ifdef VIDEO_DEBUG_2
#define D2(a) a
#else
#define D2(a)
#endif
#ifdef VIDEO_DEBUG_3
#define D3(a) a
#else
#define D3(a)
#endif
//Video *video = NULL;
#define QTABLES_INCLUDE
int fd_circbuf = 0;
int fd_jpeghead = 0; /// to get quantization tables
//int fd_fparmsall = 0;
int lastDaemonBit = DAEMON_BIT_STREAMER;
//struct framepars_all_t *frameParsAll;
//struct framepars_t *framePars;
//unsigned long *globalPars; /// parameters that are not frame-related, their changes do not initiate any actions
Video::Video(void) {
D( cerr << "Video::Video()" << endl;)
D( cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << endl;)
stream_name = "video";
params = Parameters::instance();
waitDaemonEnabled(-1); /// <0 - use default
fd_circbuf = open("/dev/circbuf", O_RDONLY);
if(fd_circbuf < 0)
throw("can't open /dev/circbuf");
buffer_length = lseek(fd_circbuf, 0, SEEK_END);
/// mmap for all the lifetime of the program, not per stream. AF
buffer_ptr = (unsigned long *)mmap(0, buffer_length, PROT_READ, MAP_SHARED, fd_circbuf, 0);
if((int)buffer_ptr == -1)
throw("Error in mmap /dev/circbuf");
buffer_ptr_s = (unsigned long *)mmap(buffer_ptr + (buffer_length >>2 ), buffer_length, PROT_READ, MAP_FIXED | MAP_SHARED, fd_circbuf, 0); /// preventing buffer rollovers
if((int)buffer_ptr_s == -1)
throw("Error in second mmap /dev/circbuf");
/// Skip several frames if it is just booted
/// May get stuck here if compressor is off, it should be enabled externally
D( cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " frame=" << params->getGPValue(G_THIS_FRAME) << " buffer_length=" << buffer_length << endl;)
while(params->getGPValue(G_THIS_FRAME) < 10) {
lseek(fd_circbuf, LSEEK_CIRC_TOWP, SEEK_END); /// get to the end of buffer
lseek(fd_circbuf, LSEEK_CIRC_WAIT, SEEK_END); /// wait frame got ready there
}
/// One more wait always to make sure compressor is actually running
lseek(fd_circbuf, LSEEK_CIRC_WAIT, SEEK_END);
lseek(fd_circbuf, LSEEK_CIRC_WAIT, SEEK_END);
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " frame=" << params->getGPValue(G_THIS_FRAME) << " buffer_length=" << buffer_length <<endl;)
fd_jpeghead = open("/dev/jpeghead", O_RDWR);
if(fd_jpeghead < 0)
throw("can't open /dev/jpeghead");
qtables_include = true;
SSRC = 12;
_ptype = 26;
rtp_socket = NULL;
rtcp_socket = NULL;
_play = false;
prev_jpeg_wp = 0;
// buffer_length = 0;
f_quality = -1;
// create thread...
init_pthread((void *)this);
D( cerr << __FILE__<< ":" << __FUNCTION__ << ":" << __LINE__ << endl;)
}
Video::~Video(void) {
cerr << "Video::~Video()" << endl;
if(fd_circbuf > 0)
close(fd_circbuf);
if(fd_jpeghead > 0)
close(fd_jpeghead);
}
/// Compressor should be turned on outside of the streamer
#define TURN_COMPRESSOR_ON 0
void Video::Start(string ip, long port, int _fps_scale, int ttl) {
D( cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << "_play=" << _play << endl;)
if(_play) {
cerr << "ERROR-->> wrong usage: Video()->Start() when already play!!!" << endl;
return;
}
//return;
// statistic
v_t_sec = 0;
v_t_usec = 0;
v_frames = 0;
// create udp socket
struct video_desc_t video_desc = get_current_desc(false);
f_width = video_desc.width;
f_height = video_desc.height;
used_width = f_width;
used_height = f_height;
// f_width = width();
// f_height = height();
fps_scale = _fps_scale;
if(fps_scale < 1)
fps_scale = 1;
fps_scale_c = 0;
/// start compressor...NOTE: Maybe it should not?
#if TURN_COMPRESSOR_ON
unsigned long write_data[4];
write_data[0] = FRAMEPARS_SETFRAME;
write_data[1] = params->getGPValue(G_THIS_FRAME) + 1;
write_data[2] = P_COMPRESSOR_RUN;
write_data[3] = COMPRESSOR_RUN_CONT;
write(fd_fparmsall, write_data, sizeof(write_data));
#endif
RTP_Stream::Start(ip, port, ttl);
}
void Video::Stop(void) {
if(!_play)
return;
//return;
RTP_Stream::Stop();
_play = false;
// destroy udp socket
prev_jpeg_wp = 0;
}
/**
* @brief check if this application is enabled (by appropriate bit in P_DAEMON_EN), if not -
* and wait until enabled (return false when enabled)
* @param daemonBit - bit number to accept control in P_DAEMON_EN parameter
* @return (after possible waiting) true if there was no waiting, false if there was waiting
*/
bool Video::waitDaemonEnabled(int daemonBit) { // <0 - use default
if((daemonBit >= 0) && (daemonBit < 32))
lastDaemonBit = daemonBit;
unsigned long this_frame = params->getGPValue(G_THIS_FRAME);
/// No semaphors, so it is possible to miss event and wait until the streamer will be re-enabled before sending message,
/// but it seems not so terrible
D(cerr << " lseek(fd_circbuf, LSEEK_DAEMON_CIRCBUF+lastDaemonBit, SEEK_END)... " << endl;)
lseek(fd_circbuf, LSEEK_DAEMON_CIRCBUF + lastDaemonBit, SEEK_END); ///
D(cerr << "...done" << endl;)
if(this_frame == params->getGPValue(G_THIS_FRAME))
return true;
return false;
}
/**
* @brief check if this application is enabled (by appropriate bit in P_DAEMON_EN)
* @param daemonBit - bit number to accept control in P_DAEMON_EN parameter
* @return (after possible waiting) true if there was no waiting, false if there was waiting
*/
bool Video::isDaemonEnabled(int daemonBit) { // <0 - use default
if((daemonBit >= 0) && (daemonBit < 32))
lastDaemonBit = daemonBit;
// return((framePars[GLOBALPARS(G_THIS_FRAME) & PARS_FRAMES_MASK].pars[P_DAEMON_EN] & (1 << lastDaemonBit)) != 0);
return((params->getFrameValue(P_DAEMON_EN) & (1 << lastDaemonBit)) != 0);
}
/**
* @brief Return (byte) pointer to valid frame 'before' current(if current is invalid - use latest,
* wait if none are ready. Restore (or modify if had to wait) file pointer.
* fill provided frame_pars with the metadata (including the time stamp)
* @param frame_pars - pointer to a interframe parameters structure
* @param before - how many frames before current pointer is needed
* @return pointer (offset in circbuf) to the frame start
*/
long Video::getFramePars(struct interframe_params_t *frame_pars, long before, long ptr_before) {
long cur_pointer, p;
long this_pointer = 0;
if(ptr_before > 0) {
/// if we need some before frame, we should set pointer to saved one (saved with before == 0)
this_pointer = lseek(fd_circbuf, ptr_before, SEEK_SET); /// restore the file pointer
}
if(ptr_before < 0) {
/// otherwise, set pointer to the actual frame
this_pointer = lseek(fd_circbuf, LSEEK_CIRC_TOWP, SEEK_END); /// byte index in circbuf of the frame start
}
if(ptr_before == 0)
this_pointer = lseek(fd_circbuf, 0, SEEK_CUR); /// save orifinal file pointer
char *char_buffer_ptr = (char *)buffer_ptr;
if(lseek(fd_circbuf, LSEEK_CIRC_VALID, SEEK_END) < 0) { /// Invalid frame - reset to the latest acquired
this_pointer = lseek(fd_circbuf, LSEEK_CIRC_LAST, SEEK_END); /// Last acquired frame (may be not yet available if none are)
}
cur_pointer = this_pointer;
if(before == 0)
lseek(fd_circbuf, LSEEK_CIRC_WAIT, SEEK_END);
while(before && (((p = lseek(fd_circbuf, LSEEK_CIRC_PREV, SEEK_END))) >= 0)) { /// try to get earlier valid frame
cur_pointer = p;
before--;
}
/// if 'before' is still >0 - not enough frames acquired, wait for more
while(before > 0) {
lseek(fd_circbuf, this_pointer, SEEK_SET);
lseek(fd_circbuf, LSEEK_CIRC_WAIT, SEEK_END);
this_pointer = lseek(fd_circbuf, LSEEK_CIRC_NEXT, SEEK_END);
before--;
}
long metadata_start = cur_pointer - 32;
if(metadata_start < 0)
metadata_start += buffer_length;
/// copy the interframe data (timestamps are not yet there)
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " before=" << before << " metadata_start=" << metadata_start << endl;)
memcpy(frame_pars, &char_buffer_ptr[metadata_start], 32);
long jpeg_len = frame_pars->frame_length; //! frame_pars->frame_length is now the length of bitstream
if(frame_pars->signffff != 0xffff) {
cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " Wrong signature in getFramePars() (broken frame), frame_pars->signffff="<< frame_pars->signffff << endl;
int i;
long * dd =(long *) frame_pars;
cerr << hex << (metadata_start/4) << ": ";
// for (i=0;i<8;i++) {
for (i=0;i<8;i++) {
cerr << hex << dd[i] << " ";
}
cerr << dec << endl;
return -1;
} else {
// cerr << hex << (metadata_start/4) << dec << endl; ///************* debug
}
/// find location of the timestamp and copy it to the frame_pars structure
///==================================
long timestamp_start = (cur_pointer) + ((jpeg_len + CCAM_MMAP_META + 3) & (~0x1f)) + 32 - CCAM_MMAP_META_SEC; //! magic shift - should index first byte of the time stamp
if(timestamp_start >= buffer_length)
timestamp_start -= buffer_length;
memcpy(&(frame_pars->timestamp_sec), &char_buffer_ptr[timestamp_start], 8);
if(ptr_before == 0)
lseek(fd_circbuf, this_pointer, SEEK_SET); /// restore the file pointer
//D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " this_pointer=" << this_pointer << " cur_pointer=" << cur_pointer << endl;)
return cur_pointer;
}
/// In the next function I assume that the frame pointed by current file pointer in circbuf is ready. Otherwise
/// (if it points at next frame to be acquired) we need to increase argument of getValidFrame(long before) by 1
/// get all parameters together
#define FRAMEPARS_BEFORE 0 /// Change to 1 if frames are not yet ready when these functions are called
struct video_desc_t Video::get_current_desc(bool with_fps) {
struct interframe_params_t frame_pars, prev_pars;
struct video_desc_t video_desc;
video_desc.valid = false;
long ptr = -1;
if((ptr = getFramePars(&frame_pars, FRAMEPARS_BEFORE, -1)) < 0) {
return video_desc;
} else {
if(with_fps) {
if(getFramePars(&prev_pars, FRAMEPARS_BEFORE + 1, ptr) < 0)
return video_desc;
double fps = (frame_pars.timestamp_sec - prev_pars.timestamp_sec);
fps *= 1000000.0;
fps += frame_pars.timestamp_usec;
fps -= prev_pars.timestamp_usec;
D3( float _f = fps;)
fps = 1000000.0 / fps;
video_desc.fps = (used_fps = fps);
D( cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " fps=" << fps << endl;)
// cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " fps=" << video_desc.fps << endl;
D3(if(_f == 0))
D3(cerr << "delta == " << _f << endl << endl;)
}
}
video_desc.valid = true;
// video_desc.width = (used_width = frame_pars.width);
// video_desc.height = (used_height = frame_pars.height);
video_desc.width = frame_pars.width;
video_desc.height = frame_pars.height;
video_desc.quality = frame_pars.quality2;
return video_desc;
}
//#define FRAMES_AHEAD_FPS 3 /// number of frames ahead of current to frite FPS limit
//#define FRAMES_SKIP_FPS 3 /// number of frames to wait after target so circbuf will have at least 2 frames with new fps for calculation
void Video::fps(float fps) {
if(fps < 0.01)
return;
/// currently limiting FPS only works with free running TODO: Add external trigger frequency support.
unsigned long write_data[6];
long target_frame = params->getGPValue(G_THIS_FRAME) + FRAMES_AHEAD_FPS;
write_data[0] = FRAMEPARS_SETFRAME;
write_data[1] = target_frame; /// wait then for that frame to be available on the output plus 2 frames for fps to be stable
write_data[2] = P_FP1000SLIM;
write_data[3] = (unsigned long)fps * 1000;
write_data[4] = P_FPSFLAGS;
write_data[5] = 3;
// long rslt = write(fd_fparmsall, write_data, sizeof(write_data));
int rslt = params->write(write_data, sizeof(write_data));
if(rslt == sizeof(write_data)) { /// written OK
// lseek(fd_fparmsall, LSEEK_FRAME_WAIT_ABS + target_frame + FRAMES_SKIP_FPS, SEEK_END); /// skip frames
params->lseek(LSEEK_FRAME_WAIT_ABS + target_frame + FRAMES_SKIP_FPS, SEEK_END); /// skip frames
}
}
#define USE_REAL_OLD_TIMESTAMP 0
long Video::capture(void) {
long frame_len;
struct interframe_params_t frame_pars;
// long len;
int quality;
unsigned long latestAvailableFrame_ptr;
unsigned long frameStartByteIndex;
int before;
///Make sure the streamer is not disabled through the bit in P_DAEMON_EN
// if((framePars[pars->getGPValue(G_THIS_FRAME) & PARS_FRAMES_MASK].pars[P_DAEMON_EN] & (1 << lastDaemonBit)) == 0) {
if((params->getFrameValue(P_DAEMON_EN) & (1 << lastDaemonBit)) == 0) {
return -DAEMON_DISABLED; /// return exception (will stop the stream)
}
frameStartByteIndex = lseek(fd_circbuf, LSEEK_CIRC_TOWP, SEEK_END); /// byte index in circbuf of the frame start
latestAvailableFrame_ptr = frameStartByteIndex;
lseek(fd_circbuf, LSEEK_CIRC_WAIT, SEEK_END);
frame_ptr = (char *)((unsigned long)buffer_ptr + latestAvailableFrame_ptr);
//fprintf(stderr, "frame_ptr == %08X; ", frame_ptr);
if(latestAvailableFrame_ptr < 32)
latestAvailableFrame_ptr += buffer_length;
latestAvailableFrame_ptr >>= 2;
frame_len = buffer_ptr[latestAvailableFrame_ptr - 1];
// read timestamp
char *ts_ptr = (char *)((unsigned long)frame_ptr + (long)(((frame_len + CCAM_MMAP_META + 3) & (~0x1f)) + 32 - CCAM_MMAP_META_SEC));
unsigned long t[2];
memcpy(&t, (void *)ts_ptr, 8);
f_tv.tv_sec = t[0];
f_tv.tv_usec = t[1];
// read Q value
char *meta = (char *)frame_ptr;
meta -= 32;
if(meta < (char *)buffer_ptr)
meta += buffer_length;
struct interframe_params_t *fp = (struct interframe_params_t *)meta;
/// See if the frame parameters are the same as used when starting the stream,
/// Otherwise check for up to G_SKIP_DIFF_FRAME older frames and return them instead,
/// If that number is exceeded - return exception
/// Each time the latest acquired frame is considered, so we do not need to save frmae poointer additionally
if((fp->width != used_width) || (fp->height != used_height)) {
for(before = 1; before <= (int)params->getGPValue(G_SKIP_DIFF_FRAME); before++) {
if(((frameStartByteIndex = getFramePars(&frame_pars, before))) && (frame_pars.width == used_width) && (frame_pars.height == used_height)) {
/// substitute older frame instead of the latest one. Leave wrong timestamp?
/// copying code above (may need some cleanup). Maybe - just move earlier so there will be no code duplication?
latestAvailableFrame_ptr = frameStartByteIndex;
frame_ptr = (char *)((unsigned long)buffer_ptr + latestAvailableFrame_ptr);
if(latestAvailableFrame_ptr < 32)
latestAvailableFrame_ptr += buffer_length;
latestAvailableFrame_ptr >>= 2;
frame_len = buffer_ptr[latestAvailableFrame_ptr - 1];
#if USE_REAL_OLD_TIMESTAMP
/// read timestamp
ts_ptr = (char *)((unsigned long)frame_ptr + (long)(((frame_len + CCAM_MMAP_META + 3) & (~0x1f)) + 32 - CCAM_MMAP_META_SEC));
memcpy(&t, (void *)ts_ptr, 8);
f_tv.tv_sec = t[0];
f_tv.tv_usec = t[1];
#endif
//cerr << "skip frame: before == " << before << endl;
//cerr << "used_width == " << used_width << "; current_width == " << frame_pars.width << endl;
/// update interframe data pointer
// char *meta = (char *)frame_ptr;
meta = (char *)frame_ptr;
meta -= 32;
if(meta < (char *)buffer_ptr)
meta += buffer_length;
fp = (struct interframe_params_t *)meta;
break;
}
}
if(before > (int) params->getGPValue(G_SKIP_DIFF_FRAME)) {
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__<< " Killing stream because of frame size change " << endl;)
return -SIZE_CHANGE; /// It seems that frame size is changed for good, need to restart the stream
}
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__<< " Waiting for the original frame size to be restored , using " << before << " frames ago" << endl;)
}
///long Video::getFramePars(struct interframe_params_t * frame_pars, long before) {
///getGPValue(unsigned long GPNumber)
quality = fp->quality2;
if(qtables_include && quality != f_quality) {
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__<< " Updating quality tables, new quality is " << quality << endl;)
lseek(fd_jpeghead, frameStartByteIndex | 2, SEEK_END); /// '||2' indicates that we need just quantization tables, not full JPEG header
read(fd_jpeghead, (void *)&qtable[0], 128);
}
f_quality = quality;
/*
// check statistic
static bool first = true;
if(first) {
struct timeval tv;
gettimeofday(&tv, NULL);
first = false;
fprintf(stderr, "VIDEO first with time: %d:%06d at: %d:%06d\n", f_tv.tv_sec, f_tv.tv_usec, tv.tv_sec, tv.tv_usec);
}
*/
return frame_len;
}
long Video::process(void) {
//D(cerr << "< ";)
int _plen = 1400;
int to_send = _plen;
int _qtables_len = 128 + 4;
long frame_len = capture();
if(frame_len == 0) {
//D(cerr << "[";)
// return false;
return 0; /// now never here
} else {
if(frame_len < 0) {
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__<< "capture returned negative" << frame_len << endl;)
// return false;
return frame_len; /// attention (restart) is needed
}
}
// check FPS decimation
bool to_skip = true;
if(fps_scale_c == 0)
to_skip = false;
fps_scale_c++;
if(fps_scale_c >= fps_scale)
fps_scale_c = 0;
//cerr << "fps_scale == " << fps_scale << "; fps_scale_c == " << fps_scale_c << "; to_skip == " << to_skip << endl;
if(to_skip)
return 1;
int to_send_len = frame_len;
unsigned char h[20 + 4];
int packet_len = 0;
unsigned char *data = (unsigned char *)frame_ptr;
uint64_t t = f_tv.tv_sec;
t *= 90000;
t &= 0x00FFFFFFFF;
timestamp = t;
double f = f_tv.tv_usec;
f /= 1000000.0;
f *= 90000.0;
timestamp += (uint32_t)f;
uint32_t ts;
ts = timestamp;
ts = htonl(ts);
long offset = 0;
void *v_ptr[4];
int v_len[4] = {0, 0, 0, 0};
bool first = true;
while(to_send_len && _play) {
unsigned long pnum = htons(packet_num);
bool last = false;
to_send = _plen;
if(qtables_include && first)
to_send = _plen - _qtables_len;
if(to_send_len <= to_send) {
packet_len = to_send_len;
to_send_len = 0;
last = true;
} else {
packet_len = to_send;
to_send_len -= to_send;
}
// make RTP packet
h[0] = 0x80;
if(!last)
h[1] = _ptype;
else
h[1] = 0x80 + _ptype;
memcpy((void *)&h[2], (void *)&pnum, 2);
memcpy((void *)&h[4], (void *)&ts, 4);
memcpy((void *)&h[8], (void *)&SSRC, 4);
// make MJPEG header
unsigned long off = htonl(offset);
memcpy((void *)&h[12], (void *)&off, 4);
h[12] = 0x00;
h[16] = 0x01;
unsigned int q = f_quality;
if(qtables_include)
q += 128;
h[17] = (unsigned char)(q & 0xFF);
if(f_width <= 2040)
h[18] = (f_width / 8) & 0xFF;
else
h[18] = 0;
if(f_height <= 2040)
h[19] = (f_height / 8) & 0xFF;
else
h[19] = 0;
h[20] = 0;
h[21] = 0;
unsigned short l = htons(128);
memcpy((void *)&h[22], (void *)&l, 2);
// update RTCP statistic
rtp_packets++;
rtp_octets += packet_len + 8; // data + MJPEG header
// send vector
if(first) {
v_ptr[0] = h;
if(qtables_include) {
v_len[0] = 24;
v_ptr[1] = qtable;
v_len[1] = 128;
v_ptr[2] = data;
v_len[2] = packet_len;
rtp_socket->send3v(&v_ptr[0], &v_len[0]);
} else {
v_len[0] = 20;
v_ptr[1] = data;
v_len[1] = packet_len;
rtp_socket->send2v(&v_ptr[0], &v_len[0]);
}
first = false;
} else {
v_ptr[0] = h;
v_len[0] = 20;
v_ptr[1] = data;
v_len[1] = packet_len;
rtp_socket->send2v(&v_ptr[0], &v_len[0]);
}
// --==--
packet_num++;
data += packet_len;
offset += packet_len;
}
//D(cerr << "]";)
// return true;
return 1;
}
#ifndef _VIDEO__H_
#define _VIDEO__H_
#include <string>
#include "rtp_stream.h"
#include "parameters.h"
using namespace std;
#include <asm/elphel/c313a.h>
#define FRAMES_AHEAD_FPS 3 /// number of frames ahead of current to frite FPS limit
#define FRAMES_SKIP_FPS 3 /// number of frames to wait after target so circbuf will have at least 2 frames with new fps for calculation
/// structure to store current video description
struct video_desc_t {
bool valid;
int width;
int height;
int quality;
float fps;
};
class Video : public RTP_Stream {
public:
enum vevent {
VEVENT0,
DAEMON_DISABLED,
FPS_CHANGE,
SIZE_CHANGE
};
Video(void);
virtual ~Video(void);
/// return description of the current frame - i.e. current video parameters
struct video_desc_t get_current_desc(bool with_fps = true);
void fps(float);
void Start(string ip, long port, int fps_scale, int ttl = -1);
void Stop(void);
Parameters *params;
/// Using Video class to interface global camera parameters
bool waitDaemonEnabled(int daemonBit); // <0 - use default
bool isDaemonEnabled(int daemonBit); // <0 - use default
protected:
long getFramePars(struct interframe_params_t * frame_pars, long before, long ptr_before = 0);
unsigned long prev_jpeg_wp;
// frame params
int f_width;
int f_height;
int f_quality;
bool qtables_include;
unsigned char qtable[128];
// struct timeval f_tv;
long buffer_length;
unsigned long *buffer_ptr;
unsigned long *buffer_ptr_s; /// Second copy of the circbuf just after the end of the first to prevent rollovers
void *frame_ptr;
long capture(void);
// bool process(void);
long process(void);
// for statistic
long v_t_sec;
long v_t_usec;
int v_frames;
unsigned long used_width; ///frame width reported by Video::width(), used as the stream width
unsigned long used_height; /// similar to above
float used_fps; /// similar to above
int fps_scale;
int fps_scale_c; // counter for fps_scale
};
//extern Video *video;
#endif // _VIDEO__H_
#!/usr/bin/env python
# encoding: utf-8
from __future__ import division
from __future__ import print_function
"""
# @file used_files.py
# @brief Extract file access data after build, modify CDT project configuration
# (.cproject) accordingly
# @copyright Copyright (C) 2016, Elphel.inc.
# @param <b>License</b>
# 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/>.
@author: Andrey Filippov
@license: GPLv3.0+
@contact: andrey@elphel.coml
@deffield updated: Updated
"""
__author__ = "Andrey Filippov"
__copyright__ = "Copyright 2016, Elphel, Inc."
__license__ = "GPL"
__version__ = "3.0+"
__maintainer__ = "Andrey Filippov"
__email__ = "andrey@elphel.com"
__status__ = "Development"
import sys
import os
import time
import xml.etree.ElementTree as ET
'''
TODO:Automate, find out why separate touch commands are needed
Run this program twice:
1-st run ./used_files.py linux -1
and save shown timestamp
Then run (some mystery here)
touch src/drivers/ata/ahci_elphel.c
touch src/drivers/elphel/sensor_common.c
Wait 5 seconds and run (in a different console with appropriate sourcing)
bitbake linux-xlnx -c compile -f
Then again
./used_files.py linux <timestamp_from_the_first_run>
If somethong went wrong you will need to resore .cproject from eclipse_project_setup directory
For php:
bitbake php -c cleansstate
bitbake php -c unpack -f
bitbake php -c configure -f
./used_files.py php -1
bitbake php -c compile -f
./used_files.py php 1471044836.8
Doing:
bitbake php -c compile -f
./used_files.py php -1
bitbake php -c compile -f
./used_files.py php 1471044836.8
Corrupts make process
'''
def file_tree(flist): # Each file in list is a file, no directories
ftree={}
for p in flist:
node = ftree
seg_list=p.split(os.sep)
last_i=len(seg_list)-1
for i,segm in enumerate(seg_list):
if not segm in node:
if i == last_i:
node[segm] = None
else:
node[segm] = {}
node=node[segm]
return ftree
def exclude_list(ftree, flist):
mark = "*" # no file/dir name can be "*"
def list_tree_recursive(root):
rslt = []
if not mark in root:
return [[""]] # convert to trailing "/" for directories
for n in root:
if not n == mark:
if root[n] is None:
rslt.append([n])
else:
for l in list_tree_recursive(root[n]):
rslt.append([n]+l)
return rslt
ftree[mark]=None # mark top level dir
for p in flist:
node = ftree
for segm in p.split(os.sep)[:-1]:
node=node[segm]
node[mark]=None # [mark] means used in flist
del node[p.split(os.sep)[-1]]
#print (ftree)
# for k in ftree:
# print(k)
#Now prune unused directories
#prune_recursive(ftree) # (assuming root is used)
# now create list
files_list_list = list_tree_recursive(ftree)
# print (files_list_list)
#converrt to file paths
pl = []
for l in files_list_list:
pl.append(os.path.join(*(l[1:])))
pl = sorted (pl)
return pl
def proc_tree():
DEBUG = True
extensions = [".h",".c",".cpp"]
exclude_start = ["linux"+os.sep+"scripts"+os.sep,"linux"+os.sep+"source"+os.sep+"scripts"+os.sep]
delta_t = 3 # seconds
try:
root_path = sys.argv[1]
except:
print ("Calling %s <root directory path> [timestamp]"%(os.path.basename(sys.argv[0])))
try:
start_time = float(sys.argv[2])
except:
start_time = 0.0
touch_files= start_time < 0.0
print ("root_path = %s"%(root_path))
# root_path = "/home/eyesis/git/poky/linux-elphel/linux/"
lstFiles = []
# Append files to a list
for path, _, files in os.walk(root_path, followlinks = True):
for f in files:
for ext in extensions:
if f.endswith(ext):
lstFiles.append(os.path.join(path, f))
break
all_tree= file_tree(sorted(lstFiles))
include_lst=[]
lst_a = []
latest_at=0
for p in lstFiles:
if touch_files:
if os.path.islink(p):
try:
os.utime(os.path.realpath(p), None)
except:
print("missing linked file: %s"%(os.path.realpath(p)))
else:
os.utime(p, None)
else:
# at = time.ctime(os.stat(p).st_atime)
try:
at = os.stat(p).st_atime
l = None
except:
at = 0
if os.path.islink(p):
try:
l = os.path.realpath(p)
at = os.stat(l).st_atime
except:
at = 0 # missing file
latest_at = max((latest_at,at))
if at > (start_time + delta_t):
#Scripts/lexers result in problems
exclude=False
for exStr in exclude_start:
if p.startswith(exStr):
exclude=True
break
if exclude:
break
#exclude_start
lst_a.append([p,at,l])
include_lst.append(p)
if touch_files:
print (len(lstFiles), "last time = ", time.time())
return
excluding = exclude_list(all_tree, include_lst)
# print (all_tree)
# print (sorted(include_lst))
# print ("|".join(excluding))
if DEBUG:
with open("all_sources.lst","w" ) as f:
for p in sorted(lstFiles):
try:
at = os.stat(p).st_atime
except:
at = 0
lnk=""
if os.path.islink(p):
try:
at = os.stat(os.path.realpath(p)).st_atime
except:
at = 0
lnk = os.path.realpath(p)
print (p,at,lnk, file=f)
with open("excluding.lst","w" ) as f:
for p in excluding:
print (p, file=f)
with open("including.lst","w" ) as f:
for p in include_lst:
print (p, file=f)
# include_tree= file_tree(sorted(include_lst))
# print(include_tree)
root_dir=include_lst[0].split(os.sep)[0]
print ("root_dir=",root_dir)
xml= ET.parse(".cproject")
root=xml.getroot()
# for child in root:
# print(child.tag, child.attrib)
for child in root.iter('sourceEntries'):
for gchild in child:
print(gchild.tag)
for child in root.iter('sourceEntries'):
for gchild in child:
if gchild.tag == 'entry':
attr = gchild.attrib
try:
if (attr['kind'] == 'sourcePath') and (attr['name'] == root_dir):
child.remove (gchild)
print ("Removed existing entry ",gchild.tag)
break
except:
print ("error matching attributes for ",gchild.tag)
pass
break #after first 'sourceEntries' - should be just one?
ET.SubElement(child, 'entry', {"flags":"VALUE_WORKSPACE_PATH", "kind":"sourcePath", "name":root_dir, "excluding":"|".join(excluding)})
for child in root.iter('sourceEntries'):
for gchild in child:
print(gchild.tag)
oneliner= ET.tostring(root)
#overwrites original .cproject, may change to somethong different
with open(".cproject", "wr") as f:
f.write("""<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?>""")
f.write(oneliner)
print (len(lstFiles), len(lst_a), "last access time = ",latest_at)
if __name__ == '__main__':
proc_tree()
"""
make clean # otherwise compiled files are preserved
bitbake apps-autoexposure -c cleansstate
bitbake apps-autoexposure -c unpack -f
bitbake apps-autoexposure -c configure -f
./used_files.py sysroots -1
bitbake apps-autoexposure -c compile -f
./used_files.py sysroots 1473297567.42
eyesis@eyesis-SH87R:~/git/elphel393/rootfs-elphel/elphel-apps-autoexposure$ ./used_files.py sysroots/elphel393/usr -1
root_path = sysroots/elphel393/usr
5615 last time = 1473300068.01
eyesis@eyesis-SH87R:~/git/elphel393/rootfs-elphel/elphel-apps-autoexposure$ ./used_files.py sysroots/elphel393/usr 1473300068.01
root_path = sysroots/elphel393/usr
root_dir= sysroots
entry
entry
entry
entry
entry
5615 84 last access time = 1473300080.1
"""
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment