Initial commit, with basic functionality.
This commit is contained in:
commit
c9eda8ac15
|
@ -0,0 +1,11 @@
|
||||||
|
*.swp
|
||||||
|
build
|
||||||
|
debug
|
||||||
|
obj-*
|
||||||
|
debian/files
|
||||||
|
debian/moonfire-nvr.debhelper.log
|
||||||
|
debian/moonfire-nvr.postinst.debhelper
|
||||||
|
debian/moonfire-nvr.postrm.debhelper
|
||||||
|
debian/moonfire-nvr.prerm.debhelper
|
||||||
|
debian/moonfire-nvr.substvars
|
||||||
|
debian/moonfire-nvr/
|
|
@ -0,0 +1,119 @@
|
||||||
|
# This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
# Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
#
|
||||||
|
# In addition, as a special exception, the copyright holders give
|
||||||
|
# permission to link the code of portions of this program with the
|
||||||
|
# OpenSSL library under certain conditions as described in each
|
||||||
|
# individual source file, and distribute linked combinations including
|
||||||
|
# the two.
|
||||||
|
#
|
||||||
|
# You must obey the GNU General Public License in all respects for all
|
||||||
|
# of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
# exception, you may extend this exception to your version of the
|
||||||
|
# file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
# so, delete this exception statement from your version. If you delete
|
||||||
|
# this exception statement from all source files in the program, then
|
||||||
|
# also delete it here.
|
||||||
|
#
|
||||||
|
# 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/>.
|
||||||
|
#
|
||||||
|
# CMakeLists.txt: top-level definitions for building Moonfire NVR.
|
||||||
|
|
||||||
|
cmake_minimum_required(VERSION 3.0.2)
|
||||||
|
project(moonfire-nvr)
|
||||||
|
|
||||||
|
if(CMAKE_VERSION VERSION_LESS "3.1")
|
||||||
|
set(CMAKE_CXX_FLAGS "--std=c++11 ${CMAKE_CXX_FLAGS}")
|
||||||
|
else()
|
||||||
|
set(CMAKE_CXX_STANDARD 11)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_CXX_FLAGS "-Wall -Werror -pedantic-errors ${CMAKE_CXX_FLAGS}")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Dependencies.
|
||||||
|
#
|
||||||
|
|
||||||
|
# https://cmake.org/cmake/help/v3.0/module/FindProtobuf.html
|
||||||
|
find_package(Protobuf REQUIRED)
|
||||||
|
|
||||||
|
# https://gflags.github.io/gflags/#cmake mentions a cmake module, but at
|
||||||
|
# least on Ubuntu 15.10, libgflags-dev does not include it. There's no
|
||||||
|
# pkgconfig either. Do this by hand.
|
||||||
|
find_library(GFLAGS_LIBRARIES gflags)
|
||||||
|
find_library(RE2_LIBRARIES re2)
|
||||||
|
find_library(PROFILER_LIBRARIES profiler)
|
||||||
|
|
||||||
|
# https://cmake.org/cmake/help/v3.0/module/FindPkgConfig.html
|
||||||
|
find_package(PkgConfig)
|
||||||
|
pkg_check_modules(FFMPEG REQUIRED libavutil libavcodec libavformat)
|
||||||
|
pkg_check_modules(LIBEVENT REQUIRED libevent)
|
||||||
|
pkg_check_modules(GLOG REQUIRED libglog)
|
||||||
|
|
||||||
|
# Check if ffmpeg support "stimeout".
|
||||||
|
set(CMAKE_REQUIRED_INCLUDES ${FFMPEG_INCLUDES})
|
||||||
|
set(CMAKE_REQUIRED_LIBRARIES ${FFMPEG_LIBRARIES})
|
||||||
|
include(CheckCSourceRuns)
|
||||||
|
check_c_source_runs([[
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <libavutil/opt.h>
|
||||||
|
#include <libavformat/avformat.h>
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
av_register_all();
|
||||||
|
AVInputFormat *input = av_find_input_format("rtsp");
|
||||||
|
const AVClass *klass = input->priv_class;
|
||||||
|
const AVOption *opt =
|
||||||
|
av_opt_find2(&klass, "stimeout", NULL, 0, AV_OPT_SEARCH_FAKE_OBJ, NULL);
|
||||||
|
return (opt != NULL) ? EXIT_SUCCESS : EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
]] HAVE_STIMEOUT)
|
||||||
|
if(NOT HAVE_STIMEOUT)
|
||||||
|
message(WARNING [[
|
||||||
|
Your libavformat library lacks support for the "stimeout" rtsp option.
|
||||||
|
Moonfire NVR will not be able to detect network partitions or retry.
|
||||||
|
Consider installing a recent ffmpeg, from source if necessary.
|
||||||
|
]])
|
||||||
|
else()
|
||||||
|
message(STATUS "libavformat library has support for \"stimeout\" - good.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
enable_testing()
|
||||||
|
|
||||||
|
# http://www.kaizou.org/2014/11/gtest-cmake/
|
||||||
|
find_package(Threads REQUIRED)
|
||||||
|
include(ExternalProject)
|
||||||
|
ExternalProject_Add(
|
||||||
|
GMockProject
|
||||||
|
URL "https://googlemock.googlecode.com/files/gmock-1.7.0.zip"
|
||||||
|
URL_HASH "SHA1=f9d9dd882a25f4069ed9ee48e70aff1b53e3c5a5"
|
||||||
|
INSTALL_COMMAND "")
|
||||||
|
ExternalProject_Get_Property(GMockProject source_dir binary_dir)
|
||||||
|
set(GTest_INCLUDE_DIR ${source_dir}/gtest/include)
|
||||||
|
add_library(GTest STATIC IMPORTED)
|
||||||
|
add_dependencies(GTest GMockProject)
|
||||||
|
set_target_properties(GTest PROPERTIES
|
||||||
|
IMPORTED_LOCATION "${binary_dir}/gtest/${CMAKE_STATIC_LIBRARY_PREFIX}gtest${CMAKE_STATIC_LIBRARY_SUFFIX}"
|
||||||
|
IMPORTED_LINK_INTERFACE_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
|
||||||
|
set(GMock_INCLUDE_DIR ${source_dir}/include)
|
||||||
|
add_library(GMock STATIC IMPORTED)
|
||||||
|
add_dependencies(GMock GMockProject)
|
||||||
|
set_target_properties(GMock PROPERTIES
|
||||||
|
IMPORTED_LOCATION "${binary_dir}/${CMAKE_STATIC_LIBRARY_PREFIX}gmock${CMAKE_STATIC_LIBRARY_SUFFIX}"
|
||||||
|
IMPORTED_LINK_INTERFACE_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
|
||||||
|
|
||||||
|
#
|
||||||
|
# Subdirectories.
|
||||||
|
#
|
||||||
|
|
||||||
|
add_subdirectory(src)
|
|
@ -0,0 +1,674 @@
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -0,0 +1,267 @@
|
||||||
|
# Introduction
|
||||||
|
|
||||||
|
Moonfire NVR is an open-source security camera network video recorder, started
|
||||||
|
by Scott Lamb <slamb@slamb.org>. Currently it is basic: it saves
|
||||||
|
H.264-over-RTSP streams from IP cameras to disk as .mp4 files and provides a
|
||||||
|
simple HTTP interface for listing and viewing fixed-length segments of video.
|
||||||
|
It does not decode, analyze, or re-encode video frames, so it requires little
|
||||||
|
CPU. It handles six 720p/15fps streams on a [Raspberry Pi
|
||||||
|
2](https://www.raspberrypi.org/products/raspberry-pi-2-model-b/), using roughly
|
||||||
|
5% of the machine's total CPU.
|
||||||
|
|
||||||
|
This is version 0.1, the initial release. Until version 1.0, there will be no
|
||||||
|
compatibility guarantees: configuration and storage formats may change from
|
||||||
|
version to version.
|
||||||
|
|
||||||
|
I hope to add features such as salient motion detection. It's way too early to
|
||||||
|
make promises, but it seems possible to build a full-featured
|
||||||
|
hobbyist-oriented multi-camera NVR that requires nothing but a cheap machine
|
||||||
|
with a big hard drive. I welcome help; see [Getting help and getting
|
||||||
|
involved](#help) below. There are many exciting techniques we could use to
|
||||||
|
make this possible:
|
||||||
|
|
||||||
|
* avoiding CPU-intensive H.264 encoding in favor of simply continuing to use the
|
||||||
|
camera's already-encoded video streams. Cheap IP cameras these days provide
|
||||||
|
pre-encoded H.264 streams in both "main" (full-sized) and "sub" (lower
|
||||||
|
resolution, compression quality, and/or frame rate) varieties. The "sub"
|
||||||
|
stream is more suitable for fast computer vision work as well as
|
||||||
|
remote/mobile streaming. Disk space these days is quite cheap (with 3 TB
|
||||||
|
drives costing about $100), so we can afford to keep many camera-months of
|
||||||
|
both streams on disk.
|
||||||
|
* decoding and analyzing only select "key" video frames (see
|
||||||
|
[wikipedia](https://en.wikipedia.org/wiki/Video_compression_picture_types).
|
||||||
|
* off-loading expensive work to a GPU. Even the Raspberry Pi has a
|
||||||
|
surprisingly powerful GPU.
|
||||||
|
* using [HTTP Live Streaming](https://en.wikipedia.org/wiki/HTTP_Live_Streaming)
|
||||||
|
rather than requiring custom browser plug-ins.
|
||||||
|
* taking advantage of cameras' built-in motion detection. This is
|
||||||
|
the most obvious way to reduce motion detection CPU. It's a last resort
|
||||||
|
because these cheap cameras' proprietary algorithms are awful compared to
|
||||||
|
those described on [changedetection.net](http://changedetection.net).
|
||||||
|
Cameras have high false-positive and false-negative rates, are hard to
|
||||||
|
experiment with (as opposed to rerunning against saved video files), and
|
||||||
|
don't provide any information beyond if motion exceeded the threshold or
|
||||||
|
not.
|
||||||
|
|
||||||
|
# Downloading
|
||||||
|
|
||||||
|
See the [github page](https://github.com/scottlamb/moonfire-nvr) (in case
|
||||||
|
you're not reading this text there already). You can download the bleeding
|
||||||
|
edge version from the commandline via git:
|
||||||
|
|
||||||
|
$ git clone https://github.com/scottlamb/moonfire-nvr.git
|
||||||
|
|
||||||
|
# Building from source
|
||||||
|
|
||||||
|
There are no binary packages of Moonfire NVR available yet, so it must be built
|
||||||
|
from source. It requires several packages to build:
|
||||||
|
|
||||||
|
* [CMake](https://cmake.org/) version 3.1.0 or higher.
|
||||||
|
* a C++11 compiler, such as [gcc](https://gcc.gnu.org/) 4.7 or higher.
|
||||||
|
* [ffmpeg](http://ffmpeg.org/), including `libavutil`,
|
||||||
|
`libavcodec` (to inspect H.264 frames), and `libavformat` (to connect to RTSP
|
||||||
|
servers and write `.mp4` files). Note ffmpeg versions older than 55.1.101,
|
||||||
|
along with all versions of the competing project [libav](http://libav.org),
|
||||||
|
does not support socket timeouts for RTSP. For reliable reconnections on
|
||||||
|
error, it's strongly recommended to use ffmpeg >= 55.1.101.
|
||||||
|
* [libevent](http://libevent.org/) 2.x, for the built-in HTTP server.
|
||||||
|
(This might be replaced with the more full-featured
|
||||||
|
[nghttp2](https://github.com/tatsuhiro-t/nghttp2) in the future.)
|
||||||
|
* [protocol buffers](https://developers.google.com/protocol-buffers/),
|
||||||
|
currently just for the configuration file.
|
||||||
|
* [gflags](http://gflags.github.io/gflags/), for commandline flag parsing.
|
||||||
|
* [glog](https://github.com/google/glog), for debug logging.
|
||||||
|
* [gperftools](https://github.com/gperftools/gperftools), for debugging.
|
||||||
|
* [googletest](https://github.com/google/googletest), for automated testing.
|
||||||
|
This will be automatically downloaded during the build process, so it's
|
||||||
|
not necessary to install it beforehand.
|
||||||
|
* [re2](https://github.com/google/re2), for parsing with regular expressions.
|
||||||
|
|
||||||
|
On Ubuntu 15.10 or Raspbian Jessie, the following command will install all
|
||||||
|
pre-requisites (see also the `Build-Depends` field in `debian/control`):
|
||||||
|
|
||||||
|
$ sudo apt-get install \
|
||||||
|
build-essential \
|
||||||
|
cmake \
|
||||||
|
libprotobuf-dev \
|
||||||
|
libavcodec-dev \
|
||||||
|
libavformat-dev \
|
||||||
|
libavutil-dev \
|
||||||
|
libevent-dev \
|
||||||
|
libgflags-dev \
|
||||||
|
libgoogle-glog-dev \
|
||||||
|
libgoogle-perftools-dev \
|
||||||
|
libre2-dev \
|
||||||
|
pkgconf \
|
||||||
|
protobuf-compiler
|
||||||
|
|
||||||
|
Once prerequisites are installed, Moonfire NVR can be built as follows:
|
||||||
|
|
||||||
|
$ mkdir build
|
||||||
|
$ cd build
|
||||||
|
$ cmake ..
|
||||||
|
$ make
|
||||||
|
$ sudo make install
|
||||||
|
|
||||||
|
Alternatively, you can prepare a `.deb` package:
|
||||||
|
|
||||||
|
$ sudo apt-get install devscripts dh-systemd
|
||||||
|
$ debuild -us -uc
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
|
||||||
|
Moonfire NVR expects a configuration file `/etc/moonfire_nvr.conf` (overridable
|
||||||
|
with the `--config` argument). Currently this file should contain a
|
||||||
|
text-format `moonfire_nvr.Config` protocol buffer message; see
|
||||||
|
`src/config.protodevel` which describes the meaning of fields. The general
|
||||||
|
syntax is as in the example below: `field: value` for simple fields, or
|
||||||
|
(`field < ... >`) for "message" fields. It supports line-based comments
|
||||||
|
starting with #.
|
||||||
|
|
||||||
|
base_path: "/var/lib/moonfire_nvr"
|
||||||
|
rotate_sec: 600
|
||||||
|
http_port: 8080
|
||||||
|
|
||||||
|
camera <
|
||||||
|
short_name: "back_west"
|
||||||
|
host: "192.168.1.101:554"
|
||||||
|
user: "admin"
|
||||||
|
password: "12345"
|
||||||
|
main_rtsp_path: "/Streaming/Channels/1"
|
||||||
|
sub_rtsp_path: "/Streaming/Channels/2"
|
||||||
|
retain_bytes: 52428800 # 50 MiB
|
||||||
|
>
|
||||||
|
camera <
|
||||||
|
short_name: "back_east"
|
||||||
|
host: "192.168.1.102:554"
|
||||||
|
user: "admin"
|
||||||
|
password: "12345"
|
||||||
|
main_rtsp_path: "/Streaming/Channels/1"
|
||||||
|
sub_rtsp_path: "/Streaming/Channels/2"
|
||||||
|
retain_bytes: 52428800 # 50 MiB
|
||||||
|
>
|
||||||
|
|
||||||
|
The example configuration above does the following:
|
||||||
|
|
||||||
|
* streams the `main_rtsp_path` from both cameras, reconnecting on errors, and
|
||||||
|
writing 10-minute segments of video to subdirectories of
|
||||||
|
`/var/lib/surveillance/`. (The `sub_rtsp_path` field is not used yet.)
|
||||||
|
* deletes old files to stay within the 50 MiB limit for each camera, excluding
|
||||||
|
the video file currently being written.
|
||||||
|
* writes human-readable debug logs to `/tmp/moonfire_nvr.INFO`.
|
||||||
|
* runs an HTTP server on the port 8080 (try
|
||||||
|
[`http://localhost:8080/`](http://localhost:8080/) which allows streaming the
|
||||||
|
video. Note: Moonfire NVR does not yet support authentication or SSL, so
|
||||||
|
this webserver should not be directly exposed to the Internet.
|
||||||
|
|
||||||
|
When configuring Moonfire NVR, it may be helpful to replicate its basic
|
||||||
|
functionality with the `ffmpeg` commandline tool. The command below is roughly
|
||||||
|
equivalent to the configuration for `back_west` above.
|
||||||
|
|
||||||
|
$ ffmpeg \
|
||||||
|
-i "rtsp://admin:12345@192.168.1.101:554/Streaming/Channels/1" \
|
||||||
|
-c copy \
|
||||||
|
-map 0:0 \
|
||||||
|
-flags:v +global_header \
|
||||||
|
-bsf:v dump_extra \
|
||||||
|
-f segment \
|
||||||
|
-segment_time 600 \
|
||||||
|
-use_strftime 1 \
|
||||||
|
-segment_format mp4 \
|
||||||
|
%Y%m%d%H%M%S-back_west.mp4
|
||||||
|
|
||||||
|
# Installation
|
||||||
|
|
||||||
|
Moonfire NVR should be run under a dedicated user. This user should own the
|
||||||
|
`base_path` directory mentioned in the configuration file. Because video is
|
||||||
|
served through an HTTP interface, there's no need for any other user to access
|
||||||
|
the files.
|
||||||
|
|
||||||
|
$ sudo adduser --system moonfire-nvr
|
||||||
|
$ sudo mkdir /var/lib/moonfire_nvr
|
||||||
|
$ sudo chown moonfire-nvr:moonfire-nvr /var/lib/moonfire_nvr
|
||||||
|
$ sudo chmod 700 /var/lib/moonfire_nvr
|
||||||
|
|
||||||
|
It can be run as a systemd service. Create
|
||||||
|
`/etc/systemd/system/moonfire-nvr.service`:
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Moonfire NVR
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart=/usr/local/bin/moonfire_nvr
|
||||||
|
Type=simple
|
||||||
|
User=moonfire-nvr
|
||||||
|
Nice=-20
|
||||||
|
Restart=on-abnormal
|
||||||
|
CPUAccounting=true
|
||||||
|
MemoryAccounting=true
|
||||||
|
BlockIOAccounting=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
|
Complete the installation through `systemctl` commands:
|
||||||
|
|
||||||
|
$ sudo systemctl daemon-reload
|
||||||
|
$ sudo systemctl start moonfire-nvr.service
|
||||||
|
$ sudo systemctl status moonfire-nvr.service
|
||||||
|
$ sudo systemctl enable moonfire-nvr.service
|
||||||
|
|
||||||
|
See the [systemd](http://www.freedesktop.org/wiki/Software/systemd/)
|
||||||
|
documentation for more information. The [manual
|
||||||
|
pages](http://www.freedesktop.org/software/systemd/man/) for `systemd.service`
|
||||||
|
and `systemctl` may be of particular interest.
|
||||||
|
|
||||||
|
While Moonfire NVR is running, logs will be written to `/tmp/moonfire_nvr.INFO`.
|
||||||
|
|
||||||
|
# <a name="help"></a> Getting help and getting involved
|
||||||
|
|
||||||
|
Please email the
|
||||||
|
[moonfire-nvr-users]([https://groups.google.com/d/forum/moonfire-nvr-users)
|
||||||
|
mailing list with questions, bug reports, feature requests, or just to say
|
||||||
|
you love/hate the software and why.
|
||||||
|
|
||||||
|
I'd welcome help with testing, development (in C++, JavaScript, and HTML), user
|
||||||
|
interface/graphic design, and documentation. Please email the mailing list
|
||||||
|
if interested. Patches are welcome, but I encourage you to discuss large
|
||||||
|
changes on the mailing list first to save effort.
|
||||||
|
|
||||||
|
C++ code should be written using C++11 features, should follow the [Google C++
|
||||||
|
style guide](https://google.github.io/styleguide/cppguide.html) for
|
||||||
|
consistency, and should be automatically tested where practical. But don't
|
||||||
|
worry about this too much; I'm much happier to work with you to refine a rough
|
||||||
|
draft patch than never see your contribution at all!
|
||||||
|
|
||||||
|
# License
|
||||||
|
|
||||||
|
This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
In addition, as a special exception, the copyright holders give
|
||||||
|
permission to link the code of portions of this program with the
|
||||||
|
OpenSSL library under certain conditions as described in each
|
||||||
|
individual source file, and distribute linked combinations including
|
||||||
|
the two.
|
||||||
|
|
||||||
|
You must obey the GNU General Public License in all respects for all
|
||||||
|
of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
exception, you may extend this exception to your version of the
|
||||||
|
file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
so, delete this exception statement from your version. If you delete
|
||||||
|
this exception statement from all source files in the program, then
|
||||||
|
also delete it here.
|
||||||
|
|
||||||
|
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/>.
|
|
@ -0,0 +1,5 @@
|
||||||
|
moonfire-nvr (0.1.0) UNRELEASED; urgency=medium
|
||||||
|
|
||||||
|
* Initial release.
|
||||||
|
|
||||||
|
-- Scott Lamb <slamb@slamb.org> Fri, 1 Jan 2016 21:00:00 -0800
|
|
@ -0,0 +1 @@
|
||||||
|
9
|
|
@ -0,0 +1,12 @@
|
||||||
|
Source: moonfire-nvr
|
||||||
|
Maintainer: Scott Lamb <slamb@slamb.org>
|
||||||
|
Section: video
|
||||||
|
Priority: optional
|
||||||
|
Standards-Version: 3.9.6.1
|
||||||
|
Build-Depends: debhelper (>= 9), dh-systemd, cmake, libprotobuf-dev, libavcodec-dev, libavformat-dev, libevent-dev, libgflags-dev, libgoogle-glog-dev, libgoogle-perftools-dev, libre2-dev, pkgconf, protobuf-compiler
|
||||||
|
|
||||||
|
Package: moonfire-nvr
|
||||||
|
Architecture: any
|
||||||
|
Depends: ${shlibs:Depends}, ${misc:Depends}, adduser
|
||||||
|
Description: security camera network video recorder
|
||||||
|
moonfire-nvr records video files from IP security cameras.
|
|
@ -0,0 +1,43 @@
|
||||||
|
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||||
|
Upstream-Name: Moonfire NVR
|
||||||
|
Upstream-Contact: Scott Lamb <slamb@slamb.org>
|
||||||
|
Source: http://github.com/scottlamb/moonfire-nvr
|
||||||
|
|
||||||
|
Files: *
|
||||||
|
Copyright: 2016 Scott Lamb
|
||||||
|
License: GPL-3+ with OpenSSL exception
|
||||||
|
|
||||||
|
License: GPL-3+ with OpenSSL exception
|
||||||
|
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.
|
||||||
|
.
|
||||||
|
In addition, as a special exception, the copyright holders give
|
||||||
|
permission to link the code of portions of this program with the
|
||||||
|
OpenSSL library under certain conditions as described in each
|
||||||
|
individual source file, and distribute linked combinations including
|
||||||
|
the two.
|
||||||
|
.
|
||||||
|
You must obey the GNU General Public License in all respects for all
|
||||||
|
of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
exception, you may extend this exception to your version of the
|
||||||
|
file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
so, delete this exception statement from your version. If you delete
|
||||||
|
this exception statement from all source files in the program, then
|
||||||
|
also delete it here.
|
||||||
|
.
|
||||||
|
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/>.
|
||||||
|
.
|
||||||
|
On Debian systems, the full text of the GNU General Public
|
||||||
|
License version 3 can be found in the file
|
||||||
|
`/usr/share/common-licenses/GPL-3'.
|
|
@ -0,0 +1,8 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
set -e
|
||||||
|
adduser --system moonfire-nvr
|
||||||
|
|
||||||
|
#DEBHELPER#
|
||||||
|
|
||||||
|
exit 0
|
|
@ -0,0 +1,16 @@
|
||||||
|
[Unit]
|
||||||
|
Description=Moonfire NVR
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart=/usr/bin/moonfire-nvr
|
||||||
|
Type=simple
|
||||||
|
User=moonfire-nvr
|
||||||
|
Nice=-20
|
||||||
|
Restart=on-abnormal
|
||||||
|
CPUAccounting=true
|
||||||
|
MemoryAccounting=true
|
||||||
|
BlockIOAccounting=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
|
@ -0,0 +1,3 @@
|
||||||
|
#!/usr/bin/make -f
|
||||||
|
%:
|
||||||
|
dh $@ --with=systemd
|
|
@ -0,0 +1 @@
|
||||||
|
3.0 (native)
|
|
@ -0,0 +1,59 @@
|
||||||
|
# Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
#
|
||||||
|
# In addition, as a special exception, the copyright holders give
|
||||||
|
# permission to link the code of portions of this program with the
|
||||||
|
# OpenSSL library under certain conditions as described in each
|
||||||
|
# individual source file, and distribute linked combinations including
|
||||||
|
# the two.
|
||||||
|
#
|
||||||
|
# You must obey the GNU General Public License in all respects for all
|
||||||
|
# of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
# exception, you may extend this exception to your version of the
|
||||||
|
# file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
# so, delete this exception statement from your version. If you delete
|
||||||
|
# this exception statement from all source files in the program, then
|
||||||
|
# also delete it here.
|
||||||
|
#
|
||||||
|
# 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/>.
|
||||||
|
|
||||||
|
include_directories(${CMAKE_CURRENT_BINARY_DIR})
|
||||||
|
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS config.protodevel)
|
||||||
|
|
||||||
|
set(MOONFIRE_DEPS
|
||||||
|
${FFMPEG_LIBRARIES}
|
||||||
|
${LIBEVENT_LIBRARIES}
|
||||||
|
${GFLAGS_LIBRARIES}
|
||||||
|
${GLOG_LIBRARIES}
|
||||||
|
${PROFILER_LIBRARIES}
|
||||||
|
${PROTOBUF_LIBRARIES}
|
||||||
|
${RE2_LIBRARIES})
|
||||||
|
|
||||||
|
add_library(moonfire-nvr-lib moonfire-nvr.cc ffmpeg.cc http.cc string.cc profiler.cc filesystem.cc time.cc ${PROTO_SRCS} ${PROTO_HDRS})
|
||||||
|
target_link_libraries(moonfire-nvr-lib ${MOONFIRE_DEPS})
|
||||||
|
|
||||||
|
add_executable(moonfire-nvr moonfire-nvr-main.cc)
|
||||||
|
target_link_libraries(moonfire-nvr moonfire-nvr-lib)
|
||||||
|
install_programs(/bin FILES moonfire-nvr)
|
||||||
|
|
||||||
|
# Tests.
|
||||||
|
include_directories(${GTest_INCLUDE_DIR})
|
||||||
|
include_directories(${GMock_INCLUDE_DIR})
|
||||||
|
|
||||||
|
foreach(test http moonfire-nvr string)
|
||||||
|
add_executable(${test}-test ${test}-test.cc testutil.cc)
|
||||||
|
target_link_libraries(${test}-test GTest GMock moonfire-nvr-lib)
|
||||||
|
add_test(NAME ${test}-test
|
||||||
|
COMMAND ${test}-test
|
||||||
|
WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
|
||||||
|
endforeach(test)
|
|
@ -0,0 +1,93 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// config.protodevel: protocol buffer definition for configuration.
|
||||||
|
// Currently this is used only for an ASCII-format protocol buffer config
|
||||||
|
// file, so tag numbers are insignificant. Additionally, as moonfire-nvr has not
|
||||||
|
// yet reached 1.0, there is no promise of compatibility between versions---
|
||||||
|
// names and structure are free to change as desired.
|
||||||
|
//
|
||||||
|
// Quick note to those unfamiliar with protocol buffers: the word "optional"
|
||||||
|
// below does *not* imply that a field may be omitted. If the comment does not
|
||||||
|
// say that a field may be omitted, supply the field. "optional" is
|
||||||
|
// just a word that proto2 syntax wants everywhere, like "please". See also:
|
||||||
|
// http://stackoverflow.com/questions/31801257/why-required-and-optional-is-removed-in-protocol-buffers-3
|
||||||
|
|
||||||
|
syntax = "proto2";
|
||||||
|
|
||||||
|
package moonfire_nvr;
|
||||||
|
|
||||||
|
message Camera {
|
||||||
|
// A short name of the camera, used as a path component and in log messages.
|
||||||
|
optional string short_name = 1;
|
||||||
|
|
||||||
|
// A short description of the camera.
|
||||||
|
optional string description = 2;
|
||||||
|
|
||||||
|
// The host (or IP address) to use in rtsp:// URLs when accessing the camera.
|
||||||
|
optional string host = 3;
|
||||||
|
|
||||||
|
// The username to use when accessing the camera.
|
||||||
|
// If empty, no username or password will be supplied.
|
||||||
|
optional string user = 4;
|
||||||
|
|
||||||
|
// The password to use when accessing the camera.
|
||||||
|
optional string password = 5;
|
||||||
|
|
||||||
|
// The path (starting with "/") to use in rtsp:// URLs to reference this
|
||||||
|
// camera's "main" (full-quality) video stream.
|
||||||
|
optional string main_rtsp_path = 6;
|
||||||
|
|
||||||
|
// The path (starting with "/") to use in rtsp:// URLs to reference this
|
||||||
|
// camera's "main" (full-quality) video stream. Currently unused.
|
||||||
|
optional string sub_rtsp_path = 7;
|
||||||
|
|
||||||
|
// The number of bytes of video to retain, excluding the currently-recording
|
||||||
|
// file. Older files will be deleted as necessary to stay within this limit.
|
||||||
|
optional uint64 retain_bytes = 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
message Config {
|
||||||
|
// The base path for recorded files. E.g., "/var/lib/surveillance".
|
||||||
|
// Each camera will record to a subdirectory of this path.
|
||||||
|
optional string base_path = 1;
|
||||||
|
|
||||||
|
// Approximate number of seconds after which to close a video file and
|
||||||
|
// open a new one. E.g., 600 (meaning 10 minutes). All files will begin with
|
||||||
|
// a key frame, so video files will often be slightly over this limit.
|
||||||
|
optional uint32 rotate_sec = 2;
|
||||||
|
|
||||||
|
// A port to use for a HTTP server. For example, "8080".
|
||||||
|
// This webserver currently allows unauthenticated access to video files, so
|
||||||
|
// it should not be exposed to the Internet.
|
||||||
|
optional uint32 http_port = 4;
|
||||||
|
|
||||||
|
repeated Camera camera = 3;
|
||||||
|
}
|
|
@ -0,0 +1,84 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// ffmpeg-test.cc: tests of the ffmpeg.h interface.
|
||||||
|
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include "ffmpeg.h"
|
||||||
|
|
||||||
|
DECLARE_bool(alsologtostderr);
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
class FfmpegTest : public testing::Test {
|
||||||
|
public:
|
||||||
|
static void SetUpTestCase() {
|
||||||
|
FfmpegGlobalSetup();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
TEST_F(FfmpegTest, Read) {
|
||||||
|
// The cwd should be the cmake build directory, which should be a subdir of
|
||||||
|
// the project.
|
||||||
|
InputVideoPacketStream stream;
|
||||||
|
std::string error_msg;
|
||||||
|
ASSERT_TRUE(
|
||||||
|
stream.Open("../src/testdata/ffmpeg-bug-5018.mp4", &error_msg))
|
||||||
|
<< error_msg;
|
||||||
|
VideoPacket pkt;
|
||||||
|
std::vector<int64_t> ptses;
|
||||||
|
while (stream.GetNext(&pkt, &error_msg)) {
|
||||||
|
ptses.push_back(pkt.pts());
|
||||||
|
}
|
||||||
|
ASSERT_EQ("", error_msg);
|
||||||
|
int64_t kExpectedPtses[] = {
|
||||||
|
71001, 81005, 88995, 99005, 107043, 117022, 125000, 135022, 142992,
|
||||||
|
153101, 161005, 171005, 178996, 189008, 197039, 207023, 215003, 225004,
|
||||||
|
232993, 243007, 251000, 261014, 268991, 279009, 287079, 297037, 305008,
|
||||||
|
315010, 322995, 333016, 341001, 351105, 359009, 369017, 377005, 387029
|
||||||
|
};
|
||||||
|
ASSERT_THAT(ptses, testing::ElementsAreArray(kExpectedPtses));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
FLAGS_alsologtostderr = true;
|
||||||
|
google::ParseCommandLineFlags(&argc, &argv, true);
|
||||||
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
google::InitGoogleLogging(argv[0]);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
|
@ -0,0 +1,429 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// ffmpeg.cc: See ffmpeg.h for description.
|
||||||
|
|
||||||
|
#include "ffmpeg.h"
|
||||||
|
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include <libavutil/buffer.h>
|
||||||
|
#include <libavutil/mathematics.h>
|
||||||
|
#include <libavutil/version.h>
|
||||||
|
#include <libavcodec/avcodec.h>
|
||||||
|
#include <libavcodec/version.h>
|
||||||
|
#include <libavformat/version.h>
|
||||||
|
} // extern "C"
|
||||||
|
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
// libav lacks this ffmpeg constant.
|
||||||
|
#ifndef AV_ERROR_MAX_STRING_SIZE
|
||||||
|
#define AV_ERROR_MAX_STRING_SIZE 64
|
||||||
|
#endif
|
||||||
|
|
||||||
|
DEFINE_int32(avlevel, AV_LOG_INFO,
|
||||||
|
"maximum logging level for ffmpeg/libav; "
|
||||||
|
"higher levels will be ignored.");
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::string AvError2Str(re2::StringPiece function, int err) {
|
||||||
|
char str[AV_ERROR_MAX_STRING_SIZE];
|
||||||
|
if (av_strerror(err, str, sizeof(str)) == 0) {
|
||||||
|
return StrCat(function, ": ", str);
|
||||||
|
}
|
||||||
|
return StrCat(function, ": unknown error ", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Dictionary {
|
||||||
|
Dictionary() {}
|
||||||
|
Dictionary(const Dictionary &) = delete;
|
||||||
|
Dictionary &operator=(const Dictionary &) = delete;
|
||||||
|
~Dictionary() { av_dict_free(&dict); }
|
||||||
|
|
||||||
|
bool Set(const char *key, const char *value, std::string *error_message) {
|
||||||
|
int ret = av_dict_set(&dict, key, value, 0);
|
||||||
|
if (ret < 0) {
|
||||||
|
*error_message = AvError2Str("av_dict_set", ret);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool size() const { return av_dict_count(dict); }
|
||||||
|
|
||||||
|
AVDictionary *dict = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
google::LogSeverity GlogLevelFromAvLevel(int avlevel) {
|
||||||
|
if (avlevel >= AV_LOG_INFO) {
|
||||||
|
return google::GLOG_INFO;
|
||||||
|
} else if (avlevel >= AV_LOG_WARNING) {
|
||||||
|
return google::GLOG_WARNING;
|
||||||
|
} else if (avlevel > AV_LOG_PANIC) {
|
||||||
|
return google::GLOG_ERROR;
|
||||||
|
} else {
|
||||||
|
return google::GLOG_FATAL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AvLogCallback(void *avcl, int avlevel, const char *fmt, va_list vl) {
|
||||||
|
if (avlevel > FLAGS_avlevel) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// google::LogMessage expects a "file" and "line" to be prefixed to the
|
||||||
|
// log message, like so:
|
||||||
|
//
|
||||||
|
// W1210 11:00:32.224936 28739 ffmpeg_rtsp:0] Estimating duration ...
|
||||||
|
// ^file ^line
|
||||||
|
//
|
||||||
|
// Normally this is filled in via the __FILE__ and __LINE__
|
||||||
|
// C preprocessor macros. In this case, try to fill in something useful
|
||||||
|
// based on the information ffmpeg supplies.
|
||||||
|
std::string file("ffmpeg");
|
||||||
|
if (avcl != nullptr) {
|
||||||
|
auto *avclass = *reinterpret_cast<AVClass **>(avcl);
|
||||||
|
file.push_back('_');
|
||||||
|
file.append(avclass->item_name(avcl));
|
||||||
|
}
|
||||||
|
char line[512];
|
||||||
|
vsnprintf(line, sizeof(line), fmt, vl);
|
||||||
|
google::LogSeverity glog_level = GlogLevelFromAvLevel(avlevel);
|
||||||
|
google::LogMessage(file.c_str(), 0, glog_level).stream() << line;
|
||||||
|
}
|
||||||
|
|
||||||
|
int AvLockCallback(void **mutex, enum AVLockOp op) {
|
||||||
|
auto typed_mutex = reinterpret_cast<std::mutex **>(mutex);
|
||||||
|
switch (op) {
|
||||||
|
case AV_LOCK_CREATE:
|
||||||
|
LOG_IF(DFATAL, *typed_mutex != nullptr)
|
||||||
|
<< "creating mutex over existing value.";
|
||||||
|
*typed_mutex = new std::mutex;
|
||||||
|
break;
|
||||||
|
case AV_LOCK_DESTROY:
|
||||||
|
delete *typed_mutex;
|
||||||
|
*typed_mutex = nullptr;
|
||||||
|
break;
|
||||||
|
case AV_LOCK_OBTAIN:
|
||||||
|
(*typed_mutex)->lock();
|
||||||
|
break;
|
||||||
|
case AV_LOCK_RELEASE:
|
||||||
|
(*typed_mutex)->unlock();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string StringifyVersion(int version_int) {
|
||||||
|
return StrCat((version_int >> 16) & 0xFF, ".", (version_int >> 8) & 0xFF, ".",
|
||||||
|
(version_int)&0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
void LogVersion(const char *library_name, int compiled_version,
|
||||||
|
int running_version, const char *configuration) {
|
||||||
|
LOG(INFO) << library_name << ": compiled with version "
|
||||||
|
<< StringifyVersion(compiled_version) << ", running with version "
|
||||||
|
<< StringifyVersion(running_version)
|
||||||
|
<< ", configuration: " << configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
class RealInputVideoPacketStream : public InputVideoPacketStream {
|
||||||
|
public:
|
||||||
|
RealInputVideoPacketStream() {
|
||||||
|
ctx_ = CHECK_NOTNULL(avformat_alloc_context());
|
||||||
|
}
|
||||||
|
|
||||||
|
RealInputVideoPacketStream(const RealInputVideoPacketStream &) = delete;
|
||||||
|
RealInputVideoPacketStream &operator=(const RealInputVideoPacketStream &) =
|
||||||
|
delete;
|
||||||
|
|
||||||
|
~RealInputVideoPacketStream() final {
|
||||||
|
avformat_close_input(&ctx_);
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool GetNext(VideoPacket *pkt, std::string *error_message) final {
|
||||||
|
while (true) {
|
||||||
|
av_packet_unref(pkt->pkt());
|
||||||
|
int ret = av_read_frame(ctx_, pkt->pkt());
|
||||||
|
if (ret != 0) {
|
||||||
|
if (ret == AVERROR_EOF) {
|
||||||
|
error_message->clear();
|
||||||
|
} else {
|
||||||
|
*error_message = AvError2Str("av_read_frame", ret);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (pkt->pkt()->stream_index != stream_index_) {
|
||||||
|
VLOG(3) << "Ignoring packet for stream " << pkt->pkt()->stream_index
|
||||||
|
<< "; only interested in " << stream_index_;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
VLOG(2) << "Read packet with pts=" << pkt->pkt()->pts
|
||||||
|
<< ", dts=" << pkt->pkt()->dts << ", key=" << pkt->is_key();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const AVStream *stream() const final { return ctx_->streams[stream_index_]; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
friend class RealVideoSource;
|
||||||
|
int64_t min_next_pts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
int64_t min_next_dts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
AVFormatContext *ctx_ = nullptr; // owned.
|
||||||
|
int stream_index_ = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RealVideoSource : public VideoSource {
|
||||||
|
public:
|
||||||
|
RealVideoSource() {
|
||||||
|
CHECK_GE(0, av_lockmgr_register(&AvLockCallback));
|
||||||
|
av_log_set_callback(&AvLogCallback);
|
||||||
|
av_register_all();
|
||||||
|
avformat_network_init();
|
||||||
|
LogVersion("avutil", LIBAVUTIL_VERSION_INT, avutil_version(),
|
||||||
|
avutil_configuration());
|
||||||
|
LogVersion("avformat", LIBAVFORMAT_VERSION_INT, avformat_version(),
|
||||||
|
avformat_configuration());
|
||||||
|
LogVersion("avcodec", LIBAVCODEC_VERSION_INT, avcodec_version(),
|
||||||
|
avcodec_configuration());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unique_ptr<InputVideoPacketStream> OpenRtsp(
|
||||||
|
const std::string &url, std::string *error_message) final {
|
||||||
|
std::unique_ptr<InputVideoPacketStream> stream;
|
||||||
|
Dictionary open_options;
|
||||||
|
if (!open_options.Set("rtsp_transport", "tcp", error_message) ||
|
||||||
|
!open_options.Set("user-agent", "moonfire-nvr", error_message) ||
|
||||||
|
// 10-second socket timeout, in microseconds.
|
||||||
|
!open_options.Set("stimeout", "10000000", error_message)) {
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
stream = OpenCommon(url, &open_options.dict, error_message);
|
||||||
|
if (stream == nullptr) {
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Discard the first packet.
|
||||||
|
LOG(INFO) << "Discarding the first packet to work around "
|
||||||
|
"https://trac.ffmpeg.org/ticket/5018";
|
||||||
|
VideoPacket dummy;
|
||||||
|
if (!stream->GetNext(&dummy, error_message)) {
|
||||||
|
stream.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unique_ptr<InputVideoPacketStream> OpenFile(
|
||||||
|
const std::string &filename, std::string *error_message) final {
|
||||||
|
AVDictionary *open_options = nullptr;
|
||||||
|
return OpenCommon(filename, &open_options, error_message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::unique_ptr<InputVideoPacketStream> OpenCommon(
|
||||||
|
const std::string &source, AVDictionary **dict,
|
||||||
|
std::string *error_message) {
|
||||||
|
std::unique_ptr<RealInputVideoPacketStream> stream(
|
||||||
|
new RealInputVideoPacketStream);
|
||||||
|
|
||||||
|
int ret = avformat_open_input(&stream->ctx_, source.c_str(), nullptr, dict);
|
||||||
|
if (ret != 0) {
|
||||||
|
*error_message = AvError2Str("avformat_open_input", ret);
|
||||||
|
return std::unique_ptr<InputVideoPacketStream>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (av_dict_count(*dict) != 0) {
|
||||||
|
std::vector<std::string> ignored;
|
||||||
|
AVDictionaryEntry *ent = nullptr;
|
||||||
|
while ((ent = av_dict_get(*dict, "", ent, AV_DICT_IGNORE_SUFFIX)) !=
|
||||||
|
nullptr) {
|
||||||
|
ignored.push_back(StrCat(ent->key, "=", ent->value));
|
||||||
|
}
|
||||||
|
LOG(WARNING) << "avformat_open_input ignored " << ignored.size()
|
||||||
|
<< " options: " << Join(ignored, ", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = avformat_find_stream_info(stream->ctx_, nullptr);
|
||||||
|
if (ret < 0) {
|
||||||
|
*error_message = AvError2Str("avformat_find_stream_info", ret);
|
||||||
|
return std::unique_ptr<InputVideoPacketStream>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the video stream.
|
||||||
|
for (unsigned int i = 0; i < stream->ctx_->nb_streams; ++i) {
|
||||||
|
if (stream->ctx_->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
|
||||||
|
VLOG(1) << "Video stream index is " << i;
|
||||||
|
stream->stream_index_ = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (stream->stream() == nullptr) {
|
||||||
|
*error_message = StrCat("no video stream");
|
||||||
|
return std::unique_ptr<InputVideoPacketStream>();
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::unique_ptr<InputVideoPacketStream>(stream.release());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool OutputVideoPacketStream::OpenFile(const std::string &filename,
|
||||||
|
const InputVideoPacketStream &input,
|
||||||
|
std::string *error_message) {
|
||||||
|
CHECK(ctx_ == nullptr) << ": already open.";
|
||||||
|
CHECK(stream_ == nullptr);
|
||||||
|
|
||||||
|
if ((ctx_ = avformat_alloc_context()) == nullptr) {
|
||||||
|
*error_message = "avformat_alloc_context failed.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx_->oformat = av_guess_format(nullptr, filename.c_str(), nullptr);
|
||||||
|
if (ctx_->oformat == nullptr) {
|
||||||
|
*error_message =
|
||||||
|
StrCat("Can't find output format for filename: ", filename.c_str());
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
ctx_ = nullptr;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ret = avio_open2(&ctx_->pb, filename.c_str(), AVIO_FLAG_WRITE, nullptr,
|
||||||
|
nullptr);
|
||||||
|
if (ret < 0) {
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
ctx_ = nullptr;
|
||||||
|
*error_message = AvError2Str("avio_open2", ret);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
stream_ = avformat_new_stream(ctx_, input.stream()->codec->codec);
|
||||||
|
if (stream_ == nullptr) {
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
ctx_ = nullptr;
|
||||||
|
unlink(filename.c_str());
|
||||||
|
*error_message = AvError2Str("avformat_new_stream", ret);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
stream_->time_base = input.stream()->time_base;
|
||||||
|
ret = avcodec_copy_context(stream_->codec, input.stream()->codec);
|
||||||
|
if (ret != 0) {
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
ctx_ = nullptr;
|
||||||
|
stream_ = nullptr;
|
||||||
|
unlink(filename.c_str());
|
||||||
|
*error_message = AvError2Str("avcodec_copy_context", ret);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
stream_->codec->codec_tag = 0;
|
||||||
|
if ((ctx_->oformat->flags & AVFMT_GLOBALHEADER) != 0) {
|
||||||
|
stream_->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = avformat_write_header(ctx_, nullptr);
|
||||||
|
if (ret != 0) {
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
ctx_ = nullptr;
|
||||||
|
stream_ = nullptr;
|
||||||
|
unlink(filename.c_str());
|
||||||
|
*error_message = AvError2Str("avformat_write_header", ret);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
frames_written_ = 0;
|
||||||
|
key_frames_written_ = 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OutputVideoPacketStream::Write(VideoPacket *pkt,
|
||||||
|
std::string *error_message) {
|
||||||
|
#if 0
|
||||||
|
if (pkt->pkt()->pts < min_next_pts_ || pkt->pkt()->dts < min_next_dts_) {
|
||||||
|
*error_message = StrCat("refusing to write non-increasing pts/dts, pts=",
|
||||||
|
pkt->pkt()->pts, " vs min ", min_next_pts_, " dts=",
|
||||||
|
pkt->pkt()->dts, " vs min ", min_next_dts_);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
min_next_pts_ = pkt->pkt()->pts + 1;
|
||||||
|
min_next_dts_ = pkt->pkt()->dts + 1;
|
||||||
|
#endif
|
||||||
|
VLOG(2) << "Writing packet with pts=" << pkt->pkt()->pts
|
||||||
|
<< " dts=" << pkt->pkt()->dts << ", key=" << pkt->is_key();
|
||||||
|
int ret = av_write_frame(ctx_, pkt->pkt());
|
||||||
|
if (ret < 0) {
|
||||||
|
*error_message = AvError2Str("av_write_frame", ret);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
++frames_written_;
|
||||||
|
if (pkt->is_key()) {
|
||||||
|
key_frames_written_++;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OutputVideoPacketStream::Close() {
|
||||||
|
if (ctx_ == nullptr) {
|
||||||
|
CHECK(stream_ == nullptr);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ret = av_write_trailer(ctx_);
|
||||||
|
if (ret != 0) {
|
||||||
|
LOG(WARNING) << AvError2Str("av_write_trailer", ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = avio_closep(&ctx_->pb);
|
||||||
|
if (ret != 0) {
|
||||||
|
LOG(WARNING) << AvError2Str("avio_closep", ret);
|
||||||
|
}
|
||||||
|
avformat_free_context(ctx_);
|
||||||
|
ctx_ = nullptr;
|
||||||
|
stream_ = nullptr;
|
||||||
|
frames_written_ = -1;
|
||||||
|
key_frames_written_ = -1;
|
||||||
|
min_next_pts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
min_next_dts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
}
|
||||||
|
|
||||||
|
VideoSource *GetRealVideoSource() {
|
||||||
|
static auto *real_video_source = new RealVideoSource; // never deleted.
|
||||||
|
return real_video_source;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,164 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// ffmpeg.h: ffmpeg (or libav) wrappers for operations needed by moonfire_nvr.
|
||||||
|
// This is not a general-purpose wrapper. It makes assumptions about the
|
||||||
|
// data we will be operated on and the desired operations, such as:
|
||||||
|
//
|
||||||
|
// * The input should contain no "B" frames (bi-directionally predicted
|
||||||
|
// pictures) and thus input frames should be strictly in order of ascending
|
||||||
|
// PTS as well as DTS.
|
||||||
|
//
|
||||||
|
// * Only video frames are of interest.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_FFMPEG_H
|
||||||
|
#define MOONFIRE_NVR_FFMPEG_H
|
||||||
|
|
||||||
|
#include <limits>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include <libavformat/avformat.h>
|
||||||
|
} // extern "C"
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
// An encoded video packet.
|
||||||
|
class VideoPacket {
|
||||||
|
public:
|
||||||
|
VideoPacket() { av_init_packet(&pkt_); }
|
||||||
|
VideoPacket(const VideoPacket &) = delete;
|
||||||
|
VideoPacket &operator=(const VideoPacket &) = delete;
|
||||||
|
~VideoPacket() { av_packet_unref(&pkt_); }
|
||||||
|
|
||||||
|
// Returns iff this packet represents a key frame.
|
||||||
|
//
|
||||||
|
// (A key frame is one that can be decoded without previous frames.)
|
||||||
|
//
|
||||||
|
// PRE: this packet is valid, as if it has been filled by
|
||||||
|
// InputVideoPacketStream::Next.
|
||||||
|
bool is_key() const { return (pkt_.flags & AV_PKT_FLAG_KEY) != 0; }
|
||||||
|
|
||||||
|
int64_t pts() const { return pkt_.pts; }
|
||||||
|
|
||||||
|
AVPacket *pkt() { return &pkt_; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
AVPacket pkt_;
|
||||||
|
};
|
||||||
|
|
||||||
|
// An input stream of (still-encoded) video packets.
|
||||||
|
class InputVideoPacketStream {
|
||||||
|
public:
|
||||||
|
InputVideoPacketStream() {}
|
||||||
|
InputVideoPacketStream(const InputVideoPacketStream &) = delete;
|
||||||
|
InputVideoPacketStream &operator=(const InputVideoPacketStream &) = delete;
|
||||||
|
|
||||||
|
// Closes the stream.
|
||||||
|
virtual ~InputVideoPacketStream() {}
|
||||||
|
|
||||||
|
// Get the next packet.
|
||||||
|
//
|
||||||
|
// Returns true iff one is available, false on EOF or failure.
|
||||||
|
// |error_message| will be filled on failure, empty on EOF.
|
||||||
|
//
|
||||||
|
// PRE: the stream is healthy: there was no prior Close() call or GetNext()
|
||||||
|
// failure.
|
||||||
|
virtual bool GetNext(VideoPacket *pkt, std::string *error_message) = 0;
|
||||||
|
|
||||||
|
// Returns the video stream.
|
||||||
|
virtual const AVStream *stream() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A class which opens streams.
|
||||||
|
// There's one of these for proudction use; see GetRealVideoSource().
|
||||||
|
// It's an abstract class for testability.
|
||||||
|
class VideoSource {
|
||||||
|
public:
|
||||||
|
virtual ~VideoSource() {}
|
||||||
|
|
||||||
|
// Open the given RTSP URL, accessing the first video stream.
|
||||||
|
//
|
||||||
|
// The RTSP URL will be opened with TCP and a hardcoded socket timeout.
|
||||||
|
//
|
||||||
|
// The first frame will be automatically discarded as a bug workaround.
|
||||||
|
// https://trac.ffmpeg.org/ticket/5018
|
||||||
|
//
|
||||||
|
// Returns success, filling |error_message| on failure.
|
||||||
|
//
|
||||||
|
// PRE: closed.
|
||||||
|
virtual std::unique_ptr<InputVideoPacketStream> OpenRtsp(
|
||||||
|
const std::string &url, std::string *error_message) = 0;
|
||||||
|
|
||||||
|
// Open the given video file, accessing the first video stream.
|
||||||
|
//
|
||||||
|
// Returns the stream. On failure, returns nullptr and fills
|
||||||
|
// |error_message|.
|
||||||
|
virtual std::unique_ptr<InputVideoPacketStream> OpenFile(
|
||||||
|
const std::string &filename, std::string *error_message) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Returns a VideoSource for production use, which will never be deleted.
|
||||||
|
VideoSource *GetRealVideoSource();
|
||||||
|
|
||||||
|
class OutputVideoPacketStream {
|
||||||
|
public:
|
||||||
|
OutputVideoPacketStream() {}
|
||||||
|
OutputVideoPacketStream(const OutputVideoPacketStream &) = delete;
|
||||||
|
OutputVideoPacketStream &operator=(const OutputVideoPacketStream &) = delete;
|
||||||
|
|
||||||
|
~OutputVideoPacketStream() { Close(); }
|
||||||
|
|
||||||
|
bool OpenFile(const std::string &filename,
|
||||||
|
const InputVideoPacketStream &input,
|
||||||
|
std::string *error_message);
|
||||||
|
|
||||||
|
bool Write(VideoPacket *pkt, std::string *error_message);
|
||||||
|
|
||||||
|
void Close();
|
||||||
|
|
||||||
|
bool is_open() const { return ctx_ != nullptr; }
|
||||||
|
AVRational time_base() const { return stream_->time_base; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
int64_t key_frames_written_ = -1;
|
||||||
|
int64_t frames_written_ = -1;
|
||||||
|
int64_t min_next_dts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
int64_t min_next_pts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
AVFormatContext *ctx_ = nullptr; // owned.
|
||||||
|
AVStream *stream_ = nullptr; // ctx_ owns.
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_FFMPEG_H
|
|
@ -0,0 +1,84 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// filesystem.cc: See filesystem.h.
|
||||||
|
|
||||||
|
#include "filesystem.h"
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/queue.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/event.h>
|
||||||
|
#include <event2/keyvalq_struct.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <gperftools/profiler.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
bool DirForEach(const std::string &dir_path,
|
||||||
|
std::function<IterationControl(const dirent *)> fn,
|
||||||
|
std::string *error_message) {
|
||||||
|
DIR *owned_dir = opendir(dir_path.c_str());
|
||||||
|
if (owned_dir == nullptr) {
|
||||||
|
int err = errno;
|
||||||
|
*error_message =
|
||||||
|
StrCat("Unable to examine ", dir_path, ": ", strerror(err));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
struct dirent *ent;
|
||||||
|
while (errno = 0, (ent = readdir(owned_dir)) != nullptr) {
|
||||||
|
if (fn(ent) == IterationControl::kBreak) {
|
||||||
|
closedir(owned_dir);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int err = errno;
|
||||||
|
closedir(owned_dir);
|
||||||
|
if (err != 0) {
|
||||||
|
*error_message = StrCat("readdir failed: ", strerror(err));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,69 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// filesystem.h: helpers for dealing with the local filesystem.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_FILESYSTEM_H
|
||||||
|
#define MOONFIRE_NVR_FILESYSTEM_H
|
||||||
|
|
||||||
|
#include <dirent.h>
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <re2/stringpiece.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
// Return value for *ForEach callbacks.
|
||||||
|
enum class IterationControl {
|
||||||
|
kContinue, // indicates the caller should proceed with the loop.
|
||||||
|
kBreak // indicates the caller should terminate the loop with success.
|
||||||
|
};
|
||||||
|
|
||||||
|
// Execute |fn| for each directory entry in |dir_path|, stopping early
|
||||||
|
// (successfully) if the callback returns IterationControl::kBreak.
|
||||||
|
//
|
||||||
|
// On success, returns true.
|
||||||
|
// On failure, returns false and updates |error_msg|.
|
||||||
|
bool DirForEach(const std::string &dir_path,
|
||||||
|
std::function<IterationControl(const dirent *)> fn,
|
||||||
|
std::string *error_msg);
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_FILESYSTEM_H
|
|
@ -0,0 +1,162 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// util_test.cc: tests of the util.h interface.
|
||||||
|
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#include "http.h"
|
||||||
|
#include "string.h"
|
||||||
|
#include "testutil.h"
|
||||||
|
|
||||||
|
DECLARE_bool(alsologtostderr);
|
||||||
|
|
||||||
|
using moonfire_nvr::internal::ParseRangeHeader;
|
||||||
|
using moonfire_nvr::internal::RangeHeaderType;
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
TEST(EvBufferTest, AddFileTest) {
|
||||||
|
std::string dir = PrepareTempDirOrDie("http");
|
||||||
|
std::string foo_filename = StrCat(dir, "/foo");
|
||||||
|
WriteFileOrDie(foo_filename, "foo");
|
||||||
|
|
||||||
|
int in_fd = open(foo_filename.c_str(), O_RDONLY);
|
||||||
|
PCHECK(in_fd >= 0) << "open: " << foo_filename;
|
||||||
|
std::string error_message;
|
||||||
|
|
||||||
|
// Ensure adding the whole file succeeds.
|
||||||
|
EvBuffer buf1;
|
||||||
|
ASSERT_TRUE(buf1.AddFile(in_fd, 0, 3, &error_message)) << error_message;
|
||||||
|
EXPECT_EQ(3u, evbuffer_get_length(buf1.get()));
|
||||||
|
|
||||||
|
// Ensure adding an empty region succeeds.
|
||||||
|
EvBuffer buf2;
|
||||||
|
ASSERT_TRUE(buf2.AddFile(in_fd, 0, 0, &error_message)) << error_message;
|
||||||
|
EXPECT_EQ(0u, evbuffer_get_length(buf2.get()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test the specific examples enumerated in RFC 2616 section 14.35.1.
|
||||||
|
TEST(RangeHeaderTest, Rfc_2616_Section_14_35_1) {
|
||||||
|
std::vector<ByteRange> ranges;
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-499", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(0, 500)));
|
||||||
|
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=500-999", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(500, 1000)));
|
||||||
|
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=-500", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(9500, 10000)));
|
||||||
|
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=9500-", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(9500, 10000)));
|
||||||
|
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-0,-1", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges,
|
||||||
|
testing::ElementsAre(ByteRange(0, 1), ByteRange(9999, 10000)));
|
||||||
|
|
||||||
|
// Non-canonical ranges. Possibly the point of these is that the adjacent
|
||||||
|
// and overlapping ranges are supposed to be coalesced into one? I'm not
|
||||||
|
// going to do that for now...just trying to get something working...
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=500-600,601-999", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges,
|
||||||
|
testing::ElementsAre(ByteRange(500, 601), ByteRange(601, 1000)));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=500-700,601-999", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges,
|
||||||
|
testing::ElementsAre(ByteRange(500, 701), ByteRange(601, 1000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(RangeHeaderTest, Satisfiability) {
|
||||||
|
std::vector<ByteRange> ranges;
|
||||||
|
EXPECT_EQ(RangeHeaderType::kNotSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=10000-", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-499,10000-", 10000, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(0, 500)));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kNotSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=-1", 0, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kNotSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-0", 0, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kNotSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-", 0, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-0", 1, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(0, 1)));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kSatisfiable,
|
||||||
|
ParseRangeHeader("bytes=0-", 1, &ranges));
|
||||||
|
EXPECT_THAT(ranges, testing::ElementsAre(ByteRange(0, 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(RangeHeaderTest, AbsentOrInvalid) {
|
||||||
|
std::vector<ByteRange> ranges;
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader(nullptr, 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("foo=0-499", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("foo=0-499", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("bytes=499-0", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("bytes=", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("bytes=,", 10000, &ranges));
|
||||||
|
EXPECT_EQ(RangeHeaderType::kAbsentOrInvalid,
|
||||||
|
ParseRangeHeader("bytes=-", 10000, &ranges));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
FLAGS_alsologtostderr = true;
|
||||||
|
google::ParseCommandLineFlags(&argc, &argv, true);
|
||||||
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
google::InitGoogleLogging(argv[0]);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
|
@ -0,0 +1,283 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// http.cc: See http.h.
|
||||||
|
|
||||||
|
#include "http.h"
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/queue.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/event.h>
|
||||||
|
#include <event2/keyvalq_struct.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
class RealFile : public VirtualFile {
|
||||||
|
public:
|
||||||
|
RealFile(re2::StringPiece mime_type, re2::StringPiece filename,
|
||||||
|
const struct stat &statbuf)
|
||||||
|
: mime_type_(mime_type.as_string()),
|
||||||
|
filename_(filename.as_string()),
|
||||||
|
stat_(statbuf) {}
|
||||||
|
~RealFile() final {}
|
||||||
|
|
||||||
|
int64_t size() const final { return stat_.st_size; }
|
||||||
|
time_t last_modified() const final { return stat_.st_mtime; }
|
||||||
|
std::string etag() const final {
|
||||||
|
return StrCat("\"", stat_.st_ino, ":", stat_.st_size, ":",
|
||||||
|
stat_.st_mtim.tv_sec, ":", stat_.st_mtim.tv_nsec, "\"");
|
||||||
|
}
|
||||||
|
std::string mime_type() const final { return mime_type_; }
|
||||||
|
std::string filename() const final { return filename_; }
|
||||||
|
|
||||||
|
// Add the given range of the file to the buffer.
|
||||||
|
bool AddRange(ByteRange range, EvBuffer *buf,
|
||||||
|
std::string *error_message) const final {
|
||||||
|
int fd = open(filename_.c_str(), O_RDONLY);
|
||||||
|
if (fd < 0) {
|
||||||
|
int err = errno;
|
||||||
|
*error_message = StrCat("open: ", strerror(err));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!buf->AddFile(fd, range.begin, range.end - range.begin,
|
||||||
|
error_message)) {
|
||||||
|
close(fd);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// |buf| now owns |fd|.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
const std::string mime_type_;
|
||||||
|
const std::string filename_;
|
||||||
|
const struct stat stat_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
namespace internal {
|
||||||
|
|
||||||
|
RangeHeaderType ParseRangeHeader(const char *inptr, int64_t size,
|
||||||
|
std::vector<ByteRange> *ranges) {
|
||||||
|
if (inptr == nullptr) {
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid; // absent.
|
||||||
|
}
|
||||||
|
if (strncmp(inptr, "bytes=", strlen("bytes=")) != 0) {
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid; // invalid syntax.
|
||||||
|
}
|
||||||
|
inptr += strlen("bytes=");
|
||||||
|
ranges->clear();
|
||||||
|
int n_ranges = 0;
|
||||||
|
while (*inptr != 0) { // have more byte-range-sets.
|
||||||
|
++n_ranges;
|
||||||
|
ByteRange r;
|
||||||
|
|
||||||
|
// Parse a number.
|
||||||
|
const char *endptr;
|
||||||
|
int64_t value;
|
||||||
|
if (!strto64(inptr, 10, &endptr, &value)) {
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid; // invalid syntax.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value < 0) { // just parsed suffix-byte-range-spec.
|
||||||
|
r.begin = std::max(size + value, INT64_C(0));
|
||||||
|
r.end = size;
|
||||||
|
if (r.begin < r.end) { // satisfiable.
|
||||||
|
ranges->emplace_back(std::move(r));
|
||||||
|
}
|
||||||
|
inptr = endptr;
|
||||||
|
|
||||||
|
} else { // just parsed start of byte-range-spec.
|
||||||
|
if (*endptr != '-') {
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid;
|
||||||
|
}
|
||||||
|
r.begin = value;
|
||||||
|
inptr = endptr + 1; // move past the '-'.
|
||||||
|
if (*inptr == ',' || *inptr == 0) { // no end specified; use EOF.
|
||||||
|
r.end = size;
|
||||||
|
} else { // explicit range.
|
||||||
|
if (!strto64(inptr, 10, &endptr, &value) || value < r.begin) {
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid; // invalid syntax.
|
||||||
|
}
|
||||||
|
inptr = endptr;
|
||||||
|
r.end = std::min(size, value + 1); // note inclusive->exclusive.
|
||||||
|
}
|
||||||
|
if (r.begin < size) {
|
||||||
|
ranges->emplace_back(std::move(r)); // satisfiable.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (*inptr == ',') {
|
||||||
|
inptr++;
|
||||||
|
if (*inptr == 0) {
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid; // invalid syntax.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (n_ranges == 0) { // must be at least one range.
|
||||||
|
return RangeHeaderType::kAbsentOrInvalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ranges->empty() ? RangeHeaderType::kNotSatisfiable
|
||||||
|
: RangeHeaderType::kSatisfiable;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace internal
|
||||||
|
|
||||||
|
bool EvBuffer::AddFile(int fd, ev_off_t offset, ev_off_t length,
|
||||||
|
std::string *error_message) {
|
||||||
|
if (length == 0) {
|
||||||
|
// evbuffer_add_file fails in this trivial case, at least when using mmap.
|
||||||
|
// Just return true since there's nothing to be done.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (evbuffer_add_file(buf_, fd, offset, length) != 0) {
|
||||||
|
int err = errno;
|
||||||
|
*error_message = StrCat("evbuffer_add_file failed with offset ", offset,
|
||||||
|
", length ", length, ": ", strerror(err));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpSendError(evhttp_request *req, int http_err, const std::string &prefix,
|
||||||
|
int posix_err) {
|
||||||
|
evhttp_send_error(req, http_err,
|
||||||
|
EscapeHtml(prefix + strerror(posix_err)).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpServe(const VirtualFile &file, evhttp_request *req) {
|
||||||
|
// We could support HEAD, but there's probably no need.
|
||||||
|
if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
|
||||||
|
return evhttp_send_error(req, HTTP_BADMETHOD, "only GET allowed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const struct evkeyvalq *in_hdrs = evhttp_request_get_input_headers(req);
|
||||||
|
struct evkeyvalq *out_hdrs = evhttp_request_get_output_headers(req);
|
||||||
|
|
||||||
|
// Construct a Last-Modified: header.
|
||||||
|
time_t last_modified = file.last_modified();
|
||||||
|
struct tm last_modified_tm;
|
||||||
|
if (gmtime_r(&last_modified, &last_modified_tm) == 0) {
|
||||||
|
return HttpSendError(req, HTTP_INTERNAL, "gmtime_r failed: ", errno);
|
||||||
|
}
|
||||||
|
char last_modified_str[50];
|
||||||
|
if (strftime(last_modified_str, sizeof(last_modified_str),
|
||||||
|
"%a, %d %b %Y %H:%M:%S GMT", &last_modified_tm) == 0) {
|
||||||
|
return HttpSendError(req, HTTP_INTERNAL, "strftime failed: ", errno);
|
||||||
|
}
|
||||||
|
std::string etag = file.etag();
|
||||||
|
|
||||||
|
// Ignore the "Range:" header if "If-Range:" specifies an incorrect etag.
|
||||||
|
const char *if_range = evhttp_find_header(in_hdrs, "If-Range");
|
||||||
|
const char *range_hdr = evhttp_find_header(in_hdrs, "Range");
|
||||||
|
if (if_range != nullptr && etag != if_range) {
|
||||||
|
LOG(INFO) << "Ignoring Range: because If-Range: is stale.";
|
||||||
|
range_hdr = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
EvBuffer buf;
|
||||||
|
std::vector<ByteRange> ranges;
|
||||||
|
auto range_type = internal::ParseRangeHeader(range_hdr, file.size(), &ranges);
|
||||||
|
std::string error_message;
|
||||||
|
int http_status;
|
||||||
|
const char *http_status_str;
|
||||||
|
switch (range_type) {
|
||||||
|
case internal::RangeHeaderType::kNotSatisfiable: {
|
||||||
|
std::string range_hdr = StrCat("bytes */", file.size());
|
||||||
|
evhttp_add_header(out_hdrs, "Content-Range", range_hdr.c_str());
|
||||||
|
http_status = 416;
|
||||||
|
http_status_str = "Range Not Satisfiable";
|
||||||
|
LOG(INFO) << "Replying to non-satisfiable range request for "
|
||||||
|
<< file.filename() << ": " << range_hdr;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case internal::RangeHeaderType::kSatisfiable:
|
||||||
|
// We only support the simpler single-range case for now.
|
||||||
|
if (ranges.size() == 1) {
|
||||||
|
std::string range_hdr = StrCat("bytes ", ranges[0].begin, "-",
|
||||||
|
ranges[0].end - 1, "/", file.size());
|
||||||
|
if (!file.AddRange(ranges[0], &buf, &error_message)) {
|
||||||
|
LOG(ERROR) << "Unable to serve " << file.filename() << " "
|
||||||
|
<< ranges[0] << ": " << error_message;
|
||||||
|
return evhttp_send_error(req, HTTP_INTERNAL,
|
||||||
|
EscapeHtml(error_message).c_str());
|
||||||
|
}
|
||||||
|
evhttp_add_header(out_hdrs, "Content-Range", range_hdr.c_str());
|
||||||
|
http_status = 206;
|
||||||
|
http_status_str = "Partial Content";
|
||||||
|
LOG(INFO) << "Replying to range request for " << file.filename();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// FALLTHROUGH
|
||||||
|
|
||||||
|
case internal::RangeHeaderType::kAbsentOrInvalid:
|
||||||
|
if (!file.AddRange(ByteRange(0, file.size()), &buf, &error_message)) {
|
||||||
|
LOG(ERROR) << "Unable to serve " << file.filename() << ": "
|
||||||
|
<< error_message;
|
||||||
|
return evhttp_send_error(req, HTTP_INTERNAL,
|
||||||
|
EscapeHtml(error_message).c_str());
|
||||||
|
}
|
||||||
|
LOG(INFO) << "Replying to whole-file request for " << file.filename();
|
||||||
|
http_status = HTTP_OK;
|
||||||
|
http_status_str = "OK";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Successful reply ready; add common headers and send.
|
||||||
|
evhttp_add_header(out_hdrs, "Content-Type", file.mime_type().c_str());
|
||||||
|
evhttp_add_header(out_hdrs, "Accept-Ranges", "bytes");
|
||||||
|
evhttp_add_header(out_hdrs, "Last-Modified", last_modified_str);
|
||||||
|
evhttp_add_header(out_hdrs, "ETag", etag.c_str());
|
||||||
|
evhttp_send_reply(req, http_status, http_status_str, buf.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpServeFile(evhttp_request *req, const std::string &mime_type,
|
||||||
|
const std::string &filename, const struct stat &statbuf) {
|
||||||
|
return HttpServe(RealFile(mime_type, filename, statbuf), req);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,171 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// http.h: classes for HTTP serving. In particular, there are helpers for
|
||||||
|
// serving HTTP byte range requests with libevent.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_HTTP_H
|
||||||
|
#define MOONFIRE_NVR_HTTP_H
|
||||||
|
|
||||||
|
#include <dirent.h>
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <re2/stringpiece.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
// Wrapped version of libevent's "struct evbuffer" which uses RAII and simply
|
||||||
|
// aborts the process if allocations fail. (Moonfire NVR is intended to run on
|
||||||
|
// Linux systems with the default vm.overcommit_memory=0, so there's probably
|
||||||
|
// no point in trying to gracefully recover from a condition that's unlikely
|
||||||
|
// to ever happen.)
|
||||||
|
class EvBuffer {
|
||||||
|
public:
|
||||||
|
EvBuffer() { buf_ = CHECK_NOTNULL(evbuffer_new()); }
|
||||||
|
EvBuffer(const EvBuffer &) = delete;
|
||||||
|
EvBuffer &operator=(const EvBuffer &) = delete;
|
||||||
|
~EvBuffer() { evbuffer_free(buf_); }
|
||||||
|
|
||||||
|
struct evbuffer *get() {
|
||||||
|
return buf_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Add(const re2::StringPiece &s) {
|
||||||
|
CHECK_EQ(0, evbuffer_add(buf_, s.data(), s.size()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void AddPrintf(const char *fmt, ...) __attribute__((format(printf, 2, 3))) {
|
||||||
|
va_list argp;
|
||||||
|
va_start(argp, fmt);
|
||||||
|
CHECK_LE(0, evbuffer_add_vprintf(buf_, fmt, argp));
|
||||||
|
va_end(argp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delegates to evbuffer_add_file.
|
||||||
|
// On success, |fd| will be closed by libevent. On failure, it remains open.
|
||||||
|
bool AddFile(int fd, ev_off_t offset, ev_off_t length,
|
||||||
|
std::string *error_message);
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct evbuffer *buf_;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ByteRange {
|
||||||
|
ByteRange() {}
|
||||||
|
ByteRange(int64_t begin, int64_t end) : begin(begin), end(end) {}
|
||||||
|
int64_t begin = 0;
|
||||||
|
int64_t end = 0; // exclusive.
|
||||||
|
bool operator==(const ByteRange &o) const {
|
||||||
|
return begin == o.begin && end == o.end;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
inline std::ostream &operator<<(std::ostream &out, const ByteRange &range) {
|
||||||
|
out << "[" << range.begin << ", " << range.end << ")";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper for sending HTTP errors based on POSIX error returns.
|
||||||
|
void HttpSendError(evhttp_request *req, int http_err, const std::string &prefix,
|
||||||
|
int posix_errno);
|
||||||
|
|
||||||
|
class VirtualFile {
|
||||||
|
public:
|
||||||
|
virtual ~VirtualFile() {}
|
||||||
|
|
||||||
|
// Return the given property of the file.
|
||||||
|
virtual int64_t size() const = 0;
|
||||||
|
virtual time_t last_modified() const = 0;
|
||||||
|
virtual std::string etag() const = 0;
|
||||||
|
virtual std::string mime_type() const = 0;
|
||||||
|
virtual std::string filename() const = 0; // for logging.
|
||||||
|
|
||||||
|
// Add the given range of the file to the buffer.
|
||||||
|
virtual bool AddRange(ByteRange range, EvBuffer *buf,
|
||||||
|
std::string *error_message) const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Serve an HTTP request |req| from |file|, handling byte range and
|
||||||
|
// conditional serving. (Similar to golang's http.ServeContent.)
|
||||||
|
//
|
||||||
|
// |file| only needs to live through the call to HttpServe itself.
|
||||||
|
// This contract may change in the future; currently all the ranges are added
|
||||||
|
// at the beginning of the request, so if large memory-backed buffers (as
|
||||||
|
// opposed to file-backed buffers) are used, the program's memory usage will
|
||||||
|
// spike, even if the HTTP client aborts early in the request. If this becomes
|
||||||
|
// problematic, this interface may change to take advantage of
|
||||||
|
// evbuffer_add_cb, adding buffers incrementally, and some mechanism will be
|
||||||
|
// added to guarantee VirtualFile objects outlive the HTTP requests they serve.
|
||||||
|
void HttpServe(const VirtualFile &file, evhttp_request *req);
|
||||||
|
|
||||||
|
// Serve a file over HTTP. Expects the caller to supply a sanitized |filename|
|
||||||
|
// (rather than taking it straight from the path specified in |req|).
|
||||||
|
void HttpServeFile(evhttp_request *req, const std::string &mime_type,
|
||||||
|
const std::string &filename, const struct stat &statbuf);
|
||||||
|
|
||||||
|
namespace internal {
|
||||||
|
|
||||||
|
// Value to represent result of parsing HTTP 1.1 "Range:" header.
|
||||||
|
enum class RangeHeaderType {
|
||||||
|
// Ignore the header, serving all bytes in the file.
|
||||||
|
kAbsentOrInvalid,
|
||||||
|
|
||||||
|
// The server SHOULD return a response with status 416 (Requested range not
|
||||||
|
// satisfiable).
|
||||||
|
kNotSatisfiable,
|
||||||
|
|
||||||
|
// The server SHOULD return a response with status 406 (Partial Content).
|
||||||
|
kSatisfiable
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parse an HTTP 1.1 "Range:" header value, following RFC 2616 section 14.35.
|
||||||
|
// This function is for use by HttpServe; it is exposed for testing only.
|
||||||
|
//
|
||||||
|
// |value| on entry should be the header value (after the ": "), or nullptr.
|
||||||
|
// |size| on entry should be the number of bytes available to serve.
|
||||||
|
// On kSatisfiable return, |ranges| will be filled with the satisfiable ranges.
|
||||||
|
// Otherwise, its contents are undefined.
|
||||||
|
RangeHeaderType ParseRangeHeader(const char *value, int64_t size,
|
||||||
|
std::vector<ByteRange> *ranges);
|
||||||
|
|
||||||
|
} // namespace internal
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_HTTP_H
|
|
@ -0,0 +1,176 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// moonfire-nvr-main.cc: main program. This should be kept as short as
|
||||||
|
// practical, so that individual parts of the program can be tested with the
|
||||||
|
// googletest framework.
|
||||||
|
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/event.h>
|
||||||
|
#include <event2/event_struct.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
#include <google/protobuf/io/zero_copy_stream_impl.h>
|
||||||
|
#include <google/protobuf/text_format.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
#include "config.pb.h"
|
||||||
|
#include "ffmpeg.h"
|
||||||
|
#include "profiler.h"
|
||||||
|
#include "moonfire-nvr.h"
|
||||||
|
|
||||||
|
DEFINE_string(config, "/etc/moonfire-nvr.conf", "Path to configuration file.");
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
const struct timeval kLogFlushInterval = {1, 0};
|
||||||
|
|
||||||
|
struct event_base* base;
|
||||||
|
|
||||||
|
void EventLogCallback(int severity, const char* msg) {
|
||||||
|
int vlog_level = 0;
|
||||||
|
google::LogSeverity glog_level;
|
||||||
|
if (severity <= EVENT_LOG_DEBUG) {
|
||||||
|
vlog_level = 1;
|
||||||
|
glog_level = google::GLOG_INFO;
|
||||||
|
} else if (severity <= EVENT_LOG_MSG) {
|
||||||
|
glog_level = google::GLOG_INFO;
|
||||||
|
} else if (severity <= EVENT_LOG_WARN) {
|
||||||
|
glog_level = google::GLOG_WARNING;
|
||||||
|
} else {
|
||||||
|
glog_level = google::GLOG_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vlog_level > 0 && !VLOG_IS_ON(vlog_level)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
google::LogMessage("libevent", 0, glog_level).stream() << msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LoadConfiguration(const std::string& filename,
|
||||||
|
moonfire_nvr::Config* config) {
|
||||||
|
int fd = open(filename.c_str(), O_RDONLY);
|
||||||
|
if (fd == -1) {
|
||||||
|
PLOG(ERROR) << "can't open " << filename;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
google::protobuf::io::FileInputStream file(fd);
|
||||||
|
file.SetCloseOnDelete(true);
|
||||||
|
// TODO(slamb): report more specific errors via an ErrorCollector.
|
||||||
|
if (!google::protobuf::TextFormat::Parse(&file, config)) {
|
||||||
|
LOG(ERROR) << "can't parse " << filename;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called on SIGTERM or SIGINT.
|
||||||
|
void SignalCallback(evutil_socket_t, short, void*) {
|
||||||
|
event_base_loopexit(base, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void FlushLogsCallback(evutil_socket_t, short, void* ev) {
|
||||||
|
google::FlushLogFiles(google::GLOG_INFO);
|
||||||
|
CHECK_EQ(0,
|
||||||
|
event_add(reinterpret_cast<struct event*>(ev), &kLogFlushInterval));
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpCallback(evhttp_request* req, void* arg) {
|
||||||
|
auto* nvr = reinterpret_cast<moonfire_nvr::Nvr*>(arg);
|
||||||
|
nvr->HttpCallback(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
GOOGLE_PROTOBUF_VERIFY_VERSION;
|
||||||
|
google::ParseCommandLineFlags(&argc, &argv, true);
|
||||||
|
google::InitGoogleLogging(argv[0]);
|
||||||
|
google::InstallFailureSignalHandler();
|
||||||
|
signal(SIGPIPE, SIG_IGN);
|
||||||
|
|
||||||
|
moonfire_nvr::Config config;
|
||||||
|
if (!LoadConfiguration(FLAGS_config, &config)) {
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
event_set_log_callback(&EventLogCallback);
|
||||||
|
LOG(INFO) << "libevent: compiled with version " << LIBEVENT_VERSION
|
||||||
|
<< ", running with version " << event_get_version();
|
||||||
|
base = CHECK_NOTNULL(event_base_new());
|
||||||
|
|
||||||
|
std::unique_ptr<moonfire_nvr::Nvr> nvr(new moonfire_nvr::Nvr);
|
||||||
|
std::string error_msg;
|
||||||
|
if (!nvr->Init(config, &error_msg)) {
|
||||||
|
LOG(ERROR) << "Unable to initialize: " << error_msg;
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
evhttp* http = CHECK_NOTNULL(evhttp_new(base));
|
||||||
|
moonfire_nvr::RegisterProfiler(base, http);
|
||||||
|
evhttp_set_gencb(http, &HttpCallback, nvr.get());
|
||||||
|
if (evhttp_bind_socket(http, "0.0.0.0", config.http_port()) != 0) {
|
||||||
|
LOG(ERROR) << "Unable to bind to port " << config.http_port();
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register for termination signals.
|
||||||
|
struct event ev_sigterm;
|
||||||
|
struct event ev_sigint;
|
||||||
|
CHECK_EQ(0, event_assign(&ev_sigterm, base, SIGTERM, EV_SIGNAL | EV_PERSIST,
|
||||||
|
&SignalCallback, nullptr));
|
||||||
|
CHECK_EQ(0, event_assign(&ev_sigint, base, SIGINT, EV_SIGNAL | EV_PERSIST,
|
||||||
|
&SignalCallback, nullptr));
|
||||||
|
CHECK_EQ(0, event_add(&ev_sigterm, nullptr));
|
||||||
|
CHECK_EQ(0, event_add(&ev_sigint, nullptr));
|
||||||
|
|
||||||
|
// Flush the logfiles regularly for debuggability.
|
||||||
|
struct event ev_flushlogs;
|
||||||
|
CHECK_EQ(0, event_assign(&ev_flushlogs, base, 0, 0, &FlushLogsCallback,
|
||||||
|
&ev_flushlogs));
|
||||||
|
CHECK_EQ(0, event_add(&ev_flushlogs, &kLogFlushInterval));
|
||||||
|
|
||||||
|
// Wait for events.
|
||||||
|
LOG(INFO) << "Main thread entering event loop.";
|
||||||
|
CHECK_EQ(0, event_base_loop(base, 0));
|
||||||
|
|
||||||
|
LOG(INFO) << "Shutting down.";
|
||||||
|
google::FlushLogFiles(google::GLOG_INFO);
|
||||||
|
nvr.reset();
|
||||||
|
LOG(INFO) << "Done.";
|
||||||
|
google::ShutdownGoogleLogging();
|
||||||
|
exit(0);
|
||||||
|
}
|
|
@ -0,0 +1,428 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// moonfire-nvr-test.cc: tests of the moonfire-nvr.cc interface.
|
||||||
|
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include "moonfire-nvr.h"
|
||||||
|
#include "string.h"
|
||||||
|
#include "testutil.h"
|
||||||
|
|
||||||
|
DECLARE_bool(alsologtostderr);
|
||||||
|
|
||||||
|
using testing::_;
|
||||||
|
using testing::AnyNumber;
|
||||||
|
using testing::HasSubstr;
|
||||||
|
using testing::Invoke;
|
||||||
|
using testing::Return;
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
class MockVideoSource : public VideoSource {
|
||||||
|
public:
|
||||||
|
// Proxy, as gmock doesn't support non-copyable return values.
|
||||||
|
std::unique_ptr<InputVideoPacketStream> OpenRtsp(
|
||||||
|
const std::string &url, std::string *error_message) final {
|
||||||
|
return std::unique_ptr<InputVideoPacketStream>(
|
||||||
|
OpenRtspRaw(url, error_message));
|
||||||
|
}
|
||||||
|
std::unique_ptr<InputVideoPacketStream> OpenFile(
|
||||||
|
const std::string &file, std::string *error_message) final {
|
||||||
|
return std::unique_ptr<InputVideoPacketStream>(
|
||||||
|
OpenFileRaw(file, error_message));
|
||||||
|
}
|
||||||
|
|
||||||
|
MOCK_METHOD2(OpenRtspRaw,
|
||||||
|
InputVideoPacketStream *(const std::string &, std::string *));
|
||||||
|
MOCK_METHOD2(OpenFileRaw,
|
||||||
|
InputVideoPacketStream *(const std::string &, std::string *));
|
||||||
|
};
|
||||||
|
|
||||||
|
class FileManagerTest : public testing::Test {
|
||||||
|
protected:
|
||||||
|
FileManagerTest() {
|
||||||
|
test_dir_ = PrepareTempDirOrDie("moonfire-nvr-file-manager");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> GetFilenames(const FileManager &mgr) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
mgr.ForEachFile([&out](const std::string &f, const struct stat &) {
|
||||||
|
out.push_back(f);
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string test_dir_;
|
||||||
|
};
|
||||||
|
|
||||||
|
TEST_F(FileManagerTest, InitWithNoDirectory) {
|
||||||
|
std::string subdir = test_dir_ + "/" + "subdir";
|
||||||
|
FileManager manager("foo", subdir, 0);
|
||||||
|
|
||||||
|
// Should succeed.
|
||||||
|
std::string error_message;
|
||||||
|
EXPECT_TRUE(manager.Init(&error_message)) << error_message;
|
||||||
|
|
||||||
|
// Should create the directory.
|
||||||
|
struct stat buf;
|
||||||
|
ASSERT_EQ(0, lstat(subdir.c_str(), &buf)) << strerror(errno);
|
||||||
|
EXPECT_TRUE(S_ISDIR(buf.st_mode));
|
||||||
|
|
||||||
|
// Should report empty.
|
||||||
|
EXPECT_EQ(0, manager.total_bytes());
|
||||||
|
EXPECT_THAT(GetFilenames(manager), testing::ElementsAre());
|
||||||
|
|
||||||
|
// Adding files: nonexistent, simple, out of order.
|
||||||
|
EXPECT_FALSE(manager.AddFile("nonexistent.mp4", &error_message));
|
||||||
|
WriteFileOrDie(subdir + "/1.mp4", "1");
|
||||||
|
WriteFileOrDie(subdir + "/2.mp4", "123");
|
||||||
|
EXPECT_TRUE(manager.AddFile("2.mp4", &error_message)) << error_message;
|
||||||
|
EXPECT_EQ(3, manager.total_bytes());
|
||||||
|
EXPECT_THAT(GetFilenames(manager), testing::ElementsAre("2.mp4"));
|
||||||
|
EXPECT_TRUE(manager.AddFile("1.mp4", &error_message)) << error_message;
|
||||||
|
EXPECT_EQ(4, manager.total_bytes());
|
||||||
|
EXPECT_THAT(GetFilenames(manager), testing::ElementsAre("1.mp4", "2.mp4"));
|
||||||
|
|
||||||
|
EXPECT_TRUE(manager.Rotate(&error_message)) << error_message;
|
||||||
|
EXPECT_EQ(0, manager.total_bytes());
|
||||||
|
EXPECT_THAT(GetFilenames(manager), testing::ElementsAre());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(FileManagerTest, InitAndRotateWithExistingFiles) {
|
||||||
|
WriteFileOrDie(test_dir_ + "/1.mp4", "1");
|
||||||
|
WriteFileOrDie(test_dir_ + "/2.mp4", "123");
|
||||||
|
WriteFileOrDie(test_dir_ + "/3.mp4", "12345");
|
||||||
|
WriteFileOrDie(test_dir_ + "/other", "1234567");
|
||||||
|
FileManager manager("foo", test_dir_, 8);
|
||||||
|
|
||||||
|
// Should succeed.
|
||||||
|
std::string error_message;
|
||||||
|
EXPECT_TRUE(manager.Init(&error_message)) << error_message;
|
||||||
|
|
||||||
|
EXPECT_THAT(GetFilenames(manager),
|
||||||
|
testing::ElementsAre("1.mp4", "2.mp4", "3.mp4"));
|
||||||
|
EXPECT_EQ(1 + 3 + 5, manager.total_bytes());
|
||||||
|
|
||||||
|
EXPECT_TRUE(manager.Rotate(&error_message)) << error_message;
|
||||||
|
EXPECT_THAT(GetFilenames(manager), testing::ElementsAre("2.mp4", "3.mp4"));
|
||||||
|
EXPECT_EQ(8, manager.total_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
class StreamTest : public testing::Test {
|
||||||
|
public:
|
||||||
|
StreamTest() {
|
||||||
|
test_dir_ = PrepareTempDirOrDie("moonfire-nvr-stream-copier");
|
||||||
|
env_.clock = &clock_;
|
||||||
|
env_.video_source = &video_source_;
|
||||||
|
clock_.Sleep({1430006400, 0}); // 2016-04-26 00:00:00 UTC
|
||||||
|
|
||||||
|
config_.set_base_path(test_dir_);
|
||||||
|
config_.set_rotate_sec(5);
|
||||||
|
auto *camera = config_.add_camera();
|
||||||
|
camera->set_short_name("test");
|
||||||
|
camera->set_host("test-camera");
|
||||||
|
camera->set_user("foo");
|
||||||
|
camera->set_password("bar");
|
||||||
|
camera->set_main_rtsp_path("/main");
|
||||||
|
camera->set_sub_rtsp_path("/sub");
|
||||||
|
camera->set_retain_bytes(1000000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A function to use in OpenRtspRaw invocations which shuts down the stream
|
||||||
|
// and indicates that the input video source can't be opened.
|
||||||
|
InputVideoPacketStream *Shutdown(const std::string &url,
|
||||||
|
std::string *error_message) {
|
||||||
|
*error_message = "(shutting down)";
|
||||||
|
signal_.Shutdown();
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Frame {
|
||||||
|
Frame(bool is_key, int64_t pts, int64_t duration)
|
||||||
|
: is_key(is_key), pts(pts), duration(duration) {}
|
||||||
|
bool is_key;
|
||||||
|
int64_t pts;
|
||||||
|
int64_t duration;
|
||||||
|
|
||||||
|
bool operator==(const Frame &o) const {
|
||||||
|
return is_key == o.is_key && pts == o.pts && duration == o.duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
friend std::ostream &operator<<(std::ostream &os, const Frame &f) {
|
||||||
|
return os << "Frame(" << f.is_key << ", " << f.pts << ", " << f.duration
|
||||||
|
<< ")";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<Frame> GetFrames(const std::string &path) {
|
||||||
|
std::vector<Frame> frames;
|
||||||
|
std::string error_message;
|
||||||
|
std::string full_path = StrCat(test_dir_, "/test/", path);
|
||||||
|
auto f = GetRealVideoSource()->OpenFile(full_path, &error_message);
|
||||||
|
if (f == nullptr) {
|
||||||
|
ADD_FAILURE() << full_path << ": " << error_message;
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
VideoPacket pkt;
|
||||||
|
while (f->GetNext(&pkt, &error_message)) {
|
||||||
|
frames.push_back(Frame(pkt.is_key(), pkt.pts(), pkt.pkt()->duration));
|
||||||
|
}
|
||||||
|
EXPECT_EQ("", error_message);
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
|
||||||
|
ShutdownSignal signal_;
|
||||||
|
Config config_;
|
||||||
|
SimulatedClock clock_;
|
||||||
|
testing::StrictMock<MockVideoSource> video_source_;
|
||||||
|
Environment env_;
|
||||||
|
std::string test_dir_;
|
||||||
|
};
|
||||||
|
|
||||||
|
class ProxyingInputVideoPacketStream : public InputVideoPacketStream {
|
||||||
|
public:
|
||||||
|
explicit ProxyingInputVideoPacketStream(
|
||||||
|
std::unique_ptr<InputVideoPacketStream> base, SimulatedClock *clock)
|
||||||
|
: base_(std::move(base)), clock_(clock) {}
|
||||||
|
|
||||||
|
bool GetNext(VideoPacket *pkt, std::string *error_message) final {
|
||||||
|
if (pkts_left_-- == 0) {
|
||||||
|
*error_message = "(pkt limit reached)";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advance time to when this packet starts.
|
||||||
|
clock_->Sleep(SecToTimespec(last_duration_sec_));
|
||||||
|
if (!base_->GetNext(pkt, error_message)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
last_duration_sec_ =
|
||||||
|
pkt->pkt()->duration * av_q2d(base_->stream()->time_base);
|
||||||
|
|
||||||
|
// Adjust timestamps.
|
||||||
|
if (ts_offset_pkts_left_ > 0) {
|
||||||
|
pkt->pkt()->pts += ts_offset_;
|
||||||
|
pkt->pkt()->dts += ts_offset_;
|
||||||
|
--ts_offset_pkts_left_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use a fixed duration, as the duration from a real RTSP stream is only
|
||||||
|
// an estimate. Our test video is 1 fps, 90 kHz time base.
|
||||||
|
pkt->pkt()->duration = 90000;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AVStream *stream() const final { return base_->stream(); }
|
||||||
|
|
||||||
|
void set_ts_offset(int64_t offset, int pkts) {
|
||||||
|
ts_offset_ = offset;
|
||||||
|
ts_offset_pkts_left_ = pkts;
|
||||||
|
}
|
||||||
|
|
||||||
|
void set_pkts(int num) { pkts_left_ = num; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::unique_ptr<InputVideoPacketStream> base_;
|
||||||
|
SimulatedClock *clock_ = nullptr;
|
||||||
|
double last_duration_sec_ = 0.;
|
||||||
|
int64_t ts_offset_ = 0;
|
||||||
|
int ts_offset_pkts_left_ = 0;
|
||||||
|
int pkts_left_ = std::numeric_limits<int>::max();
|
||||||
|
};
|
||||||
|
|
||||||
|
TEST_F(StreamTest, Basic) {
|
||||||
|
Stream stream(&signal_, config_, &env_, config_.camera(0));
|
||||||
|
std::string error_message;
|
||||||
|
ASSERT_TRUE(stream.Init(&error_message)) << error_message;
|
||||||
|
|
||||||
|
// This is a ~1 fps test video with a timebase of 90 kHz.
|
||||||
|
auto in_stream = GetRealVideoSource()->OpenFile("../src/testdata/clip.mp4",
|
||||||
|
&error_message);
|
||||||
|
ASSERT_TRUE(in_stream != nullptr) << error_message;
|
||||||
|
auto *proxy_stream =
|
||||||
|
new ProxyingInputVideoPacketStream(std::move(in_stream), &clock_);
|
||||||
|
|
||||||
|
// The starting pts of the input should be irrelevant.
|
||||||
|
proxy_stream->set_ts_offset(180000, std::numeric_limits<int>::max());
|
||||||
|
|
||||||
|
EXPECT_CALL(video_source_, OpenRtspRaw("rtsp://foo:bar@test-camera/main", _))
|
||||||
|
.WillOnce(Return(proxy_stream))
|
||||||
|
.WillOnce(Invoke(this, &StreamTest::Shutdown));
|
||||||
|
stream.Run();
|
||||||
|
|
||||||
|
// Compare frame-by-frame.
|
||||||
|
// Note below that while the rotation is scheduled to happen near 5-second
|
||||||
|
// boundaries (such as 2016-04-26 00:00:05), it gets deferred until the next
|
||||||
|
// key frame, which in this case is 00:00:07.
|
||||||
|
EXPECT_THAT(stream.GetFilesForTesting(),
|
||||||
|
testing::ElementsAre("20150426000000_test.mp4",
|
||||||
|
"20150426000007_test.mp4"));
|
||||||
|
EXPECT_THAT(GetFrames("20150426000000_test.mp4"),
|
||||||
|
testing::ElementsAre(
|
||||||
|
Frame(true, 0, 90379), Frame(false, 90379, 89884),
|
||||||
|
Frame(false, 180263, 89749), Frame(false, 270012, 89981),
|
||||||
|
Frame(true, 359993, 90055),
|
||||||
|
Frame(false, 450048,
|
||||||
|
89967), // pts_time 5.000533, past rotation time.
|
||||||
|
Frame(false, 540015, 90021),
|
||||||
|
Frame(false, 630036,
|
||||||
|
90000))); // XXX: duration=89958 would be better!
|
||||||
|
EXPECT_THAT(
|
||||||
|
GetFrames("20150426000007_test.mp4"),
|
||||||
|
testing::ElementsAre(Frame(true, 0, 90011), Frame(false, 90011, 90000)));
|
||||||
|
// Note that the final "90000" duration is ffmpeg's estimate based on frame
|
||||||
|
// rate. For non-final packets, the correct duration gets written based on
|
||||||
|
// the next packet's timestamp. The same currently applies to the first
|
||||||
|
// written segment---it uses an estimated time, not the real time until the
|
||||||
|
// next packet. This probably should be fixed...
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(StreamTest, NonIncreasingTimestamp) {
|
||||||
|
Stream stream(&signal_, config_, &env_, config_.camera(0));
|
||||||
|
std::string error_message;
|
||||||
|
ASSERT_TRUE(stream.Init(&error_message)) << error_message;
|
||||||
|
auto in_stream = GetRealVideoSource()->OpenFile("../src/testdata/clip.mp4",
|
||||||
|
&error_message);
|
||||||
|
ASSERT_TRUE(in_stream != nullptr) << error_message;
|
||||||
|
auto *proxy_stream =
|
||||||
|
new ProxyingInputVideoPacketStream(std::move(in_stream), &clock_);
|
||||||
|
proxy_stream->set_ts_offset(12345678, 1);
|
||||||
|
EXPECT_CALL(video_source_, OpenRtspRaw("rtsp://foo:bar@test-camera/main", _))
|
||||||
|
.WillOnce(Return(proxy_stream))
|
||||||
|
.WillOnce(Invoke(this, &StreamTest::Shutdown));
|
||||||
|
|
||||||
|
{
|
||||||
|
ScopedMockLog log;
|
||||||
|
EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
|
||||||
|
EXPECT_CALL(log,
|
||||||
|
Log(_, _, HasSubstr("Rejecting non-increasing pts=90379")));
|
||||||
|
log.Start();
|
||||||
|
stream.Run();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The output file should still be added to the file manager, with the one
|
||||||
|
// packet that made it.
|
||||||
|
EXPECT_THAT(stream.GetFilesForTesting(),
|
||||||
|
testing::ElementsAre("20150426000000_test.mp4"));
|
||||||
|
EXPECT_THAT(
|
||||||
|
GetFrames("20150426000000_test.mp4"),
|
||||||
|
testing::ElementsAre(Frame(true, 0, 90000))); // estimated duration.
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(StreamTest, RetryOnInputError) {
|
||||||
|
Stream stream(&signal_, config_, &env_, config_.camera(0));
|
||||||
|
std::string error_message;
|
||||||
|
ASSERT_TRUE(stream.Init(&error_message)) << error_message;
|
||||||
|
|
||||||
|
auto in_stream_1 = GetRealVideoSource()->OpenFile("../src/testdata/clip.mp4",
|
||||||
|
&error_message);
|
||||||
|
ASSERT_TRUE(in_stream_1 != nullptr) << error_message;
|
||||||
|
auto *proxy_stream_1 =
|
||||||
|
new ProxyingInputVideoPacketStream(std::move(in_stream_1), &clock_);
|
||||||
|
proxy_stream_1->set_pkts(1);
|
||||||
|
|
||||||
|
auto in_stream_2 = GetRealVideoSource()->OpenFile("../src/testdata/clip.mp4",
|
||||||
|
&error_message);
|
||||||
|
ASSERT_TRUE(in_stream_2 != nullptr) << error_message;
|
||||||
|
auto *proxy_stream_2 =
|
||||||
|
new ProxyingInputVideoPacketStream(std::move(in_stream_2), &clock_);
|
||||||
|
proxy_stream_2->set_pkts(1);
|
||||||
|
|
||||||
|
EXPECT_CALL(video_source_, OpenRtspRaw("rtsp://foo:bar@test-camera/main", _))
|
||||||
|
.WillOnce(Return(proxy_stream_1))
|
||||||
|
.WillOnce(Return(proxy_stream_2))
|
||||||
|
.WillOnce(Invoke(this, &StreamTest::Shutdown));
|
||||||
|
stream.Run();
|
||||||
|
|
||||||
|
// Each attempt should have resulted in a file with one packet.
|
||||||
|
EXPECT_THAT(stream.GetFilesForTesting(),
|
||||||
|
testing::ElementsAre("20150426000000_test.mp4",
|
||||||
|
"20150426000001_test.mp4"));
|
||||||
|
EXPECT_THAT(GetFrames("20150426000000_test.mp4"),
|
||||||
|
testing::ElementsAre(Frame(true, 0, 90000)));
|
||||||
|
EXPECT_THAT(GetFrames("20150426000001_test.mp4"),
|
||||||
|
testing::ElementsAre(Frame(true, 0, 90000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(StreamTest, DiscardInitialNonKeyFrames) {
|
||||||
|
Stream stream(&signal_, config_, &env_, config_.camera(0));
|
||||||
|
std::string error_message;
|
||||||
|
ASSERT_TRUE(stream.Init(&error_message)) << error_message;
|
||||||
|
auto in_stream = GetRealVideoSource()->OpenFile("../src/testdata/clip.mp4",
|
||||||
|
&error_message);
|
||||||
|
ASSERT_TRUE(in_stream != nullptr) << error_message;
|
||||||
|
|
||||||
|
// Discard the initial key frame packet.
|
||||||
|
VideoPacket dummy;
|
||||||
|
ASSERT_TRUE(in_stream->GetNext(&dummy, &error_message)) << error_message;
|
||||||
|
|
||||||
|
auto *proxy_stream =
|
||||||
|
new ProxyingInputVideoPacketStream(std::move(in_stream), &clock_);
|
||||||
|
EXPECT_CALL(video_source_, OpenRtspRaw("rtsp://foo:bar@test-camera/main", _))
|
||||||
|
.WillOnce(Return(proxy_stream))
|
||||||
|
.WillOnce(Invoke(this, &StreamTest::Shutdown));
|
||||||
|
stream.Run();
|
||||||
|
|
||||||
|
// Skipped: initial key frame packet (duration 90379)
|
||||||
|
// Ignored: duration 89884, 89749, 89981 (total pts time: 2.99571... sec)
|
||||||
|
// Thus, the first output file should start at 00:00:02.
|
||||||
|
EXPECT_THAT(stream.GetFilesForTesting(),
|
||||||
|
testing::ElementsAre("20150426000002_test.mp4",
|
||||||
|
"20150426000006_test.mp4"));
|
||||||
|
EXPECT_THAT(
|
||||||
|
GetFrames("20150426000002_test.mp4"),
|
||||||
|
testing::ElementsAre(
|
||||||
|
Frame(true, 0, 90055),
|
||||||
|
Frame(false, 90055, 89967), // pts_time 5.000533, past rotation time.
|
||||||
|
Frame(false, 180022, 90021),
|
||||||
|
Frame(false, 270043,
|
||||||
|
90000))); // XXX: duration=89958 would be better!
|
||||||
|
EXPECT_THAT(
|
||||||
|
GetFrames("20150426000006_test.mp4"),
|
||||||
|
testing::ElementsAre(Frame(true, 0, 90011), Frame(false, 90011, 90000)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: test output stream error (on open, writing packet, closing).
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
FLAGS_alsologtostderr = true;
|
||||||
|
google::ParseCommandLineFlags(&argc, &argv, true);
|
||||||
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
google::InitGoogleLogging(argv[0]);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
|
@ -0,0 +1,551 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// moonfire-nvr.cc: implementation of moonfire-nvr.h.
|
||||||
|
|
||||||
|
#define _BSD_SOURCE // for timegm(3).
|
||||||
|
|
||||||
|
#include "moonfire-nvr.h"
|
||||||
|
|
||||||
|
#include <dirent.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <re2/re2.h>
|
||||||
|
|
||||||
|
#include "filesystem.h"
|
||||||
|
#include "http.h"
|
||||||
|
#include "string.h"
|
||||||
|
#include "time.h"
|
||||||
|
|
||||||
|
using std::string;
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
const char kFilenameSuffix[] = ".mp4";
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
FileManager::FileManager(const std::string &short_name, const std::string &path,
|
||||||
|
uint64_t byte_limit)
|
||||||
|
: short_name_(short_name), path_(path), byte_limit_(byte_limit) {}
|
||||||
|
|
||||||
|
bool FileManager::Init(std::string *error_message) {
|
||||||
|
// Create the directory if it doesn't exist.
|
||||||
|
// If the path exists, assume it is a valid directory.
|
||||||
|
if (mkdir(path_.c_str(), 0700) < 0 && errno != EEXIST) {
|
||||||
|
int err = errno;
|
||||||
|
*error_message = StrCat("Unable to create ", path_, ": ", strerror(err));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ok = true;
|
||||||
|
|
||||||
|
auto file_fn = [this, &ok, error_message](const dirent *ent) {
|
||||||
|
string filename(ent->d_name);
|
||||||
|
if (ent->d_type != DT_REG) {
|
||||||
|
VLOG(1) << short_name_ << ": Ignoring non-plain file " << filename;
|
||||||
|
return IterationControl::kContinue;
|
||||||
|
}
|
||||||
|
if (!re2::StringPiece(filename).ends_with(kFilenameSuffix)) {
|
||||||
|
VLOG(1) << short_name_ << ": Ignoring non-matching file " << filename
|
||||||
|
<< " of size " << ent->d_reclen;
|
||||||
|
return IterationControl::kContinue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!AddFile(filename, error_message)) {
|
||||||
|
ok = false;
|
||||||
|
return IterationControl::kBreak; // no point in doing more.
|
||||||
|
}
|
||||||
|
return IterationControl::kContinue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!DirForEach(path_, file_fn, error_message)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FileManager::Rotate(std::string *error_message) {
|
||||||
|
mu_.lock();
|
||||||
|
while (total_bytes_ > byte_limit_) {
|
||||||
|
CHECK(!files_.empty()) << "total_bytes_=" << total_bytes_
|
||||||
|
<< " vs retain=" << byte_limit_;
|
||||||
|
auto it = files_.begin();
|
||||||
|
const string filename = it->first;
|
||||||
|
int64_t size = it->second.st_size;
|
||||||
|
|
||||||
|
// Release the lock while doing (potentially slow) I/O.
|
||||||
|
// Don't mark the file as deleted yet, so that a simultaneous Rotate() call
|
||||||
|
// won't return prematurely.
|
||||||
|
mu_.unlock();
|
||||||
|
string fpath = StrCat(path_, "/", filename);
|
||||||
|
if (unlink(fpath.c_str()) == 0) {
|
||||||
|
LOG(INFO) << short_name_ << ": Deleted " << filename << " to reclaim "
|
||||||
|
<< size << " bytes.";
|
||||||
|
} else if (errno == ENOENT) {
|
||||||
|
// This may have happened due to a racing Rotate() call.
|
||||||
|
// In any case, the file is gone, so proceed to mark it as such.
|
||||||
|
LOG(INFO) << short_name_ << ": File " << filename
|
||||||
|
<< " was already deleted.";
|
||||||
|
} else {
|
||||||
|
int err = errno;
|
||||||
|
*error_message =
|
||||||
|
StrCat("unlink failed on ", filename, ": ", strerror(err));
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note that the file has been deleted.
|
||||||
|
mu_.lock();
|
||||||
|
if (!files_.empty()) {
|
||||||
|
it = files_.begin();
|
||||||
|
if (it->first == filename) {
|
||||||
|
size = it->second.st_size;
|
||||||
|
files_.erase(it);
|
||||||
|
CHECK_GE(total_bytes_, size);
|
||||||
|
total_bytes_ -= size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int64_t total_bytes_copy = total_bytes_;
|
||||||
|
mu_.unlock();
|
||||||
|
LOG(INFO) << short_name_ << ": Path " << path_ << " total size is "
|
||||||
|
<< total_bytes_copy << ", within limit of " << byte_limit_;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FileManager::AddFile(const std::string &filename,
|
||||||
|
std::string *error_message) {
|
||||||
|
struct stat buf;
|
||||||
|
string fpath = StrCat(path_, "/", filename);
|
||||||
|
if (lstat(fpath.c_str(), &buf) != 0) {
|
||||||
|
int err = errno;
|
||||||
|
*error_message = StrCat("lstat on ", fpath, " failed: ", strerror(err));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
VLOG(1) << short_name_ << ": adding file " << filename << " size "
|
||||||
|
<< buf.st_size;
|
||||||
|
std::lock_guard<std::mutex> lock(mu_);
|
||||||
|
CHECK_GE(buf.st_size, 0) << fpath;
|
||||||
|
uint64_t size = buf.st_size;
|
||||||
|
if (!files_.emplace(filename, std::move(buf)).second) {
|
||||||
|
*error_message = StrCat("filename ", filename, " already present.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
total_bytes_ += size;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileManager::ForEachFile(FileManager::FileCallback fn) const {
|
||||||
|
std::lock_guard<std::mutex> lock(mu_);
|
||||||
|
for (const auto &f : files_) {
|
||||||
|
fn(f.first, f.second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FileManager::Lookup(const std::string &filename,
|
||||||
|
struct stat *statbuf) const {
|
||||||
|
std::lock_guard<std::mutex> lock(mu_);
|
||||||
|
const auto it = files_.find(filename);
|
||||||
|
if (it != files_.end()) {
|
||||||
|
*statbuf = it->second;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Stream::Init(std::string *error_message) {
|
||||||
|
// Validate configuration.
|
||||||
|
if (!IsWord(camera_.short_name())) {
|
||||||
|
*error_message = StrCat("Camera name ", camera_.short_name(), " invalid.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (rotate_interval_ <= 0) {
|
||||||
|
*error_message = StrCat("Rotate interval for ", camera_.short_name(),
|
||||||
|
" must be positive.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return manager_.Init(error_message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call from dedicated thread. Runs until shutdown requested.
|
||||||
|
void Stream::Run() {
|
||||||
|
std::string error_message;
|
||||||
|
|
||||||
|
// Do an initial rotation so that if retain_bytes has been reduced, the
|
||||||
|
// bulk deletion happens now, rather than while an input stream is open.
|
||||||
|
if (!manager_.Rotate(&error_message)) {
|
||||||
|
LOG(WARNING) << short_name()
|
||||||
|
<< ": initial rotation failed: " << error_message;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (!signal_->ShouldShutdown()) {
|
||||||
|
if (in_ == nullptr && !OpenInput(&error_message)) {
|
||||||
|
LOG(WARNING) << short_name()
|
||||||
|
<< ": Failed to open input; sleeping before retrying: "
|
||||||
|
<< error_message;
|
||||||
|
env_->clock->Sleep({1, 0});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG(INFO) << short_name() << ": Calling ProcessPackets.";
|
||||||
|
ProcessPacketsResult res = ProcessPackets(&error_message);
|
||||||
|
if (res == kInputError) {
|
||||||
|
CloseOutput();
|
||||||
|
in_.reset();
|
||||||
|
LOG(WARNING) << short_name()
|
||||||
|
<< ": Input error; sleeping before retrying: "
|
||||||
|
<< error_message;
|
||||||
|
env_->clock->Sleep({1, 0});
|
||||||
|
continue;
|
||||||
|
} else if (res == kOutputError) {
|
||||||
|
CloseOutput();
|
||||||
|
LOG(WARNING) << short_name()
|
||||||
|
<< ": Output error; sleeping before retrying: "
|
||||||
|
<< error_message;
|
||||||
|
env_->clock->Sleep({1, 0});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CloseOutput();
|
||||||
|
}
|
||||||
|
|
||||||
|
Stream::ProcessPacketsResult Stream::ProcessPackets(
|
||||||
|
std::string *error_message) {
|
||||||
|
moonfire_nvr::VideoPacket pkt;
|
||||||
|
CHECK(in_ != nullptr);
|
||||||
|
CHECK(!out_.is_open());
|
||||||
|
while (!signal_->ShouldShutdown()) {
|
||||||
|
if (!in_->GetNext(&pkt, error_message)) {
|
||||||
|
if (error_message->empty()) {
|
||||||
|
*error_message = "unexpected end of stream";
|
||||||
|
}
|
||||||
|
return kInputError;
|
||||||
|
}
|
||||||
|
|
||||||
|
// With gcc 4.9 (Raspbian Jessie),
|
||||||
|
// #define AV_NOPTS_VALUE INT64_C(0x8000000000000000)
|
||||||
|
// produces an unsigned value. Argh. Work around.
|
||||||
|
static const int64_t kAvNoptsValue = AV_NOPTS_VALUE;
|
||||||
|
if (pkt.pkt()->pts == kAvNoptsValue || pkt.pkt()->dts == kAvNoptsValue) {
|
||||||
|
*error_message = "Rejecting packet with missing pts/dts";
|
||||||
|
return kInputError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pkt.pkt()->pts != pkt.pkt()->dts) {
|
||||||
|
*error_message =
|
||||||
|
StrCat("Rejecting packet with pts=", pkt.pkt()->pts, " != dts=",
|
||||||
|
pkt.pkt()->dts, "; expecting only I or P frames.");
|
||||||
|
return kInputError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pkt.pkt()->pts < min_next_pts_) {
|
||||||
|
*error_message = StrCat("Rejecting non-increasing pts=", pkt.pkt()->pts,
|
||||||
|
"; expected at least ", min_next_pts_);
|
||||||
|
return kInputError;
|
||||||
|
}
|
||||||
|
min_next_pts_ = pkt.pkt()->pts + 1;
|
||||||
|
|
||||||
|
frame_realtime_ = env_->clock->Now();
|
||||||
|
|
||||||
|
if (out_.is_open() && frame_realtime_.tv_sec >= rotate_time_ &&
|
||||||
|
pkt.is_key()) {
|
||||||
|
LOG(INFO) << short_name() << ": Reached rotation time; closing "
|
||||||
|
<< out_file_ << ".";
|
||||||
|
VLOG(2) << short_name() << ": (Rotation time=" << rotate_time_
|
||||||
|
<< " vs current time=" << frame_realtime_.tv_sec << ")";
|
||||||
|
out_.Close();
|
||||||
|
|
||||||
|
if (!manager_.AddFile(out_file_, error_message)) {
|
||||||
|
return kOutputError;
|
||||||
|
}
|
||||||
|
} else if (out_.is_open()) {
|
||||||
|
VLOG(2) << short_name() << ": Rotation time=" << rotate_time_
|
||||||
|
<< " vs current time=" << frame_realtime_.tv_sec;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Discard the initial, non-key frames from the input.
|
||||||
|
if (!seen_key_frame_ && !pkt.is_key()) {
|
||||||
|
continue;
|
||||||
|
} else if (!seen_key_frame_) {
|
||||||
|
seen_key_frame_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!out_.is_open()) {
|
||||||
|
start_pts_ = pkt.pts();
|
||||||
|
if (!OpenOutput(error_message)) {
|
||||||
|
return kOutputError;
|
||||||
|
}
|
||||||
|
rotate_time_ = frame_realtime_.tv_sec -
|
||||||
|
(frame_realtime_.tv_sec % rotate_interval_) +
|
||||||
|
rotate_interval_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// In the output stream, the pts and dts should start at 0.
|
||||||
|
pkt.pkt()->pts -= start_pts_;
|
||||||
|
pkt.pkt()->dts -= start_pts_;
|
||||||
|
|
||||||
|
// The input's byte position and stream index aren't relevant to the
|
||||||
|
// output.
|
||||||
|
pkt.pkt()->pos = -1;
|
||||||
|
pkt.pkt()->stream_index = 0;
|
||||||
|
|
||||||
|
if (!out_.Write(&pkt, error_message)) {
|
||||||
|
return kOutputError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return kStopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Stream::OpenInput(std::string *error_message) {
|
||||||
|
CHECK(in_ == nullptr);
|
||||||
|
string url = StrCat("rtsp://", camera_.user(), ":", camera_.password(), "@",
|
||||||
|
camera_.host(), camera_.main_rtsp_path());
|
||||||
|
string redacted_url = StrCat("rtsp://", camera_.user(), ":redacted@",
|
||||||
|
camera_.host(), camera_.main_rtsp_path());
|
||||||
|
LOG(INFO) << short_name() << ": Opening input: " << redacted_url;
|
||||||
|
in_ = env_->video_source->OpenRtsp(url, error_message);
|
||||||
|
min_next_pts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
seen_key_frame_ = false;
|
||||||
|
return in_ != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Stream::CloseOutput() {
|
||||||
|
out_.Close();
|
||||||
|
// TODO: should know if the file was written or not.
|
||||||
|
std::string error_message;
|
||||||
|
if (!manager_.AddFile(out_file_, &error_message)) {
|
||||||
|
VLOG(1) << short_name() << ": AddFile on recently closed output file "
|
||||||
|
<< out_file_ << "failed; the file may never have been written: "
|
||||||
|
<< error_message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Stream::MakeOutputFilename() {
|
||||||
|
const size_t kTimeBufLen = sizeof("YYYYmmDDHHMMSS");
|
||||||
|
char formatted_time[kTimeBufLen];
|
||||||
|
struct tm mytm;
|
||||||
|
gmtime_r(&frame_realtime_.tv_sec, &mytm);
|
||||||
|
strftime(formatted_time, kTimeBufLen, "%Y%m%d%H%M%S", &mytm);
|
||||||
|
return StrCat(formatted_time, "_", camera_.short_name(), kFilenameSuffix);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Stream::OpenOutput(std::string *error_message) {
|
||||||
|
if (!manager_.Rotate(error_message)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
CHECK(!out_.is_open());
|
||||||
|
string filename = MakeOutputFilename();
|
||||||
|
if (!out_.OpenFile(StrCat(camera_path_, "/", filename), *in_,
|
||||||
|
error_message)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
LOG(INFO) << short_name() << ": Opened output " << filename
|
||||||
|
<< ", using start_pts=" << start_pts_
|
||||||
|
<< ", input timebase=" << in_->stream()->time_base.num << "/"
|
||||||
|
<< in_->stream()->time_base.den
|
||||||
|
<< ", output timebase=" << out_.time_base().num << "/"
|
||||||
|
<< out_.time_base().den;
|
||||||
|
out_file_ = std::move(filename);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Stream::HttpCallbackForDirectory(evhttp_request *req) {
|
||||||
|
EvBuffer buf;
|
||||||
|
buf.AddPrintf(
|
||||||
|
"<!DOCTYPE html>\n"
|
||||||
|
"<html>\n"
|
||||||
|
"<head>\n"
|
||||||
|
"<title>%s camera recordings</title>\n"
|
||||||
|
"<style type=\"text/css\">\n"
|
||||||
|
"th, td { text-align: left; padding-right: 3em; }\n"
|
||||||
|
".filename { font: 90%% monospace; }\n"
|
||||||
|
"</style>\n"
|
||||||
|
"</head>\n"
|
||||||
|
"<body>\n"
|
||||||
|
"<h1>%s camera recordings</h1>\n"
|
||||||
|
"<p>%s</p>\n"
|
||||||
|
"<table>\n"
|
||||||
|
"<tr><th>Filename</th><th>Start</th><th>End</th></tr>\n",
|
||||||
|
// short_name passed IsWord(); there's no need to escape it.
|
||||||
|
camera_.short_name().c_str(), camera_.short_name().c_str(),
|
||||||
|
EscapeHtml(camera_.description()).c_str());
|
||||||
|
manager_.ForEachFile(
|
||||||
|
[&buf](const std::string &filename, const struct stat &statbuf) {
|
||||||
|
// Attempt to make a pretty version of the timestamp embedded in the
|
||||||
|
// filename: with separators and in the local time zone. If this fails,
|
||||||
|
// just leave it blank.
|
||||||
|
string pretty_start_time;
|
||||||
|
struct tm mytm;
|
||||||
|
memset(&mytm, 0, sizeof(mytm));
|
||||||
|
const size_t kTimeBufLen = 50;
|
||||||
|
char tmbuf[kTimeBufLen];
|
||||||
|
static const RE2 kFilenameRe(
|
||||||
|
// YYYY mm DD HH MM SS
|
||||||
|
"^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})_");
|
||||||
|
if (RE2::PartialMatch(filename, kFilenameRe, &mytm.tm_year,
|
||||||
|
&mytm.tm_mon, &mytm.tm_mday, &mytm.tm_hour,
|
||||||
|
&mytm.tm_min, &mytm.tm_sec)) {
|
||||||
|
mytm.tm_year -= 1900;
|
||||||
|
mytm.tm_mon--;
|
||||||
|
time_t start = timegm(&mytm);
|
||||||
|
localtime_r(&start, &mytm);
|
||||||
|
strftime(tmbuf, kTimeBufLen, "%a, %d %b %Y %H:%M:%S %Z", &mytm);
|
||||||
|
pretty_start_time = tmbuf;
|
||||||
|
}
|
||||||
|
string pretty_end_time;
|
||||||
|
localtime_r(&statbuf.st_mtime, &mytm);
|
||||||
|
strftime(tmbuf, kTimeBufLen, "%a, %d %b %Y %H:%M:%S %Z", &mytm);
|
||||||
|
pretty_end_time = tmbuf;
|
||||||
|
|
||||||
|
buf.AddPrintf(
|
||||||
|
"<tr><td class=\"filename\"><a href=\"%s\">%s</td>"
|
||||||
|
"<td>%s</td><td>%s</td></tr>\n",
|
||||||
|
filename.c_str(), filename.c_str(),
|
||||||
|
EscapeHtml(pretty_start_time).c_str(),
|
||||||
|
EscapeHtml(pretty_end_time).c_str());
|
||||||
|
});
|
||||||
|
buf.AddPrintf("</table>\n</html>\n");
|
||||||
|
evhttp_send_reply(req, HTTP_OK, "OK", buf.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> Stream::GetFilesForTesting() {
|
||||||
|
std::vector<std::string> files;
|
||||||
|
manager_.ForEachFile(
|
||||||
|
[&files](const std::string &filename, const struct stat &statbuf) {
|
||||||
|
files.push_back(filename);
|
||||||
|
});
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Stream::HttpCallbackForFile(evhttp_request *req, const string &filename) {
|
||||||
|
struct stat s;
|
||||||
|
if (!manager_.Lookup(filename, &s)) {
|
||||||
|
return evhttp_send_error(req, HTTP_NOTFOUND, "File not found.");
|
||||||
|
}
|
||||||
|
HttpServeFile(req, "video/mp4", StrCat(camera_path_, "/", filename), s);
|
||||||
|
}
|
||||||
|
|
||||||
|
Nvr::Nvr() {
|
||||||
|
env_.clock = GetRealClock();
|
||||||
|
env_.video_source = GetRealVideoSource();
|
||||||
|
}
|
||||||
|
|
||||||
|
Nvr::~Nvr() {
|
||||||
|
signal_.Shutdown();
|
||||||
|
for (auto &thread : stream_threads_) {
|
||||||
|
thread.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Nvr::Init(const moonfire_nvr::Config &config, std::string *error_msg) {
|
||||||
|
if (config.base_path().empty()) {
|
||||||
|
*error_msg = "base_path must be configured.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &camera : config.camera()) {
|
||||||
|
streams_.emplace_back(new Stream(&signal_, config, &env_, camera));
|
||||||
|
if (!streams_.back()->Init(error_msg)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto &stream : streams_) {
|
||||||
|
stream_threads_.emplace_back([&stream]() { stream->Run(); });
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nvr::HttpCallback(evhttp_request *req) {
|
||||||
|
if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
|
||||||
|
return evhttp_send_error(req, HTTP_BADMETHOD, "only GET allowed");
|
||||||
|
}
|
||||||
|
|
||||||
|
evhttp_uri *uri = evhttp_uri_parse(evhttp_request_get_uri(req));
|
||||||
|
if (uri == nullptr || evhttp_uri_get_path(uri) == nullptr) {
|
||||||
|
return evhttp_send_error(req, HTTP_INTERNAL, "Failed to parse URI.");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string uri_path = evhttp_uri_get_path(uri);
|
||||||
|
evhttp_uri_free(uri);
|
||||||
|
uri = nullptr;
|
||||||
|
|
||||||
|
if (uri_path == "/") {
|
||||||
|
return HttpCallbackForTopLevel(req);
|
||||||
|
} else if (!re2::StringPiece(uri_path).starts_with("/c/")) {
|
||||||
|
return evhttp_send_error(req, HTTP_NOTFOUND, "Not found.");
|
||||||
|
}
|
||||||
|
size_t camera_name_start = strlen("/c/");
|
||||||
|
size_t next_slash = uri_path.find('/', camera_name_start);
|
||||||
|
if (next_slash == std::string::npos) {
|
||||||
|
CHECK_EQ(0, evhttp_add_header(evhttp_request_get_output_headers(req),
|
||||||
|
"Location", StrCat(uri_path, "/").c_str()));
|
||||||
|
return evhttp_send_reply(req, HTTP_MOVEPERM, "OK", EvBuffer().get());
|
||||||
|
}
|
||||||
|
re2::StringPiece camera_name =
|
||||||
|
uri_path.substr(camera_name_start, next_slash - camera_name_start);
|
||||||
|
for (const auto &stream : streams_) {
|
||||||
|
if (stream->camera_name() == camera_name) {
|
||||||
|
if (uri_path.size() == next_slash + 1) {
|
||||||
|
return stream->HttpCallbackForDirectory(req);
|
||||||
|
} else {
|
||||||
|
return stream->HttpCallbackForFile(req,
|
||||||
|
uri_path.substr(next_slash + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return evhttp_send_error(req, HTTP_NOTFOUND, "No such camera.");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Nvr::HttpCallbackForTopLevel(evhttp_request *req) {
|
||||||
|
EvBuffer buf;
|
||||||
|
buf.Add("<ul>\n");
|
||||||
|
for (const auto &stream : streams_) {
|
||||||
|
// Camera name passed IsWord; there's no need to escape it.
|
||||||
|
const string &name = stream->camera_name();
|
||||||
|
string escaped_description = EscapeHtml(stream->camera_description());
|
||||||
|
buf.AddPrintf("<li><a href=\"/c/%s/\">%s</a>: %s</li>\n", name.c_str(),
|
||||||
|
name.c_str(), escaped_description.c_str());
|
||||||
|
}
|
||||||
|
buf.Add("</ul>\n");
|
||||||
|
return evhttp_send_reply(req, HTTP_OK, "OK", buf.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,236 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// moonfire-nvr.h: main digital video recorder components.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_NVR_H
|
||||||
|
#define MOONFIRE_NVR_NVR_H
|
||||||
|
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include <event2/http.h>
|
||||||
|
|
||||||
|
#include "config.pb.h"
|
||||||
|
#include "ffmpeg.h"
|
||||||
|
#include "time.h"
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
// A signal that all streams associated with an Nvr should shut down.
|
||||||
|
class ShutdownSignal {
|
||||||
|
public:
|
||||||
|
ShutdownSignal() {}
|
||||||
|
ShutdownSignal(const ShutdownSignal &) = delete;
|
||||||
|
ShutdownSignal &operator=(const ShutdownSignal &) = delete;
|
||||||
|
|
||||||
|
void Shutdown() { shutdown_.store(true, std::memory_order_relaxed); }
|
||||||
|
|
||||||
|
bool ShouldShutdown() const {
|
||||||
|
return shutdown_.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::atomic_bool shutdown_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Environment for streams to use. This is supplied for testability.
|
||||||
|
struct Environment {
|
||||||
|
WallClock *clock = nullptr;
|
||||||
|
VideoSource *video_source = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Delete old ".mp4" files within a specified directory, keeping them within a
|
||||||
|
// byte limit. In particular, "old" means "lexographically smaller filename".
|
||||||
|
// Thread-safe.
|
||||||
|
//
|
||||||
|
// On startup, FileManager reads the directory and stats every matching file.
|
||||||
|
// Afterward, it assumes that (1) it is informed of every added file and (2)
|
||||||
|
// files are deleted only through calls to Rotate.
|
||||||
|
class FileManager {
|
||||||
|
public:
|
||||||
|
using FileCallback = std::function<void(const std::string &filename,
|
||||||
|
const struct stat &statbuf)>;
|
||||||
|
|
||||||
|
// |short_name| will be prepended to log messages.
|
||||||
|
FileManager(const std::string &short_name, const std::string &path,
|
||||||
|
uint64_t byte_limit);
|
||||||
|
FileManager(const FileManager &) = delete;
|
||||||
|
FileManager &operator=(const FileManager &) = delete;
|
||||||
|
|
||||||
|
// Initialize the FileManager by examining existing directory contents.
|
||||||
|
// Create the directory if necessary.
|
||||||
|
bool Init(std::string *error_message);
|
||||||
|
|
||||||
|
// Delete files to go back within the byte limit if necessary.
|
||||||
|
bool Rotate(std::string *error_message);
|
||||||
|
|
||||||
|
// Note that a file has been added. This may bring the FileManager over the
|
||||||
|
// byte limit; no files will be deleted immediately.
|
||||||
|
bool AddFile(const std::string &filename, std::string *error_message);
|
||||||
|
|
||||||
|
// Call |fn| for each file, while holding the lock.
|
||||||
|
void ForEachFile(FileCallback) const;
|
||||||
|
|
||||||
|
// Look up a file.
|
||||||
|
// If |filename| is known to the manager, returns true and fills |statbuf|.
|
||||||
|
// Otherwise returns false.
|
||||||
|
bool Lookup(const std::string &filename, struct stat *statbuf) const;
|
||||||
|
|
||||||
|
int64_t total_bytes() const {
|
||||||
|
std::lock_guard<std::mutex> lock(mu_);
|
||||||
|
return total_bytes_;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
const std::string short_name_;
|
||||||
|
const std::string path_;
|
||||||
|
const uint64_t byte_limit_;
|
||||||
|
|
||||||
|
mutable std::mutex mu_;
|
||||||
|
std::map<std::string, struct stat> files_;
|
||||||
|
uint64_t total_bytes_ = 0; // total bytes of all |files_|.
|
||||||
|
};
|
||||||
|
|
||||||
|
// A single video stream, currently always a camera's "main" (as opposed to
|
||||||
|
// "sub") stream. Methods are thread-compatible rather than thread-safe; the
|
||||||
|
// Nvr should call Init + Run in a dedicated thread.
|
||||||
|
class Stream {
|
||||||
|
public:
|
||||||
|
Stream(const ShutdownSignal *signal, const moonfire_nvr::Config &config,
|
||||||
|
const Environment *env, const moonfire_nvr::Camera &camera)
|
||||||
|
: signal_(signal),
|
||||||
|
env_(env),
|
||||||
|
camera_path_(config.base_path() + "/" + camera.short_name()),
|
||||||
|
rotate_interval_(config.rotate_sec()),
|
||||||
|
camera_(camera),
|
||||||
|
manager_(camera_.short_name(), camera_path_, camera.retain_bytes()) {}
|
||||||
|
Stream(const Stream &) = delete;
|
||||||
|
Stream &operator=(const Stream &) = delete;
|
||||||
|
|
||||||
|
// Call once on startup, before Run().
|
||||||
|
bool Init(std::string *error_message);
|
||||||
|
|
||||||
|
const std::string &camera_name() const { return camera_.short_name(); }
|
||||||
|
const std::string &camera_description() const {
|
||||||
|
return camera_.description();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call from dedicated thread. Runs until shutdown requested.
|
||||||
|
void Run();
|
||||||
|
|
||||||
|
// Handle HTTP requests which have been pre-determined to be for the
|
||||||
|
// directory view of this stream or a particular file, respectively.
|
||||||
|
// Thread-safe.
|
||||||
|
void HttpCallbackForDirectory(evhttp_request *req);
|
||||||
|
void HttpCallbackForFile(evhttp_request *req, const std::string &filename);
|
||||||
|
|
||||||
|
std::vector<std::string> GetFilesForTesting();
|
||||||
|
|
||||||
|
private:
|
||||||
|
enum ProcessPacketsResult { kInputError, kOutputError, kStopped };
|
||||||
|
|
||||||
|
const std::string &short_name() const { return camera_.short_name(); }
|
||||||
|
|
||||||
|
ProcessPacketsResult ProcessPackets(std::string *error_message);
|
||||||
|
bool OpenInput(std::string *error_message);
|
||||||
|
void CloseOutput();
|
||||||
|
std::string MakeOutputFilename();
|
||||||
|
bool OpenOutput(std::string *error_message);
|
||||||
|
bool RotateFiles();
|
||||||
|
bool Stat(const std::string &filename, struct stat *file,
|
||||||
|
std::string *error_message);
|
||||||
|
|
||||||
|
const ShutdownSignal *signal_;
|
||||||
|
const Environment *env_;
|
||||||
|
const std::string camera_path_;
|
||||||
|
const int32_t rotate_interval_;
|
||||||
|
const moonfire_nvr::Camera camera_;
|
||||||
|
|
||||||
|
FileManager manager_; // thread-safe.
|
||||||
|
|
||||||
|
//
|
||||||
|
// State below is used only by the thread in Run().
|
||||||
|
//
|
||||||
|
|
||||||
|
std::unique_ptr<moonfire_nvr::InputVideoPacketStream> in_;
|
||||||
|
int64_t min_next_pts_ = std::numeric_limits<int64_t>::min();
|
||||||
|
bool seen_key_frame_ = false;
|
||||||
|
|
||||||
|
// Current output segment.
|
||||||
|
moonfire_nvr::OutputVideoPacketStream out_;
|
||||||
|
time_t rotate_time_ = 0; // rotate when frame_realtime_ >= rotate_time_.
|
||||||
|
std::string out_file_; // current output filename.
|
||||||
|
int64_t start_pts_ = -1;
|
||||||
|
|
||||||
|
// Packet-to-packet state.
|
||||||
|
struct timespec frame_realtime_ = {0, 0};
|
||||||
|
};
|
||||||
|
|
||||||
|
// The main network video recorder, which manages a collection of streams.
|
||||||
|
class Nvr {
|
||||||
|
public:
|
||||||
|
Nvr();
|
||||||
|
Nvr(const Nvr &) = delete;
|
||||||
|
Nvr &operator=(const Nvr &) = delete;
|
||||||
|
|
||||||
|
// Shut down, blocking for outstanding streams.
|
||||||
|
// Caller only has to guarantee that HttpCallback is not being called / will
|
||||||
|
// not be called again, likely by having already shut down the event loop.
|
||||||
|
~Nvr();
|
||||||
|
|
||||||
|
// Initialize the NVR. Call before any other operation.
|
||||||
|
// Verifies configuration and starts background threads to capture/rotate
|
||||||
|
// streams.
|
||||||
|
bool Init(const moonfire_nvr::Config &config, std::string *error_msg);
|
||||||
|
|
||||||
|
// Handle an HTTP request.
|
||||||
|
void HttpCallback(evhttp_request *req);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void HttpCallbackForTopLevel(evhttp_request *req);
|
||||||
|
|
||||||
|
Environment env_;
|
||||||
|
moonfire_nvr::Config config_;
|
||||||
|
std::vector<std::unique_ptr<Stream>> streams_;
|
||||||
|
std::vector<std::thread> stream_threads_;
|
||||||
|
ShutdownSignal signal_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_NVR_H
|
|
@ -0,0 +1,148 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// profiler.cc: See profiler.h.
|
||||||
|
|
||||||
|
#include "profiler.h"
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/event.h>
|
||||||
|
#include <event2/keyvalq_struct.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
#include <gperftools/profiler.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
#include "http.h"
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
const int kDefaultProfileSeconds = 30;
|
||||||
|
|
||||||
|
// Only a single CPU profile may be active at once. Track if it is active now.
|
||||||
|
bool profiling;
|
||||||
|
|
||||||
|
struct ProfileRequestContext {
|
||||||
|
#define TEMPLATE "/tmp/moonfire-nvr.profile.XXXXXX"
|
||||||
|
char filename[sizeof(TEMPLATE)] = TEMPLATE;
|
||||||
|
#undef TEMPLATE
|
||||||
|
evhttp_request *req = nullptr;
|
||||||
|
event *timer = nullptr;
|
||||||
|
int fd = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// End a CPU profile. Serve the result from the temporary file and delete it.
|
||||||
|
void EndProfileCallback(evutil_socket_t, short, void *arg) {
|
||||||
|
CHECK(profiling);
|
||||||
|
ProfilerStop();
|
||||||
|
profiling = false;
|
||||||
|
std::unique_ptr<ProfileRequestContext> ctx(
|
||||||
|
reinterpret_cast<ProfileRequestContext *>(arg));
|
||||||
|
if (unlink(ctx->filename) < 0) {
|
||||||
|
int err = errno;
|
||||||
|
LOG(WARNING) << "Unable to unlink temporary profile file: " << ctx->filename
|
||||||
|
<< ": " << strerror(err);
|
||||||
|
}
|
||||||
|
event_free(ctx->timer);
|
||||||
|
struct stat statbuf;
|
||||||
|
if (fstat(ctx->fd, &statbuf) < 0) {
|
||||||
|
close(ctx->fd);
|
||||||
|
return HttpSendError(ctx->req, HTTP_INTERNAL, "fstat: ", errno);
|
||||||
|
}
|
||||||
|
EvBuffer buf;
|
||||||
|
std::string error_message;
|
||||||
|
if (!buf.AddFile(ctx->fd, 0, statbuf.st_size, &error_message)) {
|
||||||
|
evhttp_send_error(ctx->req, HTTP_INTERNAL,
|
||||||
|
EscapeHtml(error_message).c_str());
|
||||||
|
close(ctx->fd);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
evhttp_send_reply(ctx->req, HTTP_OK, "OK", buf.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start a CPU profile. Creates a temporary file for the profiler library
|
||||||
|
// to use and schedules a call to EndProfileCallback.
|
||||||
|
void StartProfileCallback(struct evhttp_request *req, void *arg) {
|
||||||
|
auto *base = reinterpret_cast<event_base *>(arg);
|
||||||
|
if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
|
||||||
|
return evhttp_send_error(req, HTTP_BADMETHOD, "only GET allowed");
|
||||||
|
}
|
||||||
|
if (profiling) {
|
||||||
|
return evhttp_send_error(req, HTTP_SERVUNAVAIL,
|
||||||
|
"Profiling already in progress");
|
||||||
|
}
|
||||||
|
struct timeval timeout = {0, 0};
|
||||||
|
struct evkeyvalq query_options;
|
||||||
|
evhttp_parse_query(evhttp_request_get_uri(req), &query_options);
|
||||||
|
const char *seconds_value = evhttp_find_header(&query_options, "seconds");
|
||||||
|
timeout.tv_sec =
|
||||||
|
seconds_value == nullptr ? kDefaultProfileSeconds : atoi(seconds_value);
|
||||||
|
evhttp_clear_headers(&query_options);
|
||||||
|
if (timeout.tv_sec <= 0) {
|
||||||
|
return evhttp_send_error(req, HTTP_BADREQUEST, "invalid seconds");
|
||||||
|
}
|
||||||
|
|
||||||
|
auto *ctx = new ProfileRequestContext;
|
||||||
|
ctx->fd = mkstemp(ctx->filename);
|
||||||
|
if (ctx->fd < 0) {
|
||||||
|
delete ctx;
|
||||||
|
return HttpSendError(req, HTTP_INTERNAL, "mkstemp: ", errno);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ProfilerStart(ctx->filename) == 0) {
|
||||||
|
delete ctx;
|
||||||
|
return evhttp_send_error(req, HTTP_INTERNAL, "ProfilerStart failed");
|
||||||
|
}
|
||||||
|
profiling = true;
|
||||||
|
ctx->req = req;
|
||||||
|
ctx->timer = evtimer_new(base, &EndProfileCallback, ctx);
|
||||||
|
evtimer_add(ctx->timer, &timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void RegisterProfiler(event_base *base, evhttp *http) {
|
||||||
|
evhttp_set_cb(http, "/pprof/profile", &StartProfileCallback, base);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,51 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// profiler.h: support for on-demand profiling. The interface is described here:
|
||||||
|
// <https://github.com/gperftools/gperftools/blob/master/doc/pprof_remote_servers.html>
|
||||||
|
// Currently this only supports CPU profiling; heap profiling may be added
|
||||||
|
// later.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_PROFILER_H
|
||||||
|
#define MOONFIRE_NVR_PROFILER_H
|
||||||
|
|
||||||
|
#include <event2/buffer.h>
|
||||||
|
#include <event2/http.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
// Register a HTTP URI for a CPU profile with google-perftools.
|
||||||
|
// Not thread-safe, so |http| must be running on |base|, and |base| must be
|
||||||
|
// using a single thread.
|
||||||
|
void RegisterProfiler(event_base *base, evhttp *http);
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_PROFILER_H
|
|
@ -0,0 +1,104 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// string-test.cc: tests of the string.h interface.
|
||||||
|
|
||||||
|
#include <gflags/gflags.h>
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
DECLARE_bool(alsologtostderr);
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
TEST(StrCatTest, Simple) {
|
||||||
|
EXPECT_EQ("foo", StrCat("foo"));
|
||||||
|
EXPECT_EQ("foobar", StrCat("foo", "bar"));
|
||||||
|
EXPECT_EQ("foo", StrCat(std::string("foo")));
|
||||||
|
|
||||||
|
EXPECT_EQ("42", StrCat(uint64_t(42)));
|
||||||
|
EXPECT_EQ("0", StrCat(uint64_t(0)));
|
||||||
|
EXPECT_EQ("18446744073709551615",
|
||||||
|
StrCat(std::numeric_limits<uint64_t>::max()));
|
||||||
|
|
||||||
|
EXPECT_EQ("42", StrCat(int64_t(42)));
|
||||||
|
EXPECT_EQ("0", StrCat(int64_t(0)));
|
||||||
|
EXPECT_EQ("-9223372036854775808",
|
||||||
|
StrCat(std::numeric_limits<int64_t>::min()));
|
||||||
|
EXPECT_EQ("9223372036854775807", StrCat(std::numeric_limits<int64_t>::max()));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(JoinTest, Simple) {
|
||||||
|
EXPECT_EQ("", Join(std::initializer_list<std::string>(), ","));
|
||||||
|
EXPECT_EQ("a", Join(std::initializer_list<std::string>({"a"}), ","));
|
||||||
|
EXPECT_EQ("a,b", Join(std::initializer_list<const char *>({"a", "b"}), ","));
|
||||||
|
EXPECT_EQ(
|
||||||
|
"a,b,c",
|
||||||
|
Join(std::initializer_list<re2::StringPiece>({"a", "b", "c"}), ","));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(IsWordTest, Simple) {
|
||||||
|
EXPECT_TRUE(IsWord(""));
|
||||||
|
EXPECT_TRUE(IsWord("0123456789"));
|
||||||
|
EXPECT_TRUE(IsWord("abcdefghijklmnopqrstuvwxyz"));
|
||||||
|
EXPECT_TRUE(IsWord("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
|
||||||
|
EXPECT_TRUE(IsWord("_"));
|
||||||
|
|
||||||
|
EXPECT_TRUE(IsWord("4bJ_"));
|
||||||
|
|
||||||
|
EXPECT_FALSE(IsWord("/"));
|
||||||
|
EXPECT_FALSE(IsWord("abc/"));
|
||||||
|
EXPECT_FALSE(IsWord(" "));
|
||||||
|
EXPECT_FALSE(IsWord("@"));
|
||||||
|
EXPECT_FALSE(IsWord("["));
|
||||||
|
EXPECT_FALSE(IsWord("`"));
|
||||||
|
EXPECT_FALSE(IsWord("{"));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(EscapeTest, Simple) {
|
||||||
|
EXPECT_EQ("", moonfire_nvr::EscapeHtml(""));
|
||||||
|
EXPECT_EQ("no special chars", moonfire_nvr::EscapeHtml("no special chars"));
|
||||||
|
EXPECT_EQ("<tag> & text", moonfire_nvr::EscapeHtml("<tag> & text"));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
FLAGS_alsologtostderr = true;
|
||||||
|
google::ParseCommandLineFlags(&argc, &argv, true);
|
||||||
|
testing::InitGoogleTest(&argc, argv);
|
||||||
|
google::InitGoogleLogging(argv[0]);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
|
@ -0,0 +1,114 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// string.cc: See string.h.
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace internal {
|
||||||
|
|
||||||
|
StrCatPiece::StrCatPiece(uint64_t p) {
|
||||||
|
if (p == 0) {
|
||||||
|
piece_ = "0";
|
||||||
|
} else {
|
||||||
|
size_t i = sizeof(buf_);
|
||||||
|
while (p != 0) {
|
||||||
|
buf_[--i] = '0' + (p % 10);
|
||||||
|
p /= 10;
|
||||||
|
}
|
||||||
|
piece_.set(buf_ + i, sizeof(buf_) - i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
StrCatPiece::StrCatPiece(int64_t p) {
|
||||||
|
if (p == 0) {
|
||||||
|
piece_ = "0";
|
||||||
|
} else {
|
||||||
|
bool negative = p < 0;
|
||||||
|
size_t i = sizeof(buf_);
|
||||||
|
while (p != 0) {
|
||||||
|
buf_[--i] = '0' + std::abs(p % 10);
|
||||||
|
p /= 10;
|
||||||
|
}
|
||||||
|
if (negative) {
|
||||||
|
buf_[--i] = '-';
|
||||||
|
}
|
||||||
|
piece_.set(buf_ + i, sizeof(buf_) - i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace internal
|
||||||
|
|
||||||
|
bool IsWord(const std::string &str) {
|
||||||
|
for (char c : str) {
|
||||||
|
if (!(('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') ||
|
||||||
|
('a' <= c && c <= 'z') || c == '_')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string EscapeHtml(const std::string &input) {
|
||||||
|
std::string output;
|
||||||
|
output.reserve(input.size());
|
||||||
|
for (char c : input) {
|
||||||
|
switch (c) {
|
||||||
|
case '&':
|
||||||
|
output.append("&");
|
||||||
|
break;
|
||||||
|
case '<':
|
||||||
|
output.append("<");
|
||||||
|
break;
|
||||||
|
case '>':
|
||||||
|
output.append(">");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
output.push_back(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool strto64(const char *str, int base, const char **endptr, int64_t *value) {
|
||||||
|
static_assert(sizeof(int64_t) == sizeof(long long int),
|
||||||
|
"unknown memory model");
|
||||||
|
errno = 0;
|
||||||
|
*value = ::strtoll(str, const_cast<char **>(endptr), base);
|
||||||
|
return *endptr != str && errno == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,127 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// string.h: convenience methods for dealing with strings.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_STRING_H
|
||||||
|
#define MOONFIRE_NVR_STRING_H
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include <re2/stringpiece.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace internal {
|
||||||
|
|
||||||
|
// Only used within StrCat() and Join().
|
||||||
|
// Note implicit constructor, which is necessary to avoid a copy,
|
||||||
|
// though it could be wrapped in another type.
|
||||||
|
// http://stackoverflow.com/questions/34112755/can-i-avoid-a-c11-move-when-initializing-an-array/34113744
|
||||||
|
class StrCatPiece {
|
||||||
|
public:
|
||||||
|
StrCatPiece(uint64_t p);
|
||||||
|
StrCatPiece(int64_t p);
|
||||||
|
StrCatPiece(uint32_t p) : StrCatPiece(static_cast<uint64_t>(p)) {}
|
||||||
|
StrCatPiece(int32_t p) : StrCatPiece(static_cast<int64_t>(p)) {}
|
||||||
|
|
||||||
|
#ifndef __LP64__ // if sizeof(long) == sizeof(int32_t)
|
||||||
|
// Need to resolve ambiguity.
|
||||||
|
StrCatPiece(long p) : StrCatPiece(static_cast<int32_t>(p)) {}
|
||||||
|
StrCatPiece(unsigned long p) : StrCatPiece(static_cast<uint32_t>(p)) {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
StrCatPiece(re2::StringPiece p) : piece_(p) {}
|
||||||
|
|
||||||
|
StrCatPiece(const StrCatPiece &) = delete;
|
||||||
|
StrCatPiece &operator=(const StrCatPiece &) = delete;
|
||||||
|
|
||||||
|
const char *data() const { return piece_.data(); }
|
||||||
|
size_t size() const { return piece_.size(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Not allowed: ambiguous meaning.
|
||||||
|
StrCatPiece(char);
|
||||||
|
|
||||||
|
// |piece_| points either to within buf_ (numeric constructors) or to unowned
|
||||||
|
// string data (StringPiece constructor).
|
||||||
|
re2::StringPiece piece_;
|
||||||
|
char buf_[20]; // length of maximum uint64 (no terminator needed).
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace internal
|
||||||
|
|
||||||
|
// Concatenate any number of strings, StringPieces, and numeric values into a
|
||||||
|
// single string.
|
||||||
|
template <typename... Types>
|
||||||
|
std::string StrCat(Types... args) {
|
||||||
|
internal::StrCatPiece pieces[] = {{args}...};
|
||||||
|
size_t size = 0;
|
||||||
|
for (const auto &p : pieces) {
|
||||||
|
size += p.size();
|
||||||
|
}
|
||||||
|
std::string out;
|
||||||
|
out.reserve(size);
|
||||||
|
for (const auto &p : pieces) {
|
||||||
|
out.append(p.data(), p.size());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join any number of string fragments (of like type) together into a single
|
||||||
|
// string, with a separator.
|
||||||
|
template <typename Container>
|
||||||
|
std::string Join(const Container &pieces, re2::StringPiece separator) {
|
||||||
|
std::string out;
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &p : pieces) {
|
||||||
|
if (!first) {
|
||||||
|
out.append(separator.data(), separator.size());
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
internal::StrCatPiece piece(p);
|
||||||
|
out.append(piece.data(), piece.size());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return true if every character in |str| is in [A-Za-z0-9_].
|
||||||
|
bool IsWord(const std::string &str);
|
||||||
|
|
||||||
|
// HTML-escape the given UTF-8-encoded string.
|
||||||
|
std::string EscapeHtml(const std::string &input);
|
||||||
|
|
||||||
|
// Wrapper around ::strtol that returns true iff valid and corrects
|
||||||
|
// constness.
|
||||||
|
bool strto64(const char *str, int base, const char **endptr, int64_t *value);
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_STRING_H
|
Binary file not shown.
|
@ -0,0 +1,113 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// testutil.cc: implementation of testutil.h interface.
|
||||||
|
|
||||||
|
#include "testutil.h"
|
||||||
|
|
||||||
|
#include <dirent.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#include <fstream>
|
||||||
|
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
#include "filesystem.h"
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
bool DeleteChildrenRecursively(const std::string &dirname,
|
||||||
|
std::string *error_msg) {
|
||||||
|
bool ok = true;
|
||||||
|
auto fn = [&dirname, &ok, error_msg](const struct dirent *ent) {
|
||||||
|
std::string name(ent->d_name);
|
||||||
|
std::string path = dirname + "/" + name;
|
||||||
|
if (name == "." || name == "..") {
|
||||||
|
return IterationControl::kContinue;
|
||||||
|
}
|
||||||
|
bool is_dir = (ent->d_type == DT_DIR);
|
||||||
|
if (ent->d_type == DT_UNKNOWN) {
|
||||||
|
struct stat buf;
|
||||||
|
PCHECK(stat(path.c_str(), &buf) == 0) << path;
|
||||||
|
is_dir = S_ISDIR(buf.st_mode);
|
||||||
|
}
|
||||||
|
if (is_dir) {
|
||||||
|
ok = ok && DeleteChildrenRecursively(path, error_msg);
|
||||||
|
if (!ok) {
|
||||||
|
return IterationControl::kBreak;
|
||||||
|
}
|
||||||
|
if (rmdir(path.c_str()) != 0) {
|
||||||
|
*error_msg =
|
||||||
|
std::string("rmdir failed on ") + path + ": " + strerror(errno);
|
||||||
|
ok = false;
|
||||||
|
return IterationControl::kBreak;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (unlink(path.c_str()) != 0) {
|
||||||
|
*error_msg =
|
||||||
|
std::string("unlink failed on ") + path + ": " + strerror(errno);
|
||||||
|
ok = false;
|
||||||
|
return IterationControl::kBreak;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return IterationControl::kContinue;
|
||||||
|
};
|
||||||
|
if (!DirForEach(dirname, fn, error_msg)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string PrepareTempDirOrDie(const std::string &test_name) {
|
||||||
|
std::string dirname = std::string("/tmp/test.") + test_name;
|
||||||
|
int res = mkdir(dirname.c_str(), 0700);
|
||||||
|
if (res != 0) {
|
||||||
|
int err = errno;
|
||||||
|
CHECK_EQ(err, EEXIST) << "mkdir failed: " << strerror(err);
|
||||||
|
std::string error_msg;
|
||||||
|
CHECK(DeleteChildrenRecursively(dirname, &error_msg)) << error_msg;
|
||||||
|
}
|
||||||
|
return dirname;
|
||||||
|
}
|
||||||
|
|
||||||
|
void WriteFileOrDie(const std::string &path, const std::string &contents) {
|
||||||
|
std::ofstream f(path);
|
||||||
|
f << contents;
|
||||||
|
f.close();
|
||||||
|
CHECK(!f.fail()) << "failed to write: " << path;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,104 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// testutil.h: utilities for testing.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_TESTUTIL_H
|
||||||
|
#define MOONFIRE_NVR_TESTUTIL_H
|
||||||
|
|
||||||
|
#include <glog/logging.h>
|
||||||
|
#include <gmock/gmock.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
// Create or empty the given test directory, or die.
|
||||||
|
// Returns the full path.
|
||||||
|
std::string PrepareTempDirOrDie(const std::string &test_name);
|
||||||
|
|
||||||
|
// Write the given file contents to the given path, or die.
|
||||||
|
void WriteFileOrDie(const std::string &path, const std::string &contents);
|
||||||
|
|
||||||
|
// A scoped log sink for testing that the right log messages are sent.
|
||||||
|
// Modelled after glog's "mock-log.h", which is not exported.
|
||||||
|
// Use as follows:
|
||||||
|
//
|
||||||
|
// {
|
||||||
|
// ScopedMockLog log;
|
||||||
|
// EXPECT_CALL(log, Log(ERROR, _, HasSubstr("blah blah")));
|
||||||
|
// log.Start();
|
||||||
|
// ThingThatLogs();
|
||||||
|
// }
|
||||||
|
class ScopedMockLog : public google::LogSink {
|
||||||
|
public:
|
||||||
|
~ScopedMockLog() final { google::RemoveLogSink(this); }
|
||||||
|
|
||||||
|
// Start logging to this sink.
|
||||||
|
// This is not done at construction time so that it's possible to set
|
||||||
|
// expectations first, which is important if some background thread is
|
||||||
|
// already logging.
|
||||||
|
void Start() { google::AddLogSink(this); }
|
||||||
|
|
||||||
|
// Set expectations here.
|
||||||
|
MOCK_METHOD3(Log, void(google::LogSeverity severity,
|
||||||
|
const std::string &full_filename,
|
||||||
|
const std::string &message));
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct LogEntry {
|
||||||
|
google::LogSeverity severity = -1;
|
||||||
|
std::string full_filename;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
// This method is called with locks held and thus shouldn't call Log.
|
||||||
|
// It just stashes away the log entry for later.
|
||||||
|
void send(google::LogSeverity severity, const char *full_filename,
|
||||||
|
const char *base_filename, int line, const tm *tm_time,
|
||||||
|
const char *message, size_t message_len) final {
|
||||||
|
pending_.severity = severity;
|
||||||
|
pending_.full_filename = full_filename;
|
||||||
|
pending_.message.assign(message, message_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
// This method is always called after send() without locks.
|
||||||
|
// It does the actual work of calling Log. It moves data away from
|
||||||
|
// pending_ in case Log() logs itself (causing a nested call to send() and
|
||||||
|
// WaitTillSent()).
|
||||||
|
void WaitTillSent() final {
|
||||||
|
LogEntry entry = std::move(pending_);
|
||||||
|
Log(entry.severity, entry.full_filename, entry.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
LogEntry pending_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_TESTUTIL_H
|
|
@ -0,0 +1,90 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// time.cc: implementation of time.h interface.
|
||||||
|
|
||||||
|
#include "time.h"
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <glog/logging.h>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
class RealClock : public WallClock {
|
||||||
|
public:
|
||||||
|
struct timespec Now() const final {
|
||||||
|
struct timespec now;
|
||||||
|
CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now)) << strerror(errno);
|
||||||
|
return now;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Sleep(struct timespec req) final {
|
||||||
|
struct timespec rem;
|
||||||
|
while (true) {
|
||||||
|
int ret = nanosleep(&req, &rem);
|
||||||
|
if (ret != 0 && errno != EINTR) {
|
||||||
|
PLOG(FATAL) << "nanosleep";
|
||||||
|
}
|
||||||
|
if (ret == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req = rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// Returns the real wall clock, which will never be deleted.
|
||||||
|
WallClock *GetRealClock() {
|
||||||
|
static RealClock *real_clock = new RealClock; // never deleted.
|
||||||
|
return real_clock;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct timespec SimulatedClock::Now() const {
|
||||||
|
std::lock_guard<std::mutex> l(mu_);
|
||||||
|
return now_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SimulatedClock::Sleep(struct timespec req) {
|
||||||
|
std::lock_guard<std::mutex> l(mu_);
|
||||||
|
now_.tv_sec += req.tv_sec;
|
||||||
|
now_.tv_nsec += req.tv_nsec;
|
||||||
|
if (now_.tv_nsec > kNanos) {
|
||||||
|
now_.tv_nsec -= kNanos;
|
||||||
|
now_.tv_sec++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
|
@ -0,0 +1,74 @@
|
||||||
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
||||||
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// In addition, as a special exception, the copyright holders give
|
||||||
|
// permission to link the code of portions of this program with the
|
||||||
|
// OpenSSL library under certain conditions as described in each
|
||||||
|
// individual source file, and distribute linked combinations including
|
||||||
|
// the two.
|
||||||
|
//
|
||||||
|
// You must obey the GNU General Public License in all respects for all
|
||||||
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
||||||
|
// exception, you may extend this exception to your version of the
|
||||||
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
||||||
|
// so, delete this exception statement from your version. If you delete
|
||||||
|
// this exception statement from all source files in the program, then
|
||||||
|
// also delete it here.
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
//
|
||||||
|
// time.h: functions dealing with (wall) time.
|
||||||
|
|
||||||
|
#ifndef MOONFIRE_NVR_TIME_H
|
||||||
|
#define MOONFIRE_NVR_TIME_H
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
|
namespace moonfire_nvr {
|
||||||
|
|
||||||
|
constexpr long kNanos = 1000000000;
|
||||||
|
|
||||||
|
class WallClock {
|
||||||
|
public:
|
||||||
|
virtual ~WallClock() {}
|
||||||
|
virtual struct timespec Now() const = 0;
|
||||||
|
virtual void Sleep(struct timespec) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class SimulatedClock : public WallClock {
|
||||||
|
public:
|
||||||
|
SimulatedClock() : now_({0, 0}) {}
|
||||||
|
struct timespec Now() const final;
|
||||||
|
void Sleep(struct timespec req) final;
|
||||||
|
|
||||||
|
private:
|
||||||
|
mutable std::mutex mu_;
|
||||||
|
struct timespec now_;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline struct timespec SecToTimespec(double sec) {
|
||||||
|
double intpart;
|
||||||
|
double fractpart = modf(sec, &intpart);
|
||||||
|
return {static_cast<time_t>(intpart), static_cast<long>(fractpart * kNanos)};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the real wall clock, which will never be deleted.
|
||||||
|
WallClock *GetRealClock();
|
||||||
|
|
||||||
|
} // namespace moonfire_nvr
|
||||||
|
|
||||||
|
#endif // MOONFIRE_NVR_TIME_H
|
Loading…
Reference in New Issue