diff --git a/src/zm_monitor.cpp b/src/zm_monitor.cpp index 0bacadd0f..1de2c31de 100644 --- a/src/zm_monitor.cpp +++ b/src/zm_monitor.cpp @@ -74,8 +74,7 @@ std::vector split(const std::string &s, char delim) { -Monitor::MonitorLink::MonitorLink( int p_id, const char *p_name ) : id( p_id ) -{ +Monitor::MonitorLink::MonitorLink( int p_id, const char *p_name ) : id( p_id ) { strncpy( name, p_name, sizeof(name) ); #if ZM_MEM_MAPPED @@ -94,15 +93,12 @@ Monitor::MonitorLink::MonitorLink( int p_id, const char *p_name ) : id( p_id ) connected = false; } -Monitor::MonitorLink::~MonitorLink() -{ +Monitor::MonitorLink::~MonitorLink() { disconnect(); } -bool Monitor::MonitorLink::connect() -{ - if ( !last_connect_time || (time( 0 ) - last_connect_time) > 60 ) - { +bool Monitor::MonitorLink::connect() { + if ( !last_connect_time || (time( 0 ) - last_connect_time) > 60 ) { last_connect_time = time( 0 ); mem_size = sizeof(SharedData) + sizeof(TriggerData); @@ -110,8 +106,7 @@ bool Monitor::MonitorLink::connect() Debug( 1, "link.mem.size=%d", mem_size ); #if ZM_MEM_MAPPED map_fd = open( mem_file, O_RDWR, (mode_t)0600 ); - if ( map_fd < 0 ) - { + if ( map_fd < 0 ) { Debug( 3, "Can't open linked memory map file %s: %s", mem_file, strerror(errno) ); disconnect(); return( false ); @@ -124,44 +119,37 @@ bool Monitor::MonitorLink::connect() } struct stat map_stat; - if ( fstat( map_fd, &map_stat ) < 0 ) - { + if ( fstat( map_fd, &map_stat ) < 0 ) { Error( "Can't stat linked memory map file %s: %s", mem_file, strerror(errno) ); disconnect(); return( false ); } - if ( map_stat.st_size == 0 ) - { + if ( map_stat.st_size == 0 ) { Error( "Linked memory map file %s is empty: %s", mem_file, strerror(errno) ); disconnect(); return( false ); - } - else if ( map_stat.st_size < mem_size ) - { + } else if ( map_stat.st_size < mem_size ) { Error( "Got unexpected memory map file size %ld, expected %d", map_stat.st_size, mem_size ); disconnect(); return( false ); } mem_ptr = (unsigned char *)mmap( NULL, mem_size, PROT_READ|PROT_WRITE, MAP_SHARED, map_fd, 0 ); - if ( mem_ptr == MAP_FAILED ) - { + if ( mem_ptr == MAP_FAILED ) { Error( "Can't map file %s (%d bytes) to memory: %s", mem_file, mem_size, strerror(errno) ); disconnect(); return( false ); } #else // ZM_MEM_MAPPED shm_id = shmget( (config.shm_key&0xffff0000)|id, mem_size, 0700 ); - if ( shm_id < 0 ) - { + if ( shm_id < 0 ) { Debug( 3, "Can't shmget link memory: %s", strerror(errno) ); connected = false; return( false ); } mem_ptr = (unsigned char *)shmat( shm_id, 0, 0 ); - if ( mem_ptr < 0 ) - { + if ( mem_ptr < 0 ) { Debug( 3, "Can't shmat link memory: %s", strerror(errno) ); connected = false; return( false ); @@ -171,8 +159,7 @@ bool Monitor::MonitorLink::connect() shared_data = (SharedData *)mem_ptr; trigger_data = (TriggerData *)((char *)shared_data + sizeof(SharedData)); - if ( !shared_data->valid ) - { + if ( !shared_data->valid ) { Debug( 3, "Linked memory not initialised by capture daemon" ); disconnect(); return( false ); @@ -187,15 +174,12 @@ bool Monitor::MonitorLink::connect() return( false ); } -bool Monitor::MonitorLink::disconnect() -{ - if ( connected ) - { +bool Monitor::MonitorLink::disconnect() { + if ( connected ) { connected = false; #if ZM_MEM_MAPPED - if ( mem_ptr > 0 ) - { + if ( mem_ptr > 0 ) { msync( mem_ptr, mem_size, MS_ASYNC ); munmap( mem_ptr, mem_size ); } @@ -205,25 +189,21 @@ bool Monitor::MonitorLink::disconnect() map_fd = -1; #else // ZM_MEM_MAPPED struct shmid_ds shm_data; - if ( shmctl( shm_id, IPC_STAT, &shm_data ) < 0 ) - { + if ( shmctl( shm_id, IPC_STAT, &shm_data ) < 0 ) { Debug( 3, "Can't shmctl: %s", strerror(errno) ); return( false ); } shm_id = 0; - if ( shm_data.shm_nattch <= 1 ) - { - if ( shmctl( shm_id, IPC_RMID, 0 ) < 0 ) - { + if ( shm_data.shm_nattch <= 1 ) { + if ( shmctl( shm_id, IPC_RMID, 0 ) < 0 ) { Debug( 3, "Can't shmctl: %s", strerror(errno) ); return( false ); } } - if ( shmdt( mem_ptr ) < 0 ) - { + if ( shmdt( mem_ptr ) < 0 ) { Debug( 3, "Can't shmdt: %s", strerror(errno) ); return( false ); } @@ -235,32 +215,24 @@ bool Monitor::MonitorLink::disconnect() return( true ); } -bool Monitor::MonitorLink::isAlarmed() -{ - if ( !connected ) - { +bool Monitor::MonitorLink::isAlarmed() { + if ( !connected ) { return( false ); } return( shared_data->state == ALARM ); } -bool Monitor::MonitorLink::inAlarm() -{ - if ( !connected ) - { +bool Monitor::MonitorLink::inAlarm() { + if ( !connected ) { return( false ); } return( shared_data->state == ALARM || shared_data->state == ALERT ); } -bool Monitor::MonitorLink::hasAlarmed() -{ - if ( shared_data->state == ALARM ) - { +bool Monitor::MonitorLink::hasAlarmed() { + if ( shared_data->state == ALARM ) { return( true ); - } - else if( shared_data->last_event != (unsigned int)last_event ) - { + } else if( shared_data->last_event != (unsigned int)last_event ) { last_event = shared_data->last_event; } return( false ); @@ -350,16 +322,12 @@ Monitor::Monitor( // Change \n to actual line feeds char *token_ptr = label_format; const char *token_string = "\n"; - while( ( token_ptr = strstr( token_ptr, token_string ) ) ) - { - if ( *(token_ptr+1) ) - { + while( ( token_ptr = strstr( token_ptr, token_string ) ) ) { + if ( *(token_ptr+1) ) { *token_ptr = '\n'; token_ptr++; strcpy( token_ptr, token_ptr+1 ); - } - else - { + } else { *token_ptr = '\0'; break; } @@ -435,10 +403,8 @@ Monitor::Monitor( shared_data->alarm_y = -1; } - if ( ( ! mem_ptr ) || ! shared_data->valid ) - { - if ( purpose != QUERY ) - { + if ( ( ! mem_ptr ) || ! shared_data->valid ) { + if ( purpose != QUERY ) { Error( "Shared data not initialised by capture daemon for monitor %s", name ); exit( -1 ); } @@ -460,8 +426,7 @@ Monitor::Monitor( Debug( 1, "Monitor %s LBF = '%s', LBX = %d, LBY = %d, LBS = %d", name, label_format, label_coord.X(), label_coord.Y(), label_size ); Debug( 1, "Monitor %s IBC = %d, WUC = %d, pEC = %d, PEC = %d, EAF = %d, FRI = %d, RBP = %d, ARBP = %d, FM = %d", name, image_buffer_count, warmup_count, pre_event_count, post_event_count, alarm_frame_count, fps_report_interval, ref_blend_perc, alarm_ref_blend_perc, track_motion ); - if ( purpose == ANALYSIS ) - { + if ( purpose == ANALYSIS ) { static char path[PATH_MAX]; strncpy( path, config.dir_events, sizeof(path) ); @@ -469,10 +434,8 @@ Monitor::Monitor( struct stat statbuf; errno = 0; stat( path, &statbuf ); - if ( errno == ENOENT || errno == ENOTDIR ) - { - if ( mkdir( path, 0755 ) ) - { + if ( errno == ENOENT || errno == ENOTDIR ) { + if ( mkdir( path, 0755 ) ) { Error( "Can't make %s: %s", path, strerror(errno)); } } @@ -481,10 +444,8 @@ Monitor::Monitor( errno = 0; stat( path, &statbuf ); - if ( errno == ENOENT || errno == ENOTDIR ) - { - if ( mkdir( path, 0755 ) ) - { + if ( errno == ENOENT || errno == ENOTDIR ) { + if ( mkdir( path, 0755 ) ) { Error( "Can't make %s: %s", path, strerror(errno)); } char temp_path[PATH_MAX]; @@ -575,29 +536,25 @@ bool Monitor::connect() { shared_images = (uint8_t*)((unsigned long)shared_images + (16 - ((unsigned long)shared_images % 16))); } image_buffer = new Snapshot[image_buffer_count]; - for ( int i = 0; i < image_buffer_count; i++ ) - { + for ( int i = 0; i < image_buffer_count; i++ ) { image_buffer[i].timestamp = &(shared_timestamps[i]); image_buffer[i].image = new Image( width, height, camera->Colours(), camera->SubpixelOrder(), &(shared_images[i*camera->ImageSize()]) ); image_buffer[i].image->HoldBuffer(true); /* Don't release the internal buffer or replace it with another */ } - if ( (deinterlacing & 0xff) == 4) - { + if ( (deinterlacing & 0xff) == 4) { /* Four field motion adaptive deinterlacing in use */ /* Allocate a buffer for the next image */ next_buffer.image = new Image( width, height, camera->Colours(), camera->SubpixelOrder()); next_buffer.timestamp = new struct timeval; } - if ( ( purpose == ANALYSIS ) && analysis_fps ) - { + if ( ( purpose == ANALYSIS ) && analysis_fps ) { // Size of pre event buffer must be greater than pre_event_count // if alarm_frame_count > 1, because in this case the buffer contains // alarmed images that must be discarded when event is created pre_event_buffer_count = pre_event_count + alarm_frame_count - 1; pre_event_buffer = new Snapshot[pre_event_buffer_count]; - for ( int i = 0; i < pre_event_buffer_count; i++ ) - { + for ( int i = 0; i < pre_event_buffer_count; i++ ) { pre_event_buffer[i].timestamp = new struct timeval; pre_event_buffer[i].image = new Image( width, height, camera->Colours(), camera->SubpixelOrder()); } @@ -606,8 +563,7 @@ bool Monitor::connect() { return true; } -Monitor::~Monitor() -{ +Monitor::~Monitor() { if ( timestamps ) { delete[] timestamps; timestamps = 0; @@ -625,20 +581,17 @@ Monitor::~Monitor() Info( "%s: %03d - Closing event %d, shutting down", name, image_count, event->Id() ); closeEvent(); - if ( (deinterlacing & 0xff) == 4) - { + if ( (deinterlacing & 0xff) == 4) { delete next_buffer.image; delete next_buffer.timestamp; } - for ( int i = 0; i < image_buffer_count; i++ ) - { + for ( int i = 0; i < image_buffer_count; i++ ) { delete image_buffer[i].image; } delete[] image_buffer; } // end if mem_ptr - for ( int i = 0; i < n_zones; i++ ) - { + for ( int i = 0; i < n_zones; i++ ) { delete zones[i]; } delete[] zones; @@ -646,24 +599,19 @@ Monitor::~Monitor() delete camera; if ( mem_ptr ) { - if ( purpose == ANALYSIS ) - { + if ( purpose == ANALYSIS ) { shared_data->state = state = IDLE; shared_data->last_read_index = image_buffer_count; shared_data->last_read_time = 0; - if ( analysis_fps ) - { - for ( int i = 0; i < pre_event_buffer_count; i++ ) - { + if ( analysis_fps ) { + for ( int i = 0; i < pre_event_buffer_count; i++ ) { delete pre_event_buffer[i].image; delete pre_event_buffer[i].timestamp; } delete[] pre_event_buffer; } - } - else if ( purpose == CAPTURE ) - { + } else if ( purpose == CAPTURE ) { shared_data->valid = false; memset( mem_ptr, 0, mem_size ); } @@ -699,8 +647,7 @@ Monitor::~Monitor() } // end if mem_ptr } -void Monitor::AddZones( int p_n_zones, Zone *p_zones[] ) -{ +void Monitor::AddZones( int p_n_zones, Zone *p_zones[] ) { for ( int i = 0; i < n_zones; i++ ) delete zones[i]; delete[] zones; @@ -708,19 +655,15 @@ void Monitor::AddZones( int p_n_zones, Zone *p_zones[] ) zones = p_zones; } -void Monitor::AddPrivacyBitmask( Zone *p_zones[] ) -{ +void Monitor::AddPrivacyBitmask( Zone *p_zones[] ) { if ( privacy_bitmask ) delete[] privacy_bitmask; privacy_bitmask = NULL; Image *privacy_image = NULL; - for ( int i = 0; i < n_zones; i++ ) - { - if ( p_zones[i]->IsPrivacy() ) - { - if ( !privacy_image ) - { + for ( int i = 0; i < n_zones; i++ ) { + if ( p_zones[i]->IsPrivacy() ) { + if ( !privacy_image ) { privacy_image = new Image( width, height, 1, ZM_SUBPIX_ORDER_NONE); privacy_image->Clear(); } @@ -732,20 +675,16 @@ void Monitor::AddPrivacyBitmask( Zone *p_zones[] ) privacy_bitmask = privacy_image->Buffer(); } -Monitor::State Monitor::GetState() const -{ +Monitor::State Monitor::GetState() const { return( (State)shared_data->state ); } -int Monitor::GetImage( int index, int scale ) -{ - if ( index < 0 || index > image_buffer_count ) - { +int Monitor::GetImage( int index, int scale ) { + if ( index < 0 || index > image_buffer_count ) { index = shared_data->last_write_index; } - if ( index != image_buffer_count ) - { + if ( index != image_buffer_count ) { Image *image; // If we are going to be modifying the snapshot before writing, then we need to copy it if ( ( scale != ZM_SCALE_BASE ) || ( !config.timestamp_on_capture ) ) { @@ -772,75 +711,59 @@ int Monitor::GetImage( int index, int scale ) static char filename[PATH_MAX]; snprintf( filename, sizeof(filename), "Monitor%d.jpg", id ); image->WriteJpeg( filename ); - } - else - { + } else { Error( "Unable to generate image, no images in buffer" ); } return( 0 ); } -struct timeval Monitor::GetTimestamp( int index ) const -{ - if ( index < 0 || index > image_buffer_count ) - { +struct timeval Monitor::GetTimestamp( int index ) const { + if ( index < 0 || index > image_buffer_count ) { index = shared_data->last_write_index; } - if ( index != image_buffer_count ) - { + if ( index != image_buffer_count ) { Snapshot *snap = &image_buffer[index]; return( *(snap->timestamp) ); - } - else - { + } else { static struct timeval null_tv = { 0, 0 }; return( null_tv ); } } -unsigned int Monitor::GetLastReadIndex() const -{ +unsigned int Monitor::GetLastReadIndex() const { return( shared_data->last_read_index!=(unsigned int)image_buffer_count?shared_data->last_read_index:-1 ); } -unsigned int Monitor::GetLastWriteIndex() const -{ +unsigned int Monitor::GetLastWriteIndex() const { return( shared_data->last_write_index!=(unsigned int)image_buffer_count?shared_data->last_write_index:-1 ); } -unsigned int Monitor::GetLastEvent() const -{ +unsigned int Monitor::GetLastEvent() const { return( shared_data->last_event ); } -double Monitor::GetFPS() const -{ +double Monitor::GetFPS() const { int index1 = shared_data->last_write_index; - if ( index1 == image_buffer_count ) - { + if ( index1 == image_buffer_count ) { return( 0.0 ); } Snapshot *snap1 = &image_buffer[index1]; - if ( !snap1->timestamp || !snap1->timestamp->tv_sec ) - { + if ( !snap1->timestamp || !snap1->timestamp->tv_sec ) { return( 0.0 ); } struct timeval time1 = *snap1->timestamp; int image_count = image_buffer_count; int index2 = (index1+1)%image_buffer_count; - if ( index2 == image_buffer_count ) - { + if ( index2 == image_buffer_count ) { return( 0.0 ); } Snapshot *snap2 = &image_buffer[index2]; - while ( !snap2->timestamp || !snap2->timestamp->tv_sec ) - { - if ( index1 == index2 ) - { + while ( !snap2->timestamp || !snap2->timestamp->tv_sec ) { + if ( index1 == index2 ) { return( 0.0 ); } index2 = (index2+1)%image_buffer_count; @@ -853,143 +776,110 @@ double Monitor::GetFPS() const double curr_fps = image_count/time_diff; - if ( curr_fps < 0.0 ) - { + if ( curr_fps < 0.0 ) { //Error( "Negative FPS %f, time_diff = %lf (%d:%ld.%ld - %d:%ld.%ld), ibc: %d", curr_fps, time_diff, index2, time2.tv_sec, time2.tv_usec, index1, time1.tv_sec, time1.tv_usec, image_buffer_count ); return( 0.0 ); } return( curr_fps ); } -useconds_t Monitor::GetAnalysisRate() -{ +useconds_t Monitor::GetAnalysisRate() { double capturing_fps = GetFPS(); - if ( !analysis_fps ) - { + if ( !analysis_fps ) { return( 0 ); - } - else if ( analysis_fps > capturing_fps ) - { + } else if ( analysis_fps > capturing_fps ) { Warning( "Analysis fps (%.2f) is greater than capturing fps (%.2f)", analysis_fps, capturing_fps ); return( 0 ); - } - else - { + } else { return( ( 1000000 / analysis_fps ) - ( 1000000 / capturing_fps ) ); } } -void Monitor::UpdateAdaptiveSkip() -{ - if ( config.opt_adaptive_skip ) - { +void Monitor::UpdateAdaptiveSkip() { + if ( config.opt_adaptive_skip ) { double capturing_fps = GetFPS(); - if ( adaptive_skip && analysis_fps && ( analysis_fps < capturing_fps ) ) - { + if ( adaptive_skip && analysis_fps && ( analysis_fps < capturing_fps ) ) { Info( "Analysis fps (%.2f) is lower than capturing fps (%.2f), disabling adaptive skip feature", analysis_fps, capturing_fps ); adaptive_skip = false; - } - else if ( !adaptive_skip && ( !analysis_fps || ( analysis_fps >= capturing_fps ) ) ) - { + } else if ( !adaptive_skip && ( !analysis_fps || ( analysis_fps >= capturing_fps ) ) ) { Info( "Enabling adaptive skip feature" ); adaptive_skip = true; } - } - else - { + } else { adaptive_skip = false; } } -void Monitor::ForceAlarmOn( int force_score, const char *force_cause, const char *force_text ) -{ +void Monitor::ForceAlarmOn( int force_score, const char *force_cause, const char *force_text ) { trigger_data->trigger_state = TRIGGER_ON; trigger_data->trigger_score = force_score; strncpy( trigger_data->trigger_cause, force_cause, sizeof(trigger_data->trigger_cause) ); strncpy( trigger_data->trigger_text, force_text, sizeof(trigger_data->trigger_text) ); } -void Monitor::ForceAlarmOff() -{ +void Monitor::ForceAlarmOff() { trigger_data->trigger_state = TRIGGER_OFF; } -void Monitor::CancelForced() -{ +void Monitor::CancelForced() { trigger_data->trigger_state = TRIGGER_CANCEL; } -void Monitor::actionReload() -{ +void Monitor::actionReload() { shared_data->action |= RELOAD; } -void Monitor::actionEnable() -{ +void Monitor::actionEnable() { shared_data->action |= RELOAD; static char sql[ZM_SQL_SML_BUFSIZ]; snprintf( sql, sizeof(sql), "update Monitors set Enabled = 1 where Id = '%d'", id ); - if ( mysql_query( &dbconn, sql ) ) - { + if ( mysql_query( &dbconn, sql ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } } -void Monitor::actionDisable() -{ +void Monitor::actionDisable() { shared_data->action |= RELOAD; static char sql[ZM_SQL_SML_BUFSIZ]; snprintf( sql, sizeof(sql), "update Monitors set Enabled = 0 where Id = '%d'", id ); - if ( mysql_query( &dbconn, sql ) ) - { + if ( mysql_query( &dbconn, sql ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } } -void Monitor::actionSuspend() -{ +void Monitor::actionSuspend() { shared_data->action |= SUSPEND; } -void Monitor::actionResume() -{ +void Monitor::actionResume() { shared_data->action |= RESUME; } -int Monitor::actionBrightness( int p_brightness ) -{ - if ( purpose != CAPTURE ) - { - if ( p_brightness >= 0 ) - { +int Monitor::actionBrightness( int p_brightness ) { + if ( purpose != CAPTURE ) { + if ( p_brightness >= 0 ) { shared_data->brightness = p_brightness; shared_data->action |= SET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & SET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & SET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to set brightness" ); return( -1 ); } } - } - else - { + } else { shared_data->action |= GET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & GET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & GET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to get brightness" ); return( -1 ); } @@ -1000,36 +890,27 @@ int Monitor::actionBrightness( int p_brightness ) return( camera->Brightness( p_brightness ) ); } -int Monitor::actionContrast( int p_contrast ) -{ - if ( purpose != CAPTURE ) - { - if ( p_contrast >= 0 ) - { +int Monitor::actionContrast( int p_contrast ) { + if ( purpose != CAPTURE ) { + if ( p_contrast >= 0 ) { shared_data->contrast = p_contrast; shared_data->action |= SET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & SET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & SET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to set contrast" ); return( -1 ); } } - } - else - { + } else { shared_data->action |= GET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & GET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & GET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to get contrast" ); return( -1 ); } @@ -1040,36 +921,27 @@ int Monitor::actionContrast( int p_contrast ) return( camera->Contrast( p_contrast ) ); } -int Monitor::actionHue( int p_hue ) -{ - if ( purpose != CAPTURE ) - { - if ( p_hue >= 0 ) - { +int Monitor::actionHue( int p_hue ) { + if ( purpose != CAPTURE ) { + if ( p_hue >= 0 ) { shared_data->hue = p_hue; shared_data->action |= SET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & SET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & SET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to set hue" ); return( -1 ); } } - } - else - { + } else { shared_data->action |= GET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & GET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & GET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to get hue" ); return( -1 ); } @@ -1080,36 +952,27 @@ int Monitor::actionHue( int p_hue ) return( camera->Hue( p_hue ) ); } -int Monitor::actionColour( int p_colour ) -{ - if ( purpose != CAPTURE ) - { - if ( p_colour >= 0 ) - { +int Monitor::actionColour( int p_colour ) { + if ( purpose != CAPTURE ) { + if ( p_colour >= 0 ) { shared_data->colour = p_colour; shared_data->action |= SET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & SET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & SET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to set colour" ); return( -1 ); } } - } - else - { + } else { shared_data->action |= GET_SETTINGS; int wait_loops = 10; - while ( shared_data->action & GET_SETTINGS ) - { - if ( wait_loops-- ) + while ( shared_data->action & GET_SETTINGS ) { + if ( wait_loops-- ) { usleep( 100000 ); - else - { + } else { Warning( "Timed out waiting to get colour" ); return( -1 ); } @@ -1120,16 +983,13 @@ int Monitor::actionColour( int p_colour ) return( camera->Colour( p_colour ) ); } -void Monitor::DumpZoneImage( const char *zone_string ) -{ +void Monitor::DumpZoneImage( const char *zone_string ) { int exclude_id = 0; int extra_colour = 0; Polygon extra_zone; - if ( zone_string ) - { - if ( !Zone::ParseZoneString( zone_string, exclude_id, extra_colour, extra_zone ) ) - { + if ( zone_string ) { + if ( !Zone::ParseZoneString( zone_string, exclude_id, extra_colour, extra_zone ) ) { Error( "Failed to parse zone string, ignoring" ); } } @@ -1143,36 +1003,23 @@ void Monitor::DumpZoneImage( const char *zone_string ) zone_image.Colourise(ZM_COLOUR_RGB24, ZM_SUBPIX_ORDER_RGB ); } - for( int i = 0; i < n_zones; i++ ) - { + for( int i = 0; i < n_zones; i++ ) { if ( exclude_id && (!extra_colour || extra_zone.getNumCoords()) && zones[i]->Id() == exclude_id ) continue; Rgb colour; - if ( exclude_id && !extra_zone.getNumCoords() && zones[i]->Id() == exclude_id ) - { + if ( exclude_id && !extra_zone.getNumCoords() && zones[i]->Id() == exclude_id ) { colour = extra_colour; - } - else - { - if ( zones[i]->IsActive() ) - { + } else { + if ( zones[i]->IsActive() ) { colour = RGB_RED; - } - else if ( zones[i]->IsInclusive() ) - { + } else if ( zones[i]->IsInclusive() ) { colour = RGB_ORANGE; - } - else if ( zones[i]->IsExclusive() ) - { + } else if ( zones[i]->IsExclusive() ) { colour = RGB_PURPLE; - } - else if ( zones[i]->IsPreclusive() ) - { + } else if ( zones[i]->IsPreclusive() ) { colour = RGB_BLUE; - } - else - { + } else { colour = RGB_WHITE; } } @@ -1180,8 +1027,7 @@ void Monitor::DumpZoneImage( const char *zone_string ) zone_image.Outline( colour, zones[i]->GetPolygon() ); } - if ( extra_zone.getNumCoords() ) - { + if ( extra_zone.getNumCoords() ) { zone_image.Fill( extra_colour, 2, extra_zone ); zone_image.Outline( extra_colour, extra_zone ); } @@ -1191,10 +1037,8 @@ void Monitor::DumpZoneImage( const char *zone_string ) zone_image.WriteJpeg( filename ); } -void Monitor::DumpImage( Image *dump_image ) const -{ - if ( image_count && !(image_count%10) ) - { +void Monitor::DumpImage( Image *dump_image ) const { + if ( image_count && !(image_count%10) ) { static char filename[PATH_MAX]; static char new_filename[PATH_MAX]; snprintf( filename, sizeof(filename), "Monitor%d.jpg", id ); @@ -1204,8 +1048,7 @@ void Monitor::DumpImage( Image *dump_image ) const } } -bool Monitor::CheckSignal( const Image *image ) -{ +bool Monitor::CheckSignal( const Image *image ) { static bool static_undef = true; /* RGB24 colors */ static uint8_t red_val; @@ -1215,10 +1058,8 @@ bool Monitor::CheckSignal( const Image *image ) static Rgb colour_val; /* RGB32 color */ static int usedsubpixorder; - if ( config.signal_check_points > 0 ) - { - if ( static_undef ) - { + if ( config.signal_check_points > 0 ) { + if ( static_undef ) { static_undef = false; usedsubpixorder = camera->SubpixelOrder(); colour_val = rgb_convert(signal_check_colour, ZM_SUBPIX_ORDER_BGR); /* HTML colour code is actually BGR in memory, we want RGB */ @@ -1235,10 +1076,8 @@ bool Monitor::CheckSignal( const Image *image ) int colours = image->Colours(); int index = 0; - for ( int i = 0; i < config.signal_check_points; i++ ) - { - while( true ) - { + for ( int i = 0; i < config.signal_check_points; i++ ) { + while( true ) { index = (int)(((long long)rand()*(long long)(pixels-1))/RAND_MAX); if ( !config.timestamp_on_capture || !label_format[0] ) break; @@ -1247,32 +1086,32 @@ bool Monitor::CheckSignal( const Image *image ) break; } - if(colours == ZM_COLOUR_GRAY8) { - if ( *(buffer+index) != grayscale_val ) - return true; - - } else if(colours == ZM_COLOUR_RGB24) { - const uint8_t *ptr = buffer+(index*colours); - - 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) ) - return true; - } else { - /* Assume RGB */ - if ( (RED_PTR_RGBA(ptr) != red_val) || (GREEN_PTR_RGBA(ptr) != green_val) || (BLUE_PTR_RGBA(ptr) != blue_val) ) - return true; - } - - } else if(colours == ZM_COLOUR_RGB32) { - if ( usedsubpixorder == ZM_SUBPIX_ORDER_ARGB || usedsubpixorder == ZM_SUBPIX_ORDER_ABGR) { - if ( ARGB_ABGR_ZEROALPHA(*(((const Rgb*)buffer)+index)) != ARGB_ABGR_ZEROALPHA(colour_val) ) - return true; - } else { - /* Assume RGBA or BGRA */ - if ( RGBA_BGRA_ZEROALPHA(*(((const Rgb*)buffer)+index)) != RGBA_BGRA_ZEROALPHA(colour_val) ) - return true; - } - } + if(colours == ZM_COLOUR_GRAY8) { + if ( *(buffer+index) != grayscale_val ) + return true; + + } else if(colours == ZM_COLOUR_RGB24) { + const uint8_t *ptr = buffer+(index*colours); + + 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) ) + return true; + } else { + /* Assume RGB */ + if ( (RED_PTR_RGBA(ptr) != red_val) || (GREEN_PTR_RGBA(ptr) != green_val) || (BLUE_PTR_RGBA(ptr) != blue_val) ) + return true; + } + + } else if(colours == ZM_COLOUR_RGB32) { + if ( usedsubpixorder == ZM_SUBPIX_ORDER_ARGB || usedsubpixorder == ZM_SUBPIX_ORDER_ABGR) { + if ( ARGB_ABGR_ZEROALPHA(*(((const Rgb*)buffer)+index)) != ARGB_ABGR_ZEROALPHA(colour_val) ) + return true; + } else { + /* Assume RGBA or BGRA */ + if ( RGBA_BGRA_ZEROALPHA(*(((const Rgb*)buffer)+index)) != RGBA_BGRA_ZEROALPHA(colour_val) ) + return true; + } + } } return( false ); @@ -1280,32 +1119,27 @@ bool Monitor::CheckSignal( const Image *image ) return( true ); } -bool Monitor::Analyse() -{ - if ( shared_data->last_read_index == shared_data->last_write_index ) - { +bool Monitor::Analyse() { + if ( shared_data->last_read_index == shared_data->last_write_index ) { return( false ); } struct timeval now; gettimeofday( &now, NULL ); - if ( image_count && fps_report_interval && !(image_count%fps_report_interval) ) - { + if ( image_count && fps_report_interval && !(image_count%fps_report_interval) ) { fps = double(fps_report_interval)/(now.tv_sec-last_fps_time); Info( "%s: %d - Analysing at %.2f fps", name, image_count, fps ); last_fps_time = now.tv_sec; } int index; - if ( adaptive_skip ) - { + if ( adaptive_skip ) { int read_margin = shared_data->last_read_index - shared_data->last_write_index; if ( read_margin < 0 ) read_margin += image_buffer_count; int step = 1; - if ( read_margin > 0 ) - { + if ( read_margin > 0 ) { step = (9*image_buffer_count)/(5*read_margin); } @@ -1313,21 +1147,15 @@ bool Monitor::Analyse() if ( pending_frames < 0 ) pending_frames += image_buffer_count; Debug( 4, "RI:%d, WI: %d, PF = %d, RM = %d, Step = %d", shared_data->last_read_index, shared_data->last_write_index, pending_frames, read_margin, step ); - if ( step <= pending_frames ) - { + if ( step <= pending_frames ) { index = (shared_data->last_read_index+step)%image_buffer_count; - } - else - { - if ( pending_frames ) - { + } else { + if ( pending_frames ) { Warning( "Approaching buffer overrun, consider slowing capture, simplifying analysis or increasing ring buffer size" ); } index = shared_data->last_write_index%image_buffer_count; } - } - else - { + } else { index = shared_data->last_write_index%image_buffer_count; } @@ -1335,32 +1163,25 @@ bool Monitor::Analyse() struct timeval *timestamp = snap->timestamp; Image *snap_image = snap->image; - if ( shared_data->action ) - { - if ( shared_data->action & RELOAD ) - { + if ( shared_data->action ) { + if ( shared_data->action & RELOAD ) { Info( "Received reload indication at count %d", image_count ); shared_data->action &= ~RELOAD; Reload(); } - if ( shared_data->action & SUSPEND ) - { - if ( Active() ) - { + if ( shared_data->action & SUSPEND ) { + if ( Active() ) { Info( "Received suspend indication at count %d", image_count ); shared_data->active = false; //closeEvent(); } - if ( config.max_suspend_time ) - { + if ( config.max_suspend_time ) { auto_resume_time = now.tv_sec + config.max_suspend_time; } shared_data->action &= ~SUSPEND; } - if ( shared_data->action & RESUME ) - { - if ( Enabled() && !Active() ) - { + if ( shared_data->action & RESUME ) { + if ( Enabled() && !Active() ) { Info( "Received resume indication at count %d", image_count ); shared_data->active = true; ref_image = *snap_image; @@ -1370,8 +1191,7 @@ bool Monitor::Analyse() shared_data->action &= ~RESUME; } } - if ( auto_resume_time && (now.tv_sec >= auto_resume_time) ) - { + if ( auto_resume_time && (now.tv_sec >= auto_resume_time) ) { Info( "Auto resuming at count %d", image_count ); shared_data->active = true; ref_image = *snap_image; @@ -1383,31 +1203,25 @@ bool Monitor::Analyse() static int last_section_mod = 0; static bool last_signal; - if ( static_undef ) - { + if ( static_undef ) { static_undef = false; timestamps = new struct timeval *[pre_event_count]; images = new Image *[pre_event_count]; last_signal = shared_data->signal; } - if ( Enabled() ) - { + if ( Enabled() ) { bool signal = shared_data->signal; bool signal_change = (signal != last_signal); - if ( trigger_data->trigger_state != TRIGGER_OFF ) - { + if ( trigger_data->trigger_state != TRIGGER_OFF ) { unsigned int score = 0; - if ( Ready() ) - { + if ( Ready() ) { std::string cause; Event::StringSetMap noteSetMap; - if ( trigger_data->trigger_state == TRIGGER_ON ) - { + if ( trigger_data->trigger_state == TRIGGER_ON ) { score += trigger_data->trigger_score; - if ( !event ) - { + if ( !event ) { if ( cause.length() ) cause += ", "; cause += trigger_data->trigger_cause; @@ -1416,25 +1230,21 @@ bool Monitor::Analyse() noteSet.insert( trigger_data->trigger_text ); noteSetMap[trigger_data->trigger_cause] = noteSet; } - if ( signal_change ) - { + if ( signal_change ) { const char *signalText; if ( !signal ) signalText = "Lost"; - else - { + else { signalText = "Reacquired"; score += 100; } Warning( "%s: %s", SIGNAL_CAUSE, signalText ); - if ( event && !signal ) - { + if ( event && !signal ) { Info( "%s: %03d - Closing event %d, signal loss", name, image_count, event->Id() ); closeEvent(); last_section_mod = 0; } - if ( !event ) - { + if ( !event ) { if ( cause.length() ) cause += ", "; cause += SIGNAL_CAUSE; @@ -1445,28 +1255,21 @@ bool Monitor::Analyse() shared_data->state = state = IDLE; shared_data->active = signal; ref_image = *snap_image; - } - else if ( signal && Active() && (function == MODECT || function == MOCORD) ) - { + } else if ( signal && Active() && (function == MODECT || function == MOCORD) ) { Event::StringSet zoneSet; int motion_score = last_motion_score; - if ( !(image_count % (motion_frame_skip+1) ) ) - { + if ( !(image_count % (motion_frame_skip+1) ) ) { // Get new score. motion_score = last_motion_score = DetectMotion( *snap_image, zoneSet ); } //int motion_score = DetectBlack( *snap_image, zoneSet ); - if ( motion_score ) - { - if ( !event ) - { + if ( motion_score ) { + if ( !event ) { score += motion_score; if ( cause.length() ) cause += ", "; cause += MOTION_CAUSE; - } - else - { + } else { score += motion_score; } noteSetMap[MOTION_CAUSE] = zoneSet; @@ -1474,20 +1277,14 @@ bool Monitor::Analyse() } shared_data->active = signal; } - if ( (!signal_change && signal) && n_linked_monitors > 0 ) - { + if ( (!signal_change && signal) && n_linked_monitors > 0 ) { bool first_link = true; Event::StringSet noteSet; - for ( int i = 0; i < n_linked_monitors; i++ ) - { - if ( linked_monitors[i]->isConnected() ) - { - if ( linked_monitors[i]->hasAlarmed() ) - { - if ( !event ) - { - if ( first_link ) - { + for ( int i = 0; i < n_linked_monitors; i++ ) { + if ( linked_monitors[i]->isConnected() ) { + if ( linked_monitors[i]->hasAlarmed() ) { + if ( !event ) { + if ( first_link ) { if ( cause.length() ) cause += ", "; cause += LINKED_CAUSE; @@ -1497,42 +1294,31 @@ bool Monitor::Analyse() noteSet.insert( linked_monitors[i]->Name() ); score += 50; } - } - else - { + } else { linked_monitors[i]->connect(); } } if ( noteSet.size() > 0 ) noteSetMap[LINKED_CAUSE] = noteSet; } - if ( (!signal_change && signal) && (function == RECORD || function == MOCORD) ) - { - if ( event ) - { + if ( (!signal_change && signal) && (function == RECORD || function == MOCORD) ) { + if ( event ) { int section_mod = timestamp->tv_sec%section_length; - if ( section_mod < last_section_mod ) - { - if ( state == IDLE || state == TAPE || event_close_mode == CLOSE_TIME ) - { - if ( state == TAPE ) - { + if ( section_mod < last_section_mod ) { + if ( state == IDLE || state == TAPE || event_close_mode == CLOSE_TIME ) { + if ( state == TAPE ) { shared_data->state = state = IDLE; Info( "%s: %03d - Closing event %d, section end", name, image_count, event->Id() ) - } - else + } else Info( "%s: %03d - Closing event %d, section end forced ", name, image_count, event->Id() ); closeEvent(); last_section_mod = 0; } - } - else - { + } else { last_section_mod = section_mod; } } - if ( !event ) - { + if ( !event ) { // Create event event = new Event( this, *timestamp, "Continuous", noteSetMap ); @@ -1541,102 +1327,84 @@ bool Monitor::Analyse() Info( "%s: %03d - Opening new event %d, section start", name, image_count, event->Id() ); /* To prevent cancelling out an existing alert\prealarm\alarm state */ - if ( state == IDLE ) - { + if ( state == IDLE ) { shared_data->state = state = TAPE; } //if ( config.overlap_timed_events ) - if ( false ) - { + if ( false ) { int pre_index; int pre_event_images = pre_event_count; - if ( analysis_fps ) - { + if ( analysis_fps ) { // If analysis fps is set, // compute the index for pre event images in the dedicated buffer pre_index = image_count%pre_event_buffer_count; // Seek forward the next filled slot in to the buffer (oldest data) // from the current position - while ( pre_event_images && !pre_event_buffer[pre_index].timestamp->tv_sec ) - { + while ( pre_event_images && !pre_event_buffer[pre_index].timestamp->tv_sec ) { pre_index = (pre_index + 1)%pre_event_buffer_count; // Slot is empty, removing image from counter pre_event_images--; } - } - else - { + } else { // If analysis fps is not set (analysis performed at capturing framerate), // compute the index for pre event images in the capturing buffer pre_index = ((index + image_buffer_count) - pre_event_count)%image_buffer_count; // Seek forward the next filled slot in to the buffer (oldest data) // from the current position - while ( pre_event_images && !image_buffer[pre_index].timestamp->tv_sec ) - { + while ( pre_event_images && !image_buffer[pre_index].timestamp->tv_sec ) { pre_index = (pre_index + 1)%image_buffer_count; // Slot is empty, removing image from counter pre_event_images--; } } - if ( pre_event_images ) - { - if ( analysis_fps ) - for ( int i = 0; i < pre_event_images; i++ ) - { + if ( pre_event_images ) { + if ( analysis_fps ) { + for ( int i = 0; i < pre_event_images; i++ ) { timestamps[i] = pre_event_buffer[pre_index].timestamp; images[i] = pre_event_buffer[pre_index].image; pre_index = (pre_index + 1)%pre_event_buffer_count; } - else - for ( int i = 0; i < pre_event_images; i++ ) - { + } else { + for ( int i = 0; i < pre_event_images; i++ ) { timestamps[i] = image_buffer[pre_index].timestamp; images[i] = image_buffer[pre_index].image; pre_index = (pre_index + 1)%image_buffer_count; } - + } event->AddFrames( pre_event_images, images, timestamps ); } } - } + } // end if ! event } - if ( score ) - { - if ( (state == IDLE || state == TAPE || state == PREALARM ) ) - { - if ( Event::PreAlarmCount() >= (alarm_frame_count-1) ) - { + if ( score ) { + if ( (state == IDLE || state == TAPE || state == PREALARM ) ) { + if ( Event::PreAlarmCount() >= (alarm_frame_count-1) ) { Info( "%s: %03d - Gone into alarm state", name, image_count ); shared_data->state = state = ALARM; - if ( signal_change || (function != MOCORD && state != ALERT) ) - { + if ( signal_change || (function != MOCORD && state != ALERT) ) { int pre_index; int pre_event_images = pre_event_count; - if ( analysis_fps ) - { + if ( analysis_fps ) { // If analysis fps is set, // compute the index for pre event images in the dedicated buffer pre_index = image_count%pre_event_buffer_count; // Seek forward the next filled slot in to the buffer (oldest data) // from the current position - while ( pre_event_images && !pre_event_buffer[pre_index].timestamp->tv_sec ) - { + while ( pre_event_images && !pre_event_buffer[pre_index].timestamp->tv_sec ) { pre_index = (pre_index + 1)%pre_event_buffer_count; // Slot is empty, removing image from counter pre_event_images--; } event = new Event( this, *(pre_event_buffer[pre_index].timestamp), cause, noteSetMap ); - } - else - { + } else { // If analysis fps is not set (analysis performed at capturing framerate), // compute the index for pre event images in the capturing buffer if ( alarm_frame_count > 1 ) @@ -1646,8 +1414,7 @@ bool Monitor::Analyse() // Seek forward the next filled slot in to the buffer (oldest data) // from the current position - while ( pre_event_images && !image_buffer[pre_index].timestamp->tv_sec ) - { + while ( pre_event_images && !image_buffer[pre_index].timestamp->tv_sec ) { pre_index = (pre_index + 1)%image_buffer_count; // Slot is empty, removing image from counter pre_event_images--; @@ -1659,18 +1426,15 @@ bool Monitor::Analyse() Info( "%s: %03d - Opening new event %d, alarm start", name, image_count, event->Id() ); - if ( pre_event_images ) - { - if ( analysis_fps ) - for ( int i = 0; i < pre_event_images; i++ ) - { + if ( pre_event_images ) { + if ( analysis_fps ) { + for ( int i = 0; i < pre_event_images; i++ ) { timestamps[i] = pre_event_buffer[pre_index].timestamp; images[i] = pre_event_buffer[pre_index].image; pre_index = (pre_index + 1)%pre_event_buffer_count; } - else - for ( int i = 0; i < pre_event_images; i++ ) - { + } else { + for ( int i = 0; i < pre_event_images; i++ ) { timestamps[i] = image_buffer[pre_index].timestamp; images[i] = image_buffer[pre_index].image; pre_index = (pre_index + 1)%image_buffer_count; @@ -1678,110 +1442,77 @@ bool Monitor::Analyse() event->AddFrames( pre_event_images, images, timestamps ); } - if ( alarm_frame_count ) - { + if ( alarm_frame_count ) { event->SavePreAlarmFrames(); } } - } - else if ( state != PREALARM ) - { + } else if ( state != PREALARM ) { Info( "%s: %03d - Gone into prealarm state", name, image_count ); shared_data->state = state = PREALARM; } - } - else if ( state == ALERT ) - { + } else if ( state == ALERT ) { Info( "%s: %03d - Gone back into alarm state", name, image_count ); shared_data->state = state = ALARM; } last_alarm_count = image_count; - } - else - { - if ( state == ALARM ) - { + } else { + if ( state == ALARM ) { Info( "%s: %03d - Gone into alert state", name, image_count ); shared_data->state = state = ALERT; - } - else if ( state == ALERT ) - { - if ( image_count-last_alarm_count > post_event_count ) - { + } else if ( state == ALERT ) { + if ( image_count-last_alarm_count > post_event_count ) { Info( "%s: %03d - Left alarm state (%d) - %d(%d) images", name, image_count, event->Id(), event->Frames(), event->AlarmFrames() ); //if ( function != MOCORD || event_close_mode == CLOSE_ALARM || event->Cause() == SIGNAL_CAUSE ) - if ( function != MOCORD || event_close_mode == CLOSE_ALARM ) - { + if ( function != MOCORD || event_close_mode == CLOSE_ALARM ) { shared_data->state = state = IDLE; Info( "%s: %03d - Closing event %d, alarm end%s", name, image_count, event->Id(), (function==MOCORD)?", section truncated":"" ); closeEvent(); - } - else - { + } else { shared_data->state = state = TAPE; } } } - if ( state == PREALARM ) - { - if ( function != MOCORD ) - { + if ( state == PREALARM ) { + if ( function != MOCORD ) { shared_data->state = state = IDLE; - } - else - { + } else { shared_data->state = state = TAPE; } } if ( Event::PreAlarmCount() ) Event::EmptyPreAlarmFrames(); } - if ( state != IDLE ) - { - if ( state == PREALARM || state == ALARM ) - { - if ( config.create_analysis_images ) - { + if ( state != IDLE ) { + if ( state == PREALARM || state == ALARM ) { + if ( config.create_analysis_images ) { bool got_anal_image = false; alarm_image.Assign( *snap_image ); - for( int i = 0; i < n_zones; i++ ) - { - if ( zones[i]->Alarmed() ) - { - if ( zones[i]->AlarmImage() ) - { + for( int i = 0; i < n_zones; i++ ) { + if ( zones[i]->Alarmed() ) { + if ( zones[i]->AlarmImage() ) { alarm_image.Overlay( *(zones[i]->AlarmImage()) ); got_anal_image = true; } - if ( config.record_event_stats && state == ALARM ) - { + if ( config.record_event_stats && state == ALARM ) { zones[i]->RecordStats( event ); } } } - if ( got_anal_image ) - { + if ( got_anal_image ) { if ( state == PREALARM ) Event::AddPreAlarmFrame( snap_image, *timestamp, score, &alarm_image ); else event->AddFrame( snap_image, *timestamp, score, &alarm_image ); - } - else - { + } else { if ( state == PREALARM ) Event::AddPreAlarmFrame( snap_image, *timestamp, score ); else event->AddFrame( snap_image, *timestamp, score ); } - } - else - { - for( int i = 0; i < n_zones; i++ ) - { - if ( zones[i]->Alarmed() ) - { - if ( config.record_event_stats && state == ALARM ) - { + } else { + for( int i = 0; i < n_zones; i++ ) { + if ( zones[i]->Alarmed() ) { + if ( config.record_event_stats && state == ALARM ) { zones[i]->RecordStats( event ); } } @@ -1793,42 +1524,30 @@ bool Monitor::Analyse() } if ( event && noteSetMap.size() > 0 ) event->updateNotes( noteSetMap ); - } - else if ( state == ALERT ) - { + } else if ( state == ALERT ) { event->AddFrame( snap_image, *timestamp ); if ( noteSetMap.size() > 0 ) event->updateNotes( noteSetMap ); - } - else if ( state == TAPE ) - { - if ( !(image_count%(frame_skip+1)) ) - { - if ( config.bulk_frame_interval > 1 ) - { + } else if ( state == TAPE ) { + if ( !(image_count%(frame_skip+1)) ) { + if ( config.bulk_frame_interval > 1 ) { event->AddFrame( snap_image, *timestamp, (event->Frames()AddFrame( snap_image, *timestamp ); } } } - } + } // end if ! IDLE } - } - else - { - if ( event ) - { + } else { + if ( event ) { Info( "%s: %03d - Closing event %d, trigger off", name, image_count, event->Id() ); closeEvent(); } shared_data->state = state = IDLE; last_section_mod = 0; } - if ( (!signal_change && signal) && (function == MODECT || function == MOCORD) ) - { + if ( (!signal_change && signal) && (function == MODECT || function == MOCORD) ) { if ( state == ALARM ) { ref_image.Blend( *snap_image, alarm_ref_blend_perc ); } else { @@ -1842,8 +1561,7 @@ bool Monitor::Analyse() //shared_data->last_read_time = image_buffer[index].timestamp->tv_sec; shared_data->last_read_time = now.tv_sec; - if ( analysis_fps ) - { + if ( analysis_fps ) { // If analysis fps is set, add analysed image to dedicated pre event buffer int pre_index = image_count%pre_event_buffer_count; pre_event_buffer[pre_index].image->Assign(*snap->image); @@ -1855,8 +1573,7 @@ bool Monitor::Analyse() return( true ); } -void Monitor::Reload() -{ +void Monitor::Reload() { Debug( 1, "Reloading monitor %s", name ); if ( event ) @@ -1867,27 +1584,23 @@ void Monitor::Reload() static char sql[ZM_SQL_MED_BUFSIZ]; snprintf( sql, sizeof(sql), "select Function+0, Enabled, LinkedMonitors, EventPrefix, LabelFormat, LabelX, LabelY, LabelSize, WarmupCount, PreEventCount, PostEventCount, AlarmFrameCount, SectionLength, FrameSkip, MotionFrameSkip, AnalysisFPS, AnalysisUpdateDelay, MaxFPS, AlarmMaxFPS, FPSReportInterval, RefBlendPerc, AlarmRefBlendPerc, TrackMotion, SignalCheckColour from Monitors where Id = '%d'", id ); - if ( mysql_query( &dbconn, sql ) ) - { + if ( mysql_query( &dbconn, sql ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } MYSQL_RES *result = mysql_store_result( &dbconn ); - if ( !result ) - { + if ( !result ) { Error( "Can't use query result: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } int n_monitors = mysql_num_rows( result ); - if ( n_monitors != 1 ) - { + if ( n_monitors != 1 ) { Error( "Bogus number of monitors, %d, returned. Can't reload", n_monitors ); return; } - if ( MYSQL_ROW dbrow = mysql_fetch_row( result ) ) - { + if ( MYSQL_ROW dbrow = mysql_fetch_row( result ) ) { int index = 0; function = (Function)atoi(dbrow[index++]); enabled = atoi(dbrow[index++]); @@ -1927,8 +1640,7 @@ void Monitor::Reload() ReloadLinkedMonitors( p_linked_monitors ); } - if ( mysql_errno( &dbconn ) ) - { + if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } @@ -1937,11 +1649,9 @@ void Monitor::Reload() ReloadZones(); } -void Monitor::ReloadZones() -{ +void Monitor::ReloadZones() { Debug( 1, "Reloading zones for monitor %s", name ); - for( int i = 0; i < n_zones; i++ ) - { + for( int i = 0; i < n_zones; i++ ) { delete zones[i]; } delete[] zones; @@ -1950,13 +1660,10 @@ void Monitor::ReloadZones() //DumpZoneImage(); } -void Monitor::ReloadLinkedMonitors( const char *p_linked_monitors ) -{ +void Monitor::ReloadLinkedMonitors( const char *p_linked_monitors ) { Debug( 1, "Reloading linked monitors for monitor %s, '%s'", name, p_linked_monitors ); - if ( n_linked_monitors ) - { - for( int i = 0; i < n_linked_monitors; i++ ) - { + if ( n_linked_monitors ) { + for( int i = 0; i < n_linked_monitors; i++ ) { delete linked_monitors[i]; } delete[] linked_monitors; @@ -1964,44 +1671,34 @@ void Monitor::ReloadLinkedMonitors( const char *p_linked_monitors ) } n_linked_monitors = 0; - if ( p_linked_monitors ) - { + if ( p_linked_monitors ) { int n_link_ids = 0; unsigned int link_ids[256]; char link_id_str[8]; char *dest_ptr = link_id_str; const char *src_ptr = p_linked_monitors; - while( 1 ) - { + while( 1 ) { dest_ptr = link_id_str; - while( *src_ptr >= '0' && *src_ptr <= '9' ) - { - if ( (dest_ptr-link_id_str) < (unsigned int)(sizeof(link_id_str)-1) ) - { + while( *src_ptr >= '0' && *src_ptr <= '9' ) { + if ( (dest_ptr-link_id_str) < (unsigned int)(sizeof(link_id_str)-1) ) { *dest_ptr++ = *src_ptr++; - } - else - { + } else { break; } } // Add the link monitor - if ( dest_ptr != link_id_str ) - { + if ( dest_ptr != link_id_str ) { *dest_ptr = '\0'; unsigned int link_id = atoi(link_id_str); - if ( link_id > 0 && link_id != id) - { + if ( link_id > 0 && link_id != id) { Debug( 3, "Found linked monitor id %d", link_id ); int j; - for ( j = 0; j < n_link_ids; j++ ) - { + for ( j = 0; j < n_link_ids; j++ ) { if ( link_ids[j] == link_id ) break; } - if ( j == n_link_ids ) // Not already found - { + if ( j == n_link_ids ) { // Not already found link_ids[n_link_ids++] = link_id; } } @@ -2013,38 +1710,31 @@ void Monitor::ReloadLinkedMonitors( const char *p_linked_monitors ) if ( !*src_ptr ) break; } - if ( n_link_ids > 0 ) - { + if ( n_link_ids > 0 ) { Debug( 1, "Linking to %d monitors", n_link_ids ); linked_monitors = new MonitorLink *[n_link_ids]; int count = 0; - for ( int i = 0; i < n_link_ids; i++ ) - { + for ( int i = 0; i < n_link_ids; i++ ) { Debug( 1, "Checking linked monitor %d", link_ids[i] ); static char sql[ZM_SQL_SML_BUFSIZ]; snprintf( sql, sizeof(sql), "select Id, Name from Monitors where Id = %d and Function != 'None' and Function != 'Monitor' and Enabled = 1", link_ids[i] ); - if ( mysql_query( &dbconn, sql ) ) - { + if ( mysql_query( &dbconn, sql ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } MYSQL_RES *result = mysql_store_result( &dbconn ); - if ( !result ) - { + if ( !result ) { Error( "Can't use query result: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } int n_monitors = mysql_num_rows( result ); - if ( n_monitors == 1 ) - { + if ( n_monitors == 1 ) { MYSQL_ROW dbrow = mysql_fetch_row( result ); Debug( 1, "Linking to monitor %d", link_ids[i] ); linked_monitors[count++] = new MonitorLink( link_ids[i], dbrow[1] ); - } - else - { + } else { Warning( "Can't link to monitor %d, invalid id, function or not enabled", link_ids[i] ); } mysql_free_result( result ); @@ -2055,8 +1745,7 @@ void Monitor::ReloadLinkedMonitors( const char *p_linked_monitors ) } #if ZM_HAS_V4L -int Monitor::LoadLocalMonitors( const char *device, Monitor **&monitors, Purpose purpose ) -{ +int Monitor::LoadLocalMonitors( const char *device, Monitor **&monitors, Purpose purpose ) { std::string sql = "select Id, Name, ServerId, Function+0, Enabled, LinkedMonitors, Device, Channel, Format, V4LMultiBuffer, V4LCapturesPerFrame, Method, Width, Height, Colours, Palette, Orientation+0, Deinterlacing, Brightness, Contrast, Hue, Colour, EventPrefix, LabelFormat, LabelX, LabelY, LabelSize, ImageBufferCount, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, SectionLength, FrameSkip, MotionFrameSkip, AnalysisFPS, AnalysisUpdateDelay, MaxFPS, AlarmMaxFPS, FPSReportInterval, RefBlendPerc, AlarmRefBlendPerc, TrackMotion, SignalCheckColour, Exif from Monitors where Function != 'None' and Type = 'Local'"; if ( device[0] ) { sql += " AND Device='"; @@ -2077,8 +1766,7 @@ int Monitor::LoadLocalMonitors( const char *device, Monitor **&monitors, Purpose Debug( 1, "Got %d monitors", n_monitors ); delete[] monitors; monitors = new Monitor *[n_monitors]; - for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) - { + for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { int col = 0; int id = atoi(dbrow[col]); col++; @@ -2220,8 +1908,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); monitors[i]->AddPrivacyBitmask( zones ); Debug( 1, "Loaded monitor %d(%s), %d zones", id, name, n_zones ); } - if ( mysql_errno( &dbconn ) ) - { + if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } @@ -2232,8 +1919,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); } #endif // ZM_HAS_V4L -int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const char *port, const char *path, Monitor **&monitors, Purpose purpose ) -{ +int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const char *port, const char *path, Monitor **&monitors, Purpose purpose ) { std::string sql = "select Id, Name, ServerId, Function+0, Enabled, LinkedMonitors, Protocol, Method, Host, Port, Path, Width, Height, Colours, Palette, Orientation+0, Deinterlacing, RTSPDescribe, Brightness, Contrast, Hue, Colour, EventPrefix, LabelFormat, LabelX, LabelY, LabelSize, ImageBufferCount, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, SectionLength, FrameSkip, MotionFrameSkip, AnalysisFPS, AnalysisUpdateDelay, MaxFPS, AlarmMaxFPS, FPSReportInterval, RefBlendPerc, AlarmRefBlendPerc, TrackMotion, Exif from Monitors where Function != 'None' and Type = 'Remote'"; if ( staticConfig.SERVER_ID ) { sql += stringtf( " AND ServerId=%d", staticConfig.SERVER_ID ); @@ -2253,8 +1939,7 @@ int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const c Debug( 1, "Got %d monitors", n_monitors ); delete[] monitors; monitors = new Monitor *[n_monitors]; - for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) - { + for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { int col = 0; int id = atoi(dbrow[col]); col++; @@ -2309,8 +1994,7 @@ int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const c bool embed_exif = (*dbrow[col] != '0'); col++; Camera *camera = 0; - if ( protocol == "http" ) - { + if ( protocol == "http" ) { camera = new RemoteCameraHttp( id, method, @@ -2328,8 +2012,7 @@ int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const c ); } #if HAVE_LIBAVFORMAT - else if ( protocol == "rtsp" ) - { + else if ( protocol == "rtsp" ) { camera = new RemoteCameraRtsp( id, method, @@ -2348,8 +2031,7 @@ int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const c ); } #endif // HAVE_LIBAVFORMAT - else - { + else { Fatal( "Unexpected remote camera protocol '%s'", protocol.c_str() ); } @@ -2397,8 +2079,7 @@ int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const c monitors[i]->AddPrivacyBitmask( zones ); Debug( 1, "Loaded monitor %d(%s), %d zones", id, name.c_str(), n_zones ); } - if ( mysql_errno( &dbconn ) ) - { + if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } @@ -2408,8 +2089,7 @@ int Monitor::LoadRemoteMonitors( const char *protocol, const char *host, const c return( n_monitors ); } -int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose purpose ) -{ +int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose purpose ) { std::string sql = "select Id, Name, ServerId, Function+0, Enabled, LinkedMonitors, Path, Width, Height, Colours, Palette, Orientation+0, Deinterlacing, Brightness, Contrast, Hue, Colour, EventPrefix, LabelFormat, LabelX, LabelY, LabelSize, ImageBufferCount, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, SectionLength, FrameSkip, MotionFrameSkip, AnalysisFPS, AnalysisUpdateDelay, MaxFPS, AlarmMaxFPS, FPSReportInterval, RefBlendPerc, AlarmRefBlendPerc, TrackMotion, Exif from Monitors where Function != 'None' and Type = 'File'"; if ( file[0] ) { sql += " AND Path='"; @@ -2421,8 +2101,7 @@ int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose pu } Debug( 1, "Loading File Monitors with %s", sql.c_str() ); MYSQL_RES *result = zmDbFetch( sql.c_str() ); - if ( !result ) - { + if ( !result ) { Error( "Can't use query result: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } @@ -2430,8 +2109,7 @@ int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose pu Debug( 1, "Got %d monitors", n_monitors ); delete[] monitors; monitors = new Monitor *[n_monitors]; - for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) - { + for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { int col = 0; int id = atoi(dbrow[col]); col++; @@ -2536,8 +2214,7 @@ int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose pu monitors[i]->AddPrivacyBitmask( zones ); Debug( 1, "Loaded monitor %d(%s), %d zones", id, name, n_zones ); } - if ( mysql_errno( &dbconn ) ) - { + if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } @@ -2548,8 +2225,7 @@ int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose pu } #if HAVE_LIBAVFORMAT -int Monitor::LoadFfmpegMonitors( const char *file, Monitor **&monitors, Purpose purpose ) -{ +int Monitor::LoadFfmpegMonitors( const char *file, Monitor **&monitors, Purpose purpose ) { std::string sql = "select Id, Name, ServerId, Function+0, Enabled, LinkedMonitors, Path, Method, Options, Width, Height, Colours, Palette, Orientation+0, Deinterlacing, Brightness, Contrast, Hue, Colour, EventPrefix, LabelFormat, LabelX, LabelY, LabelSize, ImageBufferCount, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, SectionLength, FrameSkip, MotionFrameSkip, AnalysisFPS, AnalysisUpdateDelay, MaxFPS, AlarmMaxFPS, FPSReportInterval, RefBlendPerc, AlarmRefBlendPerc, TrackMotion, Exif from Monitors where Function != 'None' and Type = 'Ffmpeg'"; if ( file[0] ) { sql += " AND Path = '"; @@ -2570,8 +2246,7 @@ int Monitor::LoadFfmpegMonitors( const char *file, Monitor **&monitors, Purpose Debug( 1, "Got %d monitors", n_monitors ); delete[] monitors; monitors = new Monitor *[n_monitors]; - for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) - { + for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { int col = 0; int id = atoi(dbrow[col]); col++; @@ -2680,8 +2355,7 @@ int Monitor::LoadFfmpegMonitors( const char *file, Monitor **&monitors, Purpose monitors[i]->AddPrivacyBitmask( zones ); Debug( 1, "Loaded monitor %d(%s), %d zones", id, name, n_zones ); } - if ( mysql_errno( &dbconn ) ) - { + if ( mysql_errno( &dbconn ) ) { Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } @@ -2692,8 +2366,7 @@ int Monitor::LoadFfmpegMonitors( const char *file, Monitor **&monitors, Purpose } #endif // HAVE_LIBAVFORMAT -Monitor *Monitor::Load( unsigned int p_id, bool load_zones, Purpose purpose ) -{ +Monitor *Monitor::Load( unsigned int p_id, bool load_zones, Purpose purpose ) { std::string sql = stringtf( "select Id, Name, ServerId, Type, Function+0, Enabled, LinkedMonitors, Device, Channel, Format, V4LMultiBuffer, V4LCapturesPerFrame, Protocol, Method, Host, Port, Path, Options, User, Pass, Width, Height, Colours, Palette, Orientation+0, Deinterlacing, RTSPDescribe, Brightness, Contrast, Hue, Colour, EventPrefix, LabelFormat, LabelX, LabelY, LabelSize, ImageBufferCount, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, SectionLength, FrameSkip, MotionFrameSkip, AnalysisFPS, AnalysisUpdateDelay, MaxFPS, AlarmMaxFPS, FPSReportInterval, RefBlendPerc, AlarmRefBlendPerc, TrackMotion, SignalCheckColour, Exif from Monitors where Id = %d", p_id ); MYSQL_ROW dbrow = zmDbFetchOne( sql.c_str() ); @@ -2792,8 +2465,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); int extras = (deinterlacing>>24)&0xff; Camera *camera = 0; - if ( type == "Local" ) - { + if ( type == "Local" ) { #if ZM_HAS_V4L camera = new LocalCamera( id, @@ -2817,11 +2489,8 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); #else // ZM_HAS_V4L Fatal( "You must have video4linux libraries and headers installed to use local analog or USB cameras for monitor %d", id ); #endif // ZM_HAS_V4L - } - else if ( type == "Remote" ) - { - if ( protocol == "http" ) - { + } else if ( type == "Remote" ) { + if ( protocol == "http" ) { camera = new RemoteCameraHttp( id, method.c_str(), @@ -2837,9 +2506,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); colour, purpose==CAPTURE ); - } - else if ( protocol == "rtsp" ) - { + } else if ( protocol == "rtsp" ) { #if HAVE_LIBAVFORMAT camera = new RemoteCameraRtsp( id, @@ -2860,14 +2527,10 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); #else // HAVE_LIBAVFORMAT Fatal( "You must have ffmpeg libraries installed to use remote camera protocol '%s' for monitor %d", protocol.c_str(), id ); #endif // HAVE_LIBAVFORMAT - } - else - { + } else { Fatal( "Unexpected remote camera protocol '%s' for monitor %d", protocol.c_str(), id ); } - } - else if ( type == "File" ) - { + } else if ( type == "File" ) { camera = new FileCamera( id, path.c_str(), @@ -2880,9 +2543,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); colour, purpose==CAPTURE ); - } - else if ( type == "Ffmpeg" ) - { + } else if ( type == "Ffmpeg" ) { #if HAVE_LIBAVFORMAT camera = new FfmpegCamera( id, @@ -2901,9 +2562,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); #else // HAVE_LIBAVFORMAT Fatal( "You must have ffmpeg libraries installed to use ffmpeg cameras for monitor %d", id ); #endif // HAVE_LIBAVFORMAT - } - else if (type == "Libvlc") - { + } else if (type == "Libvlc") { #if HAVE_LIBVLC camera = new LibvlcCamera( id, @@ -2922,9 +2581,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); #else // HAVE_LIBVLC Fatal( "You must have vlc libraries installed to use vlc cameras for monitor %d", id ); #endif // HAVE_LIBVLC - } - else if ( type == "cURL" ) - { + } else if ( type == "cURL" ) { #if HAVE_LIBCURL camera = new cURLCamera( id, @@ -2943,9 +2600,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); #else // HAVE_LIBCURL Fatal( "You must have libcurl installed to use ffmpeg cameras for monitor %d", id ); #endif // HAVE_LIBCURL - } - else - { + } else { Fatal( "Bogus monitor type '%s' for monitor %d", type.c_str(), id ); } monitor = new Monitor( @@ -2988,8 +2643,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); ); int n_zones = 0; - if ( load_zones ) - { + if ( load_zones ) { Zone **zones = 0; n_zones = Zone::Load( monitor, zones ); monitor->AddZones( n_zones, zones ); @@ -2999,8 +2653,7 @@ Debug( 1, "Got %d for v4l_captures_per_frame", v4l_captures_per_frame ); return( monitor ); } -int Monitor::Capture() -{ +int Monitor::Capture() { static int FirstCapture = 1; int captureResult; @@ -3026,8 +2679,7 @@ int Monitor::Capture() captureResult = camera->Capture(*capture_image); } - if ( captureResult != 0 ) - { + if ( captureResult != 0 ) { // Unable to capture image for temporary reason // Fake a signal loss image Rgb signalcolor; @@ -3038,8 +2690,7 @@ int Monitor::Capture() captureResult = 1; } - if ( captureResult == 1 ) - { + if ( captureResult == 1 ) { /* Deinterlacing */ if ( (deinterlacing & 0xff) == 1 ) { @@ -3055,10 +2706,8 @@ int Monitor::Capture() } - if ( orientation != ROTATE_0 ) - { - switch ( orientation ) - { + if ( orientation != ROTATE_0 ) { + switch ( orientation ) { case ROTATE_0 : { // No action required @@ -3083,14 +2732,12 @@ int Monitor::Capture() } if ( true ) { - if ( capture_image->Size() > camera->ImageSize() ) - { + if ( capture_image->Size() > camera->ImageSize() ) { Error( "Captured image %d does not match expected size %d check width, height and colour depth",capture_image->Size(),camera->ImageSize() ); return( -1 ); } - if ( ((unsigned int)index == shared_data->last_read_index) && (function > MONITOR) ) - { + if ( ((unsigned int)index == shared_data->last_read_index) && (function > MONITOR) ) { Warning( "Buffer overrun at index %d, image %d, slow down capture, speed up analysis or increase ring buffer size", index, image_count ); time_t now = time(0); double approxFps = double(image_buffer_count)/double(now-image_buffer[index].timestamp->tv_sec); @@ -3106,8 +2753,7 @@ int Monitor::Capture() capture_image->MaskPrivacy( privacy_bitmask ); gettimeofday( image_buffer[index].timestamp, NULL ); - if ( config.timestamp_on_capture ) - { + if ( config.timestamp_on_capture ) { TimestampImage( capture_image, image_buffer[index].timestamp ); } shared_data->signal = CheckSignal(capture_image); @@ -3116,8 +2762,7 @@ int Monitor::Capture() image_count++; - if ( image_count && fps_report_interval && !(image_count%fps_report_interval) ) - { + if ( image_count && fps_report_interval && !(image_count%fps_report_interval) ) { time_t now = image_buffer[index].timestamp->tv_sec; fps = double(fps_report_interval)/(now-last_fps_time); //Info( "%d -> %d -> %d", fps_report_interval, now, last_fps_time ); @@ -3126,16 +2771,14 @@ int Monitor::Capture() last_fps_time = now; } - if ( shared_data->action & GET_SETTINGS ) - { + if ( shared_data->action & GET_SETTINGS ) { shared_data->brightness = camera->Brightness(); shared_data->hue = camera->Hue(); shared_data->colour = camera->Colour(); shared_data->contrast = camera->Contrast(); shared_data->action &= ~GET_SETTINGS; } - if ( shared_data->action & SET_SETTINGS ) - { + if ( shared_data->action & SET_SETTINGS ) { camera->Brightness( shared_data->brightness ); camera->Hue( shared_data->hue ); camera->Colour( shared_data->colour ); @@ -3148,10 +2791,8 @@ int Monitor::Capture() return( -1 ); } -void Monitor::TimestampImage( Image *ts_image, const struct timeval *ts_time ) const -{ - if ( label_format[0] ) - { +void Monitor::TimestampImage( Image *ts_image, const struct timeval *ts_time ) const { + if ( label_format[0] ) { // Expand the strftime macros first char label_time_text[256]; strftime( label_time_text, sizeof(label_time_text), label_format, localtime( &ts_time->tv_sec ) ); @@ -3159,13 +2800,10 @@ void Monitor::TimestampImage( Image *ts_image, const struct timeval *ts_time ) c char label_text[1024]; const char *s_ptr = label_time_text; char *d_ptr = label_text; - while ( *s_ptr && ((d_ptr-label_text) < (unsigned int)sizeof(label_text)) ) - { - if ( *s_ptr == '%' ) - { + while ( *s_ptr && ((d_ptr-label_text) < (unsigned int)sizeof(label_text)) ) { + if ( *s_ptr == '%' ) { bool found_macro = false; - switch ( *(s_ptr+1) ) - { + switch ( *(s_ptr+1) ) { case 'N' : d_ptr += snprintf( d_ptr, sizeof(label_text)-(d_ptr-label_text), "%s", name ); found_macro = true; @@ -3179,8 +2817,7 @@ void Monitor::TimestampImage( Image *ts_image, const struct timeval *ts_time ) c found_macro = true; break; } - if ( found_macro ) - { + if ( found_macro ) { s_ptr += 2; continue; } @@ -3192,12 +2829,9 @@ void Monitor::TimestampImage( Image *ts_image, const struct timeval *ts_time ) c } } -bool Monitor::closeEvent() -{ - if ( event ) - { - if ( function == RECORD || function == MOCORD ) - { +bool Monitor::closeEvent() { + if ( event ) { + if ( function == RECORD || function == MOCORD ) { gettimeofday( &(event->EndTime()), NULL ); } delete event; @@ -3207,18 +2841,15 @@ bool Monitor::closeEvent() return( false ); } -unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &zoneSet ) -{ +unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &zoneSet ) { bool alarm = false; unsigned int score = 0; if ( n_zones <= 0 ) return( alarm ); - if ( config.record_diag_images ) - { + if ( config.record_diag_images ) { static char diag_path[PATH_MAX] = ""; - if ( !diag_path[0] ) - { + if ( !diag_path[0] ) { snprintf( diag_path, sizeof(diag_path), "%s/%d/diag-r.jpg", config.dir_events, id ); } ref_image.WriteJpeg( diag_path ); @@ -3226,25 +2857,21 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z ref_image.Delta( comp_image, &delta_image); - if ( config.record_diag_images ) - { + if ( config.record_diag_images ) { static char diag_path[PATH_MAX] = ""; - if ( !diag_path[0] ) - { + if ( !diag_path[0] ) { snprintf( diag_path, sizeof(diag_path), "%s/%d/diag-d.jpg", config.dir_events, id ); } delta_image.WriteJpeg( diag_path ); } // Blank out all exclusion zones - for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) - { + for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { Zone *zone = zones[n_zone]; // need previous alarmed state for preclusive zone, so don't clear just yet if (!zone->IsPreclusive()) zone->ClearAlarm(); - if ( !zone->IsInactive() ) - { + if ( !zone->IsInactive() ) { continue; } Debug( 3, "Blanking inactive zone %s", zone->Label() ); @@ -3252,18 +2879,15 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z } // Check preclusive zones first - for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) - { + for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { Zone *zone = zones[n_zone]; - if ( !zone->IsPreclusive() ) - { + if ( !zone->IsPreclusive() ) { continue; } int old_zone_score = zone->Score(); bool old_zone_alarmed = zone->Alarmed(); Debug( 3, "Checking preclusive zone %s - old score: %d, state: %s", zone->Label(),old_zone_score, zone->Alarmed()?"alarmed":"quiet" ); - if ( zone->CheckAlarms( &delta_image ) ) - { + if ( zone->CheckAlarms( &delta_image ) ) { alarm = true; score += zone->Score(); zone->SetAlarm(); @@ -3279,7 +2903,7 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z } if (zone->CheckExtendAlarmCount()) { alarm=true; - zone->SetAlarm(); + zone->SetAlarm(); } else { zone->ClearAlarm(); } @@ -3290,33 +2914,25 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z Coord alarm_centre; int top_score = -1; - if ( alarm ) - { + if ( alarm ) { alarm = false; score = 0; - } - else - { + } else { // Find all alarm pixels in active zones - for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) - { + for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { Zone *zone = zones[n_zone]; - if ( !zone->IsActive() || zone->IsPreclusive()) - { + if ( !zone->IsActive() || zone->IsPreclusive()) { continue; } Debug( 3, "Checking active zone %s", zone->Label() ); - if ( zone->CheckAlarms( &delta_image ) ) - { + if ( zone->CheckAlarms( &delta_image ) ) { alarm = true; score += zone->Score(); zone->SetAlarm(); Debug( 3, "Zone is alarmed, zone score = %d", zone->Score() ); zoneSet.insert( zone->Label() ); - if ( config.opt_control && track_motion ) - { - if ( (int)zone->Score() > top_score ) - { + if ( config.opt_control && track_motion ) { + if ( (int)zone->Score() > top_score ) { top_score = zone->Score(); alarm_centre = zone->GetAlarmCentre(); } @@ -3324,47 +2940,36 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z } } - if ( alarm ) - { - for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) - { + if ( alarm ) { + for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { Zone *zone = zones[n_zone]; - if ( !zone->IsInclusive() ) - { + if ( !zone->IsInclusive() ) { continue; } Debug( 3, "Checking inclusive zone %s", zone->Label() ); - if ( zone->CheckAlarms( &delta_image ) ) - { + if ( zone->CheckAlarms( &delta_image ) ) { alarm = true; score += zone->Score(); zone->SetAlarm(); Debug( 3, "Zone is alarmed, zone score = %d", zone->Score() ); zoneSet.insert( zone->Label() ); - if ( config.opt_control && track_motion ) - { - if ( zone->Score() > (unsigned int)top_score ) - { + if ( config.opt_control && track_motion ) { + if ( zone->Score() > (unsigned int)top_score ) { top_score = zone->Score(); alarm_centre = zone->GetAlarmCentre(); } } } } - } - else - { + } else { // Find all alarm pixels in exclusive zones - for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) - { + for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { Zone *zone = zones[n_zone]; - if ( !zone->IsExclusive() ) - { + if ( !zone->IsExclusive() ) { continue; } Debug( 3, "Checking exclusive zone %s", zone->Label() ); - if ( zone->CheckAlarms( &delta_image ) ) - { + if ( zone->CheckAlarms( &delta_image ) ) { alarm = true; score += zone->Score(); zone->SetAlarm(); @@ -3372,18 +2977,15 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z zoneSet.insert( zone->Label() ); } } - } + } // end if alaram or not } - if ( top_score > 0 ) - { + if ( top_score > 0 ) { shared_data->alarm_x = alarm_centre.X(); shared_data->alarm_y = alarm_centre.Y(); Info( "Got alarm centre at %d,%d, at count %d", shared_data->alarm_x, shared_data->alarm_y, image_count ); - } - else - { + } else { shared_data->alarm_x = shared_data->alarm_y = -1; } @@ -3391,44 +2993,36 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z return( score?score:alarm ); } -bool Monitor::DumpSettings( char *output, bool verbose ) -{ +bool Monitor::DumpSettings( char *output, bool verbose ) { output[0] = 0; sprintf( output+strlen(output), "Id : %d\n", id ); sprintf( output+strlen(output), "Name : %s\n", name ); sprintf( output+strlen(output), "Type : %s\n", camera->IsLocal()?"Local":(camera->IsRemote()?"Remote":"File") ); #if ZM_HAS_V4L - if ( camera->IsLocal() ) - { + if ( camera->IsLocal() ) { sprintf( output+strlen(output), "Device : %s\n", ((LocalCamera *)camera)->Device().c_str() ); sprintf( output+strlen(output), "Channel : %d\n", ((LocalCamera *)camera)->Channel() ); sprintf( output+strlen(output), "Standard : %d\n", ((LocalCamera *)camera)->Standard() ); - } - else + } else #endif // ZM_HAS_V4L - if ( camera->IsRemote() ) - { + if ( camera->IsRemote() ) { sprintf( output+strlen(output), "Protocol : %s\n", ((RemoteCamera *)camera)->Protocol().c_str() ); sprintf( output+strlen(output), "Host : %s\n", ((RemoteCamera *)camera)->Host().c_str() ); sprintf( output+strlen(output), "Port : %s\n", ((RemoteCamera *)camera)->Port().c_str() ); sprintf( output+strlen(output), "Path : %s\n", ((RemoteCamera *)camera)->Path().c_str() ); - } - else if ( camera->IsFile() ) - { + } else if ( camera->IsFile() ) { sprintf( output+strlen(output), "Path : %s\n", ((FileCamera *)camera)->Path() ); } #if HAVE_LIBAVFORMAT - else if ( camera->IsFfmpeg() ) - { + else if ( camera->IsFfmpeg() ) { sprintf( output+strlen(output), "Path : %s\n", ((FfmpegCamera *)camera)->Path().c_str() ); } #endif // HAVE_LIBAVFORMAT sprintf( output+strlen(output), "Width : %d\n", camera->Width() ); sprintf( output+strlen(output), "Height : %d\n", camera->Height() ); #if ZM_HAS_V4L - if ( camera->IsLocal() ) - { + if ( camera->IsLocal() ) { sprintf( output+strlen(output), "Palette : %d\n", ((LocalCamera *)camera)->Palette() ); } #endif // ZM_HAS_V4L @@ -3459,78 +3053,61 @@ bool Monitor::DumpSettings( char *output, bool verbose ) function==NODECT?"Externally Triggered only, no Motion Detection":"Unknown" )))))); sprintf( output+strlen(output), "Zones : %d\n", n_zones ); - for ( int i = 0; i < n_zones; i++ ) - { + for ( int i = 0; i < n_zones; i++ ) { zones[i]->DumpSettings( output+strlen(output), verbose ); } return( true ); } -bool MonitorStream::checkSwapPath( const char *path, bool create_path ) -{ +bool MonitorStream::checkSwapPath( const char *path, bool create_path ) { uid_t uid = getuid(); gid_t gid = getgid(); struct stat stat_buf; - if ( stat( path, &stat_buf ) < 0 ) - { - if ( create_path && errno == ENOENT ) - { + if ( stat( path, &stat_buf ) < 0 ) { + if ( create_path && errno == ENOENT ) { Debug( 3, "Swap path '%s' missing, creating", path ); - if ( mkdir( path, 0755 ) ) - { + if ( mkdir( path, 0755 ) ) { Error( "Can't mkdir %s: %s", path, strerror(errno)); return( false ); } - if ( stat( path, &stat_buf ) < 0 ) - { + if ( stat( path, &stat_buf ) < 0 ) { Error( "Can't stat '%s': %s", path, strerror(errno) ); return( false ); } - } - else - { + } else { Error( "Can't stat '%s': %s", path, strerror(errno) ); return( false ); } } - if ( !S_ISDIR(stat_buf.st_mode) ) - { + if ( !S_ISDIR(stat_buf.st_mode) ) { Error( "Swap image path '%s' is not a directory", path ); return( false ); } mode_t mask = 0; - if ( uid == stat_buf.st_uid ) - { + if ( uid == stat_buf.st_uid ) { // If we are the owner mask = 00700; - } - else if ( gid == stat_buf.st_gid ) - { + } else if ( gid == stat_buf.st_gid ) { // If we are in the owner group mask = 00070; - } - else - { + } else { // We are neither the owner nor in the group mask = 00007; } - if ( (stat_buf.st_mode & mask) != mask ) - { + if ( (stat_buf.st_mode & mask) != mask ) { Error( "Insufficient permissions on swap image path '%s'", path ); return( false ); } return( true ); } -void MonitorStream::processCommand( const CmdMsg *msg ) -{ +void MonitorStream::processCommand( const CmdMsg *msg ) { Debug( 2, "Got message, type %d, msg %d", msg->msg_type, msg->msg_data[0] ); // Check for incoming command - switch( (MsgCommand)msg->msg_data[0] ) - { + switch( (MsgCommand)msg->msg_data[0] ) { case CMD_PAUSE : { Debug( 1, "Got PAUSE command" ); @@ -3545,8 +3122,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) case CMD_PLAY : { Debug( 1, "Got PLAY command" ); - if ( paused ) - { + if ( paused ) { // Clear paused flag paused = false; // Set delayed_play flag @@ -3558,8 +3134,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) case CMD_VARPLAY : { Debug( 1, "Got VARPLAY command" ); - if ( paused ) - { + if ( paused ) { // Clear paused flag paused = false; // Set delayed_play flag @@ -3581,8 +3156,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) case CMD_FASTFWD : { Debug( 1, "Got FAST FWD command" ); - if ( paused ) - { + if ( paused ) { // Clear paused flag paused = false; // Set delayed_play flag @@ -3639,16 +3213,14 @@ void MonitorStream::processCommand( const CmdMsg *msg ) case CMD_FASTREV : { Debug( 1, "Got FAST REV command" ); - if ( paused ) - { + if ( paused ) { // Clear paused flag paused = false; // Set delayed_play flag delayed = true; } // Set play rate - switch ( replay_rate ) - { + switch ( replay_rate ) { case -2 * ZM_RATE_BASE : replay_rate = -5 * ZM_RATE_BASE; break; @@ -3673,8 +3245,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) x = ((unsigned char)msg->msg_data[1]<<8)|(unsigned char)msg->msg_data[2]; y = ((unsigned char)msg->msg_data[3]<<8)|(unsigned char)msg->msg_data[4]; Debug( 1, "Got ZOOM IN command, to %d,%d", x, y ); - switch ( zoom ) - { + switch ( zoom ) { case 100: zoom = 150; break; @@ -3697,8 +3268,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) case CMD_ZOOMOUT : { Debug( 1, "Got ZOOM OUT command" ); - switch ( zoom ) - { + switch ( zoom ) { case 500: zoom = 400; break; @@ -3792,8 +3362,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) status_msg.msg_type = MSG_DATA_WATCH; memcpy( &status_msg.msg_data, &status_data, sizeof(status_data) ); int nbytes = 0; - if ( (nbytes = sendto( sd, &status_msg, sizeof(status_msg), MSG_DONTWAIT, (sockaddr *)&rem_addr, sizeof(rem_addr) )) < 0 ) - { + if ( (nbytes = sendto( sd, &status_msg, sizeof(status_msg), MSG_DONTWAIT, (sockaddr *)&rem_addr, sizeof(rem_addr) )) < 0 ) { //if ( errno != EAGAIN ) { Error( "Can't sendto on sd %d: %s", sd, strerror(errno) ); @@ -3808,8 +3377,7 @@ void MonitorStream::processCommand( const CmdMsg *msg ) updateFrameRate( monitor->GetFPS() ); } -bool MonitorStream::sendFrame( const char *filepath, struct timeval *timestamp ) -{ +bool MonitorStream::sendFrame( const char *filepath, struct timeval *timestamp ) { bool send_raw = ((scale>=ZM_SCALE_BASE)&&(zoom==ZM_SCALE_BASE)); if ( type != STREAM_JPEG ) @@ -3817,25 +3385,19 @@ bool MonitorStream::sendFrame( const char *filepath, struct timeval *timestamp ) if ( !config.timestamp_on_capture && timestamp ) send_raw = false; - if ( !send_raw ) - { + if ( !send_raw ) { Image temp_image( filepath ); return( sendFrame( &temp_image, timestamp ) ); - } - else - { + } else { int img_buffer_size = 0; static unsigned char img_buffer[ZM_MAX_IMAGE_SIZE]; FILE *fdj = NULL; - if ( (fdj = fopen( filepath, "r" )) ) - { + if ( (fdj = fopen( filepath, "r" )) ) { img_buffer_size = fread( img_buffer, 1, sizeof(img_buffer), fdj ); fclose( fdj ); - } - else - { + } else { Error( "Can't open %s: %s", filepath, strerror(errno) ); return( false ); } @@ -3847,8 +3409,7 @@ bool MonitorStream::sendFrame( const char *filepath, struct timeval *timestamp ) fprintf( stdout, "--ZoneMinderFrame\r\n" ); fprintf( stdout, "Content-Length: %d\r\n", img_buffer_size ); fprintf( stdout, "Content-Type: image/jpeg\r\n\r\n" ); - if ( fwrite( img_buffer, img_buffer_size, 1, stdout ) != 1 ) - { + if ( fwrite( img_buffer, img_buffer_size, 1, stdout ) != 1 ) { if ( !zm_terminate ) Error( "Unable to send stream frame: %s", strerror(errno) ); return( false ); @@ -3860,8 +3421,7 @@ bool MonitorStream::sendFrame( const char *filepath, struct timeval *timestamp ) gettimeofday( &frameEndTime, NULL ); int frameSendTime = tvDiffMsec( frameStartTime, frameEndTime ); - if ( frameSendTime > 1000/maxfps ) - { + if ( frameSendTime > 1000/maxfps ) { maxfps /= 2; Error( "Frame send time %d msec too slow, throttling maxfps to %.2f", frameSendTime, maxfps ); } @@ -3873,17 +3433,14 @@ bool MonitorStream::sendFrame( const char *filepath, struct timeval *timestamp ) return( false ); } -bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) -{ +bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) { Image *send_image = prepareImage( image ); if ( !config.timestamp_on_capture && timestamp ) monitor->TimestampImage( send_image, timestamp ); #if HAVE_LIBAVCODEC - if ( type == STREAM_MPEG ) - { - if ( !vid_stream ) - { + if ( type == STREAM_MPEG ) { + if ( !vid_stream ) { vid_stream = new VideoStream( "pipe:", format, bitrate, effective_fps, send_image->Colours(), send_image->SubpixelOrder(), send_image->Width(), send_image->Height() ); fprintf( stdout, "Content-type: %s\r\n\r\n", vid_stream->MimeType() ); vid_stream->OpenStream(); @@ -3894,8 +3451,7 @@ bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) base_time = *timestamp; DELTA_TIMEVAL( delta_time, *timestamp, base_time, DT_PREC_3 ); /* double pts = */ vid_stream->EncodeFrame( send_image->Buffer(), send_image->Size(), config.mpeg_timed_frames, delta_time.delta ); - } - else + } else #endif // HAVE_LIBAVCODEC { static unsigned char temp_img_buffer[ZM_MAX_IMAGE_SIZE]; @@ -3908,8 +3464,7 @@ bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) gettimeofday( &frameStartTime, NULL ); fprintf( stdout, "--ZoneMinderFrame\r\n" ); - switch( type ) - { + switch( type ) { case STREAM_JPEG : send_image->EncodeJpeg( img_buffer, &img_buffer_size ); fprintf( stdout, "Content-Type: image/jpeg\r\n" ); @@ -3930,8 +3485,7 @@ bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) break; } fprintf( stdout, "Content-Length: %d\r\n\r\n", img_buffer_size ); - if ( fwrite( img_buffer, img_buffer_size, 1, stdout ) != 1 ) - { + if ( fwrite( img_buffer, img_buffer_size, 1, stdout ) != 1 ) { if ( !zm_terminate ) Error( "Unable to send stream frame: %s", strerror(errno) ); return( false ); @@ -3943,8 +3497,7 @@ bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) gettimeofday( &frameEndTime, NULL ); int frameSendTime = tvDiffMsec( frameStartTime, frameEndTime ); - if ( frameSendTime > 1000/maxfps ) - { + if ( frameSendTime > 1000/maxfps ) { maxfps /= 1.5; Error( "Frame send time %d msec too slow, throttling maxfps to %.2f", frameSendTime, maxfps ); } @@ -3953,10 +3506,8 @@ bool MonitorStream::sendFrame( Image *image, struct timeval *timestamp ) return( true ); } -void MonitorStream::runStream() -{ - if ( type == STREAM_SINGLE ) - { +void MonitorStream::runStream() { + if ( type == STREAM_SINGLE ) { // Not yet migrated over to stream class monitor->SingleImage( scale ); return; @@ -4033,28 +3584,23 @@ void MonitorStream::runStream() } float max_secs_since_last_sent_frame = 10.0; //should be > keep alive amount (5 secs) - while ( !zm_terminate ) - { + while ( !zm_terminate ) { bool got_command = false; - if ( feof( stdout ) || ferror( stdout ) || !monitor->ShmValid() ) - { + if ( feof( stdout ) || ferror( stdout ) || !monitor->ShmValid() ) { break; } gettimeofday( &now, NULL ); - if ( connkey ) - { + if ( connkey ) { while(checkCommandQueue()) { got_command = true; } } //bool frame_sent = false; - if ( buffered_playback && delayed ) - { - if ( temp_read_index == temp_write_index ) - { + if ( buffered_playback && delayed ) { + if ( temp_read_index == temp_write_index ) { // Go back to live viewing Debug( 1, "Exceeded temporary streaming buffer" ); // Clear paused flag @@ -4062,34 +3608,26 @@ void MonitorStream::runStream() // Clear delayed_play flag delayed = false; replay_rate = ZM_RATE_BASE; - } - else - { - if ( !paused ) - { + } else { + if ( !paused ) { int temp_index = MOD_ADD( temp_read_index, 0, temp_image_buffer_count ); //Debug( 3, "tri: %d, ti: %d", temp_read_index, temp_index ); SwapImage *swap_image = &temp_image_buffer[temp_index]; - if ( !swap_image->valid ) - { + if ( !swap_image->valid ) { paused = true; delayed = true; temp_read_index = MOD_ADD( temp_read_index, (replay_rate>=0?-1:1), temp_image_buffer_count ); - } - else - { + } else { //Debug( 3, "siT: %f, lfT: %f", TV_2_FLOAT( swap_image->timestamp ), TV_2_FLOAT( last_frame_timestamp ) ); double expected_delta_time = ((TV_2_FLOAT( swap_image->timestamp ) - TV_2_FLOAT( last_frame_timestamp )) * ZM_RATE_BASE)/replay_rate; double actual_delta_time = TV_2_FLOAT( now ) - last_frame_sent; //Debug( 3, "eDT: %.3lf, aDT: %.3f, lFS:%.3f, NOW:%.3f", expected_delta_time, actual_delta_time, last_frame_sent, TV_2_FLOAT( now ) ); // If the next frame is due - if ( actual_delta_time > expected_delta_time ) - { + if ( actual_delta_time > expected_delta_time ) { //Debug( 2, "eDT: %.3lf, aDT: %.3f", expected_delta_time, actual_delta_time ); - if ( temp_index%frame_mod == 0 ) - { + if ( temp_index%frame_mod == 0 ) { Debug( 2, "Sending delayed frame %d", temp_index ); // Send the next frame if ( !sendFrame( temp_image_buffer[temp_index].file_name, &temp_image_buffer[temp_index].timestamp ) ) @@ -4100,9 +3638,7 @@ void MonitorStream::runStream() temp_read_index = MOD_ADD( temp_read_index, (replay_rate>0?1:-1), temp_image_buffer_count ); } } - } - else if ( step != 0 ) - { + } else if ( step != 0 ) { temp_read_index = MOD_ADD( temp_read_index, (step>0?1:-1), temp_image_buffer_count ); SwapImage *swap_image = &temp_image_buffer[temp_read_index]; @@ -4113,14 +3649,11 @@ void MonitorStream::runStream() memcpy( &last_frame_timestamp, &(swap_image->timestamp), sizeof(last_frame_timestamp) ); //frame_sent = true; step = 0; - } - else - { + } else { int temp_index = MOD_ADD( temp_read_index, 0, temp_image_buffer_count ); double actual_delta_time = TV_2_FLOAT( now ) - last_frame_sent; - if ( got_command || actual_delta_time > 5 ) - { + if ( got_command || actual_delta_time > 5 ) { // Send keepalive Debug( 2, "Sending keepalive frame %d", temp_index ); // Send the next frame @@ -4130,8 +3663,7 @@ void MonitorStream::runStream() } } } - if ( temp_read_index == temp_write_index ) - { + if ( temp_read_index == temp_write_index ) { // Go back to live viewing Warning( "Rewound over write index, resuming live play" ); // Clear paused flag @@ -4141,15 +3673,12 @@ void MonitorStream::runStream() replay_rate = ZM_RATE_BASE; } } - if ( (unsigned int)last_read_index != monitor->shared_data->last_write_index ) - { + if ( (unsigned int)last_read_index != monitor->shared_data->last_write_index ) { int index = monitor->shared_data->last_write_index%monitor->image_buffer_count; last_read_index = monitor->shared_data->last_write_index; //Debug( 1, "%d: %x - %x", index, image_buffer[index].image, image_buffer[index].image->buffer ); - if ( (frame_mod == 1) || ((frame_count%frame_mod) == 0) ) - { - if ( !paused && !delayed ) - { + if ( (frame_mod == 1) || ((frame_count%frame_mod) == 0) ) { + if ( !paused && !delayed ) { // Send the next frame Monitor::Snapshot *snap = &monitor->image_buffer[index]; @@ -4161,24 +3690,19 @@ void MonitorStream::runStream() temp_read_index = temp_write_index; } } - if ( buffered_playback ) - { - if ( monitor->shared_data->valid ) - { - if ( monitor->image_buffer[index].timestamp->tv_sec ) - { + if ( buffered_playback ) { + if ( monitor->shared_data->valid ) { + if ( monitor->image_buffer[index].timestamp->tv_sec ) { int temp_index = temp_write_index%temp_image_buffer_count; Debug( 2, "Storing frame %d", temp_index ); - if ( !temp_image_buffer[temp_index].valid ) - { + if ( !temp_image_buffer[temp_index].valid ) { snprintf( temp_image_buffer[temp_index].file_name, sizeof(temp_image_buffer[0].file_name), "%s/zmswap-i%05d.jpg", swap_path, temp_index ); temp_image_buffer[temp_index].valid = true; } memcpy( &(temp_image_buffer[temp_index].timestamp), monitor->image_buffer[index].timestamp, sizeof(temp_image_buffer[0].timestamp) ); monitor->image_buffer[index].image->WriteJpeg( temp_image_buffer[temp_index].file_name, config.jpeg_file_quality ); temp_write_index = MOD_ADD( temp_write_index, 1, temp_image_buffer_count ); - if ( temp_write_index == temp_read_index ) - { + if ( temp_write_index == temp_read_index ) { // Go back to live viewing Warning( "Exceeded temporary buffer, resuming live play" ); // Clear paused flag @@ -4187,79 +3711,56 @@ void MonitorStream::runStream() delayed = false; replay_rate = ZM_RATE_BASE; } - } - else - { + } else { Warning( "Unable to store frame as timestamp invalid" ); } - } - else - { + } else { Warning( "Unable to store frame as shared memory invalid" ); } } frame_count++; } usleep( (unsigned long)((1000000 * ZM_RATE_BASE)/((base_fps?base_fps:1)*abs(replay_rate*2))) ); - if ( ttl ) - { - if ( (now.tv_sec - stream_start_time) > ttl ) - { + if ( ttl ) { + if ( (now.tv_sec - stream_start_time) > ttl ) { break; } } - if ( (TV_2_FLOAT( now ) - last_frame_sent) > max_secs_since_last_sent_frame ) - { + if ( (TV_2_FLOAT( now ) - last_frame_sent) > max_secs_since_last_sent_frame ) { Error( "Terminating, last frame sent time %f secs more than maximum of %f", TV_2_FLOAT( now ) - last_frame_sent, max_secs_since_last_sent_frame ); break; } } - if ( buffered_playback ) - { + if ( buffered_playback ) { Debug( 1, "Cleaning swap files from %s", swap_path ); struct stat stat_buf; - if ( stat( swap_path, &stat_buf ) < 0 ) - { - if ( errno != ENOENT ) - { + if ( stat( swap_path, &stat_buf ) < 0 ) { + if ( errno != ENOENT ) { Error( "Can't stat '%s': %s", swap_path, strerror(errno) ); } - } - else if ( !S_ISDIR(stat_buf.st_mode) ) - { + } else if ( !S_ISDIR(stat_buf.st_mode) ) { Error( "Swap image path '%s' is not a directory", swap_path ); - } - else - { + } else { char glob_pattern[PATH_MAX] = ""; snprintf( glob_pattern, sizeof(glob_pattern), "%s/*.*", swap_path ); glob_t pglob; int glob_status = glob( glob_pattern, 0, 0, &pglob ); - if ( glob_status != 0 ) - { - if ( glob_status < 0 ) - { + if ( glob_status != 0 ) { + if ( glob_status < 0 ) { Error( "Can't glob '%s': %s", glob_pattern, strerror(errno) ); - } - else - { + } else { Debug( 1, "Can't glob '%s': %d", glob_pattern, glob_status ); } - } - else - { - for ( unsigned int i = 0; i < pglob.gl_pathc; i++ ) - { - if ( unlink( pglob.gl_pathv[i] ) < 0 ) - { + } else { + for ( unsigned int i = 0; i < pglob.gl_pathc; i++ ) { + if ( unlink( pglob.gl_pathv[i] ) < 0 ) { Error( "Can't unlink '%s': %s", pglob.gl_pathv[i], strerror(errno) ); } } } globfree( &pglob ); - if ( rmdir( swap_path ) < 0 ) - { + if ( rmdir( swap_path ) < 0 ) { Error( "Can't rmdir '%s': %s", swap_path, strerror(errno) ); } } @@ -4268,8 +3769,7 @@ void MonitorStream::runStream() closeComms(); } -void Monitor::SingleImage( int scale) -{ +void Monitor::SingleImage( int scale) { int img_buffer_size = 0; static JOCTET img_buffer[ZM_MAX_IMAGE_SIZE]; Image scaled_image; @@ -4277,14 +3777,12 @@ void Monitor::SingleImage( int scale) Snapshot *snap = &image_buffer[index]; Image *snap_image = snap->image; - if ( scale != ZM_SCALE_BASE ) - { + if ( scale != ZM_SCALE_BASE ) { scaled_image.Assign( *snap_image ); scaled_image.Scale( scale ); snap_image = &scaled_image; } - if ( !config.timestamp_on_capture ) - { + if ( !config.timestamp_on_capture ) { TimestampImage( snap_image, snap->timestamp ); } snap_image->EncodeJpeg( img_buffer, &img_buffer_size ); @@ -4294,21 +3792,18 @@ void Monitor::SingleImage( int scale) fwrite( img_buffer, img_buffer_size, 1, stdout ); } -void Monitor::SingleImageRaw( int scale) -{ +void Monitor::SingleImageRaw( int scale) { Image scaled_image; int index = shared_data->last_write_index%image_buffer_count; Snapshot *snap = &image_buffer[index]; Image *snap_image = snap->image; - if ( scale != ZM_SCALE_BASE ) - { + if ( scale != ZM_SCALE_BASE ) { scaled_image.Assign( *snap_image ); scaled_image.Scale( scale ); snap_image = &scaled_image; } - if ( !config.timestamp_on_capture ) - { + if ( !config.timestamp_on_capture ) { TimestampImage( snap_image, snap->timestamp ); } @@ -4317,8 +3812,7 @@ void Monitor::SingleImageRaw( int scale) fwrite( snap_image->Buffer(), snap_image->Size(), 1, stdout ); } -void Monitor::SingleImageZip( int scale) -{ +void Monitor::SingleImageZip( int scale) { unsigned long img_buffer_size = 0; static Bytef img_buffer[ZM_MAX_IMAGE_SIZE]; Image scaled_image; @@ -4326,14 +3820,12 @@ void Monitor::SingleImageZip( int scale) Snapshot *snap = &image_buffer[index]; Image *snap_image = snap->image; - if ( scale != ZM_SCALE_BASE ) - { + if ( scale != ZM_SCALE_BASE ) { scaled_image.Assign( *snap_image ); scaled_image.Scale( scale ); snap_image = &scaled_image; } - if ( !config.timestamp_on_capture ) - { + if ( !config.timestamp_on_capture ) { TimestampImage( snap_image, snap->timestamp ); } snap_image->Zip( img_buffer, &img_buffer_size );