Merge branch 'master' of github.com:zoneminder/ZoneMinder

This commit is contained in:
Isaac Connor 2020-08-27 11:55:26 -04:00
commit 69be26213a
143 changed files with 2430 additions and 2335 deletions

2
.gitignore vendored
View File

@ -120,7 +120,7 @@ src/CMakeFiles/
src/cmake_install.cmake src/cmake_install.cmake
src/libzm.a src/libzm.a
src/nph-zms src/nph-zms
src/zm_config.h src/zm_config_data.h
src/zm_config_defines.h src/zm_config_defines.h
src/zma src/zma
src/zmc src/zmc

View File

@ -37,12 +37,9 @@ env:
- SMPFLAGS=-j4 OS=el DIST=8 DOCKER_REPO=knnniggett/packpack - SMPFLAGS=-j4 OS=el DIST=8 DOCKER_REPO=knnniggett/packpack
- SMPFLAGS=-j4 OS=fedora DIST=31 DOCKER_REPO=knnniggett/packpack - SMPFLAGS=-j4 OS=fedora DIST=31 DOCKER_REPO=knnniggett/packpack
- SMPFLAGS=-j4 OS=fedora DIST=32 DOCKER_REPO=knnniggett/packpack - SMPFLAGS=-j4 OS=fedora DIST=32 DOCKER_REPO=knnniggett/packpack
- SMPFLAGS=-j4 OS=ubuntu DIST=trusty DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=ubuntu DIST=xenial DOCKER_REPO=iconzm/packpack - SMPFLAGS=-j4 OS=ubuntu DIST=xenial DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=ubuntu DIST=bionic DOCKER_REPO=iconzm/packpack - SMPFLAGS=-j4 OS=ubuntu DIST=bionic DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=ubuntu DIST=disco DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=ubuntu DIST=focal DOCKER_REPO=iconzm/packpack - SMPFLAGS=-j4 OS=ubuntu DIST=focal DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=debian DIST=jessie DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=debian DIST=stretch DOCKER_REPO=iconzm/packpack - SMPFLAGS=-j4 OS=debian DIST=stretch DOCKER_REPO=iconzm/packpack
- SMPFLAGS=-j4 OS=debian DIST=buster DOCKER_REPO=iconzm/packpack - SMPFLAGS=-j4 OS=debian DIST=buster DOCKER_REPO=iconzm/packpack
@ -67,3 +64,4 @@ deploy:
script: utils/packpack/rsync_xfer.sh script: utils/packpack/rsync_xfer.sh
on: on:
branch: master branch: master
condition: fork = false

View File

@ -1,2 +1,2 @@
/* This was done in 1.31.0 but zm_create.sql.in wasn't updated to match */ /* This was done in 1.31.0 but zm_create.sql.in wasn't updated to match. */
ALTER TABLE Monitors MODIFY LinkedMonitors varchar(255); ALTER TABLE Monitors MODIFY LinkedMonitors varchar(255);

View File

@ -21,7 +21,7 @@ endif(ZM_TARGET_DISTRO MATCHES "^el")
# Configure the common zoneminder files # Configure the common zoneminder files
configure_file(common/zoneminder.logrotate.in ${CMAKE_CURRENT_SOURCE_DIR}/zoneminder.logrotate @ONLY) configure_file(common/zoneminder.logrotate.in ${CMAKE_CURRENT_SOURCE_DIR}/zoneminder.logrotate @ONLY)
configure_file(common/zoneminder.service.in ${CMAKE_CURRENT_SOURCE_DIR}/zoneminder.service @ONLY) configure_file(common/zoneminder.service.in ${CMAKE_CURRENT_SOURCE_DIR}/zoneminder.service @ONLY)
file(MAKE_DIRECTORY sock swap zoneminder zoneminder-upload events temp) file(MAKE_DIRECTORY sock swap zoneminder events temp)
# Configure the Apache zoneminder files # Configure the Apache zoneminder files
configure_file(httpd/zm-httpd.conf.in ${CMAKE_CURRENT_SOURCE_DIR}/zm-httpd.conf @ONLY) configure_file(httpd/zm-httpd.conf.in ${CMAKE_CURRENT_SOURCE_DIR}/zm-httpd.conf @ONLY)
@ -51,7 +51,6 @@ install(DIRECTORY sock swap DESTINATION /var/lib/zoneminder DIRECTORY_PERMISSION
install(DIRECTORY zoneminder DESTINATION /var/log DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) install(DIRECTORY zoneminder DESTINATION /var/log DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
install(DIRECTORY zoneminder DESTINATION /var/run DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) install(DIRECTORY zoneminder DESTINATION /var/run DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
install(DIRECTORY zoneminder DESTINATION /var/cache DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) install(DIRECTORY zoneminder DESTINATION /var/cache DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
install(DIRECTORY zoneminder-upload DESTINATION /var/spool DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
install(DIRECTORY events temp DESTINATION /var/lib/zoneminder DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) install(DIRECTORY events temp DESTINATION /var/lib/zoneminder DIRECTORY_PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
# Install the Apache zoneminder files # Install the Apache zoneminder files

View File

@ -28,7 +28,7 @@
%global _hardened_build 1 %global _hardened_build 1
Name: zoneminder Name: zoneminder
Version: 1.35.5 Version: 1.35.6
Release: 1%{?dist} Release: 1%{?dist}
Summary: A camera monitoring and analysis tool Summary: A camera monitoring and analysis tool
Group: System Environment/Daemons Group: System Environment/Daemons
@ -204,7 +204,6 @@ mv -f CakePHP-Enum-Behavior-%{ceb_version} ./web/api/app/Plugin/CakePHP-Enum-Beh
# Change the following default values # Change the following default values
./utils/zmeditconfigdata.sh ZM_OPT_CAMBOZOLA yes ./utils/zmeditconfigdata.sh ZM_OPT_CAMBOZOLA yes
./utils/zmeditconfigdata.sh ZM_UPLOAD_FTP_LOC_DIR %{_localstatedir}/spool/zoneminder-upload
./utils/zmeditconfigdata.sh ZM_OPT_CONTROL yes ./utils/zmeditconfigdata.sh ZM_OPT_CONTROL yes
./utils/zmeditconfigdata.sh ZM_CHECK_FOR_UPDATES no ./utils/zmeditconfigdata.sh ZM_CHECK_FOR_UPDATES no
./utils/zmeditconfigdata.sh ZM_DYN_SHOW_DONATE_REMINDER no ./utils/zmeditconfigdata.sh ZM_DYN_SHOW_DONATE_REMINDER no
@ -399,7 +398,6 @@ EOF
%dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_sharedstatedir}/zoneminder/temp %dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_sharedstatedir}/zoneminder/temp
%dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_localstatedir}/cache/zoneminder %dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_localstatedir}/cache/zoneminder
%dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_localstatedir}/log/zoneminder %dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_localstatedir}/log/zoneminder
%dir %attr(755,%{zmuid_final},%{zmgid_final}) %{_localstatedir}/spool/zoneminder-upload
%files nginx %files nginx
%config(noreplace) %attr(640,root,nginx) %{_sysconfdir}/zm/zm.conf %config(noreplace) %attr(640,root,nginx) %{_sysconfdir}/zm/zm.conf
@ -423,7 +421,6 @@ EOF
%dir %attr(755,nginx,nginx) %{_sharedstatedir}/zoneminder/temp %dir %attr(755,nginx,nginx) %{_sharedstatedir}/zoneminder/temp
%dir %attr(755,nginx,nginx) %{_localstatedir}/cache/zoneminder %dir %attr(755,nginx,nginx) %{_localstatedir}/cache/zoneminder
%dir %attr(755,nginx,nginx) %{_localstatedir}/log/zoneminder %dir %attr(755,nginx,nginx) %{_localstatedir}/log/zoneminder
%dir %attr(755,nginx,nginx) %{_localstatedir}/spool/zoneminder-upload
%changelog %changelog
* Tue Feb 04 2020 Andrew Bauer <zonexpertconsulting@outlook.com> - 1.34.2-1 * Tue Feb 04 2020 Andrew Bauer <zonexpertconsulting@outlook.com> - 1.34.2-1

View File

@ -1,3 +1,3 @@
zoneminder (1.31.39~20180223.27-stretch-1) unstable; urgency=low zoneminder (1.35.6~20200825.27-xenial) xenial; urgency=low
* *
-- Isaac Connor <iconnor@connortechnology.com> Fri, 23 Feb 2018 14:15:59 -0500 -- Isaac Connor <isaac@zoneminder.com> Tue, 25 Aug 2020 09:28:18 -0400

View File

@ -3,7 +3,7 @@ Section: net
Priority: optional Priority: optional
Maintainer: Isaac Connor <isaac@zoneminder.com> Maintainer: Isaac Connor <isaac@zoneminder.com>
Uploaders: Isaac Connor <isaac@zoneminder.com> Uploaders: Isaac Connor <isaac@zoneminder.com>
Build-Depends: debhelper, dh-systemd, sphinx-doc, dh-linktree, dh-systemd, dh-apache2 Build-Depends: debhelper, dh-systemd, sphinx-doc, python3-sphinx, dh-linktree, dh-systemd, dh-apache2
,cmake ,cmake
,libx264-dev, libmp4v2-dev ,libx264-dev, libmp4v2-dev
,libavdevice-dev ,libavdevice-dev

View File

@ -76,8 +76,7 @@ BEGIN {
require ZoneMinder::Database; require ZoneMinder::Database;
# Process name, value pairs from the main config file first # Process name, value pairs from the main config file first
my $config_file = ZM_CONFIG; process_configfile(ZM_CONFIG);
process_configfile($config_file);
# Search for user created config files. If one or more are found then # Search for user created config files. If one or more are found then
# update the Config hash with those values # update the Config hash with those values
@ -92,10 +91,14 @@ require ZoneMinder::Database;
} }
my $dbh = ZoneMinder::Database::zmDbConnect(); my $dbh = ZoneMinder::Database::zmDbConnect();
die "Unable to connect to DB. ZM Cannot continue.\n" if !$dbh;
my $sql = 'SELECT Name,Value FROM Config'; my $sql = 'SELECT Name,Value FROM Config';
my $sth = $dbh->prepare_cached($sql) or croak("Can't prepare '$sql': ".$dbh->errstr()); my $sth = $dbh->prepare_cached($sql) or croak("Can't prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute() or croak("Can't execute: ".$sth->errstr()); my $res = $sth->execute() or croak("Can't execute: ".$sth->errstr());
while ( my $config = $sth->fetchrow_hashref() ) { while ( my $config = $sth->fetchrow_hashref() ) {
# If already defined skip it because we want the values in /etc/zm.conf to override the values in Config Table
next if exists $Config{$config->{Name}};
$Config{$config->{Name}} = $config->{Value}; $Config{$config->{Name}} = $config->{Value};
} }
$sth->finish(); $sth->finish();
@ -133,7 +136,7 @@ require ZoneMinder::Database;
print(STDERR "Warning, bad line in $config_file: $str\n"); print(STDERR "Warning, bad line in $config_file: $str\n");
next; next;
} # end if } # end if
$name =~ tr/a-z/A-Z/; $name = uc $name;
#if ( !$ZoneMinder::ConfigData::options_hash{$name} ) { #if ( !$ZoneMinder::ConfigData::options_hash{$name} ) {
#print(STDERR "Warning, unknown config option name $name in $config_file\n"); #print(STDERR "Warning, unknown config option name $name in $config_file\n");
#} else { #} else {

View File

@ -582,26 +582,6 @@ our @options = (
type => $types{integer}, type => $types{integer},
category => 'images', category => 'images',
}, },
# Deprecated, now stream quality
{
name => 'ZM_JPEG_IMAGE_QUALITY',
default => '70',
description => q`Set the JPEG quality setting for the streamed 'live' images (1-100)`,
help => q`
When viewing a 'live' stream for a monitor ZoneMinder will grab
an image from the buffer and encode it into JPEG format before
sending it. This option specifies what image quality should be
used to encode these images. A higher number means better
quality but less compression so will take longer to view over a
slow connection. By contrast a low number means quicker to view
images but at the price of lower quality images. This option
does not apply when viewing events or still images as these are
usually just read from disk and so will be encoded at the
quality specified by the previous options.
`,
type => $types{integer},
category => 'hidden',
},
{ {
name => 'ZM_JPEG_STREAM_QUALITY', name => 'ZM_JPEG_STREAM_QUALITY',
default => '70', default => '70',
@ -877,38 +857,6 @@ our @options = (
type => $types{integer}, type => $types{integer},
category => 'config', category => 'config',
}, },
# Deprecated, really no longer necessary
{
name => 'ZM_OPT_REMOTE_CAMERAS',
default => 'no',
description => 'Are you going to use remote/networked cameras',
help => q`
ZoneMinder can work with both local cameras, ie. those attached
physically to your computer and remote or network cameras. If
you will be using networked cameras select this option.
`,
type => $types{boolean},
category => 'hidden',
},
# Deprecated, now set on a per monitor basis using the Method field
{
name => 'ZM_NETCAM_REGEXPS',
default => 'yes',
description => 'Use regular expression matching with network cameras',
help => q`
Traditionally ZoneMinder has used complex regular regular
expressions to handle the multitude of formats that network
cameras produce. In versions from 1.21.1 the default is to use
a simpler and faster built in pattern matching methodology.
This works well with most networks cameras but if you have
problems you can try the older, but more flexible, regular
expression based method by selecting this option. Note, to use
this method you must have libpcre installed on your system.
`,
requires => [ { name => 'ZM_OPT_REMOTE_CAMERAS', value => 'yes' } ],
type => $types{boolean},
category => 'hidden',
},
{ {
name => 'ZM_HTTP_VERSION', name => 'ZM_HTTP_VERSION',
default => '1.0', default => '1.0',
@ -1974,19 +1922,6 @@ our @options = (
}, },
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_HOST',
default => '',
description => 'The remote server to upload to',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. This option indicates the name, or ip
address, of the server to use.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{hostname},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_HOST', name => 'ZM_UPLOAD_HOST',
default => '', default => '',
@ -2015,19 +1950,6 @@ our @options = (
type => $types{integer}, type => $types{integer},
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_USER',
default => '',
description => 'Your ftp username',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. This option indicates the username that
ZoneMinder should use to log in for ftp transfer.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{alphanum},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_USER', name => 'ZM_UPLOAD_USER',
default => '', default => '',
@ -2041,19 +1963,6 @@ our @options = (
type => $types{alphanum}, type => $types{alphanum},
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_PASS',
default => '',
description => 'Your ftp password',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. This option indicates the password that
ZoneMinder should use to log in for ftp transfer.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{string},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_PASS', name => 'ZM_UPLOAD_PASS',
default => '', default => '',
@ -2069,21 +1978,6 @@ our @options = (
type => $types{string}, type => $types{string},
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_LOC_DIR',
default => '@ZM_TMPDIR@',
description => 'The local directory in which to create upload files',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. This option indicates the local directory
that ZoneMinder should use for temporary upload files. These
are files that are created from events, uploaded and then
deleted.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{abs_path},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_LOC_DIR', name => 'ZM_UPLOAD_LOC_DIR',
default => '@ZM_TMPDIR@', default => '@ZM_TMPDIR@',
@ -2098,19 +1992,6 @@ our @options = (
type => $types{abs_path}, type => $types{abs_path},
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_REM_DIR',
default => '',
description => 'The remote directory to upload to',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. This option indicates the remote directory
that ZoneMinder should use to upload event files to.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{rel_path},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_REM_DIR', name => 'ZM_UPLOAD_REM_DIR',
default => '', default => '',
@ -2124,21 +2005,6 @@ our @options = (
type => $types{rel_path}, type => $types{rel_path},
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_TIMEOUT',
default => '120',
description => 'How long to allow the transfer to take for each file',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. This option indicates the maximum ftp
inactivity timeout (in seconds) that should be tolerated before
ZoneMinder determines that the transfer has failed and closes
down the connection.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{integer},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_TIMEOUT', name => 'ZM_UPLOAD_TIMEOUT',
default => '120', default => '120',
@ -2191,20 +2057,6 @@ our @options = (
type => $types{boolean}, type => $types{boolean},
category => 'upload', category => 'upload',
}, },
{
name => 'ZM_UPLOAD_FTP_DEBUG',
default => 'no',
description => 'Switch ftp debugging on',
help => q`
You can use filters to instruct ZoneMinder to upload events to
a remote ftp server. If you are having (or expecting) troubles
with uploading events then setting this to 'yes' permits
additional information to be included in the zmfilter log file.
`,
requires => [ { name => 'ZM_OPT_UPLOAD', value => 'yes' } ],
type => $types{boolean},
category => 'hidden',
},
{ {
name => 'ZM_UPLOAD_DEBUG', name => 'ZM_UPLOAD_DEBUG',
default => 'no', default => 'no',
@ -2237,85 +2089,6 @@ our @options = (
type => $types{boolean}, type => $types{boolean},
category => 'mail', category => 'mail',
}, },
{
name => 'ZM_EMAIL_ADDRESS',
default => '',
description => 'The email address to send matching event details to',
requires => [ { name => 'ZM_OPT_EMAIL', value => 'yes' } ],
help => q`
This option is used to define the email address that any events
that match the appropriate filters will be sent to.
`,
type => $types{email},
category => 'hidden',
},
{
name => 'ZM_EMAIL_TEXT',
default => 'subject = "ZoneMinder: Alarm - %MN%-%EI% (%ESM% - %ESA% %EFA%)"
body = "
Hello,
An alarm has been detected on your installation of the ZoneMinder.
The details are as follows :-
Monitor : %MN%
Event Id : %EI%
Length : %EL%
Frames : %EF% (%EFA%)
Scores : t%EST% m%ESM% a%ESA%
This alarm was matched by the %FN% filter and can be viewed at %EPS%
ZoneMinder"',
description => 'The text of the email used to send matching event details',
requires => [ { name => 'ZM_OPT_EMAIL', value => 'yes' } ],
help => q`
This option is used to define the content of the email that is
sent for any events that match the appropriate filters.
`,
type => $types{text},
category => 'hidden',
},
{
name => 'ZM_EMAIL_SUBJECT',
default => 'ZoneMinder: Alarm - %MN%-%EI% (%ESM% - %ESA% %EFA%)',
description => 'The subject of the email used to send matching event details',
requires => [ { name => 'ZM_OPT_EMAIL', value => 'yes' } ],
help => q`
This option is used to define the subject of the email that is
sent for any events that match the appropriate filters.
`,
type => $types{string},
category => 'hidden',
},
{
name => 'ZM_EMAIL_BODY',
default => '
Hello,
An alarm has been detected on your installation of the ZoneMinder.
The details are as follows :-
Monitor : %MN%
Event Id : %EI%
Length : %EL%
Frames : %EF% (%EFA%)
Scores : t%EST% m%ESM% a%ESA%
This alarm was matched by the %FN% filter and can be viewed at %EPS%
ZoneMinder',
description => 'The body of the email used to send matching event details',
requires => [ { name => 'ZM_OPT_EMAIL', value => 'yes' } ],
help => q`
This option is used to define the content of the email that is
sent for any events that match the appropriate filters.
`,
type => $types{text},
category => 'hidden',
},
{ {
name => 'ZM_OPT_MESSAGE', name => 'ZM_OPT_MESSAGE',
default => 'no', default => 'no',
@ -2347,19 +2120,6 @@ our @options = (
type => $types{email}, type => $types{email},
category => 'mail', category => 'mail',
}, },
{
name => 'ZM_MESSAGE_TEXT',
default => 'subject = "ZoneMinder: Alarm - %MN%-%EI%"
body = "ZM alarm detected - %EL% secs, %EF%/%EFA% frames, t%EST%/m%ESM%/a%ESA% score."',
description => 'The text of the message used to send matching event details',
requires => [ { name => 'ZM_OPT_MESSAGE', value => 'yes' } ],
help => q`
This option is used to define the content of the message that
is sent for any events that match the appropriate filters.
`,
type => $types{text},
category => 'hidden',
},
{ {
name => 'ZM_MESSAGE_SUBJECT', name => 'ZM_MESSAGE_SUBJECT',
default => 'ZoneMinder: Alarm - %MN%-%EI%', default => 'ZoneMinder: Alarm - %MN%-%EI%',
@ -2652,23 +2412,6 @@ our @options = (
category => 'config', category => 'config',
}, },
# Deprecated, superseded by event close mode # Deprecated, superseded by event close mode
{
name => 'ZM_FORCE_CLOSE_EVENTS',
default => 'no',
description => 'Close events at section ends.',
help => q`
When a monitor is running in a continuous recording mode
(Record or Mocord) events are usually closed after a fixed
period of time (the section length). However in Mocord mode it
is possible that motion detection may occur near the end of a
section and ordinarily this will prevent the event being closed
until the motion has ceased. Switching this option on will
force the event closed at the specified time regardless of any
motion activity.
`,
type => $types{boolean},
category => 'hidden',
},
{ {
name => 'ZM_WEIGHTED_ALARM_CENTRES', name => 'ZM_WEIGHTED_ALARM_CENTRES',
default => 'no', default => 'no',
@ -2876,34 +2619,6 @@ our @options = (
type => $types{hexadecimal}, type => $types{hexadecimal},
category => 'system', category => 'system',
}, },
# Deprecated, really no longer necessary
{
name => 'ZM_WEB_REFRESH_METHOD',
default => 'javascript',
description => 'What method windows should use to refresh themselves',
help => q`
Many windows in ZoneMinder need to refresh themselves to keep
their information current. This option determines what method
they should use to do this. Choosing 'javascript' means that
each window will have a short JavaScript statement in with a
timer to prompt the refresh. This is the most compatible
method. Choosing 'http' means the refresh instruction is put in
the HTTP header. This is a cleaner method but refreshes are
interrupted or cancelled when a link in the window is clicked
meaning that the window will no longer refresh and this would
have to be done manually.
`,
type => {
db_type =>'string',
hint =>'javascript|http',
pattern =>qr|^([jh])|i,
format =>q( $1 =~ /^j/
? 'javascript'
: 'http'
)
},
category => 'hidden',
},
{ {
name => 'ZM_WEB_EVENT_SORT_FIELD', name => 'ZM_WEB_EVENT_SORT_FIELD',
default => 'DateTime', default => 'DateTime',
@ -4043,7 +3758,6 @@ sub initialiseConfig {
} else { } else {
$option->{value} = ''; $option->{value} = '';
} }
#next if ( $option->{category} eq 'hidden' );
$option->{id} = $option_id++; $option->{id} = $option_id++;
} }
$configInitialised = 1; $configInitialised = 1;

View File

@ -82,6 +82,13 @@ sub Execute {
my $self = $_[0]; my $self = $_[0];
my $sql = $self->Sql(undef); my $sql = $self->Sql(undef);
if ( $$self{PreSQLConditions} and @{$$self{PreSQLConditions}} ) {
foreach my $term ( @{$$self{PreSQLConditions}} ) {
if ( $$term{attr} eq 'DiskPercent' ) {
}
}
}
if ( $self->{HasDiskPercent} ) { if ( $self->{HasDiskPercent} ) {
my $disk_percent = getDiskPercent($$self{Storage} ? $$self{Storage}->Path() : ()); my $disk_percent = getDiskPercent($$self{Storage} ? $$self{Storage}->Path() : ());
$sql =~ s/zmDiskPercent/$disk_percent/g; $sql =~ s/zmDiskPercent/$disk_percent/g;
@ -104,14 +111,27 @@ sub Execute {
return; return;
} }
my @results; my @results;
while ( my $event = $sth->fetchrow_hashref() ) { while ( my $event = $sth->fetchrow_hashref() ) {
push @results, $event; push @results, $event;
} }
$sth->finish(); $sth->finish();
Debug('Loaded ' . @results . " events for filter $_[0]{Name} using query ($sql)"); Debug('Loaded ' . @results . ' events for filter '.$$self{Name}.' using query ('.$sql.')"');
return @results; if ( $self->{PostSQLConditions} ) {
my @filtered_events;
foreach my $term ( @{$$self{PostSQLConditions}} ) {
if ( $$term{attr} eq 'ExistsInFileSystem' ) {
foreach my $row ( @results ) {
my $event = new ZoneMinder::Event($row);
if ( -e $event->Path() ) {
push @filtered_events, $row;
} }
}
}
} # end foreach term
@results = @filtered_events;
} # end if has PostSQLConditions
return @results;
} # end sub Execute
sub Sql { sub Sql {
my $self = shift; my $self = shift;
@ -183,18 +203,23 @@ sub Sql {
$self->{Sql} .= "weekday( E.EndTime )"; $self->{Sql} .= "weekday( E.EndTime )";
# #
} elsif ( $term->{attr} eq 'EventExists' ) {
push @{$self->{PreConditions}}, $term;
} elsif ( $term->{attr} eq 'DiskSpace' ) { } elsif ( $term->{attr} eq 'DiskSpace' ) {
$self->{Sql} .= 'E.DiskSpace'; $self->{Sql} .= 'E.DiskSpace';
$self->{HasDiskPercent} = !undef; push @{$self->{PostConditions}}, $term;
} elsif ( $term->{attr} eq 'DiskPercent' ) { } elsif ( $term->{attr} eq 'DiskPercent' ) {
$self->{Sql} .= 'zmDiskPercent'; $self->{Sql} .= 'zmDiskPercent';
$self->{HasDiskPercent} = !undef; $self->{HasDiskPercent} = !undef;
$self->{HasPreCondition} = !undef;
} elsif ( $term->{attr} eq 'DiskBlocks' ) { } elsif ( $term->{attr} eq 'DiskBlocks' ) {
$self->{Sql} .= 'zmDiskBlocks'; $self->{Sql} .= 'zmDiskBlocks';
$self->{HasDiskBlocks} = !undef; $self->{HasDiskBlocks} = !undef;
$self->{HasPreCondition} = !undef;
} elsif ( $term->{attr} eq 'SystemLoad' ) { } elsif ( $term->{attr} eq 'SystemLoad' ) {
$self->{Sql} .= 'zmSystemLoad'; $self->{Sql} .= 'zmSystemLoad';
$self->{HasSystemLoad} = !undef; $self->{HasSystemLoad} = !undef;
$self->{HasPreCondition} = !undef;
} else { } else {
$self->{Sql} .= 'E.'.$term->{attr}; $self->{Sql} .= 'E.'.$term->{attr};
} }

View File

@ -1,7 +1,7 @@
# CMakeLists.txt for the ZoneMinder binaries # CMakeLists.txt for the ZoneMinder binaries
# Create files from the .in files # Create files from the .in files
configure_file(zm_config.h.in "${CMAKE_CURRENT_BINARY_DIR}/zm_config.h" @ONLY) configure_file(zm_config_data.h.in "${CMAKE_CURRENT_BINARY_DIR}/zm_config_data.h" @ONLY)
# Group together all the source files that are used by all the binaries (zmc, zma, zmu, zms etc) # Group together all the source files that are used by all the binaries (zmc, zma, zmu, zms etc)
set(ZM_BIN_SRC_FILES zm_box.cpp zm_buffer.cpp zm_camera.cpp zm_comms.cpp zm_config.cpp zm_coord.cpp zm_curl_camera.cpp zm.cpp zm_db.cpp zm_logger.cpp zm_event.cpp zm_frame.cpp zm_eventstream.cpp zm_exception.cpp zm_file_camera.cpp zm_ffmpeg_input.cpp zm_ffmpeg_camera.cpp zm_group.cpp zm_image.cpp zm_jpeg.cpp zm_libvlc_camera.cpp zm_libvnc_camera.cpp zm_local_camera.cpp zm_monitor.cpp zm_monitorstream.cpp zm_ffmpeg.cpp zm_mpeg.cpp zm_packet.cpp zm_packetqueue.cpp zm_poly.cpp zm_regexp.cpp zm_remote_camera.cpp zm_remote_camera_http.cpp zm_remote_camera_nvsocket.cpp zm_remote_camera_rtsp.cpp zm_rtp.cpp zm_rtp_ctrl.cpp zm_rtp_data.cpp zm_rtp_source.cpp zm_rtsp.cpp zm_rtsp_auth.cpp zm_sdp.cpp zm_signal.cpp zm_stream.cpp zm_swscale.cpp zm_thread.cpp zm_time.cpp zm_timer.cpp zm_user.cpp zm_utils.cpp zm_video.cpp zm_videostore.cpp zm_zone.cpp zm_storage.cpp zm_fifo.cpp zm_crypt.cpp) set(ZM_BIN_SRC_FILES zm_box.cpp zm_buffer.cpp zm_camera.cpp zm_comms.cpp zm_config.cpp zm_coord.cpp zm_curl_camera.cpp zm.cpp zm_db.cpp zm_logger.cpp zm_event.cpp zm_frame.cpp zm_eventstream.cpp zm_exception.cpp zm_file_camera.cpp zm_ffmpeg_input.cpp zm_ffmpeg_camera.cpp zm_group.cpp zm_image.cpp zm_jpeg.cpp zm_libvlc_camera.cpp zm_libvnc_camera.cpp zm_local_camera.cpp zm_monitor.cpp zm_monitorstream.cpp zm_ffmpeg.cpp zm_mpeg.cpp zm_packet.cpp zm_packetqueue.cpp zm_poly.cpp zm_regexp.cpp zm_remote_camera.cpp zm_remote_camera_http.cpp zm_remote_camera_nvsocket.cpp zm_remote_camera_rtsp.cpp zm_rtp.cpp zm_rtp_ctrl.cpp zm_rtp_data.cpp zm_rtp_source.cpp zm_rtsp.cpp zm_rtsp_auth.cpp zm_sdp.cpp zm_signal.cpp zm_stream.cpp zm_swscale.cpp zm_thread.cpp zm_time.cpp zm_timer.cpp zm_user.cpp zm_utils.cpp zm_video.cpp zm_videostore.cpp zm_zone.cpp zm_storage.cpp zm_fifo.cpp zm_crypt.cpp)

View File

@ -20,4 +20,4 @@
#include "zm.h" #include "zm.h"
/* This is our argv[0], we need it for backtrace */ /* This is our argv[0], we need it for backtrace */
const char* self = 0; const char* self = nullptr;

View File

@ -34,7 +34,7 @@ protected:
unsigned char *mTail; unsigned char *mTail;
public: public:
Buffer() : mStorage( 0 ), mAllocation( 0 ), mSize( 0 ), mHead( 0 ), mTail( 0 ) { Buffer() : mStorage( nullptr ), mAllocation( 0 ), mSize( 0 ), mHead( nullptr ), mTail( nullptr ) {
} }
explicit Buffer( unsigned int pSize ) : mAllocation( pSize ), mSize( 0 ) { explicit Buffer( unsigned int pSize ) : mAllocation( pSize ), mSize( 0 ) {
mHead = mStorage = new unsigned char[mAllocation]; mHead = mStorage = new unsigned char[mAllocation];

View File

@ -55,7 +55,7 @@ Camera::Camera(
Debug(2, "New camera id: %d width: %d line size: %d height: %d colours: %d subpixelorder: %d capture: %d", Debug(2, "New camera id: %d width: %d line size: %d height: %d colours: %d subpixelorder: %d capture: %d",
monitor_id, width, linesize, height, colours, subpixelorder, capture); monitor_id, width, linesize, height, colours, subpixelorder, capture);
monitor = NULL; monitor = nullptr;
} }
Camera::~Camera() { Camera::~Camera() {

View File

@ -142,13 +142,13 @@ SockAddr *SockAddr::newSockAddr( const struct sockaddr &addr, socklen_t len )
return( new SockAddrUnix( (const struct sockaddr_un *)&addr ) ); return( new SockAddrUnix( (const struct sockaddr_un *)&addr ) );
} }
Error( "Unable to create new SockAddr from addr family %d with size %d", addr.sa_family, len ); Error( "Unable to create new SockAddr from addr family %d with size %d", addr.sa_family, len );
return( 0 ); return nullptr;
} }
SockAddr *SockAddr::newSockAddr( const SockAddr *addr ) SockAddr *SockAddr::newSockAddr( const SockAddr *addr )
{ {
if ( !addr ) if ( !addr )
return( 0 ); return nullptr;
if ( addr->getDomain() == AF_INET ) if ( addr->getDomain() == AF_INET )
{ {
@ -159,7 +159,7 @@ SockAddr *SockAddr::newSockAddr( const SockAddr *addr )
return( new SockAddrUnix( *(SockAddrUnix *)addr ) ); return( new SockAddrUnix( *(SockAddrUnix *)addr ) );
} }
Error( "Unable to create new SockAddr from addr family %d", addr->getDomain() ); Error( "Unable to create new SockAddr from addr family %d", addr->getDomain() );
return( 0 ); return nullptr;
} }
SockAddrInet::SockAddrInet() : SockAddr( (struct sockaddr *)&mAddrIn ) SockAddrInet::SockAddrInet() : SockAddr( (struct sockaddr *)&mAddrIn )
@ -170,14 +170,14 @@ bool SockAddrInet::resolve( const char *host, const char *serv, const char *prot
{ {
memset( &mAddrIn, 0, sizeof(mAddrIn) ); memset( &mAddrIn, 0, sizeof(mAddrIn) );
struct hostent *hostent=0; struct hostent *hostent=nullptr;
if ( !(hostent = ::gethostbyname( host ) ) ) if ( !(hostent = ::gethostbyname( host ) ) )
{ {
Error( "gethostbyname( %s ), h_errno = %d", host, h_errno ); Error( "gethostbyname( %s ), h_errno = %d", host, h_errno );
return( false ); return( false );
} }
struct servent *servent=0; struct servent *servent=nullptr;
if ( !(servent = ::getservbyname( serv, proto ) ) ) if ( !(servent = ::getservbyname( serv, proto ) ) )
{ {
Error( "getservbyname( %s ), errno = %d, error = %s", serv, errno, strerror(errno) ); Error( "getservbyname( %s ), errno = %d, error = %s", serv, errno, strerror(errno) );
@ -195,7 +195,7 @@ bool SockAddrInet::resolve( const char *host, int port, const char *proto )
{ {
memset( &mAddrIn, 0, sizeof(mAddrIn) ); memset( &mAddrIn, 0, sizeof(mAddrIn) );
struct hostent *hostent=0; struct hostent *hostent=nullptr;
if ( !(hostent = ::gethostbyname( host ) ) ) if ( !(hostent = ::gethostbyname( host ) ) )
{ {
Error( "gethostbyname( %s ), h_errno = %d", host, h_errno ); Error( "gethostbyname( %s ), h_errno = %d", host, h_errno );
@ -212,7 +212,7 @@ bool SockAddrInet::resolve( const char *serv, const char *proto )
{ {
memset( &mAddrIn, 0, sizeof(mAddrIn) ); memset( &mAddrIn, 0, sizeof(mAddrIn) );
struct servent *servent=0; struct servent *servent=nullptr;
if ( !(servent = ::getservbyname( serv, proto ) ) ) if ( !(servent = ::getservbyname( serv, proto ) ) )
{ {
Error( "getservbyname( %s ), errno = %d, error = %s", serv, errno, strerror(errno) ); Error( "getservbyname( %s ), errno = %d, error = %s", serv, errno, strerror(errno) );
@ -541,7 +541,7 @@ bool InetSocket::connect( const char *host, const char *serv )
* If socket(2) (or connect(2)) fails, we (close the socket * If socket(2) (or connect(2)) fails, we (close the socket
* and) try the next address. */ * and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) { for (rp = result; rp != nullptr; rp = rp->ai_next) {
if (mSd != -1) { if (mSd != -1) {
if (::connect(mSd, rp->ai_addr, rp->ai_addrlen) != -1) if (::connect(mSd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */ break; /* Success */
@ -576,7 +576,7 @@ bool InetSocket::connect( const char *host, const char *serv )
freeaddrinfo(result); /* No longer needed */ freeaddrinfo(result); /* No longer needed */
if (rp == NULL) { /* No address succeeded */ if (rp == nullptr) { /* No address succeeded */
Error( "connect(), Could not connect" ); Error( "connect(), Could not connect" );
mAddressFamily = AF_UNSPEC; mAddressFamily = AF_UNSPEC;
return( false ); return( false );
@ -607,9 +607,9 @@ bool InetSocket::bind( const char * host, const char * serv )
hints.ai_socktype = getType(); hints.ai_socktype = getType();
hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
hints.ai_protocol = 0; /* Any protocol */ hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL; hints.ai_canonname = nullptr;
hints.ai_addr = NULL; hints.ai_addr = nullptr;
hints.ai_next = NULL; hints.ai_next = nullptr;
s = getaddrinfo(host, serv, &hints, &result); s = getaddrinfo(host, serv, &hints, &result);
if (s != 0) { if (s != 0) {
@ -621,7 +621,7 @@ bool InetSocket::bind( const char * host, const char * serv )
* Try each address until we successfully bind(2). * Try each address until we successfully bind(2).
* If socket(2) (or bind(2)) fails, we (close the socket * If socket(2) (or bind(2)) fails, we (close the socket
* and) try the next address. */ * and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) { for (rp = result; rp != nullptr; rp = rp->ai_next) {
memset(&buf, 0, sizeof(buf)); memset(&buf, 0, sizeof(buf));
if (rp->ai_family == AF_INET) { if (rp->ai_family == AF_INET) {
inet_ntop(AF_INET, &((struct sockaddr_in *)rp->ai_addr)->sin_addr, buf, sizeof(buf)-1); inet_ntop(AF_INET, &((struct sockaddr_in *)rp->ai_addr)->sin_addr, buf, sizeof(buf)-1);
@ -645,7 +645,7 @@ bool InetSocket::bind( const char * host, const char * serv )
mSd = -1; mSd = -1;
} }
if (rp == NULL) { /* No address succeeded */ if (rp == nullptr) { /* No address succeeded */
Error( "bind(), Could not bind" ); Error( "bind(), Could not bind" );
return( false ); return( false );
} }
@ -657,7 +657,7 @@ bool InetSocket::bind( const char * host, const char * serv )
bool InetSocket::bind( const char * serv ) bool InetSocket::bind( const char * serv )
{ {
return bind( NULL, serv); return bind( nullptr, serv);
} }
bool InetSocket::bind( const char * host, int port ) bool InetSocket::bind( const char * host, int port )
@ -673,7 +673,7 @@ bool InetSocket::bind( int port )
char serv[8]; char serv[8];
snprintf(serv, sizeof(serv), "%d", port); snprintf(serv, sizeof(serv), "%d", port);
return bind( NULL, serv ); return bind( nullptr, serv );
} }
bool TcpInetServer::listen() bool TcpInetServer::listen()
@ -689,7 +689,7 @@ bool TcpInetServer::accept()
bool TcpInetServer::accept( TcpInetSocket *&newSocket ) bool TcpInetServer::accept( TcpInetSocket *&newSocket )
{ {
int newSd = -1; int newSd = -1;
newSocket = 0; newSocket = nullptr;
if ( !Socket::accept( newSd ) ) if ( !Socket::accept( newSd ) )
return( false ); return( false );
@ -702,7 +702,7 @@ bool TcpInetServer::accept( TcpInetSocket *&newSocket )
bool TcpUnixServer::accept( TcpUnixSocket *&newSocket ) bool TcpUnixServer::accept( TcpUnixSocket *&newSocket )
{ {
int newSd = -1; int newSd = -1;
newSocket = 0; newSocket = nullptr;
if ( !Socket::accept( newSd ) ) if ( !Socket::accept( newSd ) )
return( false ); return( false );
@ -830,7 +830,7 @@ void Select::clearWriters()
int Select::wait() int Select::wait()
{ {
struct timeval tempTimeout = mTimeout; struct timeval tempTimeout = mTimeout;
struct timeval *selectTimeout = mHasTimeout?&tempTimeout:NULL; struct timeval *selectTimeout = mHasTimeout?&tempTimeout:nullptr;
fd_set rfds; fd_set rfds;
fd_set wfds; fd_set wfds;
@ -845,7 +845,7 @@ int Select::wait()
for ( CommsSet::iterator iter = mWriters.begin(); iter != mWriters.end(); ++iter ) for ( CommsSet::iterator iter = mWriters.begin(); iter != mWriters.end(); ++iter )
FD_SET((*iter)->getWriteDesc(),&wfds); FD_SET((*iter)->getWriteDesc(),&wfds);
int nFound = select( mMaxFd+1, &rfds, &wfds, NULL, selectTimeout ); int nFound = select( mMaxFd+1, &rfds, &wfds, nullptr, selectTimeout );
if( nFound == 0 ) if( nFound == 0 )
{ {
Debug( 1, "Select timed out" ); Debug( 1, "Select timed out" );

View File

@ -416,8 +416,8 @@ public:
} }
public: public:
virtual int sendto( const void *msg, int len, const SockAddr *addr=0 ) const { virtual int sendto( const void *msg, int len, const SockAddr *addr=nullptr ) const {
ssize_t nBytes = ::sendto( mSd, msg, len, 0, addr?addr->getAddr():NULL, addr?addr->getAddrSize():0 ); ssize_t nBytes = ::sendto( mSd, msg, len, 0, addr?addr->getAddr():nullptr, addr?addr->getAddrSize():0 );
if ( nBytes < 0 ) if ( nBytes < 0 )
Debug( 1, "Sendto of %d bytes on sd %d failed: %s", len, mSd, strerror(errno) ); Debug( 1, "Sendto of %d bytes on sd %d failed: %s", len, mSd, strerror(errno) );
return( nBytes ); return( nBytes );
@ -432,7 +432,7 @@ public:
Debug( 1, "Recvfrom of %d bytes max on sd %d (with address) failed: %s", len, mSd, strerror(errno) ); Debug( 1, "Recvfrom of %d bytes max on sd %d (with address) failed: %s", len, mSd, strerror(errno) );
} }
} else { } else {
nBytes = ::recvfrom( mSd, msg, len, 0, NULL, 0 ); nBytes = ::recvfrom( mSd, msg, len, 0, nullptr, 0 );
if ( nBytes < 0 ) if ( nBytes < 0 )
Debug( 1, "Recvfrom of %d bytes max on sd %d (no address) failed: %s", len, mSd, strerror(errno) ); Debug( 1, "Recvfrom of %d bytes max on sd %d (no address) failed: %s", len, mSd, strerror(errno) );
} }

View File

@ -36,8 +36,7 @@
void zmLoadConfig() { void zmLoadConfig() {
// Process name, value pairs from the main config file first // Process name, value pairs from the main config file first
char configFile[PATH_MAX] = ZM_CONFIG; process_configfile(ZM_CONFIG);
process_configfile(configFile);
// Search for user created config files. If one or more are found then // Search for user created config files. If one or more are found then
// update the Config hash with those values // update the Config hash with those values
@ -108,14 +107,14 @@ void zmLoadConfig() {
snprintf(staticConfig.video_file_format, sizeof(staticConfig.video_file_format), "%%s/%%s"); snprintf(staticConfig.video_file_format, sizeof(staticConfig.video_file_format), "%%s/%%s");
} }
void process_configfile(char* configFile) { void process_configfile(char const *configFile) {
FILE *cfg; FILE *cfg;
char line[512]; char line[512];
if ( (cfg = fopen(configFile, "r")) == NULL ) { if ( (cfg = fopen(configFile, "r")) == nullptr ) {
Fatal("Can't open %s: %s", configFile, strerror(errno)); Fatal("Can't open %s: %s", configFile, strerror(errno));
return; return;
} }
while ( fgets(line, sizeof(line), cfg) != NULL ) { while ( fgets(line, sizeof(line), cfg) != nullptr ) {
char *line_ptr = line; char *line_ptr = line;
// Trim off any cr/lf line endings // Trim off any cr/lf line endings
@ -260,16 +259,16 @@ ConfigItem::~ConfigItem() {
void ConfigItem::ConvertValue() const { void ConfigItem::ConvertValue() const {
if ( !strcmp( type, "boolean" ) ) { if ( !strcmp( type, "boolean" ) ) {
cfg_type = CFG_BOOLEAN; cfg_type = CFG_BOOLEAN;
cfg_value.boolean_value = (bool)strtol(value, 0, 0); cfg_value.boolean_value = (bool)strtol(value, nullptr, 0);
} else if ( !strcmp(type, "integer") ) { } else if ( !strcmp(type, "integer") ) {
cfg_type = CFG_INTEGER; cfg_type = CFG_INTEGER;
cfg_value.integer_value = strtol(value, 0, 10); cfg_value.integer_value = strtol(value, nullptr, 10);
} else if ( !strcmp(type, "hexadecimal") ) { } else if ( !strcmp(type, "hexadecimal") ) {
cfg_type = CFG_INTEGER; cfg_type = CFG_INTEGER;
cfg_value.integer_value = strtol(value, 0, 16); cfg_value.integer_value = strtol(value, nullptr, 16);
} else if ( !strcmp(type, "decimal") ) { } else if ( !strcmp(type, "decimal") ) {
cfg_type = CFG_DECIMAL; cfg_type = CFG_DECIMAL;
cfg_value.decimal_value = strtod(value, 0); cfg_value.decimal_value = strtod(value, nullptr);
} else { } else {
cfg_type = CFG_STRING; cfg_type = CFG_STRING;
cfg_value.string_value = value; cfg_value.string_value = value;
@ -334,10 +333,10 @@ Config::~Config() {
if ( items ) { if ( items ) {
for ( int i = 0; i < n_items; i++ ) { for ( int i = 0; i < n_items; i++ ) {
delete items[i]; delete items[i];
items[i] = NULL; items[i] = nullptr;
} }
delete[] items; delete[] items;
items = NULL; items = nullptr;
} }
} }

View File

@ -23,19 +23,13 @@
#if !defined(PATH_MAX) #if !defined(PATH_MAX)
#define PATH_MAX 1024 #define PATH_MAX 1024
#endif #endif
#include "config.h" #include "config.h"
#include "zm_config_defines.h" #include "zm_config_defines.h"
#include "zm_config_data.h"
#include <string> #include <string>
#define ZM_CONFIG "@ZM_CONFIG@" // Path to config file
#define ZM_CONFIG_SUBDIR "@ZM_CONFIG_SUBDIR@" // Path to the ZoneMinder config subfolder
#define ZM_VERSION "@VERSION@" // ZoneMinder Version
#define ZM_HAS_V4L1 @ZM_HAS_V4L1@
#define ZM_HAS_V4L2 @ZM_HAS_V4L2@
#define ZM_HAS_V4L @ZM_HAS_V4L@
#ifdef HAVE_LIBAVFORMAT #ifdef HAVE_LIBAVFORMAT
#define ZM_HAS_FFMPEG 1 #define ZM_HAS_FFMPEG 1
#endif // HAVE_LIBAVFORMAT #endif // HAVE_LIBAVFORMAT
@ -62,7 +56,7 @@
extern void zmLoadConfig(); extern void zmLoadConfig();
extern void process_configfile( char* configFile ); extern void process_configfile(char const *configFile);
struct StaticConfig { struct StaticConfig {
std::string DB_HOST; std::string DB_HOST;

31
src/zm_config_data.h.in Normal file
View File

@ -0,0 +1,31 @@
//
// ZoneMinder Configuration, $Date$, $Revision$
// Copyright (C) 2001-2008 Philip Coombes
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#ifndef ZM_CONFIG_DATA_H
#define ZM_CONFIG_DATA_H
#define ZM_CONFIG "@ZM_CONFIG@" // Path to config file
#define ZM_CONFIG_SUBDIR "@ZM_CONFIG_SUBDIR@" // Path to the ZoneMinder config subfolder
#define ZM_VERSION "@VERSION@" // ZoneMinder Version
#define ZM_HAS_V4L1 @ZM_HAS_V4L1@
#define ZM_HAS_V4L2 @ZM_HAS_V4L2@
#define ZM_HAS_V4L @ZM_HAS_V4L@
#endif // ZM_CONFIG_DATA_H

View File

@ -106,26 +106,26 @@ void cURLCamera::Initialise() {
Debug(2,"libcurl version: %s", (*curl_version_f)()); Debug(2,"libcurl version: %s", (*curl_version_f)());
/* Create the shared data mutex */ /* Create the shared data mutex */
int nRet = pthread_mutex_init(&shareddata_mutex, NULL); int nRet = pthread_mutex_init(&shareddata_mutex, nullptr);
if(nRet != 0) { if(nRet != 0) {
Error("Shared data mutex creation failed: %s",strerror(nRet)); Error("Shared data mutex creation failed: %s",strerror(nRet));
return; return;
} }
/* Create the data available condition variable */ /* Create the data available condition variable */
nRet = pthread_cond_init(&data_available_cond, NULL); nRet = pthread_cond_init(&data_available_cond, nullptr);
if(nRet != 0) { if(nRet != 0) {
Error("Data available condition variable creation failed: %s",strerror(nRet)); Error("Data available condition variable creation failed: %s",strerror(nRet));
return; return;
} }
/* Create the request complete condition variable */ /* Create the request complete condition variable */
nRet = pthread_cond_init(&request_complete_cond, NULL); nRet = pthread_cond_init(&request_complete_cond, nullptr);
if(nRet != 0) { if(nRet != 0) {
Error("Request complete condition variable creation failed: %s",strerror(nRet)); Error("Request complete condition variable creation failed: %s",strerror(nRet));
return; return;
} }
/* Create the thread */ /* Create the thread */
nRet = pthread_create(&thread, NULL, thread_func_dispatcher, this); nRet = pthread_create(&thread, nullptr, thread_func_dispatcher, this);
if(nRet != 0) { if(nRet != 0) {
Error("Thread creation failed: %s",strerror(nRet)); Error("Thread creation failed: %s",strerror(nRet));
return; return;
@ -137,7 +137,7 @@ void cURLCamera::Terminate() {
bTerminate = true; bTerminate = true;
/* Wait for thread termination */ /* Wait for thread termination */
pthread_join(thread, NULL); pthread_join(thread, nullptr);
/* Destroy condition variables */ /* Destroy condition variables */
pthread_cond_destroy(&request_complete_cond); pthread_cond_destroy(&request_complete_cond);
@ -425,7 +425,7 @@ void* cURLCamera::thread_func() {
double dSize; double dSize;
c = (*curl_easy_init_f)(); c = (*curl_easy_init_f)();
if(c == NULL) { if(c == nullptr) {
dlclose(curl_lib); dlclose(curl_lib);
Error("Failed getting easy handle from libcurl"); Error("Failed getting easy handle from libcurl");
tRet = -51; tRet = -51;
@ -572,7 +572,7 @@ void* cURLCamera::thread_func() {
/* Cleanup */ /* Cleanup */
(*curl_easy_cleanup_f)(c); (*curl_easy_cleanup_f)(c);
c = NULL; c = nullptr;
return (void*)tRet; return (void*)tRet;
} }

View File

@ -48,10 +48,10 @@ bool zmDbConnect() {
staticConfig.DB_SSL_CLIENT_KEY.c_str(), staticConfig.DB_SSL_CLIENT_KEY.c_str(),
staticConfig.DB_SSL_CLIENT_CERT.c_str(), staticConfig.DB_SSL_CLIENT_CERT.c_str(),
staticConfig.DB_SSL_CA_CERT.c_str(), staticConfig.DB_SSL_CA_CERT.c_str(),
NULL, NULL); nullptr, nullptr);
std::string::size_type colonIndex = staticConfig.DB_HOST.find(":"); std::string::size_type colonIndex = staticConfig.DB_HOST.find(":");
if ( colonIndex == std::string::npos ) { if ( colonIndex == std::string::npos ) {
if ( !mysql_real_connect(&dbconn, staticConfig.DB_HOST.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, 0, NULL, 0) ) { if ( !mysql_real_connect(&dbconn, staticConfig.DB_HOST.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), nullptr, 0, nullptr, 0) ) {
Error( "Can't connect to server: %s", mysql_error(&dbconn)); Error( "Can't connect to server: %s", mysql_error(&dbconn));
return false; return false;
} }
@ -59,12 +59,12 @@ bool zmDbConnect() {
std::string dbHost = staticConfig.DB_HOST.substr( 0, colonIndex ); std::string dbHost = staticConfig.DB_HOST.substr( 0, colonIndex );
std::string dbPortOrSocket = staticConfig.DB_HOST.substr( colonIndex+1 ); std::string dbPortOrSocket = staticConfig.DB_HOST.substr( colonIndex+1 );
if ( dbPortOrSocket[0] == '/' ) { if ( dbPortOrSocket[0] == '/' ) {
if ( !mysql_real_connect(&dbconn, NULL, staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, 0, dbPortOrSocket.c_str(), 0) ) { if ( !mysql_real_connect(&dbconn, nullptr, staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), nullptr, 0, dbPortOrSocket.c_str(), 0) ) {
Error("Can't connect to server: %s", mysql_error(&dbconn)); Error("Can't connect to server: %s", mysql_error(&dbconn));
return false; return false;
} }
} else { } else {
if ( !mysql_real_connect( &dbconn, dbHost.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), NULL, atoi(dbPortOrSocket.c_str()), NULL, 0 ) ) { if ( !mysql_real_connect( &dbconn, dbHost.c_str(), staticConfig.DB_USER.c_str(), staticConfig.DB_PASS.c_str(), nullptr, atoi(dbPortOrSocket.c_str()), nullptr, 0 ) ) {
Error( "Can't connect to server: %s", mysql_error( &dbconn ) ); Error( "Can't connect to server: %s", mysql_error( &dbconn ) );
return false; return false;
} }
@ -94,20 +94,20 @@ void zmDbClose() {
MYSQL_RES * zmDbFetch(const char * query) { MYSQL_RES * zmDbFetch(const char * query) {
if ( !zmDbConnected ) { if ( !zmDbConnected ) {
Error("Not connected."); Error("Not connected.");
return NULL; return nullptr;
} }
db_mutex.lock(); db_mutex.lock();
// Might have been disconnected while we waited for the lock // Might have been disconnected while we waited for the lock
if ( !zmDbConnected ) { if ( !zmDbConnected ) {
db_mutex.unlock(); db_mutex.unlock();
Error("Not connected."); Error("Not connected.");
return NULL; return nullptr;
} }
if ( mysql_query(&dbconn, query) ) { if ( mysql_query(&dbconn, query) ) {
db_mutex.unlock(); db_mutex.unlock();
Error("Can't run query: %s", mysql_error(&dbconn)); Error("Can't run query: %s", mysql_error(&dbconn));
return NULL; return nullptr;
} }
Debug(4, "Success running query: %s", query); Debug(4, "Success running query: %s", query);
MYSQL_RES *result = mysql_store_result(&dbconn); MYSQL_RES *result = mysql_store_result(&dbconn);
@ -124,7 +124,7 @@ zmDbRow *zmDbFetchOne(const char *query) {
return row; return row;
} }
delete row; delete row;
return NULL; return nullptr;
} }
MYSQL_RES *zmDbRow::fetch(const char *query) { MYSQL_RES *zmDbRow::fetch(const char *query) {
@ -135,14 +135,14 @@ MYSQL_RES *zmDbRow::fetch(const char *query) {
if ( n_rows != 1 ) { if ( n_rows != 1 ) {
Error("Bogus number of lines return from query, %d returned for query %s.", n_rows, query); Error("Bogus number of lines return from query, %d returned for query %s.", n_rows, query);
mysql_free_result(result_set); mysql_free_result(result_set);
result_set = NULL; result_set = nullptr;
return result_set; return result_set;
} }
row = mysql_fetch_row(result_set); row = mysql_fetch_row(result_set);
if ( ! row ) { if ( ! row ) {
mysql_free_result(result_set); mysql_free_result(result_set);
result_set = NULL; result_set = nullptr;
Error("Error getting row from query %s. Error is %s", query, mysql_error(&dbconn)); Error("Error getting row from query %s. Error is %s", query, mysql_error(&dbconn));
} else { } else {
Debug(5, "Success"); Debug(5, "Success");
@ -153,6 +153,6 @@ MYSQL_RES *zmDbRow::fetch(const char *query) {
zmDbRow::~zmDbRow() { zmDbRow::~zmDbRow() {
if ( result_set ) { if ( result_set ) {
mysql_free_result(result_set); mysql_free_result(result_set);
result_set = NULL; result_set = nullptr;
} }
} }

View File

@ -28,7 +28,7 @@ class zmDbRow {
MYSQL_RES *result_set; MYSQL_RES *result_set;
MYSQL_ROW row; MYSQL_ROW row;
public: public:
zmDbRow() { result_set = NULL; row = NULL; }; zmDbRow() { result_set = nullptr; row = nullptr; };
MYSQL_RES *fetch( const char *query ); MYSQL_RES *fetch( const char *query );
zmDbRow( MYSQL_RES *, MYSQL_ROW *row ); zmDbRow( MYSQL_RES *, MYSQL_ROW *row );
~zmDbRow(); ~zmDbRow();

View File

@ -55,7 +55,7 @@ Event::Event(
cause(p_cause), cause(p_cause),
noteSetMap(p_noteSetMap), noteSetMap(p_noteSetMap),
videoEvent(p_videoEvent), videoEvent(p_videoEvent),
videowriter(NULL) videowriter(nullptr)
{ {
std::string notes; std::string notes;
@ -222,19 +222,19 @@ Event::Event(
Error("ZoneMinder was not compiled with the X264 MP4 video writer, check dependencies (x264 and mp4v2)"); Error("ZoneMinder was not compiled with the X264 MP4 video writer, check dependencies (x264 and mp4v2)");
#endif #endif
if ( videowriter != NULL ) { if ( videowriter != nullptr ) {
/* Open the video stream */ /* Open the video stream */
int nRet = videowriter->Open(); int nRet = videowriter->Open();
if ( nRet != 0 ) { if ( nRet != 0 ) {
Error("Failed opening video stream"); Error("Failed opening video stream");
delete videowriter; delete videowriter;
videowriter = NULL; videowriter = nullptr;
} }
} }
} }
} else { } else {
/* No video object */ /* No video object */
videowriter = NULL; videowriter = nullptr;
} }
} // Event::Event( Monitor *p_monitor, struct timeval p_start_time, const std::string &p_cause, const StringSetMap &p_noteSetMap, bool p_videoEvent ) } // Event::Event( Monitor *p_monitor, struct timeval p_start_time, const std::string &p_cause, const StringSetMap &p_noteSetMap, bool p_videoEvent )
@ -242,13 +242,13 @@ Event::~Event() {
// We close the videowriter first, because if we finish the event, we might try to view the file, but we aren't done writing it yet. // We close the videowriter first, because if we finish the event, we might try to view the file, but we aren't done writing it yet.
/* Close the video file */ /* Close the video file */
if ( videowriter != NULL ) { if ( videowriter != nullptr ) {
int nRet = videowriter->Close(); int nRet = videowriter->Close();
if ( nRet != 0 ) { if ( nRet != 0 ) {
Error("Failed closing video stream"); Error("Failed closing video stream");
} }
delete videowriter; delete videowriter;
videowriter = NULL; videowriter = nullptr;
} }
struct DeltaTimeval delta_time; struct DeltaTimeval delta_time;
@ -347,7 +347,7 @@ bool Event::WriteFrameVideo(
Image ts_image; Image ts_image;
/* Checking for invalid parameters */ /* Checking for invalid parameters */
if ( videow == NULL ) { if ( videow == nullptr ) {
Error("NULL Video object"); Error("NULL Video object");
return false; return false;
} }
@ -509,7 +509,7 @@ void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, str
WriteFrameImage(images[i], *(timestamps[i]), snapshot_file.c_str()); WriteFrameImage(images[i], *(timestamps[i]), snapshot_file.c_str());
} }
if ( videowriter != NULL ) { if ( videowriter != nullptr ) {
WriteFrameVideo(images[i], *(timestamps[i]), videowriter); WriteFrameVideo(images[i], *(timestamps[i]), videowriter);
} }
@ -646,7 +646,7 @@ void Event::AddFrame(Image *image, struct timeval timestamp, int score, Image *a
} }
} // end if frame_type == ALARM } // end if frame_type == ALARM
if ( videowriter != NULL ) { if ( videowriter != nullptr ) {
WriteFrameVideo(image, timestamp, videowriter); WriteFrameVideo(image, timestamp, videowriter);
} }

View File

@ -129,7 +129,7 @@ class Event {
void updateNotes( const StringSetMap &stringSetMap ); void updateNotes( const StringSetMap &stringSetMap );
void AddFrames( int n_frames, Image **images, struct timeval **timestamps ); void AddFrames( int n_frames, Image **images, struct timeval **timestamps );
void AddFrame( Image *image, struct timeval timestamp, int score=0, Image *alarm_frame=NULL ); void AddFrame( Image *image, struct timeval timestamp, int score=0, Image *alarm_frame=nullptr );
private: private:
void AddFramesInternal( int n_frames, int start_frame, Image **images, struct timeval **timestamps ); void AddFramesInternal( int n_frames, int start_frame, Image **images, struct timeval **timestamps );
@ -158,16 +158,16 @@ class Event {
while ( pre_alarm_count > 0 ) { while ( pre_alarm_count > 0 ) {
int i = pre_alarm_count - 1; int i = pre_alarm_count - 1;
delete pre_alarm_data[i].image; delete pre_alarm_data[i].image;
pre_alarm_data[i].image = NULL; pre_alarm_data[i].image = nullptr;
if ( pre_alarm_data[i].alarm_frame ) { if ( pre_alarm_data[i].alarm_frame ) {
delete pre_alarm_data[i].alarm_frame; delete pre_alarm_data[i].alarm_frame;
pre_alarm_data[i].alarm_frame = NULL; pre_alarm_data[i].alarm_frame = nullptr;
} }
pre_alarm_count--; pre_alarm_count--;
} }
pre_alarm_count = 0; pre_alarm_count = 0;
} }
static void AddPreAlarmFrame(Image *image, struct timeval timestamp, int score=0, Image *alarm_frame=NULL) { static void AddPreAlarmFrame(Image *image, struct timeval timestamp, int score=0, Image *alarm_frame=nullptr) {
pre_alarm_data[pre_alarm_count].image = new Image(*image); pre_alarm_data[pre_alarm_count].image = new Image(*image);
pre_alarm_data[pre_alarm_count].timestamp = timestamp; pre_alarm_data[pre_alarm_count].timestamp = timestamp;
pre_alarm_data[pre_alarm_count].score = score; pre_alarm_data[pre_alarm_count].score = score;

View File

@ -148,7 +148,7 @@ bool EventStream::loadEventData(uint64_t event_id) {
event_data->monitor_id = atoi(dbrow[0]); event_data->monitor_id = atoi(dbrow[0]);
event_data->storage_id = dbrow[1] ? atoi(dbrow[1]) : 0; event_data->storage_id = dbrow[1] ? atoi(dbrow[1]) : 0;
event_data->frame_count = dbrow[2] == NULL ? 0 : atoi(dbrow[2]); event_data->frame_count = dbrow[2] == nullptr ? 0 : atoi(dbrow[2]);
event_data->start_time = atoi(dbrow[3]); event_data->start_time = atoi(dbrow[3]);
event_data->duration = dbrow[4] ? atof(dbrow[4]) : 0.0; event_data->duration = dbrow[4] ? atof(dbrow[4]) : 0.0;
strncpy(event_data->video_file, dbrow[5], sizeof(event_data->video_file)-1); strncpy(event_data->video_file, dbrow[5], sizeof(event_data->video_file)-1);
@ -160,8 +160,8 @@ bool EventStream::loadEventData(uint64_t event_id) {
} else { } else {
event_data->scheme = Storage::SHALLOW; event_data->scheme = Storage::SHALLOW;
} }
event_data->SaveJPEGs = dbrow[7] == NULL ? 0 : atoi(dbrow[7]); event_data->SaveJPEGs = dbrow[7] == nullptr ? 0 : atoi(dbrow[7]);
event_data->Orientation = (Monitor::Orientation)(dbrow[8] == NULL ? 0 : atoi(dbrow[8])); event_data->Orientation = (Monitor::Orientation)(dbrow[8] == nullptr ? 0 : atoi(dbrow[8]));
mysql_free_result(result); mysql_free_result(result);
if ( !monitor ) { if ( !monitor ) {
@ -303,7 +303,7 @@ bool EventStream::loadEventData(uint64_t event_id) {
if ( 0 > ffmpeg_input->Open(filepath.c_str()) ) { if ( 0 > ffmpeg_input->Open(filepath.c_str()) ) {
Warning("Unable to open ffmpeg_input %s", filepath.c_str()); Warning("Unable to open ffmpeg_input %s", filepath.c_str());
delete ffmpeg_input; delete ffmpeg_input;
ffmpeg_input = NULL; ffmpeg_input = nullptr;
} }
} }
@ -646,7 +646,7 @@ bool EventStream::sendFrame(int delta_us) {
static char filepath[PATH_MAX]; static char filepath[PATH_MAX];
static struct stat filestat; static struct stat filestat;
FILE *fdj = NULL; FILE *fdj = nullptr;
// This needs to be abstracted. If we are saving jpgs, then load the capture file. // This needs to be abstracted. If we are saving jpgs, then load the capture file.
// If we are only saving analysis frames, then send that. // If we are only saving analysis frames, then send that.
@ -711,7 +711,7 @@ bool EventStream::sendFrame(int delta_us) {
img_buffer_size = fread(img_buffer, 1, sizeof(temp_img_buffer), fdj); img_buffer_size = fread(img_buffer, 1, sizeof(temp_img_buffer), fdj);
#endif #endif
} else { } else {
Image *image = NULL; Image *image = nullptr;
if ( filepath[0] ) { if ( filepath[0] ) {
image = new Image(filepath); image = new Image(filepath);
@ -790,7 +790,7 @@ bool EventStream::sendFrame(int delta_us) {
break; break;
} }
delete image; delete image;
image = NULL; image = nullptr;
} // end if send_raw or not } // end if send_raw or not
switch ( type ) { switch ( type ) {
@ -870,7 +870,7 @@ void EventStream::runStream() {
Debug(3, "frame rate is: (%f)", (double)event_data->frame_count/event_data->duration); Debug(3, "frame rate is: (%f)", (double)event_data->frame_count/event_data->duration);
updateFrameRate((double)event_data->frame_count/event_data->duration); updateFrameRate((double)event_data->frame_count/event_data->duration);
gettimeofday(&start, NULL); gettimeofday(&start, nullptr);
uint64_t start_usec = start.tv_sec * 1000000 + start.tv_usec; uint64_t start_usec = start.tv_sec * 1000000 + start.tv_usec;
uint64_t last_frame_offset = 0; uint64_t last_frame_offset = 0;
@ -878,7 +878,7 @@ void EventStream::runStream() {
double time_to_event = 0; double time_to_event = 0;
while ( !zm_terminate ) { while ( !zm_terminate ) {
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
int delta_us = 0; int delta_us = 0;
send_frame = false; send_frame = false;
@ -982,7 +982,7 @@ void EventStream::runStream() {
// +/- 1? What if we are skipping frames? // +/- 1? What if we are skipping frames?
curr_frame_id += (replay_rate>0) ? frame_mod : -1*frame_mod; curr_frame_id += (replay_rate>0) ? frame_mod : -1*frame_mod;
// sending the frame may have taken some time, so reload now // sending the frame may have taken some time, so reload now
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
uint64_t now_usec = (now.tv_sec * 1000000 + now.tv_usec); uint64_t now_usec = (now.tv_sec * 1000000 + now.tv_usec);
// we incremented by replay_rate, so might have jumped past frame_count // we incremented by replay_rate, so might have jumped past frame_count

View File

@ -97,33 +97,33 @@ class EventStream : public StreamBase {
curr_frame_id(0), curr_frame_id(0),
curr_stream_time(0.0), curr_stream_time(0.0),
send_frame(false), send_frame(false),
event_data(0), event_data(nullptr),
storage(NULL), storage(nullptr),
ffmpeg_input(NULL), ffmpeg_input(nullptr),
// Used when loading frames from an mp4 // Used when loading frames from an mp4
input_codec_context(0), input_codec_context(nullptr),
input_codec(0) input_codec(nullptr)
{} {}
~EventStream() { ~EventStream() {
if ( event_data ) { if ( event_data ) {
if ( event_data->frames ) { if ( event_data->frames ) {
delete[] event_data->frames; delete[] event_data->frames;
event_data->frames = NULL; event_data->frames = nullptr;
} }
delete event_data; delete event_data;
event_data = NULL; event_data = nullptr;
} }
if ( monitor ) { if ( monitor ) {
delete monitor; delete monitor;
monitor = NULL; monitor = nullptr;
} }
if ( storage ) { if ( storage ) {
delete storage; delete storage;
storage = NULL; storage = nullptr;
} }
if ( ffmpeg_input ) { if ( ffmpeg_input ) {
delete ffmpeg_input; delete ffmpeg_input;
ffmpeg_input = NULL; ffmpeg_input = nullptr;
} }
} }
void setStreamStart( uint64_t init_event_id, unsigned int init_frame_id ); void setStreamStart( uint64_t init_event_id, unsigned int init_frame_id );

View File

@ -151,7 +151,7 @@ static int parse_key_value_pair(AVDictionary **pm, const char **buf,
int flags) int flags)
{ {
char *key = av_get_token(buf, key_val_sep); char *key = av_get_token(buf, key_val_sep);
char *val = NULL; char *val = nullptr;
int ret; int ret;
if (key && *key && strspn(*buf, key_val_sep)) { if (key && *key && strspn(*buf, key_val_sep)) {
@ -225,7 +225,7 @@ int hacked_up_context2_for_older_ffmpeg(AVFormatContext **avctx, AVOutputFormat
AVFormatContext *s = avformat_alloc_context(); AVFormatContext *s = avformat_alloc_context();
int ret = 0; int ret = 0;
*avctx = NULL; *avctx = nullptr;
if (!s) { if (!s) {
av_log(s, AV_LOG_ERROR, "Out of memory\n"); av_log(s, AV_LOG_ERROR, "Out of memory\n");
ret = AVERROR(ENOMEM); ret = AVERROR(ENOMEM);
@ -234,13 +234,13 @@ int hacked_up_context2_for_older_ffmpeg(AVFormatContext **avctx, AVOutputFormat
if (!oformat) { if (!oformat) {
if (format) { if (format) {
oformat = av_guess_format(format, NULL, NULL); oformat = av_guess_format(format, nullptr, nullptr);
if (!oformat) { if (!oformat) {
av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format); av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
ret = AVERROR(EINVAL); ret = AVERROR(EINVAL);
} }
} else { } else {
oformat = av_guess_format(NULL, filename, NULL); oformat = av_guess_format(nullptr, filename, nullptr);
if (!oformat) { if (!oformat) {
ret = AVERROR(EINVAL); ret = AVERROR(EINVAL);
av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n", filename); av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n", filename);
@ -267,7 +267,7 @@ int hacked_up_context2_for_older_ffmpeg(AVFormatContext **avctx, AVOutputFormat
ret = AVERROR(ENOMEM); ret = AVERROR(ENOMEM);
return ret; return ret;
} }
s->priv_data = NULL; s->priv_data = nullptr;
} }
#endif #endif
@ -335,7 +335,7 @@ void zm_dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
Debug(1, "Dumping stream index i(%d) index(%d)", i, index ); Debug(1, "Dumping stream index i(%d) index(%d)", i, index );
int flags = (is_output ? ic->oformat->flags : ic->iformat->flags); int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
AVStream *st = ic->streams[i]; AVStream *st = ic->streams[i];
AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0); AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", nullptr, 0);
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
AVCodecParameters *codec = st->codecpar; AVCodecParameters *codec = st->codecpar;
#else #else
@ -533,7 +533,7 @@ int zm_receive_packet(AVCodecContext *context, AVPacket &packet) {
return 1; return 1;
#else #else
int got_packet = 0; int got_packet = 0;
int ret = avcodec_encode_audio2(context, &packet, NULL, &got_packet); int ret = avcodec_encode_audio2(context, &packet, nullptr, &got_packet);
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Error encoding (%d) (%s)", ret, av_err2str(ret)); Error("Error encoding (%d) (%s)", ret, av_err2str(ret));
} }
@ -719,7 +719,7 @@ int zm_resample_audio(
Error("Flushing resampler not supported by AVRESAMPLE"); Error("Flushing resampler not supported by AVRESAMPLE");
return 0; return 0;
} }
int ret = avresample_convert(resample_ctx, NULL, 0, 0, in_frame->data, int ret = avresample_convert(resample_ctx, nullptr, 0, 0, in_frame->data,
0, in_frame->nb_samples); 0, in_frame->nb_samples);
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Could not resample frame (error '%s')", Error("Could not resample frame (error '%s')",

View File

@ -133,32 +133,32 @@ FfmpegCamera::FfmpegCamera(
Initialise(); Initialise();
} }
mFormatContext = NULL; mFormatContext = nullptr;
mVideoStreamId = -1; mVideoStreamId = -1;
mAudioStreamId = -1; mAudioStreamId = -1;
mVideoCodecContext = NULL; mVideoCodecContext = nullptr;
mAudioCodecContext = NULL; mAudioCodecContext = nullptr;
mVideoCodec = NULL; mVideoCodec = nullptr;
mAudioCodec = NULL; mAudioCodec = nullptr;
mRawFrame = NULL; mRawFrame = nullptr;
mFrame = NULL; mFrame = nullptr;
frameCount = 0; frameCount = 0;
mCanCapture = false; mCanCapture = false;
videoStore = NULL; videoStore = nullptr;
have_video_keyframe = false; have_video_keyframe = false;
packetqueue = NULL; packetqueue = nullptr;
error_count = 0; error_count = 0;
use_hwaccel = true; use_hwaccel = true;
#if HAVE_LIBAVUTIL_HWCONTEXT_H #if HAVE_LIBAVUTIL_HWCONTEXT_H
hwFrame = NULL; hwFrame = nullptr;
hw_device_ctx = NULL; hw_device_ctx = nullptr;
#if LIBAVCODEC_VERSION_CHECK(57, 89, 0, 89, 0) #if LIBAVCODEC_VERSION_CHECK(57, 89, 0, 89, 0)
hw_pix_fmt = AV_PIX_FMT_NONE; hw_pix_fmt = AV_PIX_FMT_NONE;
#endif #endif
#endif #endif
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
mConvertContext = NULL; mConvertContext = nullptr;
#endif #endif
/* Has to be located inside the constructor so other components such as zma /* Has to be located inside the constructor so other components such as zma
* will receive correct colours and subpixel order */ * will receive correct colours and subpixel order */
@ -175,7 +175,7 @@ FfmpegCamera::FfmpegCamera(
Panic("Unexpected colours: %d", colours); Panic("Unexpected colours: %d", colours);
} }
frame_buffer = NULL; frame_buffer = nullptr;
// sws_scale needs 32bit aligned width and an extra 16 bytes padding, so recalculate imagesize, which was width*height*bytes_per_pixel // sws_scale needs 32bit aligned width and an extra 16 bytes padding, so recalculate imagesize, which was width*height*bytes_per_pixel
#if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0) #if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0)
alignment = 32; alignment = 32;
@ -351,10 +351,10 @@ int FfmpegCamera::OpenFfmpeg() {
// Open the input, not necessarily a file // Open the input, not necessarily a file
#if !LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 4, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 4, 0)
if ( av_open_input_file(&mFormatContext, mPath.c_str(), NULL, 0, NULL) != 0 ) if ( av_open_input_file(&mFormatContext, mPath.c_str(), nullptr, 0, nullptr) != 0 )
#else #else
// Handle options // Handle options
AVDictionary *opts = 0; AVDictionary *opts = nullptr;
ret = av_dict_parse_string(&opts, Options().c_str(), "=", ",", 0); ret = av_dict_parse_string(&opts, Options().c_str(), "=", ",", 0);
if ( ret < 0 ) { if ( ret < 0 ) {
Warning("Could not parse ffmpeg input options '%s'", Options().c_str()); Warning("Could not parse ffmpeg input options '%s'", Options().c_str());
@ -392,7 +392,7 @@ int FfmpegCamera::OpenFfmpeg() {
mFormatContext->interrupt_callback.callback = FfmpegInterruptCallback; mFormatContext->interrupt_callback.callback = FfmpegInterruptCallback;
mFormatContext->interrupt_callback.opaque = this; mFormatContext->interrupt_callback.opaque = this;
ret = avformat_open_input(&mFormatContext, mPath.c_str(), NULL, &opts); ret = avformat_open_input(&mFormatContext, mPath.c_str(), nullptr, &opts);
if ( ret != 0 ) if ( ret != 0 )
#endif #endif
{ {
@ -403,15 +403,15 @@ int FfmpegCamera::OpenFfmpeg() {
#else #else
if ( mFormatContext ) { if ( mFormatContext ) {
avformat_close_input(&mFormatContext); avformat_close_input(&mFormatContext);
mFormatContext = NULL; mFormatContext = nullptr;
} }
#endif #endif
av_dict_free(&opts); av_dict_free(&opts);
return -1; return -1;
} }
AVDictionaryEntry *e = NULL; AVDictionaryEntry *e = nullptr;
while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) { while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr ) {
Warning("Option %s not recognized by ffmpeg", e->key); Warning("Option %s not recognized by ffmpeg", e->key);
} }
av_dict_free(&opts); av_dict_free(&opts);
@ -419,7 +419,7 @@ int FfmpegCamera::OpenFfmpeg() {
#if !LIBAVFORMAT_VERSION_CHECK(53, 6, 0, 6, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 6, 0, 6, 0)
ret = av_find_stream_info(mFormatContext); ret = av_find_stream_info(mFormatContext);
#else #else
ret = avformat_find_stream_info(mFormatContext, 0); ret = avformat_find_stream_info(mFormatContext, nullptr);
#endif #endif
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Unable to find stream info from %s due to: %s", Error("Unable to find stream info from %s due to: %s",
@ -474,7 +474,7 @@ int FfmpegCamera::OpenFfmpeg() {
#endif #endif
if ( mVideoCodecContext->codec_id == AV_CODEC_ID_H264 ) { if ( mVideoCodecContext->codec_id == AV_CODEC_ID_H264 ) {
if ( (mVideoCodec = avcodec_find_decoder_by_name("h264_mmal")) == NULL ) { if ( (mVideoCodec = avcodec_find_decoder_by_name("h264_mmal")) == nullptr ) {
Debug(1, "Failed to find decoder (h264_mmal)"); Debug(1, "Failed to find decoder (h264_mmal)");
} else { } else {
Debug(1, "Success finding decoder (h264_mmal)"); Debug(1, "Success finding decoder (h264_mmal)");
@ -540,7 +540,7 @@ int FfmpegCamera::OpenFfmpeg() {
hw_pix_fmt, av_get_pix_fmt_name(hw_pix_fmt)); hw_pix_fmt, av_get_pix_fmt_name(hw_pix_fmt));
ret = av_hwdevice_ctx_create(&hw_device_ctx, type, ret = av_hwdevice_ctx_create(&hw_device_ctx, type,
(hwaccel_device != "" ? hwaccel_device.c_str(): NULL), NULL, 0); (hwaccel_device != "" ? hwaccel_device.c_str(): nullptr), nullptr, 0);
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Failed to create hwaccel device. %s",av_make_error_string(ret).c_str()); Error("Failed to create hwaccel device. %s",av_make_error_string(ret).c_str());
hw_pix_fmt = AV_PIX_FMT_NONE; hw_pix_fmt = AV_PIX_FMT_NONE;
@ -567,8 +567,8 @@ int FfmpegCamera::OpenFfmpeg() {
#else #else
ret = avcodec_open2(mVideoCodecContext, mVideoCodec, &opts); ret = avcodec_open2(mVideoCodecContext, mVideoCodec, &opts);
#endif #endif
e = NULL; e = nullptr;
while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) { while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr ) {
Warning("Option %s not recognized by ffmpeg", e->key); Warning("Option %s not recognized by ffmpeg", e->key);
} }
if ( ret < 0 ) { if ( ret < 0 ) {
@ -587,7 +587,7 @@ int FfmpegCamera::OpenFfmpeg() {
#else #else
mFormatContext->streams[mAudioStreamId]->codec->codec_id mFormatContext->streams[mAudioStreamId]->codec->codec_id
#endif #endif
)) == NULL ) { )) == nullptr ) {
Debug(1, "Can't find codec for audio stream from %s", mPath.c_str()); Debug(1, "Can't find codec for audio stream from %s", mPath.c_str());
} else { } else {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
@ -606,7 +606,7 @@ int FfmpegCamera::OpenFfmpeg() {
#if !LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 8, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 8, 0)
if ( avcodec_open(mAudioCodecContext, mAudioCodec) < 0 ) { if ( avcodec_open(mAudioCodecContext, mAudioCodec) < 0 ) {
#else #else
if ( avcodec_open2(mAudioCodecContext, mAudioCodec, 0) < 0 ) { if ( avcodec_open2(mAudioCodecContext, mAudioCodec, nullptr) < 0 ) {
#endif #endif
Error("Unable to open codec for audio stream from %s", mPath.c_str()); Error("Unable to open codec for audio stream from %s", mPath.c_str());
return -1; return -1;
@ -621,7 +621,7 @@ int FfmpegCamera::OpenFfmpeg() {
// Allocate space for the converted video frame // Allocate space for the converted video frame
mFrame = zm_av_frame_alloc(); mFrame = zm_av_frame_alloc();
if ( mRawFrame == NULL || mFrame == NULL ) { if ( mRawFrame == nullptr || mFrame == nullptr ) {
Error("Unable to allocate frame for %s", mPath.c_str()); Error("Unable to allocate frame for %s", mPath.c_str());
return -1; return -1;
} }
@ -670,29 +670,29 @@ int FfmpegCamera::Close() {
if ( mFrame ) { if ( mFrame ) {
av_frame_free(&mFrame); av_frame_free(&mFrame);
mFrame = NULL; mFrame = nullptr;
} }
if ( mRawFrame ) { if ( mRawFrame ) {
av_frame_free(&mRawFrame); av_frame_free(&mRawFrame);
mRawFrame = NULL; mRawFrame = nullptr;
} }
#if HAVE_LIBAVUTIL_HWCONTEXT_H #if HAVE_LIBAVUTIL_HWCONTEXT_H
if ( hwFrame ) { if ( hwFrame ) {
av_frame_free(&hwFrame); av_frame_free(&hwFrame);
hwFrame = NULL; hwFrame = nullptr;
} }
#endif #endif
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
if ( mConvertContext ) { if ( mConvertContext ) {
sws_freeContext(mConvertContext); sws_freeContext(mConvertContext);
mConvertContext = NULL; mConvertContext = nullptr;
} }
#endif #endif
if ( videoStore ) { if ( videoStore ) {
delete videoStore; delete videoStore;
videoStore = NULL; videoStore = nullptr;
} }
if ( mVideoCodecContext ) { if ( mVideoCodecContext ) {
@ -700,14 +700,14 @@ int FfmpegCamera::Close() {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// avcodec_free_context(&mVideoCodecContext); // avcodec_free_context(&mVideoCodecContext);
#endif #endif
mVideoCodecContext = NULL; // Freed by av_close_input_file mVideoCodecContext = nullptr; // Freed by av_close_input_file
} }
if ( mAudioCodecContext ) { if ( mAudioCodecContext ) {
avcodec_close(mAudioCodecContext); avcodec_close(mAudioCodecContext);
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
avcodec_free_context(&mAudioCodecContext); avcodec_free_context(&mAudioCodecContext);
#endif #endif
mAudioCodecContext = NULL; // Freed by av_close_input_file mAudioCodecContext = nullptr; // Freed by av_close_input_file
} }
#if HAVE_LIBAVUTIL_HWCONTEXT_H #if HAVE_LIBAVUTIL_HWCONTEXT_H
@ -722,12 +722,12 @@ int FfmpegCamera::Close() {
#else #else
avformat_close_input(&mFormatContext); avformat_close_input(&mFormatContext);
#endif #endif
mFormatContext = NULL; mFormatContext = nullptr;
} }
if ( packetqueue ) { if ( packetqueue ) {
delete packetqueue; delete packetqueue;
packetqueue = NULL; packetqueue = nullptr;
} }
return 0; return 0;
@ -823,7 +823,7 @@ int FfmpegCamera::CaptureAndRecord(
} // end if video } // end if video
delete videoStore; delete videoStore;
videoStore = NULL; videoStore = nullptr;
have_video_keyframe = false; have_video_keyframe = false;
monitor->SetVideoWriterEventId(0); monitor->SetVideoWriterEventId(0);
@ -839,7 +839,7 @@ int FfmpegCamera::CaptureAndRecord(
Debug(3, "Record Audio on but no audio stream found"); Debug(3, "Record Audio on but no audio stream found");
videoStore = new VideoStore((const char *) event_file, "mp4", videoStore = new VideoStore((const char *) event_file, "mp4",
mFormatContext->streams[mVideoStreamId], mFormatContext->streams[mVideoStreamId],
NULL, nullptr,
this->getMonitor()); this->getMonitor());
} else { } else {
@ -855,13 +855,13 @@ int FfmpegCamera::CaptureAndRecord(
} }
videoStore = new VideoStore((const char *) event_file, "mp4", videoStore = new VideoStore((const char *) event_file, "mp4",
mFormatContext->streams[mVideoStreamId], mFormatContext->streams[mVideoStreamId],
NULL, nullptr,
this->getMonitor()); this->getMonitor());
} // end if record_audio } // end if record_audio
if ( !videoStore->open() ) { if ( !videoStore->open() ) {
delete videoStore; delete videoStore;
videoStore = NULL; videoStore = nullptr;
} else { } else {
monitor->SetVideoWriterEventId(last_event_id); monitor->SetVideoWriterEventId(last_event_id);
@ -920,7 +920,7 @@ int FfmpegCamera::CaptureAndRecord(
if ( videoStore ) { if ( videoStore ) {
Debug(1, "Deleting videoStore instance"); Debug(1, "Deleting videoStore instance");
delete videoStore; delete videoStore;
videoStore = NULL; videoStore = nullptr;
have_video_keyframe = false; have_video_keyframe = false;
monitor->SetVideoWriterEventId(0); monitor->SetVideoWriterEventId(0);
} }
@ -1091,7 +1091,7 @@ int FfmpegCamera::transfer_to_image(
/* Request a writeable buffer of the target image */ /* Request a writeable buffer of the target image */
image_buffer = image.WriteBuffer(width, height, colours, subpixelorder); image_buffer = image.WriteBuffer(width, height, colours, subpixelorder);
if ( image_buffer == NULL ) { if ( image_buffer == nullptr ) {
Error("Failed requesting writeable buffer for the captured image."); Error("Failed requesting writeable buffer for the captured image.");
return -1; return -1;
} }
@ -1128,9 +1128,9 @@ int FfmpegCamera::transfer_to_image(
input_frame->height, input_frame->height,
(AVPixelFormat)input_frame->format, (AVPixelFormat)input_frame->format,
width, height, width, height,
imagePixFormat, SWS_BICUBIC, NULL, imagePixFormat, SWS_BICUBIC, nullptr,
NULL, NULL); nullptr, nullptr);
if ( mConvertContext == NULL ) { if ( mConvertContext == nullptr ) {
Error("Unable to create conversion context for %s from %s to %s", Error("Unable to create conversion context for %s from %s to %s",
mPath.c_str(), mPath.c_str(),
av_get_pix_fmt_name((AVPixelFormat)input_frame->format), av_get_pix_fmt_name((AVPixelFormat)input_frame->format),

View File

@ -64,7 +64,7 @@ class FfmpegCamera : public Camera {
AVFrame *hwFrame; // Will also be used to indicate if hwaccel is in use AVFrame *hwFrame; // Will also be used to indicate if hwaccel is in use
bool use_hwaccel; //will default to on if hwaccel specified, will get turned off if there is a failure bool use_hwaccel; //will default to on if hwaccel specified, will get turned off if there is a failure
#if HAVE_LIBAVUTIL_HWCONTEXT_H #if HAVE_LIBAVUTIL_HWCONTEXT_H
AVBufferRef *hw_device_ctx = NULL; AVBufferRef *hw_device_ctx = nullptr;
#endif #endif
// Used to store the incoming packet, it will get copied when queued. // Used to store the incoming packet, it will get copied when queued.

View File

@ -4,12 +4,12 @@
#include "zm_ffmpeg.h" #include "zm_ffmpeg.h"
FFmpeg_Input::FFmpeg_Input() { FFmpeg_Input::FFmpeg_Input() {
input_format_context = NULL; input_format_context = nullptr;
video_stream_id = -1; video_stream_id = -1;
audio_stream_id = -1; audio_stream_id = -1;
FFMPEGInit(); FFMPEGInit();
streams = NULL; streams = nullptr;
frame = NULL; frame = nullptr;
last_seek_request = -1; last_seek_request = -1;
} }
@ -17,14 +17,14 @@ FFmpeg_Input::~FFmpeg_Input() {
if ( streams ) { if ( streams ) {
for ( unsigned int i = 0; i < input_format_context->nb_streams; i += 1 ) { for ( unsigned int i = 0; i < input_format_context->nb_streams; i += 1 ) {
avcodec_close(streams[i].context); avcodec_close(streams[i].context);
streams[i].context = NULL; streams[i].context = nullptr;
} }
delete[] streams; delete[] streams;
streams = NULL; streams = nullptr;
} }
if ( frame ) { if ( frame ) {
av_frame_free(&frame); av_frame_free(&frame);
frame = NULL; frame = nullptr;
} }
if ( input_format_context ) { if ( input_format_context ) {
#if !LIBAVFORMAT_VERSION_CHECK(53, 17, 0, 25, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 17, 0, 25, 0)
@ -32,7 +32,7 @@ FFmpeg_Input::~FFmpeg_Input() {
#else #else
avformat_close_input(&input_format_context); avformat_close_input(&input_format_context);
#endif #endif
input_format_context = NULL; input_format_context = nullptr;
} }
} // end ~FFmpeg_Input() } // end ~FFmpeg_Input()
@ -41,16 +41,16 @@ int FFmpeg_Input::Open(const char *filepath) {
int error; int error;
/** Open the input file to read from it. */ /** Open the input file to read from it. */
error = avformat_open_input(&input_format_context, filepath, NULL, NULL); error = avformat_open_input(&input_format_context, filepath, nullptr, nullptr);
if ( error < 0 ) { if ( error < 0 ) {
Error("Could not open input file '%s' (error '%s')\n", Error("Could not open input file '%s' (error '%s')\n",
filepath, av_make_error_string(error).c_str() ); filepath, av_make_error_string(error).c_str() );
input_format_context = NULL; input_format_context = nullptr;
return error; return error;
} }
/** Get information on the input file (number of streams etc.). */ /** Get information on the input file (number of streams etc.). */
if ( (error = avformat_find_stream_info(input_format_context, NULL)) < 0 ) { if ( (error = avformat_find_stream_info(input_format_context, nullptr)) < 0 ) {
Error( Error(
"Could not open find stream info (error '%s')", "Could not open find stream info (error '%s')",
av_make_error_string(error).c_str() av_make_error_string(error).c_str()
@ -84,7 +84,7 @@ int FFmpeg_Input::Open(const char *filepath) {
streams[i].frame_count = 0; streams[i].frame_count = 0;
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
streams[i].context = avcodec_alloc_context3(NULL); streams[i].context = avcodec_alloc_context3(nullptr);
avcodec_parameters_to_context(streams[i].context, input_format_context->streams[i]->codecpar); avcodec_parameters_to_context(streams[i].context, input_format_context->streams[i]->codecpar);
#else #else
streams[i].context = input_format_context->streams[i]->codec; streams[i].context = input_format_context->streams[i]->codec;
@ -98,7 +98,7 @@ int FFmpeg_Input::Open(const char *filepath) {
Debug(1, "Using codec (%s) for stream %d", streams[i].codec->name, i); Debug(1, "Using codec (%s) for stream %d", streams[i].codec->name, i);
} }
error = avcodec_open2(streams[i].context, streams[i].codec, NULL); error = avcodec_open2(streams[i].context, streams[i].codec, nullptr);
if ( error < 0 ) { if ( error < 0 ) {
Error("Could not open input codec (error '%s')", Error("Could not open input codec (error '%s')",
av_make_error_string(error).c_str()); av_make_error_string(error).c_str());
@ -106,7 +106,7 @@ int FFmpeg_Input::Open(const char *filepath) {
avcodec_free_context(&streams[i].context); avcodec_free_context(&streams[i].context);
#endif #endif
avformat_close_input(&input_format_context); avformat_close_input(&input_format_context);
input_format_context = NULL; input_format_context = nullptr;
return error; return error;
} }
} // end foreach stream } // end foreach stream
@ -134,11 +134,11 @@ AVFrame *FFmpeg_Input::get_frame(int stream_id) {
(ret == -110) (ret == -110)
) { ) {
Info("av_read_frame returned %s.", av_make_error_string(ret).c_str()); Info("av_read_frame returned %s.", av_make_error_string(ret).c_str());
return NULL; return nullptr;
} }
Error("Unable to read packet from stream %d: error %d \"%s\".", Error("Unable to read packet from stream %d: error %d \"%s\".",
packet.stream_index, ret, av_make_error_string(ret).c_str()); packet.stream_index, ret, av_make_error_string(ret).c_str());
return NULL; return nullptr;
} }
dumpPacket(input_format_context->streams[packet.stream_index], &packet, "Received packet"); dumpPacket(input_format_context->streams[packet.stream_index], &packet, "Received packet");
@ -193,7 +193,7 @@ AVFrame *FFmpeg_Input::get_frame(int stream_id, double at) {
ret = av_seek_frame(input_format_context, stream_id, seek_target, AVSEEK_FLAG_FRAME); ret = av_seek_frame(input_format_context, stream_id, seek_target, AVSEEK_FLAG_FRAME);
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Unable to seek in stream"); Error("Unable to seek in stream");
return NULL; return nullptr;
} }
// Have to grab a frame to update our current frame to know where we are // Have to grab a frame to update our current frame to know where we are
get_frame(stream_id); get_frame(stream_id);
@ -201,7 +201,7 @@ AVFrame *FFmpeg_Input::get_frame(int stream_id, double at) {
if ( !frame ) { if ( !frame ) {
Warning("Unable to get frame."); Warning("Unable to get frame.");
return NULL; return nullptr;
} }
if ( if (
@ -217,7 +217,7 @@ AVFrame *FFmpeg_Input::get_frame(int stream_id, double at) {
AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME
) < 0 ) ) { ) < 0 ) ) {
Error("Unable to seek in stream"); Error("Unable to seek in stream");
return NULL; return nullptr;
} }
// Have to grab a frame to update our current frame to know where we are // Have to grab a frame to update our current frame to know where we are
get_frame(stream_id); get_frame(stream_id);

View File

@ -30,13 +30,13 @@
#include "zm_fifo.h" #include "zm_fifo.h"
#define RAW_BUFFER 512 #define RAW_BUFFER 512
static bool zm_fifodbg_inited = false; static bool zm_fifodbg_inited = false;
FILE *zm_fifodbg_log_fd = 0; FILE *zm_fifodbg_log_fd = nullptr;
char zm_fifodbg_log[PATH_MAX] = ""; char zm_fifodbg_log[PATH_MAX] = "";
static bool zmFifoDbgOpen() { static bool zmFifoDbgOpen() {
if ( zm_fifodbg_log_fd ) if ( zm_fifodbg_log_fd )
fclose(zm_fifodbg_log_fd); fclose(zm_fifodbg_log_fd);
zm_fifodbg_log_fd = NULL; zm_fifodbg_log_fd = nullptr;
signal(SIGPIPE, SIG_IGN); signal(SIGPIPE, SIG_IGN);
FifoStream::fifo_create_if_missing(zm_fifodbg_log); FifoStream::fifo_create_if_missing(zm_fifodbg_log);
int fd = open(zm_fifodbg_log, O_WRONLY|O_NONBLOCK|O_TRUNC); int fd = open(zm_fifodbg_log, O_WRONLY|O_NONBLOCK|O_TRUNC);
@ -48,7 +48,7 @@ static bool zmFifoDbgOpen() {
return false; return false;
} }
zm_fifodbg_log_fd = fdopen(fd, "wb"); zm_fifodbg_log_fd = fdopen(fd, "wb");
if ( zm_fifodbg_log_fd == NULL ) { if ( zm_fifodbg_log_fd == nullptr ) {
close(fd); close(fd);
return false; return false;
} }
@ -95,7 +95,7 @@ void zmFifoDbgOutput(
int res = fwrite(dbg_string, dbg_ptr-dbg_string, 1, zm_fifodbg_log_fd); int res = fwrite(dbg_string, dbg_ptr-dbg_string, 1, zm_fifodbg_log_fd);
if ( res != 1 ) { if ( res != 1 ) {
fclose(zm_fifodbg_log_fd); fclose(zm_fifodbg_log_fd);
zm_fifodbg_log_fd = NULL; zm_fifodbg_log_fd = nullptr;
} else { } else {
fflush(zm_fifodbg_log_fd); fflush(zm_fifodbg_log_fd);
} }
@ -249,7 +249,7 @@ void FifoStream::runStream() {
} }
while ( !zm_terminate ) { while ( !zm_terminate ) {
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
checkCommandQueue(); checkCommandQueue();
if ( stream_type == MJPEG ) { if ( stream_type == MJPEG ) {
if ( !sendMJEGFrames() ) if ( !sendMJEGFrames() )

View File

@ -88,7 +88,7 @@ int FileCamera::PreCapture() {
// This waits until 1 second has passed since it was modified. Effectively limiting fps to 60. // This waits until 1 second has passed since it was modified. Effectively limiting fps to 60.
// Which is kinda bogus. If we were writing to this jpg constantly faster than we are monitoring it here // Which is kinda bogus. If we were writing to this jpg constantly faster than we are monitoring it here
// we would never break out of this loop // we would never break out of this loop
while ( (time(0) - statbuf.st_mtime) < 1 ) { while ( (time(nullptr) - statbuf.st_mtime) < 1 ) {
usleep(100000); usleep(100000);
} }
return 0; return 0;

View File

@ -48,12 +48,12 @@ static short *g_v_table;
static short *g_u_table; static short *g_u_table;
static short *b_u_table; static short *b_u_table;
struct SwsContext *sws_convert_context = NULL; struct SwsContext *sws_convert_context = nullptr;
jpeg_compress_struct *Image::writejpg_ccinfo[101] = { 0 }; jpeg_compress_struct *Image::writejpg_ccinfo[101] = { };
jpeg_compress_struct *Image::encodejpg_ccinfo[101] = { 0 }; jpeg_compress_struct *Image::encodejpg_ccinfo[101] = { };
jpeg_decompress_struct *Image::readjpg_dcinfo = 0; jpeg_decompress_struct *Image::readjpg_dcinfo = nullptr;
jpeg_decompress_struct *Image::decodejpg_dcinfo = 0; jpeg_decompress_struct *Image::decodejpg_dcinfo = nullptr;
struct zm_error_mgr Image::jpg_err; struct zm_error_mgr Image::jpg_err;
/* Pointer to blend function. */ /* Pointer to blend function. */
@ -152,7 +152,7 @@ Image::Image(int p_width, int p_height, int p_colours, int p_subpixelorder, uint
padding = p_padding; padding = p_padding;
subpixelorder = p_subpixelorder; subpixelorder = p_subpixelorder;
size = linesize*height + padding; size = linesize*height + padding;
buffer = 0; buffer = nullptr;
holdbuffer = 0; holdbuffer = 0;
if ( p_buffer ) { if ( p_buffer ) {
allocation = size; allocation = size;
@ -177,7 +177,7 @@ Image::Image(int p_width, int p_linesize, int p_height, int p_colours, int p_sub
padding = p_padding; padding = p_padding;
subpixelorder = p_subpixelorder; subpixelorder = p_subpixelorder;
size = linesize*height + padding; size = linesize*height + padding;
buffer = 0; buffer = nullptr;
holdbuffer = 0; holdbuffer = 0;
if ( p_buffer ) { if ( p_buffer ) {
allocation = size; allocation = size;
@ -210,7 +210,7 @@ Image::Image(const AVFrame *frame) {
size = avpicture_get_size(AV_PIX_FMT_RGBA, width, height); size = avpicture_get_size(AV_PIX_FMT_RGBA, width, height);
#endif #endif
buffer = 0; buffer = nullptr;
holdbuffer = 0; holdbuffer = 0;
AllocImgBuffer(size); AllocImgBuffer(size);
@ -229,9 +229,9 @@ Image::Image(const AVFrame *frame) {
height, height,
(AVPixelFormat)frame->format, (AVPixelFormat)frame->format,
width, height, width, height,
AV_PIX_FMT_RGBA, SWS_BICUBIC, NULL, AV_PIX_FMT_RGBA, SWS_BICUBIC, nullptr,
NULL, NULL); nullptr, nullptr);
if ( sws_convert_context == NULL ) if ( sws_convert_context == nullptr )
Fatal("Unable to create conversion context"); Fatal("Unable to create conversion context");
if ( sws_scale(sws_convert_context, frame->data, frame->linesize, 0, frame->height, if ( sws_scale(sws_convert_context, frame->data, frame->linesize, 0, frame->height,
@ -254,7 +254,7 @@ Image::Image(const Image &p_image) {
colours = p_image.colours; colours = p_image.colours;
subpixelorder = p_image.subpixelorder; subpixelorder = p_image.subpixelorder;
size = p_image.size; // allocation is set in AllocImgBuffer size = p_image.size; // allocation is set in AllocImgBuffer
buffer = 0; buffer = nullptr;
holdbuffer = 0; holdbuffer = 0;
AllocImgBuffer(size); AllocImgBuffer(size);
(*fptr_imgbufcpy)(buffer, p_image.buffer, size); (*fptr_imgbufcpy)(buffer, p_image.buffer, size);
@ -273,24 +273,24 @@ void Image::Deinitialise() {
if ( readjpg_dcinfo ) { if ( readjpg_dcinfo ) {
jpeg_destroy_decompress(readjpg_dcinfo); jpeg_destroy_decompress(readjpg_dcinfo);
delete readjpg_dcinfo; delete readjpg_dcinfo;
readjpg_dcinfo = NULL; readjpg_dcinfo = nullptr;
} }
if ( decodejpg_dcinfo ) { if ( decodejpg_dcinfo ) {
jpeg_destroy_decompress(decodejpg_dcinfo); jpeg_destroy_decompress(decodejpg_dcinfo);
delete decodejpg_dcinfo; delete decodejpg_dcinfo;
decodejpg_dcinfo = NULL; decodejpg_dcinfo = nullptr;
} }
for ( unsigned int quality=0; quality <= 100; quality += 1 ) { for ( unsigned int quality=0; quality <= 100; quality += 1 ) {
if ( writejpg_ccinfo[quality] ) { if ( writejpg_ccinfo[quality] ) {
jpeg_destroy_compress(writejpg_ccinfo[quality]); jpeg_destroy_compress(writejpg_ccinfo[quality]);
delete writejpg_ccinfo[quality]; delete writejpg_ccinfo[quality];
writejpg_ccinfo[quality] = NULL; writejpg_ccinfo[quality] = nullptr;
} }
} // end foreach quality } // end foreach quality
if ( sws_convert_context ) { if ( sws_convert_context ) {
sws_freeContext(sws_convert_context); sws_freeContext(sws_convert_context);
sws_convert_context = NULL; sws_convert_context = nullptr;
} }
} // end void Image::Deinitialise() } // end void Image::Deinitialise()
@ -501,25 +501,25 @@ uint8_t* Image::WriteBuffer(
&& &&
p_colours != ZM_COLOUR_RGB32 ) { p_colours != ZM_COLOUR_RGB32 ) {
Error("WriteBuffer called with unexpected colours: %d", p_colours); Error("WriteBuffer called with unexpected colours: %d", p_colours);
return NULL; return nullptr;
} }
if ( ! ( p_height > 0 && p_width > 0 ) ) { if ( ! ( p_height > 0 && p_width > 0 ) ) {
Error("WriteBuffer called with invalid width or height: %d %d", p_width, p_height); Error("WriteBuffer called with invalid width or height: %d %d", p_width, p_height);
return NULL; return nullptr;
} }
if ( p_width != width || p_height != height || p_colours != colours || p_subpixelorder != subpixelorder ) { if ( p_width != width || p_height != height || p_colours != colours || p_subpixelorder != subpixelorder ) {
unsigned int newsize = (p_width * p_height) * p_colours; unsigned int newsize = (p_width * p_height) * p_colours;
if ( buffer == NULL ) { if ( buffer == nullptr ) {
AllocImgBuffer(newsize); AllocImgBuffer(newsize);
} else { } else {
if ( allocation < newsize ) { if ( allocation < newsize ) {
if ( holdbuffer ) { if ( holdbuffer ) {
Error("Held buffer is undersized for requested buffer"); Error("Held buffer is undersized for requested buffer");
return NULL; return nullptr;
} else { } else {
/* Replace buffer with a bigger one */ /* Replace buffer with a bigger one */
//DumpImgBuffer(); // Done in AllocImgBuffer too //DumpImgBuffer(); // Done in AllocImgBuffer too
@ -552,7 +552,7 @@ void Image::AssignDirect(
const size_t buffer_size, const size_t buffer_size,
const int p_buffertype) { const int p_buffertype) {
if ( new_buffer == NULL ) { if ( new_buffer == nullptr ) {
Error("Attempt to directly assign buffer from a NULL pointer"); Error("Attempt to directly assign buffer from a NULL pointer");
return; return;
} }
@ -623,7 +623,7 @@ void Image::Assign(
const size_t buffer_size) { const size_t buffer_size) {
unsigned int new_size = (p_width * p_height) * p_colours; unsigned int new_size = (p_width * p_height) * p_colours;
if ( new_buffer == NULL ) { if ( new_buffer == nullptr ) {
Error("Attempt to assign buffer from a NULL pointer"); Error("Attempt to assign buffer from a NULL pointer");
return; return;
} }
@ -672,7 +672,7 @@ void Image::Assign(
void Image::Assign(const Image &image) { void Image::Assign(const Image &image) {
unsigned int new_size = image.height * image.linesize; unsigned int new_size = image.height * image.linesize;
if ( image.buffer == NULL ) { if ( image.buffer == nullptr ) {
Error("Attempt to assign image with an empty buffer"); Error("Attempt to assign image with an empty buffer");
return; return;
} }
@ -811,7 +811,7 @@ Image *Image::HighlightEdges(
bool Image::ReadRaw(const char *filename) { bool Image::ReadRaw(const char *filename) {
FILE *infile; FILE *infile;
if ( (infile = fopen(filename, "rb")) == NULL ) { if ( (infile = fopen(filename, "rb")) == nullptr ) {
Error("Can't open %s: %s", filename, strerror(errno)); Error("Can't open %s: %s", filename, strerror(errno));
return false; return false;
} }
@ -842,7 +842,7 @@ bool Image::ReadRaw(const char *filename) {
bool Image::WriteRaw(const char *filename) const { bool Image::WriteRaw(const char *filename) const {
FILE *outfile; FILE *outfile;
if ( (outfile = fopen(filename, "wb")) == NULL ) { if ( (outfile = fopen(filename, "wb")) == nullptr ) {
Error("Can't open %s: %s", filename, strerror(errno)); Error("Can't open %s: %s", filename, strerror(errno));
return false; return false;
} }
@ -871,7 +871,7 @@ bool Image::ReadJpeg(const char *filename, unsigned int p_colours, unsigned int
} }
FILE *infile; FILE *infile;
if ( (infile = fopen(filename, "rb")) == NULL ) { if ( (infile = fopen(filename, "rb")) == nullptr ) {
Error("Can't open %s: %s", filename, strerror(errno)); Error("Can't open %s: %s", filename, strerror(errno));
return false; return false;
} }
@ -895,7 +895,7 @@ bool Image::ReadJpeg(const char *filename, unsigned int p_colours, unsigned int
/* Check if the image has at least one huffman table defined. If not, use the standard ones */ /* Check if the image has at least one huffman table defined. If not, use the standard ones */
/* This is required for the MJPEG capture palette of USB devices */ /* This is required for the MJPEG capture palette of USB devices */
if ( cinfo->dc_huff_tbl_ptrs[0] == NULL ) { if ( cinfo->dc_huff_tbl_ptrs[0] == nullptr ) {
zm_use_std_huff_tables(cinfo); zm_use_std_huff_tables(cinfo);
} }
@ -960,7 +960,7 @@ cinfo->out_color_space = JCS_RGB;
break; break;
} // end switch p_colours } // end switch p_colours
if ( WriteBuffer(new_width, new_height, new_colours, new_subpixelorder) == NULL ) { if ( WriteBuffer(new_width, new_height, new_colours, new_subpixelorder) == nullptr ) {
Error("Failed requesting writeable buffer for reading JPEG image."); Error("Failed requesting writeable buffer for reading JPEG image.");
jpeg_abort_decompress(cinfo); jpeg_abort_decompress(cinfo);
fclose(infile); fclose(infile);
@ -1011,7 +1011,7 @@ bool Image::WriteJpeg(const char *filename, int quality_override, struct timeval
int quality = quality_override ? quality_override : config.jpeg_file_quality; int quality = quality_override ? quality_override : config.jpeg_file_quality;
struct jpeg_compress_struct *cinfo = writejpg_ccinfo[quality]; struct jpeg_compress_struct *cinfo = writejpg_ccinfo[quality];
FILE *outfile = NULL; FILE *outfile = nullptr;
static int raw_fd = 0; static int raw_fd = 0;
raw_fd = 0; raw_fd = 0;
@ -1028,7 +1028,7 @@ bool Image::WriteJpeg(const char *filename, int quality_override, struct timeval
jpg_err.pub.emit_message = zm_jpeg_emit_silence; jpg_err.pub.emit_message = zm_jpeg_emit_silence;
if ( setjmp(jpg_err.setjmp_buffer) ) { if ( setjmp(jpg_err.setjmp_buffer) ) {
jpeg_abort_compress(cinfo); jpeg_abort_compress(cinfo);
Debug(1, "Aborted a write mid-stream and %s and %d", (outfile == NULL) ? "closing file" : "file not opened", raw_fd); Debug(1, "Aborted a write mid-stream and %s and %d", (outfile == nullptr) ? "closing file" : "file not opened", raw_fd);
if ( raw_fd ) if ( raw_fd )
close(raw_fd); close(raw_fd);
if ( outfile ) if ( outfile )
@ -1038,7 +1038,7 @@ bool Image::WriteJpeg(const char *filename, int quality_override, struct timeval
} }
if ( !on_blocking_abort ) { if ( !on_blocking_abort ) {
if ( (outfile = fopen(filename, "wb")) == NULL ) { if ( (outfile = fopen(filename, "wb")) == nullptr ) {
Error("Can't open %s for writing: %s", filename, strerror(errno)); Error("Can't open %s for writing: %s", filename, strerror(errno));
return false; return false;
} }
@ -1047,7 +1047,7 @@ bool Image::WriteJpeg(const char *filename, int quality_override, struct timeval
if ( raw_fd < 0 ) if ( raw_fd < 0 )
return false; return false;
outfile = fdopen(raw_fd, "wb"); outfile = fdopen(raw_fd, "wb");
if ( outfile == NULL ) { if ( outfile == nullptr ) {
close(raw_fd); close(raw_fd);
return false; return false;
} }
@ -1190,7 +1190,7 @@ bool Image::DecodeJpeg(
/* Check if the image has at least one huffman table defined. If not, use the standard ones */ /* Check if the image has at least one huffman table defined. If not, use the standard ones */
/* This is required for the MJPEG capture palette of USB devices */ /* This is required for the MJPEG capture palette of USB devices */
if ( cinfo->dc_huff_tbl_ptrs[0] == NULL ) { if ( cinfo->dc_huff_tbl_ptrs[0] == nullptr ) {
zm_use_std_huff_tables(cinfo); zm_use_std_huff_tables(cinfo);
} }
@ -1256,7 +1256,7 @@ cinfo->out_color_space = JCS_RGB;
break; break;
} // end switch } // end switch
if ( WriteBuffer(new_width, new_height, new_colours, new_subpixelorder) == NULL ) { if ( WriteBuffer(new_width, new_height, new_colours, new_subpixelorder) == nullptr ) {
Error("Failed requesting writeable buffer for reading JPEG image."); Error("Failed requesting writeable buffer for reading JPEG image.");
jpeg_abort_decompress(cinfo); jpeg_abort_decompress(cinfo);
return false; return false;
@ -1799,7 +1799,7 @@ void Image::Delta( const Image &image, Image* targetimage) const {
uint8_t *pdiff = targetimage->WriteBuffer(width, height, ZM_COLOUR_GRAY8, ZM_SUBPIX_ORDER_NONE); uint8_t *pdiff = targetimage->WriteBuffer(width, height, ZM_COLOUR_GRAY8, ZM_SUBPIX_ORDER_NONE);
if ( pdiff == NULL ) { if ( pdiff == nullptr ) {
Panic("Failed requesting writeable buffer for storing the delta image"); Panic("Failed requesting writeable buffer for storing the delta image");
} }

View File

@ -57,7 +57,7 @@ extern imgbufcpy_fptr_t fptr_imgbufcpy;
/* Should be called from Image class functions */ /* Should be called from Image class functions */
inline static uint8_t* AllocBuffer(size_t p_bufsize) { inline static uint8_t* AllocBuffer(size_t p_bufsize) {
uint8_t* buffer = (uint8_t*)zm_mallocaligned(64, p_bufsize); uint8_t* buffer = (uint8_t*)zm_mallocaligned(64, p_bufsize);
if ( buffer == NULL ) if ( buffer == nullptr )
Fatal("Memory allocation failed: %s", strerror(errno)); Fatal("Memory allocation failed: %s", strerror(errno));
return buffer; return buffer;
@ -122,7 +122,7 @@ protected:
inline void DumpImgBuffer() { inline void DumpImgBuffer() {
DumpBuffer(buffer, buffertype); DumpBuffer(buffer, buffertype);
buffer = NULL; buffer = nullptr;
allocation = 0; allocation = 0;
} }

View File

@ -192,7 +192,7 @@ void zm_jpeg_mem_dest (j_compress_ptr cinfo, JOCTET *outbuffer, int *outbuffer_s
* manager serially with the same JPEG object, because their private object * manager serially with the same JPEG object, because their private object
* sizes may be different. Caveat programmer. * sizes may be different. Caveat programmer.
*/ */
if ( cinfo->dest == NULL ) if ( cinfo->dest == nullptr )
{ {
/* first time for this JPEG object? */ /* first time for this JPEG object? */
cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(mem_destination_mgr)); cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(mem_destination_mgr));
@ -369,7 +369,7 @@ void zm_jpeg_mem_src( j_decompress_ptr cinfo, const JOCTET *inbuffer, int inbuff
* This makes it unsafe to use this manager and a different source * This makes it unsafe to use this manager and a different source
* manager serially with the same JPEG object. Caveat programmer. * manager serially with the same JPEG object. Caveat programmer.
*/ */
if ( cinfo->src == NULL ) if ( cinfo->src == nullptr )
{ {
/* first time for this JPEG object? */ /* first time for this JPEG object? */
cinfo->src = (struct jpeg_source_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(mem_source_mgr)); cinfo->src = (struct jpeg_source_mgr *)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(mem_source_mgr));
@ -396,7 +396,7 @@ void zm_jpeg_mem_src( j_decompress_ptr cinfo, const JOCTET *inbuffer, int inbuff
src->inbuffer = (JOCTET *)inbuffer; src->inbuffer = (JOCTET *)inbuffer;
src->inbuffer_size = inbuffer_size; src->inbuffer_size = inbuffer_size;
src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
src->pub.next_input_byte = NULL; /* until buffer loaded */ src->pub.next_input_byte = nullptr; /* until buffer loaded */
} }
void zm_use_std_huff_tables( j_decompress_ptr cinfo ) { void zm_use_std_huff_tables( j_decompress_ptr cinfo ) {

View File

@ -72,7 +72,7 @@ void* LibvlcLockBuffer(void* opaque, void** planes) {
data->prevBuffer = buffer; data->prevBuffer = buffer;
*planes = data->buffer; *planes = data->buffer;
return NULL; return nullptr;
} }
void LibvlcUnlockBuffer(void* opaque, void* picture, void *const *planes) { void LibvlcUnlockBuffer(void* opaque, void* picture, void *const *planes) {
@ -129,12 +129,12 @@ LibvlcCamera::LibvlcCamera(
mMethod(p_method), mMethod(p_method),
mOptions(p_options) mOptions(p_options)
{ {
mLibvlcInstance = NULL; mLibvlcInstance = nullptr;
mLibvlcMedia = NULL; mLibvlcMedia = nullptr;
mLibvlcMediaPlayer = NULL; mLibvlcMediaPlayer = nullptr;
mLibvlcData.buffer = NULL; mLibvlcData.buffer = nullptr;
mLibvlcData.prevBuffer = NULL; mLibvlcData.prevBuffer = nullptr;
mOptArgV = NULL; mOptArgV = nullptr;
/* Has to be located inside the constructor so other components such as zma will receive correct colours and subpixel order */ /* Has to be located inside the constructor so other components such as zma will receive correct colours and subpixel order */
if ( colours == ZM_COLOUR_RGB32 ) { if ( colours == ZM_COLOUR_RGB32 ) {
@ -163,19 +163,19 @@ LibvlcCamera::~LibvlcCamera() {
if ( capture ) { if ( capture ) {
Terminate(); Terminate();
} }
if ( mLibvlcMediaPlayer != NULL ) { if ( mLibvlcMediaPlayer != nullptr ) {
(*libvlc_media_player_release_f)(mLibvlcMediaPlayer); (*libvlc_media_player_release_f)(mLibvlcMediaPlayer);
mLibvlcMediaPlayer = NULL; mLibvlcMediaPlayer = nullptr;
} }
if ( mLibvlcMedia != NULL ) { if ( mLibvlcMedia != nullptr ) {
(*libvlc_media_release_f)(mLibvlcMedia); (*libvlc_media_release_f)(mLibvlcMedia);
mLibvlcMedia = NULL; mLibvlcMedia = nullptr;
} }
if ( mLibvlcInstance != NULL ) { if ( mLibvlcInstance != nullptr ) {
(*libvlc_release_f)(mLibvlcInstance); (*libvlc_release_f)(mLibvlcInstance);
mLibvlcInstance = NULL; mLibvlcInstance = nullptr;
} }
if ( mOptArgV != NULL ) { if ( mOptArgV != nullptr ) {
delete[] mOptArgV; delete[] mOptArgV;
} }
} }
@ -188,12 +188,12 @@ void LibvlcCamera::Terminate() {
(*libvlc_media_player_stop_f)(mLibvlcMediaPlayer); (*libvlc_media_player_stop_f)(mLibvlcMediaPlayer);
if ( mLibvlcData.buffer ) { if ( mLibvlcData.buffer ) {
zm_freealigned(mLibvlcData.buffer); zm_freealigned(mLibvlcData.buffer);
mLibvlcData.buffer = NULL; mLibvlcData.buffer = nullptr;
} }
if ( mLibvlcData.prevBuffer ) { if ( mLibvlcData.prevBuffer ) {
zm_freealigned(mLibvlcData.prevBuffer); zm_freealigned(mLibvlcData.prevBuffer);
mLibvlcData.prevBuffer = NULL; mLibvlcData.prevBuffer = nullptr;
} }
} }
@ -223,27 +223,27 @@ int LibvlcCamera::PrimeCapture() {
} }
mLibvlcInstance = (*libvlc_new_f)(opVect.size(), (const char* const*)mOptArgV); mLibvlcInstance = (*libvlc_new_f)(opVect.size(), (const char* const*)mOptArgV);
if ( mLibvlcInstance == NULL ) { if ( mLibvlcInstance == nullptr ) {
Error("Unable to create libvlc instance due to: %s", (*libvlc_errmsg_f)()); Error("Unable to create libvlc instance due to: %s", (*libvlc_errmsg_f)());
return -1; return -1;
} }
(*libvlc_log_set_f)(mLibvlcInstance, LibvlcCamera::log_callback, NULL); (*libvlc_log_set_f)(mLibvlcInstance, LibvlcCamera::log_callback, nullptr);
mLibvlcMedia = (*libvlc_media_new_location_f)(mLibvlcInstance, mPath.c_str()); mLibvlcMedia = (*libvlc_media_new_location_f)(mLibvlcInstance, mPath.c_str());
if ( mLibvlcMedia == NULL ) { if ( mLibvlcMedia == nullptr ) {
Error("Unable to open input %s due to: %s", mPath.c_str(), (*libvlc_errmsg_f)()); Error("Unable to open input %s due to: %s", mPath.c_str(), (*libvlc_errmsg_f)());
return -1; return -1;
} }
mLibvlcMediaPlayer = (*libvlc_media_player_new_from_media_f)(mLibvlcMedia); mLibvlcMediaPlayer = (*libvlc_media_player_new_from_media_f)(mLibvlcMedia);
if ( mLibvlcMediaPlayer == NULL ) { if ( mLibvlcMediaPlayer == nullptr ) {
Error("Unable to create player for %s due to: %s", mPath.c_str(), (*libvlc_errmsg_f)()); Error("Unable to create player for %s due to: %s", mPath.c_str(), (*libvlc_errmsg_f)());
return -1; return -1;
} }
(*libvlc_video_set_format_f)(mLibvlcMediaPlayer, mTargetChroma.c_str(), width, height, width * mBpp); (*libvlc_video_set_format_f)(mLibvlcMediaPlayer, mTargetChroma.c_str(), width, height, width * mBpp);
(*libvlc_video_set_callbacks_f)(mLibvlcMediaPlayer, &LibvlcLockBuffer, &LibvlcUnlockBuffer, NULL, &mLibvlcData); (*libvlc_video_set_callbacks_f)(mLibvlcMediaPlayer, &LibvlcLockBuffer, &LibvlcUnlockBuffer, nullptr, &mLibvlcData);
mLibvlcData.bufferSize = width * height * mBpp; mLibvlcData.bufferSize = width * height * mBpp;
// Libvlc wants 32 byte alignment for images (should in theory do this for all image lines) // Libvlc wants 32 byte alignment for images (should in theory do this for all image lines)

View File

@ -50,7 +50,7 @@ static rfbCredential* GetCredentialsCallback(rfbClient* cl, int credentialType){
rfbCredential *c = (rfbCredential *)malloc(sizeof(rfbCredential)); rfbCredential *c = (rfbCredential *)malloc(sizeof(rfbCredential));
if ( credentialType != rfbCredentialTypeUser ) { if ( credentialType != rfbCredentialTypeUser ) {
free(c); free(c);
return NULL; return nullptr;
} }
c->userCredential.password = strdup((const char *)(*rfbClientGetClientData_f)(cl, &TAG_1)); c->userCredential.password = strdup((const char *)(*rfbClientGetClientData_f)(cl, &TAG_1));

View File

@ -302,10 +302,10 @@ LocalCamera::V4L1Data LocalCamera::v4l1_data;
#endif // ZM_HAS_V4L1 #endif // ZM_HAS_V4L1
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
AVFrame **LocalCamera::capturePictures = 0; AVFrame **LocalCamera::capturePictures = nullptr;
#endif // HAVE_LIBSWSCALE #endif // HAVE_LIBSWSCALE
LocalCamera *LocalCamera::last_camera = NULL; LocalCamera *LocalCamera::last_camera = nullptr;
LocalCamera::LocalCamera( LocalCamera::LocalCamera(
int p_id, int p_id,
@ -673,14 +673,14 @@ LocalCamera::LocalCamera(
Fatal("Image size mismatch. Required: %d Available: %u", pSize, imagesize); Fatal("Image size mismatch. Required: %d Available: %u", pSize, imagesize);
} }
imgConversionContext = sws_getContext(width, height, capturePixFormat, width, height, imagePixFormat, SWS_BICUBIC, NULL, NULL, NULL); imgConversionContext = sws_getContext(width, height, capturePixFormat, width, height, imagePixFormat, SWS_BICUBIC, nullptr, nullptr, nullptr);
if ( !imgConversionContext ) { if ( !imgConversionContext ) {
Fatal("Unable to initialise image scaling context"); Fatal("Unable to initialise image scaling context");
} }
} else { } else {
tmpPicture = NULL; tmpPicture = nullptr;
imgConversionContext = NULL; imgConversionContext = nullptr;
} }
#endif #endif
} // end LocalCamera::LocalCamera } // end LocalCamera::LocalCamera
@ -693,7 +693,7 @@ LocalCamera::~LocalCamera() {
/* Clean up swscale stuff */ /* Clean up swscale stuff */
if ( capture && conversion_type == 1 ) { if ( capture && conversion_type == 1 ) {
sws_freeContext(imgConversionContext); sws_freeContext(imgConversionContext);
imgConversionContext = NULL; imgConversionContext = nullptr;
av_frame_free(&tmpPicture); av_frame_free(&tmpPicture);
} }
@ -898,7 +898,7 @@ void LocalCamera::Initialise() {
Fatal("Unable to query video buffer: %s", strerror(errno)); Fatal("Unable to query video buffer: %s", strerror(errno));
v4l2_data.buffers[i].length = vid_buf.length; v4l2_data.buffers[i].length = vid_buf.length;
v4l2_data.buffers[i].start = mmap(NULL, vid_buf.length, PROT_READ|PROT_WRITE, MAP_SHARED, vid_fd, vid_buf.m.offset); v4l2_data.buffers[i].start = mmap(nullptr, vid_buf.length, PROT_READ|PROT_WRITE, MAP_SHARED, vid_fd, vid_buf.m.offset);
if ( v4l2_data.buffers[i].start == MAP_FAILED ) if ( v4l2_data.buffers[i].start == MAP_FAILED )
Fatal("Can't map video buffer %u (%u bytes) to memory: %s(%d)", Fatal("Can't map video buffer %u (%u bytes) to memory: %s(%d)",
@ -1991,7 +1991,7 @@ int LocalCamera::PrimeCapture() {
if ( vidioctl(vid_fd, VIDIOC_QBUF, &vid_buf) < 0 ) if ( vidioctl(vid_fd, VIDIOC_QBUF, &vid_buf) < 0 )
Fatal("Failed to queue buffer %d: %s", frame, strerror(errno)); Fatal("Failed to queue buffer %d: %s", frame, strerror(errno));
} }
v4l2_data.bufptr = NULL; v4l2_data.bufptr = nullptr;
Debug(3, "Starting video stream"); Debug(3, "Starting video stream");
//enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE; //enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
@ -2023,7 +2023,7 @@ int LocalCamera::PreCapture() {
int LocalCamera::Capture(Image &image) { int LocalCamera::Capture(Image &image) {
Debug(3, "Capturing"); Debug(3, "Capturing");
static uint8_t* buffer = NULL; static uint8_t* buffer = nullptr;
int buffer_bytesused = 0; int buffer_bytesused = 0;
int capture_frame = -1; int capture_frame = -1;
@ -2116,7 +2116,7 @@ int LocalCamera::Capture(Image &image) {
/* Request a writeable buffer of the target image */ /* Request a writeable buffer of the target image */
uint8_t* directbuffer = image.WriteBuffer(width, height, colours, subpixelorder); uint8_t* directbuffer = image.WriteBuffer(width, height, colours, subpixelorder);
if ( directbuffer == NULL ) { if ( directbuffer == nullptr ) {
Error("Failed requesting writeable buffer for the captured image."); Error("Failed requesting writeable buffer for the captured image.");
return -1; return -1;
} }

View File

@ -38,7 +38,7 @@
#endif #endif
bool Logger::smInitialised = false; bool Logger::smInitialised = false;
Logger *Logger::smInstance = NULL; Logger *Logger::smInstance = nullptr;
Logger::StringMap Logger::smCodes; Logger::StringMap Logger::smCodes;
Logger::IntMap Logger::smSyslogPriorities; Logger::IntMap Logger::smSyslogPriorities;
@ -74,7 +74,7 @@ Logger::Logger() :
mDbConnected(false), mDbConnected(false),
mLogPath(staticConfig.PATH_LOGS.c_str()), mLogPath(staticConfig.PATH_LOGS.c_str()),
//mLogFile( mLogPath+"/"+mId+".log" ), //mLogFile( mLogPath+"/"+mId+".log" ),
mLogFileFP(NULL), mLogFileFP(nullptr),
mHasTerminal(false), mHasTerminal(false),
mFlush(false) { mFlush(false) {
@ -413,7 +413,7 @@ void Logger::logFile(const std::string &logFile) {
void Logger::openFile() { void Logger::openFile() {
if ( mLogFile.size() ) { if ( mLogFile.size() ) {
if ( (mLogFileFP = fopen(mLogFile.c_str(), "a")) == (FILE *)NULL ) { if ( (mLogFileFP = fopen(mLogFile.c_str(), "a")) == nullptr ) {
mFileLevel = NOLOG; mFileLevel = NOLOG;
Error("fopen() for %s, error = %s", mLogFile.c_str(), strerror(errno)); Error("fopen() for %s, error = %s", mLogFile.c_str(), strerror(errno));
} }
@ -426,10 +426,10 @@ void Logger::closeFile() {
if ( mLogFileFP ) { if ( mLogFileFP ) {
fflush(mLogFileFP); fflush(mLogFileFP);
if ( fclose(mLogFileFP) < 0 ) { if ( fclose(mLogFileFP) < 0 ) {
mLogFileFP = (FILE *)NULL; mLogFileFP = nullptr;
Error("fclose(), error = %s", strerror(errno)); Error("fclose(), error = %s", strerror(errno));
} }
mLogFileFP = (FILE *)NULL; mLogFileFP = nullptr;
} }
} }
@ -464,7 +464,7 @@ void Logger::logPrint(bool hex, const char * const filepath, const int line, con
if ( level < PANIC || level > DEBUG9 ) if ( level < PANIC || level > DEBUG9 )
Panic("Invalid logger level %d", level); Panic("Invalid logger level %d", level);
gettimeofday(&timeVal, NULL); gettimeofday(&timeVal, nullptr);
#if 0 #if 0
if ( logRuntime ) { if ( logRuntime ) {
@ -604,7 +604,7 @@ void Logger::logPrint(bool hex, const char * const filepath, const int line, con
void logInit(const char *name, const Logger::Options &options) { void logInit(const char *name, const Logger::Options &options) {
if ( Logger::smInstance ) { if ( Logger::smInstance ) {
delete Logger::smInstance; delete Logger::smInstance;
Logger::smInstance = NULL; Logger::smInstance = nullptr;
} }
Logger::smInstance = new Logger(); Logger::smInstance = new Logger();
@ -614,6 +614,6 @@ void logInit(const char *name, const Logger::Options &options) {
void logTerm() { void logTerm() {
if ( Logger::smInstance ) { if ( Logger::smInstance ) {
delete Logger::smInstance; delete Logger::smInstance;
Logger::smInstance = NULL; Logger::smInstance = nullptr;
} }
} }

View File

@ -27,15 +27,15 @@ inline void* zm_mallocaligned(unsigned int reqalignment, size_t reqsize) {
uint8_t* retptr; uint8_t* retptr;
#if HAVE_POSIX_MEMALIGN #if HAVE_POSIX_MEMALIGN
if ( posix_memalign((void**)&retptr,reqalignment,reqsize) != 0 ) if ( posix_memalign((void**)&retptr,reqalignment,reqsize) != 0 )
return NULL; return nullptr;
return retptr; return retptr;
#else #else
uint8_t* alloc; uint8_t* alloc;
retptr = (uint8_t*)malloc(reqsize+reqalignment+sizeof(void*)); retptr = (uint8_t*)malloc(reqsize+reqalignment+sizeof(void*));
if ( retptr == NULL ) if ( retptr == nullptr )
return NULL; return nullptr;
alloc = retptr + sizeof(void*); alloc = retptr + sizeof(void*);
@ -60,7 +60,7 @@ inline void zm_freealigned(void* ptr) {
inline char *mempbrk(const char *s, const char *accept, size_t limit) { inline char *mempbrk(const char *s, const char *accept, size_t limit) {
if ( limit == 0 || !s || !accept || !*accept ) if ( limit == 0 || !s || !accept || !*accept )
return 0; return nullptr;
unsigned int i,j; unsigned int i,j;
size_t acc_len = strlen(accept); size_t acc_len = strlen(accept);
@ -72,12 +72,12 @@ inline char *mempbrk(const char *s, const char *accept, size_t limit) {
} }
} }
} }
return 0; return nullptr;
} }
inline char *memstr(const char *s, const char *n, size_t limit) { inline char *memstr(const char *s, const char *n, size_t limit) {
if ( limit == 0 || !s || !n ) if ( limit == 0 || !s || !n )
return 0; return nullptr;
if ( !*n ) if ( !*n )
return (char *)s; return (char *)s;
@ -97,7 +97,7 @@ inline char *memstr(const char *s, const char *n, size_t limit) {
break; break;
} }
} }
return 0; return nullptr;
} }
inline size_t memspn(const char *s, const char *accept, size_t limit) { inline size_t memspn(const char *s, const char *accept, size_t limit) {

View File

@ -108,9 +108,9 @@ std::vector<std::string> split(const std::string &s, char delim) {
Monitor::MonitorLink::MonitorLink(unsigned int p_id, const char *p_name) : Monitor::MonitorLink::MonitorLink(unsigned int p_id, const char *p_name) :
id(p_id), id(p_id),
shared_data(NULL), shared_data(nullptr),
trigger_data(NULL), trigger_data(nullptr),
video_store_data(NULL) video_store_data(nullptr)
{ {
strncpy(name, p_name, sizeof(name)-1); strncpy(name, p_name, sizeof(name)-1);
@ -121,7 +121,7 @@ Monitor::MonitorLink::MonitorLink(unsigned int p_id, const char *p_name) :
shm_id = 0; shm_id = 0;
#endif // ZM_MEM_MAPPED #endif // ZM_MEM_MAPPED
mem_size = 0; mem_size = 0;
mem_ptr = 0; mem_ptr = nullptr;
last_event = 0; last_event = 0;
last_state = IDLE; last_state = IDLE;
@ -135,8 +135,8 @@ Monitor::MonitorLink::~MonitorLink() {
} }
bool Monitor::MonitorLink::connect() { bool Monitor::MonitorLink::connect() {
if ( !last_connect_time || (time(0) - last_connect_time) > 60 ) { if ( !last_connect_time || (time(nullptr) - last_connect_time) > 60 ) {
last_connect_time = time(0); last_connect_time = time(nullptr);
mem_size = sizeof(SharedData) + sizeof(TriggerData); mem_size = sizeof(SharedData) + sizeof(TriggerData);
@ -172,7 +172,7 @@ bool Monitor::MonitorLink::connect() {
return false; return false;
} }
mem_ptr = (unsigned char *)mmap(NULL, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED, map_fd, 0); mem_ptr = (unsigned char *)mmap(nullptr, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED, map_fd, 0);
if ( mem_ptr == MAP_FAILED ) { if ( mem_ptr == MAP_FAILED ) {
Error("Can't map file %s (%d bytes) to memory: %s", mem_file, mem_size, strerror(errno)); Error("Can't map file %s (%d bytes) to memory: %s", mem_file, mem_size, strerror(errno));
disconnect(); disconnect();
@ -247,7 +247,7 @@ bool Monitor::MonitorLink::disconnect() {
#endif // ZM_MEM_MAPPED #endif // ZM_MEM_MAPPED
mem_size = 0; mem_size = 0;
mem_ptr = 0; mem_ptr = nullptr;
} }
return( true ); return( true );
} }
@ -368,10 +368,10 @@ Monitor::Monitor(
camera( p_camera ), camera( p_camera ),
n_zones( p_n_zones ), n_zones( p_n_zones ),
zones( p_zones ), zones( p_zones ),
timestamps( 0 ), timestamps( nullptr ),
images( 0 ), images( nullptr ),
privacy_bitmask( NULL ), privacy_bitmask( nullptr ),
event_delete_thread(NULL) event_delete_thread(nullptr)
{ {
if (analysis_fps > 0.0) { if (analysis_fps > 0.0) {
uint64_t usec = round(1000000*pre_event_count/analysis_fps); uint64_t usec = round(1000000*pre_event_count/analysis_fps);
@ -440,7 +440,7 @@ Monitor::Monitor(
(image_buffer_count*sizeof(struct timeval)), (image_buffer_count*sizeof(struct timeval)),
image_buffer_count, camera->ImageSize(), (image_buffer_count*camera->ImageSize()), image_buffer_count, camera->ImageSize(), (image_buffer_count*camera->ImageSize()),
mem_size); mem_size);
mem_ptr = NULL; mem_ptr = nullptr;
storage = new Storage(storage_id); storage = new Storage(storage_id);
Debug(1, "Storage path: %s", storage->Path()); Debug(1, "Storage path: %s", storage->Path());
@ -516,7 +516,7 @@ Monitor::Monitor(
videoRecording = ((GetOptVideoWriter() == H264PASSTHROUGH) && camera->SupportsNativeVideo()); videoRecording = ((GetOptVideoWriter() == H264PASSTHROUGH) && camera->SupportsNativeVideo());
n_linked_monitors = 0; n_linked_monitors = 0;
linked_monitors = 0; linked_monitors = nullptr;
if ( purpose == ANALYSIS ) { if ( purpose == ANALYSIS ) {
while( while(
@ -588,12 +588,12 @@ bool Monitor::connect() {
Debug(3, "MMap file size is %ld", map_stat.st_size); Debug(3, "MMap file size is %ld", map_stat.st_size);
#ifdef MAP_LOCKED #ifdef MAP_LOCKED
mem_ptr = (unsigned char *)mmap(NULL, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, map_fd, 0); mem_ptr = (unsigned char *)mmap(nullptr, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, map_fd, 0);
if ( mem_ptr == MAP_FAILED ) { if ( mem_ptr == MAP_FAILED ) {
if ( errno == EAGAIN ) { if ( errno == EAGAIN ) {
Debug(1, "Unable to map file %s (%d bytes) to locked memory, trying unlocked", mem_file, mem_size); Debug(1, "Unable to map file %s (%d bytes) to locked memory, trying unlocked", mem_file, mem_size);
#endif #endif
mem_ptr = (unsigned char *)mmap(NULL, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED, map_fd, 0); mem_ptr = (unsigned char *)mmap(nullptr, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED, map_fd, 0);
Debug(1, "Mapped file %s (%d bytes) to unlocked memory", mem_file, mem_size); Debug(1, "Mapped file %s (%d bytes) to unlocked memory", mem_file, mem_size);
#ifdef MAP_LOCKED #ifdef MAP_LOCKED
} else { } else {
@ -603,7 +603,7 @@ bool Monitor::connect() {
#endif #endif
if ( mem_ptr == MAP_FAILED ) if ( mem_ptr == MAP_FAILED )
Fatal("Can't map file %s (%d bytes) to memory: %s(%d)", mem_file, mem_size, strerror(errno), errno); Fatal("Can't map file %s (%d bytes) to memory: %s(%d)", mem_file, mem_size, strerror(errno), errno);
if ( mem_ptr == NULL ) { if ( mem_ptr == nullptr ) {
Error("mmap gave a NULL address:"); Error("mmap gave a NULL address:");
} else { } else {
Debug(3, "mmapped to %p", mem_ptr); Debug(3, "mmapped to %p", mem_ptr);
@ -670,19 +670,19 @@ Monitor::~Monitor() {
delete linked_monitors[i]; delete linked_monitors[i];
} }
delete[] linked_monitors; delete[] linked_monitors;
linked_monitors = 0; linked_monitors = nullptr;
} }
if ( timestamps ) { if ( timestamps ) {
delete[] timestamps; delete[] timestamps;
timestamps = 0; timestamps = nullptr;
} }
if ( images ) { if ( images ) {
delete[] images; delete[] images;
images = 0; images = nullptr;
} }
if ( privacy_bitmask ) { if ( privacy_bitmask ) {
delete[] privacy_bitmask; delete[] privacy_bitmask;
privacy_bitmask = NULL; privacy_bitmask = nullptr;
} }
if ( mem_ptr ) { if ( mem_ptr ) {
if ( event ) { if ( event ) {
@ -693,7 +693,7 @@ Monitor::~Monitor() {
if ( event_delete_thread ) { if ( event_delete_thread ) {
event_delete_thread->join(); event_delete_thread->join();
delete event_delete_thread; delete event_delete_thread;
event_delete_thread = NULL; event_delete_thread = nullptr;
} }
} }
@ -776,9 +776,9 @@ void Monitor::AddZones( int p_n_zones, Zone *p_zones[] ) {
void Monitor::AddPrivacyBitmask( Zone *p_zones[] ) { void Monitor::AddPrivacyBitmask( Zone *p_zones[] ) {
if ( privacy_bitmask ) { if ( privacy_bitmask ) {
delete[] privacy_bitmask; delete[] privacy_bitmask;
privacy_bitmask = NULL; privacy_bitmask = nullptr;
} }
Image *privacy_image = NULL; Image *privacy_image = nullptr;
for ( int i = 0; i < n_zones; i++ ) { for ( int i = 0; i < n_zones; i++ ) {
if ( p_zones[i]->IsPrivacy() ) { if ( p_zones[i]->IsPrivacy() ) {
@ -1139,7 +1139,7 @@ void Monitor::DumpZoneImage(const char *zone_string) {
} }
} }
Image *zone_image = NULL; Image *zone_image = nullptr;
if ( ( (!staticConfig.SERVER_ID) || ( staticConfig.SERVER_ID == server_id ) ) && mem_ptr ) { if ( ( (!staticConfig.SERVER_ID) || ( staticConfig.SERVER_ID == server_id ) ) && mem_ptr ) {
Debug(3, "Trying to load from local zmc"); Debug(3, "Trying to load from local zmc");
int index = shared_data->last_write_index; int index = shared_data->last_write_index;
@ -1158,7 +1158,7 @@ void Monitor::DumpZoneImage(const char *zone_string) {
stream->setStreamStart(event_id, (unsigned int)1); stream->setStreamStart(event_id, (unsigned int)1);
zone_image = stream->getImage(); zone_image = stream->getImage();
delete stream; delete stream;
stream = NULL; stream = nullptr;
} else { } else {
Error("Unable to load an event for monitor %d", id); Error("Unable to load an event for monitor %d", id);
return; return;
@ -1294,7 +1294,7 @@ bool Monitor::Analyse() {
} }
struct timeval now; struct timeval now;
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
if ( image_count && fps_report_interval && !(image_count%fps_report_interval) ) { if ( image_count && fps_report_interval && !(image_count%fps_report_interval) ) {
if ( now.tv_sec != last_fps_time ) { if ( now.tv_sec != last_fps_time ) {
@ -1700,9 +1700,9 @@ bool Monitor::Analyse() {
} // end foreach zone } // end foreach zone
if ( state == PREALARM ) { if ( state == PREALARM ) {
Event::AddPreAlarmFrame(snap_image, *timestamp, score, (got_anal_image?&alarm_image:NULL)); Event::AddPreAlarmFrame(snap_image, *timestamp, score, (got_anal_image?&alarm_image:nullptr));
} else { } else {
event->AddFrame(snap_image, *timestamp, score, (got_anal_image?&alarm_image:NULL)); event->AddFrame(snap_image, *timestamp, score, (got_anal_image?&alarm_image:nullptr));
} }
} else { } else {
// Not doing alarm frame storage // Not doing alarm frame storage
@ -1848,8 +1848,8 @@ void Monitor::Reload() {
min_section_length = atoi(dbrow[index++]); min_section_length = atoi(dbrow[index++]);
frame_skip = atoi(dbrow[index++]); frame_skip = atoi(dbrow[index++]);
motion_frame_skip = atoi(dbrow[index++]); motion_frame_skip = atoi(dbrow[index++]);
analysis_fps = dbrow[index] ? strtod(dbrow[index], NULL) : 0; index++; analysis_fps = dbrow[index] ? strtod(dbrow[index], nullptr) : 0; index++;
analysis_update_delay = strtoul(dbrow[index++], NULL, 0); analysis_update_delay = strtoul(dbrow[index++], nullptr, 0);
capture_max_fps = dbrow[index] ? atof(dbrow[index]) : 0.0; index++; capture_max_fps = dbrow[index] ? atof(dbrow[index]) : 0.0; index++;
capture_delay = ( capture_max_fps > 0.0 ) ? int(DT_PREC_3/capture_max_fps) : 0; capture_delay = ( capture_max_fps > 0.0 ) ? int(DT_PREC_3/capture_max_fps) : 0;
@ -1882,7 +1882,7 @@ void Monitor::ReloadZones() {
delete zones[i]; delete zones[i];
} }
delete[] zones; delete[] zones;
zones = 0; zones = nullptr;
n_zones = Zone::Load(this, zones); n_zones = Zone::Load(this, zones);
//DumpZoneImage(); //DumpZoneImage();
} // end void Monitor::ReloadZones() } // end void Monitor::ReloadZones()
@ -1894,7 +1894,7 @@ void Monitor::ReloadLinkedMonitors(const char *p_linked_monitors) {
delete linked_monitors[i]; delete linked_monitors[i];
} }
delete[] linked_monitors; delete[] linked_monitors;
linked_monitors = 0; linked_monitors = nullptr;
} }
n_linked_monitors = 0; n_linked_monitors = 0;
@ -2082,8 +2082,8 @@ Monitor *Monitor::Load(MYSQL_ROW dbrow, bool load_zones, Purpose purpose) {
int enabled = dbrow[col] ? atoi(dbrow[col]) : 0; col++; int enabled = dbrow[col] ? atoi(dbrow[col]) : 0; col++;
const char *linked_monitors = dbrow[col];col++; const char *linked_monitors = dbrow[col];col++;
double analysis_fps = dbrow[col] ? strtod(dbrow[col], NULL) : 0; col++; double analysis_fps = dbrow[col] ? strtod(dbrow[col], nullptr) : 0; col++;
unsigned int analysis_update_delay = strtoul(dbrow[col++], NULL, 0); unsigned int analysis_update_delay = strtoul(dbrow[col++], nullptr, 0);
double capture_max_fps = dbrow[col] ? atof(dbrow[col]) : 0.0; col++; double capture_max_fps = dbrow[col] ? atof(dbrow[col]) : 0.0; col++;
double capture_delay = ( capture_max_fps > 0.0 ) ? int(DT_PREC_3/capture_max_fps) : 0; double capture_delay = ( capture_max_fps > 0.0 ) ? int(DT_PREC_3/capture_max_fps) : 0;
@ -2161,9 +2161,9 @@ Monitor *Monitor::Load(MYSQL_ROW dbrow, bool load_zones, Purpose purpose) {
int track_motion = atoi(dbrow[col]); col++; int track_motion = atoi(dbrow[col]); col++;
bool embed_exif = (*dbrow[col] != '0'); col++; bool embed_exif = (*dbrow[col] != '0'); col++;
int signal_check_points = dbrow[col] ? atoi(dbrow[col]) : 0;col++; int signal_check_points = dbrow[col] ? atoi(dbrow[col]) : 0;col++;
int signal_check_color = strtol(dbrow[col][0] == '#' ? dbrow[col]+1 : dbrow[col], 0, 16); col++; int signal_check_color = strtol(dbrow[col][0] == '#' ? dbrow[col]+1 : dbrow[col], nullptr, 16); col++;
Camera *camera = 0; Camera *camera = nullptr;
if ( type == "Local" ) { if ( type == "Local" ) {
#if ZM_HAS_V4L #if ZM_HAS_V4L
@ -2412,7 +2412,7 @@ Monitor *Monitor::Load(unsigned int p_id, bool load_zones, Purpose purpose) {
zmDbRow dbrow; zmDbRow dbrow;
if ( ! dbrow.fetch(sql.c_str()) ) { if ( ! dbrow.fetch(sql.c_str()) ) {
Error("Can't use query result: %s", mysql_error(&dbconn)); Error("Can't use query result: %s", mysql_error(&dbconn));
return NULL; return nullptr;
} }
Monitor *monitor = Monitor::Load(dbrow.mysql_row(), load_zones, purpose); Monitor *monitor = Monitor::Load(dbrow.mysql_row(), load_zones, purpose);
@ -2521,7 +2521,7 @@ int Monitor::Capture() {
if ( (index == shared_data->last_read_index) && (function > MONITOR) ) { if ( (index == shared_data->last_read_index) && (function > MONITOR) ) {
Warning("Buffer overrun at index %d, image %d, slow down capture, speed up analysis or increase ring buffer size", Warning("Buffer overrun at index %d, image %d, slow down capture, speed up analysis or increase ring buffer size",
index, image_count ); index, image_count );
time_t now = time(0); time_t now = time(nullptr);
double approxFps = double(image_buffer_count)/double(now-image_buffer[index].timestamp->tv_sec); double approxFps = double(image_buffer_count)/double(now-image_buffer[index].timestamp->tv_sec);
time_t last_read_delta = now - shared_data->last_read_time; time_t last_read_delta = now - shared_data->last_read_time;
if ( last_read_delta > (image_buffer_count/approxFps) ) { if ( last_read_delta > (image_buffer_count/approxFps) ) {
@ -2534,7 +2534,7 @@ int Monitor::Capture() {
capture_image->MaskPrivacy(privacy_bitmask); capture_image->MaskPrivacy(privacy_bitmask);
// Might be able to remove this call, when we start passing around ZMPackets, which will already have a timestamp // Might be able to remove this call, when we start passing around ZMPackets, which will already have a timestamp
gettimeofday(image_buffer[index].timestamp, NULL); gettimeofday(image_buffer[index].timestamp, nullptr);
if ( config.timestamp_on_capture ) { if ( config.timestamp_on_capture ) {
TimestampImage(capture_image, image_buffer[index].timestamp); TimestampImage(capture_image, image_buffer[index].timestamp);
} }
@ -2642,23 +2642,23 @@ bool Monitor::closeEvent() {
if ( function == RECORD || function == MOCORD ) { if ( function == RECORD || function == MOCORD ) {
//FIXME Is this neccessary? ENdTime should be set in the destructor //FIXME Is this neccessary? ENdTime should be set in the destructor
gettimeofday(&(event->EndTime()), NULL); gettimeofday(&(event->EndTime()), nullptr);
} }
if ( event_delete_thread ) { if ( event_delete_thread ) {
event_delete_thread->join(); event_delete_thread->join();
delete event_delete_thread; delete event_delete_thread;
event_delete_thread = NULL; event_delete_thread = nullptr;
} }
#if 0 #if 0
event_delete_thread = new std::thread([](Event *event) { event_delete_thread = new std::thread([](Event *event) {
Event * e = event; Event * e = event;
event = NULL; event = nullptr;
delete e; delete e;
e = NULL; e = nullptr;
}, event); }, event);
#else #else
delete event; delete event;
event = NULL; event = nullptr;
#endif #endif
video_store_data->recording = (struct timeval){0}; video_store_data->recording = (struct timeval){0};
return true; return true;

View File

@ -315,7 +315,7 @@ bool MonitorStream::sendFrame(const char *filepath, struct timeval *timestamp) {
int img_buffer_size = 0; int img_buffer_size = 0;
static unsigned char img_buffer[ZM_MAX_IMAGE_SIZE]; static unsigned char img_buffer[ZM_MAX_IMAGE_SIZE];
FILE *fdj = NULL; FILE *fdj = nullptr;
if ( (fdj = fopen(filepath, "r")) ) { if ( (fdj = fopen(filepath, "r")) ) {
img_buffer_size = fread(img_buffer, 1, sizeof(img_buffer), fdj); img_buffer_size = fread(img_buffer, 1, sizeof(img_buffer), fdj);
fclose(fdj); fclose(fdj);
@ -326,7 +326,7 @@ bool MonitorStream::sendFrame(const char *filepath, struct timeval *timestamp) {
// Calculate how long it takes to actually send the frame // Calculate how long it takes to actually send the frame
struct timeval frameStartTime; struct timeval frameStartTime;
gettimeofday(&frameStartTime, NULL); gettimeofday(&frameStartTime, nullptr);
if ( if (
(0 > fprintf(stdout, "Content-Length: %d\r\nX-Timestamp: %d.%06d\r\n\r\n", (0 > fprintf(stdout, "Content-Length: %d\r\nX-Timestamp: %d.%06d\r\n\r\n",
@ -342,7 +342,7 @@ bool MonitorStream::sendFrame(const char *filepath, struct timeval *timestamp) {
fflush(stdout); fflush(stdout);
struct timeval frameEndTime; struct timeval frameEndTime;
gettimeofday(&frameEndTime, NULL); gettimeofday(&frameEndTime, nullptr);
int frameSendTime = tvDiffMsec(frameStartTime, frameEndTime); int frameSendTime = tvDiffMsec(frameStartTime, frameEndTime);
if ( frameSendTime > 1000/maxfps ) { if ( frameSendTime > 1000/maxfps ) {
@ -386,7 +386,7 @@ bool MonitorStream::sendFrame(Image *image, struct timeval *timestamp) {
// Calculate how long it takes to actually send the frame // Calculate how long it takes to actually send the frame
struct timeval frameStartTime; struct timeval frameStartTime;
gettimeofday(&frameStartTime, NULL); gettimeofday(&frameStartTime, nullptr);
fputs("--ZoneMinderFrame\r\n", stdout); fputs("--ZoneMinderFrame\r\n", stdout);
switch ( type ) { switch ( type ) {
@ -430,7 +430,7 @@ bool MonitorStream::sendFrame(Image *image, struct timeval *timestamp) {
fflush(stdout); fflush(stdout);
struct timeval frameEndTime; struct timeval frameEndTime;
gettimeofday(&frameEndTime, NULL); gettimeofday(&frameEndTime, nullptr);
int frameSendTime = tvDiffMsec(frameStartTime, frameEndTime); int frameSendTime = tvDiffMsec(frameStartTime, frameEndTime);
if ( frameSendTime > 1000/maxfps ) { if ( frameSendTime > 1000/maxfps ) {
@ -470,7 +470,7 @@ void MonitorStream::runStream() {
frame_count = 0; frame_count = 0;
temp_image_buffer = 0; temp_image_buffer = nullptr;
temp_image_buffer_count = playback_buffer; temp_image_buffer_count = playback_buffer;
temp_read_index = temp_image_buffer_count; temp_read_index = temp_image_buffer_count;
temp_write_index = temp_image_buffer_count; temp_write_index = temp_image_buffer_count;
@ -479,7 +479,7 @@ void MonitorStream::runStream() {
bool buffered_playback = false; bool buffered_playback = false;
// Last image and timestamp when paused, will be resent occasionally to prevent timeout // Last image and timestamp when paused, will be resent occasionally to prevent timeout
Image *paused_image = NULL; Image *paused_image = nullptr;
struct timeval paused_timestamp; struct timeval paused_timestamp;
if ( connkey && ( playback_buffer > 0 ) ) { if ( connkey && ( playback_buffer > 0 ) ) {
@ -487,8 +487,8 @@ void MonitorStream::runStream() {
const int max_swap_len_suffix = 15; const int max_swap_len_suffix = 15;
int swap_path_length = staticConfig.PATH_SWAP.length() + 1; // +1 for NULL terminator int swap_path_length = staticConfig.PATH_SWAP.length() + 1; // +1 for NULL terminator
int subfolder1_length = snprintf(NULL, 0, "/zmswap-m%d", monitor->Id()) + 1; int subfolder1_length = snprintf(nullptr, 0, "/zmswap-m%d", monitor->Id()) + 1;
int subfolder2_length = snprintf(NULL, 0, "/zmswap-q%06d", connkey) + 1; int subfolder2_length = snprintf(nullptr, 0, "/zmswap-q%06d", connkey) + 1;
int total_swap_path_length = swap_path_length + subfolder1_length + subfolder2_length; int total_swap_path_length = swap_path_length + subfolder1_length + subfolder2_length;
if ( total_swap_path_length + max_swap_len_suffix > PATH_MAX ) { if ( total_swap_path_length + max_swap_len_suffix > PATH_MAX ) {
@ -545,7 +545,7 @@ void MonitorStream::runStream() {
break; break;
} }
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
bool was_paused = paused; bool was_paused = paused;
if ( connkey ) { if ( connkey ) {
@ -571,7 +571,7 @@ void MonitorStream::runStream() {
} else if ( paused_image ) { } else if ( paused_image ) {
Debug(1, "Clearing paused_image"); Debug(1, "Clearing paused_image");
delete paused_image; delete paused_image;
paused_image = NULL; paused_image = nullptr;
} }
if ( buffered_playback && delayed ) { if ( buffered_playback && delayed ) {

View File

@ -59,7 +59,7 @@ class MonitorStream : public StreamBase {
public: public:
MonitorStream() : MonitorStream() :
temp_image_buffer(NULL), temp_image_buffer_count(0), temp_read_index(0), temp_write_index(0), temp_image_buffer(nullptr), temp_image_buffer_count(0), temp_read_index(0), temp_write_index(0),
ttl(0), playback_buffer(0), delayed(false), frame_count(0) { ttl(0), playback_buffer(0), delayed(false), frame_count(0) {
} }
void setStreamBuffer(int p_playback_buffer) { void setStreamBuffer(int p_playback_buffer) {

View File

@ -46,9 +46,9 @@ void VideoStream::Initialise( ) {
void VideoStream::SetupFormat( ) { void VideoStream::SetupFormat( ) {
/* allocate the output media context */ /* allocate the output media context */
ofc = NULL; ofc = nullptr;
#if (LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 2, 0) && (LIBAVFORMAT_VERSION_MICRO >= 100)) #if (LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 2, 0) && (LIBAVFORMAT_VERSION_MICRO >= 100))
avformat_alloc_output_context2(&ofc, NULL, format, filename); avformat_alloc_output_context2(&ofc, nullptr, format, filename);
#else #else
AVFormatContext *s = avformat_alloc_context(); AVFormatContext *s = avformat_alloc_context();
if ( !s ) { if ( !s ) {
@ -59,18 +59,18 @@ void VideoStream::SetupFormat( ) {
AVOutputFormat *oformat; AVOutputFormat *oformat;
if ( format ) { if ( format ) {
#if LIBAVFORMAT_VERSION_CHECK(52, 45, 0, 45, 0) #if LIBAVFORMAT_VERSION_CHECK(52, 45, 0, 45, 0)
oformat = av_guess_format(format, NULL, NULL); oformat = av_guess_format(format, nullptr, nullptr);
#else #else
oformat = guess_format(format, NULL, NULL); oformat = guess_format(format, nullptr, nullptr);
#endif #endif
if ( !oformat ) { if ( !oformat ) {
Fatal("Requested output format '%s' is not a suitable output format", format); Fatal("Requested output format '%s' is not a suitable output format", format);
} }
} else { } else {
#if LIBAVFORMAT_VERSION_CHECK(52, 45, 0, 45, 0) #if LIBAVFORMAT_VERSION_CHECK(52, 45, 0, 45, 0)
oformat = av_guess_format(NULL, filename, NULL); oformat = av_guess_format(nullptr, filename, nullptr);
#else #else
oformat = guess_format(NULL, filename, NULL); oformat = guess_format(nullptr, filename, nullptr);
#endif #endif
if ( !oformat ) { if ( !oformat ) {
Fatal("Unable to find a suitable output format for '%s'", format); Fatal("Unable to find a suitable output format for '%s'", format);
@ -91,7 +91,7 @@ void VideoStream::SetupFormat( ) {
#endif #endif
} else { } else {
Debug(1, "No allocating priv_data"); Debug(1, "No allocating priv_data");
s->priv_data = NULL; s->priv_data = nullptr;
} }
if ( filename ) { if ( filename ) {
@ -172,7 +172,7 @@ void VideoStream::SetupCodec( int colours, int subpixelorder, int width, int hei
/* add the video streams using the default format codecs /* add the video streams using the default format codecs
and initialize the codecs */ and initialize the codecs */
ost = NULL; ost = nullptr;
if ( codec_id != AV_CODEC_ID_NONE ) { if ( codec_id != AV_CODEC_ID_NONE ) {
codec = avcodec_find_encoder(codec_id); codec = avcodec_find_encoder(codec_id);
if ( !codec ) { if ( !codec ) {
@ -204,7 +204,7 @@ void VideoStream::SetupCodec( int colours, int subpixelorder, int width, int hei
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
codec_context = avcodec_alloc_context3(NULL); codec_context = avcodec_alloc_context3(nullptr);
//avcodec_parameters_to_context(codec_context, ost->codecpar); //avcodec_parameters_to_context(codec_context, ost->codecpar);
#else #else
codec_context = ost->codec; codec_context = ost->codec;
@ -296,7 +296,7 @@ bool VideoStream::OpenStream( ) {
#if !LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 8, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 8, 0)
if ( (ret = avcodec_open(codec_context, codec)) < 0 ) if ( (ret = avcodec_open(codec_context, codec)) < 0 )
#else #else
if ( (ret = avcodec_open2(codec_context, codec, 0)) < 0 ) if ( (ret = avcodec_open2(codec_context, codec, nullptr)) < 0 )
#endif #endif
{ {
Error("Could not open codec. Error code %d \"%s\"", ret, av_err2str(ret)); Error("Could not open codec. Error code %d \"%s\"", ret, av_err2str(ret));
@ -338,7 +338,7 @@ bool VideoStream::OpenStream( ) {
/* if the output format is not identical to the input format, then a temporary /* if the output format is not identical to the input format, then a temporary
picture is needed too. It is then converted to the required picture is needed too. It is then converted to the required
output format */ output format */
tmp_opicture = NULL; tmp_opicture = nullptr;
if ( codec_context->pix_fmt != pf ) { if ( codec_context->pix_fmt != pf ) {
#if LIBAVCODEC_VERSION_CHECK(55, 28, 1, 45, 101) #if LIBAVCODEC_VERSION_CHECK(55, 28, 1, 45, 101)
tmp_opicture = av_frame_alloc( ); tmp_opicture = av_frame_alloc( );
@ -374,7 +374,7 @@ bool VideoStream::OpenStream( ) {
/* open the output file, if needed */ /* open the output file, if needed */
if ( !(of->flags & AVFMT_NOFILE) ) { if ( !(of->flags & AVFMT_NOFILE) ) {
#if LIBAVFORMAT_VERSION_CHECK(53, 15, 0, 21, 0) #if LIBAVFORMAT_VERSION_CHECK(53, 15, 0, 21, 0)
ret = avio_open2( &ofc->pb, filename, AVIO_FLAG_WRITE, NULL, NULL ); ret = avio_open2( &ofc->pb, filename, AVIO_FLAG_WRITE, nullptr, nullptr );
#elif LIBAVFORMAT_VERSION_CHECK(52, 102, 0, 102, 0) #elif LIBAVFORMAT_VERSION_CHECK(52, 102, 0, 102, 0)
ret = avio_open( &ofc->pb, filename, AVIO_FLAG_WRITE ); ret = avio_open( &ofc->pb, filename, AVIO_FLAG_WRITE );
#else #else
@ -391,7 +391,7 @@ bool VideoStream::OpenStream( ) {
return false; return false;
} }
video_outbuf = NULL; video_outbuf = nullptr;
#if LIBAVFORMAT_VERSION_CHECK(57, 0, 0, 0, 0) #if LIBAVFORMAT_VERSION_CHECK(57, 0, 0, 0, 0)
if (codec_context->codec_type == AVMEDIA_TYPE_VIDEO && if (codec_context->codec_type == AVMEDIA_TYPE_VIDEO &&
codec_context->codec_id == AV_CODEC_ID_RAWVIDEO) { codec_context->codec_id == AV_CODEC_ID_RAWVIDEO) {
@ -403,7 +403,7 @@ bool VideoStream::OpenStream( ) {
// TODO: Make buffer dynamic. // TODO: Make buffer dynamic.
video_outbuf_size = 4000000; video_outbuf_size = 4000000;
video_outbuf = (uint8_t *)malloc( video_outbuf_size ); video_outbuf = (uint8_t *)malloc( video_outbuf_size );
if ( video_outbuf == NULL ) { if ( video_outbuf == nullptr ) {
Fatal("Unable to malloc memory for outbuf"); Fatal("Unable to malloc memory for outbuf");
} }
} }
@ -417,7 +417,7 @@ bool VideoStream::OpenStream( ) {
#if !LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 4, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 4, 0)
ret = av_write_header(ofc); ret = av_write_header(ofc);
#else #else
ret = avformat_write_header(ofc, NULL); ret = avformat_write_header(ofc, nullptr);
#endif #endif
if ( ret < 0 ) { if ( ret < 0 ) {
@ -430,16 +430,16 @@ bool VideoStream::OpenStream( ) {
VideoStream::VideoStream( const char *in_filename, const char *in_format, int bitrate, double frame_rate, int colours, int subpixelorder, int width, int height ) : VideoStream::VideoStream( const char *in_filename, const char *in_format, int bitrate, double frame_rate, int colours, int subpixelorder, int width, int height ) :
filename(in_filename), filename(in_filename),
format(in_format), format(in_format),
opicture(NULL), opicture(nullptr),
tmp_opicture(NULL), tmp_opicture(nullptr),
video_outbuf(NULL), video_outbuf(nullptr),
video_outbuf_size(0), video_outbuf_size(0),
last_pts( -1 ), last_pts( -1 ),
streaming_thread(0), streaming_thread(0),
do_streaming(true), do_streaming(true),
add_timestamp(false), add_timestamp(false),
timestamp(0), timestamp(0),
buffer_copy(NULL), buffer_copy(nullptr),
buffer_copy_lock(new pthread_mutex_t), buffer_copy_lock(new pthread_mutex_t),
buffer_copy_size(0), buffer_copy_size(0),
buffer_copy_used(0), buffer_copy_used(0),
@ -454,15 +454,15 @@ VideoStream::VideoStream( const char *in_filename, const char *in_format, int bi
codec_and_format = new char[length+1];; codec_and_format = new char[length+1];;
strcpy( codec_and_format, format ); strcpy( codec_and_format, format );
format = codec_and_format; format = codec_and_format;
codec_name = NULL; codec_name = nullptr;
char *f = strchr(codec_and_format, '/'); char *f = strchr(codec_and_format, '/');
if (f != NULL) { if (f != nullptr) {
*f = 0; *f = 0;
codec_name = f+1; codec_name = f+1;
} }
} }
codec_context = NULL; codec_context = nullptr;
SetupFormat( ); SetupFormat( );
SetupCodec( colours, subpixelorder, width, height, bitrate, frame_rate ); SetupCodec( colours, subpixelorder, width, height, bitrate, frame_rate );
SetParameters( ); SetParameters( );
@ -474,7 +474,7 @@ VideoStream::VideoStream( const char *in_filename, const char *in_format, int bi
packet_index = 0; packet_index = 0;
// Initialize mutex used by streaming thread. // Initialize mutex used by streaming thread.
if ( pthread_mutex_init( buffer_copy_lock, NULL ) != 0 ) { if ( pthread_mutex_init( buffer_copy_lock, nullptr ) != 0 ) {
Fatal("pthread_mutex_init failed"); Fatal("pthread_mutex_init failed");
} }
@ -494,7 +494,7 @@ VideoStream::~VideoStream( ) {
pthread_join(streaming_thread, &thread_exit_code); pthread_join(streaming_thread, &thread_exit_code);
} }
if ( buffer_copy != NULL ) { if ( buffer_copy != nullptr ) {
av_free( buffer_copy ); av_free( buffer_copy );
} }
@ -582,7 +582,7 @@ double VideoStream::EncodeFrame( const uint8_t *buffer, int buffer_size, bool _a
Debug( 1, "Starting streaming thread" ); Debug( 1, "Starting streaming thread" );
// Start a thread for streaming encoded video. // Start a thread for streaming encoded video.
if (pthread_create( &streaming_thread, NULL, StreamingThreadCallback, (void*) this) != 0){ if (pthread_create( &streaming_thread, nullptr, StreamingThreadCallback, (void*) this) != 0){
// Log a fatal error and exit the process. // Log a fatal error and exit the process.
Fatal( "VideoStream failed to create streaming thread." ); Fatal( "VideoStream failed to create streaming thread." );
} }
@ -597,12 +597,12 @@ double VideoStream::ActuallyEncodeFrame( const uint8_t *buffer, int buffer_size,
if ( codec_context->pix_fmt != pf ) { if ( codec_context->pix_fmt != pf ) {
#ifdef HAVE_LIBSWSCALE #ifdef HAVE_LIBSWSCALE
static struct SwsContext *img_convert_ctx = 0; static struct SwsContext *img_convert_ctx = nullptr;
#endif // HAVE_LIBSWSCALE #endif // HAVE_LIBSWSCALE
memcpy( tmp_opicture->data[0], buffer, buffer_size ); memcpy( tmp_opicture->data[0], buffer, buffer_size );
#ifdef HAVE_LIBSWSCALE #ifdef HAVE_LIBSWSCALE
if ( !img_convert_ctx ) { if ( !img_convert_ctx ) {
img_convert_ctx = sws_getCachedContext( NULL, codec_context->width, codec_context->height, pf, codec_context->width, codec_context->height, codec_context->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL ); img_convert_ctx = sws_getCachedContext( nullptr, codec_context->width, codec_context->height, pf, codec_context->width, codec_context->height, codec_context->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr );
if ( !img_convert_ctx ) if ( !img_convert_ctx )
Panic( "Unable to initialise image scaling context" ); Panic( "Unable to initialise image scaling context" );
} }
@ -659,7 +659,7 @@ double VideoStream::ActuallyEncodeFrame( const uint8_t *buffer, int buffer_size,
#else #else
int out_size = avcodec_encode_video( codec_context, video_outbuf, video_outbuf_size, opicture_ptr ); int out_size = avcodec_encode_video( codec_context, video_outbuf, video_outbuf_size, opicture_ptr );
got_packet = out_size > 0 ? 1 : 0; got_packet = out_size > 0 ? 1 : 0;
pkt->data = got_packet ? video_outbuf : NULL; pkt->data = got_packet ? video_outbuf : nullptr;
pkt->size = got_packet ? out_size : 0; pkt->size = got_packet ? out_size : 0;
#endif #endif
#endif #endif
@ -705,7 +705,7 @@ void *VideoStream::StreamingThreadCallback(void *ctx){
Debug( 1, "StreamingThreadCallback started" ); Debug( 1, "StreamingThreadCallback started" );
if (ctx == NULL) return NULL; if (ctx == nullptr) return nullptr;
VideoStream* videoStream = reinterpret_cast<VideoStream*>(ctx); VideoStream* videoStream = reinterpret_cast<VideoStream*>(ctx);
@ -765,7 +765,7 @@ void *VideoStream::StreamingThreadCallback(void *ctx){
frame_count++; frame_count++;
} }
return 0; return nullptr;
} }
#endif // HAVE_LIBAVCODEC #endif // HAVE_LIBAVCODEC

View File

@ -25,18 +25,18 @@
using namespace std; using namespace std;
ZMPacket::ZMPacket( AVPacket *p ) { ZMPacket::ZMPacket( AVPacket *p ) {
frame = NULL; frame = nullptr;
image = NULL; image = nullptr;
av_init_packet( &packet ); av_init_packet( &packet );
if ( zm_av_packet_ref( &packet, p ) < 0 ) { if ( zm_av_packet_ref( &packet, p ) < 0 ) {
Error("error refing packet"); Error("error refing packet");
} }
gettimeofday( &timestamp, NULL ); gettimeofday( &timestamp, nullptr );
} }
ZMPacket::ZMPacket( AVPacket *p, struct timeval *t ) { ZMPacket::ZMPacket( AVPacket *p, struct timeval *t ) {
frame = NULL; frame = nullptr;
image = NULL; image = nullptr;
av_init_packet( &packet ); av_init_packet( &packet );
if ( zm_av_packet_ref( &packet, p ) < 0 ) { if ( zm_av_packet_ref( &packet, p ) < 0 ) {
Error("error refing packet"); Error("error refing packet");

View File

@ -32,7 +32,7 @@ zm_packetqueue::zm_packetqueue( int p_max_stream_id ) {
zm_packetqueue::~zm_packetqueue() { zm_packetqueue::~zm_packetqueue() {
clearQueue(); clearQueue();
delete[] packet_counts; delete[] packet_counts;
packet_counts = NULL; packet_counts = nullptr;
} }
bool zm_packetqueue::queuePacket(ZMPacket* zm_packet) { bool zm_packetqueue::queuePacket(ZMPacket* zm_packet) {
@ -116,7 +116,7 @@ bool zm_packetqueue::queuePacket(AVPacket* av_packet) {
ZMPacket* zm_packetqueue::popPacket( ) { ZMPacket* zm_packetqueue::popPacket( ) {
if ( pktQueue.empty() ) { if ( pktQueue.empty() ) {
return NULL; return nullptr;
} }
ZMPacket *packet = pktQueue.front(); ZMPacket *packet = pktQueue.front();
@ -137,7 +137,7 @@ unsigned int zm_packetqueue::clearQueue(unsigned int frames_to_keep, int stream_
} }
std::list<ZMPacket *>::reverse_iterator it; std::list<ZMPacket *>::reverse_iterator it;
ZMPacket *packet = NULL; ZMPacket *packet = nullptr;
for ( it = pktQueue.rbegin(); it != pktQueue.rend() && frames_to_keep; ++it ) { for ( it = pktQueue.rbegin(); it != pktQueue.rend() && frames_to_keep; ++it ) {
ZMPacket *zm_packet = *it; ZMPacket *zm_packet = *it;
@ -186,13 +186,13 @@ unsigned int zm_packetqueue::clearQueue(unsigned int frames_to_keep, int stream_
delete_count += 1; delete_count += 1;
} }
packet = NULL; // tidy up for valgrind packet = nullptr; // tidy up for valgrind
Debug(3, "Deleted %d packets, %d remaining", delete_count, pktQueue.size()); Debug(3, "Deleted %d packets, %d remaining", delete_count, pktQueue.size());
return delete_count; return delete_count;
} // end unsigned int zm_packetqueue::clearQueue( unsigned int frames_to_keep, int stream_id ) } // end unsigned int zm_packetqueue::clearQueue( unsigned int frames_to_keep, int stream_id )
void zm_packetqueue::clearQueue() { void zm_packetqueue::clearQueue() {
ZMPacket *packet = NULL; ZMPacket *packet = nullptr;
int delete_count = 0; int delete_count = 0;
while ( !pktQueue.empty() ) { while ( !pktQueue.empty() ) {
packet = pktQueue.front(); packet = pktQueue.front();
@ -256,7 +256,7 @@ unsigned int zm_packetqueue::clearQueue(struct timeval *duration, int streamId)
} }
unsigned int deleted_frames = 0; unsigned int deleted_frames = 0;
ZMPacket *zm_packet = NULL; ZMPacket *zm_packet = nullptr;
while (distance(it, pktQueue.rend()) > 1) { while (distance(it, pktQueue.rend()) > 1) {
zm_packet = pktQueue.front(); zm_packet = pktQueue.front();
pktQueue.pop_front(); pktQueue.pop_front();
@ -264,7 +264,7 @@ unsigned int zm_packetqueue::clearQueue(struct timeval *duration, int streamId)
delete zm_packet; delete zm_packet;
deleted_frames += 1; deleted_frames += 1;
} }
zm_packet = NULL; zm_packet = nullptr;
Debug(3, "Deleted %d frames", deleted_frames); Debug(3, "Deleted %d frames", deleted_frames);
return deleted_frames; return deleted_frames;
@ -366,7 +366,7 @@ void zm_packetqueue::clear_unwanted_packets(
pktQueue.size() ); pktQueue.size() );
unsigned int deleted_frames = 0; unsigned int deleted_frames = 0;
ZMPacket *packet = NULL; ZMPacket *packet = nullptr;
while ( distance(it, pktQueue.rend()) > 1 ) { while ( distance(it, pktQueue.rend()) > 1 ) {
//while ( pktQueue.rend() != it ) { //while ( pktQueue.rend() != it ) {
packet = pktQueue.front(); packet = pktQueue.front();
@ -375,7 +375,7 @@ void zm_packetqueue::clear_unwanted_packets(
delete packet; delete packet;
deleted_frames += 1; deleted_frames += 1;
} }
packet = NULL; // tidy up for valgrind packet = nullptr; // tidy up for valgrind
zm_packet = pktQueue.front(); zm_packet = pktQueue.front();
av_packet = &(zm_packet->packet); av_packet = &(zm_packet->packet);

View File

@ -61,7 +61,7 @@ protected:
min_x = 0; min_x = 0;
max_x = 0; max_x = 0;
n_edges = 0; n_edges = 0;
edges = 0; edges = nullptr;
} }
~Slice() { ~Slice() {
delete edges; delete edges;
@ -83,7 +83,7 @@ protected:
void calcCentre(); void calcCentre();
public: public:
inline Polygon() : n_coords(0), coords(0), area(0), edges(0), slices(0) { inline Polygon() : n_coords(0), coords(nullptr), area(0), edges(nullptr), slices(nullptr) {
} }
Polygon(int p_n_coords, const Coord *p_coords); Polygon(int p_n_coords, const Coord *p_coords);
Polygon(const Polygon &p_polygon); Polygon(const Polygon &p_polygon);

View File

@ -24,7 +24,7 @@
#if HAVE_LIBPCRE #if HAVE_LIBPCRE
RegExpr::RegExpr( const char *pattern, int flags, int p_max_matches ) : max_matches( p_max_matches ), match_buffers( 0 ), match_lengths( 0 ), match_valid( 0 ) RegExpr::RegExpr( const char *pattern, int flags, int p_max_matches ) : max_matches( p_max_matches ), match_buffers( nullptr ), match_lengths( nullptr ), match_valid( nullptr )
{ {
const char *errstr; const char *errstr;
int erroffset = 0; int erroffset = 0;
@ -50,7 +50,7 @@ RegExpr::RegExpr( const char *pattern, int flags, int p_max_matches ) : max_matc
match_valid = new bool[max_matches]; match_valid = new bool[max_matches];
memset( match_valid, 0, sizeof(*match_valid)*max_matches ); memset( match_valid, 0, sizeof(*match_valid)*max_matches );
} else { } else {
match_vectors = NULL; match_vectors = nullptr;
} }
match_string = ""; match_string = "";
n_matches = 0; n_matches = 0;

View File

@ -44,20 +44,20 @@ RemoteCamera::RemoteCamera(
path( p_path ), path( p_path ),
hp( 0 ), hp( 0 ),
mNeedAuth(false), mNeedAuth(false),
mAuthenticator(NULL) mAuthenticator(nullptr)
{ {
if ( path[0] != '/' ) if ( path[0] != '/' )
path = '/'+path; path = '/'+path;
} }
RemoteCamera::~RemoteCamera() { RemoteCamera::~RemoteCamera() {
if ( hp != NULL ) { if ( hp != nullptr ) {
freeaddrinfo(hp); freeaddrinfo(hp);
hp = NULL; hp = nullptr;
} }
if ( mAuthenticator ) { if ( mAuthenticator ) {
delete mAuthenticator; delete mAuthenticator;
mAuthenticator = NULL; mAuthenticator = nullptr;
} }
} }
@ -99,9 +99,9 @@ void RemoteCamera::Initialise() {
if ( ret != 0 ) { if ( ret != 0 ) {
Fatal( "Can't getaddrinfo(%s port %s): %s", host.c_str(), port.c_str(), gai_strerror(ret) ); Fatal( "Can't getaddrinfo(%s port %s): %s", host.c_str(), port.c_str(), gai_strerror(ret) );
} }
struct addrinfo *p = NULL; struct addrinfo *p = nullptr;
int addr_count = 0; int addr_count = 0;
for ( p = hp; p != NULL; p = p->ai_next ) { for ( p = hp; p != nullptr; p = p->ai_next ) {
addr_count++; addr_count++;
} }
Debug(1, "%d addresses returned", addr_count); Debug(1, "%d addresses returned", addr_count);

View File

@ -36,11 +36,11 @@
#endif #endif
#if HAVE_LIBPCRE #if HAVE_LIBPCRE
static RegExpr *header_expr = 0; static RegExpr *header_expr = nullptr;
static RegExpr *status_expr = 0; static RegExpr *status_expr = nullptr;
static RegExpr *connection_expr = 0; static RegExpr *connection_expr = nullptr;
static RegExpr *content_length_expr = 0; static RegExpr *content_length_expr = nullptr;
static RegExpr *content_type_expr = 0; static RegExpr *content_type_expr = nullptr;
#endif #endif
RemoteCameraHttp::RemoteCameraHttp( RemoteCameraHttp::RemoteCameraHttp(
@ -140,9 +140,9 @@ void RemoteCameraHttp::Initialise() {
} // end void RemoteCameraHttp::Initialise() } // end void RemoteCameraHttp::Initialise()
int RemoteCameraHttp::Connect() { int RemoteCameraHttp::Connect() {
struct addrinfo *p = NULL; struct addrinfo *p = nullptr;
for ( p = hp; p != NULL; p = p->ai_next ) { for ( p = hp; p != nullptr; p = p->ai_next ) {
sd = socket( p->ai_family, p->ai_socktype, p->ai_protocol ); sd = socket( p->ai_family, p->ai_socktype, p->ai_protocol );
if ( sd < 0 ) { if ( sd < 0 ) {
Warning("Can't create socket: %s", strerror(errno) ); Warning("Can't create socket: %s", strerror(errno) );
@ -165,7 +165,7 @@ int RemoteCameraHttp::Connect() {
break; break;
} }
if ( p == NULL ) { if ( p == nullptr ) {
Error("Unable to connect to the remote camera, aborting"); Error("Unable to connect to the remote camera, aborting");
return -1; return -1;
} }
@ -207,7 +207,7 @@ int RemoteCameraHttp::ReadData( Buffer &buffer, unsigned int bytes_expected ) {
struct timeval temp_timeout = timeout; struct timeval temp_timeout = timeout;
int n_found = select(sd+1, &rfds, NULL, NULL, &temp_timeout); int n_found = select(sd+1, &rfds, nullptr, nullptr, &temp_timeout);
if( n_found == 0 ) { if( n_found == 0 ) {
Debug( 1, "Select timed out timeout was %d secs %d usecs", temp_timeout.tv_sec, temp_timeout.tv_usec ); Debug( 1, "Select timed out timeout was %d secs %d usecs", temp_timeout.tv_sec, temp_timeout.tv_usec );
int error = 0; int error = 0;
@ -293,10 +293,10 @@ int RemoteCameraHttp::ReadData( Buffer &buffer, unsigned int bytes_expected ) {
} }
int RemoteCameraHttp::GetData() { int RemoteCameraHttp::GetData() {
time_t start_time = time(NULL); time_t start_time = time(nullptr);
int buffer_len = 0; int buffer_len = 0;
while ( !( buffer_len = ReadData(buffer) ) ) { while ( !( buffer_len = ReadData(buffer) ) ) {
if ( zm_terminate || ( start_time - time(NULL) < ZM_WATCH_MAX_DELAY )) if ( zm_terminate || ( start_time - time(nullptr) < ZM_WATCH_MAX_DELAY ))
return -1; return -1;
Debug(4, "Timeout waiting for REGEXP HEADER"); Debug(4, "Timeout waiting for REGEXP HEADER");
usleep(100000); usleep(100000);
@ -308,16 +308,16 @@ int RemoteCameraHttp::GetResponse() {
int buffer_len; int buffer_len;
#if HAVE_LIBPCRE #if HAVE_LIBPCRE
if ( method == REGEXP ) { if ( method == REGEXP ) {
const char *header = 0; const char *header = nullptr;
int header_len = 0; int header_len = 0;
const char *http_version = 0; const char *http_version = nullptr;
int status_code = 0; int status_code = 0;
const char *status_mesg = 0; const char *status_mesg = nullptr;
const char *connection_type = ""; const char *connection_type = "";
int content_length = 0; int content_length = 0;
const char *content_type = ""; const char *content_type = "";
const char *content_boundary = ""; const char *content_boundary = "";
const char *subheader = 0; const char *subheader = nullptr;
int subheader_len = 0; int subheader_len = 0;
//int subcontent_length = 0; //int subcontent_length = 0;
//const char *subcontent_type = ""; //const char *subcontent_type = "";
@ -450,9 +450,9 @@ int RemoteCameraHttp::GetResponse() {
} }
case SUBHEADER : case SUBHEADER :
{ {
static RegExpr *subheader_expr = 0; static RegExpr *subheader_expr = nullptr;
static RegExpr *subcontent_length_expr = 0; static RegExpr *subcontent_length_expr = nullptr;
static RegExpr *subcontent_type_expr = 0; static RegExpr *subcontent_type_expr = nullptr;
if ( !subheader_expr ) if ( !subheader_expr )
{ {
@ -641,11 +641,11 @@ int RemoteCameraHttp::GetResponse() {
case HEADER : case HEADER :
{ {
n_headers = 0; n_headers = 0;
http_header = 0; http_header = nullptr;
connection_header = 0; connection_header = nullptr;
content_length_header = 0; content_length_header = nullptr;
content_type_header = 0; content_type_header = nullptr;
authenticate_header = 0; authenticate_header = nullptr;
http_version[0] = '\0'; http_version[0] = '\0';
status_code [0]= '\0'; status_code [0]= '\0';
@ -665,7 +665,7 @@ int RemoteCameraHttp::GetResponse() {
} }
bytes += buffer_len; bytes += buffer_len;
char *crlf = 0; char *crlf = nullptr;
char *header_ptr = (char *)buffer; char *header_ptr = (char *)buffer;
int header_len = buffer.size(); int header_len = buffer.size();
bool all_headers = false; bool all_headers = false;
@ -870,7 +870,7 @@ int RemoteCameraHttp::GetResponse() {
} }
case SUBHEADERCONT : case SUBHEADERCONT :
{ {
char *crlf = 0; char *crlf = nullptr;
char *subheader_ptr = (char *)buffer; char *subheader_ptr = (char *)buffer;
int subheader_len = buffer.size(); int subheader_len = buffer.size();
bool all_headers = false; bool all_headers = false;

View File

@ -64,18 +64,18 @@ RemoteCameraRtsp::RemoteCameraRtsp(
Initialise(); Initialise();
} }
mFormatContext = NULL; mFormatContext = nullptr;
mVideoStreamId = -1; mVideoStreamId = -1;
mAudioStreamId = -1; mAudioStreamId = -1;
mCodecContext = NULL; mCodecContext = nullptr;
mCodec = NULL; mCodec = nullptr;
mRawFrame = NULL; mRawFrame = nullptr;
mFrame = NULL; mFrame = nullptr;
frameCount = 0; frameCount = 0;
startTime=0; startTime=0;
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
mConvertContext = NULL; mConvertContext = nullptr;
#endif #endif
/* Has to be located inside the constructor so other components such as zma will receive correct colours and subpixel order */ /* Has to be located inside the constructor so other components such as zma will receive correct colours and subpixel order */
if ( colours == ZM_COLOUR_RGB32 ) { if ( colours == ZM_COLOUR_RGB32 ) {
@ -99,13 +99,13 @@ RemoteCameraRtsp::~RemoteCameraRtsp() {
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
if ( mConvertContext ) { if ( mConvertContext ) {
sws_freeContext(mConvertContext); sws_freeContext(mConvertContext);
mConvertContext = NULL; mConvertContext = nullptr;
} }
#endif #endif
if ( mCodecContext ) { if ( mCodecContext ) {
avcodec_close(mCodecContext); avcodec_close(mCodecContext);
mCodecContext = NULL; // Freed by avformat_free_context in the destructor of RtspThread class mCodecContext = nullptr; // Freed by avformat_free_context in the destructor of RtspThread class
} }
if ( capture ) { if ( capture ) {
@ -144,7 +144,7 @@ int RemoteCameraRtsp::Disconnect() {
rtspThread->stop(); rtspThread->stop();
rtspThread->join(); rtspThread->join();
delete rtspThread; delete rtspThread;
rtspThread = 0; rtspThread = nullptr;
} }
return 0; return 0;
} }
@ -197,7 +197,7 @@ int RemoteCameraRtsp::PrimeCapture() {
// Find the decoder for the video stream // Find the decoder for the video stream
mCodec = avcodec_find_decoder(mCodecContext->codec_id); mCodec = avcodec_find_decoder(mCodecContext->codec_id);
if ( mCodec == NULL ) if ( mCodec == nullptr )
Panic("Unable to locate codec %d decoder", mCodecContext->codec_id); Panic("Unable to locate codec %d decoder", mCodecContext->codec_id);
// Open codec // Open codec
@ -214,7 +214,7 @@ int RemoteCameraRtsp::PrimeCapture() {
// Allocate space for the converted video frame // Allocate space for the converted video frame
mFrame = zm_av_frame_alloc(); mFrame = zm_av_frame_alloc();
if ( mRawFrame == NULL || mFrame == NULL ) if ( mRawFrame == nullptr || mFrame == nullptr )
Fatal("Unable to allocate frame(s)"); Fatal("Unable to allocate frame(s)");
#if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0) #if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0)
@ -261,7 +261,7 @@ int RemoteCameraRtsp::Capture( Image &image ) {
/* Request a writeable buffer of the target image */ /* Request a writeable buffer of the target image */
directbuffer = image.WriteBuffer(width, height, colours, subpixelorder); directbuffer = image.WriteBuffer(width, height, colours, subpixelorder);
if ( directbuffer == NULL ) { if ( directbuffer == nullptr ) {
Error("Failed requesting writeable buffer for the captured image."); Error("Failed requesting writeable buffer for the captured image.");
return -1; return -1;
} }
@ -343,12 +343,12 @@ int RemoteCameraRtsp::Capture( Image &image ) {
#endif #endif
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
if ( mConvertContext == NULL ) { if ( mConvertContext == nullptr ) {
mConvertContext = sws_getContext( mConvertContext = sws_getContext(
mCodecContext->width, mCodecContext->height, mCodecContext->pix_fmt, mCodecContext->width, mCodecContext->height, mCodecContext->pix_fmt,
width, height, imagePixFormat, SWS_BICUBIC, NULL, NULL, NULL); width, height, imagePixFormat, SWS_BICUBIC, nullptr, nullptr, nullptr);
if ( mConvertContext == NULL ) if ( mConvertContext == nullptr )
Fatal("Unable to create conversion context"); Fatal("Unable to create conversion context");
if ( if (

View File

@ -272,12 +272,12 @@ int RtpCtrlThread::run() {
unsigned char buffer[ZM_NETWORK_BUFSIZ]; unsigned char buffer[ZM_NETWORK_BUFSIZ];
time_t last_receive = time(NULL); time_t last_receive = time(nullptr);
bool timeout = false; // used as a flag that we had a timeout, and then sent an RR to see if we wake back up. Real timeout will happen when this is true. bool timeout = false; // used as a flag that we had a timeout, and then sent an RR to see if we wake back up. Real timeout will happen when this is true.
while ( !mStop && select.wait() >= 0 ) { while ( !mStop && select.wait() >= 0 ) {
time_t now = time(NULL); time_t now = time(nullptr);
Select::CommsList readable = select.getReadable(); Select::CommsList readable = select.getReadable();
if ( readable.size() == 0 ) { if ( readable.size() == 0 ) {
if ( ! timeout ) { if ( ! timeout ) {
@ -300,7 +300,7 @@ int RtpCtrlThread::run() {
} }
} else { } else {
timeout = false; timeout = false;
last_receive = time(NULL); last_receive = time(nullptr);
} }
for ( Select::CommsList::iterator iter = readable.begin(); iter != readable.end(); ++iter ) { for ( Select::CommsList::iterator iter = readable.begin(); iter != readable.end(); ++iter ) {
if ( UdpInetSocket *socket = dynamic_cast<UdpInetSocket *>(*iter) ) { if ( UdpInetSocket *socket = dynamic_cast<UdpInetSocket *>(*iter) ) {

View File

@ -198,14 +198,14 @@ RtspThread::~RtspThread() {
#else #else
av_free_format_context(mFormatContext); av_free_format_context(mFormatContext);
#endif #endif
mFormatContext = NULL; mFormatContext = nullptr;
} }
if ( mSessDesc ) { if ( mSessDesc ) {
delete mSessDesc; delete mSessDesc;
mSessDesc = NULL; mSessDesc = nullptr;
} }
delete mAuthenticator; delete mAuthenticator;
mAuthenticator = NULL; mAuthenticator = nullptr;
} }
int RtspThread::run() { int RtspThread::run() {
@ -387,7 +387,7 @@ int RtspThread::run() {
if ( !mAuth.empty() ) if ( !mAuth.empty() )
authUrl.insert( authUrl.find( "://" )+3, mAuth+"@" ); authUrl.insert( authUrl.find( "://" )+3, mAuth+"@" );
if ( av_open_input_file( &mFormatContext, authUrl.c_str(), NULL, 0, NULL ) != 0 ) if ( av_open_input_file( &mFormatContext, authUrl.c_str(), nullptr, 0, nullptr ) != 0 )
{ {
Error( "Unable to open input '%s'", authUrl.c_str() ); Error( "Unable to open input '%s'", authUrl.c_str() );
return( -1 ); return( -1 );
@ -499,26 +499,26 @@ int RtspThread::run() {
method = "RTP/UNICAST"; method = "RTP/UNICAST";
StringVector subparts = split( parts[i], "=" ); StringVector subparts = split( parts[i], "=" );
StringVector ports = split( subparts[1], "-" ); StringVector ports = split( subparts[1], "-" );
remotePorts[0] = strtol( ports[0].c_str(), NULL, 10 ); remotePorts[0] = strtol( ports[0].c_str(), nullptr, 10 );
remotePorts[1] = strtol( ports[1].c_str(), NULL, 10 ); remotePorts[1] = strtol( ports[1].c_str(), nullptr, 10 );
} else if ( startsWith( parts[i], "interleaved=" ) ) { } else if ( startsWith( parts[i], "interleaved=" ) ) {
method = "RTP/RTSP"; method = "RTP/RTSP";
StringVector subparts = split( parts[i], "=" ); StringVector subparts = split( parts[i], "=" );
StringVector channels = split( subparts[1], "-" ); StringVector channels = split( subparts[1], "-" );
remoteChannels[0] = strtol( channels[0].c_str(), NULL, 10 ); remoteChannels[0] = strtol( channels[0].c_str(), nullptr, 10 );
remoteChannels[1] = strtol( channels[1].c_str(), NULL, 10 ); remoteChannels[1] = strtol( channels[1].c_str(), nullptr, 10 );
} else if ( startsWith( parts[i], "port=" ) ) { } else if ( startsWith( parts[i], "port=" ) ) {
method = "RTP/MULTICAST"; method = "RTP/MULTICAST";
StringVector subparts = split( parts[i], "=" ); StringVector subparts = split( parts[i], "=" );
StringVector ports = split( subparts[1], "-" ); StringVector ports = split( subparts[1], "-" );
localPorts[0] = strtol( ports[0].c_str(), NULL, 10 ); localPorts[0] = strtol( ports[0].c_str(), nullptr, 10 );
localPorts[1] = strtol( ports[1].c_str(), NULL, 10 ); localPorts[1] = strtol( ports[1].c_str(), nullptr, 10 );
} else if ( startsWith( parts[i], "destination=" ) ) { } else if ( startsWith( parts[i], "destination=" ) ) {
StringVector subparts = split( parts[i], "=" ); StringVector subparts = split( parts[i], "=" );
localHost = subparts[1]; localHost = subparts[1];
} else if ( startsWith( parts[i], "ssrc=" ) ) { } else if ( startsWith( parts[i], "ssrc=" ) ) {
StringVector subparts = split( parts[i], "=" ); StringVector subparts = split( parts[i], "=" );
ssrc = strtoll( subparts[1].c_str(), NULL, 16 ); ssrc = strtoll( subparts[1].c_str(), nullptr, 16 );
} }
} }
@ -568,10 +568,10 @@ int RtspThread::run() {
for ( size_t j = 0; j < parts.size(); j++ ) { for ( size_t j = 0; j < parts.size(); j++ ) {
if ( startsWith( parts[j], "seq=" ) ) { if ( startsWith( parts[j], "seq=" ) ) {
StringVector subparts = split( parts[j], "=" ); StringVector subparts = split( parts[j], "=" );
seq = strtol( subparts[1].c_str(), NULL, 10 ); seq = strtol( subparts[1].c_str(), nullptr, 10 );
} else if ( startsWith( parts[j], "rtptime=" ) ) { } else if ( startsWith( parts[j], "rtptime=" ) ) {
StringVector subparts = split( parts[j], "=" ); StringVector subparts = split( parts[j], "=" );
rtpTime = strtol( subparts[1].c_str(), NULL, 10 ); rtpTime = strtol( subparts[1].c_str(), nullptr, 10 );
} }
} }
break; break;
@ -582,7 +582,7 @@ int RtspThread::run() {
Debug( 2, "RTSP Seq is %d", seq ); Debug( 2, "RTSP Seq is %d", seq );
Debug( 2, "RTSP Rtptime is %ld", rtpTime ); Debug( 2, "RTSP Rtptime is %ld", rtpTime );
time_t lastKeepalive = time(NULL); time_t lastKeepalive = time(nullptr);
time_t now; time_t now;
message = "GET_PARAMETER "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n"; message = "GET_PARAMETER "+mUrl+" RTSP/1.0\r\nSession: "+session+"\r\n";
@ -598,7 +598,7 @@ int RtspThread::run() {
rtpCtrlThread.start(); rtpCtrlThread.start();
while( !mStop ) { while( !mStop ) {
now = time(NULL); now = time(nullptr);
// Send a keepalive message if the server supports this feature and we are close to the timeout expiration // Send a keepalive message if the server supports this feature and we are close to the timeout expiration
Debug(5, "sendkeepalive %d, timeout %d, now: %d last: %d since: %d", Debug(5, "sendkeepalive %d, timeout %d, now: %d last: %d since: %d",
sendKeepalive, timeout, now, lastKeepalive, (now-lastKeepalive) ); sendKeepalive, timeout, now, lastKeepalive, (now-lastKeepalive) );
@ -721,7 +721,7 @@ int RtspThread::run() {
} }
// Send a keepalive message if the server supports this feature and we are close to the timeout expiration // Send a keepalive message if the server supports this feature and we are close to the timeout expiration
// FIXME: Is this really necessary when using tcp ? // FIXME: Is this really necessary when using tcp ?
now = time(NULL); now = time(nullptr);
// Send a keepalive message if the server supports this feature and we are close to the timeout expiration // Send a keepalive message if the server supports this feature and we are close to the timeout expiration
Debug(5, "sendkeepalive %d, timeout %d, now: %d last: %d since: %d", sendKeepalive, timeout, now, lastKeepalive, (now-lastKeepalive) ); Debug(5, "sendkeepalive %d, timeout %d, now: %d last: %d since: %d", sendKeepalive, timeout, now, lastKeepalive, (now-lastKeepalive) );
if ( sendKeepalive && (timeout > 0) && ((now-lastKeepalive) > (timeout-5)) ) if ( sendKeepalive && (timeout > 0) && ((now-lastKeepalive) > (timeout-5)) )
@ -761,10 +761,10 @@ Debug(5, "sendkeepalive %d, timeout %d, now: %d last: %d since: %d", sendKeepali
while ( !mStop ) { while ( !mStop ) {
// Send a keepalive message if the server supports this feature and we are close to the timeout expiration // Send a keepalive message if the server supports this feature and we are close to the timeout expiration
if ( sendKeepalive && (timeout > 0) && ((time(NULL)-lastKeepalive) > (timeout-5)) ) { if ( sendKeepalive && (timeout > 0) && ((time(nullptr)-lastKeepalive) > (timeout-5)) ) {
if ( !sendCommand( message ) ) if ( !sendCommand( message ) )
return -1; return -1;
lastKeepalive = time(NULL); lastKeepalive = time(nullptr);
} }
usleep(100000); usleep(100000);
} }

View File

@ -152,16 +152,16 @@ SessionDescriptor::MediaDescriptor::MediaDescriptor(
mWidth( 0 ), mWidth( 0 ),
mHeight( 0 ), mHeight( 0 ),
mSprops( "" ), mSprops( "" ),
mConnInfo( 0 ) mConnInfo( nullptr )
{ {
} }
SessionDescriptor::SessionDescriptor( const std::string &url, const std::string &sdp ) : SessionDescriptor::SessionDescriptor( const std::string &url, const std::string &sdp ) :
mUrl( url ), mUrl( url ),
mConnInfo( 0 ), mConnInfo( nullptr ),
mBandInfo( 0 ) mBandInfo( nullptr )
{ {
MediaDescriptor *currMedia = 0; MediaDescriptor *currMedia = nullptr;
StringVector lines = split( sdp, "\r\n" ); StringVector lines = split( sdp, "\r\n" );
for ( StringVector::const_iterator iter = lines.begin(); iter != lines.end(); ++iter ) { for ( StringVector::const_iterator iter = lines.begin(); iter != lines.end(); ++iter ) {
@ -344,12 +344,12 @@ AVFormatContext *SessionDescriptor::generateFormatContext() const {
#if !LIBAVFORMAT_VERSION_CHECK(53, 10, 0, 17, 0) #if !LIBAVFORMAT_VERSION_CHECK(53, 10, 0, 17, 0)
AVStream *stream = av_new_stream(formatContext, i); AVStream *stream = av_new_stream(formatContext, i);
#else #else
AVStream *stream = avformat_new_stream(formatContext, NULL); AVStream *stream = avformat_new_stream(formatContext, nullptr);
stream->id = i; stream->id = i;
#endif #endif
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
AVCodecContext *codec_context = avcodec_alloc_context3(NULL); AVCodecContext *codec_context = avcodec_alloc_context3(nullptr);
avcodec_parameters_to_context(codec_context, stream->codecpar); avcodec_parameters_to_context(codec_context, stream->codecpar);
stream->codec = codec_context; stream->codec = codec_context;
#else #else
@ -434,7 +434,7 @@ AVFormatContext *SessionDescriptor::generateFormatContext() const {
if ( codec_context->codec_id == AV_CODEC_ID_H264 && mediaDesc->getSprops().size()) { if ( codec_context->codec_id == AV_CODEC_ID_H264 && mediaDesc->getSprops().size()) {
uint8_t start_sequence[]= { 0, 0, 1 }; uint8_t start_sequence[]= { 0, 0, 1 };
codec_context->extradata_size= 0; codec_context->extradata_size= 0;
codec_context->extradata= NULL; codec_context->extradata= nullptr;
char pvalue[1024], *value = pvalue; char pvalue[1024], *value = pvalue;
strcpy(pvalue, mediaDesc->getSprops().c_str()); strcpy(pvalue, mediaDesc->getSprops().c_str());

View File

@ -211,7 +211,7 @@ public:
MediaDescriptor *getStream( int index ) MediaDescriptor *getStream( int index )
{ {
if ( index < 0 || (unsigned int)index >= mMediaList.size() ) if ( index < 0 || (unsigned int)index >= mMediaList.size() )
return( 0 ); return nullptr;
return( mMediaList[index] ); return( mMediaList[index] );
} }

View File

@ -22,7 +22,7 @@ int zm_sendfile(int out_fd, int in_fd, off_t *offset, size_t size) {
#include <sys/uio.h> #include <sys/uio.h>
int zm_sendfile(int out_fd, int in_fd, off_t *offset, off_t size) { int zm_sendfile(int out_fd, int in_fd, off_t *offset, off_t size) {
int err; int err;
err = sendfile(in_fd, out_fd, *offset, size, NULL, &size, 0); err = sendfile(in_fd, out_fd, *offset, size, nullptr, &size, 0);
if (err && errno != EAGAIN) if (err && errno != EAGAIN)
return -errno; return -errno;

View File

@ -53,8 +53,8 @@ RETSIGTYPE zm_die_handler(int signal)
#if (defined(__i386__) || defined(__x86_64__)) #if (defined(__i386__) || defined(__x86_64__))
// Get more information if available // Get more information if available
#if ( HAVE_SIGINFO_T && HAVE_UCONTEXT_T ) #if ( HAVE_SIGINFO_T && HAVE_UCONTEXT_T )
void *ip = 0; void *ip = nullptr;
void *cr2 = 0; void *cr2 = nullptr;
if (info && context) { if (info && context) {
Debug(1, Debug(1,

View File

@ -33,7 +33,7 @@ StreamBase::~StreamBase() {
#if HAVE_LIBAVCODEC #if HAVE_LIBAVCODEC
if ( vid_stream ) { if ( vid_stream ) {
delete vid_stream; delete vid_stream;
vid_stream = NULL; vid_stream = nullptr;
} }
#endif #endif
closeComms(); closeComms();
@ -351,7 +351,7 @@ void StreamBase::openComms() {
strncpy(rem_addr.sun_path, rem_sock_path, sizeof(rem_addr.sun_path)); strncpy(rem_addr.sun_path, rem_sock_path, sizeof(rem_addr.sun_path));
rem_addr.sun_family = AF_UNIX; rem_addr.sun_family = AF_UNIX;
gettimeofday(&last_comm_update, NULL); gettimeofday(&last_comm_update, nullptr);
} // end if connKey > 0 } // end if connKey > 0
Debug(3, "comms open at %s", loc_sock_path); Debug(3, "comms open at %s", loc_sock_path);
} // end void StreamBase::openComms() } // end void StreamBase::openComms()

View File

@ -24,7 +24,7 @@
#include "zm_swscale.h" #include "zm_swscale.h"
#if HAVE_LIBSWSCALE && HAVE_LIBAVUTIL #if HAVE_LIBSWSCALE && HAVE_LIBAVUTIL
SWScale::SWScale() : gotdefaults(false), swscale_ctx(NULL), input_avframe(NULL), output_avframe(NULL) { SWScale::SWScale() : gotdefaults(false), swscale_ctx(nullptr), input_avframe(nullptr), output_avframe(nullptr) {
Debug(4,"SWScale object created"); Debug(4,"SWScale object created");
} }
@ -36,7 +36,7 @@ bool SWScale::init() {
#else #else
input_avframe = avcodec_alloc_frame(); input_avframe = avcodec_alloc_frame();
#endif #endif
if ( input_avframe == NULL ) { if ( input_avframe == nullptr ) {
Error("Failed allocating AVFrame for the input"); Error("Failed allocating AVFrame for the input");
return false; return false;
} }
@ -47,7 +47,7 @@ bool SWScale::init() {
#else #else
output_avframe = avcodec_alloc_frame(); output_avframe = avcodec_alloc_frame();
#endif #endif
if ( output_avframe == NULL ) { if ( output_avframe == nullptr ) {
Error("Failed allocating AVFrame for the output"); Error("Failed allocating AVFrame for the output");
return false; return false;
} }
@ -65,7 +65,7 @@ SWScale::~SWScale() {
if ( swscale_ctx ) { if ( swscale_ctx ) {
sws_freeContext(swscale_ctx); sws_freeContext(swscale_ctx);
swscale_ctx = NULL; swscale_ctx = nullptr;
} }
Debug(4,"SWScale object destroyed"); Debug(4,"SWScale object destroyed");
@ -86,7 +86,7 @@ int SWScale::SetDefaults(enum _AVPIXELFORMAT in_pf, enum _AVPIXELFORMAT out_pf,
int SWScale::Convert(const uint8_t* in_buffer, const size_t in_buffer_size, uint8_t* out_buffer, const size_t out_buffer_size, enum _AVPIXELFORMAT in_pf, enum _AVPIXELFORMAT out_pf, unsigned int width, unsigned int height, unsigned int new_width, unsigned int new_height) { int SWScale::Convert(const uint8_t* in_buffer, const size_t in_buffer_size, uint8_t* out_buffer, const size_t out_buffer_size, enum _AVPIXELFORMAT in_pf, enum _AVPIXELFORMAT out_pf, unsigned int width, unsigned int height, unsigned int new_width, unsigned int new_height) {
/* Parameter checking */ /* Parameter checking */
if(in_buffer == NULL || out_buffer == NULL) { if(in_buffer == nullptr || out_buffer == nullptr) {
Error("NULL Input or output buffer"); Error("NULL Input or output buffer");
return -1; return -1;
} }
@ -131,8 +131,8 @@ int SWScale::Convert(const uint8_t* in_buffer, const size_t in_buffer_size, uint
} }
/* Get the context */ /* Get the context */
swscale_ctx = sws_getCachedContext( swscale_ctx, width, height, in_pf, new_width, new_height, out_pf, SWS_FAST_BILINEAR, NULL, NULL, NULL ); swscale_ctx = sws_getCachedContext( swscale_ctx, width, height, in_pf, new_width, new_height, out_pf, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr );
if(swscale_ctx == NULL) { if(swscale_ctx == nullptr) {
Error("Failed getting swscale context"); Error("Failed getting swscale context");
return -6; return -6;
} }

View File

@ -30,7 +30,7 @@
struct timespec getTimeout( int secs ) { struct timespec getTimeout( int secs ) {
struct timespec timeout; struct timespec timeout;
struct timeval temp_timeout; struct timeval temp_timeout;
gettimeofday(&temp_timeout, 0); gettimeofday(&temp_timeout, nullptr);
timeout.tv_sec = temp_timeout.tv_sec + secs; timeout.tv_sec = temp_timeout.tv_sec + secs;
timeout.tv_nsec = temp_timeout.tv_usec*1000; timeout.tv_nsec = temp_timeout.tv_usec*1000;
return timeout; return timeout;
@ -39,7 +39,7 @@ struct timespec getTimeout( int secs ) {
struct timespec getTimeout( double secs ) { struct timespec getTimeout( double secs ) {
struct timespec timeout; struct timespec timeout;
struct timeval temp_timeout; struct timeval temp_timeout;
gettimeofday( &temp_timeout, 0 ); gettimeofday( &temp_timeout, nullptr );
timeout.tv_sec = temp_timeout.tv_sec + int(secs); timeout.tv_sec = temp_timeout.tv_sec + int(secs);
timeout.tv_nsec = temp_timeout.tv_usec += (long int)(1000000000.0*(secs-int(secs))); timeout.tv_nsec = temp_timeout.tv_usec += (long int)(1000000000.0*(secs-int(secs)));
if ( timeout.tv_nsec > 1000000000 ) { if ( timeout.tv_nsec > 1000000000 ) {
@ -50,7 +50,7 @@ struct timespec getTimeout( double secs ) {
} }
Mutex::Mutex() { Mutex::Mutex() {
if ( pthread_mutex_init(&mMutex, NULL) < 0 ) if ( pthread_mutex_init(&mMutex, nullptr) < 0 )
Error("Unable to create pthread mutex: %s", strerror(errno)); Error("Unable to create pthread mutex: %s", strerror(errno));
} }
@ -105,7 +105,7 @@ RecursiveMutex::RecursiveMutex() {
} }
Condition::Condition( Mutex &mutex ) : mMutex( mutex ) { Condition::Condition( Mutex &mutex ) : mMutex( mutex ) {
if ( pthread_cond_init( &mCondition, NULL ) < 0 ) if ( pthread_cond_init( &mCondition, nullptr ) < 0 )
throw ThreadException( stringtf( "Unable to create pthread condition: %s", strerror(errno) ) ); throw ThreadException( stringtf( "Unable to create pthread condition: %s", strerror(errno) ) );
} }

View File

@ -86,7 +86,7 @@ inline int tvDiffUsec( struct timeval first, struct timeval last )
inline int tvDiffUsec( struct timeval first ) inline int tvDiffUsec( struct timeval first )
{ {
struct timeval now; struct timeval now;
gettimeofday( &now, NULL ); gettimeofday( &now, nullptr );
return( tvDiffUsec( first, now ) ); return( tvDiffUsec( first, now ) );
} }
@ -98,7 +98,7 @@ inline int tvDiffMsec( struct timeval first, struct timeval last )
inline int tvDiffMsec( struct timeval first ) inline int tvDiffMsec( struct timeval first )
{ {
struct timeval now; struct timeval now;
gettimeofday( &now, NULL ); gettimeofday( &now, nullptr );
return( tvDiffMsec( first, now ) ); return( tvDiffMsec( first, now ) );
} }
@ -110,7 +110,7 @@ inline double tvDiffSec( struct timeval first, struct timeval last )
inline double tvDiffSec( struct timeval first ) inline double tvDiffSec( struct timeval first )
{ {
struct timeval now; struct timeval now;
gettimeofday( &now, NULL ); gettimeofday( &now, nullptr );
return( tvDiffSec( first, now ) ); return( tvDiffSec( first, now ) );
} }
@ -146,7 +146,7 @@ inline int tvEq( struct timeval t1, struct timeval t2 )
inline struct timeval tvNow( void ) inline struct timeval tvNow( void )
{ {
struct timeval t; struct timeval t;
gettimeofday( &t, NULL ); gettimeofday( &t, nullptr );
return( t ); return( t );
} }

View File

@ -116,7 +116,7 @@ User *zmLoadUser(const char *username, const char *password) {
" FROM `Users` WHERE `Username` = '%s' AND `Enabled` = 1", " FROM `Users` WHERE `Username` = '%s' AND `Enabled` = 1",
safer_username); safer_username);
delete[] safer_username; delete[] safer_username;
safer_username = NULL; safer_username = nullptr;
if ( mysql_query(&dbconn, sql) ) { if ( mysql_query(&dbconn, sql) ) {
Error("Can't run query: %s", mysql_error(&dbconn)); Error("Can't run query: %s", mysql_error(&dbconn));
@ -145,7 +145,7 @@ User *zmLoadUser(const char *username, const char *password) {
mysql_free_result(result); mysql_free_result(result);
Warning("Unable to authenticate user %s", username); Warning("Unable to authenticate user %s", username);
return NULL; return nullptr;
} // end User *zmLoadUser(const char *username, const char *password) } // end User *zmLoadUser(const char *username, const char *password)
User *zmLoadTokenUser(std::string jwt_token_str, bool use_remote_addr) { User *zmLoadTokenUser(std::string jwt_token_str, bool use_remote_addr) {
@ -169,7 +169,7 @@ User *zmLoadTokenUser(std::string jwt_token_str, bool use_remote_addr) {
Debug(1, "retrieved user '%s' from token", username.c_str()); Debug(1, "retrieved user '%s' from token", username.c_str());
if ( username == "" ) { if ( username == "" ) {
return NULL; return nullptr;
} }
char sql[ZM_SQL_MED_BUFSIZ] = ""; char sql[ZM_SQL_MED_BUFSIZ] = "";
@ -180,30 +180,30 @@ User *zmLoadTokenUser(std::string jwt_token_str, bool use_remote_addr) {
if ( mysql_query(&dbconn, sql) ) { if ( mysql_query(&dbconn, sql) ) {
Error("Can't run query: %s", mysql_error(&dbconn)); Error("Can't run query: %s", mysql_error(&dbconn));
return NULL; return nullptr;
} }
MYSQL_RES *result = mysql_store_result(&dbconn); MYSQL_RES *result = mysql_store_result(&dbconn);
if ( !result ) { if ( !result ) {
Error("Can't use query result: %s", mysql_error(&dbconn)); Error("Can't use query result: %s", mysql_error(&dbconn));
return NULL; return nullptr;
} }
int n_users = mysql_num_rows(result); int n_users = mysql_num_rows(result);
if ( n_users != 1 ) { if ( n_users != 1 ) {
mysql_free_result(result); mysql_free_result(result);
Error("Unable to authenticate user '%s'", username.c_str()); Error("Unable to authenticate user '%s'", username.c_str());
return NULL; return nullptr;
} }
MYSQL_ROW dbrow = mysql_fetch_row(result); MYSQL_ROW dbrow = mysql_fetch_row(result);
User *user = new User(dbrow); User *user = new User(dbrow);
unsigned int stored_iat = strtoul(dbrow[10], NULL, 0); unsigned int stored_iat = strtoul(dbrow[10], nullptr, 0);
if ( stored_iat > iat ) { // admin revoked tokens if ( stored_iat > iat ) { // admin revoked tokens
mysql_free_result(result); mysql_free_result(result);
Error("Token was revoked for '%s'", username.c_str()); Error("Token was revoked for '%s'", username.c_str());
return NULL; return nullptr;
} }
Debug(1, "Authenticated user '%s' via token with last revoke time: %u", Debug(1, "Authenticated user '%s' via token with last revoke time: %u",
@ -248,16 +248,16 @@ User *zmLoadAuthUser(const char *auth, bool use_remote_addr) {
MYSQL_RES *result = mysql_store_result(&dbconn); MYSQL_RES *result = mysql_store_result(&dbconn);
if ( !result ) { if ( !result ) {
Error("Can't use query result: %s", mysql_error(&dbconn)); Error("Can't use query result: %s", mysql_error(&dbconn));
return NULL; return nullptr;
} }
int n_users = mysql_num_rows(result); int n_users = mysql_num_rows(result);
if ( n_users < 1 ) { if ( n_users < 1 ) {
mysql_free_result(result); mysql_free_result(result);
Warning("Unable to authenticate user"); Warning("Unable to authenticate user");
return NULL; return nullptr;
} }
time_t now = time(0); time_t now = time(nullptr);
unsigned int hours = config.auth_hash_ttl; unsigned int hours = config.auth_hash_ttl;
if ( ! hours ) { if ( ! hours ) {
Warning("No value set for ZM_AUTH_HASH_TTL. Defaulting to 2."); Warning("No value set for ZM_AUTH_HASH_TTL. Defaulting to 2.");
@ -323,7 +323,7 @@ User *zmLoadAuthUser(const char *auth, bool use_remote_addr) {
Error("You need to build with gnutls or openssl to use hash based auth"); Error("You need to build with gnutls or openssl to use hash based auth");
#endif // HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT #endif // HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT
Debug(1, "No user found for auth_key %s", auth); Debug(1, "No user found for auth_key %s", auth);
return NULL; return nullptr;
} // end User *zmLoadAuthUser( const char *auth, bool use_remote_addr ) } // end User *zmLoadAuthUser( const char *auth, bool use_remote_addr )
// Function to check Username length // Function to check Username length

View File

@ -185,7 +185,7 @@ const std::string base64Encode(const std::string &inString) {
} }
int split(const char* string, const char delim, std::vector<std::string>& items) { int split(const char* string, const char delim, std::vector<std::string>& items) {
if ( string == NULL ) if ( string == nullptr )
return -1; return -1;
if ( string[0] == 0 ) if ( string[0] == 0 )
@ -206,7 +206,7 @@ int split(const char* string, const char delim, std::vector<std::string>& items)
} }
int pairsplit(const char* string, const char delim, std::string& name, std::string& value) { int pairsplit(const char* string, const char delim, std::string& name, std::string& value) {
if ( string == NULL ) if ( string == nullptr )
return -1; return -1;
if ( string[0] == 0 ) if ( string[0] == 0 )

View File

@ -57,7 +57,7 @@ int VideoWriter::Reset(const char* new_path) {
/* Common variables reset */ /* Common variables reset */
/* If there is a new path, use it */ /* If there is a new path, use it */
if ( new_path != NULL ) { if ( new_path != nullptr ) {
path = new_path; path = new_path;
} }
@ -116,7 +116,7 @@ X264MP4Writer::X264MP4Writer(
} }
/* If supplied with user parameters to the encoder, copy them */ /* If supplied with user parameters to the encoder, copy them */
if ( p_user_params != NULL ) { if ( p_user_params != nullptr ) {
user_params = *p_user_params; user_params = *p_user_params;
} }
@ -144,7 +144,7 @@ X264MP4Writer::~X264MP4Writer() {
int X264MP4Writer::Open() { int X264MP4Writer::Open() {
/* Open the encoder */ /* Open the encoder */
x264enc = x264_encoder_open(&x264params); x264enc = x264_encoder_open(&x264params);
if ( x264enc == NULL ) { if ( x264enc == nullptr ) {
Error("Failed opening x264 encoder"); Error("Failed opening x264 encoder");
return -1; return -1;
} }
@ -269,7 +269,7 @@ int X264MP4Writer::Encode(
const size_t data_size, const size_t data_size,
const unsigned int frame_time) { const unsigned int frame_time) {
/* Parameter checking */ /* Parameter checking */
if ( data == NULL ) { if ( data == nullptr ) {
Error("NULL buffer"); Error("NULL buffer");
return -1; return -1;
} }
@ -418,7 +418,7 @@ int X264MP4Writer::x264encodeloop(bool bFlush) {
int frame_size; int frame_size;
if ( bFlush ) { if ( bFlush ) {
frame_size = x264_encoder_encode(x264enc, &nals, &i_nals, NULL, &x264picout); frame_size = x264_encoder_encode(x264enc, &nals, &i_nals, nullptr, &x264picout);
} else { } else {
frame_size = x264_encoder_encode(x264enc, &nals, &i_nals, &x264picin, &x264picout); frame_size = x264_encoder_encode(x264enc, &nals, &i_nals, &x264picin, &x264picout);
} }
@ -515,12 +515,12 @@ int ParseEncoderParameters(
const char* str, const char* str,
std::vector<EncoderParameter_t>* vec std::vector<EncoderParameter_t>* vec
) { ) {
if ( vec == NULL ) { if ( vec == nullptr ) {
Error("NULL Encoder parameters vector pointer"); Error("NULL Encoder parameters vector pointer");
return -1; return -1;
} }
if ( str == NULL ) { if ( str == nullptr ) {
Error("NULL Encoder parameters string"); Error("NULL Encoder parameters string");
return -2; return -2;
} }

View File

@ -81,7 +81,7 @@ public:
virtual int Encode(const Image* img, const unsigned int frame_time) = 0; virtual int Encode(const Image* img, const unsigned int frame_time) = 0;
virtual int Open() = 0; virtual int Open() = 0;
virtual int Close() = 0; virtual int Close() = 0;
virtual int Reset(const char* new_path = NULL); virtual int Reset(const char* new_path = nullptr);
const char* GetContainer() const { const char* GetContainer() const {
return container.c_str(); return container.c_str();
@ -160,13 +160,13 @@ protected:
public: public:
X264MP4Writer(const char* p_path, const unsigned int p_width, const unsigned int p_height, const unsigned int p_colours, const unsigned int p_subpixelorder, const std::vector<EncoderParameter_t>* p_user_params = NULL); X264MP4Writer(const char* p_path, const unsigned int p_width, const unsigned int p_height, const unsigned int p_colours, const unsigned int p_subpixelorder, const std::vector<EncoderParameter_t>* p_user_params = nullptr);
~X264MP4Writer(); ~X264MP4Writer();
int Encode(const uint8_t* data, const size_t data_size, const unsigned int frame_time); int Encode(const uint8_t* data, const size_t data_size, const unsigned int frame_time);
int Encode(const Image* img, const unsigned int frame_time); int Encode(const Image* img, const unsigned int frame_time);
int Open(); int Open();
int Close(); int Close();
int Reset(const char* new_path = NULL); int Reset(const char* new_path = nullptr);
}; };
#endif // HAVE_LIBX264 && HAVE_LIBMP4V2 && HAVE_LIBAVUTIL && HAVE_LIBSWSCALE #endif // HAVE_LIBX264 && HAVE_LIBMP4V2 && HAVE_LIBAVUTIL && HAVE_LIBSWSCALE

View File

@ -62,7 +62,7 @@ VideoStore::VideoStore(
Info("Opening video storage stream %s format: %s", filename, format); Info("Opening video storage stream %s format: %s", filename, format);
int ret = avformat_alloc_output_context2(&oc, NULL, NULL, filename); int ret = avformat_alloc_output_context2(&oc, nullptr, nullptr, filename);
if ( ret < 0 ) { if ( ret < 0 ) {
Warning( Warning(
"Could not create video storage stream %s as no out ctx" "Could not create video storage stream %s as no out ctx"
@ -74,7 +74,7 @@ VideoStore::VideoStore(
// Couldn't deduce format from filename, trying from format name // Couldn't deduce format from filename, trying from format name
if ( !oc ) { if ( !oc ) {
avformat_alloc_output_context2(&oc, NULL, format, filename); avformat_alloc_output_context2(&oc, nullptr, format, filename);
if ( !oc ) { if ( !oc ) {
Error( Error(
"Could not create video storage stream %s as no out ctx" "Could not create video storage stream %s as no out ctx"
@ -86,7 +86,7 @@ VideoStore::VideoStore(
} }
} // end if ! oc } // end if ! oc
AVDictionary *pmetadata = NULL; AVDictionary *pmetadata = nullptr;
int dsr = int dsr =
av_dict_set(&pmetadata, "title", "Zoneminder Security Recording", 0); av_dict_set(&pmetadata, "title", "Zoneminder Security Recording", 0);
if ( dsr < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__); if ( dsr < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__);
@ -104,7 +104,7 @@ VideoStore::VideoStore(
#endif #endif
} }
video_out_stream = avformat_new_stream(oc, NULL); video_out_stream = avformat_new_stream(oc, nullptr);
if ( !video_out_stream ) { if ( !video_out_stream ) {
Error("Unable to create video out stream"); Error("Unable to create video out stream");
return; return;
@ -231,11 +231,11 @@ VideoStore::VideoStore(
video_out_codec->name, video_out_codec->name,
av_make_error_string(ret).c_str() av_make_error_string(ret).c_str()
); );
video_out_codec = NULL; video_out_codec = nullptr;
} }
AVDictionaryEntry *e = NULL; AVDictionaryEntry *e = nullptr;
while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) { while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr ) {
Warning("Encoder Option %s not recognized by ffmpeg codec", e->key); Warning("Encoder Option %s not recognized by ffmpeg codec", e->key);
} }
ret = avcodec_parameters_from_context(video_out_stream->codecpar, video_out_ctx); ret = avcodec_parameters_from_context(video_out_stream->codecpar, video_out_ctx);
@ -275,16 +275,16 @@ VideoStore::VideoStore(
} }
} }
converted_in_samples = NULL; converted_in_samples = nullptr;
audio_out_codec = NULL; audio_out_codec = nullptr;
audio_in_codec = NULL; audio_in_codec = nullptr;
audio_in_ctx = NULL; audio_in_ctx = nullptr;
audio_out_stream = NULL; audio_out_stream = nullptr;
in_frame = NULL; in_frame = nullptr;
out_frame = NULL; out_frame = nullptr;
#if defined(HAVE_LIBSWRESAMPLE) || defined(HAVE_LIBAVRESAMPLE) #if defined(HAVE_LIBSWRESAMPLE) || defined(HAVE_LIBAVRESAMPLE)
resample_ctx = NULL; resample_ctx = nullptr;
fifo = NULL; fifo = nullptr;
#endif #endif
video_first_pts = 0; video_first_pts = 0;
video_first_dts = 0; video_first_dts = 0;
@ -310,11 +310,11 @@ VideoStore::VideoStore(
} }
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
audio_out_stream = avformat_new_stream(oc, NULL); audio_out_stream = avformat_new_stream(oc, nullptr);
audio_out_ctx = avcodec_alloc_context3(audio_out_codec); audio_out_ctx = avcodec_alloc_context3(audio_out_codec);
if ( !audio_out_ctx ) { if ( !audio_out_ctx ) {
Error("could not allocate codec ctx for AAC"); Error("could not allocate codec ctx for AAC");
audio_out_stream = NULL; audio_out_stream = nullptr;
return; return;
} }
#else #else
@ -329,7 +329,7 @@ VideoStore::VideoStore(
} else { } else {
Debug(2, "Got AAC"); Debug(2, "Got AAC");
audio_out_stream = avformat_new_stream(oc, NULL); audio_out_stream = avformat_new_stream(oc, nullptr);
if ( !audio_out_stream ) { if ( !audio_out_stream ) {
Error("Could not allocate new stream"); Error("Could not allocate new stream");
return; return;
@ -366,7 +366,7 @@ VideoStore::VideoStore(
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Unable to copy audio ctx %s", Error("Unable to copy audio ctx %s",
av_make_error_string(ret).c_str()); av_make_error_string(ret).c_str());
audio_out_stream = NULL; audio_out_stream = nullptr;
return; return;
} // end if } // end if
audio_out_ctx->codec_tag = 0; audio_out_ctx->codec_tag = 0;
@ -403,7 +403,7 @@ bool VideoStore::open() {
int ret; int ret;
/* open the out file, if needed */ /* open the out file, if needed */
if ( !(out_format->flags & AVFMT_NOFILE) ) { if ( !(out_format->flags & AVFMT_NOFILE) ) {
ret = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE, NULL, NULL); ret = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE, nullptr, nullptr);
if ( ret < 0 ) { if ( ret < 0 ) {
Error("Could not open out file '%s': %s", filename, Error("Could not open out file '%s': %s", filename,
av_make_error_string(ret).c_str()); av_make_error_string(ret).c_str());
@ -414,7 +414,7 @@ bool VideoStore::open() {
zm_dump_stream_format(oc, 0, 0, 1); zm_dump_stream_format(oc, 0, 0, 1);
if ( audio_out_stream ) zm_dump_stream_format(oc, 1, 0, 1); if ( audio_out_stream ) zm_dump_stream_format(oc, 1, 0, 1);
AVDictionary *opts = NULL; AVDictionary *opts = nullptr;
std::string option_string = monitor->GetOptEncoderParams(); std::string option_string = monitor->GetOptEncoderParams();
ret = av_dict_parse_string(&opts, option_string.c_str(), "=", ",\n", 0); ret = av_dict_parse_string(&opts, option_string.c_str(), "=", ",\n", 0);
@ -422,7 +422,7 @@ bool VideoStore::open() {
Warning("Could not parse ffmpeg output options '%s'", option_string.c_str()); Warning("Could not parse ffmpeg output options '%s'", option_string.c_str());
} }
const AVDictionaryEntry *movflags_entry = av_dict_get(opts, "movflags", NULL, AV_DICT_MATCH_CASE); const AVDictionaryEntry *movflags_entry = av_dict_get(opts, "movflags", nullptr, AV_DICT_MATCH_CASE);
if ( !movflags_entry ) { if ( !movflags_entry ) {
Debug(1, "setting movflags to frag_keyframe+empty_moov"); Debug(1, "setting movflags to frag_keyframe+empty_moov");
// av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0); // av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
@ -435,14 +435,14 @@ bool VideoStore::open() {
} }
if ( (ret = avformat_write_header(oc, &opts)) < 0 ) { if ( (ret = avformat_write_header(oc, &opts)) < 0 ) {
Warning("Unable to set movflags trying with defaults."); Warning("Unable to set movflags trying with defaults.");
ret = avformat_write_header(oc, NULL); ret = avformat_write_header(oc, nullptr);
} else if ( av_dict_count(opts) != 0 ) { } else if ( av_dict_count(opts) != 0 ) {
Info("some options not used, turn on debugging for a list."); Info("some options not used, turn on debugging for a list.");
AVDictionaryEntry *e = NULL; AVDictionaryEntry *e = nullptr;
while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) { while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr ) {
Debug(1, "Encoder Option %s=>%s", e->key, e->value); Debug(1, "Encoder Option %s=>%s", e->key, e->value);
if ( !e->value ) { if ( !e->value ) {
av_dict_set(&opts, e->key, NULL, 0); av_dict_set(&opts, e->key, nullptr, 0);
} }
} }
} }
@ -468,7 +468,7 @@ VideoStore::~VideoStore() {
// whatever we get. Failures are not fatal. // whatever we get. Failures are not fatal.
AVPacket pkt; AVPacket pkt;
// Without these we seg fault I don't know why. // Without these we seg fault I don't know why.
pkt.data = NULL; pkt.data = nullptr;
pkt.size = 0; pkt.size = 0;
av_init_packet(&pkt); av_init_packet(&pkt);
@ -477,7 +477,7 @@ VideoStore::~VideoStore() {
* At the end of the file, we pass the remaining samples to * At the end of the file, we pass the remaining samples to
* the encoder. */ * the encoder. */
while ( zm_resample_get_delay(resample_ctx, audio_out_ctx->sample_rate) ) { while ( zm_resample_get_delay(resample_ctx, audio_out_ctx->sample_rate) ) {
zm_resample_audio(resample_ctx, NULL, out_frame); zm_resample_audio(resample_ctx, nullptr, out_frame);
if ( zm_add_samples_to_fifo(fifo, out_frame) ) { if ( zm_add_samples_to_fifo(fifo, out_frame) ) {
// Should probably set the frame size to what is reported FIXME // Should probably set the frame size to what is reported FIXME
@ -518,7 +518,7 @@ VideoStore::~VideoStore() {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// Put encoder into flushing mode // Put encoder into flushing mode
avcodec_send_frame(audio_out_ctx, NULL); avcodec_send_frame(audio_out_ctx, nullptr);
#endif #endif
while (1) { while (1) {
@ -537,7 +537,7 @@ VideoStore::~VideoStore() {
// Flush Queues // Flush Queues
Debug(1, "Flushing interleaved queues"); Debug(1, "Flushing interleaved queues");
av_interleaved_write_frame(oc, NULL); av_interleaved_write_frame(oc, nullptr);
Debug(1, "Writing trailer"); Debug(1, "Writing trailer");
/* Write the trailer before close */ /* Write the trailer before close */
@ -552,7 +552,7 @@ VideoStore::~VideoStore() {
/* Close the out file. */ /* Close the out file. */
Debug(2, "Closing"); Debug(2, "Closing");
if ( int rc = avio_close(oc->pb) ) { if ( int rc = avio_close(oc->pb) ) {
oc->pb = NULL; oc->pb = nullptr;
Error("Error closing avio %s", av_err2str(rc)); Error("Error closing avio %s", av_err2str(rc));
} }
} else { } else {
@ -570,24 +570,24 @@ VideoStore::~VideoStore() {
// We allocate and copy in newer ffmpeg, so need to free it // We allocate and copy in newer ffmpeg, so need to free it
//avcodec_free_context(&video_in_ctx); //avcodec_free_context(&video_in_ctx);
#endif #endif
video_in_ctx = NULL; video_in_ctx = nullptr;
if ( video_out_codec ) { if ( video_out_codec ) {
avcodec_close(video_out_ctx); avcodec_close(video_out_ctx);
Debug(4, "Success closing video_out_ctx"); Debug(4, "Success closing video_out_ctx");
video_out_codec = NULL; video_out_codec = nullptr;
} // end if video_out_codec } // end if video_out_codec
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
avcodec_free_context(&video_out_ctx); avcodec_free_context(&video_out_ctx);
#endif #endif
video_out_ctx = NULL; video_out_ctx = nullptr;
} // end if video_out_stream } // end if video_out_stream
if ( audio_out_stream ) { if ( audio_out_stream ) {
if ( audio_in_codec ) { if ( audio_in_codec ) {
avcodec_close(audio_in_ctx); avcodec_close(audio_in_ctx);
Debug(4, "Success closing audio_in_ctx"); Debug(4, "Success closing audio_in_ctx");
audio_in_codec = NULL; audio_in_codec = nullptr;
} // end if audio_in_codec } // end if audio_in_codec
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
@ -595,7 +595,7 @@ VideoStore::~VideoStore() {
avcodec_free_context(&audio_in_ctx); avcodec_free_context(&audio_in_ctx);
#endif #endif
Debug(4, "Success freeing audio_in_ctx"); Debug(4, "Success freeing audio_in_ctx");
audio_in_ctx = NULL; audio_in_ctx = nullptr;
if ( audio_out_ctx ) { if ( audio_out_ctx ) {
avcodec_close(audio_out_ctx); avcodec_close(audio_out_ctx);
@ -604,13 +604,13 @@ VideoStore::~VideoStore() {
avcodec_free_context(&audio_out_ctx); avcodec_free_context(&audio_out_ctx);
#endif #endif
} }
audio_out_ctx = NULL; audio_out_ctx = nullptr;
#if defined(HAVE_LIBAVRESAMPLE) || defined(HAVE_LIBSWRESAMPLE) #if defined(HAVE_LIBAVRESAMPLE) || defined(HAVE_LIBSWRESAMPLE)
if ( resample_ctx ) { if ( resample_ctx ) {
if ( fifo ) { if ( fifo ) {
av_audio_fifo_free(fifo); av_audio_fifo_free(fifo);
fifo = NULL; fifo = nullptr;
} }
#if defined(HAVE_LIBSWRESAMPLE) #if defined(HAVE_LIBSWRESAMPLE)
swr_free(&resample_ctx); swr_free(&resample_ctx);
@ -623,15 +623,15 @@ VideoStore::~VideoStore() {
} }
if ( in_frame ) { if ( in_frame ) {
av_frame_free(&in_frame); av_frame_free(&in_frame);
in_frame = NULL; in_frame = nullptr;
} }
if ( out_frame ) { if ( out_frame ) {
av_frame_free(&out_frame); av_frame_free(&out_frame);
out_frame = NULL; out_frame = nullptr;
} }
if ( converted_in_samples ) { if ( converted_in_samples ) {
av_free(converted_in_samples); av_free(converted_in_samples);
converted_in_samples = NULL; converted_in_samples = nullptr;
} }
#endif #endif
} // end if audio_out_stream } // end if audio_out_stream
@ -690,7 +690,7 @@ bool VideoStore::setup_resampler() {
#endif #endif
// if the codec is already open, nothing is done. // if the codec is already open, nothing is done.
if ( (ret = avcodec_open2(audio_in_ctx, audio_in_codec, NULL)) < 0 ) { if ( (ret = avcodec_open2(audio_in_ctx, audio_in_codec, nullptr)) < 0 ) {
Error("Can't open audio in codec!"); Error("Can't open audio in codec!");
return false; return false;
} }
@ -747,7 +747,7 @@ bool VideoStore::setup_resampler() {
audio_out_ctx->time_base = (AVRational){1, audio_out_ctx->sample_rate}; audio_out_ctx->time_base = (AVRational){1, audio_out_ctx->sample_rate};
AVDictionary *opts = NULL; AVDictionary *opts = nullptr;
if ( (ret = av_dict_set(&opts, "strict", "experimental", 0)) < 0 ) { if ( (ret = av_dict_set(&opts, "strict", "experimental", 0)) < 0 ) {
Error("Couldn't set experimental"); Error("Couldn't set experimental");
} }
@ -756,9 +756,9 @@ bool VideoStore::setup_resampler() {
if ( ret < 0 ) { if ( ret < 0 ) {
Error("could not open codec (%d) (%s)", Error("could not open codec (%d) (%s)",
ret, av_make_error_string(ret).c_str()); ret, av_make_error_string(ret).c_str());
audio_out_codec = NULL; audio_out_codec = nullptr;
audio_out_ctx = NULL; audio_out_ctx = nullptr;
audio_out_stream = NULL; audio_out_stream = nullptr;
return false; return false;
} }
zm_dump_codec(audio_out_ctx); zm_dump_codec(audio_out_ctx);
@ -814,14 +814,14 @@ bool VideoStore::setup_resampler() {
return false; return false;
} }
#if defined(HAVE_LIBSWRESAMPLE) #if defined(HAVE_LIBSWRESAMPLE)
resample_ctx = swr_alloc_set_opts(NULL, resample_ctx = swr_alloc_set_opts(nullptr,
audio_out_ctx->channel_layout, audio_out_ctx->channel_layout,
audio_out_ctx->sample_fmt, audio_out_ctx->sample_fmt,
audio_out_ctx->sample_rate, audio_out_ctx->sample_rate,
audio_in_ctx->channel_layout, audio_in_ctx->channel_layout,
audio_in_ctx->sample_fmt, audio_in_ctx->sample_fmt,
audio_in_ctx->sample_rate, audio_in_ctx->sample_rate,
0, NULL); 0, nullptr);
if ( !resample_ctx ) { if ( !resample_ctx ) {
Error("Could not allocate resample context"); Error("Could not allocate resample context");
av_frame_free(&in_frame); av_frame_free(&in_frame);
@ -885,7 +885,7 @@ bool VideoStore::setup_resampler() {
// The codec gives us the frame size, in samples, we calculate the size of the // The codec gives us the frame size, in samples, we calculate the size of the
// samples buffer in bytes // samples buffer in bytes
unsigned int audioSampleBuffer_size = av_samples_get_buffer_size( unsigned int audioSampleBuffer_size = av_samples_get_buffer_size(
NULL, audio_out_ctx->channels, nullptr, audio_out_ctx->channels,
audio_out_ctx->frame_size, audio_out_ctx->frame_size,
audio_out_ctx->sample_fmt, 0); audio_out_ctx->sample_fmt, 0);
converted_in_samples = reinterpret_cast<uint8_t *>(av_malloc(audioSampleBuffer_size)); converted_in_samples = reinterpret_cast<uint8_t *>(av_malloc(audioSampleBuffer_size));
@ -1013,7 +1013,7 @@ int VideoStore::writeAudioFramePacket(AVPacket *ipkt) {
if ( zm_resample_get_delay(resample_ctx, out_frame->sample_rate) < out_frame->nb_samples) if ( zm_resample_get_delay(resample_ctx, out_frame->sample_rate) < out_frame->nb_samples)
break; break;
// This will send a null frame, emptying out the resample buffer // This will send a null frame, emptying out the resample buffer
input_frame = NULL; input_frame = nullptr;
} // end while there is data in the resampler } // end while there is data in the resampler
} else { } else {

View File

@ -83,7 +83,7 @@ void Zone::Setup(
alarm_blobs = 0; alarm_blobs = 0;
min_blob_size = 0; min_blob_size = 0;
max_blob_size = 0; max_blob_size = 0;
image = 0; image = nullptr;
score = 0; score = 0;
overload_count = 0; overload_count = 0;
@ -136,7 +136,7 @@ void Zone::RecordStats(const Event *event) {
db_mutex.lock(); db_mutex.lock();
snprintf(sql, sizeof(sql), snprintf(sql, sizeof(sql),
"INSERT INTO Stats SET MonitorId=%d, ZoneId=%d, EventId=%" PRIu64 ", FrameId=%d, PixelDiff=%d, AlarmPixels=%d, FilterPixels=%d, BlobPixels=%d, Blobs=%d, MinBlobSize=%d, MaxBlobSize=%d, MinX=%d, MinY=%d, MaxX=%d, MaxY=%d, Score=%d", "INSERT INTO Stats SET MonitorId=%d, ZoneId=%d, EventId=%" PRIu64 ", FrameId=%d, PixelDiff=%d, AlarmPixels=%d, FilterPixels=%d, BlobPixels=%d, Blobs=%d, MinBlobSize=%d, MaxBlobSize=%d, MinX=%d, MinY=%d, MaxX=%d, MaxY=%d, Score=%d",
monitor->Id(), id, event->Id(), event->Frames()+1, pixel_diff, alarm_pixels, alarm_filter_pixels, alarm_blob_pixels, alarm_blobs, min_blob_size, max_blob_size, alarm_box.LoX(), alarm_box.LoY(), alarm_box.HiX(), alarm_box.HiY(), score monitor->Id(), id, event->Id(), event->Frames(), pixel_diff, alarm_pixels, alarm_filter_pixels, alarm_blob_pixels, alarm_blobs, min_blob_size, max_blob_size, alarm_box.LoX(), alarm_box.LoY(), alarm_box.HiX(), alarm_box.HiY(), score
); );
if ( mysql_query(&dbconn, sql) ) { if ( mysql_query(&dbconn, sql) ) {
Error("Can't insert event stats: %s", mysql_error(&dbconn)); Error("Can't insert event stats: %s", mysql_error(&dbconn));

View File

@ -70,15 +70,15 @@ void Usage() {
int main( int argc, char *argv[] ) { int main( int argc, char *argv[] ) {
self = argv[0]; self = argv[0];
srand(getpid() * time(0)); srand(getpid() * time(nullptr));
int id = -1; int id = -1;
static struct option long_options[] = { static struct option long_options[] = {
{"monitor", 1, 0, 'm'}, {"monitor", 1, nullptr, 'm'},
{"help", 0, 0, 'h'}, {"help", 0, nullptr, 'h'},
{"version", 0, 0, 'v'}, {"version", 0, nullptr, 'v'},
{0, 0, 0, 0} {nullptr, 0, nullptr, 0}
}; };
while (1) { while (1) {
@ -146,15 +146,15 @@ int main( int argc, char *argv[] ) {
unsigned int analysis_update_delay = monitor->GetAnalysisUpdateDelay(); unsigned int analysis_update_delay = monitor->GetAnalysisUpdateDelay();
time_t last_analysis_update_time, cur_time; time_t last_analysis_update_time, cur_time;
monitor->UpdateAdaptiveSkip(); monitor->UpdateAdaptiveSkip();
last_analysis_update_time = time(0); last_analysis_update_time = time(nullptr);
while( (!zm_terminate) && monitor->ShmValid() ) { while( (!zm_terminate) && monitor->ShmValid() ) {
// Process the next image // Process the next image
sigprocmask(SIG_BLOCK, &block_set, 0); sigprocmask(SIG_BLOCK, &block_set, nullptr);
// Some periodic updates are required for variable capturing framerate // Some periodic updates are required for variable capturing framerate
if ( analysis_update_delay ) { if ( analysis_update_delay ) {
cur_time = time(0); cur_time = time(nullptr);
if ( (unsigned int)( cur_time - last_analysis_update_time ) > analysis_update_delay ) { if ( (unsigned int)( cur_time - last_analysis_update_time ) > analysis_update_delay ) {
analysis_rate = monitor->GetAnalysisRate(); analysis_rate = monitor->GetAnalysisRate();
monitor->UpdateAdaptiveSkip(); monitor->UpdateAdaptiveSkip();
@ -174,7 +174,7 @@ int main( int argc, char *argv[] ) {
logInit(log_id_string); logInit(log_id_string);
zm_reload = false; zm_reload = false;
} }
sigprocmask(SIG_UNBLOCK, &block_set, 0); sigprocmask(SIG_UNBLOCK, &block_set, nullptr);
} // end while ! zm_terminate } // end while ! zm_terminate
delete monitor; delete monitor;
} else { } else {

View File

@ -90,7 +90,7 @@ void Usage() {
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
self = argv[0]; self = argv[0];
srand(getpid() * time(0)); srand(getpid() * time(nullptr));
const char *device = ""; const char *device = "";
const char *protocol = ""; const char *protocol = "";
@ -101,16 +101,16 @@ int main(int argc, char *argv[]) {
int monitor_id = -1; int monitor_id = -1;
static struct option long_options[] = { static struct option long_options[] = {
{"device", 1, 0, 'd'}, {"device", 1, nullptr, 'd'},
{"protocol", 1, 0, 'r'}, {"protocol", 1, nullptr, 'r'},
{"host", 1, 0, 'H'}, {"host", 1, nullptr, 'H'},
{"port", 1, 0, 'P'}, {"port", 1, nullptr, 'P'},
{"path", 1, 0, 'p'}, {"path", 1, nullptr, 'p'},
{"file", 1, 0, 'f'}, {"file", 1, nullptr, 'f'},
{"monitor", 1, 0, 'm'}, {"monitor", 1, nullptr, 'm'},
{"help", 0, 0, 'h'}, {"help", 0, nullptr, 'h'},
{"version", 0, 0, 'v'}, {"version", 0, nullptr, 'v'},
{0, 0, 0, 0} {nullptr, 0, nullptr, 0}
}; };
while (1) { while (1) {
@ -193,7 +193,7 @@ int main(int argc, char *argv[]) {
hwcaps_detect(); hwcaps_detect();
Monitor **monitors = 0; Monitor **monitors = nullptr;
int n_monitors = 0; int n_monitors = 0;
#if ZM_HAS_V4L #if ZM_HAS_V4L
if ( device[0] ) { if ( device[0] ) {
@ -240,7 +240,7 @@ int main(int argc, char *argv[]) {
result = 0; result = 0;
static char sql[ZM_SQL_SML_BUFSIZ]; static char sql[ZM_SQL_SML_BUFSIZ];
for ( int i = 0; i < n_monitors; i++ ) { for ( int i = 0; i < n_monitors; i++ ) {
time_t now = (time_t)time(NULL); time_t now = (time_t)time(nullptr);
monitors[i]->setStartupTime(now); monitors[i]->setStartupTime(now);
snprintf(sql, sizeof(sql), snprintf(sql, sizeof(sql),
@ -287,7 +287,7 @@ int main(int argc, char *argv[]) {
for ( int i = 0; i < n_monitors; i++ ) { for ( int i = 0; i < n_monitors; i++ ) {
long min_delay = MAXINT; long min_delay = MAXINT;
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
for ( int j = 0; j < n_monitors; j++ ) { for ( int j = 0; j < n_monitors; j++ ) {
if ( last_capture_times[j].tv_sec ) { if ( last_capture_times[j].tv_sec ) {
DELTA_TIMEVAL(delta_time, now, last_capture_times[j], DT_PREC_3); DELTA_TIMEVAL(delta_time, now, last_capture_times[j], DT_PREC_3);
@ -329,14 +329,14 @@ int main(int argc, char *argv[]) {
} }
if ( next_delays[i] > 0 ) { if ( next_delays[i] > 0 ) {
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
DELTA_TIMEVAL(delta_time, now, last_capture_times[i], DT_PREC_3); DELTA_TIMEVAL(delta_time, now, last_capture_times[i], DT_PREC_3);
long sleep_time = next_delays[i]-delta_time.delta; long sleep_time = next_delays[i]-delta_time.delta;
if ( sleep_time > 0 ) { if ( sleep_time > 0 ) {
usleep(sleep_time*(DT_MAXGRAN/DT_PREC_3)); usleep(sleep_time*(DT_MAXGRAN/DT_PREC_3));
} }
} }
gettimeofday(&(last_capture_times[i]), NULL); gettimeofday(&(last_capture_times[i]), nullptr);
} // end if next_delay <= min_delay || next_delays[i] <= 0 ) } // end if next_delay <= min_delay || next_delays[i] <= 0 )
} // end foreach n_monitors } // end foreach n_monitors

View File

@ -53,7 +53,7 @@ bool ValidateAccess(User *user, int mon_id) {
int main(int argc, const char *argv[]) { int main(int argc, const char *argv[]) {
self = argv[0]; self = argv[0];
srand(getpid() * time(0)); srand(getpid() * time(nullptr));
enum { ZMS_UNKNOWN, ZMS_MONITOR, ZMS_EVENT, ZMS_FIFO } source = ZMS_UNKNOWN; enum { ZMS_UNKNOWN, ZMS_MONITOR, ZMS_EVENT, ZMS_FIFO } source = ZMS_UNKNOWN;
enum { ZMS_JPEG, ZMS_MPEG, ZMS_RAW, ZMS_ZIP, ZMS_SINGLE } mode = ZMS_JPEG; enum { ZMS_JPEG, ZMS_MPEG, ZMS_RAW, ZMS_ZIP, ZMS_SINGLE } mode = ZMS_JPEG;
@ -101,12 +101,12 @@ int main(int argc, const char *argv[]) {
int parm_no = 0; int parm_no = 0;
while ( (parm_no < 16) && (parms[parm_no] = strtok(q_ptr, "&")) ) { while ( (parm_no < 16) && (parms[parm_no] = strtok(q_ptr, "&")) ) {
parm_no++; parm_no++;
q_ptr = NULL; q_ptr = nullptr;
} }
for ( int p = 0; p < parm_no; p++ ) { for ( int p = 0; p < parm_no; p++ ) {
char *name = strtok(parms[p], "="); char *name = strtok(parms[p], "=");
char const *value = strtok(NULL, "="); char const *value = strtok(nullptr, "=");
if ( !value ) if ( !value )
value = ""; value = "";
if ( !strcmp(name, "source") ) { if ( !strcmp(name, "source") ) {
@ -127,10 +127,10 @@ int main(int argc, const char *argv[]) {
} else if ( !strcmp(name, "time") ) { } else if ( !strcmp(name, "time") ) {
event_time = atoi(value); event_time = atoi(value);
} else if ( !strcmp(name, "event") ) { } else if ( !strcmp(name, "event") ) {
event_id = strtoull(value, NULL, 10); event_id = strtoull(value, nullptr, 10);
source = ZMS_EVENT; source = ZMS_EVENT;
} else if ( !strcmp(name, "frame") ) { } else if ( !strcmp(name, "frame") ) {
frame_id = strtoull(value, NULL, 10); frame_id = strtoull(value, nullptr, 10);
source = ZMS_EVENT; source = ZMS_EVENT;
} else if ( !strcmp(name, "scale") ) { } else if ( !strcmp(name, "scale") ) {
scale = atoi(value); scale = atoi(value);
@ -184,7 +184,7 @@ int main(int argc, const char *argv[]) {
logInit(log_id_string); logInit(log_id_string);
if ( config.opt_use_auth ) { if ( config.opt_use_auth ) {
User *user = NULL; User *user = nullptr;
if ( jwt_token_str != "" ) { if ( jwt_token_str != "" ) {
// user = zmLoadTokenUser(jwt_token_str, config.auth_hash_ips); // user = zmLoadTokenUser(jwt_token_str, config.auth_hash_ips);
@ -211,27 +211,27 @@ int main(int argc, const char *argv[]) {
} }
if ( !ValidateAccess(user, monitor_id) ) { if ( !ValidateAccess(user, monitor_id) ) {
delete user; delete user;
user = NULL; user = nullptr;
fputs("HTTP/1.0 403 Forbidden\r\n\r\n", stdout); fputs("HTTP/1.0 403 Forbidden\r\n\r\n", stdout);
logTerm(); logTerm();
zmDbClose(); zmDbClose();
return 0; return 0;
} }
delete user; delete user;
user = NULL; user = nullptr;
} // end if config.opt_use_auth } // end if config.opt_use_auth
hwcaps_detect(); hwcaps_detect();
zmSetDefaultTermHandler(); zmSetDefaultTermHandler();
zmSetDefaultDieHandler(); zmSetDefaultDieHandler();
setbuf(stdout, 0); setbuf(stdout, nullptr);
if ( nph ) { if ( nph ) {
fputs("HTTP/1.0 200 OK\r\n", stdout); fputs("HTTP/1.0 200 OK\r\n", stdout);
} }
fprintf(stdout, "Server: ZoneMinder Video Server/%s\r\n", ZM_VERSION); fprintf(stdout, "Server: ZoneMinder Video Server/%s\r\n", ZM_VERSION);
time_t now = time(0); time_t now = time(nullptr);
char date_string[64]; char date_string[64];
strftime(date_string, sizeof(date_string)-1, strftime(date_string, sizeof(date_string)-1,
"%a, %d %b %Y %H:%M:%S GMT", gmtime(&now)); "%a, %d %b %Y %H:%M:%S GMT", gmtime(&now));

View File

@ -211,45 +211,45 @@ int main(int argc, char *argv[]) {
self = argv[0]; self = argv[0];
srand(getpid() * time(0)); srand(getpid() * time(nullptr));
static struct option long_options[] = { static struct option long_options[] = {
{"device", 2, 0, 'd'}, {"device", 2, nullptr, 'd'},
{"monitor", 1, 0, 'm'}, {"monitor", 1, nullptr, 'm'},
{"verbose", 0, 0, 'v'}, {"verbose", 0, nullptr, 'v'},
{"image", 2, 0, 'i'}, {"image", 2, nullptr, 'i'},
{"scale", 1, 0, 'S'}, {"scale", 1, nullptr, 'S'},
{"timestamp", 2, 0, 't'}, {"timestamp", 2, nullptr, 't'},
{"state", 0, 0, 's'}, {"state", 0, nullptr, 's'},
{"brightness", 2, 0, 'B'}, {"brightness", 2, nullptr, 'B'},
{"contrast", 2, 0, 'C'}, {"contrast", 2, nullptr, 'C'},
{"hue", 2, 0, 'H'}, {"hue", 2, nullptr, 'H'},
{"contrast", 2, 0, 'O'}, {"contrast", 2, nullptr, 'O'},
{"read_index", 0, 0, 'R'}, {"read_index", 0, nullptr, 'R'},
{"write_index", 0, 0, 'W'}, {"write_index", 0, nullptr, 'W'},
{"event", 0, 0, 'e'}, {"event", 0, nullptr, 'e'},
{"fps", 0, 0, 'f'}, {"fps", 0, nullptr, 'f'},
{"zones", 2, 0, 'z'}, {"zones", 2, nullptr, 'z'},
{"alarm", 0, 0, 'a'}, {"alarm", 0, nullptr, 'a'},
{"noalarm", 0, 0, 'n'}, {"noalarm", 0, nullptr, 'n'},
{"cancel", 0, 0, 'c'}, {"cancel", 0, nullptr, 'c'},
{"reload", 0, 0, 'L'}, {"reload", 0, nullptr, 'L'},
{"enable", 0, 0, 'E'}, {"enable", 0, nullptr, 'E'},
{"disable", 0, 0, 'D'}, {"disable", 0, nullptr, 'D'},
{"suspend", 0, 0, 'u'}, {"suspend", 0, nullptr, 'u'},
{"resume", 0, 0, 'r'}, {"resume", 0, nullptr, 'r'},
{"query", 0, 0, 'q'}, {"query", 0, nullptr, 'q'},
{"username", 1, 0, 'U'}, {"username", 1, nullptr, 'U'},
{"password", 1, 0, 'P'}, {"password", 1, nullptr, 'P'},
{"auth", 1, 0, 'A'}, {"auth", 1, nullptr, 'A'},
{"token", 1, 0, 'T'}, {"token", 1, nullptr, 'T'},
{"version", 1, 0, 'V'}, {"version", 1, nullptr, 'V'},
{"help", 0, 0, 'h'}, {"help", 0, nullptr, 'h'},
{"list", 0, 0, 'l'}, {"list", 0, nullptr, 'l'},
{0, 0, 0, 0} {nullptr, 0, nullptr, 0}
}; };
const char *device = 0; const char *device = nullptr;
int mon_id = 0; int mon_id = 0;
bool verbose = false; bool verbose = false;
int function = ZMU_BOGUS; int function = ZMU_BOGUS;
@ -260,10 +260,10 @@ int main(int argc, char *argv[]) {
int contrast = -1; int contrast = -1;
int hue = -1; int hue = -1;
int colour = -1; int colour = -1;
char *zoneString = 0; char *zoneString = nullptr;
char *username = 0; char *username = nullptr;
char *password = 0; char *password = nullptr;
char *auth = 0; char *auth = nullptr;
std::string jwt_token_str = ""; std::string jwt_token_str = "";
#if ZM_HAS_V4L #if ZM_HAS_V4L
#if ZM_HAS_V4L2 #if ZM_HAS_V4L2
@ -487,7 +487,7 @@ int main(int argc, char *argv[]) {
if ( !monitor->connect() ) { if ( !monitor->connect() ) {
Error("Can't connect to capture daemon: %d %s", monitor->Id(), monitor->Name()); Error("Can't connect to capture daemon: %d %s", monitor->Id(), monitor->Name());
delete monitor; delete monitor;
monitor = NULL; monitor = nullptr;
exit_zmu(-1); exit_zmu(-1);
} }
@ -701,7 +701,7 @@ int main(int argc, char *argv[]) {
Usage(); Usage();
} }
delete monitor; delete monitor;
monitor = NULL; monitor = nullptr;
} else { // non monitor functions } else { // non monitor functions
if ( function & ZMU_QUERY ) { if ( function & ZMU_QUERY ) {
#if ZM_HAS_V4L #if ZM_HAS_V4L

View File

@ -80,7 +80,7 @@ fi;
if [ "$DISTROS" == "" ]; then if [ "$DISTROS" == "" ]; then
if [ "$RELEASE" != "" ]; then if [ "$RELEASE" != "" ]; then
DISTROS="xenial,bionic,eoan,focal" DISTROS="xenial,bionic,focal"
else else
DISTROS=`lsb_release -a 2>/dev/null | grep Codename | awk '{print $2}'`; DISTROS=`lsb_release -a 2>/dev/null | grep Codename | awk '{print $2}'`;
fi; fi;

View File

@ -1,4 +1,7 @@
#!/bin/bash #!/bin/bash
set -o pipefail
# packpack setup file for the ZoneMinder project # packpack setup file for the ZoneMinder project
# Written by Andrew Bauer # Written by Andrew Bauer
@ -250,6 +253,13 @@ execpackpack () {
else else
packpack/packpack $parms packpack/packpack $parms
fi fi
if [ $? -ne 0 ]; then
echo
echo "ERROR: An error occurred while executing packpack."
echo
exit 1
fi
} }
# Check for connectivity with the deploy target host # Check for connectivity with the deploy target host
@ -337,10 +347,10 @@ elif [ "${OS}" == "debian" ] || [ "${OS}" == "ubuntu" ] || [ "${OS}" == "raspbia
setdebpkgname setdebpkgname
movecrud movecrud
if [ "${DIST}" == "trusty" ] || [ "${DIST}" == "precise" ]; then if [ "${DIST}" == "focal" ] || [ "${DIST}" == "buster" ]; then
ln -sfT distros/ubuntu1204 debian ln -sfT distros/ubuntu2004 debian
elif [ "${DIST}" == "wheezy" ]; then elif [ "${DIST}" == "beowulf" ]; then
ln -sfT distros/debian debian ln -sfT distros/beowulf debian
else else
ln -sfT distros/ubuntu1604 debian ln -sfT distros/ubuntu1604 debian
fi fi

View File

@ -1,29 +0,0 @@
#!/bin/bash -x
set -e
set -o pipefail
set -x
with_timestamps() {
while read -r line; do
echo -e "$(date +%T)\t$line";
done
}
bootstrap_zm() {
if [ "$ZM_BUILDMETHOD" = "autotools" ]; then libtoolize --force; fi
if [ "$ZM_BUILDMETHOD" = "autotools" ]; then aclocal; fi
if [ "$ZM_BUILDMETHOD" = "autotools" ]; then autoheader; fi
if [ "$ZM_BUILDMETHOD" = "autotools" ]; then automake --force-missing --add-missing; fi
if [ "$ZM_BUILDMETHOD" = "autotools" ]; then autoconf; fi
mysql -uroot -e "CREATE DATABASE IF NOT EXISTS zm"
mysql -uroot -e "GRANT ALL ON zm.* TO 'zmuser'@'localhost' IDENTIFIED BY 'zmpass'";
mysql -uroot -e "FLUSH PRIVILEGES"
mysql -uzmuser -pzmpass < ${TRAVIS_BUILD_DIR}/db/zm_create.sql
}
bootstrap_zm | with_timestamps

View File

@ -1,33 +0,0 @@
#!/bin/bash
set -e
set -o pipefail
with_timestamps() {
while read -r line; do
echo -e "$(date +%T)\t$line";
done
}
cd $TRAVIS_BUILD_DIR
build_zm() {
if [ "$ZM_BUILDMETHOD" = "autotools" ]; then
./configure --prefix=/usr --with-libarch=lib/$DEB_HOST_GNU_TYPE --host=$DEB_HOST_GNU_TYPE --build=$DEB_BUILD_GNU_TYPE --with-mysql=/usr --with-ffmpeg=/usr --with-webdir=/usr/share/zoneminder/www --with-cgidir=/usr/libexec/zoneminder/cgi-bin --with-webuser=www-data --with-webgroup=www-data --enable-crashtrace=yes --disable-debug --enable-mmap=yes ZM_SSL_LIB=openssl
fi
if [ "$ZM_BUILDMETHOD" = "cmake" ]; then
cmake -DCMAKE_INSTALL_PREFIX="/usr"
fi
make
sudo make install
if [ "$ZM_BUILDMETHOD" = "cmake" ]; then
sudo ./zmlinkcontent.sh
fi
}
build_zm | with_timestamps

View File

@ -1,20 +0,0 @@
#!/bin/bash
set -e
set -o pipefail
with_timestamps() {
while read -r line; do
echo -e "$(date +%T)\t$line";
done
}
install_deps() {
sudo apt-get update -qq
sudo apt-get install -y -qq zlib1g-dev apache2 mysql-server php5 php5-mysql build-essential libmysqlclient-dev libssl-dev libbz2-dev libpcre3-dev libdbi-perl libarchive-zip-perl libdate-manip-perl libdevice-serialport-perl libmime-perl libwww-perl libdbd-mysql-perl libsys-mmap-perl yasm automake autoconf cmake libjpeg-turbo8-dev apache2-mpm-prefork libapache2-mod-php5 php5-cli libtheora-dev libvorbis-dev libvpx-dev libx264-dev 2>&1 > /dev/null
}
install_deps | with_timestamps

View File

@ -1,11 +0,0 @@
#!/bin/bash
set -e
git clone --depth=10 --branch=master git://source.ffmpeg.org/ffmpeg.git
cd ffmpeg
./configure --enable-shared --enable-swscale --enable-gpl --enable-libx264 --enable-libvpx --enable-libvorbis --enable-libtheora
make -j `grep processor /proc/cpuinfo|wc -l`
sudo make install
sudo make install-libs

View File

@ -1,23 +0,0 @@
#!/bin/bash
set -e
set -o pipefail
with_timestamps() {
while read -r line; do
echo -e "$(date +%T)\t$line";
done
}
run_tests() {
mysql -uzmuser -pzmpass zm < ../../db/test.monitor.sql
sudo zmu -l
sudo zmc -m1 &
sudo zma -m1 &
sudo zmu -l
sudo grep ERR /var/log/syslog
sudo zmpkg.pl start
sudo zmfilter.pl -f purgewhenfull
}
run_tests | with_timestamps

View File

@ -1 +1 @@
1.35.5 1.35.6

View File

@ -0,0 +1,10 @@
/**
* bootstrap-table - An extended table to integration with some of the most widely used CSS frameworks. (Supports Bootstrap, Semantic UI, Bulma, Material Design, Foundation)
*
* @version v1.17.1
* @homepage https://bootstrap-table.com
* @author wenzhixin <wenzhixin2010@gmail.com> (http://wenzhixin.net.cn/)
* @license MIT
*/
.bootstrap-table.bootstrap3 .fixed-table-pagination>.pagination .page-jump-to,.bootstrap-table.bootstrap3 .fixed-table-pagination>.pagination ul.pagination{display:inline}.bootstrap-table .fixed-table-pagination>.pagination .page-jump-to input{width:70px;margin-left:5px;text-align:center;float:left}

View File

@ -58,8 +58,10 @@ class Event extends ZM_Object {
if ( ! ( property_exists($this, 'Storage') and $this->{'Storage'} ) ) { if ( ! ( property_exists($this, 'Storage') and $this->{'Storage'} ) ) {
if ( isset($this->{'StorageId'}) and $this->{'StorageId'} ) if ( isset($this->{'StorageId'}) and $this->{'StorageId'} )
$this->{'Storage'} = Storage::find_one(array('Id'=>$this->{'StorageId'})); $this->{'Storage'} = Storage::find_one(array('Id'=>$this->{'StorageId'}));
if ( ! ( property_exists($this, 'Storage') and $this->{'Storage'} ) ) if ( ! ( property_exists($this, 'Storage') and $this->{'Storage'} ) ) {
$this->{'Storage'} = new Storage(NULL); $this->{'Storage'} = new Storage(NULL);
$this->{'Storage'}->Scheme($this->{'Scheme'});
}
} }
return $this->{'Storage'}; return $this->{'Storage'};
} }

View File

@ -30,9 +30,101 @@ class Filter extends ZM_Object {
'Query_json' => '', 'Query_json' => '',
); );
protected $_querystring;
protected $_sql;
protected $_hidden_fields;
public $_pre_sql_conditions;
public $_post_sql_conditions;
protected $_Terms;
public function sql() {
if ( ! isset($this->_sql) ) {
foreach ( $this->FilterTerms() as $term ) {
if ( ! ($term->is_pre_sql() or $term->is_post_sql()) )
$this->_sql .= $term->sql();
} # end foreach term
}
return $this->_sql;
}
public function querystring() {
if ( ! isset($this->_querystring) ) {
foreach ( $this->FilterTerms() as $term ) {
$this->_querystring .= $term->querystring();
} # end foreach term
}
return $this->_querystring;
}
public function hidden_fields() {
if ( ! isset($this->_hidden_fields) ) {
foreach ( $this->FilterTerms() as $term ) {
$this->_hidden_fields .= $term->hidden_fields();
} # end foreach term
}
return $this->_hidden_fields;
}
public function pre_sql_conditions() {
if ( ! isset($this->_pre_sql_conditions) ) {
$this->_pre_sql_conditions = array();
foreach ( $this->FilterTerms() as $term ) {
if ( $term->is_pre_sql() )
$this->_pre_sql_conditions[] = $term;
} # end foreach term
}
return $this->_pre_sql_conditions;
}
public function post_sql_conditions() {
if ( ! isset($this->_post_sql_conditions) ) {
$this->_post_sql_conditions = array();
foreach ( $this->FilterTerms() as $term ) {
if ( $term->is_post_sql() )
$this->_post_sql_conditions[] = $term;
} # end foreach term
}
return $this->_post_sql_conditions;
}
public function FilterTerms() {
if ( ! isset($this->Terms) ) {
$this->Terms = array();
$_terms = $this->terms();
for ( $i = 0; $i < count($_terms); $i++ ) {
$term = new FilterTerm($this, $_terms[$i], $i);
$this->Terms[] = $term;
} # end foreach term
}
return $this->Terms;
}
public static function parse($new_filter, $querySep='&amp;') {
$filter = new Filter();
$filter->Query($new_filter['Query']);
return $filter;
}
# If no storage areas are specified in the terms, then return all
public function get_StorageAreas() {
$storage_ids = array();
foreach ( $this->Terms as $term ) {
if ( $term->attr == 'StorageId' ) {
# TODO handle other operators like !=
$storage_ids[] = $term->value;
}
}
if ( count($storage_ids) ) {
return Storage::find(array('Id'=>$storage_ids));
} else {
return Storage::find();
}
} # end function get_StorageAreas
public function Query_json() { public function Query_json() {
if ( func_num_args( ) ) { if ( func_num_args( ) ) {
$this->{'Query_json'} = func_get_arg(0);; $this->{'Query_json'} = func_get_arg(0);
$this->{'Query'} = jsonDecode($this->{'Query_json'}); $this->{'Query'} = jsonDecode($this->{'Query_json'});
} }
return $this->{'Query_json'}; return $this->{'Query_json'};
@ -58,297 +150,6 @@ class Filter extends ZM_Object {
return $this->{'Query'}; return $this->{'Query'};
} }
public function parse( $querySep='&amp;') {
$filter = $this->Query();
Warning(print_r($filter, true));
$query = '';
$sql = '';
$fields = '';
$validQueryConjunctionTypes = getFilterQueryConjunctionTypes();
$StorageArea = NULL;
# It is not possible to pass an empty array in the url, so we have to deal with there not being a terms field.
$terms = (is_array($filter['terms'])) ? $filter['terms'] : array();
if ( count($terms) ) {
for ( $i = 0; $i < count($terms); $i++ ) {
$term = $terms[$i];
if ( isset($term['cnj']) && array_key_exists($term['cnj'], $validQueryConjunctionTypes) ) {
$query .= $querySep.urlencode("filter[Query][terms][$i][cnj]").'='.urlencode($term['cnj']);
$sql .= ' '.$term['cnj'].' ';
$fields .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][cnj]\" value=\"".htmlspecialchars($term['cnj'])."\"/>\n";
}
if ( isset($term['obr']) && (string)(int)$term['obr'] == $term['obr'] ) {
$query .= $querySep.urlencode("filter[Query][terms][$i][obr]").'='.urlencode($term['obr']);
$sql .= ' '.str_repeat('(', $term['obr']).' ';
$fields .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][obr]\" value=\"".htmlspecialchars($term['obr'])."\"/>\n";
}
if ( isset($term['attr']) ) {
$query .= $querySep.urlencode("filter[Query][terms][$i][attr]").'='.urlencode($term['attr']);
$fields .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][attr]\" value=\"".htmlspecialchars($term['attr'])."\"/>\n";
switch ( $term['attr'] ) {
case 'AlarmedZoneId':
$term['op'] = 'EXISTS';
break;
case 'MonitorName':
$sql .= 'M.Name';
break;
case 'ServerId':
case 'MonitorServerId':
$sql .= 'M.ServerId';
break;
case 'StorageServerId':
$sql .= 'S.ServerId';
break;
case 'FilterServerId':
$sql .= ZM_SERVER_ID;
break;
# Unspecified start or end, so assume start, this is to support legacy filters
case 'DateTime':
$sql .= 'E.StartTime';
break;
case 'Date':
$sql .= 'to_days(E.StartTime)';
break;
case 'Time':
$sql .= 'extract(hour_second FROM E.StartTime)';
break;
case 'Weekday':
$sql .= 'weekday(E.StartTime)';
break;
# Starting Time
case 'StartDateTime':
$sql .= 'E.StartTime';
break;
case 'FramesEventId':
$sql .= 'F.EventId';
break;
case 'StartDate':
$sql .= 'to_days(E.StartTime)';
break;
case 'StartTime':
$sql .= 'extract(hour_second FROM E.StartTime)';
break;
case 'StartWeekday':
$sql .= 'weekday(E.StartTime)';
break;
# Ending Time
case 'EndDateTime':
$sql .= 'E.EndTime';
break;
case 'EndDate':
$sql .= 'to_days(E.EndTime)';
break;
case 'EndTime':
$sql .= 'extract(hour_second FROM E.EndTime)';
break;
case 'EndWeekday':
$sql .= 'weekday(E.EndTime)';
break;
case 'Id':
case 'Name':
case 'DiskSpace':
case 'MonitorId':
case 'StorageId':
case 'SecondaryStorageId':
case 'Length':
case 'Frames':
case 'AlarmFrames':
case 'TotScore':
case 'AvgScore':
case 'MaxScore':
case 'Cause':
case 'Notes':
case 'StateId':
case 'Archived':
$sql .= 'E.'.$term['attr'];
break;
case 'DiskPercent':
// Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH
if ( ! $StorageArea ) {
for ( $j = 0; $j < count($terms); $j++ ) {
if (
isset($terms[$j]['attr'])
and
($terms[$j]['attr'] == 'StorageId')
and
isset($terms[$j]['val'])
) {
$StorageArea = ZM\Storage::find_one(array('Id'=>$terms[$j]['val']));
break;
}
} // end foreach remaining term
if ( ! $StorageArea ) $StorageArea = new ZM\Storage();
} // end no StorageArea found yet
$sql .= getDiskPercent($StorageArea->Path());
break;
case 'DiskBlocks':
// Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH
if ( ! $StorageArea ) {
for ( $j = $i; $j < count($terms); $j++ ) {
if (
isset($terms[$j]['attr'])
and
($terms[$j]['attr'] == 'StorageId')
and
isset($terms[$j]['val'])
) {
$StorageArea = ZM\Storage::find_one(array('Id'=>$terms[$j]['val']));
}
} // end foreach remaining term
} // end no StorageArea found yet
$sql .= getDiskBlocks( $StorageArea );
break;
case 'SystemLoad':
$sql .= getLoad();
break;
}
$valueList = array();
foreach ( preg_split('/["\'\s]*?,["\'\s]*?/', preg_replace('/^["\']+?(.+)["\']+?$/', '$1', $term['val'])) as $value ) {
switch ( $term['attr'] ) {
case 'AlarmedZoneId':
$value = '(SELECT * FROM Stats WHERE EventId=E.Id AND ZoneId='.$value.')';
break;
case 'MonitorName':
case 'Name':
case 'Cause':
case 'Notes':
if ( $term['op'] == 'LIKE' || $term['op'] == 'NOT LIKE' ) {
$value = '%'.$value.'%';
}
$value = dbEscape($value);
break;
case 'MonitorServerId':
case 'FilterServerId':
case 'StorageServerId':
case 'ServerId':
if ( $value == 'ZM_SERVER_ID' ) {
$value = ZM_SERVER_ID;
} else if ( $value == 'NULL' ) {
} else {
$value = dbEscape($value);
}
break;
case 'StorageId':
$StorageArea = ZM\Storage::find_one(array('Id'=>$value));
if ( $value != 'NULL' )
$value = dbEscape($value);
break;
case 'DateTime':
case 'StartDateTime':
case 'EndDateTime':
if ( $value != 'NULL' )
$value = '\''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\'';
break;
case 'Date':
case 'StartDate':
case 'EndDate':
if ( $value == 'CURDATE()' or $value == 'NOW()' ) {
$value = 'to_days('.$value.')';
} else if ( $value != 'NULL' ) {
$value = 'to_days(\''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\')';
}
break;
case 'Time':
case 'StartTime':
case 'EndTime':
if ( $value != 'NULL' )
$value = 'extract(hour_second from \''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\')';
break;
default :
if ( $value != 'NULL' )
$value = dbEscape($value);
break;
}
$valueList[] = $value;
} // end foreach value
switch ( $term['op'] ) {
case '=' :
case '!=' :
case '>=' :
case '>' :
case '<' :
case '<=' :
case 'LIKE' :
case 'NOT LIKE':
$sql .= ' '.$term['op'].' '. $value;
break;
case '=~' :
$sql .= ' regexp '.$value;
break;
case '!~' :
$sql .= ' not regexp '.$value;
break;
case '=[]' :
case 'IN' :
$sql .= ' IN ('.join(',', $valueList).')';
break;
case '![]' :
$sql .= ' not in ('.join(',', $valueList).')';
break;
case 'EXISTS' :
$sql .= ' EXISTS ' .$value;
break;
case 'IS' :
if ( $value == 'Odd' ) {
$sql .= ' % 2 = 1';
} else if ( $value == 'Even' ) {
$sql .= ' % 2 = 0';
} else {
$sql .= " IS $value";
}
break;
case 'IS NOT' :
$sql .= " IS NOT $value";
break;
default:
ZM\Warning('Invalid operator in filter: ' . print_r($term['op'], true));
} // end switch op
$query .= $querySep.urlencode("filter[Query][terms][$i][op]").'='.urlencode($term['op']);
$fields .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][op]\" value=\"".htmlspecialchars($term['op'])."\"/>\n";
if ( isset($term['val']) ) {
$query .= $querySep.urlencode("filter[Query][terms][$i][val]").'='.urlencode($term['val']);
$fields .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][val]\" value=\"".htmlspecialchars($term['val'])."\"/>\n";
}
} // end if isset($term['attr'])
if ( isset($term['cbr']) && (string)(int)$term['cbr'] == $term['cbr'] ) {
$query .= $querySep.urlencode("filter[Query][terms][$i][cbr]").'='.urlencode($term['cbr']);
$sql .= ' '.str_repeat(')', $term['cbr']);
$fields .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][cbr]\" value=\"".htmlspecialchars($term['cbr'])."\"/>\n";
}
} // end foreach term
if ( $sql )
$sql = ' AND ( '.$sql.' )';
} else {
$query = $querySep;
#.urlencode('filter[Query][terms]=[]');
} // end if terms
$this->{'query'} = $query;
$this->{'sql'} = $sql;
$this->{'fields'} = $fields;
#if ( 0 ) {
#// ICON I feel like these should be here, but not yet
#if ( isset($filter['Query']['sort_field']) ) {
#$sql .= ' ORDER BY ' . $filter['Query']['sort_field'] . (
#( $filter['Query']['sort_asc'] ? ' ASC' : ' DESC' ) );
#}
#if ( $filter['Query']['limit'] ) {
#$sql .= ' LIMIT ' . validInt($filter['Query']['limit']);
#}
#}
} // end function parse($querySep='&amp;')
public static function find( $parameters = array(), $options = array() ) { public static function find( $parameters = array(), $options = array() ) {
return ZM_Object::_find(get_class(), $parameters, $options); return ZM_Object::_find(get_class(), $parameters, $options);
} }
@ -495,6 +296,37 @@ class Filter extends ZM_Object {
return $status; return $status;
} }
public function test_pre_sql_conditions() {
if ( !count($this->pre_sql_conditions()) ) {
return true;
} # end if pre_sql_conditions
$failed = false;
foreach ( $this->pre_sql_conditions() as $term ) {
if ( !$term->test() ) {
$failed = true;
break;
}
}
return $failed;
}
public function test_post_sql_conditions($event) {
if ( !count($this->post_sql_conditions()) ) {
return true;
} # end if pre_sql_conditions
$failed = true;
foreach ( $this->post_sql_conditions() as $term ) {
if ( !$term->test($event) ) {
$failed = false;
break;
}
}
return $failed;
}
} # end class Filter } # end class Filter
?> ?>

408
web/includes/FilterTerm.php Normal file
View File

@ -0,0 +1,408 @@
<?php
namespace ZM;
$validConjunctionTypes = null;
function getFilterQueryConjunctionTypes() {
if ( !isset($validConjunctionTypes ) ) {
$validConjunctionTypes = array(
'and' => translate('ConjAnd'),
'or' => translate('ConjOr')
);
}
return $validConjunctionTypes;
}
class FilterTerm {
public $filter;
public $index;
public $attr;
public $op;
public $val;
public $values;
public $cnj;
public $obr;
public $cbr;
public function __construct($filter = null, $term = NULL, $index=0) {
$this->filter = $filter;
$validConjunctionTypes = getFilterQueryConjunctionTypes();
$this->index = $index;
$this->attr = $term['attr'];
$this->op = $term['op'];
$this->val = $term['val'];
if ( isset($term['cnj']) ) {
if ( array_key_exists($term['cnj'], $validConjunctionTypes) ) {
$this->cnj = $term['cnj'];
} else {
Warning('Invalid cnj ' . $term['cnj'].' in '.print_r($term, true));
}
}
if ( isset($term['obr']) ) {
if ( (string)(int)$term['obr'] == $term['obr'] ) {
$this->obr = $term['obr'];
} else {
Warning('Invalid obr ' . $term['obr'] . ' in ' . print_r($term, true));
}
}
if ( isset($term['cbr']) ) {
if ( (string)(int)$term['cbr'] == $term['cbr'] ) {
$this->obr = $term['cbr'];
} else {
Warning('Invalid cbr ' . $term['cbr'] . ' in ' . print_r($term, true));
}
}
} # end function __construct
# Returns an array of values. AS term->value can be a list, we will break it apart, remove quotes etc
public function sql_values() {
$values = array();
if ( !isset($this->val) ) {
Logger::Warning("No value in term ");
return $values;
}
foreach ( preg_split('/["\'\s]*?,["\'\s]*?/', preg_replace('/^["\']+?(.+)["\']+?$/', '$1', $this->val)) as $value ) {
switch ( $this->attr ) {
case 'AlarmedZoneId':
$value = '(SELECT * FROM Stats WHERE EventId=E.Id AND ZoneId='.$value.')';
break;
case 'ExistsInFileSystem':
break;
case 'MonitorName':
case 'Name':
case 'Cause':
case 'Notes':
if ( $this->op == 'LIKE' || $this->op == 'NOT LIKE' ) {
$value = '%'.$value.'%';
}
$value = dbEscape($value);
break;
case 'MonitorServerId':
case 'FilterServerId':
case 'StorageServerId':
case 'ServerId':
if ( $value == 'ZM_SERVER_ID' ) {
$value = ZM_SERVER_ID;
} else if ( $value == 'NULL' ) {
} else {
$value = dbEscape($value);
}
break;
case 'StorageId':
if ( $value != 'NULL' ) {
$value = dbEscape($value);
}
break;
case 'DateTime':
case 'StartDateTime':
case 'EndDateTime':
if ( $value != 'NULL' )
$value = '\''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\'';
break;
case 'Date':
case 'StartDate':
case 'EndDate':
if ( $value == 'CURDATE()' or $value == 'NOW()' ) {
$value = 'to_days('.$value.')';
} else if ( $value != 'NULL' ) {
$value = 'to_days(\''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\')';
}
break;
case 'Time':
case 'StartTime':
case 'EndTime':
if ( $value != 'NULL' )
$value = 'extract(hour_second from \''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\')';
break;
default :
if ( $value == 'Odd' ) {
$value = 1;
} else if ( $value == 'Even' ) {
$value = 0;
} else if ( $value != 'NULL' )
$value = dbEscape($value);
break;
}
$values[] = $value;
} // end foreach value
return $values;
} # end function sql_values
public function sql_operator() {
if ( $this->attr == 'AlarmZoneId' ) {
return ' EXISTS ';
}
switch ( $this->op ) {
case '=' :
case '!=' :
case '>=' :
case '>' :
case '<' :
case '<=' :
case 'LIKE' :
case 'NOT LIKE':
return ' '.$this->op.' ';
case '=~' :
return ' regexp ';
case '!~' :
return ' not regexp ';
case '=[]' :
case 'IN' :
return ' IN ';
case '![]' :
return ' NOT IN ';
case 'EXISTS' :
return ' EXISTS ';
case 'IS' :
# Odd will be replaced with 1
# Even will be replaced with 0
if ( $this->value == 'Odd' or $this->value == 'Even' ) {
return ' % 2 = ';
} else {
return ' IS ';
}
case 'IS NOT' :
if ( $this->value == 'Odd' or $this->value == 'Even' ) {
return ' % 2 = ';
}
return ' IS NOT ';
default:
ZM\Warning('Invalid operator in filter: ' . print_r($this->op, true));
} // end switch op
} # end public function sql_operator
/* Some terms don't have related SQL */
public function sql() {
if ( $this->attr == 'ExistsInFileSystem' ) {
return '';
}
$sql = '';
if ( isset($this->cnj) ) {
$sql .= ' '.$this->cnj.' ';
}
if ( isset($this->obr) ) {
$sql .= ' '.str_repeat('(', $this->obr).' ';
}
switch ( $this->attr ) {
case 'MonitorName':
$sql .= 'M.Name';
break;
case 'ServerId':
case 'MonitorServerId':
$sql .= 'M.ServerId';
break;
case 'StorageServerId':
$sql .= 'S.ServerId';
break;
case 'FilterServerId':
$sql .= ZM_SERVER_ID;
break;
# Unspecified start or end, so assume start, this is to support legacy filters
case 'DateTime':
$sql .= 'E.StartTime';
break;
case 'Date':
$sql .= 'to_days(E.StartTime)';
break;
case 'Time':
$sql .= 'extract(hour_second FROM E.StartTime)';
break;
case 'Weekday':
$sql .= 'weekday(E.StartTime)';
break;
# Starting Time
case 'StartDateTime':
$sql .= 'E.StartTime';
break;
case 'FramesEventId':
$sql .= 'F.EventId';
break;
case 'StartDate':
$sql .= 'to_days(E.StartTime)';
break;
case 'StartTime':
$sql .= 'extract(hour_second FROM E.StartTime)';
break;
case 'StartWeekday':
$sql .= 'weekday(E.StartTime)';
break;
# Ending Time
case 'EndDateTime':
$sql .= 'E.EndTime';
break;
case 'EndDate':
$sql .= 'to_days(E.EndTime)';
break;
case 'EndTime':
$sql .= 'extract(hour_second FROM E.EndTime)';
break;
case 'EndWeekday':
$sql .= 'weekday(E.EndTime)';
break;
case 'Id':
case 'Name':
case 'DiskSpace':
case 'MonitorId':
case 'StorageId':
case 'SecondaryStorageId':
case 'Length':
case 'Frames':
case 'AlarmFrames':
case 'TotScore':
case 'AvgScore':
case 'MaxScore':
case 'Cause':
case 'Notes':
case 'StateId':
case 'Archived':
$sql .= 'E.'.$this->attr;
}
$sql .= $this->sql_operator();
$values = $this->sql_values();
if ( count($values) > 1 ) {
$sql .= '('.join(',', $values).')';
} else {
$sql .= $values[0];
}
if ( isset($this->cbr) ) {
$sql .= ' '.str_repeat(')', $this->cbr).' ';
}
return $sql;
} # end public function sql
public function querystring($querySep='&amp;') {
# We don't validate the term parameters here
$query = '';
if ( $this->cnj )
$query .= $querySep.urlencode('filter[Query][terms]['.$this->index.'][cnj]').'='.$this->cnj;
if ( $this->obr )
$query .= $querySep.urlencode('filter[Query][terms]['.$this->index.'][obr]').'='.$this->obr;
$query .= $querySep.urlencode('filter[Query][terms]['.$this->index.'][attr]').'='.urlencode($this->attr);
$query .= $querySep.urlencode('filter[Query][terms]['.$this->index.'][op]').'='.urlencode($this->op);
$query .= $querySep.urlencode('filter[Query][terms]['.$this->index.'][val]').'='.urlencode($this->val);
if ( $this->cbr )
$query .= $querySep.urlencode('filter[Query][terms]['.$this->index.'][cbr]').'='.$this->cbr;
return $query;
} # end public function querystring
public function hidden_fields() {
$html ='';
if ( $this->cnj )
$html .= '<input type="hidden" name="filter[Query][terms]['.$this->index.'][cnj]" value="'.$this->cnj.'"/>'.PHP_EOL;
if ( $this->obr )
$html .= '<input type="hidden" name="filter[Query][terms]['.$this->index.'][obr]" value="'.$this->obr.'"/>'.PHP_EOL;
# attr should have been already validation, so shouldn't need htmlspecialchars
$html .= '<input type="hidden" name="filter[Query][terms]['.$this->index.'][attr]" value="'.htmlspecialchars($this->attr).'"/>'.PHP_EOL;
$html .= '<input type="hidden" name="filter[Query][terms]['.$this->index.'][op]" value="'.htmlspecialchars($this->op).'"/>'.PHP_EOL;
$html .= '<input type="hidden" name="filter[Query][terms]['.$this->index.'][val]" value="'.htmlspecialchars($this->val).'"/>'.PHP_EOL;
if ( $this->cbr )
$html .= '<input type="hidden" name="filter[Query][terms]['.$this->index.'][cbr]" value="'.$this->cbr.'"/>'.PHP_EOL;
return $html;
} # end public function hiddens_fields
public function test($event=null) {
if ( !isset($event) ) {
# Is a Pre Condition
if ( $this->attr == 'DiskPercent' ) {
# The logic on this is really ugly. We are going to treat it as an OR
foreach ( $this->filter->get_StorageAreas() as $storage ) {
$string_to_eval = 'return $storage->disk_usage_percent() '.$this->op.' '.$this->val.';';
try {
$ret = eval($string_to_eval);
Logger::Debug("Evalled $string_to_eval = $ret");
if ( $ret )
return true;
} catch ( Throwable $t ) {
Error('Failed evaluating '.$string_to_eval);
return false;
}
} # end foreach Storage Area
} else if ( $this->attr == 'SystemLoad' ) {
$string_to_eval = 'return getLoad() '.$this->op.' '.$this->val.';';
try {
$ret = eval($string_to_eval);
Logger::Debug("Evalled $string_to_eval = $ret");
if ( $ret )
return true;
} catch ( Throwable $t ) {
Error('Failed evaluating '.$string_to_eval);
return false;
}
} else {
Error('testing unsupported pre term ' . $this->attr);
}
} else {
# Is a Post Condition
if ( $this->attr == 'ExistsInFileSystem' ) {
if (
($this->op == 'IS' and $this->val == 'True')
or
($this->op == 'IS NOT' and $this->val == 'False')
) {
return file_exists($event->Path());
} else {
return !file_exists($event->Path());
}
} else if ( $this->attr == 'DiskPercent' ) {
$string_to_eval = 'return $event->Storage()->disk_usage_percent() '.$this->op.' '.$this->val.';';
try {
$ret = eval($string_to_eval);
Logger::Debug("Evalled $string_to_eval = $ret");
if ( $ret )
return true;
} catch ( Throwable $t ) {
Error('Failed evaluating '.$string_to_eval);
return false;
}
} else if ( $this->attr == 'DiskBlocks' ) {
$string_to_eval = 'return $event->Storage()->disk_usage_blocks() '.$this->op.' '.$this->val.';';
try {
$ret = eval($string_to_eval);
Logger::Debug("Evalled $string_to_eval = $ret");
if ( $ret )
return true;
} catch ( Throwable $t ) {
Error('Failed evaluating '.$string_to_eval);
return false;
}
} else {
Error('testing unsupported post term ' . $this->attr);
}
}
return false;
}
public function is_pre_sql() {
if ( $this->attr == 'DiskPercent' ) {
return true;
}
return false;
}
public function is_post_sql() {
if ( $this->attr == 'ExistsInFileSystem' ) {
return true;
} else if ( $this->attr == 'DiskPercent' ) {
return true;
}
return false;
}
} # end class FilterTerm
?>

View File

@ -205,11 +205,19 @@ class Monitor extends ZM_Object {
if ( ZM_RAND_STREAM ) { if ( ZM_RAND_STREAM ) {
$args['rand'] = time(); $args['rand'] = time();
} }
foreach ( array('scale') as $int_arg ) {
if ( isset($args[$int_arg]) and (!is_numeric($args[$int_arg]) or !$args[$int_arg] ) ) { # zms doesn't support width & height, so if no scale is set, default it
unset($args[$int_arg]); if ( ! isset($args['scale']) ) {
if ( isset($args['width']) and intval($args['width']) ) {
$args['scale'] = intval((100*intval($args['width']))/$this->ViewWidth());
} else if ( isset($args['height']) and intval($args['height']) ) {
$args['scale'] = intval((100*intval($args['height']))/$this->ViewHeight());
} }
} }
if ( isset($args['width']) )
unset($args['width']);
if ( isset($args['height']) )
unset($args['height']);
$streamSrc .= '?'.http_build_query($args, '', $querySep); $streamSrc .= '?'.http_build_query($args, '', $querySep);

View File

@ -106,7 +106,6 @@ class Server extends ZM_Object {
if ( $this->Protocol() == 'https' and $port == 443 ) { if ( $this->Protocol() == 'https' and $port == 443 ) {
} else if ( $this->Protocol() == 'http' and $port == 80 ) { } else if ( $this->Protocol() == 'http' and $port == 80 ) {
} else { } else {
Logger::Debug("Adding port $port for " . $this->Protocol());
$url .= ':'.$port; $url .= ':'.$port;
} }
return $url; return $url;

View File

@ -69,6 +69,14 @@ class Storage extends ZM_Object {
return $this->{'EventCount'}; return $this->{'EventCount'};
} }
public function disk_used_blocks() {
$df = shell_exec('df '.escapeshellarg($this->Path()));
$space = -1;
if ( preg_match('/\s(\d+)\s+\d+\s+\d+%/ms', $df, $matches) )
$space = $matches[1];
return $space;
}
public function disk_usage_percent() { public function disk_usage_percent() {
$path = $this->Path(); $path = $this->Path();
if ( ! $path ) { if ( ! $path ) {
@ -106,7 +114,7 @@ class Storage extends ZM_Object {
public function disk_used_space() { public function disk_used_space() {
# This isn't a function like this in php, so we have to add up the space used in each event. # This isn't a function like this in php, so we have to add up the space used in each event.
if ( ( !property_exists($this, 'disk_used_space')) or !$this->{'disk_used_space'} ) { if ( ( !property_exists($this, 'disk_used_space')) or !$this->{'disk_used_space'} ) {
if ( $this->{'Type'} == 's3fs' ) { if ( $this->Type() == 's3fs' ) {
$this->{'disk_used_space'} = $this->event_disk_space(); $this->{'disk_used_space'} = $this->event_disk_space();
} else { } else {
$path = $this->Path(); $path = $this->Path();

View File

@ -31,14 +31,18 @@ if ( !canEdit('Events') ) {
if ( $action == 'archive' ) { if ( $action == 'archive' ) {
$dbConn->beginTransaction(); $dbConn->beginTransaction();
foreach( getAffectedIds('eids') as $markEid ) { $eids = getAffectedIds('eids');
ZM\Logger::Debug("E IDS" . print_r($eids, true));
foreach ( $eids as $markEid ) {
dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(1, $markEid)); dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(1, $markEid));
} }
$dbConn->commit(); $dbConn->commit();
$refreshParent = true; $refreshParent = true;
} else if ( $action == 'unarchive' ) { } else if ( $action == 'unarchive' ) {
$dbConn->beginTransaction(); $dbConn->beginTransaction();
foreach( getAffectedIds('eids') as $markEid ) { $eids = getAffectedIds('eids');
ZM\Logger::Debug("E IDS" . print_r($eids, true));
foreach ( $eids as $markEid ) {
dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(0, $markEid)); dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(0, $markEid));
} }
$dbConn->commit(); $dbConn->commit();
@ -48,5 +52,7 @@ if ( $action == 'archive' ) {
deleteEvent($markEid); deleteEvent($markEid);
} }
$refreshParent = true; $refreshParent = true;
} else {
ZM\Warning("Unsupported action $action in events");
} }
?> ?>

View File

@ -21,9 +21,10 @@
if ( $action == 'logout' ) { if ( $action == 'logout' ) {
userLogout(); userLogout();
$refreshParent = true; $view = 'login';
$view = 'none';
$closePopup = true;
ZM\Logger::Debug("User: " . print_r($user,true)); ZM\Logger::Debug("User: " . print_r($user,true));
} elseif ( $action == 'config' ) {
$redirect = '?view=user&uid='.$user['Id'];
} }
?> ?>

View File

@ -260,6 +260,22 @@ function userFromSession() {
return $user; return $user;
} }
function get_auth_relay() {
if ( ZM_OPT_USE_AUTH ) {
if ( ZM_AUTH_RELAY == 'hashed' ) {
return 'auth='.generateAuthHash(ZM_AUTH_HASH_IPS);
} else if ( ZM_AUTH_RELAY == 'plain' ) {
// password probably needs to be escaped
return 'username='.$_SESSION['username'].'&password='.urlencode($_SESSION['password']);
} else if ( ZM_AUTH_RELAY == 'none' ) {
return 'username='.$_SESSION['username'];
} else {
ZM\Error('Unknown value for ZM_AUTH_RELAY ' . ZM_AUTH_RELAY);
}
}
return '';
} // end function get_auth_relay
if ( ZM_OPT_USE_AUTH ) { if ( ZM_OPT_USE_AUTH ) {
if ( !empty($_REQUEST['token']) ) { if ( !empty($_REQUEST['token']) ) {
// we only need to get the username here // we only need to get the username here

View File

@ -47,15 +47,15 @@ $configvals = process_configfile($configFile);
$configSubFolder = ZM_CONFIG_SUBDIR; $configSubFolder = ZM_CONFIG_SUBDIR;
if ( is_dir($configSubFolder) ) { if ( is_dir($configSubFolder) ) {
if ( is_readable($configSubFolder) ) { if ( is_readable($configSubFolder) ) {
foreach ( glob("$configSubFolder/*.conf") as $filename ) { foreach ( glob($configSubFolder.'/*.conf') as $filename ) {
//error_log("processing $filename"); //error_log("processing $filename");
$configvals = array_replace($configvals, process_configfile($filename)); $configvals = array_replace($configvals, process_configfile($filename));
} }
} else { } else {
error_log("WARNING: ZoneMinder configuration subfolder found but is not readable. Check folder permissions on $configSubFolder."); error_log('WARNING: ZoneMinder configuration subfolder found but is not readable. Check folder permissions on '.$configSubFolder);
} }
} else { } else {
error_log("WARNING: ZoneMinder configuration subfolder found but is not a directory. Check $configSubFolder."); error_log('WARNING: ZoneMinder configuration subfolder found but is not a directory. Check '.$configSubFolder);
} }
# Now that our array our finalized, define each key => value # Now that our array our finalized, define each key => value
@ -166,10 +166,18 @@ function loadConfig( $defineConsts=true ) {
if ( !$result ) if ( !$result )
echo mysql_error(); echo mysql_error();
while( $row = dbFetchNext($result) ) { while( $row = dbFetchNext($result) ) {
if ( $defineConsts )
define($row['Name'], $row['Value']);
$config[$row['Name']] = $row; $config[$row['Name']] = $row;
if ( $defineConsts ) {
# Values in conf.d files override db so check if already defined and update value
if ( ! defined($row['Name']) ) {
define($row['Name'], $row['Value']);
} else {
$config[$row['Name']]['Value'] = constant($row['Name']);
} }
}
}
return $config;
} # end function loadConfig } # end function loadConfig
// For Human-readability, use ZM_SERVER_HOST or ZM_SERVER_NAME in zm.conf, and convert it here to a ZM_SERVER_ID // For Human-readability, use ZM_SERVER_HOST or ZM_SERVER_NAME in zm.conf, and convert it here to a ZM_SERVER_ID
@ -200,7 +208,7 @@ function process_configfile($configFile) {
if ( is_readable($configFile) ) { if ( is_readable($configFile) ) {
$configvals = array(); $configvals = array();
$cfg = fopen($configFile, 'r') or ZM\Error("Could not open config file: $configFile."); $cfg = fopen($configFile, 'r') or ZM\Error('Could not open config file: '.$configFile);
while ( !feof($cfg) ) { while ( !feof($cfg) ) {
$str = fgets($cfg, 256); $str = fgets($cfg, 256);
if ( preg_match('/^\s*(#.*)?$/', $str) ) { if ( preg_match('/^\s*(#.*)?$/', $str) ) {
@ -214,7 +222,7 @@ function process_configfile($configFile) {
fclose($cfg); fclose($cfg);
return $configvals; return $configvals;
} else { } else {
error_log("WARNING: ZoneMinder configuration file found but is not readable. Check file permissions on $configFile."); error_log('WARNING: ZoneMinder configuration file found but is not readable. Check file permissions on '.$configFile);
return false; return false;
} }
} }

View File

@ -389,7 +389,7 @@ function csrf_conf($key, $val) {
*/ */
function csrf_start() { function csrf_start() {
if ($GLOBALS['csrf']['auto-session'] && !session_id()) { if ($GLOBALS['csrf']['auto-session'] && !session_id()) {
session_start(); zm_session_start();
} }
} }

View File

@ -153,10 +153,7 @@ function dbQuery($sql, $params=NULL) {
} }
} }
if ( defined('ZM_DB_DEBUG') ) { if ( defined('ZM_DB_DEBUG') ) {
if ( $params ) ZM\Logger::Debug('SQL: '.$sql.' '.($params?implode(',',$params):'').' rows: '.$result->rowCount());
ZM\Logger::Debug("SQL: $sql " . implode(',',$params) . ' rows: '.$result->rowCount());
else
ZM\Logger::Debug("SQL: $sql: rows:" . $result->rowCount());
} }
} catch(PDOException $e) { } catch(PDOException $e) {
ZM\Error("SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):'')); ZM\Error("SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):''));

View File

@ -17,6 +17,9 @@
// along with this program; if not, write to the Free Software // along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// //
//
require_once('Filter.php');
require_once('FilterTerm.php');
// Compatibility functions // Compatibility functions
if ( version_compare(phpversion(), '4.3.0', '<') ) { if ( version_compare(phpversion(), '4.3.0', '<') ) {
@ -846,7 +849,6 @@ function daemonStatus($daemon, $args=false) {
if ( $args ) { if ( $args ) {
if ( is_array($args) ) { if ( is_array($args) ) {
$string .= join(' ', $args); $string .= join(' ', $args);
ZM\Warning("daemonStatus args: $string");
} else { } else {
$string .= ' ' . $args; $string .= ' ' . $args;
} }
@ -1087,288 +1089,24 @@ function parseSort($saveToSession=false, $querySep='&amp;') {
} }
} }
function getFilterQueryConjunctionTypes() { # Historically this function has just modified the passed in filter array.
return array( # This would normally be $_REQUEST['filter']; We don't like modifying
'and' => translate('ConjAnd'), # request parameters. For now we will keep this behaviour, but note that we
'or' => translate('ConjOr') # now return the resulting array and other code should by modified to use that.
); #
} # Please note that I will be removing the savetosession code as well.
function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') { function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
$filter['query'] = '';
$filter['sql'] = '';
$filter['fields'] = '';
$validQueryConjunctionTypes = getFilterQueryConjunctionTypes(); $Filter = ZM\Filter::parse($filter, $querySep);
$StorageArea = NULL;
# It is not possible to pass an empty array in the url, so we have to deal with there not being a terms field. $filter['sql'] = $Filter->sql();
$terms = (isset($filter['Query']) and isset($filter['Query']['terms']) and is_array($filter['Query']['terms'])) ? $filter['Query']['terms'] : array(); $filter['querystring'] = $Filter->querystring();
$filter['hidden_fields'] = $Filter->hidden_fields();
$filter['pre_sql_conditions'] = $Filter->pre_sql_conditions();
$filter['post_sql_conditions'] = $Filter->post_sql_conditions();
if ( count($terms) ) {
for ( $i = 0; $i < count($terms); $i++ ) {
$term = $terms[$i];
if ( isset($term['cnj']) && array_key_exists($term['cnj'], $validQueryConjunctionTypes) ) {
$filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][cnj]").'='.urlencode($term['cnj']);
$filter['sql'] .= ' '.$term['cnj'].' ';
$filter['fields'] .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][cnj]\" value=\"".htmlspecialchars($term['cnj'])."\"/>\n";
}
if ( isset($term['obr']) && (string)(int)$term['obr'] == $term['obr'] ) {
$filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][obr]").'='.urlencode($term['obr']);
$filter['sql'] .= ' '.str_repeat('(', $term['obr']).' ';
$filter['fields'] .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][obr]\" value=\"".htmlspecialchars($term['obr'])."\"/>\n";
}
if ( isset($term['attr']) ) {
$filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][attr]").'='.urlencode($term['attr']);
$filter['fields'] .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][attr]\" value=\"".htmlspecialchars($term['attr'])."\"/>\n";
switch ( $term['attr'] ) {
case 'AlarmedZoneId':
$term['op'] = 'EXISTS';
break;
case 'MonitorName':
$filter['sql'] .= 'M.Name';
break;
case 'ServerId':
case 'MonitorServerId':
$filter['sql'] .= 'M.ServerId';
break;
case 'StorageServerId':
$filter['sql'] .= 'S.ServerId';
break;
case 'FilterServerId':
$filter['sql'] .= ZM_SERVER_ID;
break;
# Unspecified start or end, so assume start, this is to support legacy filters
case 'DateTime':
$filter['sql'] .= 'E.StartTime';
break;
case 'Date':
$filter['sql'] .= 'to_days(E.StartTime)';
break;
case 'Time':
$filter['sql'] .= 'extract(hour_second FROM E.StartTime)';
break;
case 'Weekday':
$filter['sql'] .= 'weekday(E.StartTime)';
break;
# Starting Time
case 'StartDateTime':
$filter['sql'] .= 'E.StartTime';
break;
case 'FramesEventId':
$filter['sql'] .= 'F.EventId';
break;
case 'StartDate':
$filter['sql'] .= 'to_days(E.StartTime)';
break;
case 'StartTime':
$filter['sql'] .= 'extract(hour_second FROM E.StartTime)';
break;
case 'StartWeekday':
$filter['sql'] .= 'weekday(E.StartTime)';
break;
# Ending Time
case 'EndDateTime':
$filter['sql'] .= 'E.EndTime';
break;
case 'EndDate':
$filter['sql'] .= 'to_days(E.EndTime)';
break;
case 'EndTime':
$filter['sql'] .= 'extract(hour_second FROM E.EndTime)';
break;
case 'EndWeekday':
$filter['sql'] .= 'weekday(E.EndTime)';
break;
case 'Id':
case 'Name':
case 'DiskSpace':
case 'MonitorId':
case 'StorageId':
case 'SecondaryStorageId':
case 'Length':
case 'Frames':
case 'AlarmFrames':
case 'TotScore':
case 'AvgScore':
case 'MaxScore':
case 'Cause':
case 'Notes':
case 'StateId':
case 'Archived':
$filter['sql'] .= 'E.'.$term['attr'];
break;
case 'DiskPercent':
// Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH
if ( ! $StorageArea ) {
for ( $j = 0; $j < count($terms); $j++ ) {
if (
isset($terms[$j]['attr'])
and
($terms[$j]['attr'] == 'StorageId')
and
isset($terms[$j]['val'])
) {
$StorageArea = ZM\Storage::find_one(array('Id'=>$terms[$j]['val']));
break;
}
} // end foreach remaining term
if ( ! $StorageArea ) $StorageArea = new ZM\Storage();
} // end no StorageArea found yet
$filter['sql'] .= getDiskPercent($StorageArea->Path());
break;
case 'DiskBlocks':
// Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH
if ( ! $StorageArea ) {
for ( $j = $i; $j < count($terms); $j++ ) {
if (
isset($terms[$j]['attr'])
and
($terms[$j]['attr'] == 'StorageId')
and
isset($terms[$j]['val'])
) {
$StorageArea = ZM\Storage::find_one(array('Id'=>$terms[$j]['val']));
}
} // end foreach remaining term
} // end no StorageArea found yet
$filter['sql'] .= getDiskBlocks( $StorageArea );
break;
case 'SystemLoad':
$filter['sql'] .= getLoad();
break;
}
$valueList = array();
if ( !isset($term['val']) ) $term['val'] = '';
foreach ( preg_split('/["\'\s]*?,["\'\s]*?/', preg_replace('/^["\']+?(.+)["\']+?$/', '$1', $term['val'])) as $value ) {
switch ( $term['attr'] ) {
case 'AlarmedZoneId':
$value = '(SELECT * FROM Stats WHERE EventId=E.Id AND ZoneId='.$value.')';
break;
case 'MonitorName':
case 'Name':
case 'Cause':
case 'Notes':
if ( $term['op'] == 'LIKE' || $term['op'] == 'NOT LIKE' ) {
$value = '%'.$value.'%';
}
$value = dbEscape($value);
break;
case 'MonitorServerId':
case 'FilterServerId':
case 'StorageServerId':
case 'ServerId':
if ( $value == 'ZM_SERVER_ID' ) {
$value = ZM_SERVER_ID;
} else if ( $value == 'NULL' ) {
} else {
$value = dbEscape($value);
}
break;
case 'StorageId':
$StorageArea = ZM\Storage::find_one(array('Id'=>$value));
if ( $value != 'NULL' )
$value = dbEscape($value);
break;
case 'DateTime':
case 'StartDateTime':
case 'EndDateTime':
if ( $value != 'NULL' )
$value = '\''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\'';
break;
case 'Date':
case 'StartDate':
case 'EndDate':
if ( $value == 'CURDATE()' or $value == 'NOW()' ) {
$value = 'to_days('.$value.')';
} else if ( $value != 'NULL' ) {
$value = 'to_days(\''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\')';
}
break;
case 'Time':
case 'StartTime':
case 'EndTime':
if ( $value != 'NULL' )
$value = 'extract(hour_second from \''.strftime(STRF_FMT_DATETIME_DB, strtotime($value)).'\')';
break;
default :
if ( $value != 'NULL' )
$value = dbEscape($value);
break;
}
$valueList[] = $value;
} // end foreach value
switch ( $term['op'] ) {
case '=' :
case '!=' :
case '>=' :
case '>' :
case '<' :
case '<=' :
case 'LIKE' :
case 'NOT LIKE':
$filter['sql'] .= ' '.$term['op'].' '. $value;
break;
case '=~' :
$filter['sql'] .= ' regexp '.$value;
break;
case '!~' :
$filter['sql'] .= ' not regexp '.$value;
break;
case '=[]' :
case 'IN' :
$filter['sql'] .= ' IN ('.join(',', $valueList).')';
break;
case '![]' :
$filter['sql'] .= ' not in ('.join(',', $valueList).')';
break;
case 'EXISTS' :
$filter['sql'] .= ' EXISTS ' .$value;
break;
case 'IS' :
if ( $value == 'Odd' ) {
$filter['sql'] .= ' % 2 = 1';
} else if ( $value == 'Even' ) {
$filter['sql'] .= ' % 2 = 0';
} else {
$filter['sql'] .= " IS $value";
}
break;
case 'IS NOT' :
$filter['sql'] .= " IS NOT $value";
break;
default:
ZM\Warning('Invalid operator in filter: ' . print_r($term['op'], true));
} // end switch op
$filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][op]").'='.urlencode($term['op']);
$filter['fields'] .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][op]\" value=\"".htmlspecialchars($term['op'])."\"/>\n";
if ( isset($term['val']) ) {
$filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][val]").'='.urlencode($term['val']);
$filter['fields'] .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][val]\" value=\"".htmlspecialchars($term['val'])."\"/>\n";
}
} // end if isset($term['attr'])
if ( isset($term['cbr']) && (string)(int)$term['cbr'] == $term['cbr'] ) {
$filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][cbr]").'='.urlencode($term['cbr']);
$filter['sql'] .= ' '.str_repeat(')', $term['cbr']);
$filter['fields'] .= "<input type=\"hidden\" name=\"filter[Query][terms][$i][cbr]\" value=\"".htmlspecialchars($term['cbr'])."\"/>\n";
}
} // end foreach term
if ( $filter['sql'] ) if ( $filter['sql'] )
$filter['sql'] = ' AND ( '.$filter['sql'].' )'; $filter['sql'] = ' AND ( '.$filter['sql'].' )';
if ( $saveToSession ) {
$_SESSION['filter'] = $filter;
}
} else {
$filter['query'] = $querySep;
#.urlencode('filter[Query][terms]=[]');
} // end if terms
#if ( 0 ) { #if ( 0 ) {
#// ICON I feel like these should be here, but not yet #// ICON I feel like these should be here, but not yet
@ -1376,10 +1114,8 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
#$filter['sql'] .= ' ORDER BY ' . $filter['Query']['sort_field'] . ( #$filter['sql'] .= ' ORDER BY ' . $filter['Query']['sort_field'] . (
#( $filter['Query']['sort_asc'] ? ' ASC' : ' DESC' ) ); #( $filter['Query']['sort_asc'] ? ' ASC' : ' DESC' ) );
#} #}
#if ( $filter['Query']['limit'] ) {
#$filter['sql'] .= ' LIMIT ' . validInt($filter['Query']['limit']);
#}
#} #}
return $filter;
} // end function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') } // end function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;')
// Please note that the filter is passed in by copy, so you need to use the return value from this function. // Please note that the filter is passed in by copy, so you need to use the return value from this function.
@ -1490,11 +1226,13 @@ function sortHeader($field, $querySep='&amp;') {
} }
function sortTag($field) { function sortTag($field) {
if ( isset($_REQUEST['sort_field']) ) {
if ( $_REQUEST['sort_field'] == $field ) if ( $_REQUEST['sort_field'] == $field )
if ( $_REQUEST['sort_asc'] ) if ( $_REQUEST['sort_asc'] )
return '(^)'; return '(^)';
else else
return '(v)'; return '(v)';
}
return false; return false;
} }
@ -1520,9 +1258,8 @@ function getDiskPercent($path = ZM_DIR_EVENTS) {
return $space; return $space;
} }
function getDiskBlocks() { function getDiskBlocks($path = ZM_DIR_EVENTS) {
if ( !$StorageArea ) $StorageArea = new ZM\Storage(); $df = shell_exec('df '.escapeshellarg($path));
$df = shell_exec('df '.escapeshellarg($StorageArea->Path()));
$space = -1; $space = -1;
if ( preg_match('/\s(\d+)\s+\d+\s+\d+%/ms', $df, $matches) ) if ( preg_match('/\s(\d+)\s+\d+\s+\d+%/ms', $df, $matches) )
$space = $matches[1]; $space = $matches[1];
@ -2314,27 +2051,50 @@ function validHtmlStr($input) {
return htmlspecialchars($input, ENT_QUOTES); return htmlspecialchars($input, ENT_QUOTES);
} }
/* options['width'] is the desired view width not necessarily the image width requested.
* It can be % in which case we us it to set the scale
* It can be px in which case we can use it to calculate the scale
* Same width height. If both are set we should calculate the smaller resulting scale
*/
function getStreamHTML($monitor, $options = array()) { function getStreamHTML($monitor, $options = array()) {
ZM\Warning(print_r($options, true));
if ( isset($options['scale']) ) { if ( isset($options['scale']) and $options['scale'] != '' ) {
if ( $options['scale'] != 'auto' && $options['scale'] != '0' and $options['scale'] != '' ) { if ( $options['scale'] != 'auto' && $options['scale'] != '0' ) {
ZM\Logger::Debug("Setting dimensions from scale:".$options['scale']); ZM\Warning("Setting dimensions from scale:".$options['scale']);
$options['width'] = reScale($monitor->ViewWidth(), $options['scale']).'px'; $options['width'] = reScale($monitor->ViewWidth(), $options['scale']).'px';
$options['height'] = reScale($monitor->ViewHeight(), $options['scale']).'px'; $options['height'] = reScale($monitor->ViewHeight(), $options['scale']).'px';
} else { } else if ( ! ( isset($options['width']) or isset($options['height']) ) ) {
$options['width'] = '100%'; $options['width'] = '100%';
$options['height'] = 'auto'; $options['height'] = 'auto';
} }
} else { } else {
$options['scale'] = 100;
# scale is empty or 100 # scale is empty or 100
# There may be a fixed width applied though, in which case we need to leave the height empty # There may be a fixed width applied though, in which case we need to leave the height empty
if ( ! ( isset($options['width']) and $options['width'] ) ) { if ( ! ( isset($options['width']) and $options['width'] ) ) {
$options['width'] = $monitor->ViewWidth().'px'; # Havn't specified width. If we specified height, then we should
# use a width that keeps the aspect ratio, otherwise no scaling,
# no dimensions, so assume the dimensions of the Monitor
if ( ! (isset($options['height']) and $options['height']) ) { if ( ! (isset($options['height']) and $options['height']) ) {
$options['width'] = $monitor->ViewWidth().'px';
$options['height'] = $monitor->ViewHeight().'px'; $options['height'] = $monitor->ViewHeight().'px';
} }
} else if ( ! isset($options['height']) ) { } else {
$options['height'] = ''; ZM\Warning("Have width ".$options['width']);
if ( preg_match('/^(\d+)px$/', $options['width'], $matches) ) {
$scale = intval(100*$matches[1]/$monitor->ViewWidth());
ZM\Warning("Scale is $scale");
if ( $scale < $options['scale'] )
$options['scale'] = $scale;
} else if ( preg_match('/^(\d+)%$/', $options['width'], $matches) ) {
$scale = intval($matches[1]);
if ( $scale < $options['scale'] )
$options['scale'] = $scale;
} else {
Warning("Invalid value for width: ".$options['width']);
}
} }
} }
if ( ! isset($options['mode'] ) ) { if ( ! isset($options['mode'] ) ) {

View File

@ -53,7 +53,7 @@ require_once('includes/Group.php');
require_once('includes/Monitor.php'); require_once('includes/Monitor.php');
// Useful debugging lines for mobile devices // Useful debugging lines for mobile devices
if ( ZM\Logger::fetch()->debugOn() ) { if ( 0 and ZM\Logger::fetch()->debugOn() ) {
ob_start(); ob_start();
phpinfo(INFO_VARIABLES); phpinfo(INFO_VARIABLES);
ZM\Logger::Debug(ob_get_contents()); ZM\Logger::Debug(ob_get_contents());

View File

@ -343,6 +343,7 @@ $SLANG = array(
'Export' => 'Export', 'Export' => 'Export',
'DownloadVideo' => 'Download Video', 'DownloadVideo' => 'Download Video',
'GenerateDownload' => 'Generate Download', 'GenerateDownload' => 'Generate Download',
'ExistsInFileSystem' => 'Exists In File System',
'ExportFailed' => 'Export Failed', 'ExportFailed' => 'Export Failed',
'ExportFormat' => 'Export File Format', 'ExportFormat' => 'Export File Format',
'ExportFormatTar' => 'Tar', 'ExportFormatTar' => 'Tar',

View File

@ -476,6 +476,15 @@ th.table-th-sort-rev span.table-th-sort-span {
color: white; color: white;
font-weight: 300; font-weight: 300;
} }
#header:after {
content: ".";
display: block;
height: 0;
font-size: 0;
clear: both;
visibility: hidden;
}
#header h2 { #header h2 {
left: 0; left: 0;
@ -742,3 +751,18 @@ li.search-choice {
transform: scale(5); /* (arbitray zoom value - Note if the zoom is too large, it will go outside of the viewport) */ transform: scale(5); /* (arbitray zoom value - Note if the zoom is too large, it will go outside of the viewport) */
} }
.zoom-right {
padding: 0px;
transition: transform .2s; /* Animation */
margin: 0 auto;
}
.zoom-right:hover {
transform-origin: 0% 50%;
transform: scale(5); /* (arbitray zoom value - Note if the zoom is too large, it will go outside of the viewport) */
}
a.flip {
float: right;
margin-right: -20px;
}

View File

@ -528,12 +528,18 @@ input[type=submit]:disabled,
margin-left: 0; margin-left: 0;
} }
.table {
width: 100%;
margin-bottom: 1rem;
color: #eeeeee;
}
.table-striped > tbody > tr:nth-of-type(2n+1) { .table-striped > tbody > tr:nth-of-type(2n+1) {
background-color: #333333; background-color: #333333;
} }
.table-hover > tbody > tr:hover { .table-hover > tbody > tr:hover {
background-color: #444444; background-color: orange;
} }
.nav-pills>li.active>a, .nav-pills>li.active>a:focus, .nav-pills>li.active>a:hover { .nav-pills>li.active>a, .nav-pills>li.active>a:focus, .nav-pills>li.active>a:hover {

View File

@ -88,6 +88,7 @@ echo output_cache_busted_stylesheet_links(array(
'css/font-awesome.min.css', 'css/font-awesome.min.css',
'css/bootstrap.min.css', 'css/bootstrap.min.css',
'css/bootstrap-table.min.css', 'css/bootstrap-table.min.css',
'css/bootstrap-table-page-jump-to.min.css',
)); ));
echo output_link_if_exists(array( echo output_link_if_exists(array(
@ -133,6 +134,9 @@ if ( $css != 'base' )
<script src="skins/<?php echo $skin; ?>/js/jquery-ui-1.12.1/jquery-ui.js"></script> <script src="skins/<?php echo $skin; ?>/js/jquery-ui-1.12.1/jquery-ui.js"></script>
<script src="skins/<?php echo $skin; ?>/js/bootstrap.min.js"></script> <script src="skins/<?php echo $skin; ?>/js/bootstrap.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/bootstrap-table.min.js"></script> <script src="skins/<?php echo $skin; ?>/js/bootstrap-table.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/tableExport.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/bootstrap-table-export.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/bootstrap-table-page-jump-to.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/bootstrap-table-cookie.min.js"></script> <script src="skins/<?php echo $skin; ?>/js/bootstrap-table-cookie.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/chosen/chosen.jquery.min.js"></script> <script src="skins/<?php echo $skin; ?>/js/chosen/chosen.jquery.min.js"></script>
<script src="skins/<?php echo $skin; ?>/js/dateTimePicker/jquery-ui-timepicker-addon.js"></script> <script src="skins/<?php echo $skin; ?>/js/dateTimePicker/jquery-ui-timepicker-addon.js"></script>
@ -227,24 +231,14 @@ function getNavBarHTML() {
global $user; global $user;
global $bandwidth_options; global $bandwidth_options;
global $view; global $view;
global $filterQuery; global $skin;
global $sortQuery;
global $limitQuery;
if ( !$sortQuery ) {
parseSort();
}
if ( (!$filterQuery) and isset($_REQUEST['filter']) ) {
parseFilter($_REQUEST['filter']);
$filterQuery = $_REQUEST['filter']['query'];
}
ob_start(); ob_start();
if ( ZM_WEB_NAVBAR_TYPE == "normal" ) { if ( ZM_WEB_NAVBAR_TYPE == "normal" ) {
echo getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $filterQuery, $sortQuery, $limitQuery); echo getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $skin);
} else { } else {
echo getCollapsedNavBarHTML($running, $user, $bandwidth_options, $view, $filterQuery, $sortQuery, $limitQuery); echo getCollapsedNavBarHTML($running, $user, $bandwidth_options, $view, $skin);
} }
return ob_get_clean(); return ob_get_clean();
@ -253,7 +247,7 @@ function getNavBarHTML() {
// //
// The legacy navigation bar that collapses into a pulldown menu on small screens. // The legacy navigation bar that collapses into a pulldown menu on small screens.
// //
function getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $filterQuery, $sortQuery, $limitQuery) { function getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $skin) {
$status = runtimeStatus($running); $status = runtimeStatus($running);
@ -284,7 +278,7 @@ function getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $filter
echo getLogHTML(); echo getLogHTML();
echo getDevicesHTML(); echo getDevicesHTML();
echo getGroupsHTML($view); echo getGroupsHTML($view);
echo getFilterHTML($view, $filterQuery, $sortQuery, $limitQuery); echo getFilterHTML($view);
echo getCycleHTML($view); echo getCycleHTML($view);
echo getMontageHTML($view); echo getMontageHTML($view);
echo getMontageReviewHTML($view); echo getMontageReviewHTML($view);
@ -293,7 +287,7 @@ function getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $filter
echo '</ul>'; echo '</ul>';
echo '<ul class="nav navbar-nav justify-content-end align-self-start flex-grow-1">'; echo '<ul class="nav navbar-nav justify-content-end align-self-start flex-grow-1">';
echo getAcctCircleHTML($user); echo getAcctCircleHTML($skin, $user);
echo getStatusBtnHTML($status); echo getStatusBtnHTML($status);
echo '</ul>'; echo '</ul>';
} }
@ -344,7 +338,7 @@ function getNormalNavBarHTML($running, $user, $bandwidth_options, $view, $filter
// //
// A new, slimmer navigation bar, permanently collapsed into a dropdown // A new, slimmer navigation bar, permanently collapsed into a dropdown
// //
function getCollapsedNavBarHTML($running, $user, $bandwidth_options, $view, $filterQuery, $sortQuery, $limitQuery) { function getCollapsedNavBarHTML($running, $user, $bandwidth_options, $view, $skin) {
$status = runtimeStatus($running); $status = runtimeStatus($running);
@ -390,7 +384,7 @@ function getCollapsedNavBarHTML($running, $user, $bandwidth_options, $view, $fil
<ul class="list-group list-group-horizontal ml-auto"> <ul class="list-group list-group-horizontal ml-auto">
<?php <?php
echo getAcctCircleHTML($user); echo getAcctCircleHTML($skin, $user);
echo getStatusBtnHTML($status); echo getStatusBtnHTML($status);
?> ?>
</ul> </ul>
@ -413,7 +407,7 @@ function getCollapsedNavBarHTML($running, $user, $bandwidth_options, $view, $fil
echo getLogHTML(); echo getLogHTML();
echo getDevicesHTML(); echo getDevicesHTML();
echo getGroupsHTML($view); echo getGroupsHTML($view);
echo getFilterHTML($view,$filterQuery,$sortQuery,$limitQuery); echo getFilterHTML($view);
echo getCycleHTML($view); echo getCycleHTML($view);
echo getMontageHTML($view); echo getMontageHTML($view);
echo getMontageReviewHTML($view); echo getMontageReviewHTML($view);
@ -702,11 +696,11 @@ function getGroupsHTML($view) {
} }
// Returns the html representing the Filter menu item // Returns the html representing the Filter menu item
function getFilterHTML($view, $filterQuery, $sortQuery, $limitQuery) { function getFilterHTML($view) {
$result = ''; $result = '';
$class = $view == 'filter' ? ' selected' : ''; $class = $view == 'filter' ? ' selected' : '';
$result .= '<li id="getFilterHTML" class="nav-item dropdown"><a class="nav-link'.$class.'" href="?view=filter'.$filterQuery.$sortQuery.$limitQuery.'">'.translate('Filters').'</a></li>'.PHP_EOL; $result .= '<li id="getFilterHTML" class="nav-item dropdown"><a class="nav-link'.$class.'" href="?view=filter">'.translate('Filters').'</a></li>'.PHP_EOL;
return $result; return $result;
} }
@ -785,14 +779,15 @@ function getHeaderFlipHTML() {
} }
// Returns the html representing the logged in user name and avatar // Returns the html representing the logged in user name and avatar
function getAcctCircleHTML($user=null) { function getAcctCircleHTML($skin, $user=null) {
// Include Logout modal
include("skins/$skin/views/logout.php");
$result = ''; $result = '';
if ( ZM_OPT_USE_AUTH and $user ) { if ( ZM_OPT_USE_AUTH and $user ) {
$result .= '<p id="getAcctCircleHTML" class="navbar-text mr-2">'.PHP_EOL; $result .= '<p id="getAcctCircleHTML" class="navbar-text mr-2">'.PHP_EOL;
$result .= makePopupLink('?view=logout', 'zmLogout', 'logout', $result .= makeLink('#', '<i class="material-icons">account_circle</i> '. $user['Username'],
'<i class="material-icons">account_circle</i> '. $user['Username'], (ZM_AUTH_TYPE == 'builtin'), 'data-toggle="modal" data-target="#modalLogout" data-backdrop="false"' ).PHP_EOL;
(ZM_AUTH_TYPE == 'builtin') ).PHP_EOL;
$result .= '</p>'.PHP_EOL; $result .= '</p>'.PHP_EOL;
} }

View File

@ -59,7 +59,7 @@ var popupSizes = {
'options': {'width': 1000, 'height': 660}, 'options': {'width': 1000, 'height': 660},
'preset': {'width': 300, 'height': 220}, 'preset': {'width': 300, 'height': 220},
'server': {'width': 600, 'height': 405}, 'server': {'width': 600, 'height': 405},
'settings': {'width': 220, 'height': 235}, 'settings': {'width': 250, 'height': 335},
'shutdown': {'width': 400, 'height': 400}, 'shutdown': {'width': 400, 'height': 400},
'state': {'width': 400, 'height': 170}, 'state': {'width': 400, 'height': 170},
'stats': {'width': 840, 'height': 200}, 'stats': {'width': 840, 'height': 200},

File diff suppressed because one or more lines are too long

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