Merge branch 'fix_out_of_files_in_encoding' into release-1.36

This commit is contained in:
Isaac Connor 2021-05-21 10:39:58 -04:00
commit d218d81f87
40 changed files with 1080 additions and 806 deletions

View File

@ -3,7 +3,8 @@ target_compile_options(zm-warning-interface
-Wall -Wall
-Wextra -Wextra
-Wimplicit-fallthrough -Wimplicit-fallthrough
-Wno-unused-parameter) -Wno-unused-parameter
-Wvla)
if(ENABLE_WERROR) if(ENABLE_WERROR)
target_compile_options(zm-warning-interface target_compile_options(zm-warning-interface

View File

@ -7,7 +7,8 @@ target_compile_options(zm-warning-interface
-Wno-cast-function-type -Wno-cast-function-type
$<$<VERSION_LESS:$<CXX_COMPILER_VERSION>,11>:-Wno-clobbered> $<$<VERSION_LESS:$<CXX_COMPILER_VERSION>,11>:-Wno-clobbered>
-Wno-unused-parameter -Wno-unused-parameter
-Woverloaded-virtual) -Woverloaded-virtual
-Wvla)
if(ENABLE_WERROR) if(ENABLE_WERROR)
target_compile_options(zm-warning-interface target_compile_options(zm-warning-interface

View File

@ -31,7 +31,7 @@
%global _hardened_build 1 %global _hardened_build 1
Name: zoneminder Name: zoneminder
Version: 1.36.0 Version: 1.37.0
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

View File

@ -6,12 +6,10 @@ configure_file(zm_config_data.h.in "${CMAKE_BINARY_DIR}/zm_config_data.h" @ONLY)
# Group together all the source files that are used by all the binaries (zmc, zmu, zms etc) # Group together all the source files that are used by all the binaries (zmc, zmu, zms etc)
set(ZM_BIN_SRC_FILES set(ZM_BIN_SRC_FILES
zm_analysis_thread.cpp zm_analysis_thread.cpp
zm_box.cpp
zm_buffer.cpp zm_buffer.cpp
zm_camera.cpp zm_camera.cpp
zm_comms.cpp zm_comms.cpp
zm_config.cpp zm_config.cpp
zm_coord.cpp
zm_curl_camera.cpp zm_curl_camera.cpp
zm_crypt.cpp zm_crypt.cpp
zm.cpp zm.cpp

View File

@ -1,22 +0,0 @@
//
// ZoneMinder Box Class Implementation, $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.
//
#include "zm_box.h"
// This section deliberately left blank

View File

@ -20,49 +20,59 @@
#ifndef ZM_BOX_H #ifndef ZM_BOX_H
#define ZM_BOX_H #define ZM_BOX_H
#include "zm_coord.h" #include "zm_line.h"
#include "zm_vector2.h"
#include <cmath> #include <cmath>
#include <vector>
// //
// Class used for storing a box, which is defined as a region // Class used for storing a box, which is defined as a region
// defined by two coordinates // defined by two coordinates
// //
class Box { class Box {
private: public:
Coord lo, hi; Box() = default;
Coord size; Box(Vector2 lo, Vector2 hi) : lo_(lo), hi_(hi), size_(hi - lo) {}
public: const Vector2 &Lo() const { return lo_; }
inline Box() : lo(0,0), hi(0,0), size(0,0) { } const Vector2 &Hi() const { return hi_; }
explicit inline Box(unsigned int p_size) : lo(0, 0), hi(p_size-1, p_size-1), size(Coord::Range(hi, lo)) { }
inline Box( int p_x_size, int p_y_size ) : lo( 0, 0 ), hi ( p_x_size-1, p_y_size-1 ), size( Coord::Range( hi, lo ) ) { }
inline Box( int lo_x, int lo_y, int hi_x, int hi_y ) : lo( lo_x, lo_y ), hi( hi_x, hi_y ), size( Coord::Range( hi, lo ) ) { }
inline Box( const Coord &p_lo, const Coord &p_hi ) : lo( p_lo ), hi( p_hi ), size( Coord::Range( hi, lo ) ) { }
inline const Coord &Lo() const { return lo; } const Vector2 &Size() const { return size_; }
inline int LoX() const { return lo.X(); } int32 Area() const { return size_.x_ * size_.y_; }
inline int LoX(int p_lo_x) { return lo.X(p_lo_x); }
inline int LoY() const { return lo.Y(); }
inline int LoY(int p_lo_y) { return lo.Y(p_lo_y); }
inline const Coord &Hi() const { return hi; }
inline int HiX() const { return hi.X(); }
inline int HiX(int p_hi_x) { return hi.X(p_hi_x); }
inline int HiY() const { return hi.Y(); }
inline int HiY(int p_hi_y) { return hi.Y(p_hi_y); }
inline const Coord &Size() const { return size; }
inline int Width() const { return size.X(); }
inline int Height() const { return size.Y(); }
inline int Area() const { return size.X()*size.Y(); }
inline const Coord Centre() const { Vector2 Centre() const {
int mid_x = int(std::round(lo.X()+(size.X()/2.0))); int32 mid_x = static_cast<int32>(std::lround(lo_.x_ + (size_.x_ / 2.0)));
int mid_y = int(std::round(lo.Y()+(size.Y()/2.0))); int32 mid_y = static_cast<int32>(std::lround(lo_.y_ + (size_.y_ / 2.0)));
return Coord( mid_x, mid_y ); return {mid_x, mid_y};
} }
inline bool Inside( const Coord &coord ) const
{ // Get vertices of the box in a counter-clockwise order
return( coord.X() >= lo.X() && coord.X() <= hi.X() && coord.Y() >= lo.Y() && coord.Y() <= hi.Y() ); std::vector<Vector2> Vertices() const {
return {lo_, {hi_.x_, lo_.y_}, hi_, {lo_.x_, hi_.y_}};
} }
// Get edges of the box in a counter-clockwise order
std::vector<LineSegment> Edges() const {
std::vector<LineSegment> edges;
edges.reserve(4);
std::vector<Vector2> v = Vertices();
edges.emplace_back(v[0], v[1]);
edges.emplace_back(v[1], v[2]);
edges.emplace_back(v[2], v[3]);
edges.emplace_back(v[3], v[0]);
return edges;
}
bool Contains(const Vector2 &coord) const {
return (coord.x_ >= lo_.x_ && coord.x_ <= hi_.x_ && coord.y_ >= lo_.y_ && coord.y_ <= hi_.y_);
}
private:
Vector2 lo_;
Vector2 hi_;
Vector2 size_;
}; };
#endif // ZM_BOX_H #endif // ZM_BOX_H

View File

@ -36,7 +36,7 @@
int ZM::CommsBase::readV(int iovcnt, /* const void *, int, */ ...) { int ZM::CommsBase::readV(int iovcnt, /* const void *, int, */ ...) {
va_list arg_ptr; va_list arg_ptr;
iovec iov[iovcnt]; std::vector<iovec> iov(iovcnt);
va_start(arg_ptr, iovcnt); va_start(arg_ptr, iovcnt);
for (int i = 0; i < iovcnt; i++) { for (int i = 0; i < iovcnt; i++) {
@ -45,7 +45,7 @@ int ZM::CommsBase::readV(int iovcnt, /* const void *, int, */ ...) {
} }
va_end(arg_ptr); va_end(arg_ptr);
int nBytes = ::readv(mRd, iov, iovcnt); int nBytes = ::readv(mRd, iov.data(), iovcnt);
if (nBytes < 0) { if (nBytes < 0) {
Debug(1, "Readv of %d buffers max on rd %d failed: %s", iovcnt, mRd, strerror(errno)); Debug(1, "Readv of %d buffers max on rd %d failed: %s", iovcnt, mRd, strerror(errno));
} }
@ -54,7 +54,7 @@ int ZM::CommsBase::readV(int iovcnt, /* const void *, int, */ ...) {
int ZM::CommsBase::writeV(int iovcnt, /* const void *, int, */ ...) { int ZM::CommsBase::writeV(int iovcnt, /* const void *, int, */ ...) {
va_list arg_ptr; va_list arg_ptr;
iovec iov[iovcnt]; std::vector<iovec> iov(iovcnt);
va_start(arg_ptr, iovcnt); va_start(arg_ptr, iovcnt);
for (int i = 0; i < iovcnt; i++) { for (int i = 0; i < iovcnt; i++) {
@ -63,7 +63,7 @@ int ZM::CommsBase::writeV(int iovcnt, /* const void *, int, */ ...) {
} }
va_end(arg_ptr); va_end(arg_ptr);
ssize_t nBytes = ::writev(mWd, iov, iovcnt); ssize_t nBytes = ::writev(mWd, iov.data(), iovcnt);
if (nBytes < 0) { if (nBytes < 0) {
Debug(1, "Writev of %d buffers on wd %d failed: %s", iovcnt, mWd, strerror(errno)); Debug(1, "Writev of %d buffers on wd %d failed: %s", iovcnt, mWd, strerror(errno));
} }

View File

@ -243,27 +243,27 @@ class Socket : public CommsBase {
return nBytes; return nBytes;
} }
virtual int recv(std::string &msg) const { virtual ssize_t recv(std::string &msg) const {
char buffer[msg.capacity()]; std::vector<char> buffer(msg.capacity());
int nBytes = 0; ssize_t nBytes;
if ((nBytes = ::recv(mSd, buffer, sizeof(buffer), 0)) < 0) { if ((nBytes = ::recv(mSd, buffer.data(), buffer.size(), 0)) < 0) {
Debug(1, "Recv of %zd bytes max to string on sd %d failed: %s", sizeof(buffer), mSd, strerror(errno)); Debug(1, "Recv of %zd bytes max to string on sd %d failed: %s", msg.size(), mSd, strerror(errno));
return nBytes; return nBytes;
} }
buffer[nBytes] = '\0'; buffer[nBytes] = '\0';
msg = buffer; msg = {buffer.begin(), buffer.begin() + nBytes};
return nBytes; return nBytes;
} }
virtual int recv(std::string &msg, size_t maxLen) const { virtual ssize_t recv(std::string &msg, size_t maxLen) const {
char buffer[maxLen]; std::vector<char> buffer(maxLen);
int nBytes = 0; ssize_t nBytes;
if ((nBytes = ::recv(mSd, buffer, sizeof(buffer), 0)) < 0) { if ((nBytes = ::recv(mSd, buffer.data(), buffer.size(), 0)) < 0) {
Debug(1, "Recv of %zd bytes max to string on sd %d failed: %s", maxLen, mSd, strerror(errno)); Debug(1, "Recv of %zd bytes max to string on sd %d failed: %s", maxLen, mSd, strerror(errno));
return nBytes; return nBytes;
} }
buffer[nBytes] = '\0'; buffer[nBytes] = '\0';
msg = buffer; msg = {buffer.begin(), buffer.begin() + nBytes};
return nBytes; return nBytes;
} }

View File

@ -1,22 +0,0 @@
//
// ZoneMinder Coordinate Class Implementation, $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.
//
#include "zm_coord.h"
// This section deliberately left blank

View File

@ -1,64 +0,0 @@
//
// ZoneMinder Coordinate Class Interface, $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_COORD_H
#define ZM_COORD_H
#include "zm_define.h"
//
// Class used for storing an x,y pair, i.e. a coordinate
//
class Coord {
private:
int x, y;
public:
inline Coord() : x(0), y(0) { }
inline Coord( int p_x, int p_y ) : x(p_x), y(p_y) { }
inline Coord( const Coord &p_coord ) : x(p_coord.x), y(p_coord.y) { }
inline Coord &operator =( const Coord &coord ) {
x = coord.x;
y = coord.y;
return *this;
}
inline int &X(int p_x) { x=p_x; return x; }
inline const int &X() const { return x; }
inline int &Y(int p_y) { y=p_y; return y; }
inline const int &Y() const { return y; }
inline static Coord Range( const Coord &coord1, const Coord &coord2 ) {
Coord result( (coord1.x-coord2.x)+1, (coord1.y-coord2.y)+1 );
return result;
}
inline bool operator==( const Coord &coord ) const { return( x == coord.x && y == coord.y ); }
inline bool operator!=( const Coord &coord ) const { return( x != coord.x || y != coord.y ); }
inline bool operator>( const Coord &coord ) const { return( x > coord.x && y > coord.y ); }
inline bool operator>=( const Coord &coord ) const { return( !(operator<(coord)) ); }
inline bool operator<( const Coord &coord ) const { return( x < coord.x && y < coord.y ); }
inline bool operator<=( const Coord &coord ) const { return( !(operator>(coord)) ); }
inline Coord &operator+=( const Coord &coord ) { x += coord.x; y += coord.y; return( *this ); }
inline Coord &operator-=( const Coord &coord ) { x -= coord.x; y -= coord.y; return( *this ); }
inline friend Coord operator+( const Coord &coord1, const Coord &coord2 ) { Coord result( coord1 ); result += coord2; return( result ); }
inline friend Coord operator-( const Coord &coord1, const Coord &coord2 ) { Coord result( coord1 ); result -= coord2; return( result ); }
};
#endif // ZM_COORD_H

View File

@ -29,6 +29,7 @@
#endif #endif
#include <cinttypes> #include <cinttypes>
#include <cstddef>
typedef std::int64_t int64; typedef std::int64_t int64;
typedef std::int32_t int32; typedef std::int32_t int32;

View File

@ -473,10 +473,10 @@ void Event::WriteDbFrames() {
stats.alarm_blobs_, stats.alarm_blobs_,
stats.min_blob_size_, stats.min_blob_size_,
stats.max_blob_size_, stats.max_blob_size_,
stats.alarm_box_.LoX(), stats.alarm_box_.Lo().x_,
stats.alarm_box_.LoY(), stats.alarm_box_.Lo().y_,
stats.alarm_box_.HiX(), stats.alarm_box_.Hi().x_,
stats.alarm_box_.HiY(), stats.alarm_box_.Hi().y_,
stats.score_); stats.score_);
} // end foreach zone stats } // end foreach zone stats
} // end if recording stats } // end if recording stats

View File

@ -250,7 +250,7 @@ int Image::PopulateFrame(AVFrame *frame) {
width, height, linesize, colours, size, width, height, linesize, colours, size,
av_get_pix_fmt_name(imagePixFormat) av_get_pix_fmt_name(imagePixFormat)
); );
AVBufferRef *ref = av_buffer_create(buffer, size, AVBufferRef *ref = av_buffer_create(buffer, size,
dont_free, /* Free callback */ dont_free, /* Free callback */
nullptr, /* opaque */ nullptr, /* opaque */
0 /* flags */ 0 /* flags */
@ -576,7 +576,7 @@ void Image::Initialise() {
if ( res == FontLoadError::kFileNotFound ) { if ( res == FontLoadError::kFileNotFound ) {
Panic("Invalid font location: %s", config.font_file_location); Panic("Invalid font location: %s", config.font_file_location);
} else if ( res == FontLoadError::kInvalidFile ) { } else if ( res == FontLoadError::kInvalidFile ) {
Panic("Invalid font file."); Panic("Invalid font file.");
} }
initialised = true; initialised = true;
} }
@ -781,7 +781,7 @@ void Image::Assign(const Image &image) {
return; return;
} }
} else { } else {
if ( new_size > allocation || !buffer ) { if (new_size > allocation || !buffer) {
// DumpImgBuffer(); This is also done in AllocImgBuffer // DumpImgBuffer(); This is also done in AllocImgBuffer
AllocImgBuffer(new_size); AllocImgBuffer(new_size);
} }
@ -820,10 +820,10 @@ Image *Image::HighlightEdges(
/* Set image to all black */ /* Set image to all black */
high_image->Clear(); high_image->Clear();
unsigned int lo_x = limits ? limits->Lo().X() : 0; unsigned int lo_x = limits ? limits->Lo().x_ : 0;
unsigned int lo_y = limits ? limits->Lo().Y() : 0; unsigned int lo_y = limits ? limits->Lo().y_ : 0;
unsigned int hi_x = limits ? limits->Hi().X() : width-1; unsigned int hi_x = limits ? limits->Hi().x_ : width - 1;
unsigned int hi_y = limits ? limits->Hi().Y() : height-1; unsigned int hi_y = limits ? limits->Hi().y_ : height - 1;
if ( p_colours == ZM_COLOUR_GRAY8 ) { if ( p_colours == ZM_COLOUR_GRAY8 ) {
for ( unsigned int y = lo_y; y <= hi_y; y++ ) { for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
@ -1508,7 +1508,7 @@ bool Image::Crop( unsigned int lo_x, unsigned int lo_y, unsigned int hi_x, unsig
} }
bool Image::Crop(const Box &limits) { bool Image::Crop(const Box &limits) {
return Crop(limits.LoX(), limits.LoY(), limits.HiX(), limits.HiY()); return Crop(limits.Lo().x_, limits.Lo().y_, limits.Hi().x_, limits.Hi().y_);
} }
/* Far from complete */ /* Far from complete */
@ -1932,7 +1932,7 @@ void Image::Delta(const Image &image, Image* targetimage) const {
#endif #endif
} }
const Coord Image::centreCoord( const char *text, int size=1 ) const { const Vector2 Image::centreCoord(const char *text, int size = 1) const {
int index = 0; int index = 0;
int line_no = 0; int line_no = 0;
int text_len = strlen(text); int text_len = strlen(text);
@ -1957,7 +1957,7 @@ const Coord Image::centreCoord( const char *text, int size=1 ) const {
uint16_t char_height = font_variant.GetCharHeight(); uint16_t char_height = font_variant.GetCharHeight();
int x = (width - (max_line_len * char_width )) / 2; int x = (width - (max_line_len * char_width )) / 2;
int y = (height - (line_no * char_height) ) / 2; int y = (height - (line_no * char_height) ) / 2;
return Coord(x, y); return {x, y};
} }
/* RGB32 compatible: complete */ /* RGB32 compatible: complete */
@ -2007,7 +2007,7 @@ https://lemire.me/blog/2018/02/21/iterating-over-set-bits-quickly/
*/ */
void Image::Annotate( void Image::Annotate(
const std::string &text, const std::string &text,
const Coord &coord, const Vector2 &coord,
const uint8 size, const uint8 size,
const Rgb fg_colour, const Rgb fg_colour,
const Rgb bg_colour) { const Rgb bg_colour) {
@ -2031,8 +2031,8 @@ void Image::Annotate(
// Calculate initial coordinates of annotation so that everything is displayed even if the // Calculate initial coordinates of annotation so that everything is displayed even if the
// user set coordinates would prevent that. // user set coordinates would prevent that.
uint32 x0 = ZM::clamp(static_cast<uint32>(coord.X()), 0u, x0_max); uint32 x0 = ZM::clamp(static_cast<uint32>(coord.x_), 0u, x0_max);
uint32 y0 = ZM::clamp(static_cast<uint32>(coord.Y()), 0u, y0_max); uint32 y0 = ZM::clamp(static_cast<uint32>(coord.y_), 0u, y0_max);
uint32 y = y0; uint32 y = y0;
for (const std::string &line : lines) { for (const std::string &line : lines) {
@ -2127,7 +2127,7 @@ void Image::Annotate(
} }
} }
void Image::Timestamp( const char *label, const time_t when, const Coord &coord, const int size ) { void Image::Timestamp(const char *label, const time_t when, const Vector2 &coord, const int size) {
char time_text[64]; char time_text[64];
tm when_tm = {}; tm when_tm = {};
strftime(time_text, sizeof(time_text), "%y/%m/%d %H:%M:%S", localtime_r(&when, &when_tm)); strftime(time_text, sizeof(time_text), "%y/%m/%d %H:%M:%S", localtime_r(&when, &when_tm));
@ -2294,10 +2294,10 @@ void Image::Fill( Rgb colour, const Box *limits ) {
/* Convert the colour's RGBA subpixel order into the image's subpixel order */ /* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour,subpixelorder); colour = rgb_convert(colour,subpixelorder);
unsigned int lo_x = limits?limits->Lo().X():0; unsigned int lo_x = limits ? limits->Lo().x_ : 0;
unsigned int lo_y = limits?limits->Lo().Y():0; unsigned int lo_y = limits ? limits->Lo().y_ : 0;
unsigned int hi_x = limits?limits->Hi().X():width-1; unsigned int hi_x = limits ? limits->Hi().x_ : width - 1;
unsigned int hi_y = limits?limits->Hi().Y():height-1; unsigned int hi_y = limits ? limits->Hi().y_ : height - 1;
if ( colours == ZM_COLOUR_GRAY8 ) { if ( colours == ZM_COLOUR_GRAY8 ) {
for ( unsigned int y = lo_y; y <= hi_y; y++ ) { for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
unsigned char *p = &buffer[(y*width)+lo_x]; unsigned char *p = &buffer[(y*width)+lo_x];
@ -2339,10 +2339,10 @@ void Image::Fill( Rgb colour, int density, const Box *limits ) {
/* Convert the colour's RGBA subpixel order into the image's subpixel order */ /* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour, subpixelorder); colour = rgb_convert(colour, subpixelorder);
unsigned int lo_x = limits?limits->Lo().X():0; unsigned int lo_x = limits ? limits->Lo().x_ : 0;
unsigned int lo_y = limits?limits->Lo().Y():0; unsigned int lo_y = limits ? limits->Lo().y_ : 0;
unsigned int hi_x = limits?limits->Hi().X():width-1; unsigned int hi_x = limits ? limits->Hi().x_ : width - 1;
unsigned int hi_y = limits?limits->Hi().Y():height-1; unsigned int hi_y = limits ? limits->Hi().y_ : height - 1;
if ( colours == ZM_COLOUR_GRAY8 ) { if ( colours == ZM_COLOUR_GRAY8 ) {
for ( unsigned int y = lo_y; y <= hi_y; y++ ) { for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
unsigned char *p = &buffer[(y*width)+lo_x]; unsigned char *p = &buffer[(y*width)+lo_x];
@ -2382,17 +2382,18 @@ void Image::Outline( Rgb colour, const Polygon &polygon ) {
} }
/* Convert the colour's RGBA subpixel order into the image's subpixel order */ /* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour,subpixelorder); colour = rgb_convert(colour, subpixelorder);
int n_coords = polygon.getNumCoords(); size_t n_coords = polygon.GetVertices().size();
for ( int j = 0, i = n_coords-1; j < n_coords; i = j++ ) { for (size_t j = 0, i = n_coords - 1; j < n_coords; i = j++) {
const Coord &p1 = polygon.getCoord( i ); const Vector2 &p1 = polygon.GetVertices()[i];
const Coord &p2 = polygon.getCoord( j ); const Vector2 &p2 = polygon.GetVertices()[j];
int x1 = p1.X(); // The last pixel we can draw is width/height - 1. Clamp to that value.
int x2 = p2.X(); int x1 = ZM::clamp(p1.x_, 0, static_cast<int>(width - 1));
int y1 = p1.Y(); int x2 = ZM::clamp(p2.x_, 0, static_cast<int>(width - 1));
int y2 = p2.Y(); int y1 = ZM::clamp(p1.y_, 0, static_cast<int>(height - 1));
int y2 = ZM::clamp(p2.y_, 0, static_cast<int>(height - 1));
double dx = x2 - x1; double dx = x2 - x1;
double dy = y2 - y1; double dy = y2 - y1;
@ -2457,129 +2458,101 @@ void Image::Outline( Rgb colour, const Polygon &polygon ) {
} // end foreach coordinate in the polygon } // end foreach coordinate in the polygon
} }
/* RGB32 compatible: complete */ // Polygon filling is based on the Scan-line Polygon filling algorithm
void Image::Fill(Rgb colour, int density, const Polygon &polygon) { void Image::Fill(Rgb colour, int density, const Polygon &polygon) {
if ( !(colours == ZM_COLOUR_GRAY8 || colours == ZM_COLOUR_RGB24 || colours == ZM_COLOUR_RGB32 ) ) { if (!(colours == ZM_COLOUR_GRAY8 || colours == ZM_COLOUR_RGB24 || colours == ZM_COLOUR_RGB32)) {
Panic("Attempt to fill image with unexpected colours %d", colours); Panic("Attempt to fill image with unexpected colours %d", colours);
} }
/* Convert the colour's RGBA subpixel order into the image's subpixel order */ /* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour, subpixelorder); colour = rgb_convert(colour, subpixelorder);
int n_coords = polygon.getNumCoords(); size_t n_coords = polygon.GetVertices().size();
int n_global_edges = 0;
Edge global_edges[n_coords];
for ( int j = 0, i = n_coords-1; j < n_coords; i = j++ ) {
const Coord &p1 = polygon.getCoord(i);
const Coord &p2 = polygon.getCoord(j);
int x1 = p1.X(); std::vector<PolygonFill::Edge> global_edges;
int x2 = p2.X(); global_edges.reserve(n_coords);
int y1 = p1.Y(); for (size_t j = 0, i = n_coords - 1; j < n_coords; i = j++) {
int y2 = p2.Y(); const Vector2 &p1 = polygon.GetVertices()[i];
const Vector2 &p2 = polygon.GetVertices()[j];
//Debug( 9, "x1:%d,y1:%d x2:%d,y2:%d", x1, y1, x2, y2 ); // Do not add horizontal edges to the global edge table.
if ( y1 == y2 ) if (p1.y_ == p2.y_)
continue; continue;
double dx = x2 - x1; Vector2 d = p2 - p1;
double dy = y2 - y1;
global_edges.emplace_back(std::min(p1.y_, p2.y_),
std::max(p1.y_, p2.y_),
p1.y_ < p2.y_ ? p1.x_ : p2.x_,
d.x_ / static_cast<double>(d.y_));
global_edges[n_global_edges].min_y = y1<y2?y1:y2;
global_edges[n_global_edges].max_y = y1<y2?y2:y1;
global_edges[n_global_edges].min_x = y1<y2?x1:x2;
global_edges[n_global_edges]._1_m = dx/dy;
n_global_edges++;
} }
std::sort(global_edges, global_edges + n_global_edges, Edge::CompareYX); std::sort(global_edges.begin(), global_edges.end(), PolygonFill::Edge::CompareYX);
#ifndef ZM_DBG_OFF std::vector<PolygonFill::Edge> active_edges;
if ( logLevel() >= Logger::DEBUG9 ) { active_edges.reserve(global_edges.size());
for ( int i = 0; i < n_global_edges; i++ ) {
Debug(9, "%d: min_y: %d, max_y:%d, min_x:%.2f, 1/m:%.2f",
i, global_edges[i].min_y, global_edges[i].max_y, global_edges[i].min_x, global_edges[i]._1_m);
}
}
#endif
int n_active_edges = 0; int32 scan_line = global_edges[0].min_y;
Edge active_edges[n_global_edges]; while (!global_edges.empty() || !active_edges.empty()) {
int y = global_edges[0].min_y; // Deactivate edges with max_y < current scan line
do { for (auto it = active_edges.begin(); it != active_edges.end();) {
for ( int i = 0; i < n_global_edges; i++ ) { if (scan_line >= it->max_y) {
if ( global_edges[i].min_y == y ) { it = active_edges.erase(it);
Debug(9, "Moving global edge");
active_edges[n_active_edges++] = global_edges[i];
if ( i < (n_global_edges-1) ) {
memmove(&global_edges[i], &global_edges[i + 1], sizeof(*global_edges) * (n_global_edges - i - 1));
i--;
}
n_global_edges--;
} else { } else {
break; it->min_x += it->_1_m;
++it;
} }
} }
std::sort(active_edges, active_edges + n_active_edges, Edge::CompareX);
#ifndef ZM_DBG_OFF // Activate edges with min_y == current scan line
if ( logLevel() >= Logger::DEBUG9 ) { for (auto it = global_edges.begin(); it != global_edges.end();) {
for ( int i = 0; i < n_active_edges; i++ ) { if (it->min_y == scan_line) {
Debug(9, "%d - %d: min_y: %d, max_y:%d, min_x:%.2f, 1/m:%.2f", active_edges.emplace_back(*it);
y, i, active_edges[i].min_y, active_edges[i].max_y, active_edges[i].min_x, active_edges[i]._1_m ); it = global_edges.erase(it);
} else {
++it;
} }
} }
#endif std::sort(active_edges.begin(), active_edges.end(), PolygonFill::Edge::CompareX);
if ( !(y%density) ) {
//Debug( 9, "%d", y ); if (!(scan_line % density)) {
for ( int i = 0; i < n_active_edges; ) { for (auto it = active_edges.begin(); it != active_edges.end(); ++it) {
int lo_x = int(round(active_edges[i++].min_x)); int32 lo_x = static_cast<int32>(it->min_x);
int hi_x = int(round(active_edges[i++].min_x)); int32 hi_x = static_cast<int32>(std::next(it)->min_x);
if ( colours == ZM_COLOUR_GRAY8 ) { if (colours == ZM_COLOUR_GRAY8) {
unsigned char *p = &buffer[(y*width)+lo_x]; uint8 *p = &buffer[(scan_line * width) + lo_x];
for ( int x = lo_x; x <= hi_x; x++, p++) {
if ( !(x%density) ) { for (int32 x = lo_x; x <= hi_x; x++, p++) {
//Debug( 9, " %d", x ); if (!(x % density)) {
*p = colour; *p = colour;
} }
} }
} else if ( colours == ZM_COLOUR_RGB24 ) { } else if (colours == ZM_COLOUR_RGB24) {
unsigned char *p = &buffer[colours*((y*width)+lo_x)]; constexpr uint8 bytesPerPixel = 3;
for ( int x = lo_x; x <= hi_x; x++, p += 3) { uint8 *ptr = &buffer[((scan_line * width) + lo_x) * bytesPerPixel];
if ( !(x%density) ) {
RED_PTR_RGBA(p) = RED_VAL_RGBA(colour);
GREEN_PTR_RGBA(p) = GREEN_VAL_RGBA(colour);
BLUE_PTR_RGBA(p) = BLUE_VAL_RGBA(colour);
}
}
} else if( colours == ZM_COLOUR_RGB32 ) {
Rgb *p = (Rgb*)&buffer[((y*width)+lo_x)<<2];
for ( int x = lo_x; x <= hi_x; x++, p++) {
if ( !(x%density) ) {
/* Fast, copies the entire pixel in a single pass */
*p = colour;
}
}
}
}
}
y++;
for ( int i = n_active_edges-1; i >= 0; i-- ) {
if ( y >= active_edges[i].max_y ) {
// Or >= as per sheets
Debug(9, "Deleting active_edge");
if ( i < (n_active_edges-1) ) {
//memcpy( &active_edges[i], &active_edges[i+1], sizeof(*active_edges)*(n_active_edges-i) );
memmove( &active_edges[i], &active_edges[i+1], sizeof(*active_edges)*(n_active_edges-i) );
}
n_active_edges--;
} else {
active_edges[i].min_x += active_edges[i]._1_m;
}
}
} while ( n_global_edges || n_active_edges );
}
void Image::Fill(Rgb colour, const Polygon &polygon) { for (int32 x = lo_x; x <= hi_x; x++, ptr += bytesPerPixel) {
Fill(colour, 1, polygon); if (!(x % density)) {
RED_PTR_RGBA(ptr) = RED_VAL_RGBA(colour);
GREEN_PTR_RGBA(ptr) = GREEN_VAL_RGBA(colour);
BLUE_PTR_RGBA(ptr) = BLUE_VAL_RGBA(colour);
}
}
} else if (colours == ZM_COLOUR_RGB32) {
constexpr uint8 bytesPerPixel = 4;
Rgb *ptr = reinterpret_cast<Rgb *>(&buffer[((scan_line * width) + lo_x) * bytesPerPixel]);
for (int32 x = lo_x; x <= hi_x; x++, ptr++) {
if (!(x % density)) {
*ptr = colour;
}
}
}
}
}
scan_line++;
}
} }
void Image::Rotate(int angle) { void Image::Rotate(int angle) {

View File

@ -20,19 +20,18 @@
#ifndef ZM_IMAGE_H #ifndef ZM_IMAGE_H
#define ZM_IMAGE_H #define ZM_IMAGE_H
#include "zm_coord.h"
#include "zm_ffmpeg.h" #include "zm_ffmpeg.h"
#include "zm_jpeg.h" #include "zm_jpeg.h"
#include "zm_logger.h" #include "zm_logger.h"
#include "zm_mem_utils.h" #include "zm_mem_utils.h"
#include "zm_rgb.h" #include "zm_rgb.h"
#include "zm_vector2.h"
#if HAVE_ZLIB_H #if HAVE_ZLIB_H
#include <zlib.h> #include <zlib.h>
#endif // HAVE_ZLIB_H #endif // HAVE_ZLIB_H
class Box; class Box;
class Image;
class Polygon; class Polygon;
#define ZM_BUFTYPE_DONTFREE 0 #define ZM_BUFTYPE_DONTFREE 0
@ -96,24 +95,6 @@ class Image {
void update_function_pointers(); void update_function_pointers();
protected: protected:
struct Edge {
int min_y;
int max_y;
double min_x;
double _1_m;
static bool CompareYX(const Edge &e1, const Edge &e2) {
if ( e1.min_y == e2.min_y )
return e1.min_x < e2.min_x;
return e1.min_y < e2.min_y;
}
static bool CompareX(const Edge &e1, const Edge &e2) {
return e1.min_x < e2.min_x;
}
};
inline void AllocImgBuffer(size_t p_bufsize) { inline void AllocImgBuffer(size_t p_bufsize) {
if ( buffer ) if ( buffer )
DumpImgBuffer(); DumpImgBuffer();
@ -280,16 +261,16 @@ class Image {
//Image *Delta( const Image &image ) const; //Image *Delta( const Image &image ) const;
void Delta( const Image &image, Image* targetimage) const; void Delta( const Image &image, Image* targetimage) const;
const Coord centreCoord(const char *text, const int size) const; const Vector2 centreCoord(const char *text, const int size) const;
void MaskPrivacy( const unsigned char *p_bitmask, const Rgb pixel_colour=0x00222222 ); void MaskPrivacy( const unsigned char *p_bitmask, const Rgb pixel_colour=0x00222222 );
void Annotate(const std::string &text, void Annotate(const std::string &text,
const Coord &coord, const Vector2 &coord,
uint8 size = 1, uint8 size = 1,
Rgb fg_colour = kRGBWhite, Rgb fg_colour = kRGBWhite,
Rgb bg_colour = kRGBBlack); Rgb bg_colour = kRGBBlack);
Image *HighlightEdges( Rgb colour, unsigned int p_colours, unsigned int p_subpixelorder, const Box *limits=0 ); Image *HighlightEdges( Rgb colour, unsigned int p_colours, unsigned int p_subpixelorder, const Box *limits=0 );
//Image *HighlightEdges( Rgb colour, const Polygon &polygon ); //Image *HighlightEdges( Rgb colour, const Polygon &polygon );
void Timestamp( const char *label, const time_t when, const Coord &coord, const int size ); void Timestamp(const char *label, const time_t when, const Vector2 &coord, const int size);
void Colourise(const unsigned int p_reqcolours, const unsigned int p_reqsubpixelorder); void Colourise(const unsigned int p_reqcolours, const unsigned int p_reqsubpixelorder);
void DeColourise(); void DeColourise();
@ -297,8 +278,8 @@ class Image {
void Fill( Rgb colour, const Box *limits=0 ); void Fill( Rgb colour, const Box *limits=0 );
void Fill( Rgb colour, int density, const Box *limits=0 ); void Fill( Rgb colour, int density, const Box *limits=0 );
void Outline( Rgb colour, const Polygon &polygon ); void Outline( Rgb colour, const Polygon &polygon );
void Fill( Rgb colour, const Polygon &polygon ); void Fill(Rgb colour, const Polygon &polygon) { Fill(colour, 1, polygon); };
void Fill( Rgb colour, int density, const Polygon &polygon ); void Fill(Rgb colour, int density, const Polygon &polygon);
void Rotate( int angle ); void Rotate( int angle );
void Flip( bool leftright ); void Flip( bool leftright );
@ -311,6 +292,31 @@ class Image {
void Deinterlace_4Field(const Image* next_image, unsigned int threshold); void Deinterlace_4Field(const Image* next_image, unsigned int threshold);
}; };
// Scan-line polygon fill algorithm
namespace PolygonFill {
class Edge {
public:
Edge() = default;
Edge(int32 min_y, int32 max_y, double min_x, double _1_m) : min_y(min_y), max_y(max_y), min_x(min_x), _1_m(_1_m) {}
static bool CompareYX(const Edge &e1, const Edge &e2) {
if (e1.min_y == e2.min_y)
return e1.min_x < e2.min_x;
return e1.min_y < e2.min_y;
}
static bool CompareX(const Edge &e1, const Edge &e2) {
return e1.min_x < e2.min_x;
}
public:
int32 min_y;
int32 max_y;
double min_x;
double _1_m;
};
}
#endif // ZM_IMAGE_H #endif // ZM_IMAGE_H
/* Blend functions */ /* Blend functions */

64
src/zm_line.h Normal file
View File

@ -0,0 +1,64 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#ifndef ZONEMINDER_SRC_ZM_LINE_H_
#define ZONEMINDER_SRC_ZM_LINE_H_
#include "zm_vector2.h"
// Represents a part of a line bounded by two end points
class LineSegment {
public:
LineSegment(Vector2 start, Vector2 end) : start_(start), end_(end) {}
public:
Vector2 start_;
Vector2 end_;
};
// Represents an infinite line
class Line {
public:
Line(Vector2 p1, Vector2 p2) : position_(p1), direction_(p2 - p1) {}
explicit Line(LineSegment segment) : Line(segment.start_, segment.end_) {};
bool IsPointLeftOfOrColinear(Vector2 p) const {
int32 det = direction_.Determinant(p - position_);
return det >= 0;
}
Vector2 Intersection(Line const &line) const {
int32 det = direction_.Determinant(line.direction_);
if (det == 0) {
// lines are parallel or overlap, no intersection
return Vector2::Inf();
}
Vector2 c = line.position_ - position_;
double t = c.Determinant(line.direction_) / static_cast<double>(det);
return position_ + direction_ * t;
}
private:
Vector2 position_;
Vector2 direction_;
};
#endif //ZONEMINDER_SRC_ZM_LINE_H_

View File

@ -529,15 +529,17 @@ void Logger::logPrint(bool hex, const char *filepath, int line, int level, const
if (level <= mDatabaseLevel) { if (level <= mDatabaseLevel) {
if (zmDbConnected) { if (zmDbConnected) {
int syslogSize = syslogEnd-syslogStart; int syslogSize = syslogEnd-syslogStart;
char escapedString[(syslogSize*2)+1]; std::string escapedString;
mysql_real_escape_string(&dbconn, escapedString, syslogStart, syslogSize); escapedString.reserve((syslogSize * 2) + 1);
mysql_real_escape_string(&dbconn, &escapedString[0], syslogStart, syslogSize);
escapedString.resize(std::strlen(escapedString.c_str()));
std::string sql_string = stringtf( std::string sql_string = stringtf(
"INSERT INTO `Logs` " "INSERT INTO `Logs` "
"( `TimeKey`, `Component`, `ServerId`, `Pid`, `Level`, `Code`, `Message`, `File`, `Line` )" "( `TimeKey`, `Component`, `ServerId`, `Pid`, `Level`, `Code`, `Message`, `File`, `Line` )"
" VALUES " " VALUES "
"( %ld.%06ld, '%s', %d, %d, %d, '%s', '%s', '%s', %d )", "( %ld.%06ld, '%s', %d, %d, %d, '%s', '%s', '%s', %d )",
timeVal.tv_sec, timeVal.tv_usec, mId.c_str(), staticConfig.SERVER_ID, tid, level, classString, escapedString, file, line timeVal.tv_sec, timeVal.tv_usec, mId.c_str(), staticConfig.SERVER_ID, tid, level, classString, escapedString.c_str(), file, line
); );
dbQueue.push(std::move(sql_string)); dbQueue.push(std::move(sql_string));
} else { } else {

View File

@ -327,7 +327,7 @@ Monitor::Monitor()
record_audio(0), record_audio(0),
//event_prefix //event_prefix
//label_format //label_format
label_coord(Coord(0,0)), label_coord(Vector2(0,0)),
label_size(0), label_size(0),
image_buffer_count(0), image_buffer_count(0),
max_image_buffer_count(0), max_image_buffer_count(0),
@ -561,7 +561,7 @@ void Monitor::Load(MYSQL_ROW dbrow, bool load_zones=true, Purpose p = QUERY) {
/* "EventPrefix, LabelFormat, LabelX, LabelY, LabelSize," */ /* "EventPrefix, LabelFormat, LabelX, LabelY, LabelSize," */
event_prefix = dbrow[col] ? dbrow[col] : ""; col++; event_prefix = dbrow[col] ? dbrow[col] : ""; col++;
label_format = dbrow[col] ? ReplaceAll(dbrow[col], "\\n", "\n") : ""; col++; label_format = dbrow[col] ? ReplaceAll(dbrow[col], "\\n", "\n") : ""; col++;
label_coord = Coord(atoi(dbrow[col]), atoi(dbrow[col+1])); col += 2; label_coord = Vector2(atoi(dbrow[col]), atoi(dbrow[col + 1])); col += 2;
label_size = atoi(dbrow[col]); col++; label_size = atoi(dbrow[col]); col++;
/* "ImageBufferCount, `MaxImageBufferCount`, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, " */ /* "ImageBufferCount, `MaxImageBufferCount`, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, " */
@ -1039,6 +1039,7 @@ bool Monitor::connect() {
// Uh, why nothing? Why not nullptr? // Uh, why nothing? Why not nullptr?
snprintf(video_store_data->event_file, sizeof(video_store_data->event_file), "nothing"); snprintf(video_store_data->event_file, sizeof(video_store_data->event_file), "nothing");
video_store_data->size = sizeof(VideoStoreData); video_store_data->size = sizeof(VideoStoreData);
usedsubpixorder = camera->SubpixelOrder(); // Used in CheckSignal
shared_data->valid = true; shared_data->valid = true;
} else if ( !shared_data->valid ) { } else if ( !shared_data->valid ) {
Error("Shared data not initialised by capture daemon for monitor %s", name.c_str()); Error("Shared data not initialised by capture daemon for monitor %s", name.c_str());
@ -1481,21 +1482,27 @@ void Monitor::DumpZoneImage(const char *zone_string) {
zone_image->Colourise(ZM_COLOUR_RGB24, ZM_SUBPIX_ORDER_RGB); zone_image->Colourise(ZM_COLOUR_RGB24, ZM_SUBPIX_ORDER_RGB);
} }
extra_zone.Clip(Box(
{0, 0},
{static_cast<int32>(zone_image->Width()), static_cast<int32>(zone_image->Height())}
));
for (const Zone &zone : zones) { for (const Zone &zone : zones) {
if ( exclude_id && (!extra_colour || extra_zone.getNumCoords()) && zone.Id() == exclude_id ) if (exclude_id && (!extra_colour || !extra_zone.GetVertices().empty()) && zone.Id() == exclude_id) {
continue; continue;
}
Rgb colour; Rgb colour;
if ( exclude_id && !extra_zone.getNumCoords() && zone.Id() == exclude_id ) { if (exclude_id && extra_zone.GetVertices().empty() && zone.Id() == exclude_id) {
colour = extra_colour; colour = extra_colour;
} else { } else {
if ( zone.IsActive() ) { if (zone.IsActive()) {
colour = kRGBRed; colour = kRGBRed;
} else if ( zone.IsInclusive() ) { } else if (zone.IsInclusive()) {
colour = kRGBOrange; colour = kRGBOrange;
} else if ( zone.IsExclusive() ) { } else if (zone.IsExclusive()) {
colour = kRGBPurple; colour = kRGBPurple;
} else if ( zone.IsPreclusive() ) { } else if (zone.IsPreclusive()) {
colour = kRGBBlue; colour = kRGBBlue;
} else { } else {
colour = kRGBWhite; colour = kRGBWhite;
@ -1505,7 +1512,7 @@ void Monitor::DumpZoneImage(const char *zone_string) {
zone_image->Outline(colour, zone.GetPolygon()); zone_image->Outline(colour, zone.GetPolygon());
} }
if ( extra_zone.getNumCoords() ) { if (!extra_zone.GetVertices().empty()) {
zone_image->Fill(extra_colour, 2, extra_zone); zone_image->Fill(extra_colour, 2, extra_zone);
zone_image->Outline(extra_colour, extra_zone); zone_image->Outline(extra_colour, extra_zone);
} }
@ -1537,40 +1544,45 @@ bool Monitor::CheckSignal(const Image *image) {
int colours = image->Colours(); int colours = image->Colours();
int index = 0; int index = 0;
for ( int i = 0; i < signal_check_points; i++ ) { for (int i = 0; i < signal_check_points; i++) {
while ( true ) { while (true) {
// Why the casting to long long? also note that on a 64bit cpu, long long is 128bits // Why the casting to long long? also note that on a 64bit cpu, long long is 128bits
index = (int)(((long long)rand()*(long long)(pixels-1))/RAND_MAX); index = (int)(((long long)rand()*(long long)(pixels-1))/RAND_MAX);
if ( !config.timestamp_on_capture || !label_format[0] ) if (!config.timestamp_on_capture || !label_format[0])
break; break;
// Avoid sampling the rows with timestamp in // Avoid sampling the rows with timestamp in
if ( index < (label_coord.Y()*width) || index >= (label_coord.Y()+Image::LINE_HEIGHT)*width ) if (
index < (label_coord.y_ * width)
||
index >= (label_coord.y_ + Image::LINE_HEIGHT) * width
) {
break; break;
}
} }
if ( colours == ZM_COLOUR_GRAY8 ) { if (colours == ZM_COLOUR_GRAY8) {
if ( *(buffer+index) != grayscale_val ) if (*(buffer+index) != grayscale_val)
return true; return true;
} else if ( colours == ZM_COLOUR_RGB24 ) { } else if (colours == ZM_COLOUR_RGB24) {
const uint8_t *ptr = buffer+(index*colours); const uint8_t *ptr = buffer+(index*colours);
if ( usedsubpixorder == ZM_SUBPIX_ORDER_BGR ) { if (usedsubpixorder == ZM_SUBPIX_ORDER_BGR) {
if ( (RED_PTR_BGRA(ptr) != red_val) || (GREEN_PTR_BGRA(ptr) != green_val) || (BLUE_PTR_BGRA(ptr) != blue_val) ) if ((RED_PTR_BGRA(ptr) != red_val) || (GREEN_PTR_BGRA(ptr) != green_val) || (BLUE_PTR_BGRA(ptr) != blue_val))
return true; return true;
} else { } else {
/* Assume RGB */ /* Assume RGB */
if ( (RED_PTR_RGBA(ptr) != red_val) || (GREEN_PTR_RGBA(ptr) != green_val) || (BLUE_PTR_RGBA(ptr) != blue_val) ) if ((RED_PTR_RGBA(ptr) != red_val) || (GREEN_PTR_RGBA(ptr) != green_val) || (BLUE_PTR_RGBA(ptr) != blue_val))
return true; return true;
} }
} else if ( colours == ZM_COLOUR_RGB32 ) { } else if (colours == ZM_COLOUR_RGB32) {
if ( usedsubpixorder == ZM_SUBPIX_ORDER_ARGB || usedsubpixorder == ZM_SUBPIX_ORDER_ABGR ) { if (usedsubpixorder == ZM_SUBPIX_ORDER_ARGB || usedsubpixorder == ZM_SUBPIX_ORDER_ABGR) {
if ( ARGB_ABGR_ZEROALPHA(*(((const Rgb*)buffer)+index)) != ARGB_ABGR_ZEROALPHA(colour_val) ) if (ARGB_ABGR_ZEROALPHA(*(((const Rgb*)buffer)+index)) != ARGB_ABGR_ZEROALPHA(colour_val))
return true; return true;
} else { } else {
/* Assume RGBA or BGRA */ /* Assume RGBA or BGRA */
if ( RGBA_BGRA_ZEROALPHA(*(((const Rgb*)buffer)+index)) != RGBA_BGRA_ZEROALPHA(colour_val) ) if (RGBA_BGRA_ZEROALPHA(*(((const Rgb*)buffer)+index)) != RGBA_BGRA_ZEROALPHA(colour_val))
return true; return true;
} }
} }
@ -1843,7 +1855,7 @@ bool Monitor::Analyse() {
/* try to stay behind the decoder. */ /* try to stay behind the decoder. */
if (decoding_enabled) { if (decoding_enabled) {
while (!snap->image and !snap->decoded and !zm_terminate and !analysis_thread->Stopped()) { while ((!snap->image or deinterlacing_value) and !snap->decoded and !zm_terminate and !analysis_thread->Stopped()) {
// Need to wait for the decoder thread. // Need to wait for the decoder thread.
Debug(1, "Waiting for decode"); Debug(1, "Waiting for decode");
packet_lock->wait(); packet_lock->wait();
@ -2832,7 +2844,7 @@ unsigned int Monitor::DetectMotion(const Image &comp_image, Event::StringSet &zo
} // end if CheckAlarms } // end if CheckAlarms
} // end foreach zone } // end foreach zone
Coord alarm_centre; Vector2 alarm_centre;
int top_score = -1; int top_score = -1;
if (alarm) { if (alarm) {
@ -2898,8 +2910,8 @@ unsigned int Monitor::DetectMotion(const Image &comp_image, Event::StringSet &zo
} // end if alarm } // end if alarm
if (top_score > 0) { if (top_score > 0) {
shared_data->alarm_x = alarm_centre.X(); shared_data->alarm_x = alarm_centre.x_;
shared_data->alarm_y = alarm_centre.Y(); shared_data->alarm_y = alarm_centre.y_;
Info("Got alarm centre at %d,%d, at count %d", Info("Got alarm centre at %d,%d, at count %d",
shared_data->alarm_x, shared_data->alarm_y, analysis_image_count); shared_data->alarm_x, shared_data->alarm_y, analysis_image_count);
@ -2954,7 +2966,7 @@ bool Monitor::DumpSettings(char *output, bool verbose) {
sprintf(output+strlen(output), "Subpixel Order : %u\n", camera->SubpixelOrder() ); sprintf(output+strlen(output), "Subpixel Order : %u\n", camera->SubpixelOrder() );
sprintf(output+strlen(output), "Event Prefix : %s\n", event_prefix.c_str() ); sprintf(output+strlen(output), "Event Prefix : %s\n", event_prefix.c_str() );
sprintf(output+strlen(output), "Label Format : %s\n", label_format.c_str() ); sprintf(output+strlen(output), "Label Format : %s\n", label_format.c_str() );
sprintf(output+strlen(output), "Label Coord : %d,%d\n", label_coord.X(), label_coord.Y() ); sprintf(output+strlen(output), "Label Coord : %d,%d\n", label_coord.x_, label_coord.y_ );
sprintf(output+strlen(output), "Label Size : %d\n", label_size ); sprintf(output+strlen(output), "Label Size : %d\n", label_size );
sprintf(output+strlen(output), "Image Buffer Count : %d\n", image_buffer_count ); sprintf(output+strlen(output), "Image Buffer Count : %d\n", image_buffer_count );
sprintf(output+strlen(output), "Warmup Count : %d\n", warmup_count ); sprintf(output+strlen(output), "Warmup Count : %d\n", warmup_count );

View File

@ -305,7 +305,7 @@ protected:
std::string event_prefix; // The prefix applied to event names as they are created std::string event_prefix; // The prefix applied to event names as they are created
std::string label_format; // The format of the timestamp on the images std::string label_format; // The format of the timestamp on the images
Coord label_coord; // The coordinates of the timestamp on the images Vector2 label_coord; // The coordinates of the timestamp on the images
int label_size; // Size of the timestamp on the images int label_size; // Size of the timestamp on the images
int32_t image_buffer_count; // Size of circular image buffer, kept in /dev/shm int32_t image_buffer_count; // Size of circular image buffer, kept in /dev/shm
int32_t max_image_buffer_count; // Max # of video packets to keep in packet queue int32_t max_image_buffer_count; // Max # of video packets to keep in packet queue

View File

@ -107,7 +107,7 @@ ZMPacket::~ZMPacket() {
int ZMPacket::decode(AVCodecContext *ctx) { int ZMPacket::decode(AVCodecContext *ctx) {
Debug(4, "about to decode video, image_index is (%d)", image_index); Debug(4, "about to decode video, image_index is (%d)", image_index);
if ( in_frame ) { if (in_frame) {
Error("Already have a frame?"); Error("Already have a frame?");
} else { } else {
in_frame = zm_av_frame_alloc(); in_frame = zm_av_frame_alloc();
@ -117,8 +117,8 @@ int ZMPacket::decode(AVCodecContext *ctx) {
//av_packet_rescale_ts(&packet, AV_TIME_BASE_Q, ctx->time_base); //av_packet_rescale_ts(&packet, AV_TIME_BASE_Q, ctx->time_base);
int ret = zm_send_packet_receive_frame(ctx, in_frame, packet); int ret = zm_send_packet_receive_frame(ctx, in_frame, packet);
if ( ret < 0 ) { if (ret < 0) {
if ( AVERROR(EAGAIN) != ret ) { if (AVERROR(EAGAIN) != ret) {
Warning("Unable to receive frame : code %d %s.", Warning("Unable to receive frame : code %d %s.",
ret, av_make_error_string(ret).c_str()); ret, av_make_error_string(ret).c_str());
} }
@ -126,7 +126,7 @@ int ZMPacket::decode(AVCodecContext *ctx) {
return 0; return 0;
} }
int bytes_consumed = ret; int bytes_consumed = ret;
if ( ret > 0 ) { if (ret > 0) {
zm_dump_video_frame(in_frame, "got frame"); zm_dump_video_frame(in_frame, "got frame");
#if HAVE_LIBAVUTIL_HWCONTEXT_H #if HAVE_LIBAVUTIL_HWCONTEXT_H
@ -258,9 +258,11 @@ AVFrame *ZMPacket::get_out_frame(int width, int height, AVPixelFormat format) {
} }
#if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0) #if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0)
int alignment = 32;
if (width%alignment) alignment = 1;
codec_imgsize = av_image_get_buffer_size( codec_imgsize = av_image_get_buffer_size(
format, width, height, 32); format, width, height, alignment);
Debug(1, "buffer size %u from %s %dx%d", codec_imgsize, av_get_pix_fmt_name(format), width, height); Debug(1, "buffer size %u from %s %dx%d", codec_imgsize, av_get_pix_fmt_name(format), width, height);
buffer = (uint8_t *)av_malloc(codec_imgsize); buffer = (uint8_t *)av_malloc(codec_imgsize);
int ret; int ret;
@ -271,7 +273,7 @@ AVFrame *ZMPacket::get_out_frame(int width, int height, AVPixelFormat format) {
format, format,
width, width,
height, height,
32))<0) { alignment))<0) {
Error("Failed to fill_arrays %s", av_make_error_string(ret).c_str()); Error("Failed to fill_arrays %s", av_make_error_string(ret).c_str());
av_frame_free(&out_frame); av_frame_free(&out_frame);
return nullptr; return nullptr;

View File

@ -19,91 +19,103 @@
#include "zm_poly.h" #include "zm_poly.h"
#include "zm_line.h"
#include <cmath> #include <cmath>
void Polygon::calcArea() { Polygon::Polygon(std::vector<Vector2> vertices) : vertices_(std::move(vertices)), area(0) {
double float_area = 0.0L; UpdateExtent();
for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ ) { UpdateArea();
double trap_area = ((coords[i].X()-coords[j].X())*((coords[i].Y()+coords[j].Y())))/2.0L; UpdateCentre();
}
void Polygon::UpdateExtent() {
if (vertices_.empty())
return;
int min_x = vertices_[0].x_;
int max_x = 0;
int min_y = vertices_[0].y_;
int max_y = 0;
for (const Vector2 &vertex : vertices_) {
min_x = std::min(min_x, vertex.x_);
max_x = std::max(max_x, vertex.x_);
min_y = std::min(min_y, vertex.y_);
max_y = std::max(max_y, vertex.y_);
}
extent = Box({min_x, min_y}, {max_x, max_y});
}
void Polygon::UpdateArea() {
double float_area = 0.0;
for (size_t i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
double trap_area = ((vertices_[i].x_ - vertices_[j].x_) * ((vertices_[i].y_ + vertices_[j].y_))) / 2.0;
float_area += trap_area; float_area += trap_area;
//printf( "%.2f (%.2f)\n", float_area, trap_area );
} }
area = (int)round(fabs(float_area));
area = static_cast<int32>(std::lround(std::fabs(float_area)));
} }
void Polygon::calcCentre() { void Polygon::UpdateCentre() {
if ( !area && n_coords ) if (!area && !vertices_.empty())
calcArea(); UpdateArea();
double float_x = 0.0L, float_y = 0.0L;
for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ ) { double float_x = 0.0;
float_x += ((coords[i].Y()-coords[j].Y())*((coords[i].X()*2)+(coords[i].X()*coords[j].X())+(coords[j].X()*2))); double float_y = 0.0;
float_y += ((coords[j].X()-coords[i].X())*((coords[i].Y()*2)+(coords[i].Y()*coords[j].Y())+(coords[j].Y()*2))); for (size_t i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
float_x += ((vertices_[i].y_ - vertices_[j].y_)
* ((vertices_[i].x_ * 2) + (vertices_[i].x_ * vertices_[j].x_) + (vertices_[j].x_ * 2)));
float_y += ((vertices_[j].x_ - vertices_[i].x_)
* ((vertices_[i].y_ * 2) + (vertices_[i].y_ * vertices_[j].y_) + (vertices_[j].y_ * 2)));
} }
float_x /= (6*area); float_x /= (6 * area);
float_y /= (6*area); float_y /= (6 * area);
centre = Coord( (int)round(float_x), (int)round(float_y) );
centre = Vector2(static_cast<int32>(std::lround(float_x)), static_cast<int32>(std::lround(float_y)));
} }
Polygon::Polygon(int p_n_coords, const Coord *p_coords) : n_coords(p_n_coords) { bool Polygon::Contains(const Vector2 &coord) const {
coords = new Coord[n_coords];
int min_x = -1;
int max_x = -1;
int min_y = -1;
int max_y = -1;
for ( int i = 0; i < n_coords; i++ ) {
coords[i] = p_coords[i];
if ( min_x == -1 || coords[i].X() < min_x )
min_x = coords[i].X();
if ( max_x == -1 || coords[i].X() > max_x )
max_x = coords[i].X();
if ( min_y == -1 || coords[i].Y() < min_y )
min_y = coords[i].Y();
if ( max_y == -1 || coords[i].Y() > max_y )
max_y = coords[i].Y();
}
extent = Box( min_x, min_y, max_x, max_y );
calcArea();
calcCentre();
}
Polygon::Polygon(const Polygon &p_polygon) :
n_coords(p_polygon.n_coords),
extent(p_polygon.extent),
area(p_polygon.area),
centre(p_polygon.centre)
{
coords = new Coord[n_coords];
for( int i = 0; i < n_coords; i++ ) {
coords[i] = p_polygon.coords[i];
}
}
Polygon &Polygon::operator=(const Polygon &p_polygon) {
n_coords = p_polygon.n_coords;
Coord *new_coords = new Coord[n_coords];
for (int i = 0; i < n_coords; i++) {
new_coords[i] = p_polygon.coords[i];
}
delete[] coords;
coords = new_coords;
extent = p_polygon.extent;
area = p_polygon.area;
centre = p_polygon.centre;
return *this;
}
bool Polygon::isInside( const Coord &coord ) const {
bool inside = false; bool inside = false;
for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ ) { for (size_t i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
if ( (((coords[i].Y() <= coord.Y()) && (coord.Y() < coords[j].Y()) ) if ((((vertices_[i].y_ <= coord.y_) && (coord.y_ < vertices_[j].y_)) || ((vertices_[j].y_ <= coord.y_) && (coord.y_ < vertices_[i].y_)))
|| ((coords[j].Y() <= coord.Y()) && (coord.Y() < coords[i].Y()))) && (coord.x_ < (vertices_[j].x_ - vertices_[i].x_) * (coord.y_ - vertices_[i].y_) / (vertices_[j].y_ - vertices_[i].y_) + vertices_[i].x_)) {
&& (coord.X() < (coords[j].X() - coords[i].X()) * (coord.Y() - coords[i].Y()) / (coords[j].Y() - coords[i].Y()) + coords[i].X()))
{
inside = !inside; inside = !inside;
} }
} }
return inside; return inside;
} }
// Clip the polygon to a rectangular boundary box using the Sutherland-Hodgman algorithm
void Polygon::Clip(const Box &boundary) {
std::vector<Vector2> clipped_vertices = vertices_;
for (LineSegment const &clip_edge : boundary.Edges()) {
// convert our line segment to an infinite line
Line clip_line = Line(clip_edge);
std::vector<Vector2> to_clip = clipped_vertices;
clipped_vertices.clear();
for (size_t i = 0; i < to_clip.size(); ++i) {
Vector2 vert1 = to_clip[i];
Vector2 vert2 = to_clip[(i + 1) % to_clip.size()];
bool vert1_left = clip_line.IsPointLeftOfOrColinear(vert1);
bool vert2_left = clip_line.IsPointLeftOfOrColinear(vert2);
if (vert2_left) {
if (!vert1_left) {
clipped_vertices.push_back(Line(vert1, vert2).Intersection(clip_line));
}
clipped_vertices.push_back(vert2);
} else if (vert1_left) {
clipped_vertices.push_back(Line(vert1, vert2).Intersection(clip_line));
}
}
}
vertices_ = clipped_vertices;
UpdateExtent();
UpdateArea();
UpdateCentre();
}

View File

@ -21,96 +21,36 @@
#define ZM_POLY_H #define ZM_POLY_H
#include "zm_box.h" #include "zm_box.h"
#include <vector>
class Coord; // This class represents convex or concave non-self-intersecting polygons.
//
// Class used for storing a box, which is defined as a region
// defined by two coordinates
//
class Polygon { class Polygon {
protected: public:
struct Edge { Polygon() : area(0) {}
int min_y; explicit Polygon(std::vector<Vector2> vertices);
int max_y;
double min_x;
double _1_m;
static int CompareYX( const void *p1, const void *p2 ) { const std::vector<Vector2> &GetVertices() const {
const Edge *e1 = reinterpret_cast<const Edge *>(p1), *e2 = reinterpret_cast<const Edge *>(p2); return vertices_;
if ( e1->min_y == e2->min_y ) }
return int(e1->min_x - e2->min_x);
else
return int(e1->min_y - e2->min_y);
}
static int CompareX( const void *p1, const void *p2 ) {
const Edge *e1 = reinterpret_cast<const Edge *>(p1), *e2 = reinterpret_cast<const Edge *>(p2);
return int(e1->min_x - e2->min_x);
}
};
struct Slice { const Box &Extent() const { return extent; }
int min_x; int32 Area() const { return area; }
int max_x; const Vector2 &Centre() const { return centre; }
int n_edges;
int *edges;
Slice() { bool Contains(const Vector2 &coord) const;
min_x = 0;
max_x = 0;
n_edges = 0;
edges = nullptr;
}
~Slice() {
delete edges;
}
};
protected: void Clip(const Box &boundary);
int n_coords;
Coord *coords; private:
void UpdateExtent();
void UpdateArea();
void UpdateCentre();
private:
std::vector<Vector2> vertices_;
Box extent; Box extent;
int area; int32 area;
Coord centre; Vector2 centre;
protected:
void initialiseEdges();
void calcArea();
void calcCentre();
public:
inline Polygon() : n_coords(0), coords(nullptr), area(0) {
}
Polygon(int p_n_coords, const Coord *p_coords);
Polygon(const Polygon &p_polygon);
~Polygon() {
delete[] coords;
}
Polygon &operator=( const Polygon &p_polygon );
inline int getNumCoords() const { return n_coords; }
inline const Coord &getCoord( int index ) const {
return coords[index];
}
inline const Box &Extent() const { return extent; }
inline int LoX() const { return extent.LoX(); }
inline int LoX(int p_lo_x) { return extent.LoX(p_lo_x); }
inline int HiX() const { return extent.HiX(); }
inline int HiX(int p_hi_x) { return extent.HiX(p_hi_x); }
inline int LoY() const { return extent.LoY(); }
inline int LoY(int p_lo_y) { return extent.LoY(p_lo_y); }
inline int HiY() const { return extent.HiY(); }
inline int HiY(int p_hi_y) { return extent.HiY(p_hi_y); }
inline int Width() const { return extent.Width(); }
inline int Height() const { return extent.Height(); }
inline int Area() const { return area; }
inline const Coord &Centre() const {
return centre;
}
bool isInside( const Coord &coord ) const;
}; };
#endif // ZM_POLY_H #endif // ZM_POLY_H

View File

@ -20,6 +20,7 @@
#include "zm_logger.h" #include "zm_logger.h"
#include "zm_utils.h" #include "zm_utils.h"
#include <cassert>
#include <cstring> #include <cstring>
namespace zm { namespace zm {
@ -131,9 +132,9 @@ std::string Authenticator::computeDigestResponse(const std::string &method, cons
#if HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT #if HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT
// The "response" field is computed as: // The "response" field is computed as:
// md5(md5(<username>:<realm>:<password>):<nonce>:md5(<cmd>:<url>)) // md5(md5(<username>:<realm>:<password>):<nonce>:md5(<cmd>:<url>))
size_t md5len = 16; constexpr size_t md5len = 16;
unsigned char md5buf[md5len]; uint8 md5buf[md5len];
char md5HexBuf[md5len*2+1]; char md5HexBuf[md5len * 2 + 1];
// Step 1: md5(<username>:<realm>:<password>) // Step 1: md5(<username>:<realm>:<password>)
std::string ha1Data = username() + ":" + realm() + ":" + password(); std::string ha1Data = username() + ":" + realm() + ":" + password();
@ -141,8 +142,10 @@ std::string Authenticator::computeDigestResponse(const std::string &method, cons
#if HAVE_DECL_MD5 #if HAVE_DECL_MD5
MD5((unsigned char*)ha1Data.c_str(), ha1Data.length(), md5buf); MD5((unsigned char*)ha1Data.c_str(), ha1Data.length(), md5buf);
#elif HAVE_DECL_GNUTLS_FINGERPRINT #elif HAVE_DECL_GNUTLS_FINGERPRINT
gnutls_datum_t md5dataha1 = { (unsigned char*)ha1Data.c_str(), (unsigned int)ha1Data.length() }; gnutls_datum_t md5dataha1 = {(unsigned char *) ha1Data.c_str(), (unsigned int) ha1Data.length()};
gnutls_fingerprint( GNUTLS_DIG_MD5, &md5dataha1, md5buf, &md5len ); size_t md5_len_tmp = md5len;
gnutls_fingerprint(GNUTLS_DIG_MD5, &md5dataha1, md5buf, &md5_len_tmp);
assert(md5_len_tmp == md5len);
#endif #endif
for ( unsigned int j = 0; j < md5len; j++ ) { for ( unsigned int j = 0; j < md5len; j++ ) {
sprintf(&md5HexBuf[2*j], "%02x", md5buf[j] ); sprintf(&md5HexBuf[2*j], "%02x", md5buf[j] );
@ -156,8 +159,10 @@ std::string Authenticator::computeDigestResponse(const std::string &method, cons
#if HAVE_DECL_MD5 #if HAVE_DECL_MD5
MD5((unsigned char*)ha2Data.c_str(), ha2Data.length(), md5buf ); MD5((unsigned char*)ha2Data.c_str(), ha2Data.length(), md5buf );
#elif HAVE_DECL_GNUTLS_FINGERPRINT #elif HAVE_DECL_GNUTLS_FINGERPRINT
gnutls_datum_t md5dataha2 = { (unsigned char*)ha2Data.c_str(), (unsigned int)ha2Data.length() }; gnutls_datum_t md5dataha2 = {(unsigned char *) ha2Data.c_str(), (unsigned int) ha2Data.length()};
gnutls_fingerprint( GNUTLS_DIG_MD5, &md5dataha2, md5buf, &md5len ); md5_len_tmp = md5len;
gnutls_fingerprint(GNUTLS_DIG_MD5, &md5dataha2, md5buf, &md5_len_tmp);
assert(md5_len_tmp == md5len);
#endif #endif
for ( unsigned int j = 0; j < md5len; j++ ) { for ( unsigned int j = 0; j < md5len; j++ ) {
sprintf( &md5HexBuf[2*j], "%02x", md5buf[j] ); sprintf( &md5HexBuf[2*j], "%02x", md5buf[j] );
@ -177,8 +182,10 @@ std::string Authenticator::computeDigestResponse(const std::string &method, cons
#if HAVE_DECL_MD5 #if HAVE_DECL_MD5
MD5((unsigned char*)digestData.c_str(), digestData.length(), md5buf); MD5((unsigned char*)digestData.c_str(), digestData.length(), md5buf);
#elif HAVE_DECL_GNUTLS_FINGERPRINT #elif HAVE_DECL_GNUTLS_FINGERPRINT
gnutls_datum_t md5datadigest = { (unsigned char*)digestData.c_str(), (unsigned int)digestData.length() }; gnutls_datum_t md5datadigest = {(unsigned char *) digestData.c_str(), (unsigned int) digestData.length()};
gnutls_fingerprint( GNUTLS_DIG_MD5, &md5datadigest, md5buf, &md5len ); md5_len_tmp = md5len;
gnutls_fingerprint(GNUTLS_DIG_MD5, &md5datadigest, md5buf, &md5_len_tmp);
assert(md5_len_tmp == md5len);
#endif #endif
for ( unsigned int j = 0; j < md5len; j++ ) { for ( unsigned int j = 0; j < md5len; j++ ) {
sprintf( &md5HexBuf[2*j], "%02x", md5buf[j] ); sprintf( &md5HexBuf[2*j], "%02x", md5buf[j] );

View File

@ -204,10 +204,10 @@ Image *StreamBase::prepareImage(Image *image) {
last_crop = Box(); last_crop = Box();
// Recalculate crop parameters, as %ges // Recalculate crop parameters, as %ges
int click_x = (last_crop.LoX() * 100 ) / last_act_image_width; // Initial crop offset from last image int click_x = (last_crop.Lo().x_ * 100) / last_act_image_width; // Initial crop offset from last image
click_x += ( x * 100 ) / last_virt_image_width; click_x += (x * 100) / last_virt_image_width;
int click_y = (last_crop.LoY() * 100 ) / last_act_image_height; // Initial crop offset from last image int click_y = (last_crop.Lo().y_ * 100) / last_act_image_height; // Initial crop offset from last image
click_y += ( y * 100 ) / last_virt_image_height; click_y += (y * 100) / last_virt_image_height;
Debug(3, "Got adjusted click at %d%%,%d%%", click_x, click_y); Debug(3, "Got adjusted click at %d%%,%d%%", click_x, click_y);
// Convert the click locations to the current image pixels // Convert the click locations to the current image pixels
@ -231,10 +231,10 @@ Image *StreamBase::prepareImage(Image *image) {
hi_y = act_image_height - 1; hi_y = act_image_height - 1;
lo_y = hi_y - (send_image_height - 1); lo_y = hi_y - (send_image_height - 1);
} }
last_crop = Box( lo_x, lo_y, hi_x, hi_y ); last_crop = Box({lo_x, lo_y}, {hi_x, hi_y});
} // end if ( mag != last_mag || x != last_x || y != last_y ) } // end if ( mag != last_mag || x != last_x || y != last_y )
Debug(3, "Cropping to %d,%d -> %d,%d", last_crop.LoX(), last_crop.LoY(), last_crop.HiX(), last_crop.HiY()); Debug(3, "Cropping to %d,%d -> %d,%d", last_crop.Lo().x_, last_crop.Lo().y_, last_crop.Hi().x_, last_crop.Hi().y_);
if ( !image_copied ) { if ( !image_copied ) {
static Image copy_image; static Image copy_image;
copy_image.Assign(*image); copy_image.Assign(*image);

View File

@ -128,11 +128,11 @@ int SWScale::Convert(
in_buffer, in_buffer_size, out_buffer, out_buffer_size, width, height, new_width, new_height, in_buffer, in_buffer_size, out_buffer, out_buffer_size, width, height, new_width, new_height,
in_pf, out_pf); in_pf, out_pf);
/* Parameter checking */ /* Parameter checking */
if ( in_buffer == nullptr ) { if (in_buffer == nullptr) {
Error("NULL Input buffer"); Error("NULL Input buffer");
return -1; return -1;
} }
if ( out_buffer == nullptr ) { if (out_buffer == nullptr) {
Error("NULL output buffer"); Error("NULL output buffer");
return -1; return -1;
} }
@ -140,7 +140,7 @@ int SWScale::Convert(
// Error("Invalid input or output pixel formats"); // Error("Invalid input or output pixel formats");
// return -2; // return -2;
// } // }
if ( !width || !height || !new_height || !new_width ) { if (!width || !height || !new_height || !new_width) {
Error("Invalid width or height"); Error("Invalid width or height");
return -3; return -3;
} }
@ -149,21 +149,21 @@ int SWScale::Convert(
#if LIBSWSCALE_VERSION_CHECK(0, 8, 0, 8, 0) #if LIBSWSCALE_VERSION_CHECK(0, 8, 0, 8, 0)
/* Warn if the input or output pixelformat is not supported */ /* Warn if the input or output pixelformat is not supported */
if ( !sws_isSupportedInput(in_pf) ) { if (!sws_isSupportedInput(in_pf)) {
Warning("swscale does not support the input format: %c%c%c%c", Warning("swscale does not support the input format: %c%c%c%c",
(in_pf)&0xff,((in_pf)&0xff),((in_pf>>16)&0xff),((in_pf>>24)&0xff)); (in_pf)&0xff,((in_pf)&0xff),((in_pf>>16)&0xff),((in_pf>>24)&0xff));
} }
if ( !sws_isSupportedOutput(out_pf) ) { if (!sws_isSupportedOutput(out_pf)) {
Warning("swscale does not support the output format: %c%c%c%c", Warning("swscale does not support the output format: %c%c%c%c",
(out_pf)&0xff,((out_pf>>8)&0xff),((out_pf>>16)&0xff),((out_pf>>24)&0xff)); (out_pf)&0xff,((out_pf>>8)&0xff),((out_pf>>16)&0xff),((out_pf>>24)&0xff));
} }
#endif #endif
int alignment = 1; int alignment = width % 32 ? 1 : 32;
/* Check the buffer sizes */ /* Check the buffer sizes */
size_t needed_insize = GetBufferSize(in_pf, width, height); size_t needed_insize = GetBufferSize(in_pf, width, height);
if ( needed_insize > in_buffer_size ) { if (needed_insize > in_buffer_size) {
Debug(1, Warning(
"The input buffer size does not match the expected size for the input format. Required: %zu for %dx%d %d Available: %zu", "The input buffer size does not match the expected size for the input format. Required: %zu for %dx%d %d Available: %zu",
needed_insize, needed_insize,
width, width,
@ -172,7 +172,7 @@ int SWScale::Convert(
in_buffer_size); in_buffer_size);
} }
size_t needed_outsize = GetBufferSize(out_pf, new_width, new_height); size_t needed_outsize = GetBufferSize(out_pf, new_width, new_height);
if ( needed_outsize > out_buffer_size ) { if (needed_outsize > out_buffer_size) {
Error("The output buffer is undersized for the output format. Required: %zu Available: %zu", Error("The output buffer is undersized for the output format. Required: %zu Available: %zu",
needed_outsize, needed_outsize,
out_buffer_size); out_buffer_size);
@ -184,11 +184,19 @@ int SWScale::Convert(
width, height, in_pf, width, height, in_pf,
new_width, new_height, out_pf, new_width, new_height, out_pf,
SWS_FAST_BILINEAR, nullptr, nullptr, nullptr); SWS_FAST_BILINEAR, nullptr, nullptr, nullptr);
if ( swscale_ctx == nullptr ) { if (swscale_ctx == nullptr) {
Error("Failed getting swscale context"); Error("Failed getting swscale context");
return -6; return -6;
} }
/*
input_avframe->format = in_pf;
input_avframe->width = width;
input_avframe->height = height;
output_avframe->format = out_pf;
output_avframe->width = new_width;
output_avframe->height = new_height;
*/
/* Fill in the buffers */ /* Fill in the buffers */
#if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0) #if LIBAVUTIL_VERSION_CHECK(54, 6, 0, 6, 0)
if (av_image_fill_arrays(input_avframe->data, input_avframe->linesize, if (av_image_fill_arrays(input_avframe->data, input_avframe->linesize,

View File

@ -22,6 +22,7 @@
#include "zm_crypt.h" #include "zm_crypt.h"
#include "zm_logger.h" #include "zm_logger.h"
#include "zm_utils.h" #include "zm_utils.h"
#include <cassert>
#include <cstring> #include <cstring>
#if HAVE_GNUTLS_GNUTLS_H #if HAVE_GNUTLS_GNUTLS_H
@ -236,8 +237,8 @@ User *zmLoadAuthUser(const char *auth, bool use_remote_addr) {
} }
char auth_key[512] = ""; char auth_key[512] = "";
char auth_md5[32+1] = ""; char auth_md5[32+1] = "";
size_t md5len = 16; constexpr size_t md5len = 16;
unsigned char md5sum[md5len]; uint8 md5sum[md5len];
const char * hex = "0123456789abcdef"; const char * hex = "0123456789abcdef";
while ( MYSQL_ROW dbrow = mysql_fetch_row(result) ) { while ( MYSQL_ROW dbrow = mysql_fetch_row(result) ) {
@ -262,8 +263,10 @@ User *zmLoadAuthUser(const char *auth, bool use_remote_addr) {
#if HAVE_DECL_MD5 #if HAVE_DECL_MD5
MD5((unsigned char *)auth_key, strlen(auth_key), md5sum); MD5((unsigned char *)auth_key, strlen(auth_key), md5sum);
#elif HAVE_DECL_GNUTLS_FINGERPRINT #elif HAVE_DECL_GNUTLS_FINGERPRINT
gnutls_datum_t md5data = { (unsigned char *)auth_key, (unsigned int)strlen(auth_key) }; gnutls_datum_t md5data = {(unsigned char *) auth_key, (unsigned int) strlen(auth_key)};
gnutls_fingerprint(GNUTLS_DIG_MD5, &md5data, md5sum, &md5len); size_t md5_len_tmp = md5len;
gnutls_fingerprint(GNUTLS_DIG_MD5, &md5data, md5sum, &md5_len_tmp);
assert(md5_len_tmp == md5len);
#endif #endif
unsigned char *md5sum_ptr = md5sum; unsigned char *md5sum_ptr = md5sum;
char *auth_md5_ptr = auth_md5; char *auth_md5_ptr = auth_md5;

80
src/zm_vector2.h Normal file
View File

@ -0,0 +1,80 @@
//
// ZoneMinder Coordinate Class Interface, $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_VECTOR2_H
#define ZM_VECTOR2_H
#include "zm_define.h"
#include <cmath>
#include <limits>
//
// Class used for storing an x,y pair, i.e. a coordinate/vector
//
class Vector2 {
public:
Vector2() : x_(0), y_(0) {}
Vector2(int32 x, int32 y) : x_(x), y_(y) {}
static Vector2 Inf() {
static const Vector2 inf = {std::numeric_limits<int32>::max(), std::numeric_limits<int32>::max()};
return inf;
}
bool operator==(const Vector2 &rhs) const { return (x_ == rhs.x_ && y_ == rhs.y_); }
bool operator!=(const Vector2 &rhs) const { return (x_ != rhs.x_ || y_ != rhs.y_); }
// These operators are not idiomatic. If lexicographic comparison is needed, it should be implemented separately.
bool operator>(const Vector2 &rhs) const = delete;
bool operator>=(const Vector2 &rhs) const = delete;
bool operator<(const Vector2 &rhs) const = delete;
bool operator<=(const Vector2 &rhs) const = delete;
Vector2 operator+(const Vector2 &rhs) const {
return {x_ + rhs.x_, y_ + rhs.y_};
}
Vector2 operator-(const Vector2 &rhs) const {
return {x_ - rhs.x_, y_ - rhs.y_};
}
Vector2 operator*(double rhs) const {
return {static_cast<int32>(std::lround(x_ * rhs)), static_cast<int32>(std::lround(y_ * rhs))};
}
Vector2 &operator+=(const Vector2 &rhs) {
x_ += rhs.x_;
y_ += rhs.y_;
return *this;
}
Vector2 &operator-=(const Vector2 &rhs) {
x_ -= rhs.x_;
y_ -= rhs.y_;
return *this;
}
// Calculated the determinant of the 2x2 matrix as given by [[x_, y_], [v.x_y, v.y_]]
int32 Determinant(Vector2 const &v) const {
return (x_ * v.y_) - (y_ * v.x_);
}
public:
int32 x_;
int32 y_;
};
#endif // ZM_VECTOR2_H

View File

@ -115,7 +115,7 @@ bool VideoStore::open() {
Debug(1, "Opening video storage stream %s format: %s", filename, format); Debug(1, "Opening video storage stream %s format: %s", filename, format);
int ret = avformat_alloc_output_context2(&oc, nullptr, nullptr, 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"
" could be assigned based on filename: %s", " could be assigned based on filename: %s",
@ -123,9 +123,9 @@ bool VideoStore::open() {
} }
// 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, nullptr, 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"
" could not be assigned based on filename or format %s", " could not be assigned based on filename or format %s",
@ -142,11 +142,11 @@ bool VideoStore::open() {
out_format = oc->oformat; out_format = oc->oformat;
out_format->flags |= AVFMT_TS_NONSTRICT; // allow non increasing dts out_format->flags |= AVFMT_TS_NONSTRICT; // allow non increasing dts
if ( video_in_stream ) { if (video_in_stream) {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
zm_dump_codecpar(video_in_stream->codecpar); zm_dump_codecpar(video_in_stream->codecpar);
#endif #endif
if ( monitor->GetOptVideoWriter() == Monitor::PASSTHROUGH ) { if (monitor->GetOptVideoWriter() == Monitor::PASSTHROUGH) {
// Don't care what codec, just copy parameters // Don't care what codec, just copy parameters
video_out_ctx = avcodec_alloc_context3(nullptr); video_out_ctx = avcodec_alloc_context3(nullptr);
// There might not be a useful video_in_stream. v4l in might not populate this very // There might not be a useful video_in_stream. v4l in might not populate this very
@ -155,12 +155,12 @@ bool VideoStore::open() {
#else #else
ret = avcodec_copy_context(video_out_ctx, video_in_ctx); ret = avcodec_copy_context(video_out_ctx, video_in_ctx);
#endif #endif
if ( ret < 0 ) { if (ret < 0) {
Error("Could not initialize ctx parameters"); Error("Could not initialize ctx parameters");
return false; return false;
} }
video_out_ctx->pix_fmt = fix_deprecated_pix_fmt(video_out_ctx->pix_fmt); video_out_ctx->pix_fmt = fix_deprecated_pix_fmt(video_out_ctx->pix_fmt);
if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) { if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
#if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0)
video_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; video_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
#else #else
@ -168,19 +168,19 @@ bool VideoStore::open() {
#endif #endif
} }
video_out_ctx->time_base = video_in_ctx->time_base; video_out_ctx->time_base = video_in_ctx->time_base;
if ( ! (video_out_ctx->time_base.num && video_out_ctx->time_base.den) ) { if (!(video_out_ctx->time_base.num && video_out_ctx->time_base.den)) {
Debug(2,"No timebase found in video in context, defaulting to Q"); Debug(2,"No timebase found in video in context, defaulting to Q");
video_out_ctx->time_base = AV_TIME_BASE_Q; video_out_ctx->time_base = AV_TIME_BASE_Q;
} }
} else if ( monitor->GetOptVideoWriter() == Monitor::ENCODE ) { } else if (monitor->GetOptVideoWriter() == Monitor::ENCODE) {
int wanted_codec = monitor->OutputCodec(); int wanted_codec = monitor->OutputCodec();
if ( !wanted_codec ) { if (!wanted_codec) {
// default to h264 // default to h264
//Debug(2, "Defaulting to H264"); //Debug(2, "Defaulting to H264");
//wanted_codec = AV_CODEC_ID_H264; //wanted_codec = AV_CODEC_ID_H264;
// FIXME what is the optimal codec? Probably low latency h264 which is effectively mjpeg // FIXME what is the optimal codec? Probably low latency h264 which is effectively mjpeg
} else { } else {
if ( AV_CODEC_ID_H264 != 27 and wanted_codec > 3 ) { if (AV_CODEC_ID_H264 != 27 and wanted_codec > 3) {
// Older ffmpeg had AV_CODEC_ID_MPEG2VIDEO_XVMC at position 3 has been deprecated // Older ffmpeg had AV_CODEC_ID_MPEG2VIDEO_XVMC at position 3 has been deprecated
wanted_codec += 1; wanted_codec += 1;
} }
@ -233,14 +233,14 @@ bool VideoStore::open() {
video_out_ctx->height = monitor->Height(); video_out_ctx->height = monitor->Height();
video_out_ctx->codec_type = AVMEDIA_TYPE_VIDEO; video_out_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
if ( video_out_ctx->codec_id == AV_CODEC_ID_H264 ) { if (video_out_ctx->codec_id == AV_CODEC_ID_H264) {
video_out_ctx->bit_rate = 2000000; video_out_ctx->bit_rate = 2000000;
video_out_ctx->gop_size = 12; video_out_ctx->gop_size = 12;
video_out_ctx->max_b_frames = 1; video_out_ctx->max_b_frames = 1;
} else if ( video_out_ctx->codec_id == AV_CODEC_ID_MPEG2VIDEO ) { } else if (video_out_ctx->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
/* just for testing, we also add B frames */ /* just for testing, we also add B frames */
video_out_ctx->max_b_frames = 2; video_out_ctx->max_b_frames = 2;
} else if ( video_out_ctx->codec_id == AV_CODEC_ID_MPEG1VIDEO ) { } else if (video_out_ctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
/* Needed to avoid using macroblocks in which some coeffs overflow. /* Needed to avoid using macroblocks in which some coeffs overflow.
* This does not happen with normal video, it just happens here as * This does not happen with normal video, it just happens here as
* the motion of the chroma plane does not match the luma plane. */ * the motion of the chroma plane does not match the luma plane. */
@ -272,7 +272,7 @@ bool VideoStore::open() {
frames_ctx->initial_pool_size = 20; frames_ctx->initial_pool_size = 20;
if ((ret = av_hwframe_ctx_init(hw_frames_ref)) < 0) { if ((ret = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
Error("Failed to initialize hwaccel frame context." Error("Failed to initialize hwaccel frame context."
"Error code: %s",av_err2str(ret)); "Error code: %s", av_err2str(ret));
av_buffer_unref(&hw_frames_ref); av_buffer_unref(&hw_frames_ref);
} else { } else {
video_out_ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref); video_out_ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
@ -281,7 +281,8 @@ bool VideoStore::open() {
} }
} }
av_buffer_unref(&hw_frames_ref); av_buffer_unref(&hw_frames_ref);
} av_buffer_unref(&hw_device_ctx);
} // end if hwdevice_type != NONE
#endif #endif
AVDictionary *opts = 0; AVDictionary *opts = 0;
@ -289,7 +290,7 @@ bool VideoStore::open() {
Debug(2, "Options? %s", Options.c_str()); Debug(2, "Options? %s", Options.c_str());
ret = av_dict_parse_string(&opts, Options.c_str(), "=", ",#\n", 0); ret = av_dict_parse_string(&opts, Options.c_str(), "=", ",#\n", 0);
if (ret < 0) { if (ret < 0) {
Warning("Could not parse ffmpeg encoder options list '%s'\n", Options.c_str()); Warning("Could not parse ffmpeg encoder options list '%s'", Options.c_str());
} else { } else {
AVDictionaryEntry *e = nullptr; AVDictionaryEntry *e = nullptr;
while ((e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr) { while ((e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr) {
@ -312,22 +313,20 @@ bool VideoStore::open() {
video_out_codec = nullptr; video_out_codec = nullptr;
} }
Debug(1, "Success");
AVDictionaryEntry *e = nullptr; AVDictionaryEntry *e = nullptr;
while ((e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr) { 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);
} }
if (video_out_codec) break; if (video_out_codec) break;
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// We allocate and copy in newer ffmpeg, so need to free it
avcodec_free_context(&video_out_ctx); avcodec_free_context(&video_out_ctx);
if (hw_device_ctx) av_buffer_unref(&hw_device_ctx); if (hw_device_ctx) av_buffer_unref(&hw_device_ctx);
#endif
} // end foreach codec } // end foreach codec
if (!video_out_codec) { if (!video_out_codec) {
Error("Can't open video codec!"); Error("Can't open video codec!");
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// We allocate and copy in newer ffmpeg, so need to free it
avcodec_free_context(&video_out_ctx);
#endif
return false; return false;
} // end if can't open codec } // end if can't open codec
Debug(2, "Success opening codec"); Debug(2, "Success opening codec");
@ -336,7 +335,7 @@ bool VideoStore::open() {
} // end if video_in_stream } // end if video_in_stream
video_out_stream = avformat_new_stream(oc, video_out_codec); video_out_stream = avformat_new_stream(oc, video_out_codec);
if ( !video_out_stream ) { if (!video_out_stream) {
Error("Unable to create video out stream"); Error("Unable to create video out stream");
return false; return false;
} }
@ -350,40 +349,34 @@ bool VideoStore::open() {
#else #else
avcodec_copy_context(video_out_stream->codec, video_out_ctx); avcodec_copy_context(video_out_stream->codec, video_out_ctx);
#endif #endif
// Only set orientation if doing passthrough, otherwise the frame image will be rotated
Monitor::Orientation orientation = monitor->getOrientation();
if ( orientation ) {
Debug(3, "Have orientation %d", orientation);
if ( orientation == Monitor::ROTATE_0 ) {
} else if ( orientation == Monitor::ROTATE_90 ) {
ret = av_dict_set(&video_out_stream->metadata, "rotate", "90", 0);
if ( ret < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__);
} else if ( orientation == Monitor::ROTATE_180 ) {
ret = av_dict_set(&video_out_stream->metadata, "rotate", "180", 0);
if ( ret < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__);
} else if ( orientation == Monitor::ROTATE_270 ) {
ret = av_dict_set(&video_out_stream->metadata, "rotate", "270", 0);
if ( ret < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__);
} else {
Warning("Unsupported Orientation(%d)", orientation);
}
} // end if orientation
video_out_stream->time_base = video_in_stream ? video_in_stream->time_base : AV_TIME_BASE_Q; video_out_stream->time_base = video_in_stream ? video_in_stream->time_base : AV_TIME_BASE_Q;
if (monitor->GetOptVideoWriter() == Monitor::PASSTHROUGH) {
// Only set orientation if doing passthrough, otherwise the frame image will be rotated
Monitor::Orientation orientation = monitor->getOrientation();
if (orientation) {
Debug(3, "Have orientation %d", orientation);
if (orientation == Monitor::ROTATE_0) {
} else if (orientation == Monitor::ROTATE_90) {
ret = av_dict_set(&video_out_stream->metadata, "rotate", "90", 0);
if (ret < 0) Warning("%s:%d: title set failed", __FILE__, __LINE__);
} else if (orientation == Monitor::ROTATE_180) {
ret = av_dict_set(&video_out_stream->metadata, "rotate", "180", 0);
if (ret < 0) Warning("%s:%d: title set failed", __FILE__, __LINE__);
} else if (orientation == Monitor::ROTATE_270) {
ret = av_dict_set(&video_out_stream->metadata, "rotate", "270", 0);
if (ret < 0) Warning("%s:%d: title set failed", __FILE__, __LINE__);
} else {
Warning("Unsupported Orientation(%d)", orientation);
}
} // end if orientation
} // end if passthrough
if ( audio_in_stream and audio_in_ctx ) { if (audio_in_stream and audio_in_ctx) {
Debug(2, "Have audio_in_stream %p", audio_in_stream); Debug(2, "Have audio_in_stream %p", audio_in_stream);
if ( if (CODEC(audio_in_stream)->codec_id != AV_CODEC_ID_AAC) {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
audio_in_stream->codecpar->codec_id
#else
audio_in_stream->codec->codec_id
#endif
!= AV_CODEC_ID_AAC
) {
audio_out_codec = avcodec_find_encoder(AV_CODEC_ID_AAC); audio_out_codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if ( !audio_out_codec ) { if (!audio_out_codec) {
Error("Could not find codec for AAC"); Error("Could not find codec for AAC");
} else { } else {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
@ -397,7 +390,7 @@ bool VideoStore::open() {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
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");
return false; return false;
} }
@ -407,7 +400,7 @@ bool VideoStore::open() {
audio_out_stream = avformat_new_stream(oc, audio_out_codec); audio_out_stream = avformat_new_stream(oc, audio_out_codec);
audio_out_stream->time_base = audio_in_stream->time_base; audio_out_stream->time_base = audio_in_stream->time_base;
if ( !setup_resampler() ) { if (!setup_resampler()) {
return false; return false;
} }
} // end if found AAC codec } // end if found AAC codec
@ -417,7 +410,7 @@ bool VideoStore::open() {
// normally we want to pass params from codec in here // normally we want to pass params from codec in here
// but since we are doing audio passthrough we don't care // but since we are doing audio passthrough we don't care
audio_out_stream = avformat_new_stream(oc, audio_out_codec); audio_out_stream = avformat_new_stream(oc, audio_out_codec);
if ( !audio_out_stream ) { if (!audio_out_stream) {
Error("Could not allocate new stream"); Error("Could not allocate new stream");
return false; return false;
} }
@ -426,7 +419,7 @@ bool VideoStore::open() {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// Just use the ctx to copy the parameters over // Just use the ctx to copy the parameters over
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 new output_context"); Error("Could not allocate new output_context");
return false; return false;
} }
@ -437,20 +430,20 @@ bool VideoStore::open() {
// Copy params from instream to ctx // Copy params from instream to ctx
ret = avcodec_parameters_to_context( ret = avcodec_parameters_to_context(
audio_out_ctx, audio_in_stream->codecpar); audio_out_ctx, audio_in_stream->codecpar);
if ( ret < 0 ) { if (ret < 0) {
Error("Unable to copy audio params to ctx %s", Error("Unable to copy audio params to ctx %s",
av_make_error_string(ret).c_str()); av_make_error_string(ret).c_str());
} }
ret = avcodec_parameters_from_context( ret = avcodec_parameters_from_context(
audio_out_stream->codecpar, audio_out_ctx); audio_out_stream->codecpar, audio_out_ctx);
if ( ret < 0 ) { if (ret < 0) {
Error("Unable to copy audio params to stream %s", Error("Unable to copy audio params to stream %s",
av_make_error_string(ret).c_str()); av_make_error_string(ret).c_str());
} }
#else #else
audio_out_ctx = audio_out_stream->codec; audio_out_ctx = audio_out_stream->codec;
ret = avcodec_copy_context(audio_out_ctx, audio_in_stream->codec); ret = avcodec_copy_context(audio_out_ctx, audio_in_stream->codec);
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 = nullptr; audio_out_stream = nullptr;
@ -459,7 +452,7 @@ bool VideoStore::open() {
audio_out_ctx->codec_tag = 0; audio_out_ctx->codec_tag = 0;
#endif #endif
if ( audio_out_ctx->channels > 1 ) { if (audio_out_ctx->channels > 1) {
Warning("Audio isn't mono, changing it."); Warning("Audio isn't mono, changing it.");
audio_out_ctx->channels = 1; audio_out_ctx->channels = 1;
} else { } else {
@ -467,7 +460,7 @@ bool VideoStore::open() {
} }
} // end if is AAC } // end if is AAC
if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) { if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
#if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0)
audio_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; audio_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
#else #else
@ -481,14 +474,14 @@ bool VideoStore::open() {
//max_stream_index is 0-based, so add 1 //max_stream_index is 0-based, so add 1
next_dts = new int64_t[max_stream_index+1]; next_dts = new int64_t[max_stream_index+1];
for ( int i = 0; i <= max_stream_index; i++ ) { for (int i = 0; i <= max_stream_index; i++) {
next_dts[i] = 0; next_dts[i] = 0;
} }
/* 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, nullptr, nullptr); 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());
return false; return false;
@ -496,39 +489,39 @@ 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 = nullptr; AVDictionary *opts = nullptr;
std::string option_string = monitor->GetEncoderOptions(); std::string option_string = monitor->GetEncoderOptions();
ret = av_dict_parse_string(&opts, option_string.c_str(), "=", ",\n", 0); ret = av_dict_parse_string(&opts, option_string.c_str(), "=", "#,\n", 0);
if ( ret < 0 ) { if (ret < 0) {
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", nullptr, 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");
// Shiboleth reports that this may break seeking in mp4 before it downloads // Shiboleth reports that this may break seeking in mp4 before it downloads
av_dict_set(&opts, "movflags", "frag_keyframe+empty_moov", 0); av_dict_set(&opts, "movflags", "frag_keyframe+empty_moov", 0);
} else { } else {
Debug(1, "using movflags %s", movflags_entry->value); Debug(1, "using movflags %s", movflags_entry->value);
} }
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, nullptr); 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 = nullptr; AVDictionaryEntry *e = nullptr;
while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != nullptr ) { 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, nullptr, 0); av_dict_set(&opts, e->key, nullptr, 0);
} }
} }
} }
if ( opts ) av_dict_free(&opts); if (opts) av_dict_free(&opts);
if ( ret < 0 ) { if (ret < 0) {
Error("Error occurred when writing out file header to %s: %s", Error("Error occurred when writing out file header to %s: %s",
filename, av_make_error_string(ret).c_str()); filename, av_make_error_string(ret).c_str());
avio_closep(&oc->pb); avio_closep(&oc->pb);
@ -550,13 +543,13 @@ void VideoStore::flush_codecs() {
av_init_packet(&pkt); av_init_packet(&pkt);
// I got crashes if the codec didn't do DELAY, so let's test for it. // I got crashes if the codec didn't do DELAY, so let's test for it.
if ( video_out_ctx->codec && ( video_out_ctx->codec->capabilities & if (video_out_ctx->codec && ( video_out_ctx->codec->capabilities &
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
AV_CODEC_CAP_DELAY AV_CODEC_CAP_DELAY
#else #else
CODEC_CAP_DELAY CODEC_CAP_DELAY
#endif #endif
) ) { )) {
// Put encoder into flushing mode // Put encoder into flushing mode
while ((zm_send_frame_receive_packet(video_out_ctx, nullptr, pkt)) > 0) { while ((zm_send_frame_receive_packet(video_out_ctx, nullptr, pkt)) > 0) {
av_packet_rescale_ts(&pkt, av_packet_rescale_ts(&pkt,
@ -568,7 +561,7 @@ void VideoStore::flush_codecs() {
Debug(1, "Done writing buffered video."); Debug(1, "Done writing buffered video.");
} // end if have delay capability } // end if have delay capability
if ( audio_out_codec ) { if (audio_out_codec) {
// The codec queues data. We need to send a flush command and out // The codec queues data. We need to send a flush command and out
// whatever we get. Failures are not fatal. // whatever we get. Failures are not fatal.
@ -576,13 +569,13 @@ void VideoStore::flush_codecs() {
/* /*
* 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, nullptr, 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
if ( zm_get_samples_from_fifo(fifo, out_frame) ) { if (zm_get_samples_from_fifo(fifo, out_frame)) {
if ( zm_send_frame_receive_packet(audio_out_ctx, out_frame, pkt) > 0 ) { if (zm_send_frame_receive_packet(audio_out_ctx, out_frame, pkt) > 0) {
av_packet_rescale_ts(&pkt, av_packet_rescale_ts(&pkt,
audio_out_ctx->time_base, audio_out_ctx->time_base,
audio_out_stream->time_base); audio_out_stream->time_base);
@ -591,11 +584,10 @@ void VideoStore::flush_codecs() {
} }
} // end if data returned from fifo } // end if data returned from fifo
} }
} // end while have buffered samples in the resampler } // end while have buffered samples in the resampler
Debug(2, "av_audio_fifo_size = %d", av_audio_fifo_size(fifo)); Debug(2, "av_audio_fifo_size = %d", av_audio_fifo_size(fifo));
while ( av_audio_fifo_size(fifo) > 0 ) { while (av_audio_fifo_size(fifo) > 0) {
/* Take one frame worth of audio samples from the FIFO buffer, /* Take one frame worth of audio samples from the FIFO buffer,
* encode it and write it to the output file. */ * encode it and write it to the output file. */
@ -603,8 +595,8 @@ void VideoStore::flush_codecs() {
frame_size, av_audio_fifo_size(fifo)); frame_size, av_audio_fifo_size(fifo));
// SHould probably set the frame size to what is reported FIXME // SHould probably set the frame size to what is reported FIXME
if ( av_audio_fifo_read(fifo, (void **)out_frame->data, frame_size) ) { if (av_audio_fifo_read(fifo, (void **)out_frame->data, frame_size)) {
if ( zm_send_frame_receive_packet(audio_out_ctx, out_frame, pkt) ) { if (zm_send_frame_receive_packet(audio_out_ctx, out_frame, pkt)) {
pkt.stream_index = audio_out_stream->index; pkt.stream_index = audio_out_stream->index;
av_packet_rescale_ts(&pkt, av_packet_rescale_ts(&pkt,
@ -622,7 +614,7 @@ void VideoStore::flush_codecs() {
#endif #endif
while (1) { while (1) {
if ( 0 >= zm_receive_packet(audio_out_ctx, pkt) ) { if (0 >= zm_receive_packet(audio_out_ctx, pkt)) {
Debug(1, "No more packets"); Debug(1, "No more packets");
break; break;
} }
@ -637,11 +629,11 @@ void VideoStore::flush_codecs() {
} // end flush_codecs } // end flush_codecs
VideoStore::~VideoStore() { VideoStore::~VideoStore() {
if ( oc->pb ) { if (oc->pb) {
flush_codecs(); flush_codecs();
// Flush Queues // Flush Queues
Debug(1, "Flushing interleaved queues"); Debug(4, "Flushing interleaved queues");
av_interleaved_write_frame(oc, nullptr); av_interleaved_write_frame(oc, nullptr);
Debug(1, "Writing trailer"); Debug(1, "Writing trailer");
@ -653,17 +645,17 @@ VideoStore::~VideoStore() {
} }
// When will we not be using a file ? // When will we not be using a file ?
if ( !(out_format->flags & AVFMT_NOFILE) ) { if (!(out_format->flags & AVFMT_NOFILE)) {
/* Close the out file. */ /* Close the out file. */
Debug(2, "Closing"); Debug(4, "Closing");
if ( int rc = avio_close(oc->pb) ) { if (int rc = avio_close(oc->pb)) {
Error("Error closing avio %s", av_err2str(rc)); Error("Error closing avio %s", av_err2str(rc));
} }
} else { } else {
Debug(3, "Not closing avio because we are not writing to a file."); Debug(3, "Not closing avio because we are not writing to a file.");
} }
oc->pb = nullptr; oc->pb = nullptr;
} // end if oc->pb } // end if oc->pb
// I wonder if we should be closing the file first. // I wonder if we should be closing the file first.
// I also wonder if we really need to be doing all the ctx // I also wonder if we really need to be doing all the ctx
@ -671,14 +663,19 @@ VideoStore::~VideoStore() {
// Just do a file open/close/writeheader/etc. // Just do a file open/close/writeheader/etc.
// What if we were only doing audio recording? // What if we were only doing audio recording?
if ( video_out_stream ) { if (video_out_stream) {
video_in_ctx = nullptr; video_in_ctx = nullptr;
Debug(4, "Freeing video_out_ctx"); avcodec_close(video_out_ctx);
Debug(3, "Freeing video_out_ctx");
avcodec_free_context(&video_out_ctx); avcodec_free_context(&video_out_ctx);
} // end if video_out_stream if (hw_device_ctx) {
Debug(3, "Freeing hw_device_ctx");
av_buffer_unref(&hw_device_ctx);
}
} // end if video_out_stream
if ( audio_out_stream ) { if (audio_out_stream) {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// 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(&audio_in_ctx); //avcodec_free_context(&audio_in_ctx);
@ -686,16 +683,17 @@ VideoStore::~VideoStore() {
//Debug(4, "Success freeing audio_in_ctx"); //Debug(4, "Success freeing audio_in_ctx");
audio_in_codec = nullptr; audio_in_codec = nullptr;
if ( audio_out_ctx ) { if (audio_out_ctx) {
Debug(4, "Success closing audio_out_ctx"); Debug(4, "Success closing audio_out_ctx");
avcodec_close(audio_out_ctx);
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
avcodec_free_context(&audio_out_ctx); avcodec_free_context(&audio_out_ctx);
#endif #endif
} }
#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 = nullptr; fifo = nullptr;
} }
@ -708,15 +706,15 @@ VideoStore::~VideoStore() {
#endif #endif
#endif #endif
} }
if ( in_frame ) { if (in_frame) {
av_frame_free(&in_frame); av_frame_free(&in_frame);
in_frame = nullptr; in_frame = nullptr;
} }
if ( out_frame ) { if (out_frame) {
av_frame_free(&out_frame); av_frame_free(&out_frame);
out_frame = nullptr; out_frame = nullptr;
} }
if ( converted_in_samples ) { if (converted_in_samples) {
av_free(converted_in_samples); av_free(converted_in_samples);
converted_in_samples = nullptr; converted_in_samples = nullptr;
} }
@ -732,7 +730,7 @@ VideoStore::~VideoStore() {
bool VideoStore::setup_resampler() { bool VideoStore::setup_resampler() {
#if !defined(HAVE_LIBSWRESAMPLE) && !defined(HAVE_LIBAVRESAMPLE) #if !defined(HAVE_LIBSWRESAMPLE) && !defined(HAVE_LIBAVRESAMPLE)
Error("%s", "Not built with resample library. Cannot do audio conversion to AAC"); Error("Not built with resample library. Cannot do audio conversion to AAC");
return false; return false;
#else #else
int ret; int ret;
@ -740,17 +738,14 @@ bool VideoStore::setup_resampler() {
#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0)
// Newer ffmpeg wants to keep everything separate... so have to lookup our own // Newer ffmpeg wants to keep everything separate... so have to lookup our own
// decoder, can't reuse the one from the camera. // decoder, can't reuse the one from the camera.
audio_in_codec = audio_in_codec = avcodec_find_decoder(audio_in_stream->codecpar->codec_id);
avcodec_find_decoder(audio_in_stream->codecpar->codec_id);
audio_in_ctx = avcodec_alloc_context3(audio_in_codec); audio_in_ctx = avcodec_alloc_context3(audio_in_codec);
// Copy params from instream to ctx // Copy params from instream to ctx
ret = avcodec_parameters_to_context( ret = avcodec_parameters_to_context(audio_in_ctx, audio_in_stream->codecpar);
audio_in_ctx, audio_in_stream->codecpar); if (ret < 0) {
if ( ret < 0 ) {
Error("Unable to copy audio params to ctx %s", Error("Unable to copy audio params to ctx %s",
av_make_error_string(ret).c_str()); av_make_error_string(ret).c_str());
} }
#else #else
// codec is already open in ffmpeg_camera // codec is already open in ffmpeg_camera
audio_in_ctx = audio_in_stream->codec; audio_in_ctx = audio_in_stream->codec;
@ -764,7 +759,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, nullptr)) < 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;
} }
@ -772,7 +767,7 @@ bool VideoStore::setup_resampler() {
Debug(2, "Got something other than AAC (%s)", audio_in_codec->name); Debug(2, "Got something other than AAC (%s)", audio_in_codec->name);
// Some formats (i.e. WAV) do not produce the proper channel layout // Some formats (i.e. WAV) do not produce the proper channel layout
if ( audio_in_ctx->channel_layout == 0 ) { if (audio_in_ctx->channel_layout == 0) {
Debug(2, "Setting input channel layout to mono"); Debug(2, "Setting input channel layout to mono");
// Perhaps we should not be modifying the audio_in_ctx.... // Perhaps we should not be modifying the audio_in_ctx....
audio_in_ctx->channel_layout = av_get_channel_layout("mono"); audio_in_ctx->channel_layout = av_get_channel_layout("mono");
@ -786,7 +781,7 @@ bool VideoStore::setup_resampler() {
audio_out_ctx->channel_layout = audio_in_ctx->channel_layout; audio_out_ctx->channel_layout = audio_in_ctx->channel_layout;
audio_out_ctx->sample_fmt = audio_in_ctx->sample_fmt; audio_out_ctx->sample_fmt = audio_in_ctx->sample_fmt;
#if LIBAVCODEC_VERSION_CHECK(56, 8, 0, 60, 100) #if LIBAVCODEC_VERSION_CHECK(56, 8, 0, 60, 100)
if ( !audio_out_ctx->channel_layout ) { if (!audio_out_ctx->channel_layout) {
Debug(3, "Correcting channel layout from (%" PRIi64 ") to (%" PRIi64 ")", Debug(3, "Correcting channel layout from (%" PRIi64 ") to (%" PRIi64 ")",
audio_out_ctx->channel_layout, audio_out_ctx->channel_layout,
av_get_default_channel_layout(audio_out_ctx->channels) av_get_default_channel_layout(audio_out_ctx->channels)
@ -794,27 +789,26 @@ bool VideoStore::setup_resampler() {
audio_out_ctx->channel_layout = av_get_default_channel_layout(audio_out_ctx->channels); audio_out_ctx->channel_layout = av_get_default_channel_layout(audio_out_ctx->channels);
} }
#endif #endif
if ( audio_out_codec->supported_samplerates ) { if (audio_out_codec->supported_samplerates) {
int found = 0; int found = 0;
for ( unsigned int i = 0; audio_out_codec->supported_samplerates[i]; i++ ) { for (unsigned int i = 0; audio_out_codec->supported_samplerates[i]; i++) {
if ( audio_out_ctx->sample_rate == if (audio_out_ctx->sample_rate ==
audio_out_codec->supported_samplerates[i] ) { audio_out_codec->supported_samplerates[i]) {
found = 1; found = 1;
break; break;
} }
} }
if ( found ) { if (found) {
Debug(3, "Sample rate is good %d", audio_out_ctx->sample_rate); Debug(3, "Sample rate is good %d", audio_out_ctx->sample_rate);
} else { } else {
audio_out_ctx->sample_rate = audio_out_ctx->sample_rate = audio_out_codec->supported_samplerates[0];
audio_out_codec->supported_samplerates[0];
Debug(1, "Sample rate is no good, setting to (%d)", Debug(1, "Sample rate is no good, setting to (%d)",
audio_out_codec->supported_samplerates[0]); audio_out_codec->supported_samplerates[0]);
} }
} }
/* check that the encoder supports s16 pcm in */ /* check that the encoder supports s16 pcm in */
if ( !check_sample_fmt(audio_out_codec, audio_out_ctx->sample_fmt) ) { if (!check_sample_fmt(audio_out_codec, audio_out_ctx->sample_fmt)) {
Debug(3, "Encoder does not support sample format %s, setting to FLTP", Debug(3, "Encoder does not support sample format %s, setting to FLTP",
av_get_sample_fmt_name(audio_out_ctx->sample_fmt)); av_get_sample_fmt_name(audio_out_ctx->sample_fmt));
audio_out_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP; audio_out_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
@ -825,12 +819,12 @@ bool VideoStore::setup_resampler() {
AVDictionary *opts = nullptr; AVDictionary *opts = nullptr;
// Needed to allow AAC // Needed to allow AAC
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");
} }
ret = avcodec_open2(audio_out_ctx, audio_out_codec, &opts); ret = avcodec_open2(audio_out_ctx, audio_out_codec, &opts);
av_dict_free(&opts); av_dict_free(&opts);
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 = nullptr; audio_out_codec = nullptr;
@ -886,7 +880,7 @@ bool VideoStore::setup_resampler() {
#endif #endif
/** Create a new frame to store the audio samples. */ /** Create a new frame to store the audio samples. */
if ( ! in_frame ) { if (!in_frame) {
if (!(in_frame = zm_av_frame_alloc())) { if (!(in_frame = zm_av_frame_alloc())) {
Error("Could not allocate in frame"); Error("Could not allocate in frame");
return false; return false;
@ -894,16 +888,16 @@ bool VideoStore::setup_resampler() {
} }
/** Create a new frame to store the audio samples. */ /** Create a new frame to store the audio samples. */
if ( !(out_frame = zm_av_frame_alloc()) ) { if (!(out_frame = zm_av_frame_alloc())) {
Error("Could not allocate out frame"); Error("Could not allocate out frame");
av_frame_free(&in_frame); av_frame_free(&in_frame);
return false; return false;
} }
out_frame->sample_rate = audio_out_ctx->sample_rate; out_frame->sample_rate = audio_out_ctx->sample_rate;
if ( !(fifo = av_audio_fifo_alloc( if (!(fifo = av_audio_fifo_alloc(
audio_out_ctx->sample_fmt, audio_out_ctx->sample_fmt,
audio_out_ctx->channels, 1)) ) { audio_out_ctx->channels, 1))) {
Error("Could not allocate FIFO"); Error("Could not allocate FIFO");
return false; return false;
} }
@ -916,13 +910,13 @@ bool VideoStore::setup_resampler() {
audio_in_ctx->sample_fmt, audio_in_ctx->sample_fmt,
audio_in_ctx->sample_rate, audio_in_ctx->sample_rate,
0, nullptr); 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);
av_frame_free(&out_frame); av_frame_free(&out_frame);
return false; return false;
} }
if ( (ret = swr_init(resample_ctx)) < 0 ) { if ((ret = swr_init(resample_ctx)) < 0) {
Error("Could not open resampler"); Error("Could not open resampler");
av_frame_free(&in_frame); av_frame_free(&in_frame);
av_frame_free(&out_frame); av_frame_free(&out_frame);
@ -935,7 +929,7 @@ bool VideoStore::setup_resampler() {
// Setup the audio resampler // Setup the audio resampler
resample_ctx = avresample_alloc_context(); resample_ctx = avresample_alloc_context();
if ( !resample_ctx ) { if (!resample_ctx) {
Error("Could not allocate resample ctx"); Error("Could not allocate resample ctx");
av_frame_free(&in_frame); av_frame_free(&in_frame);
av_frame_free(&out_frame); av_frame_free(&out_frame);
@ -959,7 +953,7 @@ bool VideoStore::setup_resampler() {
av_opt_set_int(resample_ctx, "out_channels", av_opt_set_int(resample_ctx, "out_channels",
audio_out_ctx->channels, 0); audio_out_ctx->channels, 0);
if ( (ret = avresample_open(resample_ctx)) < 0 ) { if ((ret = avresample_open(resample_ctx)) < 0) {
Error("Could not open resample ctx"); Error("Could not open resample ctx");
return false; return false;
} else { } else {
@ -984,7 +978,7 @@ bool VideoStore::setup_resampler() {
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));
if ( !converted_in_samples ) { if (!converted_in_samples) {
Error("Could not allocate converted in sample pointers"); Error("Could not allocate converted in sample pointers");
return false; return false;
} else { } else {
@ -992,11 +986,11 @@ bool VideoStore::setup_resampler() {
} }
// Setup the data pointers in the AVFrame // Setup the data pointers in the AVFrame
if ( avcodec_fill_audio_frame( if (avcodec_fill_audio_frame(
out_frame, audio_out_ctx->channels, out_frame, audio_out_ctx->channels,
audio_out_ctx->sample_fmt, audio_out_ctx->sample_fmt,
(const uint8_t *)converted_in_samples, (const uint8_t *)converted_in_samples,
audioSampleBuffer_size, 0) < 0 ) { audioSampleBuffer_size, 0) < 0) {
Error("Could not allocate converted in sample pointers"); Error("Could not allocate converted in sample pointers");
return false; return false;
} }
@ -1023,10 +1017,11 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
Debug(3, "Have encoding video frame count (%d)", frame_count); Debug(3, "Have encoding video frame count (%d)", frame_count);
if (!zm_packet->out_frame) { if (!zm_packet->out_frame) {
Debug(3, "Have no out frame. codec is %s sw_pf %d %s hw_pf %d %s", Debug(3, "Have no out frame. codec is %s sw_pf %d %s hw_pf %d %s %dx%d",
chosen_codec_data->codec_name, chosen_codec_data->codec_name,
chosen_codec_data->sw_pix_fmt, av_get_pix_fmt_name(chosen_codec_data->sw_pix_fmt), chosen_codec_data->sw_pix_fmt, av_get_pix_fmt_name(chosen_codec_data->sw_pix_fmt),
chosen_codec_data->hw_pix_fmt, av_get_pix_fmt_name(chosen_codec_data->hw_pix_fmt) chosen_codec_data->hw_pix_fmt, av_get_pix_fmt_name(chosen_codec_data->hw_pix_fmt),
video_out_ctx->width, video_out_ctx->height
); );
AVFrame *out_frame = zm_packet->get_out_frame(video_out_ctx->width, video_out_ctx->height, chosen_codec_data->sw_pix_fmt); AVFrame *out_frame = zm_packet->get_out_frame(video_out_ctx->width, video_out_ctx->height, chosen_codec_data->sw_pix_fmt);
if (!out_frame) { if (!out_frame) {
@ -1046,17 +1041,16 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
video_out_ctx->width, video_out_ctx->width,
video_out_ctx->height video_out_ctx->height
); );
} else if ( !zm_packet->in_frame ) { } else if (!zm_packet->in_frame) {
Debug(4, "Have no in_frame"); Debug(4, "Have no in_frame");
if (zm_packet->packet.size and !zm_packet->decoded) { if (zm_packet->packet.size and !zm_packet->decoded) {
Debug(4, "Decoding"); Debug(4, "Decoding");
if ( !zm_packet->decode(video_in_ctx) ) { if (!zm_packet->decode(video_in_ctx)) {
Debug(2, "unable to decode yet."); Debug(2, "unable to decode yet.");
return 0; return 0;
} }
// Go straight to out frame // Go straight to out frame
swscale.Convert(zm_packet->in_frame, out_frame); swscale.Convert(zm_packet->in_frame, out_frame);
} else { } else {
Error("Have neither in_frame or image in packet %d!", Error("Have neither in_frame or image in packet %d!",
zm_packet->image_index); zm_packet->image_index);
@ -1108,7 +1102,7 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
#endif #endif
int64_t in_pts = zm_packet->timestamp.tv_sec * (uint64_t)1000000 + zm_packet->timestamp.tv_usec; int64_t in_pts = zm_packet->timestamp.tv_sec * (uint64_t)1000000 + zm_packet->timestamp.tv_usec;
if ( !video_first_pts ) { if (!video_first_pts) {
video_first_pts = in_pts; video_first_pts = in_pts;
Debug(2, "No video_first_pts, set to (%" PRId64 ") secs(%" PRIi64 ") usecs(%" PRIi64 ")", Debug(2, "No video_first_pts, set to (%" PRId64 ") secs(%" PRIi64 ") usecs(%" PRIi64 ")",
video_first_pts, video_first_pts,
@ -1144,9 +1138,9 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
ZM_DUMP_PACKET(opkt, "packet returned by codec"); ZM_DUMP_PACKET(opkt, "packet returned by codec");
// Need to adjust pts/dts values from codec time to stream time // Need to adjust pts/dts values from codec time to stream time
if ( opkt.pts != AV_NOPTS_VALUE ) if (opkt.pts != AV_NOPTS_VALUE)
opkt.pts = av_rescale_q(opkt.pts, video_out_ctx->time_base, video_out_stream->time_base); opkt.pts = av_rescale_q(opkt.pts, video_out_ctx->time_base, video_out_stream->time_base);
if ( opkt.dts != AV_NOPTS_VALUE ) if (opkt.dts != AV_NOPTS_VALUE)
opkt.dts = av_rescale_q(opkt.dts, video_out_ctx->time_base, video_out_stream->time_base); opkt.dts = av_rescale_q(opkt.dts, video_out_ctx->time_base, video_out_stream->time_base);
Debug(1, "Timebase conversions using %d/%d -> %d/%d", Debug(1, "Timebase conversions using %d/%d -> %d/%d",
video_out_ctx->time_base.num, video_out_ctx->time_base.num,
@ -1154,10 +1148,9 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
video_out_stream->time_base.num, video_out_stream->time_base.num,
video_out_stream->time_base.den); video_out_stream->time_base.den);
int64_t duration = 0; int64_t duration = 0;
if ( zm_packet->in_frame ) { if (zm_packet->in_frame) {
if ( zm_packet->in_frame->pkt_duration ) { if (zm_packet->in_frame->pkt_duration) {
duration = av_rescale_q( duration = av_rescale_q(
zm_packet->in_frame->pkt_duration, zm_packet->in_frame->pkt_duration,
video_in_stream->time_base, video_in_stream->time_base,
@ -1171,9 +1164,8 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
video_out_stream->time_base.num, video_out_stream->time_base.num,
video_out_stream->time_base.den video_out_stream->time_base.den
); );
} else if ( video_last_pts != AV_NOPTS_VALUE ) { } else if (video_last_pts != AV_NOPTS_VALUE) {
duration = duration = av_rescale_q(
av_rescale_q(
zm_packet->in_frame->pts - video_last_pts, zm_packet->in_frame->pts - video_last_pts,
video_in_stream->time_base, video_in_stream->time_base,
video_out_stream->time_base); video_out_stream->time_base);
@ -1183,8 +1175,10 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
zm_packet->in_frame->pts - video_last_pts, zm_packet->in_frame->pts - video_last_pts,
duration duration
); );
if ( duration <= 0 ) { if (duration <= 0) {
duration = zm_packet->in_frame->pkt_duration ? zm_packet->in_frame->pkt_duration : av_rescale_q(1, video_in_stream->time_base, video_out_stream->time_base); duration = zm_packet->in_frame->pkt_duration ?
zm_packet->in_frame->pkt_duration :
av_rescale_q(1, video_in_stream->time_base, video_out_stream->time_base);
} }
} // end if in_frmae->pkt_duration } // end if in_frmae->pkt_duration
video_last_pts = zm_packet->in_frame->pts; video_last_pts = zm_packet->in_frame->pts;
@ -1192,7 +1186,6 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
//duration = av_rescale_q(zm_packet->out_frame->pts - video_last_pts, video_in_stream->time_base, video_out_stream->time_base); //duration = av_rescale_q(zm_packet->out_frame->pts - video_last_pts, video_in_stream->time_base, video_out_stream->time_base);
} // end if in_frmae } // end if in_frmae
opkt.duration = duration; opkt.duration = duration;
} else { // Passthrough } else { // Passthrough
AVPacket *ipkt = &zm_packet->packet; AVPacket *ipkt = &zm_packet->packet;
ZM_DUMP_STREAM_PACKET(video_in_stream, (*ipkt), "Doing passthrough, just copy packet"); ZM_DUMP_STREAM_PACKET(video_in_stream, (*ipkt), "Doing passthrough, just copy packet");
@ -1203,8 +1196,8 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
opkt.flags = ipkt->flags; opkt.flags = ipkt->flags;
opkt.duration = ipkt->duration; opkt.duration = ipkt->duration;
if ( ipkt->dts != AV_NOPTS_VALUE ) { if (ipkt->dts != AV_NOPTS_VALUE) {
if ( !video_first_dts ) { if (!video_first_dts) {
Debug(2, "Starting video first_dts will become %" PRId64, ipkt->dts); Debug(2, "Starting video first_dts will become %" PRId64, ipkt->dts);
video_first_dts = ipkt->dts; video_first_dts = ipkt->dts;
} }
@ -1213,14 +1206,13 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
opkt.dts = next_dts[video_out_stream->index] ? av_rescale_q(next_dts[video_out_stream->index], video_out_stream->time_base, video_in_stream->time_base) : 0; opkt.dts = next_dts[video_out_stream->index] ? av_rescale_q(next_dts[video_out_stream->index], video_out_stream->time_base, video_in_stream->time_base) : 0;
Debug(3, "Setting dts to video_next_dts %" PRId64 " from %" PRId64, opkt.dts, next_dts[video_out_stream->index]); Debug(3, "Setting dts to video_next_dts %" PRId64 " from %" PRId64, opkt.dts, next_dts[video_out_stream->index]);
} }
if ( ipkt->pts != AV_NOPTS_VALUE ) { if (ipkt->pts != AV_NOPTS_VALUE) {
opkt.pts = ipkt->pts - video_first_dts; opkt.pts = ipkt->pts - video_first_dts;
} else { } else {
opkt.pts = AV_NOPTS_VALUE; opkt.pts = AV_NOPTS_VALUE;
} }
av_packet_rescale_ts(&opkt, video_in_stream->time_base, video_out_stream->time_base); av_packet_rescale_ts(&opkt, video_in_stream->time_base, video_out_stream->time_base);
ZM_DUMP_STREAM_PACKET(video_out_stream, opkt, "after pts adjustment"); ZM_DUMP_STREAM_PACKET(video_out_stream, opkt, "after pts adjustment");
} // end if codec matches } // end if codec matches
@ -1232,18 +1224,17 @@ int VideoStore::writeVideoFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
} // end int VideoStore::writeVideoFramePacket( AVPacket *ipkt ) } // end int VideoStore::writeVideoFramePacket( AVPacket *ipkt )
int VideoStore::writeAudioFramePacket(const std::shared_ptr<ZMPacket> &zm_packet) { int VideoStore::writeAudioFramePacket(const std::shared_ptr<ZMPacket> &zm_packet) {
if (!audio_out_stream) {
AVPacket *ipkt = &zm_packet->packet;
int ret;
if ( !audio_out_stream ) {
Debug(1, "Called writeAudioFramePacket when no audio_out_stream"); Debug(1, "Called writeAudioFramePacket when no audio_out_stream");
return 0; return 0;
// FIXME -ve return codes do not free packet in ffmpeg_camera at the moment // FIXME -ve return codes do not free packet in ffmpeg_camera at the moment
} }
AVPacket *ipkt = &zm_packet->packet;
int ret;
ZM_DUMP_STREAM_PACKET(audio_in_stream, (*ipkt), "input packet"); ZM_DUMP_STREAM_PACKET(audio_in_stream, (*ipkt), "input packet");
if ( !audio_first_dts ) { if (!audio_first_dts) {
audio_first_dts = ipkt->dts; audio_first_dts = ipkt->dts;
audio_next_pts = audio_out_ctx->frame_size; audio_next_pts = audio_out_ctx->frame_size;
} }
@ -1251,10 +1242,10 @@ int VideoStore::writeAudioFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
Debug(3, "audio first_dts to %" PRId64, audio_first_dts); Debug(3, "audio first_dts to %" PRId64, audio_first_dts);
// Need to adjust pts before feeding to decoder.... should really copy the pkt instead of modifying it // Need to adjust pts before feeding to decoder.... should really copy the pkt instead of modifying it
if ( audio_out_codec ) { if (audio_out_codec) {
// I wonder if we can get multiple frames per packet? Probably // I wonder if we can get multiple frames per packet? Probably
ret = zm_send_packet_receive_frame(audio_in_ctx, in_frame, *ipkt); ret = zm_send_packet_receive_frame(audio_in_ctx, in_frame, *ipkt);
if ( ret < 0 ) { if (ret < 0) {
Debug(3, "failed to receive frame code: %d", ret); Debug(3, "failed to receive frame code: %d", ret);
return 0; return 0;
} }
@ -1262,15 +1253,15 @@ int VideoStore::writeAudioFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
AVFrame *input_frame = in_frame; AVFrame *input_frame = in_frame;
while ( zm_resample_audio(resample_ctx, input_frame, out_frame) ) { while (zm_resample_audio(resample_ctx, input_frame, out_frame)) {
//out_frame->pkt_duration = in_frame->pkt_duration; // resampling doesn't alter duration //out_frame->pkt_duration = in_frame->pkt_duration; // resampling doesn't alter duration
if ( zm_add_samples_to_fifo(fifo, out_frame) <= 0 ) if (zm_add_samples_to_fifo(fifo, out_frame) <= 0)
break; break;
// We put the samples into the fifo so we are basically resetting the frame // We put the samples into the fifo so we are basically resetting the frame
out_frame->nb_samples = audio_out_ctx->frame_size; out_frame->nb_samples = audio_out_ctx->frame_size;
if ( zm_get_samples_from_fifo(fifo, out_frame) <= 0 ) if (zm_get_samples_from_fifo(fifo, out_frame) <= 0)
break; break;
out_frame->pts = audio_next_pts; out_frame->pts = audio_next_pts;
@ -1279,7 +1270,7 @@ int VideoStore::writeAudioFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
zm_dump_frame(out_frame, "Out frame after resample"); zm_dump_frame(out_frame, "Out frame after resample");
av_init_packet(&opkt); av_init_packet(&opkt);
if ( zm_send_frame_receive_packet(audio_out_ctx, out_frame, opkt) <= 0 ) if (zm_send_frame_receive_packet(audio_out_ctx, out_frame, opkt) <= 0)
break; break;
// Scale the PTS of the outgoing packet to be the correct time base // Scale the PTS of the outgoing packet to be the correct time base
@ -1290,12 +1281,11 @@ int VideoStore::writeAudioFramePacket(const std::shared_ptr<ZMPacket> &zm_packet
write_packet(&opkt, audio_out_stream); write_packet(&opkt, audio_out_stream);
zm_av_packet_unref(&opkt); zm_av_packet_unref(&opkt);
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 = nullptr; input_frame = nullptr;
} // end while there is data in the resampler } // end while there is data in the resampler
} else { } else {
av_init_packet(&opkt); av_init_packet(&opkt);
opkt.data = ipkt->data; opkt.data = ipkt->data;
@ -1321,15 +1311,15 @@ int VideoStore::write_packet(AVPacket *pkt, AVStream *stream) {
pkt->pos = -1; pkt->pos = -1;
pkt->stream_index = stream->index; pkt->stream_index = stream->index;
if ( pkt->dts == AV_NOPTS_VALUE ) { if (pkt->dts == AV_NOPTS_VALUE) {
Debug(1, "undef dts, fixing by setting to stream cur_dts %" PRId64, stream->cur_dts); Debug(1, "undef dts, fixing by setting to stream cur_dts %" PRId64, stream->cur_dts);
pkt->dts = stream->cur_dts; pkt->dts = stream->cur_dts;
} else if ( pkt->dts < stream->cur_dts ) { } else if (pkt->dts < stream->cur_dts) {
Debug(1, "non increasing dts, fixing. our dts %" PRId64 " stream cur_dts %" PRId64, pkt->dts, stream->cur_dts); Debug(1, "non increasing dts, fixing. our dts %" PRId64 " stream cur_dts %" PRId64, pkt->dts, stream->cur_dts);
pkt->dts = stream->cur_dts; pkt->dts = stream->cur_dts;
} }
if ( pkt->dts > pkt->pts ) { if (pkt->dts > pkt->pts) {
Debug(1, Debug(1,
"pkt.dts(%" PRId64 ") must be <= pkt.pts(%" PRId64 ")." "pkt.dts(%" PRId64 ") must be <= pkt.pts(%" PRId64 ")."
"Decompression must happen before presentation.", "Decompression must happen before presentation.",
@ -1343,9 +1333,8 @@ int VideoStore::write_packet(AVPacket *pkt, AVStream *stream) {
stream->index, next_dts[stream->index]); stream->index, next_dts[stream->index]);
int ret = av_interleaved_write_frame(oc, pkt); int ret = av_interleaved_write_frame(oc, pkt);
if ( ret != 0 ) { if (ret != 0) {
Error("Error writing packet: %s", Error("Error writing packet: %s", av_make_error_string(ret).c_str());
av_make_error_string(ret).c_str());
} else { } else {
Debug(4, "Success writing packet"); Debug(4, "Success writing packet");
} }

View File

@ -23,7 +23,7 @@
#include "zm_fifo_debug.h" #include "zm_fifo_debug.h"
#include "zm_monitor.h" #include "zm_monitor.h"
void Zone::Setup( void Zone::Setup(
ZoneType p_type, ZoneType p_type,
const Polygon &p_polygon, const Polygon &p_polygon,
const Rgb p_alarm_rgb, const Rgb p_alarm_rgb,
@ -32,7 +32,7 @@ void Zone::Setup(
int p_max_pixel_threshold, int p_max_pixel_threshold,
int p_min_alarm_pixels, int p_min_alarm_pixels,
int p_max_alarm_pixels, int p_max_alarm_pixels,
const Coord &p_filter_box, const Vector2 &p_filter_box,
int p_min_filter_pixels, int p_min_filter_pixels,
int p_max_filter_pixels, int p_max_filter_pixels,
int p_min_blob_pixels, int p_min_blob_pixels,
@ -122,7 +122,7 @@ void Zone::RecordStats(const Event *event) {
"PixelDiff=%d, AlarmPixels=%d, FilterPixels=%d, BlobPixels=%d, " "PixelDiff=%d, AlarmPixels=%d, FilterPixels=%d, BlobPixels=%d, "
"Blobs=%d, MinBlobSize=%d, MaxBlobSize=%d, " "Blobs=%d, MinBlobSize=%d, MaxBlobSize=%d, "
"MinX=%d, MinY=%d, MaxX=%d, MaxY=%d, Score=%d", "MinX=%d, MinY=%d, MaxX=%d, MaxY=%d, Score=%d",
monitor->Id(), id, event->Id(), event->Frames(), monitor->Id(), id, event->Id(), event->Frames(),
stats.pixel_diff_, stats.pixel_diff_,
stats.alarm_pixels_, stats.alarm_pixels_,
stats.alarm_filter_pixels_, stats.alarm_filter_pixels_,
@ -130,10 +130,10 @@ void Zone::RecordStats(const Event *event) {
stats.alarm_blobs_, stats.alarm_blobs_,
stats.min_blob_size_, stats.min_blob_size_,
stats.max_blob_size_, stats.max_blob_size_,
stats.alarm_box_.LoX(), stats.alarm_box_.Lo().x_,
stats.alarm_box_.LoY(), stats.alarm_box_.Lo().y_,
stats.alarm_box_.HiX(), stats.alarm_box_.Hi().x_,
stats.alarm_box_.HiY(), stats.alarm_box_.Hi().y_,
stats.score_ stats.score_
); );
zmDbDo(sql); zmDbDo(sql);
@ -219,10 +219,10 @@ bool Zone::CheckAlarms(const Image *delta_image) {
int alarm_mid_x = -1; int alarm_mid_x = -1;
int alarm_mid_y = -1; int alarm_mid_y = -1;
unsigned int lo_y = polygon.LoY(); unsigned int lo_x = polygon.Extent().Lo().x_;
unsigned int lo_x = polygon.LoX(); unsigned int lo_y = polygon.Extent().Lo().y_;
unsigned int hi_x = polygon.HiX(); unsigned int hi_x = polygon.Extent().Hi().x_;
unsigned int hi_y = polygon.HiY(); unsigned int hi_y = polygon.Extent().Hi().y_;
Debug(4, "Checking alarms for zone %d/%s in lines %d -> %d", id, label.c_str(), lo_y, hi_y); Debug(4, "Checking alarms for zone %d/%s in lines %d -> %d", id, label.c_str(), lo_y, hi_y);
@ -267,8 +267,8 @@ bool Zone::CheckAlarms(const Image *delta_image) {
Debug(5, "Current score is %d", stats.score_); Debug(5, "Current score is %d", stats.score_);
if (check_method >= FILTERED_PIXELS) { if (check_method >= FILTERED_PIXELS) {
int bx = filter_box.X(); int bx = filter_box.x_;
int by = filter_box.Y(); int by = filter_box.y_;
int bx1 = bx-1; int bx1 = bx-1;
int by1 = by-1; int by1 = by-1;
@ -620,20 +620,20 @@ bool Zone::CheckAlarms(const Image *delta_image) {
stats.score_ = 0; stats.score_ = 0;
return false; return false;
} }
if (max_blob_pixels != 0) if (max_blob_pixels != 0)
stats.score_ = (100*stats.alarm_blob_pixels_)/max_blob_pixels; stats.score_ = (100*stats.alarm_blob_pixels_)/max_blob_pixels;
else else
stats.score_ = (100*stats.alarm_blob_pixels_)/polygon.Area(); stats.score_ = (100*stats.alarm_blob_pixels_)/polygon.Area();
if (stats.score_ < 1) if (stats.score_ < 1)
stats.score_ = 1; /* Fix for score of 0 when frame meets thresholds but alarmed area is not big enough */ stats.score_ = 1; /* Fix for score of 0 when frame meets thresholds but alarmed area is not big enough */
Debug(5, "Current score is %d", stats.score_); Debug(5, "Current score is %d", stats.score_);
alarm_lo_x = polygon.HiX()+1; alarm_lo_x = polygon.Extent().Hi().x_ + 1;
alarm_hi_x = polygon.LoX()-1; alarm_hi_x = polygon.Extent().Lo().x_ - 1;
alarm_lo_y = polygon.HiY()+1; alarm_lo_y = polygon.Extent().Hi().y_ + 1;
alarm_hi_y = polygon.LoY()-1; alarm_hi_y = polygon.Extent().Lo().y_ - 1;
for (uint32 i = 1; i < kWhite; i++) { for (uint32 i = 1; i < kWhite; i++) {
BlobStats *bs = &blob_stats[i]; BlobStats *bs = &blob_stats[i];
@ -684,11 +684,11 @@ bool Zone::CheckAlarms(const Image *delta_image) {
// Now outline the changed region // Now outline the changed region
if (stats.score_) { if (stats.score_) {
stats.alarm_box_ = Box(Coord(alarm_lo_x, alarm_lo_y), Coord(alarm_hi_x, alarm_hi_y)); stats.alarm_box_ = Box(Vector2(alarm_lo_x, alarm_lo_y), Vector2(alarm_hi_x, alarm_hi_y));
//if ( monitor->followMotion() ) //if ( monitor->followMotion() )
if ( true ) { if ( true ) {
stats.alarm_centre_ = Coord(alarm_mid_x, alarm_mid_y); stats.alarm_centre_ = Vector2(alarm_mid_x, alarm_mid_y);
} else { } else {
stats.alarm_centre_ = stats.alarm_box_.Centre(); stats.alarm_centre_ = stats.alarm_box_.Centre();
} }
@ -748,37 +748,39 @@ bool Zone::CheckAlarms(const Image *delta_image) {
bool Zone::ParsePolygonString(const char *poly_string, Polygon &polygon) { bool Zone::ParsePolygonString(const char *poly_string, Polygon &polygon) {
char *str = (char *)poly_string; char *str = (char *)poly_string;
int n_coords = 0;
int max_n_coords = strlen(str)/4; int max_n_coords = strlen(str)/4;
Coord *coords = new Coord[max_n_coords];
std::vector<Vector2> vertices;
vertices.reserve(max_n_coords);
while (*str != '\0') { while (*str != '\0') {
char *cp = strchr(str, ','); char *cp = strchr(str, ',');
if (!cp) { if (!cp) {
Error("Bogus coordinate %s found in polygon string", str); Error("Bogus coordinate %s found in polygon string", str);
break; break;
} }
int x = atoi(str); int x = atoi(str);
int y = atoi(cp+1); int y = atoi(cp + 1);
Debug(3, "Got coordinate %d,%d from polygon string", x, y); Debug(3, "Got coordinate %d,%d from polygon string", x, y);
coords[n_coords++] = Coord(x, y); vertices.emplace_back(x, y);
char *ws = strchr(cp+2, ' '); char *ws = strchr(cp + 2, ' ');
if (ws) if (ws) {
str = ws+1; str = ws + 1;
else } else {
break; break;
} // end while ! end of string }
if (n_coords > 2) {
Debug(3, "Successfully parsed polygon string %s", str);
polygon = Polygon(n_coords, coords);
} else {
Error("Not enough coordinates to form a polygon!");
n_coords = 0;
} }
delete[] coords; if (vertices.size() > 2) {
return n_coords ? true : false; Debug(3, "Successfully parsed polygon string %s", str);
polygon = Polygon(vertices);
} else {
Error("Not enough coordinates to form a polygon!");
}
return !vertices.empty();
} // end bool Zone::ParsePolygonString(const char *poly_string, Polygon &polygon) } // end bool Zone::ParsePolygonString(const char *poly_string, Polygon &polygon)
bool Zone::ParseZoneString(const char *zone_string, int &zone_id, int &colour, Polygon &polygon) { bool Zone::ParseZoneString(const char *zone_string, int &zone_id, int &colour, Polygon &polygon) {
@ -872,14 +874,21 @@ std::vector<Zone> Zone::Load(Monitor *monitor) {
continue; continue;
} }
if ( polygon.LoX() < 0 || polygon.HiX() >= (int)monitor->Width() if (polygon.Extent().Lo().x_ < 0 || polygon.Extent().Hi().x_ > static_cast<int32>(monitor->Width())
|| polygon.LoY() < 0 || polygon.HiY() >= (int)monitor->Height() ) { || polygon.Extent().Lo().y_ < 0 || polygon.Extent().Hi().y_ > static_cast<int32>(monitor->Height())) {
Error("Zone %d/%s for monitor %s extends outside of image dimensions, (%d,%d), (%d,%d), fixing", Error("Zone %d/%s for monitor %s extends outside of image dimensions, (%d,%d), (%d,%d), fixing",
Id, Name, monitor->Name(), polygon.LoX(), polygon.LoY(), polygon.HiX(), polygon.HiY()); Id,
if ( polygon.LoX() < 0 ) polygon.LoX(0); Name,
if ( polygon.HiX() >= (int)monitor->Width()) polygon.HiX((int)monitor->Width()); monitor->Name(),
if ( polygon.LoY() < 0 ) polygon.LoY(0); polygon.Extent().Lo().x_,
if ( polygon.HiY() >= (int)monitor->Height() ) polygon.HiY((int)monitor->Height()); polygon.Extent().Lo().y_,
polygon.Extent().Hi().x_,
polygon.Extent().Hi().y_);
polygon.Clip(Box(
{0, 0},
{static_cast<int32>(monitor->Width()), static_cast<int32>(monitor->Height())}
));
} }
if ( false && !strcmp( Units, "Percent" ) ) { if ( false && !strcmp( Units, "Percent" ) ) {
@ -899,7 +908,7 @@ std::vector<Zone> Zone::Load(Monitor *monitor) {
zones.emplace_back( zones.emplace_back(
monitor, Id, Name, Type, polygon, AlarmRGB, monitor, Id, Name, Type, polygon, AlarmRGB,
CheckMethod, MinPixelThreshold, MaxPixelThreshold, CheckMethod, MinPixelThreshold, MaxPixelThreshold,
MinAlarmPixels, MaxAlarmPixels, Coord(FilterX, FilterY), MinAlarmPixels, MaxAlarmPixels, Vector2(FilterX, FilterY),
MinFilterPixels, MaxFilterPixels, MinFilterPixels, MaxFilterPixels,
MinBlobPixels, MaxBlobPixels, MinBlobs, MaxBlobs, MinBlobPixels, MaxBlobPixels, MinBlobs, MaxBlobs,
OverloadFrames, ExtendAlarmFrames); OverloadFrames, ExtendAlarmFrames);
@ -922,9 +931,9 @@ bool Zone::DumpSettings(char *output, bool /*verbose*/) const {
type==INACTIVE?"Inactive":( type==INACTIVE?"Inactive":(
type==PRIVACY?"Privacy":"Unknown" type==PRIVACY?"Privacy":"Unknown"
)))))); ))))));
sprintf( output+strlen(output), " Shape : %d points\n", polygon.getNumCoords() ); sprintf( output+strlen(output), " Shape : %zu points\n", polygon.GetVertices().size() );
for ( int i = 0; i < polygon.getNumCoords(); i++ ) { for (size_t i = 0; i < polygon.GetVertices().size(); i++) {
sprintf( output+strlen(output), " %i: %d,%d\n", i, polygon.getCoord( i ).X(), polygon.getCoord( i ).Y() ); sprintf(output + strlen(output), " %zu: %d,%d\n", i, polygon.GetVertices()[i].x_, polygon.GetVertices()[i].y_);
} }
sprintf( output+strlen(output), " Alarm RGB : %06x\n", alarm_rgb ); sprintf( output+strlen(output), " Alarm RGB : %06x\n", alarm_rgb );
sprintf( output+strlen(output), " Check Method: %d - %s\n", check_method, sprintf( output+strlen(output), " Check Method: %d - %s\n", check_method,
@ -936,7 +945,7 @@ bool Zone::DumpSettings(char *output, bool /*verbose*/) const {
sprintf( output+strlen(output), " Max Pixel Threshold : %d\n", max_pixel_threshold ); sprintf( output+strlen(output), " Max Pixel Threshold : %d\n", max_pixel_threshold );
sprintf( output+strlen(output), " Min Alarm Pixels : %d\n", min_alarm_pixels ); sprintf( output+strlen(output), " Min Alarm Pixels : %d\n", min_alarm_pixels );
sprintf( output+strlen(output), " Max Alarm Pixels : %d\n", max_alarm_pixels ); sprintf( output+strlen(output), " Max Alarm Pixels : %d\n", max_alarm_pixels );
sprintf( output+strlen(output), " Filter Box : %d,%d\n", filter_box.X(), filter_box.Y() ); sprintf(output+strlen(output), " Filter Box : %d,%d\n", filter_box.x_, filter_box.y_ );
sprintf( output+strlen(output), " Min Filter Pixels : %d\n", min_filter_pixels ); sprintf( output+strlen(output), " Min Filter Pixels : %d\n", min_filter_pixels );
sprintf( output+strlen(output), " Max Filter Pixels : %d\n", max_filter_pixels ); sprintf( output+strlen(output), " Max Filter Pixels : %d\n", max_filter_pixels );
sprintf( output+strlen(output), " Min Blob Pixels : %d\n", min_blob_pixels ); sprintf( output+strlen(output), " Min Blob Pixels : %d\n", min_blob_pixels );
@ -960,8 +969,8 @@ void Zone::std_alarmedpixels(
if ( max_pixel_threshold ) if ( max_pixel_threshold )
calc_max_pixel_threshold = max_pixel_threshold; calc_max_pixel_threshold = max_pixel_threshold;
lo_y = polygon.LoY(); lo_y = polygon.Extent().Lo().y_;
hi_y = polygon.HiY(); hi_y = polygon.Extent().Hi().y_;
for ( unsigned int y = lo_y; y <= hi_y; y++ ) { for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
unsigned int lo_x = ranges[y].lo_x; unsigned int lo_x = ranges[y].lo_x;
unsigned int hi_x = ranges[y].hi_x; unsigned int hi_x = ranges[y].hi_x;

View File

@ -21,12 +21,12 @@
#define ZM_ZONE_H #define ZM_ZONE_H
#include "zm_box.h" #include "zm_box.h"
#include "zm_coord.h"
#include "zm_define.h" #include "zm_define.h"
#include "zm_config.h" #include "zm_config.h"
#include "zm_poly.h" #include "zm_poly.h"
#include "zm_rgb.h" #include "zm_rgb.h"
#include "zm_zone_stats.h" #include "zm_zone_stats.h"
#include "zm_vector2.h"
#include <algorithm> #include <algorithm>
#include <string> #include <string>
@ -77,7 +77,7 @@ class Zone {
int min_alarm_pixels; int min_alarm_pixels;
int max_alarm_pixels; int max_alarm_pixels;
Coord filter_box; Vector2 filter_box;
int min_filter_pixels; int min_filter_pixels;
int max_filter_pixels; int max_filter_pixels;
@ -112,7 +112,7 @@ class Zone {
int p_max_pixel_threshold, int p_max_pixel_threshold,
int p_min_alarm_pixels, int p_min_alarm_pixels,
int p_max_alarm_pixels, int p_max_alarm_pixels,
const Coord &p_filter_box, const Vector2 &p_filter_box,
int p_min_filter_pixels, int p_min_filter_pixels,
int p_max_filter_pixels, int p_max_filter_pixels,
int p_min_blob_pixels, int p_min_blob_pixels,
@ -137,7 +137,7 @@ class Zone {
int p_max_pixel_threshold=0, int p_max_pixel_threshold=0,
int p_min_alarm_pixels=50, int p_min_alarm_pixels=50,
int p_max_alarm_pixels=75000, int p_max_alarm_pixels=75000,
const Coord &p_filter_box=Coord( 3, 3 ), const Vector2 &p_filter_box = Vector2(3, 3),
int p_min_filter_pixels=50, int p_min_filter_pixels=50,
int p_max_filter_pixels=50000, int p_max_filter_pixels=50000,
int p_min_blob_pixels=10, int p_min_blob_pixels=10,
@ -164,7 +164,7 @@ class Zone {
blob_stats{}, blob_stats{},
stats(p_id) stats(p_id)
{ {
Setup(Zone::INACTIVE, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Coord(0, 0), 0, 0, 0, 0, 0, 0, 0, 0); Setup(Zone::INACTIVE, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Vector2(0, 0), 0, 0, 0, 0, 0, 0, 0, 0);
} }
Zone(Monitor *p_monitor, int p_id, const char *p_label, ZoneType p_type, const Polygon &p_polygon) Zone(Monitor *p_monitor, int p_id, const char *p_label, ZoneType p_type, const Polygon &p_polygon)
: :
@ -174,7 +174,7 @@ class Zone {
blob_stats{}, blob_stats{},
stats(p_id) stats(p_id)
{ {
Setup(p_type, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Coord( 0, 0 ), 0, 0, 0, 0, 0, 0, 0, 0 ); Setup(p_type, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Vector2(0, 0), 0, 0, 0, 0, 0, 0, 0, 0 );
} }
Zone(const Zone &z); Zone(const Zone &z);
@ -195,7 +195,7 @@ class Zone {
inline bool WasAlarmed() const { return was_alarmed; } inline bool WasAlarmed() const { return was_alarmed; }
inline void SetAlarm() { was_alarmed = alarmed; alarmed = true; } inline void SetAlarm() { was_alarmed = alarmed; alarmed = true; }
inline void ClearAlarm() { was_alarmed = alarmed; alarmed = false; } inline void ClearAlarm() { was_alarmed = alarmed; alarmed = false; }
inline Coord GetAlarmCentre() const { return stats.alarm_centre_; } inline Vector2 GetAlarmCentre() const { return stats.alarm_centre_; }
inline unsigned int Score() const { return stats.score_; } inline unsigned int Score() const { return stats.score_; }
inline void ResetStats() { inline void ResetStats() {

View File

@ -21,8 +21,8 @@
#define ZM_ZONE_STATS_H #define ZM_ZONE_STATS_H
#include "zm_box.h" #include "zm_box.h"
#include "zm_coord.h"
#include "zm_logger.h" #include "zm_logger.h"
#include "zm_vector2.h"
class ZoneStats { class ZoneStats {
public: public:
@ -35,8 +35,6 @@ class ZoneStats {
alarm_blobs_(0), alarm_blobs_(0),
min_blob_size_(0), min_blob_size_(0),
max_blob_size_(0), max_blob_size_(0),
alarm_box_({}),
alarm_centre_({}),
score_(0) {}; score_(0) {};
void Reset() { void Reset() {
@ -47,10 +45,7 @@ class ZoneStats {
alarm_blobs_ = 0; alarm_blobs_ = 0;
min_blob_size_ = 0; min_blob_size_ = 0;
max_blob_size_ = 0; max_blob_size_ = 0;
alarm_box_.LoX(0); alarm_box_ = {};
alarm_box_.LoY(0);
alarm_box_.HiX(0);
alarm_box_.HiY(0);
alarm_centre_ = {}; alarm_centre_ = {};
score_ = 0; score_ = 0;
} }
@ -67,12 +62,12 @@ class ZoneStats {
alarm_blobs_, alarm_blobs_,
min_blob_size_, min_blob_size_,
max_blob_size_, max_blob_size_,
alarm_box_.LoX(), alarm_box_.Lo().x_,
alarm_box_.LoY(), alarm_box_.Lo().y_,
alarm_box_.HiX(), alarm_box_.Hi().x_,
alarm_box_.HiY(), alarm_box_.Hi().y_,
alarm_centre_.X(), alarm_centre_.x_,
alarm_centre_.Y(), alarm_centre_.y_,
score_ score_
); );
} }
@ -87,7 +82,7 @@ class ZoneStats {
int min_blob_size_; int min_blob_size_;
int max_blob_size_; int max_blob_size_;
Box alarm_box_; Box alarm_box_;
Coord alarm_centre_; Vector2 alarm_centre_;
unsigned int score_; unsigned int score_;
}; };

View File

@ -12,10 +12,13 @@
include(Catch) include(Catch)
set(TEST_SOURCES set(TEST_SOURCES
zm_box.cpp
zm_comms.cpp zm_comms.cpp
zm_crypt.cpp zm_crypt.cpp
zm_font.cpp zm_font.cpp
zm_utils.cpp) zm_poly.cpp
zm_utils.cpp
zm_vector2.cpp)
add_executable(tests main.cpp ${TEST_SOURCES}) add_executable(tests main.cpp ${TEST_SOURCES})

52
tests/zm_box.cpp Normal file
View File

@ -0,0 +1,52 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_box.h"
TEST_CASE("Box: default constructor") {
Box b;
REQUIRE(b.Lo() == Vector2(0, 0));
REQUIRE(b.Hi() == Vector2(0, 0));
REQUIRE(b.Size() == Vector2(0, 0));
REQUIRE(b.Area() == 0);
}
TEST_CASE("Box: construct from lo and hi") {
Box b({1, 1}, {5, 5});
SECTION("basic properties") {
REQUIRE(b.Lo() == Vector2(1, 1));
REQUIRE(b.Hi() == Vector2(5, 5));
REQUIRE(b.Size() == Vector2(4 ,4));
REQUIRE(b.Area() == 16);
REQUIRE(b.Centre() == Vector2(3, 3));
REQUIRE(b.Vertices() == std::vector<Vector2>{{1, 1}, {5, 1}, {5, 5}, {1, 5}});
}
SECTION("contains") {
REQUIRE(b.Contains({0, 0}) == false);
REQUIRE(b.Contains({1, 1}) == true);
REQUIRE(b.Contains({3, 3}) == true);
REQUIRE(b.Contains({5, 5}) == true);
REQUIRE(b.Contains({6, 6}) == false);
}
}

30
tests/zm_catch2.h Normal file
View File

@ -0,0 +1,30 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#ifndef ZONEMINDER_TESTS_ZM_CATCH2_H_
#define ZONEMINDER_TESTS_ZM_CATCH2_H_
#include "catch2/catch.hpp"
#include "zm_vector2.h"
inline std::ostream &operator<<(std::ostream &os, Vector2 const &value) {
os << "{ X: " << value.x_ << ", Y: " << value.y_ << " }";
return os;
}
#endif //ZONEMINDER_TESTS_ZM_CATCH2_H_

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>. * with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "catch2/catch.hpp" #include "zm_catch2.h"
#include "zm_comms.h" #include "zm_comms.h"
#include <array> #include <array>
@ -224,23 +224,42 @@ TEST_CASE("ZM::UdpUnixSocket send/recv") {
ZM::UdpUnixSocket srv_socket; ZM::UdpUnixSocket srv_socket;
ZM::UdpUnixSocket client_socket; ZM::UdpUnixSocket client_socket;
std::array<char, 3> msg = {'a', 'b', 'c'}; SECTION("send/recv byte buffer") {
std::array<char, msg.size()> rcv{}; std::array<char, 3> msg = {'a', 'b', 'c'};
std::array<char, msg.size()> rcv{};
SECTION("send/recv on unbound socket") { SECTION("on unbound socket") {
REQUIRE(client_socket.send(msg.data(), msg.size()) == -1); REQUIRE(client_socket.send(msg.data(), msg.size()) == -1);
REQUIRE(srv_socket.recv(rcv.data(), rcv.size()) == -1); REQUIRE(srv_socket.recv(rcv.data(), rcv.size()) == -1);
}
SECTION("on bound socket") {
REQUIRE(srv_socket.bind(sock_path.c_str()) == true);
REQUIRE(srv_socket.isOpen() == true);
REQUIRE(client_socket.connect(sock_path.c_str()) == true);
REQUIRE(client_socket.isConnected() == true);
REQUIRE(client_socket.send(msg.data(), msg.size()) == msg.size());
REQUIRE(srv_socket.recv(rcv.data(), rcv.size()) == msg.size());
REQUIRE(rcv == msg);
}
} }
SECTION("send/recv") { SECTION("send/recv string") {
std::string msg = "abc";
std::string rcv;
rcv.reserve(msg.length());
REQUIRE(srv_socket.bind(sock_path.c_str()) == true); REQUIRE(srv_socket.bind(sock_path.c_str()) == true);
REQUIRE(srv_socket.isOpen() == true); REQUIRE(srv_socket.isOpen() == true);
REQUIRE(client_socket.connect(sock_path.c_str()) == true); REQUIRE(client_socket.connect(sock_path.c_str()) == true);
REQUIRE(client_socket.isConnected() == true); REQUIRE(client_socket.isConnected() == true);
REQUIRE(client_socket.send(msg.data(), msg.size()) == msg.size()); REQUIRE(client_socket.send(msg) == static_cast<ssize_t>(msg.size()));
REQUIRE(srv_socket.recv(rcv.data(), rcv.size()) == msg.size()); REQUIRE(srv_socket.recv(rcv) == static_cast<ssize_t>(msg.size()));
REQUIRE(rcv == msg); REQUIRE(rcv == msg);
} }

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>. * with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "catch2/catch.hpp" #include "zm_catch2.h"
#include "zm_crypt.h" #include "zm_crypt.h"

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>. * with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "catch2/catch.hpp" #include "zm_catch2.h"
#include "zm_font.h" #include "zm_font.h"

71
tests/zm_poly.cpp Normal file
View File

@ -0,0 +1,71 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_poly.h"
TEST_CASE("Polygon: default constructor") {
Polygon p;
REQUIRE(p.Area() == 0);
REQUIRE(p.Centre() == Vector2(0, 0));
}
TEST_CASE("Polygon: construct from vertices") {
std::vector<Vector2> vertices{{{0, 0}, {6, 0}, {0, 6}}};
Polygon p(vertices);
REQUIRE(p.Area() == 18);
REQUIRE(p.Extent().Size() == Vector2(6, 6));
}
TEST_CASE("Polygon: clipping") {
// This a concave polygon in a shape resembling a "W"
std::vector<Vector2> v = {
{3, 1},
{5, 1},
{6, 3},
{7, 1},
{9, 1},
{10, 8},
{8, 8},
{7, 5},
{5, 5},
{4, 8},
{2, 8}
};
Polygon p(v);
REQUIRE(p.GetVertices().size() == 11);
REQUIRE(p.Extent().Size() == Vector2(8, 7));
SECTION("boundary box larger than polygon") {
p.Clip(Box({1, 0}, {11, 9}));
REQUIRE(p.GetVertices().size() == 11);
REQUIRE(p.Extent().Size() == Vector2(8, 7));
}
SECTION("boundary box smaller than polygon") {
p.Clip(Box({2, 4}, {10, 7}));
REQUIRE(p.GetVertices().size() == 8);
REQUIRE(p.Extent().Size() == Vector2(8, 3));
}
}

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>. * with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "catch2/catch.hpp" #include "zm_catch2.h"
#include "zm_utils.h" #include "zm_utils.h"
#include <sstream> #include <sstream>

94
tests/zm_vector2.cpp Normal file
View File

@ -0,0 +1,94 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_vector2.h"
TEST_CASE("Vector2: default constructor") {
Vector2 c;
REQUIRE(c.x_ == 0);
REQUIRE(c.y_ == 0);
}
TEST_CASE("Vector2: x/y constructor") {
Vector2 c(1, 2);
REQUIRE(c.x_ == 1);
REQUIRE(c.y_ == 2);
}
TEST_CASE("Vector2: assignment/copy") {
Vector2 c;
Vector2 c2(1, 2);
REQUIRE(c.x_ == 0);
REQUIRE(c.y_ == 0);
SECTION("assignment operator") {
c = c2;
REQUIRE(c.x_ == 1);
REQUIRE(c.y_ == 2);
}
SECTION("copy constructor") {
Vector2 c3(c2); // NOLINT(performance-unnecessary-copy-initialization)
REQUIRE(c3.x_ == 1);
REQUIRE(c3.y_ == 2);
}
}
TEST_CASE("Vector2: comparison operators") {
Vector2 c1(1, 2);
Vector2 c2(1, 2);
Vector2 c3(1, 3);
REQUIRE((c1 == c2) == true);
REQUIRE((c1 != c3) == true);
}
TEST_CASE("Vector2: arithmetic operators") {
Vector2 c(1, 1);
SECTION("addition") {
Vector2 c1 = c + Vector2(1, 1);
REQUIRE(c1 == Vector2(2, 2));
c += {1, 2};
REQUIRE(c == Vector2(2, 3));
}
SECTION("subtraction") {
Vector2 c1 = c - Vector2(1, 1);
REQUIRE(c1 == Vector2(0, 0));
c -= {1, 2};
REQUIRE(c == Vector2(0, -1));
}
SECTION("scalar multiplication") {
c = c * 2;
REQUIRE(c == Vector2(2, 2));
}
}
TEST_CASE("Vector2: determinate") {
Vector2 v(1, 1);
REQUIRE(v.Determinant({0, 0}) == 0);
REQUIRE(v.Determinant({1, 1}) == 0);
REQUIRE(v.Determinant({1, 2}) == 1);
}

View File

@ -1 +1 @@
1.36.0 1.37.0