diff --git a/db/triggers.sql b/db/triggers.sql index 2f13be435..fb7a32b67 100644 --- a/db/triggers.sql +++ b/db/triggers.sql @@ -5,7 +5,7 @@ CREATE TRIGGER Events_Hour_delete_trigger BEFORE DELETE ON Events_Hour FOR EACH ROW BEGIN UPDATE Monitors SET HourEvents = COALESCE(HourEvents,1)-1, - HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) + HourEventDiskSpace=GREATEST(COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Id=OLD.MonitorId; END; // @@ -20,23 +20,21 @@ FOR EACH ROW set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); IF ( diff ) THEN IF ( NEW.MonitorID != OLD.MonitorID ) THEN - UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) WHERE Monitors.Id=OLD.MonitorId; - UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)-COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; + UPDATE Monitors SET HourEventDiskSpace=GREATEST(COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; ELSE UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId; END IF; END IF; END; // -DELIMITER ; -delimiter // DROP TRIGGER IF EXISTS Events_Day_delete_trigger// CREATE TRIGGER Events_Day_delete_trigger BEFORE DELETE ON Events_Day FOR EACH ROW BEGIN UPDATE Monitors SET - DayEvents = COALESCE(DayEvents,1)-1, - DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) + DayEvents = GREATEST(COALESCE(DayEvents,1)-1,0), + DayEventDiskSpace=GREATEST(COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Id=OLD.MonitorId; END; // @@ -50,10 +48,10 @@ FOR EACH ROW set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); IF ( diff ) THEN IF ( NEW.MonitorID != OLD.MonitorID ) THEN - UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET DayEventDiskSpace=GREATEST(COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Monitors.Id=OLD.MonitorId; UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; ELSE - UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId; + UPDATE Monitors SET DayEventDiskSpace=GREATEST(COALESCE(DayEventDiskSpace,0)+diff,0) WHERE Monitors.Id=NEW.MonitorId; END IF; END IF; END; @@ -65,7 +63,7 @@ CREATE TRIGGER Events_Week_delete_trigger BEFORE DELETE ON Events_Week FOR EACH ROW BEGIN UPDATE Monitors SET WeekEvents = COALESCE(WeekEvents,1)-1, - WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) + WeekEventDiskSpace=GREATEST(COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Id=OLD.MonitorId; END; // @@ -79,10 +77,10 @@ FOR EACH ROW set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); IF ( diff ) THEN IF ( NEW.MonitorID != OLD.MonitorID ) THEN - UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET WeekEventDiskSpace=GREATEST(COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Monitors.Id=OLD.MonitorId; UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; ELSE - UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId; + UPDATE Monitors SET WeekEventDiskSpace=GREATEST(COALESCE(WeekEventDiskSpace,0)+diff,0) WHERE Monitors.Id=NEW.MonitorId; END IF; END IF; END; @@ -93,7 +91,7 @@ CREATE TRIGGER Events_Month_delete_trigger BEFORE DELETE ON Events_Month FOR EACH ROW BEGIN UPDATE Monitors SET MonthEvents = COALESCE(MonthEvents,1)-1, - MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) + MonthEventDiskSpace=GREATEST(COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Id=OLD.MonitorId; END; // @@ -107,10 +105,10 @@ FOR EACH ROW set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); IF ( diff ) THEN IF ( NEW.MonitorID != OLD.MonitorID ) THEN - UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET MonthEventDiskSpace=GREATEST(COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace),0) WHERE Monitors.Id=OLD.MonitorId; UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)+COALESCE(NEW.DiskSpace) WHERE Monitors.Id=NEW.MonitorId; ELSE - UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId; + UPDATE Monitors SET MonthEventDiskSpace=GREATEST(COALESCE(MonthEventDiskSpace,0)+diff,0) WHERE Monitors.Id=NEW.MonitorId; END IF; END IF; END; @@ -128,14 +126,14 @@ BEGIN set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); IF ( NEW.StorageId = OLD.StorageID ) THEN IF ( diff ) THEN - UPDATE Storage SET DiskSpace = COALESCE(DiskSpace,0) + diff WHERE Id = OLD.StorageId; + UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) + diff,0) WHERE Id = OLD.StorageId; END IF; ELSE IF ( NEW.DiskSpace ) THEN UPDATE Storage SET DiskSpace = COALESCE(DiskSpace,0) + NEW.DiskSpace WHERE Id = NEW.StorageId; END IF; IF ( OLD.DiskSpace ) THEN - UPDATE Storage SET DiskSpace = COALESCE(DiskSpace,0) - OLD.DiskSpace WHERE Id = OLD.StorageId; + UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) - OLD.DiskSpace,0) WHERE Id = OLD.StorageId; END IF; END IF; @@ -150,12 +148,16 @@ BEGIN UPDATE Monitors SET ArchivedEvents = COALESCE(ArchivedEvents,0)+1, ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) + COALESCE(NEW.DiskSpace,0) WHERE Id=NEW.MonitorId; ELSEIF ( OLD.Archived ) THEN DELETE FROM Events_Archived WHERE EventId=OLD.Id; - UPDATE Monitors SET ArchivedEvents = COALESCE(ArchivedEvents,0)-1, ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) WHERE Id=OLD.MonitorId; + UPDATE Monitors + SET + ArchivedEvents = GREATEST(COALESCE(ArchivedEvents,0)-1,0), + ArchivedEventDiskSpace = GREATEST(COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; ELSE IF ( OLD.DiskSpace != NEW.DiskSpace ) THEN UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; UPDATE Monitors SET - ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0) + ArchivedEventDiskSpace = GREATEST(COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0),0) WHERE Id=OLD.MonitorId; END IF; END IF; @@ -164,18 +166,18 @@ BEGIN END IF; IF ( diff ) THEN - UPDATE Monitors SET TotalEventDiskSpace = COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0) WHERE Id=OLD.MonitorId; + UPDATE Monitors + SET + TotalEventDiskSpace = GREATEST(COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; END IF; END; // -delimiter ; +DROP TRIGGER IF EXISTS event_insert_trigger// -DROP TRIGGER IF EXISTS event_insert_trigger; - -delimiter // /* The assumption is that when an Event is inserted, it has no size yet, so don't bother updating the DiskSpace, just the count. * The DiskSpace will get update in the Event Update Trigger */ @@ -203,7 +205,7 @@ CREATE TRIGGER event_delete_trigger BEFORE DELETE ON Events FOR EACH ROW BEGIN IF ( OLD.DiskSpace ) THEN - UPDATE Storage SET DiskSpace = COALESCE(DiskSpace,0) - CAST(OLD.DiskSpace AS SIGNED) WHERE Id = OLD.StorageId; + UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) - COALESCE(OLD.DiskSpace,0),0) WHERE Id = OLD.StorageId; END IF; DELETE FROM Events_Hour WHERE EventId=OLD.Id; DELETE FROM Events_Day WHERE EventId=OLD.Id; @@ -212,15 +214,15 @@ BEGIN IF ( OLD.Archived ) THEN DELETE FROM Events_Archived WHERE EventId=OLD.Id; UPDATE Monitors SET - ArchivedEvents = COALESCE(ArchivedEvents,1) - 1, - ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0), - TotalEvents = COALESCE(TotalEvents,1) - 1, - TotalEventDiskSpace = COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + ArchivedEvents = GREATEST(COALESCE(ArchivedEvents,1) - 1,0), + ArchivedEventDiskSpace = GREATEST(COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),0), + TotalEvents = GREATEST(COALESCE(TotalEvents,1) - 1,0), + TotalEventDiskSpace = GREATEST(COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),0) WHERE Id=OLD.MonitorId; ELSE UPDATE Monitors SET - TotalEvents = COALESCE(TotalEvents,1)-1, - TotalEventDiskSpace=COALESCE(TotalEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) + TotalEvents = GREATEST(COALESCE(TotalEvents,1)-1,0), + TotalEventDiskSpace=GREATEST(COALESCE(TotalEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Id=OLD.MonitorId; END IF; END; diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index fd67c1323..72bb44c7b 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -68,6 +68,7 @@ CREATE TABLE `Controls` ( `CanWake` tinyint(3) unsigned NOT NULL default '0', `CanSleep` tinyint(3) unsigned NOT NULL default '0', `CanReset` tinyint(3) unsigned NOT NULL default '0', + `CanReboot` tinyint(3) unsigned NOT NULL default '0', `CanZoom` tinyint(3) unsigned NOT NULL default '0', `CanAutoZoom` tinyint(3) unsigned NOT NULL default '0', `CanZoomAbs` tinyint(3) unsigned NOT NULL default '0', @@ -499,7 +500,7 @@ CREATE TABLE `Monitors` ( `ReturnDelay` smallint(5) unsigned, `DefaultRate` smallint(5) unsigned NOT NULL default '100', `DefaultScale` smallint(5) unsigned NOT NULL default '100', - `DefaultCodec` enum('auto','H264','H265','MJPEG') NOT NULL default 'auto', + `DefaultCodec` enum('auto','MP4','MJPEG') NOT NULL default 'auto', `SignalCheckPoints` INT UNSIGNED NOT NULL default '0', `SignalCheckColour` varchar(32) NOT NULL default '#0000BE', `WebColour` varchar(32) NOT NULL default 'red', @@ -574,6 +575,7 @@ CREATE TABLE `Servers` ( `zmstats` BOOLEAN NOT NULL DEFAULT FALSE, `zmaudit` BOOLEAN NOT NULL DEFAULT FALSE, `zmtrigger` BOOLEAN NOT NULL DEFAULT FALSE, + `zmeventnotification` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`Id`) ) ENGINE=@ZM_MYSQL_ENGINE@; @@ -638,7 +640,7 @@ CREATE TABLE `Users` ( `Devices` enum('None','View','Edit') NOT NULL default 'None', `System` enum('None','View','Edit') NOT NULL default 'None', `MaxBandwidth` varchar(16), - `MonitorIds` tinytext, + `MonitorIds` text, PRIMARY KEY (`Id`), UNIQUE KEY `UC_Username` (`Username`) ) ENGINE=@ZM_MYSQL_ENGINE@; @@ -751,46 +753,46 @@ insert into Filters values (NULL,'Update DiskSpace','{"terms":[{"attr":"DiskSpac -- -- Add in some sample control protocol definitions -- -INSERT INTO Controls VALUES (NULL,'Pelco-D','Local','PelcoD',1,1,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); -INSERT INTO Controls VALUES (NULL,'Pelco-P','Local','PelcoP',1,1,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); -INSERT INTO Controls VALUES (NULL,'Sony VISCA','Local','Visca',1,1,0,1,0,0,0,1,0,16384,10,4000,1,1,6,1,1,1,0,1,0,1536,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,3,1,1,1,1,0,1,1,0,1,-15578,15578,100,10000,1,1,50,1,254,1,-7789,7789,100,5000,1,1,50,1,254,0,0); -INSERT INTO Controls VALUES (NULL,'Axis API v2','Remote','AxisV2',0,0,0,1,0,0,1,0,0,9999,10,2500,0,NULL,NULL,1,1,0,1,0,0,9999,10,2500,0,NULL,NULL,1,1,0,1,0,0,9999,10,2500,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,12,1,1,1,1,1,0,1,0,1,-360,360,1,90,0,NULL,NULL,0,NULL,1,-360,360,1,90,0,NULL,NULL,0,NULL,0,0); -INSERT INTO Controls VALUES (NULL,'Panasonic IP','Remote','PanasonicIP',0,0,0,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,8,1,1,1,0,1,0,0,1,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,0,0); -INSERT INTO Controls VALUES (NULL,'Neu-Fusion NCS370','Remote','Ncs370',0,0,0,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,24,1,0,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,0,0); -INSERT INTO Controls VALUES (NULL,'AirLink SkyIPCam 7xx','Remote','SkyIPCam7xx',0,0,1,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,8,1,1,1,0,1,0,1,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,0,0); -INSERT INTO Controls VALUES (NULL,'Pelco-D','Ffmpeg','PelcoD',1,1,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); -INSERT INTO Controls VALUES (NULL,'Pelco-P','Ffmpeg','PelcoP',1,1,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); -INSERT INTO Controls VALUES (NULL,'Foscam FI8620','Ffmpeg','FI8620_Y2k',0,0,0,1,0,0,0,1,1,10,1,10,1,1,63,1,1,0,0,1,1,63,1,63,1,1,63,1,1,0,0,1,0,0,0,0,1,0,255,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,255,1,8,0,1,1,1,0,0,0,1,1,1,360,1,360,1,1,63,0,0,1,1,90,1,90,1,1,63,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'Foscam FI8608W','Ffmpeg','FI8608W_Y2k',1,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,255,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,255,1,8,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,128,0,0,1,0,0,0,0,1,1,128,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'Foscam FI8908W','Remote','FI8908W',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'Foscam FI9821W','Ffmpeg','FI9821W_Y2k',1,0,1,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,100,1,1,0,0,1,0,100,0,100,1,0,100,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,100,0,100,1,0,100,1,16,0,1,1,1,0,0,0,1,1,0,360,0,360,1,0,4,0,0,1,0,90,0,90,1,0,4,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'Loftek Sentinel','Remote','LoftekSentinel',0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,255,16,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,6,1,1,0,0,0,1,10,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'Toshiba IK-WB11A','Remote','Toshiba_IK_WB11A',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,0,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'WanscamPT','Remote','Wanscam',1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,16,0,0,0,0,0,1,16,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO Controls VALUES (NULL,'3S Domo N5071', 'Remote', '3S', 0, 0, 1, 1, 0, 1, 1, 0, 0, 9999, 0, 9999, 0, 0, 0, 1, 1, 1, 1, 0, 0, 9999, 20, 9999, 0, 0, 0, 1, 1, 1, 1, 0, 0, 9999, 1, 9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 64, 1, 0, 1, 1, 0, 0, 0, 0, 1, -180, 180, 40, 100, 1, 40, 100, 0, 0, 1, -180, 180, 40, 100, 1, 40, 100, 0, 0, 0, 0); -INSERT INTO Controls VALUES (NULL,'ONVIF Camera','Ffmpeg','onvif',0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,255,16,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,6,1,1,0,0,0,1,10,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Foscam 9831W','Ffmpeg','FI9831W',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,16,1,1,1,1,0,0,0,1,1,0,360,0,360,1,0,4,0,0,1,0,90,0,90,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Foscam FI8918W','Ffmpeg','FI8918W',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,8,0,1,1,1,0,0,0,1,1,0,360,0,360,1,0,4,0,0,1,0,90,0,90,1,0,4,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'SunEyes SP-P1802SWPTZ','Libvlc','SPP1802SWPTZ',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,8,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,64,0,0,1,0,0,0,0,1,0,64,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Wanscam HW0025','Libvlc','WanscamHW0025', 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 350, 0, 0, 1, 0, 10, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 0, 0); -INSERT INTO `Controls` VALUES (NULL,'IPCC 7210W','Remote','IPCC7210W', 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); -INSERT INTO `Controls` VALUES (NULL,'Vivotek ePTZ','Remote','Vivotek_ePTZ',0,0,1,1,0,0,0,1,0,0,0,0,1,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,0,5,0,0,1,0,0,0,0,1,0,5,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Netcat ONVIF','Ffmpeg','Netcat',0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,100,5,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,100,5,5,0,0,0,1,255,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Keekoon','Remote','Keekoon', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); -INSERT INTO `Controls` VALUES (NULL,'HikVision','Local','',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,1,1,1,1,0,0,0,1,1,0,0,0,0,1,1,100,0,0,1,0,0,0,0,1,1,100,1,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Maginon Supra IPC','cURL','MaginonIPC',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,4,0,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Floureon 1080P','Ffmpeg','Floureon',0,0,0,1,0,0,0,1,1,18,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,8,0,0,1,0,0,0,0,1,1,8,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Reolink RLC-423','Ffmpeg','Reolink',0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,64,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Reolink RLC-411','Ffmpeg','Reolink',0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Reolink RLC-420','Ffmpeg','Reolink',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'D-LINK DCS-3415','Remote','DCS3415',0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'IOS Camera','Ffmpeg','IPCAMIOS',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Dericam P2','Ffmpeg','DericamP2',0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,45,0,0,1,0,0,0,0,1,1,45,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Trendnet','Remote','Trendnet',1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'PSIA','Remote','PSIA',0,0,0,1,0,0,1,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,0,1,1,1,0,0,1,0,1,0,0,0,0,1,-100,100,0,0,1,0,0,0,0,1,-100,100,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'Dahua','Remote','Dahua',0,0,0,1,0,0,1,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,8,0,0,1,0,0,0,0,1,1,8,0,0,0,0); -INSERT INTO `Controls` VALUES (NULL,'FOSCAMR2C','Libvlc','FOSCAMR2C',1,1,1,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,12,0,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,4,0,NULL,1,NULL,NULL,NULL,NULL,1,0,4,0,NULL,0,0); -INSERT INTO `Controls` VALUES (NULL,'Amcrest HTTP API','Ffmpeg','Amcrest_HTTP',0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,5,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,5); +INSERT INTO Controls VALUES (NULL,'Pelco-D','Local','PelcoD',1,1,0,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); +INSERT INTO Controls VALUES (NULL,'Pelco-P','Local','PelcoP',1,1,0,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); +INSERT INTO Controls VALUES (NULL,'Sony VISCA','Local','Visca',1,1,0,0,1,0,0,0,1,0,16384,10,4000,1,1,6,1,1,1,0,1,0,1536,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,3,1,1,1,1,0,1,1,0,1,-15578,15578,100,10000,1,1,50,1,254,1,-7789,7789,100,5000,1,1,50,1,254,0,0); +INSERT INTO Controls VALUES (NULL,'Axis API v2','Remote','AxisV2',0,0,0,0,1,0,0,1,0,0,9999,10,2500,0,NULL,NULL,1,1,0,1,0,0,9999,10,2500,0,NULL,NULL,1,1,0,1,0,0,9999,10,2500,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,12,1,1,1,1,1,0,1,0,1,-360,360,1,90,0,NULL,NULL,0,NULL,1,-360,360,1,90,0,NULL,NULL,0,NULL,0,0); +INSERT INTO Controls VALUES (NULL,'Panasonic IP','Remote','PanasonicIP',0,0,0,0,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,8,1,1,1,0,1,0,0,1,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,0,0); +INSERT INTO Controls VALUES (NULL,'Neu-Fusion NCS370','Remote','Ncs370',0,0,0,0,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,24,1,0,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,0,0); +INSERT INTO Controls VALUES (NULL,'AirLink SkyIPCam 7xx','Remote','SkyIPCam7xx',0,0,1,0,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,8,1,1,1,0,1,0,1,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,1,NULL,NULL,NULL,NULL,0,NULL,NULL,0,NULL,0,0); +INSERT INTO Controls VALUES (NULL,'Pelco-D','Ffmpeg','PelcoD',1,1,0,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); +INSERT INTO Controls VALUES (NULL,'Pelco-P','Ffmpeg','PelcoP',1,1,0,0,1,1,0,0,1,NULL,NULL,NULL,NULL,1,0,3,1,1,0,0,1,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,1,0,1,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,20,1,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,63,1,254,1,NULL,NULL,NULL,NULL,1,0,63,1,254,0,0); +INSERT INTO Controls VALUES (NULL,'Foscam FI8620','Ffmpeg','FI8620_Y2k',0,0,0,0,1,0,0,0,1,1,10,1,10,1,1,63,1,1,0,0,1,1,63,1,63,1,1,63,1,1,0,0,1,0,0,0,0,1,0,255,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,255,1,8,0,1,1,1,0,0,0,1,1,1,360,1,360,1,1,63,0,0,1,1,90,1,90,1,1,63,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'Foscam FI8608W','Ffmpeg','FI8608W_Y2k',1,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,255,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,255,1,8,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,128,0,0,1,0,0,0,0,1,1,128,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'Foscam FI8908W','Remote','FI8908W',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'Foscam FI9821W','Ffmpeg','FI9821W_Y2k',1,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,100,1,1,0,0,1,0,100,0,100,1,0,100,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,100,0,100,1,0,100,1,16,0,1,1,1,0,0,0,1,1,0,360,0,360,1,0,4,0,0,1,0,90,0,90,1,0,4,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'Loftek Sentinel','Remote','LoftekSentinel',0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,255,16,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,6,1,1,0,0,0,1,10,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'Toshiba IK-WB11A','Remote','Toshiba_IK_WB11A',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,0,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'WanscamPT','Remote','Wanscam',1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,16,0,0,0,0,0,1,16,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO Controls VALUES (NULL,'3S Domo N5071', 'Remote', '3S', 0, 0, 1, 0,1, 0, 1, 1, 0, 0, 9999, 0, 9999, 0, 0, 0, 1, 1, 1, 1, 0, 0, 9999, 20, 9999, 0, 0, 0, 1, 1, 1, 1, 0, 0, 9999, 1, 9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 64, 1, 0, 1, 1, 0, 0, 0, 0, 1, -180, 180, 40, 100, 1, 40, 100, 0, 0, 1, -180, 180, 40, 100, 1, 40, 100, 0, 0, 0, 0); +INSERT INTO Controls VALUES (NULL,'ONVIF Camera','Ffmpeg','onvif',0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,255,16,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,6,1,1,0,0,0,1,10,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Foscam 9831W','Ffmpeg','FI9831W',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,16,1,1,1,1,0,0,0,1,1,0,360,0,360,1,0,4,0,0,1,0,90,0,90,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Foscam FI8918W','Ffmpeg','FI8918W',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,8,0,1,1,1,0,0,0,1,1,0,360,0,360,1,0,4,0,0,1,0,90,0,90,1,0,4,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'SunEyes SP-P1802SWPTZ','Libvlc','SPP1802SWPTZ',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,8,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,64,0,0,1,0,0,0,0,1,0,64,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Wanscam HW0025','Libvlc','WanscamHW0025', 1, 1, 1, 0,1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 350, 0, 0, 1, 0, 10, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 0, 0); +INSERT INTO `Controls` VALUES (NULL,'IPCC 7210W','Remote','IPCC7210W', 1, 1, 1, 0,1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); +INSERT INTO `Controls` VALUES (NULL,'Vivotek ePTZ','Remote','Vivotek_ePTZ',0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,0,5,0,0,1,0,0,0,0,1,0,5,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Netcat ONVIF','Ffmpeg','Netcat',0,0,1,0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,100,5,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,100,5,5,0,0,0,1,255,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Keekoon','Remote','Keekoon', 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); +INSERT INTO `Controls` VALUES (NULL,'HikVision','Local','',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,1,1,1,1,0,0,0,1,1,0,0,0,0,1,1,100,0,0,1,0,0,0,0,1,1,100,1,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Maginon Supra IPC','cURL','MaginonIPC',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,4,0,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Floureon 1080P','Ffmpeg','Floureon',0,0,0,0,1,0,0,0,1,1,18,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,8,0,0,1,0,0,0,0,1,1,8,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Reolink RLC-423','Ffmpeg','Reolink',0,0,1,0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,64,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Reolink RLC-411','Ffmpeg','Reolink',0,0,1,0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Reolink RLC-420','Ffmpeg','Reolink',0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'D-LINK DCS-3415','Remote','DCS3415',0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'IOS Camera','Ffmpeg','IPCAMIOS',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Dericam P2','Ffmpeg','DericamP2',0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,10,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,45,0,0,1,0,0,0,0,1,1,45,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Trendnet','Remote','Trendnet',1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'PSIA','Remote','PSIA',0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,0,1,1,1,0,0,1,0,1,0,0,0,0,1,-100,100,0,0,1,0,0,0,0,1,-100,100,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'Dahua','Remote','Dahua',0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,20,0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,8,0,0,1,0,0,0,0,1,1,8,0,0,0,0); +INSERT INTO `Controls` VALUES (NULL,'FOSCAMR2C','Libvlc','FOSCAMR2C',1,1,1,0,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,0,0,0,0,0,NULL,NULL,NULL,NULL,0,NULL,NULL,1,12,0,1,1,1,0,0,0,1,1,NULL,NULL,NULL,NULL,1,0,4,0,NULL,1,NULL,NULL,NULL,NULL,1,0,4,0,NULL,0,0); +INSERT INTO `Controls` VALUES (NULL,'Amcrest HTTP API','Ffmpeg','Amcrest_HTTP',0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,5,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,5); -- -- Add some monitor preset values diff --git a/db/zm_update-1.28.99.sql b/db/zm_update-1.28.99.sql index 5b342a811..ccbc9c059 100644 --- a/db/zm_update-1.28.99.sql +++ b/db/zm_update-1.28.99.sql @@ -322,7 +322,7 @@ WHERE NOT EXISTS ( -- -- Hide USE_DEEP_STORAGE from user to prevent accidental event loss -- -UPDATE `zm`.`Config` SET `Category`='hidden' WHERE `Name`='ZM_USE_DEEP_STORAGE'; +UPDATE Config SET Category='hidden' WHERE Name='ZM_USE_DEEP_STORAGE'; -- -- Add Id column to State diff --git a/db/zm_update-1.33.3.sql b/db/zm_update-1.33.3.sql new file mode 100644 index 000000000..5488f809d --- /dev/null +++ b/db/zm_update-1.33.3.sql @@ -0,0 +1,12 @@ + +SET @s = (SELECT IF( + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() + AND table_name = 'Servers' + AND column_name = 'zmeventnotification' + ) > 0, + "SELECT 'Column zmeventnotification already exists in Servers'", + "ALTER TABLE Servers ADD `zmeventnotification` BOOLEAN NOT NULL DEFAULT FALSE AFTER `zmtrigger`" + )); + +PREPARE stmt FROM @s; +EXECUTE stmt; diff --git a/db/zm_update-1.33.4.sql b/db/zm_update-1.33.4.sql new file mode 100644 index 000000000..d9b498bc8 --- /dev/null +++ b/db/zm_update-1.33.4.sql @@ -0,0 +1,12 @@ + +SET @s = (SELECT IF( + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() + AND table_name = 'Monitors' + AND column_name = 'DefaultCodec' + ) > 0, + "SELECT 'Column DefaultCodec already exists in Monitors'", + "ALTER TABLE Monitors ADD `DefaultCodec` enum('auto','MP4','MJPEG') NOT NULL default 'auto' AFTER `DefaultScale`" + )); + +PREPARE stmt FROM @s; +EXECUTE stmt; diff --git a/db/zm_update-1.33.5.sql b/db/zm_update-1.33.5.sql new file mode 100644 index 000000000..39400b5d8 --- /dev/null +++ b/db/zm_update-1.33.5.sql @@ -0,0 +1,12 @@ + +SET @s = (SELECT IF( + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() + AND table_name = 'Controls' + AND column_name = 'CanReboot' + ) > 0, + "SELECT 'Column CanReboot already exists in Controls'", + "ALTER TABLE Controls ADD `CanReboot` tinyint(3) unsigned NOT NULL default '0' AFTER `CanReset`" + )); + +PREPARE stmt FROM @s; +EXECUTE stmt; diff --git a/db/zm_update-1.33.6.sql b/db/zm_update-1.33.6.sql new file mode 100644 index 000000000..159f80ac6 --- /dev/null +++ b/db/zm_update-1.33.6.sql @@ -0,0 +1 @@ +ALTER TABLE Users MODIFY MonitorIds text; diff --git a/db/zm_update-1.33.7.sql b/db/zm_update-1.33.7.sql new file mode 100644 index 000000000..b29fe0e88 --- /dev/null +++ b/db/zm_update-1.33.7.sql @@ -0,0 +1,283 @@ + +delimiter // +DROP TRIGGER IF EXISTS Events_Hour_delete_trigger// +CREATE TRIGGER Events_Hour_delete_trigger BEFORE DELETE ON Events_Hour +FOR EACH ROW BEGIN + UPDATE Monitors SET + HourEvents = COALESCE(HourEvents,1)-1, + HourEventDiskSpace=GREATEST(COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; +END; +// + +DROP TRIGGER IF EXISTS Events_Hour_update_trigger// + +CREATE TRIGGER Events_Hour_update_trigger AFTER UPDATE ON Events_Hour +FOR EACH ROW + BEGIN + declare diff BIGINT default 0; + + set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); + IF ( diff ) THEN + IF ( NEW.MonitorID != OLD.MonitorID ) THEN + UPDATE Monitors SET HourEventDiskSpace=GREATEST(COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; + ELSE + UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId; + END IF; + END IF; + END; +// + +DROP TRIGGER IF EXISTS Events_Day_delete_trigger// +CREATE TRIGGER Events_Day_delete_trigger BEFORE DELETE ON Events_Day +FOR EACH ROW BEGIN + UPDATE Monitors SET + DayEvents = GREATEST(COALESCE(DayEvents,1)-1,0), + DayEventDiskSpace=GREATEST(COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; +END; +// + +DROP TRIGGER IF EXISTS Events_Day_update_trigger; +CREATE TRIGGER Events_Day_update_trigger AFTER UPDATE ON Events_Day +FOR EACH ROW + BEGIN + declare diff BIGINT default 0; + + set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); + IF ( diff ) THEN + IF ( NEW.MonitorID != OLD.MonitorID ) THEN + UPDATE Monitors SET DayEventDiskSpace=GREATEST(COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; + ELSE + UPDATE Monitors SET DayEventDiskSpace=GREATEST(COALESCE(DayEventDiskSpace,0)+diff,0) WHERE Monitors.Id=NEW.MonitorId; + END IF; + END IF; + END; + // + + +DROP TRIGGER IF EXISTS Events_Week_delete_trigger// +CREATE TRIGGER Events_Week_delete_trigger BEFORE DELETE ON Events_Week +FOR EACH ROW BEGIN + UPDATE Monitors SET + WeekEvents = COALESCE(WeekEvents,1)-1, + WeekEventDiskSpace=GREATEST(COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; +END; +// + +DROP TRIGGER IF EXISTS Events_Week_update_trigger; +CREATE TRIGGER Events_Week_update_trigger AFTER UPDATE ON Events_Week +FOR EACH ROW + BEGIN + declare diff BIGINT default 0; + + set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); + IF ( diff ) THEN + IF ( NEW.MonitorID != OLD.MonitorID ) THEN + UPDATE Monitors SET WeekEventDiskSpace=GREATEST(COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId; + ELSE + UPDATE Monitors SET WeekEventDiskSpace=GREATEST(COALESCE(WeekEventDiskSpace,0)+diff,0) WHERE Monitors.Id=NEW.MonitorId; + END IF; + END IF; + END; + // + +DROP TRIGGER IF EXISTS Events_Month_delete_trigger// +CREATE TRIGGER Events_Month_delete_trigger BEFORE DELETE ON Events_Month +FOR EACH ROW BEGIN + UPDATE Monitors SET + MonthEvents = COALESCE(MonthEvents,1)-1, + MonthEventDiskSpace=GREATEST(COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; +END; +// + +DROP TRIGGER IF EXISTS Events_Month_update_trigger; +CREATE TRIGGER Events_Month_update_trigger AFTER UPDATE ON Events_Month +FOR EACH ROW + BEGIN + declare diff BIGINT default 0; + + set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); + IF ( diff ) THEN + IF ( NEW.MonitorID != OLD.MonitorID ) THEN + UPDATE Monitors SET MonthEventDiskSpace=GREATEST(COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace),0) WHERE Monitors.Id=OLD.MonitorId; + UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)+COALESCE(NEW.DiskSpace) WHERE Monitors.Id=NEW.MonitorId; + ELSE + UPDATE Monitors SET MonthEventDiskSpace=GREATEST(COALESCE(MonthEventDiskSpace,0)+diff,0) WHERE Monitors.Id=NEW.MonitorId; + END IF; + END IF; + END; + // + +drop procedure if exists update_storage_stats// + +drop trigger if exists event_update_trigger// + +CREATE TRIGGER event_update_trigger AFTER UPDATE ON Events +FOR EACH ROW +BEGIN + declare diff BIGINT default 0; + + set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0); + IF ( NEW.StorageId = OLD.StorageID ) THEN + IF ( diff ) THEN + UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) + diff,0) WHERE Id = OLD.StorageId; + END IF; + ELSE + IF ( NEW.DiskSpace ) THEN + UPDATE Storage SET DiskSpace = COALESCE(DiskSpace,0) + NEW.DiskSpace WHERE Id = NEW.StorageId; + END IF; + IF ( OLD.DiskSpace ) THEN + UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) - OLD.DiskSpace,0) WHERE Id = OLD.StorageId; + END IF; + END IF; + + UPDATE Events_Hour SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; + UPDATE Events_Day SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; + UPDATE Events_Week SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; + UPDATE Events_Month SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; + + IF ( NEW.Archived != OLD.Archived ) THEN + IF ( NEW.Archived ) THEN + INSERT INTO Events_Archived (EventId,MonitorId,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.DiskSpace); + UPDATE Monitors SET ArchivedEvents = COALESCE(ArchivedEvents,0)+1, ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) + COALESCE(NEW.DiskSpace,0) WHERE Id=NEW.MonitorId; + ELSEIF ( OLD.Archived ) THEN + DELETE FROM Events_Archived WHERE EventId=OLD.Id; + UPDATE Monitors + SET + ArchivedEvents = GREATEST(COALESCE(ArchivedEvents,0)-1,0), + ArchivedEventDiskSpace = GREATEST(COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; + ELSE + IF ( OLD.DiskSpace != NEW.DiskSpace ) THEN + UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; + UPDATE Monitors SET + ArchivedEventDiskSpace = GREATEST(COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; + END IF; + END IF; + ELSEIF ( NEW.Archived AND diff ) THEN + UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id; + END IF; + + IF ( diff ) THEN + UPDATE Monitors + SET + TotalEventDiskSpace = GREATEST(COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; + END IF; + +END; + +// + +DROP TRIGGER IF EXISTS event_insert_trigger// + +/* The assumption is that when an Event is inserted, it has no size yet, so don't bother updating the DiskSpace, just the count. + * The DiskSpace will get update in the Event Update Trigger + */ +CREATE TRIGGER event_insert_trigger AFTER INSERT ON Events +FOR EACH ROW + BEGIN + + INSERT INTO Events_Hour (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0); + INSERT INTO Events_Day (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0); + INSERT INTO Events_Week (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0); + INSERT INTO Events_Month (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0); + UPDATE Monitors SET + HourEvents = COALESCE(HourEvents,0)+1, + DayEvents = COALESCE(DayEvents,0)+1, + WeekEvents = COALESCE(WeekEvents,0)+1, + MonthEvents = COALESCE(MonthEvents,0)+1, + TotalEvents = COALESCE(TotalEvents,0)+1 + WHERE Id=NEW.MonitorId; +END; +// + +DROP TRIGGER IF EXISTS event_delete_trigger// + +CREATE TRIGGER event_delete_trigger BEFORE DELETE ON Events +FOR EACH ROW +BEGIN + IF ( OLD.DiskSpace ) THEN + UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) - COALESCE(OLD.DiskSpace,0),0) WHERE Id = OLD.StorageId; + END IF; + DELETE FROM Events_Hour WHERE EventId=OLD.Id; + DELETE FROM Events_Day WHERE EventId=OLD.Id; + DELETE FROM Events_Week WHERE EventId=OLD.Id; + DELETE FROM Events_Month WHERE EventId=OLD.Id; + IF ( OLD.Archived ) THEN + DELETE FROM Events_Archived WHERE EventId=OLD.Id; + UPDATE Monitors SET + ArchivedEvents = GREATEST(COALESCE(ArchivedEvents,1) - 1,0), + ArchivedEventDiskSpace = GREATEST(COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),0), + TotalEvents = GREATEST(COALESCE(TotalEvents,1) - 1,0), + TotalEventDiskSpace = GREATEST(COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; + ELSE + UPDATE Monitors SET + TotalEvents = GREATEST(COALESCE(TotalEvents,1)-1,0), + TotalEventDiskSpace=GREATEST(COALESCE(TotalEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0),0) + WHERE Id=OLD.MonitorId; + END IF; +END; + +// + +DROP TRIGGER IF EXISTS Zone_Insert_Trigger// +CREATE TRIGGER Zone_Insert_Trigger AFTER INSERT ON Zones +FOR EACH ROW + BEGIN + UPDATE Monitors SET ZoneCount=(SELECT COUNT(*) FROM Zones WHERE MonitorId=NEW.MonitorId) WHERE Id=NEW.MonitorID; + END +// +DROP TRIGGER IF EXISTS Zone_Delete_Trigger// +CREATE TRIGGER Zone_Delete_Trigger AFTER DELETE ON Zones +FOR EACH ROW + BEGIN + UPDATE Monitors SET ZoneCount=(SELECT COUNT(*) FROM Zones WHERE MonitorId=OLD.MonitorId) WHERE Id=OLD.MonitorID; + END +// + +DELIMITER ; + +REPLACE INTO Events_Hour SELECT Id,MonitorId,StartTime,DiskSpace FROM Events WHERE StartTime > DATE_SUB(NOW(), INTERVAL 1 hour); +REPLACE INTO Events_Day SELECT Id,MonitorId,StartTime,DiskSpace FROM Events WHERE StartTime > DATE_SUB(NOW(), INTERVAL 1 day); +REPLACE INTO Events_Week SELECT Id,MonitorId,StartTime,DiskSpace FROM Events WHERE StartTime > DATE_SUB(NOW(), INTERVAL 1 week); +REPLACE INTO Events_Month SELECT Id,MonitorId,StartTime,DiskSpace FROM Events WHERE StartTime > DATE_SUB(NOW(), INTERVAL 1 month); +REPLACE INTO Events_Archived SELECT Id,MonitorId,DiskSpace FROM Events WHERE Archived=1; + +UPDATE Monitors INNER JOIN ( + SELECT MonitorId, + COUNT(Id) AS TotalEvents, + SUM(DiskSpace) AS TotalEventDiskSpace, + SUM(IF(Archived,1,0)) AS ArchivedEvents, + SUM(IF(Archived,DiskSpace,0)) AS ArchivedEventDiskSpace, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 hour),1,0)) AS HourEvents, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 hour),DiskSpace,0)) AS HourEventDiskSpace, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 day),1,0)) AS DayEvents, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 day),DiskSpace,0)) AS DayEventDiskSpace, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 week),1,0)) AS WeekEvents, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 week),DiskSpace,0)) AS WeekEventDiskSpace, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 month),1,0)) AS MonthEvents, + SUM(IF(StartTime > DATE_SUB(NOW(), INTERVAL 1 month),DiskSpace,0)) AS MonthEventDiskSpace + FROM Events GROUP BY MonitorId + ) AS E ON E.MonitorId=Monitors.Id SET + Monitors.TotalEvents = E.TotalEvents, + Monitors.TotalEventDiskSpace = E.TotalEventDiskSpace, + Monitors.ArchivedEvents = E.ArchivedEvents, + Monitors.ArchivedEventDiskSpace = E.ArchivedEventDiskSpace, + Monitors.HourEvents = E.HourEvents, + Monitors.HourEventDiskSpace = E.HourEventDiskSpace, + Monitors.DayEvents = E.DayEvents, + Monitors.DayEventDiskSpace = E.DayEventDiskSpace, + Monitors.WeekEvents = E.WeekEvents, + Monitors.WeekEventDiskSpace = E.WeekEventDiskSpace, + Monitors.MonthEvents = E.MonthEvents, + Monitors.MonthEventDiskSpace = E.MonthEventDiskSpace; + diff --git a/distros/redhat/zoneminder.spec b/distros/redhat/zoneminder.spec index 8f30d6fee..440b05acc 100644 --- a/distros/redhat/zoneminder.spec +++ b/distros/redhat/zoneminder.spec @@ -23,7 +23,7 @@ %global _hardened_build 1 Name: zoneminder -Version: 1.33.0 +Version: 1.33.6 Release: 1%{?dist} Summary: A camera monitoring and analysis tool Group: System Environment/Daemons @@ -317,7 +317,7 @@ EOF %files common %license COPYING -%doc AUTHORS README.md distros/redhat/readme/README distros/redhat/readme/README.httpd distros/redhat/readme/README.nginx distros/redhat/readme/README.https +%doc README.md distros/redhat/readme/README distros/redhat/readme/README.httpd distros/redhat/readme/README.nginx distros/redhat/readme/README.https # We want these two folders to have "normal" read permission # compared to the folder contents @@ -352,6 +352,7 @@ EOF %{_bindir}/zmx10.pl %{_bindir}/zmonvif-probe.pl %{_bindir}/zmstats.pl +%{_bindir}/zmrecover.pl %{perl_vendorlib}/ZoneMinder* %{perl_vendorlib}/ONVIF* @@ -409,8 +410,14 @@ EOF %dir %attr(755,nginx,nginx) %{_localstatedir}/spool/zoneminder-upload %changelog +* Sun Apr 07 2019 Andrew Bauer - 1.33.6-1 +- Bump to 1.33.6 Development + +* Sat Mar 30 2019 Andrew Bauer - 1.33.4-1 +- Bump to 1.33.4 Development + * Tue Dec 11 2018 Andrew Bauer - 1.33.0-1 -- Bump tp 1.33.0 Development +- Bump to 1.33.0 Development * Sat Dec 08 2018 Andrew Bauer - 1.32.3-1 - 1.32.3 Release diff --git a/docs/installationguide/debian.rst b/docs/installationguide/debian.rst index 96907eee7..9f26411e0 100644 --- a/docs/installationguide/debian.rst +++ b/docs/installationguide/debian.rst @@ -3,6 +3,147 @@ Debian .. contents:: +Easy Way: Debian Stretch +------------------------ + +This procedure will guide you through the installation of ZoneMinder on Debian 9 (Stretch). This section has been tested with ZoneMinder 1.32.3 on Debian 9.8. + +**Step 1:** Make sure your system is up to date + +Open a console and use ``su`` command to become Root. + +:: + + apt update + apt upgrade + + +**Step 2:** Setup Sudo (optional but recommended) + +By default Debian does not come with sudo, so you have to install it and configure it manually. This step is optional but recommended and the following instructions assume that you have setup sudo. If you prefer to setup ZoneMinder as root, do it at your own risk and adapt the following instructions accordingly. + +:: + + apt install sudo + usermod -a -G sudo + exit + +Now your terminal session is back under your normal user. You can check that you are now part of the sudo group with the command ``groups``, "sudo" should appear in the list. If not, run ``newgrp sudo`` and check again with ``groups``. + + +**Step 3:** Install Apache and MySQL + +These are not dependencies for the ZoneMinder package as they could be installed elsewhere. If they are not installed yet in your system, you have to trigger their installation manually. + +:: + + sudo apt install apache2 mysql-server + +**Step 4:** Add ZoneMinder's Package repository to your apt sources + +ZoneMinder's Debian packages are not included in Debian's official package repositories. To be able to install ZoneMinder with APT, you have to edit the list of apt sources and add ZoneMinder's repository. + +:: + + sudo nano /etc/apt/sources.list + +Add the following to the bottom of the file + +:: + + # ZoneMinder repository + deb https://zmrepo.zoneminder.com/debian/release stretch/ + +CTRL+o and to save +CTRL+x to exit + +Because ZoneMinder's package repository provides a secure connection through HTTPS, apt must be enabled for HTTPS. +:: + + sudo apt install apt-transport-https + +Finally, download the GPG key for ZoneMinder's repository: +:: + + sudo wget -O - https://zmrepo.zoneminder.com/debian/archive-keyring.gpg | sudo apt-key add - + + +**Step 5:** Install ZoneMinder + +:: + + sudo apt update + sudo apt install zoneminder + +**Step 6:** Read the Readme + +The rest of the install process is covered in the README.Debian, so feel free to have +a read. + +:: + + gunzip /usr/share/doc/zoneminder/README.Debian.gz + cat /usr/share/doc/zoneminder/README.Debian + + +**Step 7:** Enable ZoneMinder service + +:: + + sudo systemctl enable zoneminder.service + +**Step 8:** Configure Apache + +The following commands will setup the default /zm virtual directory and configure +required apache modules. + +:: + + sudo a2enconf zoneminder + sudo a2enmod rewrite + sudo a2enmod cgi # this is done automatically when installing the package. Redo this command manually only for troubleshooting. + + +**Step 9:** Edit Timezone in PHP + +Automated way: +:: + + sudo sed -i "s/;date.timezone =/date.timezone = $(sed 's/\//\\\//' /etc/timezone)/g" /etc/php/7.0/apache2/php.ini + +Manual way +:: + + sudo nano /etc/php/7.0/apache2/php.ini + +Search for [Date] (Ctrl + w then type Date and press Enter) and change +date.timezone for your time zone. Don't forget to remove the ; from in front +of date.timezone. + +:: + + [Date] + ; Defines the default timezone used by the date functions + ; http://php.net/date.timezone + date.timezone = America/New_York + +CTRL+o then [Enter] to save + +CTRL+x to exit + + +**Step 10:** Start ZoneMinder + +Reload Apache to enable your changes and then start ZoneMinder. + +:: + + sudo systemctl reload apache2 + sudo systemctl start zoneminder + +You are now ready to go with ZoneMinder. Open a browser and type either ``localhost/zm`` one the local machine or ``{IP-OF-ZM-SERVER}/zm`` if you connect from a remote computer. + + Easy Way: Debian Jessie ----------------------- @@ -81,7 +222,7 @@ should you choose to change default database user and password. cat /usr/share/zoneminder/db/zm_create.sql | sudo mysql --defaults-file=/etc/mysql/debian.cnf echo 'grant lock tables,alter,create,select,insert,update,delete,index on zm.* to 'zmuser'@localhost identified by "zmpass";' | sudo mysql --defaults-file=/etc/mysql/debian.cnf mysql -** Step 8:** zm.conf Permissions +**Step 8:** zm.conf Permissions Adjust permissions to the zm.conf file to allow web account to access it. @@ -129,6 +270,7 @@ CTRL+x to exit **Step 12:** Please check the configuration + Zoneminder 1.32.x 1. Check path of ZM_PATH in '/etc/zm/conf.d/zmcustom.conf' is ZM_PATH_ZMS=/zm/cgi-bin/nph-zms :: diff --git a/docs/installationguide/redhat.rst b/docs/installationguide/redhat.rst index 71b4f5278..5b5067058 100644 --- a/docs/installationguide/redhat.rst +++ b/docs/installationguide/redhat.rst @@ -158,7 +158,7 @@ The list of available Mock config files are available here: ls /etc/mock/*rpmfusion_free.cfg -You choose the config file based on the desired distro (e.g. el6, el7, f20, f21) and basearch (e.g. x86, x86_64, arhmhfp). Notice that, when specifying the Mock config as a commandline parameter, you should leave off the ".cfg" filename extension. +You choose the config file based on the desired distro (e.g. el7, f29, f30) and basearch (e.g. x86, x86_64, arhmhfp). Notice that, when specifying the Mock config as a commandline parameter, you should leave off the ".cfg" filename extension. Installation ************ @@ -188,8 +188,8 @@ Now clone the ZoneMinder git repository from your home folder: :: cd - git clone https://github.com/ZoneMinder/ZoneMinder - cd ZoneMinder + git clone https://github.com/ZoneMinder/zoneminder + cd zoneminder This will create a sub-folder called ZoneMinder, which will contain the latest development source code. @@ -197,27 +197,27 @@ If you have previsouly cloned the ZoneMinder git repo and wish to update it to t :: - cd ~/ZoneMinder + cd ~/zoneminder git pull origin master Get the crud submodule tarball: :: - spectool -f -g -R -s 1 ~/ZoneMinder/distros/redhat/zoneminder.spec + spectool -f -g -R -s 1 ~/zoneminder/distros/redhat/zoneminder.spec At this point, you can make changes to the source code. Depending on what you want to do with those changes, you generally want to create a new branch first: :: - cd ~/ZoneMinder + cd ~/zoneminder git checkout -b mynewbranch Again, depending on what you want to do with those changes, you may want to commit your changes: :: - cd ~/ZoneMinder + cd ~/zoneminder git add . git commit @@ -225,28 +225,28 @@ Once you have made your changes, it is time to turn your work into a new tarball :: - less ~/ZoneMinder/distros/redhat/zoneminder.spec + less ~/zoneminder/distros/redhat/zoneminder.spec Scroll down until you see the Version field. Note the value, which will be in the format x.xx.x. Now create the tarball with the following command: :: - cd ~/ZoneMinder - git archive --prefix=ZoneMinder-1.31.1/ -o ~/rpmbuild/SOURCES/zoneminder-1.31.1.tar.gz HEAD + cd ~/zoneminder + git archive --prefix=zoneminder-1.33.4/ -o ~/rpmbuild/SOURCES/zoneminder-1.33.4.tar.gz HEAD -Replace "1.31.1" with the Version shown in the rpm specfile. +Replace "1.33.4" with the Version shown in the rpm specfile. From the root of the local ZoneMinder git repo, execute the following: :: - cd ~/ZoneMinder + cd ~/zoneminder rpmbuild -bs --nodeps distros/redhat/zoneminder.spec This step will create a source rpm and it will tell you where it was saved. For example: :: - Wrote: /home/abauer/rpmbuild/SRPMS/zoneminder-1.31.1-1.fc26.src.rpm + Wrote: /home/abauer/rpmbuild/SRPMS/zoneminder-1.33.4-1.fc26.src.rpm Now follow the previous instructions `Build from SRPM`_ which describe how to build that source rpm into an rpm. diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Config.pm.in b/scripts/ZoneMinder/lib/ZoneMinder/Config.pm.in index 3fdeb722c..10e4b4733 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Config.pm.in +++ b/scripts/ZoneMinder/lib/ZoneMinder/Config.pm.in @@ -30,6 +30,7 @@ use warnings; require Exporter; require ZoneMinder::Base; + use ZoneMinder::ConfigData qw(:all); our @ISA = qw(Exporter ZoneMinder::Base); @@ -57,20 +58,22 @@ our %EXPORT_TAGS = ( push( @{$EXPORT_TAGS{config}}, @EXPORT_CONFIG ); push( @{$EXPORT_TAGS{all}}, @{$EXPORT_TAGS{$_}} ) foreach keys %EXPORT_TAGS; -our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); +our @EXPORT_OK = @{ $EXPORT_TAGS{all} }; our @EXPORT = qw(); our $VERSION = $ZoneMinder::Base::VERSION; -use constant ZM_PID => "@ZM_PID@"; # Path to the ZoneMinder run pid file -use constant ZM_CONFIG => "@ZM_CONFIG@"; # Path to the ZoneMinder config file -use constant ZM_CONFIG_SUBDIR => "@ZM_CONFIG_SUBDIR@"; # Path to the ZoneMinder config subfolder +use constant ZM_PID => '@ZM_PID@'; # Path to the ZoneMinder run pid file +use constant ZM_CONFIG => '@ZM_CONFIG@'; # Path to the ZoneMinder config file +use constant ZM_CONFIG_SUBDIR => '@ZM_CONFIG_SUBDIR@'; # Path to the ZoneMinder config subfolder use Carp; +require ZoneMinder::Database; # Load the config from the database into the symbol table BEGIN { +require ZoneMinder::Database; # Process name, value pairs from the main config file first my $config_file = ZM_CONFIG; @@ -78,52 +81,25 @@ BEGIN { # Search for user created config files. If one or more are found then # update the Config hash with those values - if ( -d ZM_CONFIG_SUBDIR ) { + if ( ZM_CONFIG_SUBDIR and -d ZM_CONFIG_SUBDIR ) { if ( -R ZM_CONFIG_SUBDIR ) { - foreach my $filename ( glob ZM_CONFIG_SUBDIR."/*.conf" ) { + foreach my $filename ( glob ZM_CONFIG_SUBDIR.'/*.conf' ) { process_configfile($filename); } } else { - print( STDERR "WARNING: ZoneMinder configuration subfolder found but is not readable. Check folder permissions on ".ZM_CONFIG_SUBDIR.".\n" ); + print( STDERR 'WARNING: ZoneMinder configuration subfolder found but is not readable. Check folder permissions on '.ZM_CONFIG_SUBDIR.".\n" ); } } - use DBI; - my $socket; - my ( $host, $portOrSocket ) = ( $Config{ZM_DB_HOST} =~ /^([^:]+)(?::(.+))?$/ ); - - if ( defined($portOrSocket) ) { - if ( $portOrSocket =~ /^\// ) { - $socket = ';mysql_socket='.$portOrSocket; - } else { - $socket = ';host='.$host.';port='.$portOrSocket; - } - } else { - $socket = ';host='.$Config{ZM_DB_HOST}; - } - my $sslOptions = ''; - if ( $Config{ZM_DB_SSL_CA_CERT} ) { - $sslOptions = ';'.join(';', - "mysql_ssl=1", - "mysql_ssl_ca_file=".$Config{ZM_DB_SSL_CA_CERT}, - "mysql_ssl_client_key=".$Config{ZM_DB_SSL_CLIENT_KEY}, - "mysql_ssl_client_cert=".$Config{ZM_DB_SSL_CLIENT_CERT} - ); - } - my $dbh = DBI->connect( "DBI:mysql:database=".$Config{ZM_DB_NAME} - .$socket.$sslOptions - , $Config{ZM_DB_USER} - , $Config{ZM_DB_PASS} - ) or croak( "Can't connect to db" ); + my $dbh = ZoneMinder::Database::zmDbConnect(); my $sql = 'SELECT Name,Value FROM Config'; - my $sth = $dbh->prepare_cached( $sql ) or croak( "Can't prepare '$sql': ".$dbh->errstr() ); - my $res = $sth->execute() or croak( "Can't execute: ".$sth->errstr() ); + my $sth = $dbh->prepare_cached($sql) or croak("Can't prepare '$sql': ".$dbh->errstr()); + my $res = $sth->execute() or croak("Can't execute: ".$sth->errstr()); while( my $config = $sth->fetchrow_hashref() ) { $Config{$config->{Name}} = $config->{Value}; } $sth->finish(); -#$dbh->disconnect(); - # + if ( ! $Config{ZM_SERVER_ID} ) { $Config{ZM_SERVER_ID} = undef; $sth = $dbh->prepare_cached( 'SELECT * FROM Servers WHERE Name=?' ); @@ -143,25 +119,30 @@ BEGIN { sub process_configfile { my $config_file = shift; - if ( -R $config_file ) { - open( my $CONFIG, '<', $config_file ) - or croak( "Can't open config file '$config_file': $!" ); - foreach my $str ( <$CONFIG> ) { - next if ( $str =~ /^\s*$/ ); - next if ( $str =~ /^\s*#/ ); - my ( $name, $value ) = $str =~ /^\s*([^=\s]+)\s*=\s*[\'"]*(.*?)[\'"]*\s*$/; - if ( ! $name ) { - print( STDERR "Warning, bad line in $config_file: $str\n" ); - next; - } # end if - $name =~ tr/a-z/A-Z/; - $Config{$name} = $value; - } - close( $CONFIG ); - } else { - print( STDERR "WARNING: ZoneMinder configuration file found but is not readable. Check file permissions on $config_file\n" ); + if ( ! -R $config_file ) { + print(STDERR "WARNING: ZoneMinder configuration file found but is not readable. Check file permissions on $config_file\n"); + return; } - } + open( my $CONFIG, '<', $config_file ) + or croak("Can't open config file '$config_file': $!"); + foreach my $str ( <$CONFIG> ) { + next if ( $str =~ /^\s*$/ ); + next if ( $str =~ /^\s*#/ ); + my ( $name, $value ) = $str =~ /^\s*([^=\s]+)\s*=\s*[\'"]*(.*?)[\'"]*\s*$/; + if ( !$name ) { + print(STDERR "Warning, bad line in $config_file: $str\n"); + next; + } # end if + $name =~ tr/a-z/A-Z/; + #if ( !$ZoneMinder::ConfigData::options_hash{$name} ) { + #print(STDERR "Warning, unknown config option name $name in $config_file\n"); +#} else { + #print(STDERR "Warning, known config option name $name in $config_file\n"); + #} + $Config{$name} = $value; + } # end foreach config line + close($CONFIG); + } # end sub process_configfile } # end BEGIN diff --git a/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in b/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in index cd53d6754..52dd2fb32 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in +++ b/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in @@ -462,6 +462,18 @@ our @options = ( type => $types{string}, category => 'system', }, + { + name => 'ZM_SYSTEM_SHUTDOWN', + default => 'true', + description => 'Allow Admin users to power off or restart the system from the ZoneMinder UI.', + help => 'The system will need to have sudo installed and the following added to /etc/sudoers~~ + ~~ + @ZM_WEB_USER@ ALL=NOPASSWD: /sbin/shutdown~~ + ~~ + to perform the shutdown or reboot', + type => $types{boolean}, + category => 'system', + }, { name => 'ZM_USE_DEEP_STORAGE', default => 'yes', @@ -3952,7 +3964,7 @@ our %options_hash = map { ( $_->{name}, $_ ) } @options; # This function should never need to be called explicitly, except if # this module is 'require'd rather than 'use'd. See zmconfgen.pl. sub initialiseConfig { - return if ( $configInitialised ); + return if $configInitialised; # Do some initial data munging to finish the data structures # Create option ids diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Control.pm b/scripts/ZoneMinder/lib/ZoneMinder/Control.pm index efd17abcd..bbc06a884 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Control.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Control.pm @@ -67,7 +67,7 @@ sub AUTOLOAD { if ( exists($self->{$name}) ) { return $self->{$name}; } - Error("Can't access $name member of object of class $class"); + Error("Can't access $name $AUTOLOAD member of object of class $class"); } sub getKey { diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Control/Dahua.pm b/scripts/ZoneMinder/lib/ZoneMinder/Control/Dahua.pm index 6cb55d3a6..e55a6da1c 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Control/Dahua.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Control/Dahua.pm @@ -39,6 +39,8 @@ sub AUTOLOAD my $class = ref($self) || croak( "$self not object" ); my $name = $AUTOLOAD; $name =~ s/.*://; + ## This seems odd... if the method existed would we even be here? + ## https://perldoc.perl.org/perlsub.html#Autoloading if ( exists($self->{$name}) ) { return( $self->{$name} ); @@ -46,9 +48,17 @@ sub AUTOLOAD Fatal( "Can't access $name member of object of class $class" ); } +# FIXME: Do we really have to open a new connection every time? + +#Digest usernbme="bdmin", reblm="Login to 4K05DB3PAJE98BE", nonae="1720242756", +#uri="/agi-bin/ptz.agi?bation=getStbtus&ahbnnel=1", response="10dd925b26ebd559353734635b859b8b", +#opbque="1a99677524b4ae63bbe3a132b2e9b38e3b163ebd", qop=buth, na=00000001, anonae="ab1bb5d43aa5d542" + sub open { + #Debug("&open invoked by: " . (caller(1))[3]); my $self = shift; + my $cgi = shift || '/cgi-bin/configManager.cgi?action=getConfig&name=Ptz'; $self->loadMonitor(); # The Dahua camera firmware API supports the concept of having multiple @@ -73,60 +83,55 @@ sub open } use LWP::UserAgent; - $self->{ua} = LWP::UserAgent->new; - $self->{ua}->agent("ZoneMinder Control Agent/".$ZoneMinder::Base::ZM_VERSION); + $self->{ua} = LWP::UserAgent->new(keep_alive => 1); + $self->{ua}->agent("ZoneMinder Control Agent/".ZoneMinder::Base::ZM_VERSION); $self->{state} = 'closed'; # credentials: ("ip:port" (no prefix!), realm (string), username (string), password (string) - Debug("sendCmd credentials control address:'".$ADDRESS - ."' realm:'" . $REALM - . "' username:'" . $USERNAME - . "' password:'".$PASSWORD - ."'" - ); $self->{ua}->credentials($ADDRESS, $REALM, $USERNAME, $PASSWORD); # Detect REALM - my $get_config_url = $PROTOCOL . $ADDRESS . "/cgi-bin/configManager.cgi?action=getConfig&name=Ptz"; - my $req = HTTP::Request->new(GET=>$get_config_url); + my $url = $PROTOCOL . $ADDRESS . $cgi; + my $req = HTTP::Request->new(GET=>$url); my $res = $self->{ua}->request($req); if ($res->is_success) { $self->{state} = 'open'; - return; + return 1; } if ( $res->status_line() eq '401 Unauthorized' ) { my $headers = $res->headers(); - foreach my $k (keys %$headers) { - Debug("Initial Header $k => $$headers{$k}"); - } - if ($$headers{'www-authenticate'}) { my ($auth, $tokens) = $$headers{'www-authenticate'} =~ /^(\w+)\s+(.*)$/; + Debug("Tokens: " . $tokens); + ## FIXME: This is necessary because the Dahua spec does not match reality if ($tokens =~ /\w+="([^"]+)"/i) { if ($REALM ne $1) { $REALM = $1; Debug("Changing REALM to '" . $REALM . "'"); $self->{ua}->credentials($ADDRESS, $REALM, $USERNAME, $PASSWORD); - my $req = HTTP::Request->new(GET=>$get_config_url); + my $req = HTTP::Request->new(GET=>$url); $res = $self->{ua}->request($req); + if ($res->is_success()) { $self->{state} = 'open'; - return; + Debug('Authentication succeeded...'); + return 1; } Debug('Authentication still failed after updating REALM' . $res->status_line); $headers = $res->headers(); foreach my $k ( keys %$headers ) { Debug("Initial Header $k => $$headers{$k}"); } # end foreach - } else { - Error('Authentication failed, not a REALM problem'); + } else { ## NOTE: Each of these else conditions is fatal as the command will not be + ## executed. No use going further. + Fatal('Authentication failed: Check username and password.'); } } else { - Error('Failed to match realm in tokens'); + Fatal('Authentication failed: Incorrect realm.'); } # end if } else { - Error('No WWW-Authenticate Header'); + Fatal('Authentication failed: No www-authenticate header returned.'); } # end if headers } # end if $res->status_line() eq '401 Unauthorized' } @@ -146,45 +151,40 @@ sub printMsg Debug( $msg."[".$msg_len."]" ); } -sub sendGetRequest { +sub _sendGetRequest { my $self = shift; my $url_path = shift; - my $result = undef; + # Attempt to reuse the connection + + # FIXME: I think we need some sort of keepalive/heartbeat sent to the camera + # in order to keep the session alive. As it is, it appears that the + # ua's authentication times out or some such. + # + # This might be of some use: + # {"method":"global.keepAlive","params":{"timeout":300,"active":false},"id":1518,"session":"dae233a51c0693519395209b271411b6"}[!http] + # The web browser interface POSTs commands as JSON using js my $url = $PROTOCOL . $ADDRESS . $url_path; - my $req = HTTP::Request->new(GET=>$url); - + my $req = HTTP::Request->new(GET => $url); my $res = $self->{ua}->request($req); if ($res->is_success) { - $result = !undef; + return 1; } else { - if ($res->status_line() eq '401 Unauthorized') { - Debug("Error check failed, trying again: USERNAME: $USERNAME realm: $REALM password: " . $PASSWORD); - Debug("Content was " . $res->content() ); - my $res = $self->{ua}->request($req); - if ($res->is_success) { - $result = !undef; - } else { - Error("Content was " . $res->content() ); - } - } - if ( ! $result ) { - Error("Error check failed: '".$res->status_line()); - } + return($self->open($url_path)); # if we have to, open a new connection } - return($result); } -sub sendPtzCommand +sub _sendPtzCommand { my $self = shift; my $action = shift; my $command_code = shift; - my $arg1 = shift; - my $arg2 = shift; - my $arg3 = shift; + my $arg1 = shift || 0; + my $arg2 = shift || 0; + my $arg3 = shift || 0; + my $arg4 = shift || 0; my $channel = $self->{dahua_channel_number}; @@ -194,10 +194,12 @@ sub sendPtzCommand $url_path .= "code=" . $command_code . "&"; $url_path .= "arg1=" . $arg1 . "&"; $url_path .= "arg2=" . $arg2 . "&"; - $url_path .= "arg3=" . $arg3; - $self->sendGetRequest($url_path); + $url_path .= "arg3=" . $arg3 . "&"; + $url_path .= "arg4=" . $arg4; + return $self->_sendGetRequest($url_path); } -sub sendMomentaryPtzCommand + +sub _sendMomentaryPtzCommand { my $self = shift; my $command_code = shift; @@ -206,92 +208,195 @@ sub sendMomentaryPtzCommand my $arg3 = shift; my $duration_ms = shift; - $self->sendPtzCommand("start", $command_code, $arg1, $arg2, $arg3); + $self->_sendPtzCommand("start", $command_code, $arg1, $arg2, $arg3); my $duration_ns = $duration_ms * 1000; usleep($duration_ns); - $self->sendPtzCommand("stop", $command_code, $arg1, $arg2, $arg3); + $self->_sendPtzCommand("stop", $command_code, $arg1, $arg2, $arg3); +} + +sub _sendAbsolutePositionCommand +{ + my $self = shift; + my $arg1 = shift; + my $arg2 = shift; + my $arg3 = shift; + my $arg4 = shift; + + $self->_sendPtzCommand("start", "PositionABS", $arg1, $arg2, $arg3, $arg4); +} + +sub moveConLeft +{ + my $self = shift; + Debug("Move Up Left"); + $self->_sendMomentaryPtzCommand("Left", 0, 1, 0, 0); +} + +sub moveConRight +{ + my $self = shift; + Debug( "Move Right" ); + $self->_sendMomentaryPtzCommand("Right", 0, 1, 0, 0); +} + +sub moveConUp +{ + my $self = shift; + Debug( "Move Up" ); + $self->_sendMomentaryPtzCommand("Up", 0, 1, 0, 0); +} + +sub moveConDown +{ + my $self = shift; + Debug( "Move Down" ); + $self->_sendMomentaryPtzCommand("Down", 0, 1, 0, 0); +} + +sub moveConUpRight +{ + my $self = shift; + Debug( "Move Diagonally Up Right" ); + $self->_sendMomentaryPtzCommand("RightUp", 1, 1, 0, 0); +} + +sub moveConDownRight +{ + my $self = shift; + Debug( "Move Diagonally Down Right" ); + $self->_sendMomentaryPtzCommand("RightDown", 1, 1, 0, 0); +} + +sub moveConUpLeft +{ + my $self = shift; + Debug( "Move Diagonally Up Left" ); + $self->_sendMomentaryPtzCommand("LeftUp", 1, 1, 0, 0); +} + +sub moveConDownLeft +{ + my $self = shift; + Debug( "Move Diagonally Up Right" ); + $self->_sendMomentaryPtzCommand("LeftDown", 1, 1, 0, 0); +} + +sub zoomConTele +{ + my $self = shift; + Debug( "Zoom Tele" ); + $self->_sendMomentaryPtzCommand("ZoomTele", 0, 1, 0, 0); +} + +sub zoomConWide +{ + my $self = shift; + Debug( "Zoom Wide" ); + $self->_sendMomentaryPtzCommand("ZoomWide", 0, 1, 0, 0); } sub moveRelUpLeft { my $self = shift; Debug("Move Up Left"); - $self->sendMomentaryPtzCommand("LeftUp", 4, 4, 0, 500); + $self->_sendMomentaryPtzCommand("LeftUp", 4, 4, 0, 500); } sub moveRelUp { my $self = shift; Debug("Move Up"); - $self->sendMomentaryPtzCommand("Up", 0, 4, 0, 500); + $self->_sendMomentaryPtzCommand("Up", 0, 4, 0, 500); } sub moveRelUpRight { my $self = shift; Debug("Move Up Right"); - $self->sendMomentaryPtzCommand("RightUp", 0, 4, 0, 500); + $self->_sendMomentaryPtzCommand("RightUp", 0, 4, 0, 500); } sub moveRelLeft { my $self = shift; Debug("Move Left"); - $self->sendMomentaryPtzCommand("Left", 0, 4, 0, 500); + $self->_sendMomentaryPtzCommand("Left", 0, 4, 0, 500); } sub moveRelRight { my $self = shift; Debug("Move Right"); - $self->sendMomentaryPtzCommand("Right", 0, 4, 0, 500); + $self->_sendMomentaryPtzCommand("Right", 0, 4, 0, 500); } sub moveRelDownLeft { my $self = shift; Debug("Move Down Left"); - $self->sendMomentaryPtzCommand("LeftDown", 4, 4, 0, 500); + $self->_sendMomentaryPtzCommand("LeftDown", 4, 4, 0, 500); } sub moveRelDown { my $self = shift; Debug("Move Down"); - $self->sendMomentaryPtzCommand("Down", 0, 4, 0, 500); + $self->_sendMomentaryPtzCommand("Down", 0, 4, 0, 500); } sub moveRelDownRight { my $self = shift; Debug("Move Down Right"); - $self->sendMomentaryPtzCommand("RightDown", 4, 4, 0, 500); + $self->_sendMomentaryPtzCommand("RightDown", 4, 4, 0, 500); } sub zoomRelTele { my $self = shift; Debug("Zoom Relative Tele"); - $self->sendMomentaryPtzCommand("ZoomTele", 0, 0, 0, 500); + $self->_sendMomentaryPtzCommand("ZoomTele", 0, 0, 0, 500); } sub zoomRelWide { my $self = shift; Debug("Zoom Relative Wide"); - $self->sendMomentaryPtzCommand("ZoomWide", 0, 0, 0, 500); + $self->_sendMomentaryPtzCommand("ZoomWide", 0, 0, 0, 500); } +sub focusRelNear +{ + my $self = shift; + + my $response = $self->_sendPtzCommand("start", "FocusNear", 0, 1, 0, 0); + Debug("focusRelNear response: " . $response); +} + +sub focusRelFar +{ + my $self = shift; + + my $response = $self->_sendPtzCommand("start", "FocusFar", 0, 1, 0, 0); + Debug("focusRelFar response: " . $response); +} + +sub moveStop +{ + my $self = shift; + Debug( "Move Stop" ); + # The command does not matter here, just the stop... + $self->_sendPtzCommand("stop", "Up", 0, 0, 1, 0); +} sub presetClear { my $self = shift; my $params = shift; my $preset_id = $self->getParam($params, 'preset'); - $self->sendPtzCommand("start", "ClearPreset", 0, $preset_id, 0); + $self->_sendPtzCommand("start", "ClearPreset", 0, $preset_id, 0); } - sub presetSet { my $self = shift; @@ -308,8 +413,8 @@ sub presetSet my $control_preset_row = $sth->fetchrow_hashref(); my $new_label_name = $control_preset_row->{'Label'}; - $self->sendPtzCommand("start", "SetPreset", 0, $preset_id, 0); - $self->sendPtzCommand("start", "SetPresetName", $preset_id, $new_label_name, 0); + $self->_sendPtzCommand("start", "SetPreset", 0, $preset_id, 0); + $self->_sendPtzCommand("start", "SetPresetName", $preset_id, $new_label_name, 0); } sub presetGoto @@ -318,12 +423,39 @@ sub presetGoto my $params = shift; my $preset_id = $self->getParam($params, 'preset'); - $self->sendPtzCommand("start", "GotoPreset", 0, $preset_id, 0); + $self->_sendPtzCommand("start", "GotoPreset", 0, $preset_id, 0); +} + +sub presetHome +{ + my $self = shift; + + $self->_sendAbsolutePositionCommand( 0, 0, 0, 1 ); +} + +sub reset +{ + my $self = shift; + Debug( "Camera Reset" ); + $self->_sendPtzCommand("Reset", 0, 0, 0, 0); +} + +sub reboot +{ + my $self = shift; + Debug( "Camera Reboot" ); + my $cmd = "/cgi-bin/magicBox.cgi?action=reboot"; + $self->_sendGetRequest($cmd); } 1; + __END__ +=pod + +=encoding utf8 + =head1 NAME ZoneMinder::Control::Dahua - Perl module for Dahua cameras @@ -337,10 +469,6 @@ place this in /usr/share/perl5/ZoneMinder/Control This module is an implementation of the Dahua IP camera HTTP control API. -=head2 EXPORT - -None by default. - =head1 COPYRIGHT AND LICENSE Copyright (C) 2018 ZoneMinder LLC @@ -359,4 +487,138 @@ 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. +=head1 Private Methods + + Methods intended for use internally but documented here for future developers. + +=head2 _sendAbsolutePositionCommand( $arg1, $arg2, $arg3, $arg4 ) + + Where: + + $arg1 = Horizontal angle 0° to 360° + $arg2 = Vertical angle 0° to -90° + $arg3 = Zoom multiplier + $arg4 = Speed 1 to 8 + + This is an private method used to send an absolute position command to the + camera. + +=head1 Public Methods + + Methods made available to control.pl via ZoneMinder::Control + +=head2 Notes: + +=over 1 + + Which methods are invoked depends on which types of movement are selected in + the camera control type. For example: if the 'Can Move Continuous' option is + checked, then methods including 'Con' in their names are invoked. Likewise if + the 'Can Move Relative" option is checked, then methods including 'Rel' in + their names are invoked. + + + At present, these types of movement are prioritized and exclusive. This applies + to all types of movement, not just PTZ, but focus, iris, etc. as well. The options + are tested in the following order: + + 1. Continuous + + 2. Relative + + 3. Absolute + + These types are exclusive meaning that the first one that matches is the one + ZoneMinder will use to control with. It would be nice to allow the user to + select the type used given that some cameras support all three types of + movement. + +=back + +=head2 new + + This method instantiates a new control object based upon this control module + and sets the 'id' attribute to the value passed in. + +=head2 open + + This method opens an HTTP connection to the camera. It handles authentication, + etc. Upon success it sets the 'state' attribute to 'open.' + +=head2 close + + This method effectively closes the HTTP connection to the camera. It sets the + 'state' attribute to 'close.' + +=head2 printMsg + + This method appears to be used for debugging. + +=head2 moveCon + + This set of methods invoke continuous movement in the direction indicated by + the portion of their name. They accept no arguments and move the + camera at a speed of 1 for 0ms. The speed index of 1 is the lowest of the + accepted range of 1-8. + + NOTE: + + This is not true continuous movmement as currently implemented. + +=head2 focusCon + + This set of methods invoke continuous focus in the range direction indicated + by the portion of their name. They accept no arguments. + + NOTE: + + This is not true continuous movmement as currently implemented. + +=head2 moveRel + + This set of methods invoke relatvie movement in the direction indicated by + the portion of their name. They accept no arguments and move the + camera at a speed of 4 for 500ms. The speed index of 4 is half-way between + the accepted range of 1-8. + +=head2 focusRel + + This set of methods invoke realtive focus in the range direction indicated by + the portion of their name. They accept no arguments. + + NOTE: + + This only just does work. The Dahua API specifies "multiples" as the input. + We pass in a 1 for that as it does not seem to matter what number (0-8) is + provided, the camera focus behaves the same. + +=head2 moveStop + + This method attempts to stop the camera. The problem is that if continuous + motion is occurring in multiple directions, this will only stop the motion + in the 'Up' direction. Dahua does not support an "all-stop" command. + +=head2 presetHome + + This method "homes" the camera to a preset position. It accepts no arguments. + When either continuous or relative movement is enabled, pressing the center + button on the movement controls invokes this method. + + NOTE: + + The Dahua protocol does not appear to support a preset Home feature. We could + allow the user to assign a preset slot as the "home" slot. Dahua does appear + to support naming presets which may lend itself to this sort of thing. At + this point, we'll just send the camera back to center and zoom wide. (0°,0°,0) + +=head2 reset + + This method will reset the PTZ controls to their "default." It is not clear + what that is. + +=head2 reboot + + This method performs a reboot of the camera. This will take the camera offline + for the time it takes to reboot. + =cut diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Control/PSIA.pm b/scripts/ZoneMinder/lib/ZoneMinder/Control/PSIA.pm index fe067fe1f..438c5cff5 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Control/PSIA.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Control/PSIA.pm @@ -40,7 +40,7 @@ sub open use LWP::UserAgent; $self->{ua} = LWP::UserAgent->new; - $self->{ua}->agent( "ZoneMinder Control Agent/".$ZoneMinder::Base::ZM_VERSION ); + $self->{ua}->agent( "ZoneMinder Control Agent/".ZoneMinder::Base::ZM_VERSION ); $self->{state} = 'closed'; Debug( "sendCmd credentials control address:'".$ADDRESS ."' realm:'" . $REALM diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Control/Trendnet.pm b/scripts/ZoneMinder/lib/ZoneMinder/Control/Trendnet.pm index 4ee710297..4afba372c 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Control/Trendnet.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Control/Trendnet.pm @@ -45,7 +45,7 @@ sub open { use LWP::UserAgent; $self->{ua} = LWP::UserAgent->new; - $self->{ua}->agent('ZoneMinder Control Agent/'.$ZoneMinder::Base::ZM_VERSION); + $self->{ua}->agent('ZoneMinder Control Agent/'.ZoneMinder::Base::ZM_VERSION); $self->{state} = 'closed'; # credentials: ("ip:port" (no prefix!), realm (string), username (string), password (string) Debug ( "sendCmd credentials control address:'".$ADDRESS @@ -120,6 +120,7 @@ sub sendCmd { Debug('sendCmd command: ' . $url); if ( $res->is_success ) { + Debug($res->content); return !undef; } Error("Error check failed: '".$res->status_line()."' cmd:'".$cmd."'"); @@ -155,6 +156,7 @@ sub sendCmdPost { Debug("sendCmdPost credentials control to: $PROTOCOL$ADDRESS$url realm:'" . $REALM . "' username:'" . $USERNAME . "' password:'".$PASSWORD."'"); if ( $res->is_success ) { + Debug($res->content); return !undef; } Error("sendCmdPost Error check failed: '".$res->status_line()."' cmd:"); diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Database.pm b/scripts/ZoneMinder/lib/ZoneMinder/Database.pm index 173c0033c..5c6617510 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Database.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Database.pm @@ -65,7 +65,8 @@ our $VERSION = $ZoneMinder::Base::VERSION; # ========================================================================== use ZoneMinder::Logger qw(:all); -use ZoneMinder::Config qw(:all); + +require ZoneMinder::Config; our $dbh = undef; @@ -87,25 +88,25 @@ sub zmDbConnect { $socket = ';host='.$host.';port='.$portOrSocket; } } else { - $socket = ';host='.$Config{ZM_DB_HOST}; + $socket = ';host='.$ZoneMinder::Config::Config{ZM_DB_HOST}; } my $sslOptions = ''; - if ( $Config{ZM_DB_SSL_CA_CERT} ) { - $sslOptions = join(';','', + if ( $ZoneMinder::Config::Config{ZM_DB_SSL_CA_CERT} ) { + $sslOptions = join(';', '', 'mysql_ssl=1', - 'mysql_ssl_ca_file='.$Config{ZM_DB_SSL_CA_CERT}, - 'mysql_ssl_client_key='.$Config{ZM_DB_SSL_CLIENT_KEY}, - 'mysql_ssl_client_cert='.$Config{ZM_DB_SSL_CLIENT_CERT} + 'mysql_ssl_ca_file='.$ZoneMinder::Config::Config{ZM_DB_SSL_CA_CERT}, + 'mysql_ssl_client_key='.$ZoneMinder::Config::Config{ZM_DB_SSL_CLIENT_KEY}, + 'mysql_ssl_client_cert='.$ZoneMinder::Config::Config{ZM_DB_SSL_CLIENT_CERT} ); } eval { $dbh = DBI->connect( - 'DBI:mysql:database='.$Config{ZM_DB_NAME} + 'DBI:mysql:database='.$ZoneMinder::Config::Config{ZM_DB_NAME} .$socket . $sslOptions . ($options?join(';', '', map { $_.'='.$$options{$_} } keys %{$options} ) : '') - , $Config{ZM_DB_USER} - , $Config{ZM_DB_PASS} + , $ZoneMinder::Config::Config{ZM_DB_USER} + , $ZoneMinder::Config::Config{ZM_DB_PASS} ); }; if ( !$dbh or $@ ) { @@ -124,7 +125,7 @@ sub zmDbConnect { } # end sub zmDbConnect sub zmDbDisconnect { - if ( defined( $dbh ) ) { + if ( defined($dbh) ) { $dbh->disconnect() or Error('Error disconnecting db? ' . $dbh->errstr()); $dbh = undef; } diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm b/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm index ccace879a..a057f55d9 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm @@ -177,7 +177,7 @@ sub Sql { $self->{Sql} .= 'to_days( E.StartTime )'; } elsif ( $term->{attr} eq 'Time' or $term->{attr} eq 'StartTime' ) { $self->{Sql} .= 'extract( hour_second from E.StartTime )'; - } elsif ( $term->{attr} eq 'Weekday' ) { + } elsif ( $term->{attr} eq 'Weekday' or $term->{attr} eq 'StartWeekday' ) { $self->{Sql} .= 'weekday( E.StartTime )'; # EndTIme options diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm b/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm index c381d279e..18bbc35c5 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Logger.pm @@ -1,6 +1,6 @@ ############################################################################ # -# ZoneMinder Logger Module, $Date$, $Revision$ +# ZoneMinder Logger Module # Copyright (C) 2001-2008 Philip Coombes # # This program is free software; you can redistribute it and/or @@ -87,7 +87,7 @@ our $VERSION = $ZoneMinder::Base::VERSION; # ############################################################################ -use ZoneMinder::Config qw(:all); +require ZoneMinder::Config; use DBI; use Carp; @@ -156,7 +156,7 @@ sub new { $this->{autoFlush} = 1; ( $this->{fileName} = $0 ) =~ s|^.*/||; - $this->{logPath} = $Config{ZM_PATH_LOGS}; + $this->{logPath} = $ZoneMinder::Config::Config{ZM_PATH_LOGS}; $this->{logFile} = $this->{logPath}.'/'.$this->{id}.'.log'; ($this->{logFile}) = $this->{logFile} =~ /^([\w\.\/]+)$/; @@ -169,7 +169,7 @@ sub new { sub BEGIN { # Fake the config variables that are used in case they are not defined yet # Only really necessary to support upgrade from previous version - if ( !eval('defined($Config{ZM_LOG_DEBUG})') ) { + if ( !eval('defined($ZoneMinder::Config::Config{ZM_LOG_DEBUG})') ) { no strict 'subs'; no strict 'refs'; my %dbgConfig = ( @@ -221,17 +221,17 @@ sub initialise( @ ) { if ( defined($options{databaseLevel}) ) { $tempDatabaseLevel = $options{databaseLevel}; } else { - $tempDatabaseLevel = $Config{ZM_LOG_LEVEL_DATABASE}; + $tempDatabaseLevel = $ZoneMinder::Config::Config{ZM_LOG_LEVEL_DATABASE}; } if ( defined($options{fileLevel}) ) { $tempFileLevel = $options{fileLevel}; } else { - $tempFileLevel = $Config{ZM_LOG_LEVEL_FILE}; + $tempFileLevel = $ZoneMinder::Config::Config{ZM_LOG_LEVEL_FILE}; } if ( defined($options{syslogLevel}) ) { $tempSyslogLevel = $options{syslogLevel}; } else { - $tempSyslogLevel = $Config{ZM_LOG_LEVEL_SYSLOG}; + $tempSyslogLevel = $ZoneMinder::Config::Config{ZM_LOG_LEVEL_SYSLOG}; } if ( defined($ENV{LOG_PRINT}) ) { @@ -245,19 +245,19 @@ sub initialise( @ ) { $tempFileLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL_FILE')); $tempSyslogLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL_SYSLOG')); - if ( $Config{ZM_LOG_DEBUG} ) { + if ( $ZoneMinder::Config::Config{ZM_LOG_DEBUG} ) { # Splitting on an empty string doesn't return an empty string, it returns an empty array - foreach my $target ( $Config{ZM_LOG_DEBUG_TARGET} ? split(/\|/, $Config{ZM_LOG_DEBUG_TARGET}) : '' ) { + foreach my $target ( $ZoneMinder::Config::Config{ZM_LOG_DEBUG_TARGET} ? split(/\|/, $ZoneMinder::Config::Config{ZM_LOG_DEBUG_TARGET}) : '' ) { if ( $target eq $this->{id} || $target eq '_'.$this->{id} || $target eq $this->{idRoot} || $target eq '_'.$this->{idRoot} || $target eq '' ) { - if ( $Config{ZM_LOG_DEBUG_LEVEL} > NOLOG ) { - $tempLevel = $this->limit( $Config{ZM_LOG_DEBUG_LEVEL} ); - if ( $Config{ZM_LOG_DEBUG_FILE} ne '' ) { - $tempLogFile = $Config{ZM_LOG_DEBUG_FILE}; + if ( $ZoneMinder::Config::Config{ZM_LOG_DEBUG_LEVEL} > NOLOG ) { + $tempLevel = $this->limit( $ZoneMinder::Config::Config{ZM_LOG_DEBUG_LEVEL} ); + if ( $ZoneMinder::Config::Config{ZM_LOG_DEBUG_FILE} ne '' ) { + $tempLogFile = $ZoneMinder::Config::Config{ZM_LOG_DEBUG_FILE}; $tempFileLevel = $tempLevel; } } @@ -501,8 +501,8 @@ sub openFile { if ( open($LOGFILE, '>>', $this->{logFile}) ) { $LOGFILE->autoflush() if $this->{autoFlush}; - my $webUid = (getpwnam($Config{ZM_WEB_USER}))[2]; - my $webGid = (getgrnam($Config{ZM_WEB_GROUP}))[2]; + my $webUid = (getpwnam($ZoneMinder::Config::Config{ZM_WEB_USER}))[2]; + my $webGid = (getgrnam($ZoneMinder::Config::Config{ZM_WEB_GROUP}))[2]; if ( $> == 0 ) { chown( $webUid, $webGid, $this->{logFile} ) or Fatal("Can't change permissions on log file $$this{logFile}: $!"); @@ -577,7 +577,7 @@ sub logPrint { my $res = $this->{sth}->execute( $seconds+($microseconds/1000000.0), $this->{id}, - ($Config{ZM_SERVER_ID} ? $Config{ZM_SERVER_ID} : undef), + ($ZoneMinder::Config::Config{ZM_SERVER_ID} ? $ZoneMinder::Config::Config{ZM_SERVER_ID} : undef), $$, $level, $codes{$level}, diff --git a/scripts/zmaudit.pl.in b/scripts/zmaudit.pl.in index 45035ca23..41c8b0e75 100644 --- a/scripts/zmaudit.pl.in +++ b/scripts/zmaudit.pl.in @@ -766,7 +766,7 @@ FROM Frames WHERE EventId=?'; $res = $selectUnclosedEventsSth->execute() or Fatal( "Can't execute: ".$selectUnclosedEventsSth->errstr() ); while( my $event = $selectUnclosedEventsSth->fetchrow_hashref() ) { - aud_print( "Found open event '$event->{Id}' at $$event{StartTime}" ); + aud_print( "Found open event '$event->{Id}' on Monitor $event->{MonitorId} at $$event{StartTime}" ); if ( confirm( 'close', 'closing' ) ) { if ( ! ( $res = $selectFrameDataSth->execute($event->{Id}) ) ) { Error( "Can't execute: $selectFrameDataSql:".$selectFrameDataSth->errstr() ); @@ -792,13 +792,13 @@ FROM Frames WHERE EventId=?'; $frame->{MaxScore}, RECOVER_TEXT, $event->{Id} - ) or Error( "Can't execute: ".$updateUnclosedEventsSth->errstr() ); + ) or Error( 'Can\'t execute: '.$updateUnclosedEventsSth->errstr() ); } else { Error('SHOULD DELETE'); } # end if has frame data } } # end while unclosed event - Debug("Done closing open events."); + Debug('Done closing open events.'); # Now delete any old image files if ( my @old_files = grep { -M > $max_image_age } <$image_path/*.{jpg,gif,wbmp}> ) { @@ -1005,17 +1005,17 @@ sub delete_empty_directories { Error("delete_empty_directories: Can't open directory '/$_[0]': $!" ); return; } - my @contents = map { ( $_ eq '.' or $_ eq '..' ) ? () : $_ } readdir( $DIR ); + my @contents = map { ( $_ eq '.' or $_ eq '..' ) ? () : $_ } readdir($DIR); #Debug("delete_empty_directories $_[0] has " . @contents .' entries:' . ( @contents <= 2 ? join(',',@contents) : '' )); my @dirs = map { -d $_[0].'/'.$_ ? $_ : () } @contents; if ( @dirs ) { - Debug("Have " . @dirs . " dirs in $_[0]"); + Debug('Have ' . @dirs . " dirs in $_[0]"); foreach ( @dirs ) { - delete_empty_directories( $_[0].'/'.$_ ); + delete_empty_directories($_[0].'/'.$_); } #Reload, since we may now be empty rewinddir $DIR; - @contents = map { ($_ eq '.' or $_ eq '..') ? () : $_ } readdir( $DIR ); + @contents = map { ($_ eq '.' or $_ eq '..') ? () : $_ } readdir($DIR); } closedir($DIR); if ( ! @contents ) { diff --git a/scripts/zmcontrol.pl.in b/scripts/zmcontrol.pl.in index 7d7053335..f83bc82d4 100644 --- a/scripts/zmcontrol.pl.in +++ b/scripts/zmcontrol.pl.in @@ -30,7 +30,7 @@ use autouse 'Pod::Usage'=>qw(pod2usage); use POSIX qw/strftime EPIPE/; use Socket; #use Data::Dumper; -use Module::Load::Conditional qw{can_load};; +use Module::Load::Conditional qw{can_load}; use constant MAX_CONNECT_DELAY => 15; use constant MAX_COMMAND_WAIT => 1800; @@ -43,7 +43,7 @@ delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; logInit(); -my $arg_string = join( " ", @ARGV ); +my $arg_string = join(' ', @ARGV); my $id; my %options; @@ -63,23 +63,47 @@ GetOptions( 'autostop' =>\$options{autostop}, ) or pod2usage(-exitstatus => -1); -if ( !$id || !$options{command} ) { - print( STDERR "Please give a valid monitor id and command\n" ); +if ( !$id ) { + print(STDERR "Please give a valid monitor id\n"); pod2usage(-exitstatus => -1); } ( $id ) = $id =~ /^(\w+)$/; -Debug("zmcontrol: arg string: $arg_string"); my $sock_file = $Config{ZM_PATH_SOCKS}.'/zmcontrol-'.$id.'.sock'; +Debug("zmcontrol: arg string: $arg_string sock file $sock_file"); -socket(CLIENT, PF_UNIX, SOCK_STREAM, 0) - or Fatal("Can't open socket: $!"); +socket(CLIENT, PF_UNIX, SOCK_STREAM, 0) or Fatal("Can't open socket: $!"); my $saddr = sockaddr_un($sock_file); -my $server_up = connect(CLIENT, $saddr); -if ( !$server_up ) { + +if ( $options{command} ) { + # Have a command, so we are the client, connect to the server and send it. + + my $tries = 10; + my $server_up; + while ( $tries and ! ( $server_up = connect(CLIENT, $saddr) ) ) { + Debug("Failed to connect to $server_up at $sock_file"); + runCommand("zmdc.pl start zmcontrol.pl --id=$id"); + sleep 1; + $tries -= 1; + } + if ( $server_up ) { + # The server is there, connect to it + #print( "Writing commands\n" ); + CLIENT->autoflush(); + + if ( $options{command} ) { + my $message = jsonEncode(\%options); + print(CLIENT $message); + } + shutdown(CLIENT, 1); + } else { + Error("Unable to connect to zmcontrol server at $sock_file"); + } +} else { + # The server isn't there my $monitor = zmDbGetMonitorAndControl($id); if ( !$monitor ) { @@ -113,97 +137,72 @@ if ( !$server_up ) { Fatal("Can't load ZoneMinder::Control::$protocol\n$Module::Load::Conditional::ERROR"); } - if ( my $cpid = fork() ) { - logReinit(); + Info("Control server $id/$protocol starting at " + .strftime('%y/%m/%d %H:%M:%S', localtime()) + ); - # Parent process just sleep and fall through - socket(CLIENT, PF_UNIX, SOCK_STREAM, 0) - or die("Can't open socket: $!"); - my $attempts = 0; - while ( !connect(CLIENT, $saddr) ) { - $attempts++; - Fatal("Can't connect: $! after $attempts attempts to $sock_file") if $attempts > MAX_CONNECT_DELAY; - sleep(1); - } - } elsif ( defined($cpid) ) { - close(STDOUT); - close(STDERR); + $0 = $0." --id=$id"; - setpgrp(); + my $control = "ZoneMinder::Control::$protocol"->new($id); + my $control_key = $control->getKey(); + $control->loadMonitor(); - logReinit(); + $control->open(); - Info("Control server $id/$protocol starting at " - .strftime('%y/%m/%d %H:%M:%S', localtime()) - ); - - $0 = $0." --id $id"; - - my $control = "ZoneMinder::Control::$protocol"->new($id); - my $control_key = $control->getKey(); - $control->loadMonitor(); - - $control->open(); - - socket(SERVER, PF_UNIX, SOCK_STREAM, 0) - or Fatal("Can't open socket: $!"); - unlink($sock_file); - bind(SERVER, $saddr) or Fatal("Can't bind: $!"); - listen(SERVER, SOMAXCONN) or Fatal("Can't listen: $!"); - - my $rin = ''; - vec( $rin, fileno(SERVER), 1 ) = 1; - my $win = $rin; - my $ein = $win; - my $timeout = MAX_COMMAND_WAIT; - while( 1 ) { - my $nfound = select(my $rout = $rin, undef, undef, $timeout); - if ( $nfound > 0 ) { - if ( vec( $rout, fileno(SERVER), 1 ) ) { - my $paddr = accept(CLIENT, SERVER); - my $message = ; - - next if !$message; - - my $params = jsonDecode($message); - #Debug( Dumper( $params ) ); - - my $command = $params->{command}; - close( CLIENT ); - if ( $command eq 'quit' ) { - last; - } - $control->$command($params); - } else { - Fatal('Bogus descriptor'); - } - } elsif ( $nfound < 0 ) { - if ( $! == EPIPE ) { - Error("Can't select: $!"); - } else { - Fatal("Can't select: $!"); - } - } else { - #print( "Select timed out\n" ); - last; - } - } # end while forever - Info("Control server $id/$protocol exiting"); - unlink($sock_file); - $control->close(); - exit(0); - } else { - Fatal("Can't fork: $!"); + # If we have a command when starting up, then do it. + if ( $options{command} ) { + my $command = $options{command}; + $control->$command(\%options); } + + socket(SERVER, PF_UNIX, SOCK_STREAM, 0) or Fatal("Can't open socket: $!"); + unlink($sock_file); + bind(SERVER, $saddr) or Fatal("Can't bind: $!"); + listen(SERVER, SOMAXCONN) or Fatal("Can't listen: $!"); + + my $rin = ''; + vec( $rin, fileno(SERVER), 1 ) = 1; + my $win = $rin; + my $ein = $win; + my $timeout = MAX_COMMAND_WAIT; + while( 1 ) { + my $nfound = select(my $rout = $rin, undef, undef, $timeout); + if ( $nfound > 0 ) { + if ( vec( $rout, fileno(SERVER), 1 ) ) { + my $paddr = accept(CLIENT, SERVER); + my $message = ; + + next if !$message; + + my $params = jsonDecode($message); + #Debug( Dumper( $params ) ); + + my $command = $params->{command}; + close( CLIENT ); + if ( $command eq 'quit' ) { + last; + } + $control->$command($params); + } else { + Fatal('Bogus descriptor'); + } + } elsif ( $nfound < 0 ) { + if ( $! == EPIPE ) { + Error("Can't select: $!"); + } else { + Fatal("Can't select: $!"); + } + } else { + #print( "Select timed out\n" ); + last; + } + } # end while forever + Info("Control server $id/$protocol exiting"); + unlink($sock_file); + $control->close(); + exit(0); } # end if !server up -# The server is there, connect to it -#print( "Writing commands\n" ); -CLIENT->autoflush(); - -my $message = jsonEncode(\%options); -print(CLIENT $message); -shutdown(CLIENT, 1); exit(0); @@ -216,7 +215,7 @@ zmcontrol.pl - ZoneMinder control script =head1 SYNOPSIS - zmcontrol.pl --id {monitor_id} --command={command} [various options] + zmcontrol.pl --id {monitor_id} [--command={command}] [various options] =head1 DESCRIPTION diff --git a/scripts/zmdc.pl.in b/scripts/zmdc.pl.in index b5903f3da..596517b4b 100644 --- a/scripts/zmdc.pl.in +++ b/scripts/zmdc.pl.in @@ -101,6 +101,7 @@ my @daemons = ( 'zmupdate.pl', 'zmstats.pl', 'zmtrack.pl', + 'zmcontrol.pl', 'zmtelemetry.pl' ); diff --git a/scripts/zmpkg.pl.in b/scripts/zmpkg.pl.in index e1881541a..7cc8ee866 100644 --- a/scripts/zmpkg.pl.in +++ b/scripts/zmpkg.pl.in @@ -217,14 +217,17 @@ if ( $command =~ /^(?:start|restart)$/ ) { runCommand("zmdc.pl start zmc -m $monitor->{Id}"); } if ( $Config{ZM_OPT_CONTROL} ) { - if ( $monitor->{Controllable} && $monitor->{TrackMotion} ) { - if ( $monitor->{Function} eq 'Modect' || $monitor->{Function} eq 'Mocord' ) { - runCommand("zmdc.pl start zmtrack.pl -m $monitor->{Id}"); - } else { - Warning('Monitor is set to track motion, but does not have motion detection enabled.'); - } # end if Has motion enabled - } # end if track motion - } # end if ZM_OPT_CONTROL + if ( $monitor->{Controllable} ) { + runCommand("zmdc.pl start zmcontrol.pl --id $monitor->{Id}"); + if ( $monitor->{TrackMotion} ) { + if ( $monitor->{Function} eq 'Modect' || $monitor->{Function} eq 'Mocord' ) { + runCommand("zmdc.pl start zmtrack.pl -m $monitor->{Id}"); + } else { + Warning('Monitor is set to track motion, but does not have motion detection enabled.'); + } # end if Has motion enabled + } # end if track motion + } # end if controllable + } # end if ZM_OPT_CONTROL } # end if function is not none or Website } # end foreach monitor $sth->finish(); @@ -272,7 +275,11 @@ if ( $command =~ /^(?:start|restart)$/ ) { runCommand('zmdc.pl start zmtelemetry.pl'); } if ($Config{ZM_OPT_USE_EVENTNOTIFICATION} ) { + if ( $Server and exists $$Server{'zmeventnotification'} and ! $$Server{'zmeventnotification'} ) { + Debug("Not running zmnotification.pl because it is turned off for this server."); + } else { runCommand('zmdc.pl start zmeventnotification.pl'); + } } if ( $Server and exists $$Server{zmstats} and ! $$Server{zmstats} ) { Debug('Not running zmstats.pl because it is turned off for this server.'); diff --git a/scripts/zmstats.pl.in b/scripts/zmstats.pl.in index 410459158..ba6d8302a 100644 --- a/scripts/zmstats.pl.in +++ b/scripts/zmstats.pl.in @@ -18,9 +18,7 @@ use constant START_DELAY => 30; # To give everything else time to start @EXTRA_PERL_LIB@ use ZoneMinder; -use POSIX; use DBI; -use autouse 'Data::Dumper'=>qw(Dumper); $| = 1; @@ -31,15 +29,15 @@ delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; logInit(); logSetSignal(); -Info("Stats Daemon starting in ".START_DELAY." seconds"); +Info('Stats Daemon starting in '.START_DELAY.' seconds'); sleep(START_DELAY); my $dbh = zmDbConnect(); while( 1 ) { while ( ! ( $dbh and $dbh->ping() ) ) { - Info("Reconnecting to db"); - if ( ! ( $dbh = zmDbConnect() ) ) { + Info('Reconnecting to db'); + if ( !($dbh = zmDbConnect()) ) { #What we do here is not that important, so just skip this interval sleep($Config{ZM_STATS_UPDATE_INTERVAL}); } @@ -53,7 +51,7 @@ while( 1 ) { sleep($Config{ZM_STATS_UPDATE_INTERVAL}); } # end while (1) -Info("Stats Daemon exiting"); +Info('Stats Daemon exiting'); exit(); 1; __END__ diff --git a/scripts/zmupdate.pl.in b/scripts/zmupdate.pl.in index 8517e0277..bb9dddac4 100644 --- a/scripts/zmupdate.pl.in +++ b/scripts/zmupdate.pl.in @@ -923,10 +923,10 @@ if ( $version ) { die( "Can't find upgrade from version '$version'" ); } # Re-enable the privacy popup after each upgrade - my $sql = "update Config set Value = 1 where Name = 'ZM_SHOW_PRIVACY'"; - my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() ); - my $res = $sth->execute( ) or die( "Can't execute: ".$sth->errstr() ); - $sth->finish(); + #my $sql = "update Config set Value = 1 where Name = 'ZM_SHOW_PRIVACY'"; + #my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() ); + #my $res = $sth->execute( ) or die( "Can't execute: ".$sth->errstr() ); + #$sth->finish(); print( "\nDatabase upgrade to version ".ZM_VERSION." successful.\n\n" ); } zmDbDisconnect(); diff --git a/src/zm_event.cpp b/src/zm_event.cpp index d3f79fbfb..8938a6ae0 100644 --- a/src/zm_event.cpp +++ b/src/zm_event.cpp @@ -198,6 +198,9 @@ Event::Event( video_name[0] = 0; + snprintf(snapshot_file, sizeof(snapshot_file), "%s/snapshot.jpg", path); + snprintf(alarm_file, sizeof(alarm_file), "%s/alarm.jpg", path); + /* Save as video */ if ( monitor->GetOptVideoWriter() != 0 ) { @@ -254,7 +257,7 @@ Event::~Event() { WriteDbFrames(); // Should not be static because we might be multi-threaded - char sql[ZM_SQL_MED_BUFSIZ]; + char sql[ZM_SQL_LGE_BUFSIZ]; snprintf(sql, sizeof(sql), "UPDATE Events SET Name='%s %" PRIu64 "', EndTime = from_unixtime( %ld ), Length = %s%ld.%02ld, Frames = %d, AlarmFrames = %d, TotScore = %d, AvgScore = %d, MaxScore = %d, DefaultVideo = '%s' WHERE Id = %" PRIu64, monitor->EventPrefix(), id, end_time.tv_sec, @@ -442,9 +445,9 @@ void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, str frames++; - static char event_file[PATH_MAX]; - snprintf(event_file, sizeof(event_file), staticConfig.capture_file_format, path.c_str(), frames); if ( save_jpegs & 1 ) { + static char event_file[PATH_MAX]; + snprintf(event_file, sizeof(event_file), staticConfig.capture_file_format, path.c_str(), frames); Debug(1, "Writing pre-capture frame %d", frames); WriteFrameImage(images[i], *(timestamps[i]), event_file); } else { @@ -453,7 +456,6 @@ void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, str // neccessarily be of the motion. But some events are less than 10 frames, // so I am changing this to 1, but we should overwrite it later with a better snapshot. if ( frames == 1 ) { - std::string snapshot_file = path + "/snapshot.jpg"; WriteFrameImage(images[i], *(timestamps[i]), snapshot_file.c_str()); } } @@ -541,29 +543,30 @@ void Event::AddFrame(Image *image, struct timeval timestamp, int score, Image *a frames++; - static char event_file[PATH_MAX]; - snprintf(event_file, sizeof(event_file), staticConfig.capture_file_format, path.c_str(), frames); + bool write_to_db = false; if ( save_jpegs & 1 ) { + static char event_file[PATH_MAX]; + snprintf(event_file, sizeof(event_file), staticConfig.capture_file_format, path, frames); Debug(1, "Writing capture frame %d to %s", frames, event_file); if ( ! WriteFrameImage(image, timestamp, event_file) ) { Error("Failed to write frame image"); } } else { //If this is the first frame, we should add a thumbnail to the event directory - // On the first frame, max_score will be zero, this effectively makes us write out a thumbnail - // for the first frame as well. - if ( frames == 1 || score > (int)max_score ) { - std::string snapshot_file = path + "/snapshot.jpg"; + if ( (frames == 1) || (score > (int)max_score) ) { + write_to_db = true; // web ui might show this as thumbnail, so db needs to know about it. WriteFrameImage(image, timestamp, snapshot_file.c_str()); } // The first frame with a score will be the frame that alarmed the event - if (!alarm_frame_written && score > 0) { + if ( (!alarm_frame_written) && (score > 0) ) { + write_to_db = true; // OD processing will need it, so the db needs to know about it alarm_frame_written = true; - char alarm_file[PATH_MAX]; - snprintf(alarm_file, sizeof(alarm_file), "%s/alarm.jpg", path.c_str()); WriteFrameImage(image, timestamp, alarm_file); } + } // end if save_jpegs + if ( videowriter != NULL ) { + WriteFrameVideo(image, timestamp, videowriter); } struct DeltaTimeval delta_time; @@ -580,7 +583,7 @@ void Event::AddFrame(Image *image, struct timeval timestamp, int score, Image *a static char sql[ZM_SQL_MED_BUFSIZ]; frame_data.push(new Frame(id, frames, frame_type, timestamp, delta_time, score)); - if ( frame_data.size() > 20 ) { + if ( write_to_db || ( frame_data.size() > 20 ) ) { WriteDbFrames(); Debug(1, "Adding 20 frames to DB"); last_db_frame = frames; @@ -629,5 +632,6 @@ void Event::AddFrame(Image *image, struct timeval timestamp, int score, Image *a } } } - } + } // end if frame_type == ALARM + } diff --git a/src/zm_event.h b/src/zm_event.h index a7c9ed8fa..f9aa2dbb0 100644 --- a/src/zm_event.h +++ b/src/zm_event.h @@ -92,7 +92,10 @@ class Event { unsigned int max_score; std::string path; VideoStore *videoStore; - char video_name[64]; + char snapshot_file[PATH_MAX]; + char alarm_file[PATH_MAX]; + VideoWriter* videowriter; + char video_name[PATH_MAX]; char video_file[PATH_MAX]; int last_db_frame; bool have_video_keyframe; // a flag to tell us if we have had a video keyframe when writing an mp4. The first frame SHOULD be a video keyframe. diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index 488910dba..2e18dbb63 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -228,7 +228,7 @@ bool EventStream::loadEventData(uint64_t event_id) { //timestamp = atof(dbrow[1]); double delta = atof(dbrow[2]); int id_diff = id - last_id; - double frame_delta = id_diff ? (delta-last_delta)/id_diff : (delta - last_delta); + double frame_delta = id_diff ? (delta-last_delta)/id_diff : (delta-last_delta); // Fill in data between bulk frames if ( id_diff > 1 ) { for ( int i = last_id+1; i < id; i++ ) { @@ -262,8 +262,8 @@ bool EventStream::loadEventData(uint64_t event_id) { ); } if ( mysql_errno( &dbconn ) ) { - Error( "Can't fetch row: %s", mysql_error( &dbconn ) ); - exit( mysql_errno( &dbconn ) ); + Error("Can't fetch row: %s", mysql_error(&dbconn)); + exit(mysql_errno(&dbconn)); } mysql_free_result(result); @@ -355,6 +355,7 @@ void EventStream::processCommand(const CmdMsg *msg) { replay_rate = 50 * ZM_RATE_BASE; break; default : + Debug(1,"Defaulting replay_rate to 2*ZM_RATE_BASE because it is %d", replay_rate); replay_rate = 2 * ZM_RATE_BASE; break; } @@ -509,11 +510,12 @@ void EventStream::processCommand(const CmdMsg *msg) { DataMsg status_msg; status_msg.msg_type = MSG_DATA_EVENT; memcpy(&status_msg.msg_data, &status_data, sizeof(status_data)); + Debug(1,"Size of msg %d", sizeof(status_data)); if ( 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)); - exit(-1); + //exit(-1); } } // quit after sending a status, if this was a quit request @@ -521,7 +523,7 @@ void EventStream::processCommand(const CmdMsg *msg) { exit(0); updateFrameRate((double)event_data->frame_count/event_data->duration); -} +} // void EventStream::processCommand(const CmdMsg *msg) void EventStream::checkEventLoaded() { static char sql[ZM_SQL_SML_BUFSIZ]; @@ -532,6 +534,7 @@ void EventStream::checkEventLoaded() { snprintf(sql, sizeof(sql), "SELECT Id FROM Events WHERE MonitorId = %ld AND Id > %" PRIu64 " ORDER BY Id ASC LIMIT 1", event_data->monitor_id, event_data->event_id); } else { // No event change required + //Debug(3, "No event change required"); return; } @@ -673,10 +676,6 @@ Debug(1, "Loading image"); // Get the frame from the mp4 input Debug(1,"Getting frame from ffmpeg"); AVFrame *frame; - if ( curr_frame_id == 1 ) { - // Special case, first frame, we want to send the initial keyframe. - frame = ffmpeg_input->get_frame( ffmpeg_input->get_video_stream_id(), 0 ); - } FrameData *frame_data = &event_data->frames[curr_frame_id-1]; frame = ffmpeg_input->get_frame( ffmpeg_input->get_video_stream_id(), frame_data->offset ); if ( frame ) { @@ -787,22 +786,31 @@ void EventStream::runStream() { Debug(3, "frame rate is: (%f)", (double)event_data->frame_count/event_data->duration); updateFrameRate((double)event_data->frame_count/event_data->duration); + gettimeofday(&start, NULL); + uint64_t start_usec = start.tv_sec * 1000000 + start.tv_usec; + uint64_t last_frame_offset = 0; while ( !zm_terminate ) { gettimeofday(&now, NULL); - unsigned int delta_us = 0; + int delta_us = 0; send_frame = false; - // commands may set send_frame to true - while ( checkCommandQueue() && !zm_terminate ) { - // The idea is to loop here processing all commands before proceeding. - } + if ( connkey ) { + // commands may set send_frame to true + while ( checkCommandQueue() && !zm_terminate ) { + // The idea is to loop here processing all commands before proceeding. + Debug(1, "Have command queue"); + } + Debug(1, "Done command queue"); - // Update modified time of the socket .lock file so that we can tell which ones are stale. - if ( now.tv_sec - last_comm_update.tv_sec > 3600 ) { - touch(sock_path_lock); - last_comm_update = now; + // Update modified time of the socket .lock file so that we can tell which ones are stale. + if ( now.tv_sec - last_comm_update.tv_sec > 3600 ) { + touch(sock_path_lock); + last_comm_update = now; + } + } else { + Debug(1, "Not checking command queue"); } if ( step != 0 ) @@ -818,6 +826,7 @@ void EventStream::runStream() { //Info( "cfid:%d", curr_frame_id ); //Info( "fdt:%d", frame_data->timestamp ); if ( !paused ) { + Debug(3,"Not paused"); bool in_event = true; double time_to_event = 0; if ( replay_rate > 0 ) { @@ -840,6 +849,7 @@ void EventStream::runStream() { } //else //{ + Debug(2,"Sleeping because paused"); usleep(STREAM_PAUSE_WAIT); //curr_stream_time += (replay_rate>0?1:-1) * ((1.0L * replay_rate * STREAM_PAUSE_WAIT)/(ZM_RATE_BASE * 1000000)); curr_stream_time += (1.0L * replay_rate * STREAM_PAUSE_WAIT)/(ZM_RATE_BASE * 1000000); @@ -854,15 +864,17 @@ Debug(3,"cur_frame_id (%d-1) mod frame_mod(%d)",curr_frame_id, frame_mod); // so if it is 2, then we send every other frame, if is it 4 then every fourth frame, etc. if ( (frame_mod == 1) || (((curr_frame_id-1)%frame_mod) == 0) ) { delta_us = (unsigned int)(frame_data->delta * 1000000); - Debug(3,"frame delta %u ", delta_us); + Debug(3,"frame delta %uus ", delta_us); // if effective > base we should speed up frame delivery delta_us = (unsigned int)((delta_us * base_fps)/effective_fps); Debug(3,"delta %u = base_fps(%f)/effective fps(%f)", delta_us, base_fps, effective_fps); // but must not exceed maxfps delta_us = max(delta_us, 1000000 / maxfps); + Debug(3,"delta %u = base_fps(%f)/effective fps(%f) from 30fps", delta_us, base_fps, effective_fps); send_frame = true; } } else if ( step != 0 ) { + Debug(2,"Paused with step"); // We are paused and are just stepping forward or backward one frame step = 0; send_frame = true; @@ -873,28 +885,76 @@ Debug(3,"cur_frame_id (%d-1) mod frame_mod(%d)",curr_frame_id, frame_mod); // Send keepalive Debug(2, "Sending keepalive frame"); send_frame = true; + //} else { + //Debug(2, "Not Sending keepalive frame"); } } // end if streaming stepping or doing nothing - if ( send_frame ) + if ( send_frame ) { + //Debug(3,"sending frame"); if ( !sendFrame(delta_us) ) zm_terminate = true; + //} else { + //Debug(3,"Not sending frame"); + } curr_stream_time = frame_data->timestamp; if ( !paused ) { - curr_frame_id += (replay_rate>0) ? 1 : -1; + // +/- 1? What if we are skipping frames? + curr_frame_id += (replay_rate>0) ? frame_mod : -1*frame_mod; + if ( (mode == MODE_SINGLE) && ((unsigned int)curr_frame_id == event_data->frame_count) ) { Debug(2, "Have mode==MODE_SINGLE and at end of event, looping back to start"); curr_frame_id = 1; } + frame_data = &event_data->frames[curr_frame_id-1]; + + // sending the frame may have taken some time, so reload now + gettimeofday(&now, NULL); + uint64_t now_usec = (now.tv_sec * 1000000 + now.tv_usec); + // frame_data->delta is the time since last frame as a float in seconds + // but what if we are skipping frames? We need the distance from the last frame sent + // Also, what about reverse? needs to be absolute value + + // There are two ways to go about this, not sure which is correct. + // you can calculate the relationship between now and the start + // or calc the relationship from the last frame. I think from the start is better as it self-corrects + + if ( last_frame_offset ) { + // We assume that we are going forward and the next frame is in the future. + delta_us = frame_data->offset * 1000000 - (now_usec-start_usec); + // - (now_usec - start_usec); + Debug(2, "New delta_us now %" PRIu64 " - start %" PRIu64 " = %d offset %" PRId64 " - elapsed = %dusec", + now_usec, start_usec, now_usec-start_usec, frame_data->offset * 1000000, delta_us); + } else { + Debug(2, "No last frame_offset, no sleep"); + delta_us = 0; + } + last_frame_offset = frame_data->offset * 1000000; + if ( send_frame && type != STREAM_MPEG ) { - Debug(3, "dUs: %d", delta_us); - if ( delta_us ) + if ( delta_us > 0 ) { + Debug( 3, "dUs: %d", delta_us ); usleep(delta_us); + Debug(3, "Done sleeping: %d usec", delta_us); + } } } else { + delta_us = ((1000000 * ZM_RATE_BASE)/((base_fps?base_fps:1)*(replay_rate?abs(replay_rate*2):2))); + + Debug(2,"Sleeping %d because 1000000 * ZM_RATE_BASE(%d) / ( base_fps (%f), replay_rate(%d)", + (unsigned long)((1000000 * ZM_RATE_BASE)/((base_fps?base_fps:1)*abs(replay_rate*2))), + ZM_RATE_BASE, + (base_fps?base_fps:1), + (replay_rate?abs(replay_rate*2):200) + ); + if ( delta_us > 0 and delta_us < 100000 ) { usleep((unsigned long)((1000000 * ZM_RATE_BASE)/((base_fps?base_fps:1)*abs(replay_rate*2)))); + } else { + //Error("Not sleeping!"); + usleep(100000); + } } } // end while ! zm_terminate #if HAVE_LIBAVCODEC diff --git a/src/zm_eventstream.h b/src/zm_eventstream.h index 81e1641d6..5e7d91bb2 100644 --- a/src/zm_eventstream.h +++ b/src/zm_eventstream.h @@ -79,6 +79,7 @@ class EventStream : public StreamBase { int curr_frame_id; double curr_stream_time; bool send_frame; + struct timeval start; // clock time when started the event EventData *event_data; FFmpeg_Input *ffmpeg_input; @@ -95,6 +96,7 @@ class EventStream : public StreamBase { public: EventStream() { mode = DEFAULT_MODE; + replay_rate = DEFAULT_RATE; forceEventChange = false; @@ -109,7 +111,6 @@ class EventStream : public StreamBase { input_codec = 0; ffmpeg_input = NULL; - } void setStreamStart( uint64_t init_event_id, unsigned int init_frame_id ); void setStreamStart( int monitor_id, time_t event_time ); diff --git a/src/zm_ffmpeg.cpp b/src/zm_ffmpeg.cpp index f5130bd66..bdc9354db 100644 --- a/src/zm_ffmpeg.cpp +++ b/src/zm_ffmpeg.cpp @@ -65,8 +65,9 @@ void log_libav_callback( void *ptr, int level, const char *fmt, va_list vargs ) } } +static bool bInit = false; + void FFMPEGInit() { - static bool bInit = false; if ( !bInit ) { if ( logDebugging() ) @@ -77,7 +78,7 @@ void FFMPEGInit() { av_log_set_callback(log_libav_callback); else Info("Not enabling ffmpeg logs, as LOG_FFMPEG is disabled in options"); -#if LIBAVCODEC_VERSION_CHECK(58, 18, 0, 64, 0) +#if LIBAVFORMAT_VERSION_CHECK(58, 9, 0, 64, 0) #else av_register_all(); #endif @@ -86,6 +87,11 @@ void FFMPEGInit() { } } +void FFMPEGDeInit() { + avformat_network_deinit(); + bInit = false; +} + #if HAVE_LIBAVUTIL enum _AVPIXELFORMAT GetFFMPEGPixelFormat(unsigned int p_colours, unsigned p_subpixelorder) { enum _AVPIXELFORMAT pf; @@ -279,7 +285,9 @@ static void zm_log_fps(double d, const char *postfix) { } void zm_dump_frame(const AVFrame *frame,const char *text) { - Debug(1, "%s: format %d %s sample_rate %" PRIu32 " nb_samples %d channels %d layout %d", + Debug(1, "%s: format %d %s sample_rate %" PRIu32 " nb_samples %d channels %d" + " duration %" PRId64 + " layout %d pts %" PRId64, text, frame->format, av_get_sample_fmt_name((AVSampleFormat)frame->format), @@ -287,10 +295,12 @@ void zm_dump_frame(const AVFrame *frame,const char *text) { frame->nb_samples, #if LIBAVCODEC_VERSION_CHECK(56, 8, 0, 60, 100) frame->channels, + frame->pkt_duration, #else -0, +0, 0, #endif - frame->channel_layout + frame->channel_layout, + frame->pts ); } @@ -310,7 +320,8 @@ void zm_dump_codecpar ( const AVCodecParameters *par ) { #endif void zm_dump_codec(const AVCodecContext *codec) { - Debug(1, "Dumping codec_context codec_type(%d) codec_id(%d) width(%d) height(%d) timebase(%d/%d) format(%s)", + Debug(1, "Dumping codec_context codec_type(%d) codec_id(%d) width(%d) height(%d) timebase(%d/%d) format(%s)\n" + "gop_size %d max_b_frames %d me_cmp %d me_range %d qmin %d qmax %d", codec->codec_type, codec->codec_id, codec->width, @@ -318,11 +329,17 @@ void zm_dump_codec(const AVCodecContext *codec) { codec->time_base.num, codec->time_base.den, #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - (codec->pix_fmt == AV_PIX_FMT_NONE ? "none" : av_get_pix_fmt_name(codec->pix_fmt)) + (codec->pix_fmt == AV_PIX_FMT_NONE ? "none" : av_get_pix_fmt_name(codec->pix_fmt)), #else - "unsupported on avconv" + "unsupported on avconv", #endif -); + codec->gop_size, + codec->max_b_frames, + codec->me_cmp, + codec->me_range, + codec->qmin, + codec->qmax + ); } /* "user interface" functions */ @@ -346,9 +363,9 @@ void zm_dump_stream_format(AVFormatContext *ic, int i, int index, int is_output) Debug(1, "ids [0x%x]", st->id); if (lang) Debug(1, "language (%s)", lang->value); - Debug(1, "frames:%d, frame_size:%d stream timebase: %d/%d codec timebase: %d/%d", - st->codec_info_nb_frames, codec->frame_size, st->time_base.num, st->time_base.den, - st->codec->time_base.num, st->codec->time_base.den + Debug(1, "frames:%d, frame_size:%d stream timebase: %d/%d", + st->codec_info_nb_frames, codec->frame_size, + st->time_base.num, st->time_base.den ); avcodec_string(buf, sizeof(buf), st->codec, is_output); Debug(1, "codec: %s", buf); @@ -367,17 +384,14 @@ void zm_dump_stream_format(AVFormatContext *ic, int i, int index, int is_output) display_aspect_ratio.num, display_aspect_ratio.den); } - if ( st->codec->codec_type == AVMEDIA_TYPE_VIDEO ) { + if ( codec->codec_type == AVMEDIA_TYPE_VIDEO ) { int fps = st->avg_frame_rate.den && st->avg_frame_rate.num; int tbn = st->time_base.den && st->time_base.num; - int tbc = st->codec->time_base.den && st->codec->time_base.num; if (fps) zm_log_fps(av_q2d(st->avg_frame_rate), "fps"); if (tbn) zm_log_fps(1 / av_q2d(st->time_base), "stream tb numerator"); - if (tbc) - zm_log_fps(1 / av_q2d(st->codec->time_base), "codec time base:"); } if (st->disposition & AV_DISPOSITION_DEFAULT) @@ -424,6 +438,10 @@ unsigned int zm_av_packet_ref( AVPacket *dst, AVPacket *src ) { av_new_packet(dst,src->size); memcpy(dst->data, src->data, src->size); dst->flags = src->flags; + dst->pts = src->pts; + dst->dts = src->dts; + dst->duration = src->duration; + dst->stream_index = src->stream_index; return 0; } #endif @@ -443,6 +461,14 @@ bool is_video_stream( AVStream * stream ) { return false; } +bool is_video_context( AVCodecContext *codec_context ) { + return + #if (LIBAVCODEC_VERSION_CHECK(52, 64, 0, 64, 0) || LIBAVUTIL_VERSION_CHECK(50, 14, 0, 14, 0)) + ( codec_context->codec_type == AVMEDIA_TYPE_VIDEO ); + #else + ( codec_context->codec_type == CODEC_TYPE_VIDEO ); + #endif +} bool is_audio_stream( AVStream * stream ) { #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) @@ -459,6 +485,15 @@ bool is_audio_stream( AVStream * stream ) { return false; } +bool is_audio_context( AVCodecContext *codec_context ) { + return + #if (LIBAVCODEC_VERSION_CHECK(52, 64, 0, 64, 0) || LIBAVUTIL_VERSION_CHECK(50, 14, 0, 14, 0)) + ( codec_context->codec_type == AVMEDIA_TYPE_AUDIO ); + #else + ( codec_context->codec_type == CODEC_TYPE_AUDIO ); + #endif +} + int zm_receive_frame( AVCodecContext *context, AVFrame *frame, AVPacket &packet ) { int ret; #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) @@ -493,15 +528,20 @@ int zm_receive_frame( AVCodecContext *context, AVFrame *frame, AVPacket &packet # else int frameComplete = 0; while ( !frameComplete ) { - if ( (ret = zm_avcodec_decode_video( context, frame, &frameComplete, &packet )) < 0 ) { - Error( "Unable to decode frame at frame: %s, continuing", - av_make_error_string(ret).c_str() ); + if ( is_video_context(context) ) { + ret = zm_avcodec_decode_video(context, frame, &frameComplete, &packet); + } else { + ret = avcodec_decode_audio4(context, frame, &frameComplete, &packet); + } + if ( ret < 0 ) { + Error("Unable to decode frame: %s", av_make_error_string(ret).c_str()); return 0; } - } + } // end while !frameComplete #endif return 1; } // end int zm_receive_frame( AVCodecContext *context, AVFrame *frame, AVPacket &packet ) + void dumpPacket(AVStream *stream, AVPacket *pkt, const char *text) { char b[10240]; diff --git a/src/zm_ffmpeg.h b/src/zm_ffmpeg.h index ce0ee0cf5..81068d2bf 100644 --- a/src/zm_ffmpeg.h +++ b/src/zm_ffmpeg.h @@ -199,6 +199,7 @@ extern "C" { /* A single function to initialize ffmpeg, to avoid multiple initializations */ void FFMPEGInit(); +void FFMPEGDeInit(); #if HAVE_LIBAVUTIL enum _AVPIXELFORMAT GetFFMPEGPixelFormat(unsigned int p_colours, unsigned p_subpixelorder); @@ -331,8 +332,11 @@ unsigned int zm_av_packet_ref(AVPacket *dst, AVPacket *src); int check_sample_fmt(AVCodec *codec, enum AVSampleFormat sample_fmt); -bool is_video_stream( AVStream * stream ); -bool is_audio_stream( AVStream * stream ); +bool is_video_stream(AVStream *); +bool is_audio_stream(AVStream *); +bool is_video_context(AVCodec *); +bool is_audio_context(AVCodec *); + int zm_receive_frame( AVCodecContext *context, AVFrame *frame, AVPacket &packet ); void dumpPacket(AVStream *, AVPacket *,const char *text=""); #ifndef HAVE_LIBSWRESAMPLE diff --git a/src/zm_ffmpeg_camera.cpp b/src/zm_ffmpeg_camera.cpp index 8617f898d..088049b7b 100644 --- a/src/zm_ffmpeg_camera.cpp +++ b/src/zm_ffmpeg_camera.cpp @@ -144,7 +144,10 @@ FfmpegCamera::~FfmpegCamera() { Close(); - avformat_network_deinit(); + if ( capture ) { + Terminate(); + } + FFMPEGDeInit(); } int FfmpegCamera::PrimeCapture() { @@ -239,6 +242,7 @@ int FfmpegCamera::OpenFfmpeg() { } else { Warning("Unknown method (%s)", method.c_str()); } +//#av_dict_set(&opts, "timeout", "10000000", 0); // in microseconds. if ( ret < 0 ) { Warning("Could not set rtsp_transport method '%s'", method.c_str()); @@ -411,22 +415,21 @@ int FfmpegCamera::OpenFfmpeg() { // Open the codec #if !LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 8, 0) - Debug ( 1, "Calling avcodec_open" ); - if ( avcodec_open(mVideoCodecContext, mVideoCodec) < 0 ){ + ret = avcodec_open(mVideoCodecContext, mVideoCodec); #else - Debug ( 1, "Calling video avcodec_open2" ); ret = avcodec_open2(mVideoCodecContext, mVideoCodec, &opts); +#endif AVDictionaryEntry *e = NULL; while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) { - Warning("Option %s not recognized by ffmpeg", e->key); + Warning( "Option %s not recognized by ffmpeg", e->key); } - av_dict_free(&opts); -#endif if ( ret < 0 ) { Error("Unable to open codec for video stream from %s", mPath.c_str()); + av_dict_free(&opts); return -1; } - } // end if success opening codec + zm_dump_codec(mVideoCodecContext); + } if ( mVideoCodecContext->hwaccel != NULL ) { Debug(1, "HWACCEL in use"); @@ -434,15 +437,23 @@ int FfmpegCamera::OpenFfmpeg() { Debug(1, "HWACCEL not in use"); } if ( mAudioStreamId >= 0 ) { + if ( (mAudioCodec = avcodec_find_decoder( #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - mAudioCodecContext = avcodec_alloc_context3(NULL); - avcodec_parameters_to_context(mAudioCodecContext, mFormatContext->streams[mAudioStreamId]->codecpar); + mFormatContext->streams[mAudioStreamId]->codecpar->codec_id #else - mAudioCodecContext = mFormatContext->streams[mAudioStreamId]->codec; + mFormatContext->streams[mAudioStreamId]->codec->codec_id #endif - if ( (mAudioCodec = avcodec_find_decoder(mAudioCodecContext->codec_id)) == NULL ) { + )) == NULL ) { Debug(1, "Can't find codec for audio stream from %s", mPath.c_str()); } else { +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + mAudioCodecContext = avcodec_alloc_context3(mAudioCodec); + avcodec_parameters_to_context( mAudioCodecContext, mFormatContext->streams[mAudioStreamId]->codecpar ); +#else + mAudioCodecContext = mFormatContext->streams[mAudioStreamId]->codec; + // = avcodec_alloc_context3(mAudioCodec); +#endif + Debug(1, "Audio Found decoder"); zm_dump_stream_format(mFormatContext, mAudioStreamId, 0, 0); // Open the codec @@ -483,6 +494,11 @@ int FfmpegCamera::Close() { } + if ( videoStore ) { + delete videoStore; + videoStore = NULL; + } + if ( mVideoCodecContext ) { avcodec_close(mVideoCodecContext); Debug(1,"After codec close"); @@ -513,7 +529,7 @@ int FfmpegCamera::Close() { int FfmpegCamera::FfmpegInterruptCallback(void *ctx) { //FfmpegCamera* camera = reinterpret_cast(ctx); - + //Debug(4, "FfmpegInterruptCallback"); return zm_terminate; } diff --git a/src/zm_ffmpeg_input.cpp b/src/zm_ffmpeg_input.cpp index e9ae04920..3cafdf953 100644 --- a/src/zm_ffmpeg_input.cpp +++ b/src/zm_ffmpeg_input.cpp @@ -164,9 +164,10 @@ AVFrame *FFmpeg_Input::get_frame( int stream_id ) { #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) ret = avcodec_send_packet(context, &packet); if ( ret < 0 ) { - av_strerror( ret, errbuf, AV_ERROR_MAX_STRING_SIZE ); - Error( "Unable to send packet at frame %d: %s, continuing", streams[packet.stream_index].frame_count, errbuf ); - zm_av_packet_unref( &packet ); + av_strerror(ret, errbuf, AV_ERROR_MAX_STRING_SIZE); + Error("Unable to send packet at frame %d: %s, continuing", + streams[packet.stream_index].frame_count, errbuf); + zm_av_packet_unref(&packet); continue; } @@ -243,38 +244,44 @@ AVFrame *FFmpeg_Input::get_frame( int stream_id, double at ) { seek_target = av_rescale_q(seek_target, AV_TIME_BASE_Q, input_format_context->streams[stream_id]->time_base); Debug(1, "Getting frame from stream %d at %" PRId64, stream_id, seek_target); - if ( frame ) { - if ( (frame->pts + frame->pkt_duration) > seek_target ) { - // The current frame is still the valid picture. - Debug(2,"Returning previous frame which is still good"); - return frame; - } - if ( frame->pts < seek_target ) { - Debug(2, "Frame pts %" PRId64 " duration %" PRId64, frame->pts, frame->pkt_duration); - while ( frame && (frame->pts < seek_target) ) { - if ( ! get_frame(stream_id) ) - return frame; - } - return frame; - } - } - int ret; - if ( frame ) { - if ( ( ret = av_seek_frame(input_format_context, stream_id, seek_target, AVSEEK_FLAG_ANY) < 0 ) ) { - Error("Unable to seek in stream"); - return NULL; - } - } else { - // Must go for a keyframe - if ( ( ret = av_seek_frame(input_format_context, stream_id, seek_target, - AVSEEK_FLAG_FRAME + if ( !frame ) { + // Don't have a frame yet, so get a keyframe before the timestamp + if ( ( ret = av_seek_frame( + input_format_context, stream_id, seek_target, AVSEEK_FLAG_FRAME ) < 0 ) ) { Error("Unable to seek in stream"); return NULL; } + // Have to grab a frame to update our current frame to know where we are + get_frame(stream_id); + } // end if ! frame + + if ( frame->pts > seek_target ) { + zm_dump_frame(frame, "frame->pts > seek_target, seek backwards"); + // our frame must be beyond our seek target. so go backwards to before it + if ( ( ret = av_seek_frame(input_format_context, stream_id, seek_target, + AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME + ) < 0 ) ) { + Error("Unable to seek in stream"); + return NULL; + } + // Have to grab a frame to update our current frame to know where we are + get_frame(stream_id); + zm_dump_frame(frame, "frame->pts > seek_target, got"); + } // end if frame->pts > seek_target + + // Seeking seems to typically seek to a keyframe, so then we have to decode until we get the frame we want. + if ( frame->pts <= seek_target ) { + zm_dump_frame(frame, "pts <= seek_target"); + while ( frame && (frame->pts < seek_target) ) { + if ( ! get_frame(stream_id) ) + return frame; + } + return frame; } + return get_frame(stream_id); } // end AVFrame *FFmpeg_Input::get_frame( int stream_id, struct timeval at) diff --git a/src/zm_file_camera.cpp b/src/zm_file_camera.cpp index e9342c006..be26993d3 100644 --- a/src/zm_file_camera.cpp +++ b/src/zm_file_camera.cpp @@ -97,7 +97,7 @@ int FileCamera::PreCapture() { } int FileCamera::Capture( ZMPacket &zm_packet ) { - return zm_packet.image->ReadJpeg( path, colours, subpixelorder ) ; + return zm_packet.image->ReadJpeg( path, colours, subpixelorder ) ? 1 : -1; } int FileCamera::PostCapture() { diff --git a/src/zm_logger.cpp b/src/zm_logger.cpp index f6fc37a6f..ec019f392 100644 --- a/src/zm_logger.cpp +++ b/src/zm_logger.cpp @@ -253,8 +253,6 @@ void Logger::initialise(const std::string &id, const Options &options) { } void Logger::terminate() { - Debug(1, "Terminating Logger"); - if ( mFileLevel > NOLOG ) closeFile(); @@ -573,6 +571,7 @@ void Logger::logPrint( bool hex, const char * const filepath, const int line, co free(filecopy); if ( level <= FATAL ) { + log_mutex.unlock(); logTerm(); zmDbClose(); if ( level <= PANIC ) diff --git a/src/zm_monitor.cpp b/src/zm_monitor.cpp index ea0386e03..61f896ede 100644 --- a/src/zm_monitor.cpp +++ b/src/zm_monitor.cpp @@ -487,7 +487,7 @@ void Monitor::Load(MYSQL_ROW dbrow, bool load_zones=true, Purpose p = QUERY) { // Change \n to actual line feeds char *token_ptr = label_format; const char *token_string = "\n"; - while( ( token_ptr = strstr(token_ptr, token_string) ) ) { + while ( ( token_ptr = strstr(token_ptr, token_string) ) ) { if ( *(token_ptr+1) ) { *token_ptr = '\n'; token_ptr++; @@ -762,10 +762,15 @@ Monitor *Monitor::Load(unsigned int p_id, bool load_zones, Purpose purpose) { } } #endif + if ( config.record_diag_images ) { + diag_path_r = stringtf("%s/%d/diag-r.jpg", storage->Path(), id); + diag_path_d = stringtf("%s/%d/diag-d.jpg", storage->Path(), id); + } return monitor; } // end Monitor *Monitor::Load(unsigned int p_id, bool load_zones, Purpose purpose) + bool Monitor::connect() { Debug(3, "Connecting to monitor. Purpose is %d", purpose ); #if ZM_MEM_MAPPED @@ -1121,6 +1126,7 @@ unsigned int Monitor::GetLastWriteIndex() const { } uint64_t Monitor::GetLastEventId() const { +#if 0 Debug(2, "mem_ptr(%x), size(%d) State(%d) last_read_index(%d) last_read_time(%d) last_event(%" PRIu64 ")", mem_ptr, shared_data->size, @@ -1129,6 +1135,7 @@ uint64_t Monitor::GetLastEventId() const { shared_data->last_read_time, shared_data->last_event_id ); +#endif return shared_data->last_event_id; } @@ -1189,11 +1196,12 @@ double Monitor::GetFPS() const { /* I think this returns the # of micro seconds that we should sleep in order to maintain the desired analysis rate */ useconds_t Monitor::GetAnalysisRate() { +<<<<<<< HEAD capture_fps = GetFPS(); if ( !analysis_fps_limit ) { return 0; } else if ( analysis_fps_limit > capture_fps ) { - Warning( "Analysis fps (%.2f) is greater than capturing fps (%.2f)", analysis_fps_limit, capture_fps ); + Warning("Analysis fps (%.2f) is greater than capturing fps (%.2f)", analysis_fps_limit, capture_fps); return 0; } else { return( ( 1000000 / analysis_fps_limit ) - ( 1000000 / capture_fps ) ); @@ -1204,10 +1212,10 @@ void Monitor::UpdateAdaptiveSkip() { if ( config.opt_adaptive_skip ) { double capturing_fps = GetFPS(); 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 ); + 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 ) ) ) { - Info( "Enabling adaptive skip feature" ); + Info("Enabling adaptive skip feature"); adaptive_skip = true; } } else { @@ -1218,8 +1226,8 @@ void Monitor::UpdateAdaptiveSkip() { 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)-1 ); - strncpy( trigger_data->trigger_text, force_text, sizeof(trigger_data->trigger_text)-1 ); + strncpy(trigger_data->trigger_cause, force_cause, sizeof(trigger_data->trigger_cause)-1); + strncpy(trigger_data->trigger_text, force_text, sizeof(trigger_data->trigger_text)-1); } void Monitor::ForceAlarmOff() { @@ -1266,7 +1274,7 @@ void Monitor::actionResume() { shared_data->action |= RESUME; } -int Monitor::actionBrightness( int p_brightness ) { +int Monitor::actionBrightness(int p_brightness) { if ( purpose != CAPTURE ) { if ( p_brightness >= 0 ) { shared_data->brightness = p_brightness; @@ -1274,10 +1282,10 @@ int Monitor::actionBrightness( int p_brightness ) { int wait_loops = 10; while ( shared_data->action & SET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to set brightness" ); - return( -1 ); + Warning("Timed out waiting to set brightness"); + return -1; } } } else { @@ -1285,19 +1293,19 @@ int Monitor::actionBrightness( int p_brightness ) { int wait_loops = 10; while ( shared_data->action & GET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to get brightness" ); - return( -1 ); + Warning("Timed out waiting to get brightness"); + return -1; } } } - return( shared_data->brightness ); + return shared_data->brightness; } - return( camera->Brightness( p_brightness ) ); -} + return camera->Brightness(p_brightness); +} // end int Monitor::actionBrightness(int p_brightness) -int Monitor::actionContrast( int p_contrast ) { +int Monitor::actionContrast(int p_contrast) { if ( purpose != CAPTURE ) { if ( p_contrast >= 0 ) { shared_data->contrast = p_contrast; @@ -1305,10 +1313,10 @@ int Monitor::actionContrast( int p_contrast ) { int wait_loops = 10; while ( shared_data->action & SET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to set contrast" ); - return( -1 ); + Warning("Timed out waiting to set contrast"); + return -1; } } } else { @@ -1316,19 +1324,19 @@ int Monitor::actionContrast( int p_contrast ) { int wait_loops = 10; while ( shared_data->action & GET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to get contrast" ); - return( -1 ); + Warning("Timed out waiting to get contrast"); + return -1; } } } - return( shared_data->contrast ); + return shared_data->contrast; } - return( camera->Contrast( p_contrast ) ); -} + return camera->Contrast(p_contrast); +} // end int Monitor::actionContrast(int p_contrast) -int Monitor::actionHue( int p_hue ) { +int Monitor::actionHue(int p_hue) { if ( purpose != CAPTURE ) { if ( p_hue >= 0 ) { shared_data->hue = p_hue; @@ -1336,10 +1344,10 @@ int Monitor::actionHue( int p_hue ) { int wait_loops = 10; while ( shared_data->action & SET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to set hue" ); - return( -1 ); + Warning("Timed out waiting to set hue"); + return -1; } } } else { @@ -1347,19 +1355,19 @@ int Monitor::actionHue( int p_hue ) { int wait_loops = 10; while ( shared_data->action & GET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to get hue" ); - return( -1 ); + Warning("Timed out waiting to get hue"); + return -1; } } } - return( shared_data->hue ); + return shared_data->hue; } - return( camera->Hue( p_hue ) ); -} + return camera->Hue(p_hue); +} // end int Monitor::actionHue(int p_hue) -int Monitor::actionColour( int p_colour ) { +int Monitor::actionColour(int p_colour) { if ( purpose != CAPTURE ) { if ( p_colour >= 0 ) { shared_data->colour = p_colour; @@ -1367,10 +1375,10 @@ int Monitor::actionColour( int p_colour ) { int wait_loops = 10; while ( shared_data->action & SET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to set colour" ); - return( -1 ); + Warning("Timed out waiting to set colour"); + return -1; } } } else { @@ -1378,19 +1386,19 @@ int Monitor::actionColour( int p_colour ) { int wait_loops = 10; while ( shared_data->action & GET_SETTINGS ) { if ( wait_loops-- ) { - usleep( 100000 ); + usleep(100000); } else { - Warning( "Timed out waiting to get colour" ); - return( -1 ); + Warning("Timed out waiting to get colour"); + return -1; } } } - return( shared_data->colour ); + return shared_data->colour; } - return( camera->Colour( p_colour ) ); -} + return camera->Colour(p_colour); +} // end int Monitor::actionColour(int 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; @@ -1431,7 +1439,7 @@ 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; @@ -1451,33 +1459,33 @@ void Monitor::DumpZoneImage( const char *zone_string ) { colour = RGB_WHITE; } } - zone_image->Fill( colour, 2, zones[i]->GetPolygon() ); - zone_image->Outline( colour, zones[i]->GetPolygon() ); + zone_image->Fill(colour, 2, zones[i]->GetPolygon()); + zone_image->Outline(colour, zones[i]->GetPolygon()); } if ( extra_zone.getNumCoords() ) { - zone_image->Fill( extra_colour, 2, extra_zone ); - zone_image->Outline( extra_colour, extra_zone ); + zone_image->Fill(extra_colour, 2, extra_zone); + zone_image->Outline(extra_colour, extra_zone); } static char filename[PATH_MAX]; - snprintf( filename, sizeof(filename), "Zones%d.jpg", id ); - zone_image->WriteJpeg( filename ); + snprintf(filename, sizeof(filename), "Zones%d.jpg", id); + zone_image->WriteJpeg(filename); delete zone_image; -} +} // end void Monitor::DumpZoneImage(const char *zone_string) -void Monitor::DumpImage( Image *dump_image ) const { +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 ); - snprintf( new_filename, sizeof(new_filename), "Monitor%d-new.jpg", id ); - if ( dump_image->WriteJpeg( new_filename ) ) - rename( new_filename, filename ); + snprintf(filename, sizeof(filename), "Monitor%d.jpg", id); + snprintf(new_filename, sizeof(new_filename), "Monitor%d-new.jpg", id); + if ( dump_image->WriteJpeg(new_filename) ) + rename(new_filename, filename); } -} +} // end void Monitor::DumpImage(Image *dump_image) -bool Monitor::CheckSignal( const Image *image ) { +bool Monitor::CheckSignal(const Image *image) { static bool static_undef = true; /* RGB24 colors */ static uint8_t red_val; @@ -1543,11 +1551,11 @@ bool Monitor::CheckSignal( const Image *image ) { } } } // end for < signal_check_points - Debug(1,"SignalCheck: %d points, colour_val(%d)", signal_check_points, colour_val); + Debug(1, "SignalCheck: %d points, colour_val(%d)", signal_check_points, colour_val); return false; } // end if signal_check_points return true; -} +} // end bool Monitor::CheckSignal(const Image *image) void Monitor::CheckAction() { struct timeval now; @@ -1698,6 +1706,10 @@ bool Monitor::Analyse() { score += 100; } Warning("%s: %s", SIGNAL_CAUSE, signalText); + if ( event && !signal ) { + Info("%s: %03d - Closing event %" PRIu64 ", signal loss", name, image_count, event->Id()); + closeEvent(); + } if ( !event ) { if ( cause.length() ) cause += ", "; @@ -1770,19 +1782,18 @@ bool Monitor::Analyse() { if ( event ) { Debug(2,"Have event in mocard"); - if ( section_length ) { - // TODO: Wouldn't this be clearer if we just did something like if now - event->start > section_length ? - int section_mod = timestamp->tv_sec % section_length; - Debug(3, "Section length (%d) Last Section Mod(%d), tv_sec(%d) new section mod(%d)", - section_length, last_section_mod, timestamp->tv_sec, section_mod); - // This is not clear, but basically due to pauses, etc we might not get section_mod == 0 - if ( ( section_mod < last_section_mod ) && ( timestamp->tv_sec >= 10 ) ) { - Info("%s: %03d - Closing event %llu, section end forced ", name, analysis_image_count, event->Id()); - closeEvent(); - last_section_mod = 0; - } else { - last_section_mod = section_mod; - } + if ( section_length + && ( ( timestamp->tv_sec - video_store_data->recording.tv_sec ) >= section_length ) + && ( ! ( timestamp->tv_sec % section_length ) ) + ) { + + Info("%s: %03d - Closing event %" PRIu64 ", section end forced %d - %d = %d >= %d", + name, image_count, event->Id(), + timestamp->tv_sec, video_store_data->recording.tv_sec, + timestamp->tv_sec - video_store_data->recording.tv_sec, + section_length + ); + closeEvent(); } // end if section_length } // end if event @@ -1936,7 +1947,6 @@ bool Monitor::Analyse() { closeEvent(); } shared_data->state = state = IDLE; - last_section_mod = 0; trigger_data->trigger_state = TRIGGER_CANCEL; } // end if ( trigger_data->trigger_state != TRIGGER_OFF ) @@ -1987,7 +1997,7 @@ void Monitor::Reload() { Debug(1, "Reloading monitor %s", name); if ( event ) { - Info( "%s: %03d - Closing event %" PRIu64 ", reloading", name, image_count, event->Id() ); + Info("%s: %03d - Closing event %" PRIu64 ", reloading", name, image_count, event->Id()); closeEvent(); } @@ -2040,9 +2050,9 @@ void Monitor::ReloadLinkedMonitors(const char *p_linked_monitors) { 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' ) { + 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 { @@ -2120,7 +2130,7 @@ int Monitor::LoadMonitors(std::string sql, Monitor **&monitors, Purpose purpose) return 0; } int n_monitors = mysql_num_rows(result); - Debug( 1, "Got %d monitors", n_monitors ); + 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++ ) { @@ -2135,7 +2145,7 @@ int Monitor::LoadMonitors(std::string sql, Monitor **&monitors, Purpose purpose) mysql_free_result(result); return n_monitors; -} +} // end int Monitor::LoadMonitors(std::string sql, Monitor **&monitors, Purpose purpose) #if ZM_HAS_V4L int Monitor::LoadLocalMonitors(const char *device, Monitor **&monitors, Purpose purpose) { @@ -2147,7 +2157,7 @@ int Monitor::LoadLocalMonitors(const char *device, Monitor **&monitors, Purpose if ( staticConfig.SERVER_ID ) sql += stringtf(" AND ServerId=%d", staticConfig.SERVER_ID); return LoadMonitors(sql, monitors, purpose); -} +} // end int Monitor::LoadLocalMonitors(const char *device, Monitor **&monitors, Purpose purpose) #endif // ZM_HAS_V4L int Monitor::LoadRemoteMonitors(const char *protocol, const char *host, const char *port, const char *path, Monitor **&monitors, Purpose purpose) { @@ -2158,17 +2168,17 @@ int Monitor::LoadRemoteMonitors(const char *protocol, const char *host, const ch if ( protocol ) sql += stringtf(" AND Protocol = '%s' and Host = '%s' and Port = '%s' and Path = '%s'", protocol, host, port, path); return LoadMonitors(sql, monitors, purpose); -} +} // end int Monitor::LoadRemoteMonitors -int Monitor::LoadFileMonitors( const char *file, Monitor **&monitors, Purpose purpose ) { +int Monitor::LoadFileMonitors(const char *file, Monitor **&monitors, Purpose purpose) { std::string sql = load_monitor_sql + " WHERE Function != 'None' AND Type = 'File'"; if ( file[0] ) sql += " AND Path='" + std::string(file) + "'"; if ( staticConfig.SERVER_ID ) { - sql += stringtf( " AND ServerId=%d", staticConfig.SERVER_ID ); + sql += stringtf(" AND ServerId=%d", staticConfig.SERVER_ID); } return LoadMonitors(sql, monitors, purpose); -} +} // end int Monitor::LoadFileMonitors #if HAVE_LIBAVFORMAT int Monitor::LoadFfmpegMonitors(const char *file, Monitor **&monitors, Purpose purpose) { @@ -2180,7 +2190,7 @@ int Monitor::LoadFfmpegMonitors(const char *file, Monitor **&monitors, Purpose p sql += stringtf(" AND ServerId=%d", staticConfig.SERVER_ID); } return LoadMonitors(sql, monitors, purpose); -} +} // end int Monitor::LoadFfmpegMonitors #endif // HAVE_LIBAVFORMAT /* Returns 0 on success, even if no new images are available (transient error) @@ -2385,10 +2395,10 @@ int Monitor::Capture() { shared_data->action &= ~GET_SETTINGS; } if ( shared_data->action & SET_SETTINGS ) { - camera->Brightness( shared_data->brightness ); - camera->Hue( shared_data->hue ); - camera->Colour( shared_data->colour ); - camera->Contrast( shared_data->contrast ); + camera->Brightness(shared_data->brightness); + camera->Hue(shared_data->hue); + camera->Colour(shared_data->colour); + camera->Contrast(shared_data->contrast); shared_data->action &= ~SET_SETTINGS; } return captureResult; @@ -2425,12 +2435,12 @@ void Monitor::TimestampImage( Image *ts_image, const struct timeval *ts_time ) c continue; } } - *d_ptr++ = *s_ptr++; } - *d_ptr = '\0'; - ts_image->Annotate( label_text, label_coord, label_size ); - } -} + *d_ptr++ = *s_ptr++; + } // end while + *d_ptr = '\0'; + ts_image->Annotate( label_text, label_coord, label_size ); +} // end void Monitor::TimestampImage bool Monitor::closeEvent() { if ( event ) { @@ -2448,24 +2458,22 @@ bool Monitor::closeEvent() { event = NULL; delete e; e = NULL; - }, event); + }, event); #else - delete event; - event = NULL; + delete event; + event = NULL; #endif - video_store_data->recording = (struct timeval){0}; - return true; - } - return false; -} + video_store_data->recording = (struct timeval){0}; + return true; +} // end bool Monitor::closeEvent() -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; - Storage *storage = this->getStorage(); + ref_image.Delta(comp_image, &delta_image); if ( config.record_diag_images ) { static char diag_path[PATH_MAX] = ""; @@ -2489,14 +2497,14 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z 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()) + if ( !zone->IsPreclusive() ) zone->ClearAlarm(); if ( !zone->IsInactive() ) { continue; } Debug(3, "Blanking inactive zone %s", zone->Label()); delta_image.Fill(RGB_BLACK, zone->GetPolygon()); - } + } // end foreach zone // Check preclusive zones first for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { @@ -2506,30 +2514,32 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z } 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 ) ) { + 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) ) { alarm = true; score += zone->Score(); zone->SetAlarm(); - Debug( 3, "Zone is alarmed, zone score = %d", zone->Score() ); - zoneSet.insert( zone->Label() ); + Debug(3, "Zone is alarmed, zone score = %d", zone->Score()); + zoneSet.insert(zone->Label()); //zone->ResetStats(); } else { // check if end of alarm - if (old_zone_alarmed) { - Debug(3, "Preclusive Zone %s alarm Ends. Previous score: %d", zone->Label(), old_zone_score); - if (old_zone_score > 0) { + if ( old_zone_alarmed ) { + Debug(3, "Preclusive Zone %s alarm Ends. Previous score: %d", + zone->Label(), old_zone_score); + if ( old_zone_score > 0 ) { zone->SetExtendAlarmCount(zone->GetExtendAlarmFrames()); } - if (zone->CheckExtendAlarmCount()) { - alarm=true; + if ( zone->CheckExtendAlarmCount() ) { + alarm = true; zone->SetAlarm(); } else { zone->ClearAlarm(); } } - } - } + } // end if CheckAlarms + } // end foreach zone Coord alarm_centre; int top_score = -1; @@ -2544,13 +2554,13 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z if ( !zone->IsActive() || zone->IsPreclusive()) { continue; } - Debug( 3, "Checking active zone %s", zone->Label() ); - if ( zone->CheckAlarms( &delta_image ) ) { + Debug(3, "Checking active zone %s", zone->Label()); + 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() ); + 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 ) { top_score = zone->Score(); @@ -2558,7 +2568,7 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z } } } - } + } // end foreach zone if ( alarm ) { for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { @@ -2567,12 +2577,12 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z if ( !zone->IsInclusive() ) { continue; } - Debug( 3, "Checking inclusive zone %s", zone->Label() ); - if ( zone->CheckAlarms( &delta_image ) ) { + Debug(3, "Checking inclusive zone %s", zone->Label()); + if ( zone->CheckAlarms(&delta_image) ) { alarm = true; score += zone->Score(); zone->SetAlarm(); - Debug( 3, "Zone is alarmed, zone score = %d", zone->Score() ); + 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 ) { @@ -2580,8 +2590,8 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z alarm_centre = zone->GetAlarmCentre(); } } - } - } + } // end if CheckAlarm + } // end foreach zone } else { // Find all alarm pixels in exclusive zones for ( int n_zone = 0; n_zone < n_zones; n_zone++ ) { @@ -2589,32 +2599,33 @@ unsigned int Monitor::DetectMotion( const Image &comp_image, Event::StringSet &z if ( !zone->IsExclusive() ) { continue; } - Debug( 3, "Checking exclusive zone %s", zone->Label() ); - if ( zone->CheckAlarms( &delta_image ) ) { + Debug(3, "Checking exclusive zone %s", zone->Label()); + 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() ); + Debug(3, "Zone is alarmed, zone score = %d", zone->Score()); + zoneSet.insert(zone->Label()); } - } + } // end foreach zone } // end if alarm or not - } + } // end if alarm 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, analysis_image_count ); + Info("Got alarm centre at %d,%d, at count %d", + shared_data->alarm_x, shared_data->alarm_y, analysis_image_count); } else { shared_data->alarm_x = shared_data->alarm_y = -1; } // This is a small and innocent hack to prevent scores of 0 being returned in alarm state - return score?score:alarm; -} + return score ? score : alarm; +} // end MotionDetect -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 ); @@ -2720,9 +2731,9 @@ void Monitor::get_ref_image() { snap->unlock(); } -std::vector Monitor::Groups() { +std::vector Monitor::Groups() { // At the moment, only load groups once. - if ( ! groups.size() ) { + if ( !groups.size() ) { std::string sql = stringtf( "SELECT Id,ParentId,Name FROM Groups WHERE Groups.Id IN " "(SELECT GroupId FROM Groups_Monitors WHERE MonitorId=%d)",id); @@ -2742,14 +2753,13 @@ std::vector Monitor::Groups() { mysql_free_result(result); } return groups; -} +} // end Monitor::Groups() StringVector Monitor::GroupNames() { StringVector groupnames; - for(Group * g: Groups()) { + for ( Group * g: Groups() ) { groupnames.push_back(std::string(g->Name())); -Debug(1,"Groups: %s", g->Name()); + Debug(1,"Groups: %s", g->Name()); } return groupnames; -} - +} // end Monitor::GroupNames() diff --git a/src/zm_monitor.h b/src/zm_monitor.h index dddf399b1..ac1e1f6b6 100644 --- a/src/zm_monitor.h +++ b/src/zm_monitor.h @@ -311,10 +311,12 @@ protected: unsigned int last_camera_bytes; - Image delta_image; - Image ref_image; - Image alarm_image; // Used in creating analysis images, will be initialized in Analysis - Image write_image; // Used when creating snapshot images + Image delta_image; + Image ref_image; + Image alarm_image; // Used in creating analysis images, will be initialized in Analysis + Image write_image; // Used when creating snapshot images + std::string diag_path_r; + std::string diag_path_d; Purpose purpose; // What this monitor has been created to do int event_count; @@ -337,15 +339,15 @@ protected: EventCloseMode event_close_mode; #if ZM_MEM_MAPPED - int map_fd; - char mem_file[PATH_MAX]; + int map_fd; + char mem_file[PATH_MAX]; #else // ZM_MEM_MAPPED - int shm_id; + int shm_id; #endif // ZM_MEM_MAPPED - off_t mem_size; - unsigned char *mem_ptr; - SharedData *shared_data; - TriggerData *trigger_data; + off_t mem_size; + unsigned char *mem_ptr; + SharedData *shared_data; + TriggerData *trigger_data; VideoStoreData *video_store_data; struct timeval *shared_timestamps; diff --git a/src/zm_packetqueue.cpp b/src/zm_packetqueue.cpp index 4de77be1c..35e639b93 100644 --- a/src/zm_packetqueue.cpp +++ b/src/zm_packetqueue.cpp @@ -255,7 +255,7 @@ void zm_packetqueue::clearQueue() { mutex.lock(); ZMPacket *packet = NULL; int delete_count = 0; - while(!pktQueue.empty()) { + while ( !pktQueue.empty() ) { packet = pktQueue.front(); packet_counts[packet->packet.stream_index] -= 1; pktQueue.pop_front(); @@ -288,7 +288,6 @@ ZMPacket *zm_packetqueue::get_analysis_packet() { mutex.lock(); while ( ((! pktQueue.size()) || ( analysis_it == pktQueue.end() )) && !zm_terminate ) { Debug(2,"waiting. Queue size %d analysis_it == end? %d", pktQueue.size(), ( analysis_it == pktQueue.end() ) ); - condition->wait(); } diff --git a/src/zm_stream.cpp b/src/zm_stream.cpp index a24780b3e..3370ae92f 100644 --- a/src/zm_stream.cpp +++ b/src/zm_stream.cpp @@ -54,29 +54,34 @@ bool StreamBase::loadMonitor(int monitor_id) { bool StreamBase::checkInitialised() { if ( !monitor ) { - Fatal( "Cannot stream, not initialised" ); + Fatal("Cannot stream, not initialised"); return false; } return true; } void StreamBase::updateFrameRate(double fps) { - base_fps = fps; frame_mod = 1; - if ( !fps ) { - Debug(1, "Zero fps in updateFrameRate. Setting frame_mod=1 and effective_fps=0.0"); + if ( (fps < 0) || !fps || isinf(fps) ) { + Debug(1, "Zero or negative fps %f in updateFrameRate. Setting frame_mod=1 and effective_fps=0.0", fps); effective_fps = 0.0; + base_fps = 0.0; return; } + base_fps = fps; effective_fps = (base_fps*abs(replay_rate))/ZM_RATE_BASE; - Debug(3, "FPS:%.2f, MXFPS:%.2f, BFPS:%.2f, EFPS:%.2f, FM:%d", fps, maxfps, base_fps, effective_fps, frame_mod); + frame_mod = 1; + Debug(3, "FPS:%.2f, MaxFPS:%.2f, BaseFPS:%.2f, EffectiveFPS:%.2f, FrameMod:%d, replay_rate(%d)", + fps, maxfps, base_fps, effective_fps, frame_mod, replay_rate); // Min frame repeat? - while( effective_fps > maxfps ) { + // We want to keep the frame skip easy... problem is ... if effective = 31 and max = 30 then we end up with 15.5 fps. + while ( effective_fps > maxfps ) { effective_fps /= 2.0; frame_mod *= 2; - Debug(3, "EffectiveFPS:%.2f, FrameMod:%d", effective_fps, frame_mod); + Debug(3, "Changing fps to be < max %.2f EffectiveFPS:%.2f, FrameMod:%d", + maxfps, effective_fps, frame_mod); } -} +} // void StreamBase::updateFrameRate(double fps) bool StreamBase::checkCommandQueue() { if ( sd >= 0 ) { @@ -352,7 +357,7 @@ void StreamBase::openComms() { gettimeofday(&last_comm_update, NULL); } // end if connKey > 0 - Debug(3, "comms open"); + Debug(3, "comms open at %s", loc_sock_path); } // end void StreamBase::openComms() void StreamBase::closeComms() { diff --git a/src/zm_stream.h b/src/zm_stream.h index f9364bbef..4f4f144a3 100644 --- a/src/zm_stream.h +++ b/src/zm_stream.h @@ -160,6 +160,7 @@ public: scale = DEFAULT_SCALE; } void setStreamReplayRate( int p_rate ) { + Debug(2,"Setting replay_rate %d", p_rate); replay_rate = p_rate; } void setStreamMaxFPS( double p_maxfps ) { diff --git a/src/zm_user.cpp b/src/zm_user.cpp index 3ccb0aec9..cbcda28f4 100644 --- a/src/zm_user.cpp +++ b/src/zm_user.cpp @@ -249,15 +249,19 @@ User *zmLoadAuthUser( const char *auth, bool use_remote_addr ) { //Function to check Username length bool checkUser ( const char *username) { - if ( strlen(username) > 32) { + if ( ! username ) return false; - } + if ( strlen(username) > 32 ) + return false; + return true; } //Function to check password length bool checkPass (const char *password) { - if ( strlen(password) > 64) { + if ( !password ) return false; - } + if ( strlen(password) > 64 ) + return false; + return true; } diff --git a/src/zm_videostore.cpp b/src/zm_videostore.cpp index 91084d65e..de049931f 100644 --- a/src/zm_videostore.cpp +++ b/src/zm_videostore.cpp @@ -46,7 +46,10 @@ VideoStore::VideoStore( Monitor *p_monitor ) { +<<<<<<< HEAD monitor = p_monitor; +======= +>>>>>>> storageareas video_in_stream = p_video_in_stream; video_in_stream_index = -1; audio_in_stream = p_audio_in_stream; @@ -78,7 +81,13 @@ VideoStore::VideoStore( fifo = NULL; #endif #endif +<<<<<<< HEAD FFMPEGInit(); +======= + + // In future, we should just pass in the codec context instead of the stream. Don't really need the stream. + video_in_ctx = video_in_stream->codec; +>>>>>>> storageareas video_start_pts = 0; audio_next_pts = 0; @@ -111,18 +120,30 @@ bool VideoStore::open() { filename, format); return false; } else { +<<<<<<< HEAD Debug(4, "Success alocating out ctx"); +======= + Debug(4, "Success allocating out ctx"); +>>>>>>> storageareas } } // end if ! oc Debug(2, "Success opening output contect"); AVDictionary *pmetadata = NULL; +<<<<<<< HEAD ret = av_dict_set(&pmetadata, "title", "Zoneminder Security Recording", 0); if ( ret < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__); +======= + int dsr = + av_dict_set(&pmetadata, "title", "Zoneminder Security Recording", 0); + if ( dsr < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__); +>>>>>>> storageareas oc->metadata = pmetadata; out_format = oc->oformat; + out_format->flags |= AVFMT_TS_NONSTRICT; // allow non increasing dts +<<<<<<< HEAD if ( video_in_stream ) { video_in_stream_index = video_in_stream->index; #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) @@ -321,9 +342,149 @@ bool VideoStore::open() { #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); +======= + video_out_codec = avcodec_find_encoder(video_in_ctx->codec_id); + if ( !video_out_codec ) { +#if (LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 11, 0) && (LIBAVFORMAT_VERSION_MICRO >= 100)) + Fatal("Could not find encoder for '%s'", avcodec_get_name(video_out_ctx->codec_id)); +#else + Fatal("Could not find encoder for '%d'", video_out_ctx->codec_id); +#endif + } + + video_out_stream = avformat_new_stream(oc, NULL); + if ( !video_out_stream ) { + Error("Unable to create video out stream"); + return; + } else { + Debug(2, "Success creating video out stream"); + } + +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + // by allocating our own copy, we don't run into the problems when we free the streams + video_out_ctx = avcodec_alloc_context3(video_out_codec); + // Since we are not re-encoding, all we have to do is copy the parameters + // Copy params from instream to ctx + ret = avcodec_parameters_to_context(video_out_ctx, video_in_stream->codecpar); + if ( ret < 0 ) { + Error("Could not initialize video_out_ctx parameters"); + return; + } +#else + video_out_ctx = video_out_stream->codec; + // This will wipe out the codec defaults + ret = avcodec_copy_context(video_out_ctx, video_in_ctx); + if ( ret < 0 ) { + Fatal("Unable to copy in video ctx to out video ctx %s", + av_make_error_string(ret).c_str()); + } else { + Debug(3, "Success copying ctx"); + } +#endif + + // Just copy them from the in, no reason to choose different + video_out_ctx->time_base = video_in_ctx->time_base; + 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"); + video_out_ctx->time_base = AV_TIME_BASE_Q; + } + + zm_dump_codec(video_out_ctx); + +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + //// Fix deprecated formats + switch ( video_out_ctx->pix_fmt ) { + case AV_PIX_FMT_YUVJ422P : + video_out_ctx->pix_fmt = AV_PIX_FMT_YUV422P; + break; + case AV_PIX_FMT_YUVJ444P : + video_out_ctx->pix_fmt = AV_PIX_FMT_YUV444P; + break; + case AV_PIX_FMT_YUVJ440P : + video_out_ctx->pix_fmt = AV_PIX_FMT_YUV440P; + break; + case AV_PIX_FMT_NONE : + case AV_PIX_FMT_YUVJ420P : + default: + video_out_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + break; + } + + if ( !video_out_ctx->codec_tag ) { + Debug(2, "No codec_tag"); + if ( + !oc->oformat->codec_tag + || + av_codec_get_id(oc->oformat->codec_tag, video_in_ctx->codec_tag) == video_out_ctx->codec_id + || + av_codec_get_tag(oc->oformat->codec_tag, video_in_ctx->codec_id) <= 0 + ) { + Warning("Setting codec tag"); + video_out_ctx->codec_tag = video_in_ctx->codec_tag; + } + } +#endif + + video_out_stream->time_base = video_in_stream->time_base; + if ( video_in_stream->avg_frame_rate.num ) { + Debug(3,"Copying avg_frame_rate (%d/%d)", + video_in_stream->avg_frame_rate.num, + video_in_stream->avg_frame_rate.den + ); + video_out_stream->avg_frame_rate = video_in_stream->avg_frame_rate; + } + if ( video_in_stream->r_frame_rate.num ) { + Debug(3,"Copying r_frame_rate (%d/%d) to out (%d/%d)", + video_in_stream->r_frame_rate.num, + video_in_stream->r_frame_rate.den , + video_out_stream->r_frame_rate.num, + video_out_stream->r_frame_rate.den + ); + video_out_stream->r_frame_rate = video_in_stream->r_frame_rate; + } +#if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0) +#if 0 + if ( video_out_ctx->codec_id == AV_CODEC_ID_H264 ) { + //video_out_ctx->level = 32;I// + video_out_ctx->bit_rate = 400*1024; + video_out_ctx->max_b_frames = 1; + if ( video_out_ctx->priv_data ) { + av_opt_set(video_out_ctx->priv_data, "crf", "1", AV_OPT_SEARCH_CHILDREN); + av_opt_set(video_out_ctx->priv_data, "preset", "ultrafast", 0); + } else { + Debug(2, "Not setting priv_data"); + } + } +#endif + ret = avcodec_parameters_from_context(video_out_stream->codecpar, video_out_ctx); + if ( ret < 0 ) { + Error("Could not initialize video_out_ctx parameters"); + return; + } else { + zm_dump_codec(video_out_ctx); + } + + zm_dump_codecpar(video_in_stream->codecpar); + zm_dump_codecpar(video_out_stream->codecpar); +#endif + Debug(3, + "Time bases: VIDEO in stream (%d/%d) in codec: (%d/%d) out " + "stream: (%d/%d) out codec (%d/%d)", + video_in_stream->time_base.num, video_in_stream->time_base.den, + video_in_ctx->time_base.num, video_in_ctx->time_base.den, + video_out_stream->time_base.num, video_out_stream->time_base.den, + video_out_ctx->time_base.num, video_out_ctx->time_base.den); + + if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) { +#if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0) + video_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; +#else + video_out_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER; +>>>>>>> storageareas #endif video_out_ctx = NULL; +<<<<<<< HEAD return false; } // end if can't open codec @@ -335,6 +496,39 @@ bool VideoStore::open() { video_out_ctx->codec_tag = av_codec_get_tag(oc->oformat->codec_tag, video_out_ctx->codec_id); Debug(2, "No codec_tag, setting to h264 ? "); +======= +#if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0) + AVDictionary *opts = 0; + if ( (ret = avcodec_open2(video_out_ctx, video_out_codec, &opts)) < 0 ) { + Warning("Can't open video codec (%s) %s", + video_out_codec->name, + av_make_error_string(ret).c_str() + ); + video_out_codec = NULL; + } + + AVDictionaryEntry *e = NULL; + while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) { + Warning("Encoder Option %s not recognized by ffmpeg codec", e->key); + } +#endif + + Monitor::Orientation orientation = monitor->getOrientation(); + if ( orientation ) { + if ( orientation == Monitor::ROTATE_0 ) { + } else if ( orientation == Monitor::ROTATE_90 ) { + dsr = av_dict_set(&video_out_stream->metadata, "rotate", "90", 0); + if ( dsr < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__); + } else if ( orientation == Monitor::ROTATE_180 ) { + dsr = av_dict_set(&video_out_stream->metadata, "rotate", "180", 0); + if ( dsr < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__); + } else if ( orientation == Monitor::ROTATE_270 ) { + dsr = av_dict_set(&video_out_stream->metadata, "rotate", "270", 0); + if ( dsr < 0 ) Warning("%s:%d: title set failed", __FILE__, __LINE__); + } else { + Warning("Unsupported Orientation(%d)", orientation); + } +>>>>>>> storageareas } video_out_stream = avformat_new_stream(oc, video_out_codec); @@ -351,63 +545,106 @@ bool VideoStore::open() { #else avcodec_copy_context(video_out_stream->codec, video_out_ctx); #endif + video_first_pts = 0; + video_first_dts = 0; + video_last_pts = 0; + video_last_dts = 0; + + audio_first_pts = 0; + audio_first_dts = 0; + audio_next_pts = 0; + audio_next_dts = 0; if ( audio_in_stream ) { +<<<<<<< HEAD audio_in_stream_index = audio_in_stream->index; #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) audio_in_ctx = avcodec_alloc_context3(NULL); ret = avcodec_parameters_to_context(audio_in_ctx, audio_in_stream->codecpar); audio_in_ctx->time_base = audio_in_stream->time_base; -#else - audio_in_ctx = audio_in_stream->codec; -#endif +======= + Debug(3, "Have audio stream"); - if ( audio_in_ctx->codec_id != AV_CODEC_ID_AAC ) { - static char error_buffer[256]; - avcodec_string(error_buffer, sizeof(error_buffer), audio_in_ctx, 0); - Debug(2, "Got something other than AAC (%s)", error_buffer); + if ( +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + audio_in_stream->codecpar->codec_id +>>>>>>> storageareas +#else + audio_in_stream->codec->codec_id +#endif + != AV_CODEC_ID_AAC ) { + + audio_out_codec = avcodec_find_encoder(AV_CODEC_ID_AAC); + if ( !audio_out_codec ) { + Error("Could not find codec for AAC"); + return; + } + +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + audio_out_stream = avformat_new_stream(oc, NULL); + audio_out_stream->time_base = audio_in_stream->time_base; + audio_out_ctx = avcodec_alloc_context3(audio_out_codec); + if ( !audio_out_ctx ) { + Error("could not allocate codec ctx for AAC"); + audio_out_stream = NULL; + return; + } +#else + audio_out_stream = avformat_new_stream(oc, audio_out_codec); + audio_out_ctx = audio_out_stream->codec; +#endif + audio_out_stream->time_base = audio_in_stream->time_base; if ( !setup_resampler() ) { return false; } } else { - Debug(3, "Got AAC"); + Debug(2, "Got AAC"); - audio_out_stream = -#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - avformat_new_stream(oc, (const AVCodec *)(audio_in_ctx->codec)); -#else - avformat_new_stream(oc, (AVCodec *)audio_in_ctx->codec); -#endif + audio_out_stream = avformat_new_stream(oc, NULL); if ( !audio_out_stream ) { - Error("Unable to create audio out stream"); - audio_out_stream = NULL; - } else { -#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - audio_out_ctx = avcodec_alloc_context3(audio_out_codec); - // Copy params from instream to ctx - if ( (ret = avcodec_parameters_to_context(audio_out_ctx, audio_in_stream->codecpar) ) < 0 ) { - Error("Unable to copy audio params to ctx %s\n", - av_make_error_string(ret).c_str()); - } - // Then from ctx to out_stream - ret = avcodec_parameters_from_context(audio_out_stream->codecpar, audio_out_ctx); - if ( ret < 0 ) { - Error("Unable to copy audio params to stream %s\n", - av_make_error_string(ret).c_str()); - } + Error("Could not allocate new stream"); + return; + } + audio_out_stream->time_base = audio_in_stream->time_base; - if ( !audio_out_ctx->codec_tag ) { - audio_out_ctx->codec_tag = av_codec_get_tag( - oc->oformat->codec_tag, audio_in_ctx->codec_id); - Debug(2, "Setting audio codec tag to %d", audio_out_ctx->codec_tag); - } +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + // Just use the ctx to copy the parameters over + audio_out_ctx = avcodec_alloc_context3(audio_out_codec); + if ( !audio_out_ctx ) { + Error("Could not allocate new output_context"); + return; + } + + // We don't actually care what the time_base is.. + audio_out_ctx->time_base = audio_in_stream->time_base; + + // Copy params from instream to ctx + ret = avcodec_parameters_to_context( + audio_out_ctx, audio_in_stream->codecpar); + if ( ret < 0 ) { + Error("Unable to copy audio params to ctx %s", + av_make_error_string(ret).c_str()); + } + ret = avcodec_parameters_from_context( + audio_out_stream->codecpar, audio_out_ctx); + if ( ret < 0 ) { + Error("Unable to copy audio params to stream %s", + av_make_error_string(ret).c_str()); + } #else - audio_out_ctx = audio_out_stream->codec; - ret = avcodec_copy_context(audio_out_ctx, audio_in_ctx); - audio_out_ctx->codec_tag = 0; + audio_out_ctx = audio_out_stream->codec; + ret = avcodec_copy_context(audio_out_ctx, audio_in_stream->codec); + if ( ret < 0 ) { + Error("Unable to copy audio ctx %s", + av_make_error_string(ret).c_str()); + audio_out_stream = NULL; + return; + } // end if + audio_out_ctx->codec_tag = 0; #endif +<<<<<<< HEAD if ( ret < 0 ) { Error("Unable to copy audio ctx %s", av_make_error_string(ret).c_str()); @@ -422,23 +659,49 @@ bool VideoStore::open() { } } // end if audio_out_stream } // end if is AAC +======= +>>>>>>> storageareas - if ( audio_out_stream ) { - if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) { + if ( audio_out_ctx->channels > 1 ) { + Warning("Audio isn't mono, changing it."); + audio_out_ctx->channels = 1; + } else { + Debug(3, "Audio is mono"); + } + } // end if is AAC + + if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) { #if LIBAVCODEC_VERSION_CHECK(56, 35, 0, 64, 0) +<<<<<<< HEAD audio_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; #else audio_out_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER; +======= + audio_out_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; +#else + audio_out_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER; +>>>>>>> storageareas #endif - } } } // end if audio_in_stream +<<<<<<< HEAD /* open the out file, if needed */ if ( !(out_format->flags & AVFMT_NOFILE) ) { if ( (ret = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE, NULL, NULL) ) < 0 ) { Error("Could not open out file '%s': %s", filename, av_make_error_string(ret).c_str()); +======= +} // VideoStore::VideoStore + +bool VideoStore::open() { + /* open the out file, if needed */ + if ( !(out_format->flags & AVFMT_NOFILE) ) { + ret = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE, NULL, NULL); + if ( ret < 0 ) { + Error("Could not open out file '%s': %s", filename, + av_make_error_string(ret).c_str()); +>>>>>>> storageareas return false; } } @@ -447,14 +710,27 @@ bool VideoStore::open() { if (audio_out_stream) zm_dump_stream_format(oc, 1, 0, 1); AVDictionary *opts = NULL; +<<<<<<< HEAD av_dict_set(&opts, "movflags", "frag_keyframe+empty_moov", 0); +======= + // av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0); + // 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+default_base_moof", 0); +>>>>>>> storageareas if ( (ret = avformat_write_header(oc, &opts)) < 0 ) { // if ((ret = avformat_write_header(oc, &opts)) < 0) { Warning("Unable to set movflags to frag_custom+dash+delay_moov"); /* Write the stream header, if any. */ ret = avformat_write_header(oc, NULL); +<<<<<<< HEAD } else if ( av_dict_count(opts) != 0 ) { Warning("some options not set\n"); +======= + } else if (av_dict_count(opts) != 0) { + Warning("some options not set"); +>>>>>>> storageareas } if ( opts ) av_dict_free(&opts); if ( ret < 0 ) { @@ -510,9 +786,31 @@ void VideoStore::flush_codecs() { pkt.data = NULL; pkt.size = 0; av_init_packet(&pkt); +<<<<<<< HEAD #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) if ( (ret = avcodec_receive_packet(video_out_ctx, &pkt)) < 0 ) { if ( AVERROR_EOF != ret ) { +======= +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + // Put encoder into flushing mode + avcodec_send_frame(audio_out_ctx, NULL); +#endif + + while (1) { +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + ret = avcodec_receive_packet(audio_out_ctx, &pkt); + if ( ret < 0 ) { + if ( AVERROR_EOF != ret ) { + Error("Error encoding audio while flushing (%d) (%s)", ret, + av_err2str(ret)); + } + break; + } +#else + int got_packet = 0; + ret = avcodec_encode_audio2(audio_out_ctx, &pkt, NULL, &got_packet); + if ( ret < 0 ) { +>>>>>>> storageareas Error("Error encoding audio while flushing (%d) (%s)", ret, av_err2str(ret)); } @@ -528,6 +826,7 @@ void VideoStore::flush_codecs() { break; } #endif +<<<<<<< HEAD write_video_packet(pkt); zm_av_packet_unref(&pkt); } // while have buffered frames @@ -570,6 +869,14 @@ VideoStore::~VideoStore() { Debug(2,"Different codecs between in and out"); flush_codecs(); } // end if buffers +======= + pkt.stream_index = audio_out_stream->index; + dumpPacket(audio_out_stream, &pkt, "writing flushed packet"); + av_interleaved_write_frame(oc, &pkt); + zm_av_packet_unref(&pkt); + } // while have buffered frames + } // end if audio_out_codec +>>>>>>> storageareas // Flush Queues Debug(1,"Flushing interleaved queues"); @@ -594,7 +901,11 @@ VideoStore::~VideoStore() { } else { Debug(3, "Not closing avio because we are not writing to a file."); } +<<<<<<< HEAD } // end if oc->pb +======= + } // end if ( oc->pb ) +>>>>>>> storageareas // I wonder if we should be closing the file first. // I also wonder if we really need to be doing all the ctx @@ -609,43 +920,54 @@ VideoStore::~VideoStore() { #endif video_in_ctx=NULL; - avcodec_close(video_out_ctx); + if ( video_out_codec ) { + avcodec_close(video_out_ctx); + Debug(4, "Success closing video_out_ctx"); + video_out_codec = NULL; + } // end if video_out_codec #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - //avcodec_free_context(&video_out_ctx); + avcodec_free_context(&video_out_ctx); #endif video_out_ctx = NULL; - Debug(4, "Success freeing video_out_ctx"); - } + } // end if video_out_stream + if ( audio_out_stream ) { if ( audio_in_codec ) { avcodec_close(audio_in_ctx); -#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - // We allocate and copy in newer ffmpeg, so need to free it - avcodec_free_context(&audio_in_ctx); -#endif - audio_in_ctx = NULL; + Debug(4, "Success closing audio_in_ctx"); audio_in_codec = NULL; } // end if audio_in_codec - avcodec_close(audio_out_ctx); #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - avcodec_free_context(&audio_out_ctx); + // We allocate and copy in newer ffmpeg, so need to free it + avcodec_free_context(&audio_in_ctx); #endif + Debug(4, "Success freeing audio_in_ctx"); + audio_in_ctx = NULL; + + if ( audio_out_ctx ) { + avcodec_close(audio_out_ctx); + Debug(4, "Success closing audio_out_ctx"); +#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) + avcodec_free_context(&audio_out_ctx); +#endif + } audio_out_ctx = NULL; + #if defined(HAVE_LIBAVRESAMPLE) || defined(HAVE_LIBSWRESAMPLE) if ( resample_ctx ) { -#if defined(HAVE_LIBSWRESAMPLE) + #if defined(HAVE_LIBSWRESAMPLE) if ( fifo ) { av_audio_fifo_free(fifo); fifo = NULL; } swr_free(&resample_ctx); -#else -#if defined(HAVE_LIBAVRESAMPLE) + #else + #if defined(HAVE_LIBAVRESAMPLE) avresample_close(resample_ctx); avresample_free(&resample_ctx); -#endif -#endif + #endif + #endif } if ( in_frame ) { av_frame_free(&in_frame); @@ -661,19 +983,8 @@ VideoStore::~VideoStore() { } #endif } // end if audio_out_stream -#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - if ( video_in_ctx ) { - avcodec_free_context(&video_in_ctx); - video_in_ctx = NULL; - } - if ( video_out_ctx ) { - avcodec_close(video_out_ctx); - avcodec_free_context(&video_out_ctx); - video_out_ctx = NULL; - } -#endif - /* free the stream */ + /* free the streams */ avformat_free_context(oc); } // VideoStore::~VideoStore() @@ -687,31 +998,45 @@ bool VideoStore::setup_resampler() { // Newer ffmpeg wants to keep everything separate... so have to lookup our own // decoder, can't reuse the one from the camera. - audio_in_codec = avcodec_find_decoder(audio_in_ctx->codec_id); - ret = avcodec_open2(audio_in_ctx, audio_in_codec, NULL); + audio_in_codec = + avcodec_find_decoder(audio_in_stream->codecpar->codec_id); + audio_in_ctx = avcodec_alloc_context3(audio_in_codec); + // Copy params from instream to ctx + ret = avcodec_parameters_to_context( + audio_in_ctx, audio_in_stream->codecpar); if ( ret < 0 ) { - Error("Can't open in codec!"); - return false; + Error("Unable to copy audio params to ctx %s", + av_make_error_string(ret).c_str()); } - audio_out_codec = avcodec_find_encoder(AV_CODEC_ID_AAC); - if ( !audio_out_codec ) { - Error("Could not find codec for AAC"); - return false; - } - - // Now copy them to the out stream - audio_out_stream = avformat_new_stream(oc, audio_out_codec); +#else +// codec is already open in ffmpeg_camera + audio_in_ctx = audio_in_stream->codec; + audio_in_codec = (AVCodec *)audio_in_ctx->codec; + //audio_in_codec = avcodec_find_decoder(audio_in_stream->codec->codec_id); +#endif #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - audio_out_ctx = avcodec_alloc_context3(audio_out_codec); - if ( !audio_out_ctx ) { - Error("could not allocate codec ctx for AAC"); - audio_out_stream = NULL; +#else +#if 0 + ret = avcodec_copy_context(audio_in_ctx, audio_in_stream->codec); + if ( ret < 0 ) { + Fatal("Unable to copy in video ctx to out video ctx %s", + av_make_error_string(ret).c_str()); + } else { + Debug(3, "Success copying ctx"); + } +#endif +#endif + + // if the codec is already open, nothing is done. + if ( (ret = avcodec_open2(audio_in_ctx, audio_in_codec, NULL)) < 0 ) { + Error("Can't open audio in codec!"); return false; } - audio_out_ctx = audio_out_stream->codec; -#endif + + Debug(2, "Got something other than AAC (%s)", audio_in_codec->name); + // Some formats (i.e. WAV) do not produce the proper channel layout if ( audio_in_ctx->channel_layout == 0 ) { Debug(2, "Setting input channel layout to mono"); @@ -725,10 +1050,8 @@ bool VideoStore::setup_resampler() { audio_out_ctx->sample_fmt = audio_in_ctx->sample_fmt; audio_out_ctx->channels = audio_in_ctx->channels; audio_out_ctx->channel_layout = audio_in_ctx->channel_layout; -#if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) -#else - audio_out_ctx->refcounted_frames = 1; -#endif + audio_out_ctx->sample_fmt = audio_in_ctx->sample_fmt; +#if LIBAVCODEC_VERSION_CHECK(56, 8, 0, 60, 100) if ( !audio_out_ctx->channel_layout ) { Debug(3, "Correcting channel layout from (%d) to (%d)", audio_out_ctx->channel_layout, @@ -736,7 +1059,7 @@ bool VideoStore::setup_resampler() { ); audio_out_ctx->channel_layout = av_get_default_channel_layout(audio_out_ctx->channels); } - +#endif if ( audio_out_codec->supported_samplerates ) { int found = 0; for ( unsigned int i = 0; audio_out_codec->supported_samplerates[i]; i++ ) { @@ -774,7 +1097,8 @@ bool VideoStore::setup_resampler() { ret = avcodec_open2(audio_out_ctx, audio_out_codec, &opts); av_dict_free(&opts); if ( ret < 0 ) { - Error("could not open codec (%d) (%s)", ret, av_make_error_string(ret).c_str()); + Error("could not open codec (%d) (%s)", + ret, av_make_error_string(ret).c_str()); audio_out_codec = NULL; audio_out_ctx = NULL; audio_out_stream = NULL; @@ -795,6 +1119,14 @@ bool VideoStore::setup_resampler() { avcodec_copy_context( audio_out_stream->codec, audio_out_ctx ); #endif + Debug(3, + "Time bases: AUDIO in stream (%d/%d) in codec: (%d/%d) out " + "stream: (%d/%d) out codec (%d/%d)", + audio_in_stream->time_base.num, audio_in_stream->time_base.den, + audio_in_ctx->time_base.num, audio_in_ctx->time_base.den, + audio_out_stream->time_base.num, audio_out_stream->time_base.den, + audio_out_ctx->time_base.num, audio_out_ctx->time_base.den); + Debug(1, "Audio in bit_rate (%d) sample_rate(%d) channels(%d) fmt(%d) " "layout(%d) frame_size(%d)", @@ -909,7 +1241,9 @@ bool VideoStore::setup_resampler() { out_frame->nb_samples = audio_out_ctx->frame_size; out_frame->format = audio_out_ctx->sample_fmt; +#if LIBAVCODEC_VERSION_CHECK(56, 8, 0, 60, 100) out_frame->channels = audio_out_ctx->channels; +#endif out_frame->channel_layout = audio_out_ctx->channel_layout; out_frame->sample_rate = audio_out_ctx->sample_rate; @@ -1009,7 +1343,7 @@ int VideoStore::writeVideoFramePacket( ZMPacket * zm_packet ) { zm_packet->out_frame->pkt_duration = 0; #endif - if ( ! video_start_pts ) { + if ( !video_start_pts ) { uint64_t temp = zm_packet->timestamp->tv_sec*(uint64_t)1000000; video_start_pts = temp + zm_packet->timestamp->tv_usec; Debug(2, "No video_lsat_pts, set to (%" PRId64 ") secs(%d=>%" PRId64 ") usecs(%d)", @@ -1218,14 +1552,11 @@ int VideoStore::writeAudioFramePacket(ZMPacket *zm_packet) { return 0; // FIXME -ve return codes do not free packet in ffmpeg_camera at // the moment } + dumpPacket(audio_in_stream, ipkt, "input packet"); if ( audio_out_codec ) { - Debug(3, "Have audio codec"); -#if defined(HAVE_LIBSWRESAMPLE) || defined(HAVE_LIBAVRESAMPLE) - - #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) - if ( (ret = avcodec_send_packet(audio_in_ctx, ipkt)) < 0 ) { - Error("avcodec_send_packet fail %s", av_make_error_string(ret).c_str()); + Debug(2, "Have output codec"); + if ( ! zm_receive_frame(audio_in_ctx, in_frame, *ipkt) ) { return 0; } @@ -1233,15 +1564,7 @@ int VideoStore::writeAudioFramePacket(ZMPacket *zm_packet) { Error("avcodec_receive_frame fail %s", av_make_error_string(ret).c_str()); return 0; } - Debug(2, - "In Frame: samples(%d), format(%d), sample_rate(%d), " - "channels(%d) channel layout(%d) pts(%" PRId64 ")", - in_frame->nb_samples, - in_frame->format, - in_frame->sample_rate, - in_frame->channels, - in_frame->channel_layout, - in_frame->pts); + zm_dump_frame(in_frame, "In frame from decode"); #else /** * Decode the audio frame stored in the packet. @@ -1266,50 +1589,12 @@ int VideoStore::writeAudioFramePacket(ZMPacket *zm_packet) { int frame_size = out_frame->nb_samples; in_frame->pts = audio_next_pts; - // Resample the in into the audioSampleBuffer until we proceed the whole - // decoded data - Debug(2, "Converting %d to %d samples", in_frame->nb_samples, out_frame->nb_samples); - #if defined(HAVE_LIBSWRESAMPLE) -#if 0 - ret = swr_convert(resample_ctx, - out_frame->data, frame_size, - (const uint8_t**)in_frame->data, - in_frame->nb_samples - ); -#else - ret = swr_convert_frame(resample_ctx, out_frame, in_frame); - av_frame_unref(in_frame); - if ( ret < 0 ) { - Error("Could not resample frame (error '%s')", - av_make_error_string(ret).c_str()); + if ( ! resample_audio() ) { + //av_frame_unref(in_frame); return 0; } -#endif - if ((ret = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + out_frame->nb_samples)) < 0) { - Error("Could not reallocate FIFO"); - return 0; - } - /** Store the new samples in the FIFO buffer. */ - ret = av_audio_fifo_write(fifo, (void **)out_frame->data, out_frame->nb_samples); - if ( ret < frame_size ) { - Error("Could not write data to FIFO on %d written", ret); - return 0; - } + zm_dump_frame(out_frame, "Out frame after resample"); - // Reset frame_size to output_frame_size - frame_size = audio_out_ctx->frame_size; - - // AAC requires 1024 samples per encode. Our input tends to be 160, so need to buffer them. - if ( frame_size > av_audio_fifo_size(fifo) ) { - return 0; - } - - if ( av_audio_fifo_read(fifo, (void **)out_frame->data, frame_size) < frame_size ) { - Error("Could not read data from FIFO"); - return 0; - } - out_frame->nb_samples = frame_size; - /// FIXME this is not the correct pts out_frame->pts = in_frame->pts; #else #if defined(HAVE_LIBAVRESAMPLE) @@ -1333,12 +1618,9 @@ int VideoStore::writeAudioFramePacket(ZMPacket *zm_packet) { Warning("Error reading resampled audio:"); return 0; } - #endif - #endif - zm_dump_frame(out_frame, "Out frame after resample"); + audio_next_pts = out_frame->pts + out_frame->nb_samples; av_init_packet(&opkt); - #if LIBAVCODEC_VERSION_CHECK(57, 64, 0, 64, 0) if ( (ret = avcodec_send_frame(audio_out_ctx, out_frame)) < 0 ) { Error("Could not send frame (error '%s')", @@ -1347,8 +1629,6 @@ int VideoStore::writeAudioFramePacket(ZMPacket *zm_packet) { return 0; } - // av_frame_unref( out_frame ); - if ( (ret = avcodec_receive_packet(audio_out_ctx, &opkt)) < 0 ) { if ( AVERROR(EAGAIN) == ret ) { // The codec may need more samples than it has, perfectly valid @@ -1381,68 +1661,50 @@ int VideoStore::writeAudioFramePacket(ZMPacket *zm_packet) { #else Error("Have audio codec but no resampler?!"); #endif - opkt.duration = out_frame->nb_samples; + opkt.duration = av_rescale_q(opkt.duration, + audio_in_stream->time_base, + audio_out_stream->time_base); + opkt.pts = av_rescale_q(opkt.pts, + audio_in_stream->time_base, + audio_out_stream->time_base); + opkt.dts = av_rescale_q(opkt.dts, + audio_in_stream->time_base, + audio_out_stream->time_base); + dumpPacket(audio_out_stream, &opkt, "raw opkt"); + } else { + Debug(2,"copying"); av_init_packet(&opkt); - Debug(5, "after init packet"); opkt.data = ipkt->data; opkt.size = ipkt->size; opkt.duration = ipkt->duration; } - // PTS is difficult, because of the buffering of the audio packets in the - // resampler. So we have to do it once we actually have a packet... - // audio_last_pts is the pts of ipkt, audio_next_pts is the last pts of the - // out - - // Scale the PTS of the outgoing packet to be the correct time base -#if 0 - if ( ipkt->pts != AV_NOPTS_VALUE ) { - if ( !audio_last_pts ) { - opkt.pts = 0; - Debug(1, "No audio_last_pts"); - } else { - if ( audio_last_pts > ipkt->pts ) { - Debug(1, "Resetting audio_start_pts from (%d) to (%d)", audio_last_pts, ipkt->pts); - opkt.pts = audio_next_pts + av_rescale_q(ipkt->pts, audio_in_stream->time_base, audio_out_stream->time_base); + if ( ipkt->duration && (ipkt->duration != AV_NOPTS_VALUE) ) { + opkt.duration = av_rescale_q( + ipkt->duration, + audio_in_stream->time_base, + audio_out_stream->time_base); + } + // Scale the PTS of the outgoing packet to be the correct time base + if ( ipkt->pts != AV_NOPTS_VALUE ) { + if ( !audio_first_pts ) { + opkt.pts = 0; + audio_first_pts = ipkt->pts; + Debug(1, "No audio_first_pts"); } else { - opkt.pts = audio_next_pts + av_rescale_q(ipkt->pts - audio_last_pts, audio_in_stream->time_base, audio_out_stream->time_base); + opkt.pts = av_rescale_q( + ipkt->pts - audio_first_pts, + audio_in_stream->time_base, + audio_out_stream->time_base); + Debug(2, "audio opkt.pts = %" PRId64 " from ipkt->pts(%" PRId64 ") - first_pts(%" PRId64 ")", + opkt.pts, ipkt->pts, audio_first_pts); } - Debug(2, "audio opkt.pts = %d from ipkt->pts(%d) - last_pts(%d)", opkt.pts, ipkt->pts, audio_last_pts); - } - audio_last_pts = ipkt->pts; - } else { - Debug(2, "opkt.pts = undef"); - opkt.pts = AV_NOPTS_VALUE; - } -#else - opkt.pts = audio_next_pts; - opkt.dts = audio_next_dts; -#endif - -#if 0 - if ( ipkt->dts == AV_NOPTS_VALUE ) { - // So if the in has no dts assigned... still need an out dts... so we use cur_dts? - - if ( audio_last_dts >= audio_in_stream->cur_dts ) { - Debug(1, "Resetting audio_last_dts from (%d) to cur_dts (%d)", audio_last_dts, audio_in_stream->cur_dts); - opkt.dts = audio_next_dts + av_rescale_q( audio_in_stream->cur_dts, AV_TIME_BASE_Q, audio_out_stream->time_base); } else { - opkt.dts = audio_next_dts + av_rescale_q( audio_in_stream->cur_dts - audio_last_dts, AV_TIME_BASE_Q, audio_out_stream->time_base); + Debug(2, "opkt.pts = undef"); + opkt.pts = AV_NOPTS_VALUE; } - audio_last_dts = audio_in_stream->cur_dts; - Debug(2, "opkt.dts = %d from video_in_stream->cur_dts(%d) - last_dts(%d)", opkt.dts, audio_in_stream->cur_dts, audio_last_dts); - } else { - if ( audio_last_dts >= ipkt->dts ) { - Debug(1, "Resetting audio_last_dts from (%d) to (%d)", audio_last_dts, ipkt->dts ); - opkt.dts = audio_next_dts + av_rescale_q(ipkt->dts, audio_in_stream->time_base, audio_out_stream->time_base); - } else { - opkt.dts = audio_next_dts + av_rescale_q(ipkt->dts - audio_last_dts, audio_in_stream->time_base, audio_out_stream->time_base); - Debug(2, "opkt.dts = %d from previous(%d) + ( ipkt->dts(%d) - last_dts(%d) )", opkt.dts, audio_next_dts, ipkt->dts, audio_last_dts ); - } - } -} -#endif + // audio_last_dts = ipkt->dts; if ( opkt.dts > opkt.pts ) { Debug(1, @@ -1499,3 +1761,75 @@ int VideoStore::write_packets( zm_packetqueue &queue ) { Debug(2, "Wrote %d queued packets", packet_count ); return packet_count; } // end int VideoStore::write_packets( PacketQueue &queue ) { + +int VideoStore::resample_audio() { + // Resample the in into the audioSampleBuffer until we process the whole + // decoded data. Note: pts does not survive resampling or converting +#if defined(HAVE_LIBSWRESAMPLE) || defined(HAVE_LIBAVRESAMPLE) +#if defined(HAVE_LIBSWRESAMPLE) + Debug(2, "Converting %d to %d samples using swresample", + in_frame->nb_samples, out_frame->nb_samples); + ret = swr_convert_frame(resample_ctx, out_frame, in_frame); + zm_dump_frame(out_frame, "Out frame after convert"); + + if ( ret < 0 ) { + Error("Could not resample frame (error '%s')", + av_make_error_string(ret).c_str()); + return 0; + } + if ((ret = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + out_frame->nb_samples)) < 0) { + Error("Could not reallocate FIFO"); + return 0; + } + /** Store the new samples in the FIFO buffer. */ + ret = av_audio_fifo_write(fifo, (void **)out_frame->data, out_frame->nb_samples); + if ( ret < in_frame->nb_samples ) { + Error("Could not write data to FIFO on %d written", ret); + return 0; + } + + // Reset frame_size to output_frame_size + int frame_size = audio_out_ctx->frame_size; + + // AAC requires 1024 samples per encode. Our input tends to be 160, so need to buffer them. + if ( frame_size > av_audio_fifo_size(fifo) ) { + return 0; + } + + if ( av_audio_fifo_read(fifo, (void **)out_frame->data, frame_size) < frame_size ) { + Error("Could not read data from FIFO"); + return 0; + } + out_frame->nb_samples = frame_size; +#else +#if defined(HAVE_LIBAVRESAMPLE) + ret = avresample_convert(resample_ctx, NULL, 0, 0, in_frame->data, + 0, in_frame->nb_samples); + if ( ret < 0 ) { + Error("Could not resample frame (error '%s')", + av_make_error_string(ret).c_str()); + return 0; + } + + int frame_size = audio_out_ctx->frame_size; + + int samples_available = avresample_available(resample_ctx); + if ( samples_available < frame_size ) { + Debug(1, "Not enough samples yet (%d)", samples_available); + return 0; + } + + // Read a frame audio data from the resample fifo + if ( avresample_read(resample_ctx, out_frame->data, frame_size) != + frame_size) { + Warning("Error reading resampled audio."); + return 0; + } +#endif +#endif +#else + Error("Have audio codec but no resampler?!"); + return 0; +#endif + return 1; +} // end int VideoStore::resample_audio diff --git a/src/zm_videostore.h b/src/zm_videostore.h index fd04889a4..4a87167df 100644 --- a/src/zm_videostore.h +++ b/src/zm_videostore.h @@ -42,9 +42,11 @@ int audio_in_stream_index; AVCodec *video_out_codec; AVCodecContext *video_out_ctx; + AVStream *video_out_stream; - AVStream *video_in_stream; - AVStream *audio_in_stream; + AVStream *video_in_stream; + + AVStream *audio_in_stream; // Move this into the object so that we aren't constantly allocating/deallocating it on the stack AVPacket opkt; @@ -63,6 +65,7 @@ int audio_in_stream_index; unsigned int frame_count; // The following are used when encoding the audio stream to AAC + AVStream *audio_out_stream; AVCodec *audio_out_codec; AVCodecContext *audio_out_ctx; #ifdef HAVE_LIBSWRESAMPLE @@ -98,6 +101,7 @@ int audio_in_stream_index; int64_t audio_next_dts; bool setup_resampler(); + int resample_audio(); public: VideoStore( diff --git a/src/zmc.cpp b/src/zmc.cpp index ad0ffb21d..47ab49c04 100644 --- a/src/zmc.cpp +++ b/src/zmc.cpp @@ -292,7 +292,7 @@ int main(int argc, char *argv[]) { struct DeltaTimeval delta_time; while ( !zm_terminate ) { - sigprocmask(SIG_BLOCK, &block_set, 0); + //sigprocmask(SIG_BLOCK, &block_set, 0); for ( int i = 0; i < n_monitors; i++ ) { monitors[i]->CheckAction(); @@ -345,8 +345,6 @@ int main(int argc, char *argv[]) { last_capture_times[i] = now; } // end foreach n_monitors - //Debug(2,"unblocking"); - sigprocmask(SIG_UNBLOCK, &block_set, 0); if ( result < 0 ) { // Failure, try reconnecting sleep(1); diff --git a/src/zms.cpp b/src/zms.cpp index 634e07030..0a3712938 100644 --- a/src/zms.cpp +++ b/src/zms.cpp @@ -85,6 +85,9 @@ int main( int argc, const char *argv[] ) { } zmLoadConfig(); + char log_id_string[32] = "zms"; + logInit( log_id_string ); + Debug(1,"rate %d", rate); const char *query = getenv("QUERY_STRING"); if ( query ) { @@ -95,7 +98,7 @@ int main( int argc, const char *argv[] ) { char *q_ptr = temp_query; char *parms[16]; // Shouldn't be more than this int parm_no = 0; - while( (parm_no < 16) && (parms[parm_no] = strtok(q_ptr, "&")) ) { + while ( (parm_no < 16) && (parms[parm_no] = strtok(q_ptr, "&")) ) { parm_no++; q_ptr = NULL; } @@ -130,6 +133,7 @@ int main( int argc, const char *argv[] ) { scale = atoi( value ); } else if ( !strcmp( name, "rate" ) ) { rate = atoi( value ); + Debug(2,"Setting rate to %d from %s", rate, value); } else if ( !strcmp( name, "maxfps" ) ) { maxfps = atof( value ); } else if ( !strcmp( name, "bitrate" ) ) { @@ -152,34 +156,21 @@ int main( int argc, const char *argv[] ) { connkey = atoi(value); } else if ( !strcmp( name, "buffer" ) ) { playback_buffer = atoi(value); - } else if ( config.opt_use_auth ) { - if ( strcmp( config.auth_relay, "none" ) == 0 ) { - if ( !strcmp( name, "user" ) ) { - username = value; - } - } else { - //if ( strcmp( config.auth_relay, "hashed" ) == 0 ) - { - if ( !strcmp( name, "auth" ) ) { - strncpy( auth, value, sizeof(auth)-1 ); - } - } - //else if ( strcmp( config.auth_relay, "plain" ) == 0 ) - { - if ( !strcmp( name, "user" ) ) { - username = UriDecode( value ); - } - if ( !strcmp( name, "pass" ) ) { - password = UriDecode( value ); - Debug( 1, "Have %s for password", password.c_str() ); - } - } - } - } + } else if ( !strcmp( name, "auth" ) ) { + strncpy( auth, value, sizeof(auth)-1 ); + } else if ( !strcmp( name, "user" ) ) { + username = UriDecode( value ); + } else if ( !strcmp( name, "pass" ) ) { + password = UriDecode(value); + Debug(1, "Have %s for password", password.c_str()); + } else { + Debug(1, "Unknown parameter passed to zms %s=%s", name, value); + } // end if possible parameter names } // end foreach parm + } else { + Fatal("No query string."); } // end if query - char log_id_string[32] = "zms"; if ( monitor_id ) { snprintf(log_id_string, sizeof(log_id_string), "zms_m%d", monitor_id); } else { @@ -323,5 +314,5 @@ int main( int argc, const char *argv[] ) { logTerm(); zmDbClose(); - return( 0 ); + return(0); } diff --git a/src/zmu.cpp b/src/zmu.cpp index a8ee61273..2ad1471d5 100644 --- a/src/zmu.cpp +++ b/src/zmu.cpp @@ -394,7 +394,7 @@ int main(int argc, char *argv[]) { //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } - } + } // end getopt loop if ( optind < argc ) { fprintf(stderr, "Extraneous options, "); @@ -425,50 +425,44 @@ int main(int argc, char *argv[]) { if ( config.opt_use_auth ) { if ( strcmp(config.auth_relay, "none") == 0 ) { - if ( !checkUser(username)) { - fprintf(stderr, "Error, username greater than allowed 32 characters\n"); - exit_zmu(-1); - } if ( !username ) { - fprintf(stderr, "Error, username must be supplied\n"); + Error("Username must be supplied"); exit_zmu(-1); } - if ( username ) { - user = zmLoadUser(username); - } - } else { - if ( !(username && password) && !auth ) { - fprintf(stderr, "Error, username and password or auth string must be supplied\n"); - exit_zmu(-1); - } if ( !checkUser(username)) { - fprintf(stderr, "Error, username greater than allowed 32 characters\n"); + Error("Username greater than allowed 32 characters"); exit_zmu(-1); } - if ( !checkPass(password)) { - fprintf(stderr, "Error, password greater than allowed 64 characters\n"); + + user = zmLoadUser(username); + } else { + + if ( !(username && password) && !auth ) { + Error("Username and password or auth string must be supplied"); exit_zmu(-1); } - //if ( strcmp( config.auth_relay, "hashed" ) == 0 ) - { - if ( auth ) { - user = zmLoadAuthUser(auth, false); - } + if ( auth ) { + user = zmLoadAuthUser(auth, false); } - //else if ( strcmp( config.auth_relay, "plain" ) == 0 ) - { - if ( username && password ) { - user = zmLoadUser(username, password); + if ( username && password ) { + if ( !checkUser(username)) { + Error("username greater than allowed 32 characters"); + exit_zmu(-1); } - } - } + if ( !checkPass(password)) { + Error("password greater than allowed 64 characters"); + exit_zmu(-1); + } + user = zmLoadUser(username, password); + } // end if username && password + } // end if relay or not if ( !user ) { - fprintf(stderr, "Error, unable to authenticate user\n"); - return exit_zmu(-1); + Error("Unable to authenticate user"); + exit_zmu(-1); } if ( !ValidateAccess(user, mon_id, function) ) { - fprintf(stderr, "Error, insufficient privileges for requested action\n"); + Error("Insufficient privileges for requested action"); exit_zmu(-1); } } // end if auth @@ -503,201 +497,201 @@ int main(int argc, char *argv[]) { if ( verbose ) { char timestamp_str[64] = "None"; if ( timestamp.tv_sec ) - strftime( timestamp_str, sizeof(timestamp_str), "%Y-%m-%d %H:%M:%S", localtime( ×tamp.tv_sec ) ); + strftime(timestamp_str, sizeof(timestamp_str), "%Y-%m-%d %H:%M:%S", localtime(×tamp.tv_sec)); if ( image_idx == -1 ) - printf( "Time of last image capture: %s.%02ld\n", timestamp_str, timestamp.tv_usec/10000 ); + printf("Time of last image capture: %s.%02ld\n", timestamp_str, timestamp.tv_usec/10000); else - printf( "Time of image %d capture: %s.%02ld\n", image_idx, timestamp_str, timestamp.tv_usec/10000 ); + printf("Time of image %d capture: %s.%02ld\n", image_idx, timestamp_str, timestamp.tv_usec/10000); } else { - if ( have_output ) printf( "%c", separator ); - printf( "%ld.%02ld", timestamp.tv_sec, timestamp.tv_usec/10000 ); + if ( have_output ) printf("%c", separator); + printf("%ld.%02ld", timestamp.tv_sec, timestamp.tv_usec/10000); have_output = true; } } if ( function & ZMU_READ_IDX ) { if ( verbose ) - printf( "Last read index: %d\n", monitor->GetLastReadIndex() ); + printf("Last read index: %d\n", monitor->GetLastReadIndex()); else { - if ( have_output ) printf( "%c", separator ); - printf( "%d", monitor->GetLastReadIndex() ); + if ( have_output ) printf("%c", separator); + printf("%d", monitor->GetLastReadIndex()); have_output = true; } } if ( function & ZMU_WRITE_IDX ) { - if ( verbose ) - printf( "Last write index: %d\n", monitor->GetLastWriteIndex() ); - else { - if ( have_output ) printf( "%c", separator ); - printf( "%d", monitor->GetLastWriteIndex() ); + if ( verbose ) { + printf("Last write index: %d\n", monitor->GetLastWriteIndex()); + } else { + if ( have_output ) printf("%c", separator); + printf("%d", monitor->GetLastWriteIndex()); have_output = true; } } if ( function & ZMU_EVENT ) { - if ( verbose ) - printf( "Last event id: %" PRIu64 "\n", monitor->GetLastEventId() ); - else { - if ( have_output ) printf( "%c", separator ); - printf( "%" PRIu64, monitor->GetLastEventId() ); + if ( verbose ) { + printf("Last event id: %" PRIu64 "\n", monitor->GetLastEventId()); + } else { + if ( have_output ) printf("%c", separator); + printf("%" PRIu64, monitor->GetLastEventId()); have_output = true; } } if ( function & ZMU_FPS ) { if ( verbose ) - printf( "Current capture rate: %.2f frames per second\n", monitor->GetFPS() ); + printf("Current capture rate: %.2f frames per second\n", monitor->GetFPS()); else { - if ( have_output ) printf( "%c", separator ); - printf( "%.2f", monitor->GetFPS() ); + if ( have_output ) printf("%c", separator); + printf("%.2f", monitor->GetFPS()); have_output = true; } } if ( function & ZMU_IMAGE ) { if ( verbose ) { if ( image_idx == -1 ) - printf( "Dumping last image captured to Monitor%d.jpg", monitor->Id() ); + printf("Dumping last image captured to Monitor%d.jpg", monitor->Id()); else - printf( "Dumping buffer image %d to Monitor%d.jpg", image_idx, monitor->Id() ); + printf("Dumping buffer image %d to Monitor%d.jpg", image_idx, monitor->Id()); if ( scale != -1 ) - printf( ", scaling by %d%%", scale ); - printf( "\n" ); + printf(", scaling by %d%%", scale); + printf("\n"); } - monitor->GetImage( image_idx, scale>0?scale:100 ); + monitor->GetImage(image_idx, scale>0?scale:100); } if ( function & ZMU_ZONES ) { if ( verbose ) - printf( "Dumping zone image to Zones%d.jpg\n", monitor->Id() ); - monitor->DumpZoneImage( zoneString ); + printf("Dumping zone image to Zones%d.jpg\n", monitor->Id()); + monitor->DumpZoneImage(zoneString); } if ( function & ZMU_ALARM ) { if ( verbose ) - printf( "Forcing alarm on\n" ); - monitor->ForceAlarmOn( config.forced_alarm_score, "Forced Web" ); + printf("Forcing alarm on\n"); + monitor->ForceAlarmOn(config.forced_alarm_score, "Forced Web"); while ( monitor->GetState() != Monitor::ALARM ) { // Wait for monitor to notice. usleep(1000); } - printf( "Alarmed event id: %" PRIu64 "\n", monitor->GetLastEventId() ); + printf("Alarmed event id: %" PRIu64 "\n", monitor->GetLastEventId()); } if ( function & ZMU_NOALARM ) { if ( verbose ) - printf( "Forcing alarm off\n" ); + printf("Forcing alarm off\n"); monitor->ForceAlarmOff(); } if ( function & ZMU_CANCEL ) { if ( verbose ) - printf( "Cancelling forced alarm on/off\n" ); + printf("Cancelling forced alarm on/off\n"); monitor->CancelForced(); } if ( function & ZMU_RELOAD ) { if ( verbose ) - printf( "Reloading monitor settings\n" ); + printf("Reloading monitor settings\n"); monitor->actionReload(); } if ( function & ZMU_ENABLE ) { if ( verbose ) - printf( "Enabling event generation\n" ); + printf("Enabling event generation\n"); monitor->actionEnable(); } if ( function & ZMU_DISABLE ) { if ( verbose ) - printf( "Disabling event generation\n" ); + printf("Disabling event generation\n"); monitor->actionDisable(); } if ( function & ZMU_SUSPEND ) { if ( verbose ) - printf( "Suspending event generation\n" ); + printf("Suspending event generation\n"); monitor->actionSuspend(); } if ( function & ZMU_RESUME ) { if ( verbose ) - printf( "Resuming event generation\n" ); + printf("Resuming event generation\n"); monitor->actionResume(); } if ( function & ZMU_QUERY ) { char monString[16382] = ""; - monitor->DumpSettings( monString, verbose ); - printf( "%s\n", monString ); + monitor->DumpSettings(monString, verbose); + printf("%s\n", monString); } if ( function & ZMU_BRIGHTNESS ) { if ( verbose ) { if ( brightness >= 0 ) - printf( "New brightness: %d\n", monitor->actionBrightness( brightness ) ); + printf("New brightness: %d\n", monitor->actionBrightness(brightness)); else - printf( "Current brightness: %d\n", monitor->actionBrightness() ); + printf("Current brightness: %d\n", monitor->actionBrightness()); } else { - if ( have_output ) printf( "%c", separator ); + if ( have_output ) printf("%c", separator); if ( brightness >= 0 ) - printf( "%d", monitor->actionBrightness( brightness ) ); + printf("%d", monitor->actionBrightness(brightness)); else - printf( "%d", monitor->actionBrightness() ); + printf("%d", monitor->actionBrightness()); have_output = true; } } if ( function & ZMU_CONTRAST ) { if ( verbose ) { if ( contrast >= 0 ) - printf( "New brightness: %d\n", monitor->actionContrast( contrast ) ); + printf("New brightness: %d\n", monitor->actionContrast(contrast)); else - printf( "Current contrast: %d\n", monitor->actionContrast() ); + printf("Current contrast: %d\n", monitor->actionContrast()); } else { - if ( have_output ) printf( "%c", separator ); + if ( have_output ) printf("%c", separator); if ( contrast >= 0 ) - printf( "%d", monitor->actionContrast( contrast ) ); + printf("%d", monitor->actionContrast(contrast)); else - printf( "%d", monitor->actionContrast() ); + printf("%d", monitor->actionContrast()); have_output = true; } } if ( function & ZMU_HUE ) { if ( verbose ) { if ( hue >= 0 ) - printf( "New hue: %d\n", monitor->actionHue( hue ) ); + printf("New hue: %d\n", monitor->actionHue(hue)); else - printf( "Current hue: %d\n", monitor->actionHue() ); + printf("Current hue: %d\n", monitor->actionHue()); } else { - if ( have_output ) printf( "%c", separator ); + if ( have_output ) printf("%c", separator); if ( hue >= 0 ) - printf( "%d", monitor->actionHue( hue ) ); + printf("%d", monitor->actionHue(hue)); else - printf( "%d", monitor->actionHue() ); + printf("%d", monitor->actionHue()); have_output = true; } } if ( function & ZMU_COLOUR ) { if ( verbose ) { if ( colour >= 0 ) - printf( "New colour: %d\n", monitor->actionColour( colour ) ); + printf("New colour: %d\n", monitor->actionColour(colour)); else - printf( "Current colour: %d\n", monitor->actionColour() ); + printf("Current colour: %d\n", monitor->actionColour()); } else { - if ( have_output ) printf( "%c", separator ); + if ( have_output ) printf("%c", separator); if ( colour >= 0 ) - printf( "%d", monitor->actionColour( colour ) ); + printf("%d", monitor->actionColour(colour)); else - printf( "%d", monitor->actionColour() ); + printf("%d", monitor->actionColour()); have_output = true; } } if ( have_output ) { - printf( "\n" ); + printf("\n"); } if ( !function ) { Usage(); } delete monitor; } else { - fprintf(stderr, "Error, invalid monitor id %d\n", mon_id); + Error("Invalid monitor id %d", mon_id); exit_zmu(-1); } } else { if ( function & ZMU_QUERY ) { #if ZM_HAS_V4L char vidString[0x10000] = ""; - bool ok = LocalCamera::GetCurrentSettings( device, vidString, v4lVersion, verbose ); - printf( "%s", vidString ); - exit_zmu( ok?0:-1 ); + bool ok = LocalCamera::GetCurrentSettings(device, vidString, v4lVersion, verbose); + printf("%s", vidString); + exit_zmu(ok ? 0 : -1); #else // ZM_HAS_V4L - fprintf( stderr, "Error, video4linux is required for device querying\n" ); - exit_zmu( -1 ); + Error("Video4linux is required for device querying"); + exit_zmu(-1); #endif // ZM_HAS_V4L } @@ -708,25 +702,25 @@ int main(int argc, char *argv[]) { } sql += " order by Id asc"; - if ( mysql_query( &dbconn, sql.c_str() ) ) { - Error( "Can't run query: %s", mysql_error( &dbconn ) ); - exit_zmu( mysql_errno( &dbconn ) ); + if ( mysql_query(&dbconn, sql.c_str()) ) { + Error("Can't run query: %s", mysql_error(&dbconn)); + exit_zmu(mysql_errno(&dbconn)); } - MYSQL_RES *result = mysql_store_result( &dbconn ); + MYSQL_RES *result = mysql_store_result(&dbconn); if ( !result ) { - Error( "Can't use query result: %s", mysql_error( &dbconn ) ); - exit_zmu( mysql_errno( &dbconn ) ); + Error("Can't use query result: %s", mysql_error(&dbconn)); + exit_zmu(mysql_errno(&dbconn)); } - Debug( 1, "Got %d monitors", mysql_num_rows( result ) ); + Debug(1, "Got %d monitors", mysql_num_rows(result)); - printf( "%4s%5s%6s%9s%14s%6s%6s%8s%8s\n", "Id", "Func", "State", "TrgState", "LastImgTim", "RdIdx", "WrIdx", "LastEvt", "FrmRate" ); - for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { + printf("%4s%5s%6s%9s%14s%6s%6s%8s%8s\n", "Id", "Func", "State", "TrgState", "LastImgTim", "RdIdx", "WrIdx", "LastEvt", "FrmRate"); + for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row(result); i++ ) { int mon_id = atoi(dbrow[0]); int function = atoi(dbrow[1]); - if ( !user || user->canAccess( mon_id ) ) { + if ( !user || user->canAccess(mon_id) ) { if ( function > 1 ) { - Monitor *monitor = Monitor::Load( mon_id, false, Monitor::QUERY ); + Monitor *monitor = Monitor::Load(mon_id, false, Monitor::QUERY); if ( monitor && monitor->connect() ) { struct timeval tv = monitor->GetTimestamp(); printf( "%4d%5d%6d%9d%11ld.%02ld%6d%6d%8" PRIu64 "%8.2f\n", @@ -744,7 +738,7 @@ int main(int argc, char *argv[]) { } } else { struct timeval tv = { 0, 0 }; - printf( "%4d%5d%6d%9d%11ld.%02ld%6d%6d%8d%8.2f\n", + printf("%4d%5d%6d%9d%11ld.%02ld%6d%6d%8d%8.2f\n", mon_id, function, 0, @@ -755,11 +749,11 @@ int main(int argc, char *argv[]) { 0, 0.0 ); - } - } - } - mysql_free_result( result ); - } + } // end if function filter + } // endif !user || canAccess(mon_id) + } // end foreach row + mysql_free_result(result); + } // end if function && ZMU_LIST } delete user; diff --git a/version b/version index 80c8c0bd3..1304b01de 100644 --- a/version +++ b/version @@ -1 +1 @@ -1.33.2 +1.33.7 diff --git a/web/ajax/event.php b/web/ajax/event.php index d0e229267..3d9c89c36 100644 --- a/web/ajax/event.php +++ b/web/ajax/event.php @@ -1,4 +1,5 @@ $videoFile)); - else - ajaxError('Video Generation Failed'); - } - } - $ok = true; - break; + case 'video' : + if ( empty($_REQUEST['videoFormat']) ) { + ajaxError('Video Generation Failure, no format given'); + } elseif ( empty($_REQUEST['rate']) ) { + ajaxError('Video Generation Failure, no rate given'); + } elseif ( empty($_REQUEST['scale']) ) { + ajaxError('Video Generation Failure, no scale given'); + } else { + $sql = 'SELECT E.*,M.Name AS MonitorName,M.DefaultRate,M.DefaultScale FROM Events AS E INNER JOIN Monitors AS M ON E.MonitorId = M.Id WHERE E.Id = ?'.monitorLimitSql(); + if ( !($event = dbFetchOne($sql, NULL, array( $_REQUEST['id']))) ) { + ajaxError('Video Generation Failure, Unable to load event'); + } else { + if ( $videoFile = createVideo($event, $_REQUEST['videoFormat'], $_REQUEST['rate'], $_REQUEST['scale'], !empty($_REQUEST['overwrite'])) ) + ajaxResponse(array('response'=>$videoFile)); + else + ajaxError('Video Generation Failed'); } - case 'deleteVideo' : - { - unlink( $videoFiles[$_REQUEST['id']] ); - unset( $videoFiles[$_REQUEST['id']] ); - ajaxResponse(); - break; - } - case 'export' : - { - require_once(ZM_SKIN_PATH.'/includes/export_functions.php'); + } + $ok = true; + break; + case 'deleteVideo' : + unlink( $videoFiles[$_REQUEST['id']] ); + unset( $videoFiles[$_REQUEST['id']] ); + ajaxResponse(); + break; + case 'export' : + require_once(ZM_SKIN_PATH.'/includes/export_functions.php'); - # We use session vars in here, so we need to restart the session - # because we stopped it in index.php to improve concurrency. - session_start(); + # We use session vars in here, so we need to restart the session + # because we stopped it in index.php to improve concurrency. + zm_session_start(); - if ( !empty($_REQUEST['exportDetail']) ) - $exportDetail = $_SESSION['export']['detail'] = $_REQUEST['exportDetail']; - else - $exportDetail = false; + if ( !empty($_REQUEST['exportDetail']) ) + $exportDetail = $_SESSION['export']['detail'] = $_REQUEST['exportDetail']; + else + $exportDetail = false; - if ( !empty($_REQUEST['exportFrames']) ) - $exportFrames = $_SESSION['export']['frames'] = $_REQUEST['exportFrames']; - else - $exportFrames = false; + if ( !empty($_REQUEST['exportFrames']) ) + $exportFrames = $_SESSION['export']['frames'] = $_REQUEST['exportFrames']; + else + $exportFrames = false; - if ( !empty($_REQUEST['exportImages']) ) - $exportImages = $_SESSION['export']['images'] = $_REQUEST['exportImages']; - else - $exportImages = false; + if ( !empty($_REQUEST['exportImages']) ) + $exportImages = $_SESSION['export']['images'] = $_REQUEST['exportImages']; + else + $exportImages = false; - if ( !empty($_REQUEST['exportVideo']) ) - $exportVideo = $_SESSION['export']['video'] = $_REQUEST['exportVideo']; - else - $exportVideo = false; + if ( !empty($_REQUEST['exportVideo']) ) + $exportVideo = $_SESSION['export']['video'] = $_REQUEST['exportVideo']; + else + $exportVideo = false; - if ( !empty($_REQUEST['exportMisc']) ) - $exportMisc = $_SESSION['export']['misc'] = $_REQUEST['exportMisc']; - else - $exportMisc = false; + if ( !empty($_REQUEST['exportMisc']) ) + $exportMisc = $_SESSION['export']['misc'] = $_REQUEST['exportMisc']; + else + $exportMisc = false; - if ( !empty($_REQUEST['exportFormat']) ) - $exportFormat = $_SESSION['export']['format'] = $_REQUEST['exportFormat']; - else - $exportFormat = ''; + if ( !empty($_REQUEST['exportFormat']) ) + $exportFormat = $_SESSION['export']['format'] = $_REQUEST['exportFormat']; + else + $exportFormat = ''; - if ( !empty($_REQUEST['exportCompress']) ) - $exportCompress = $_SESSION['export']['compress'] = $_REQUEST['exportCompress']; - else - $exportCompress = false; + if ( !empty($_REQUEST['exportCompress']) ) + $exportCompress = $_SESSION['export']['compress'] = $_REQUEST['exportCompress']; + else + $exportCompress = false; - session_write_close(); + session_write_close(); - $exportIds = !empty($_REQUEST['eids'])?$_REQUEST['eids']:$_REQUEST['id']; - if ( $exportFile = exportEvents( - $exportIds, - (isset($_REQUEST['connkey'])?$_REQUEST['connkey']:''), - $exportDetail, - $exportFrames, - $exportImages, - $exportVideo, - $exportMisc, - $exportFormat, - $exportCompress - ) ) - ajaxResponse(array('exportFile'=>$exportFile)); - else - ajaxError('Export Failed'); - break; - } - case 'download' : - { - require_once(ZM_SKIN_PATH.'/includes/export_functions.php'); - $exportVideo = 1; - $exportFormat = $_REQUEST['exportFormat']; - $exportStructure = 'flat'; - $exportIds = !empty($_REQUEST['eids'])?$_REQUEST['eids']:$_REQUEST['id']; - if ( $exportFile = exportEvents( - $exportIds, - (isset($_REQUEST['connkey'])?$_REQUEST['connkey']:''), - false,false, false, - $exportVideo, false, $exportFormat, $exportStructure ) ) - ajaxResponse(array('exportFile'=>$exportFile)); - else - ajaxError('Export Failed'); - break; - } + $exportIds = !empty($_REQUEST['eids']) ? $_REQUEST['eids'] : $_REQUEST['id']; + if ( $exportFile = exportEvents( + $exportIds, + (isset($_REQUEST['connkey'])?$_REQUEST['connkey']:''), + $exportDetail, + $exportFrames, + $exportImages, + $exportVideo, + $exportMisc, + $exportFormat, + $exportCompress + ) ) + ajaxResponse(array('exportFile'=>$exportFile)); + else + ajaxError('Export Failed'); + break; + case 'download' : + require_once(ZM_SKIN_PATH.'/includes/export_functions.php'); + $exportVideo = 1; + $exportFormat = $_REQUEST['exportFormat']; + $exportStructure = 'flat'; + $exportIds = !empty($_REQUEST['eids'])?$_REQUEST['eids']:$_REQUEST['id']; + if ( $exportFile = exportEvents( + $exportIds, + (isset($_REQUEST['connkey'])?$_REQUEST['connkey']:''), + false,false, false, + $exportVideo, false, $exportFormat, $exportStructure ) ) + ajaxResponse(array('exportFile'=>$exportFile)); + else + ajaxError('Export Failed'); + break; } } // end if canView('Events') if ( canEdit('Events') ) { switch ( $_REQUEST['action'] ) { - case 'rename' : - { - if ( !empty($_REQUEST['eventName']) ) - dbQuery('UPDATE Events SET Name = ? WHERE Id = ?', array($_REQUEST['eventName'], $_REQUEST['id'])); - else - ajaxError('No new event name supplied'); - ajaxResponse(array('refreshEvent'=>true, 'refreshParent'=>true)); - break; - } - case 'eventdetail' : - { - dbQuery( - 'UPDATE Events SET Cause = ?, Notes = ? WHERE Id = ?', - array($_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $_REQUEST['id']) - ); - ajaxResponse(array('refreshEvent'=>true, 'refreshParent'=>true)); - break; - } - case 'archive' : - case 'unarchive' : - { - $archiveVal = ($_REQUEST['action'] == 'archive')?1:0; - dbQuery( - 'UPDATE Events SET Archived = ? WHERE Id = ?', - array($archiveVal, $_REQUEST['id']) - ); - ajaxResponse(array('refreshEvent'=>true, 'refreshParent'=>false)); - break; - } - case 'delete' : - { - $Event = new Event($_REQUEST['id']); - if ( ! $Event->Id() ) { - ajaxResponse(array('refreshEvent'=>false, 'refreshParent'=>true, 'message'=> 'Event not found.')); - } else { - $Event->delete(); - ajaxResponse(array('refreshEvent'=>false, 'refreshParent'=>true)); - } - break; - } - } + case 'rename' : + if ( !empty($_REQUEST['eventName']) ) + dbQuery('UPDATE Events SET Name = ? WHERE Id = ?', array($_REQUEST['eventName'], $_REQUEST['id'])); + else + ajaxError('No new event name supplied'); + ajaxResponse(array('refreshEvent'=>true, 'refreshParent'=>true)); + break; + case 'eventdetail' : + dbQuery( + 'UPDATE Events SET Cause = ?, Notes = ? WHERE Id = ?', + array($_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $_REQUEST['id']) + ); + ajaxResponse(array('refreshEvent'=>true, 'refreshParent'=>true)); + break; + case 'archive' : + case 'unarchive' : + $archiveVal = ($_REQUEST['action'] == 'archive')?1:0; + dbQuery( + 'UPDATE Events SET Archived = ? WHERE Id = ?', + array($archiveVal, $_REQUEST['id']) + ); + ajaxResponse(array('refreshEvent'=>true, 'refreshParent'=>false)); + break; + case 'delete' : + $Event = new ZM\Event($_REQUEST['id']); + if ( ! $Event->Id() ) { + ajaxResponse(array('refreshEvent'=>false, 'refreshParent'=>true, 'message'=> 'Event not found.')); + } else { + $Event->delete(); + ajaxResponse(array('refreshEvent'=>false, 'refreshParent'=>true)); + } + break; + } // end switch action } // end if canEdit('Events') ajaxError('Unrecognised action or insufficient permissions'); diff --git a/web/ajax/log.php b/web/ajax/log.php index e8caff6bd..2fd220578 100644 --- a/web/ajax/log.php +++ b/web/ajax/log.php @@ -19,7 +19,7 @@ switch ( $_REQUEST['task'] ) { else $line = NULL; - $levels = array_flip(Logger::$codes); + $levels = array_flip(ZM\Logger::$codes); if ( !isset($levels[$_POST['level']]) ) ZM\Panic("Unexpected logger level '".$_POST['level']."'"); $level = $levels[$_POST['level']]; @@ -322,7 +322,7 @@ switch ( $_REQUEST['task'] ) { $classLevel = ZM\Logger::FATAL; elseif ( $classLevel > ZM\Logger::DEBUG ) $classLevel = ZM\Logger::DEBUG; - $logClass = 'log-'.strtolower(Logger::$codes[$classLevel]); + $logClass = 'log-'.strtolower(ZM\Logger::$codes[$classLevel]); fprintf( $exportFP, " %s%s%s%d%s%s%s%s\n", $logClass, $log['DateTime'], $log['Component'], $log['Server'], $log['Pid'], $log['Code'], $log['Message'], $log['File'], $log['Line'] ); } fwrite( $exportFP, diff --git a/web/ajax/stream.php b/web/ajax/stream.php index 7329c7bab..8d5348ca8 100644 --- a/web/ajax/stream.php +++ b/web/ajax/stream.php @@ -10,8 +10,7 @@ if ( !($_REQUEST['connkey'] && $_REQUEST['command']) ) { ajaxError("Unexpected received message type '$type'"); } -if (!mkdir(ZM_PATH_SOCKS) ) { -} +mkdir(ZM_PATH_SOCKS); # The file that we point ftok to has to exist, and only exist if zms is running, so we are pointing it at the .sock $key = ftok(ZM_PATH_SOCKS.'/zms-'.sprintf('%06d',$_REQUEST['connkey']).'s.sock', 'Z'); @@ -26,7 +25,7 @@ if ( sem_acquire($semaphore,1) !== false ) { ZM\Warning("sock file $localSocketFile already exists?! Is someone else talking to zms?"); // They could be. We can maybe have concurrent requests from a browser. } - if ( ! socket_bind( $socket, $localSocketFile ) ) { + if ( !socket_bind( $socket, $localSocketFile ) ) { ajaxError("socket_bind( $localSocketFile ) failed: ".socket_strerror(socket_last_error()) ); } @@ -52,18 +51,20 @@ if ( sem_acquire($semaphore,1) !== false ) { $msg = pack( 'lcN', MSG_CMD, $_REQUEST['command'], $_REQUEST['offset'] ); break; default : + ZM\Logger::Debug('Sending command ' . $_REQUEST['command']); $msg = pack( 'lc', MSG_CMD, $_REQUEST['command'] ); break; } $remSockFile = ZM_PATH_SOCKS.'/zms-'.sprintf('%06d',$_REQUEST['connkey']).'s.sock'; - $max_socket_tries = 10; + // Pi can take up to 3 seconds for zms to start up. + $max_socket_tries = 1000; // FIXME This should not exceed web_ajax_timeout while ( !file_exists($remSockFile) && $max_socket_tries-- ) { //sometimes we are too fast for our own good, if it hasn't been setup yet give it a second. // WHY? We will just send another one... // ANSWER: Because otherwise we get a log of errors logged - //Logger::Debug("$remSockFile does not exist, waiting, current " . (time() - $start_time) . ' seconds' ); + //ZM\Logger::Debug("$remSockFile does not exist, waiting, current " . (time() - $start_time) . ' seconds' ); usleep(1000); } @@ -91,43 +92,35 @@ if ( sem_acquire($semaphore,1) !== false ) { ajaxError( "Socket closed $remSockFile" ); } else if ( $numSockets == 0 ) { ZM\Error( "Timed out waiting for msg $remSockFile" ); - socket_Set_nonblock($socket); - #ajaxError( "Timed out waiting for msg $remSockFile" ); + socket_set_nonblock($socket); + #ajaxError("Timed out waiting for msg $remSockFile"); } else if ( $numSockets > 0 ) { if ( count($rSockets) != 1 ) { - ZM\Error( 'Bogus return from select, '.count($rSockets).' sockets available' ); - ajaxError( 'Bogus return from select, '.count($rSockets).' sockets available' ); + ZM\Error('Bogus return from select, '.count($rSockets).' sockets available'); + ajaxError('Bogus return from select, '.count($rSockets).' sockets available'); } } switch( $nbytes = @socket_recvfrom( $socket, $msg, MSG_DATA_SIZE, 0, $remSockFile ) ) { case -1 : - { - ajaxError( "socket_recvfrom( $remSockFile ) failed: ".socket_strerror(socket_last_error()) ); + ajaxError("socket_recvfrom( $remSockFile ) failed: ".socket_strerror(socket_last_error())); break; - } case 0 : - { - ajaxError( 'No data to read from socket' ); + ajaxError('No data to read from socket'); break; - } default : - { if ( $nbytes != MSG_DATA_SIZE ) - ajaxError( "Got unexpected message size, got $nbytes, expected ".MSG_DATA_SIZE ); + ajaxError("Got unexpected message size, got $nbytes, expected ".MSG_DATA_SIZE); break; } - } - - $data = unpack( 'ltype', $msg ); + $data = unpack('ltype', $msg); switch ( $data['type'] ) { case MSG_DATA_WATCH : - { - $data = unpack( "ltype/imonitor/istate/dfps/ilevel/irate/ddelay/izoom/Cdelayed/Cpaused/Cenabled/Cforced", $msg ); - ZM\Logger::Debug("FPS: " . $data['fps'] ); + $data = unpack('ltype/imonitor/istate/dfps/ilevel/irate/ddelay/izoom/Cdelayed/Cpaused/Cenabled/Cforced', $msg); + ZM\Logger::Debug('FPS: ' . $data['fps']); $data['fps'] = round( $data['fps'], 2 ); - ZM\Logger::Debug("FPS: " . $data['fps'] ); + ZM\Logger::Debug('FPS: ' . $data['fps'] ); $data['rate'] /= RATE_BASE; $data['delay'] = round( $data['delay'], 2 ); $data['zoom'] = round( $data['zoom']/SCALE_BASE, 1 ); @@ -140,11 +133,14 @@ if ( sem_acquire($semaphore,1) !== false ) { } ajaxResponse( array( 'status'=>$data ) ); break; - } case MSG_DATA_EVENT : - { - $data = unpack( "ltype/Pevent/iprogress/irate/izoom/Cpaused", $msg ); - //$data['progress'] = sprintf( "%.2f", $data['progress'] ); + if ( version_compare( phpversion(), '5.6.0', '<') ) { + ZM\Logger::Debug('Using old unpack methods to handle 64bit event id'); + $data = unpack('ltype/ieventlow/ieventhigh/iprogress/irate/izoom/Cpaused', $msg); + $data['event'] = $data['eventhigh'] << 32 | $data['eventlow']; + } else { + $data = unpack('ltype/Qevent/iprogress/irate/izoom/Cpaused', $msg); + } $data['rate'] /= RATE_BASE; $data['zoom'] = round( $data['zoom']/SCALE_BASE, 1 ); if ( ZM_OPT_USE_AUTH && ZM_AUTH_RELAY == 'hashed' ) { @@ -154,13 +150,10 @@ if ( sem_acquire($semaphore,1) !== false ) { $data['auth'] = generateAuthHash(ZM_AUTH_HASH_IPS); } } - ajaxResponse( array( 'status'=>$data ) ); + ajaxResponse(array('status'=>$data)); break; - } default : - { - ajaxError( "Unexpected received message type '$type'" ); - } + ajaxError("Unexpected received message type '$type'"); } sem_release($semaphore); } else { diff --git a/web/api/app/Controller/AppController.php b/web/api/app/Controller/AppController.php index 9dd27e945..51575f055 100644 --- a/web/api/app/Controller/AppController.php +++ b/web/api/app/Controller/AppController.php @@ -67,7 +67,6 @@ class AppController extends Controller { # For use throughout the app. If not logged in, this will be null. global $user; - $user = $this->Session->read('user'); if ( ZM_OPT_USE_AUTH ) { require_once __DIR__ .'/../../../includes/auth.php'; diff --git a/web/api/app/Controller/Component/FilterComponent.php b/web/api/app/Controller/Component/FilterComponent.php index 326c1ce45..798452793 100644 --- a/web/api/app/Controller/Component/FilterComponent.php +++ b/web/api/app/Controller/Component/FilterComponent.php @@ -1,14 +1,88 @@ ', + '>', + '>=', + 'IS', + 'IS NOT', + //'IS NOT NULL', + //'IS NULL', + //'->', + //'->>', + '<<', + '<', + '<=', + 'LIKE', + '-', + '%', + 'MOD', + //'NOT', + //'!', + //'NOT BETWEEN ... AND ...', + '!=', + '<>', + 'NOT LIKE', + 'NOT REGEXP', + // `or` operators aren't safe as they can + // be used to skip an existing condition + // enforcing access to only certain + // monitors/events. + //'||', + //'OR', + '+', + 'REGEXP', + '>>', + 'RLIKE', + 'SOUNDS LIKE', + //'*', + '-', + //'XOR', + ); + // Build a CakePHP find() condition based on the named parameters // that are passed in public function buildFilter($namedParams) { - if ($namedParams) { - $conditions = array(); - + $conditions = array(); + if ($namedParams) { foreach ($namedParams as $attribute => $value) { + // We need to sanitize $attribute to avoid SQL injection. + $lhs = trim($attribute); + $matches = NULL; + if (preg_match('/^(?P[a-z0-9]+)(?P.+)?$/i', $lhs, $matches) !== 1) { + throw new Exception('Invalid argument before `:`: ' . $lhs); + } + $operator = trim($matches['operator']); + + // Only allow operators on our allow list. No operator + // specified defaults to `=` by cakePHP. + if ($operator != '' && !in_array($operator, $this->twoOperandSQLOperands)) { + throw new Exception('Invalid operator: ' . $operator); + } + + $lhs = '`' . $matches['field'] . '` ' . $operator; // If the named param contains an array, we want to turn it into an IN condition // Otherwise, we add it right into the $conditions array if (is_array($value)) { @@ -18,10 +92,10 @@ class FilterComponent extends Component { array_push($array, $term); } - $query = array($attribute => $array); + $query = array($lhs => $array); array_push($conditions, $query); } else { - $conditions[$attribute] = $value; + $conditions[$lhs] = $value; } } diff --git a/web/api/app/Controller/EventsController.php b/web/api/app/Controller/EventsController.php index cf8ca8f37..2f6cfd494 100644 --- a/web/api/app/Controller/EventsController.php +++ b/web/api/app/Controller/EventsController.php @@ -44,9 +44,8 @@ class EventsController extends AppController { } if ( $this->request->params['named'] ) { - //$this->FilterComponent = $this->Components->load('Filter'); - //$conditions = $this->FilterComponent->buildFilter($this->request->params['named']); - $conditions = $this->request->params['named']; + $this->FilterComponent = $this->Components->load('Filter'); + $conditions = $this->FilterComponent->buildFilter($this->request->params['named']); } else { $conditions = array(); } @@ -143,7 +142,7 @@ class EventsController extends AppController { 'event' => $event, '_serialize' => array('event') )); - } + } // end function view /** @@ -234,18 +233,34 @@ class EventsController extends AppController { public function search() { $this->Event->recursive = -1; + // Unmodified conditions to pass to find() + $find_conditions = array(); + // Conditions to be filtered by buildFilter $conditions = array(); foreach ($this->params['named'] as $param_name => $value) { - // Transform params into mysql - if ( preg_match('/interval/i', $value, $matches) ) { - $condition = array("$param_name >= (date_sub(now(), $value))"); + // Transform params into conditions + if ( preg_match('/^\s?interval\s?/i', $value) ) { + if (preg_match('/^[a-z0-9]+$/i', $param_name) !== 1) { + throw new Exception('Invalid field name: ' . $param_name); + } + $matches = NULL; + $value = preg_replace('/^\s?interval\s?/i', '', $value); + if (preg_match('/^(?P[ -.:0-9\']+)\s+(?P[_a-z]+)$/i', trim($value), $matches) !== 1) { + throw new Exception('Invalid interval: ' . $value); + } + $expr = trim($matches['expr']); + $unit = trim($matches['unit']); + array_push($find_conditions, "$param_name >= DATE_SUB(NOW(), INTERVAL $expr $unit)"); } else { - $condition = array($param_name => $value); + $conditions[$param_name] = $value; } - array_push($conditions, $condition); } + $this->FilterComponent = $this->Components->load('Filter'); + $conditions = $this->FilterComponent->buildFilter($conditions); + array_push($conditions, $find_conditions); + $results = $this->Event->find('all', array( 'conditions' => $conditions )); @@ -261,18 +276,35 @@ class EventsController extends AppController { // consoleEvents/1 hour/AlarmFrames >=: 1/AlarmFrames <=: 20.json public function consoleEvents($interval = null) { + $matches = NULL; + // https://dev.mysql.com/doc/refman/5.5/en/expressions.html#temporal-intervals + // Examples: `'1-1' YEAR_MONTH`, `'-1 10' DAY_HOUR`, `'1.999999' SECOND_MICROSECOND` + if (preg_match('/^(?P[ -.:0-9\']+)\s+(?P[_a-z]+)$/i', trim($interval), $matches) !== 1) { + throw new Exception('Invalid interval: ' . $interval); + } + $expr = trim($matches['expr']); + $unit = trim($matches['unit']); + $this->Event->recursive = -1; $results = array(); - - $moreconditions = ''; - foreach ($this->request->params['named'] as $name => $param) { - $moreconditions = $moreconditions . ' AND '.$name.$param; - } - - $query = $this->Event->query("SELECT MonitorId, COUNT(*) AS Count FROM Events WHERE (StartTime >= (DATE_SUB(NOW(), interval $interval)) $moreconditions) GROUP BY MonitorId;"); + $this->FilterComponent = $this->Components->load('Filter'); + if ( $this->request->params['named'] ) { + $conditions = $this->FilterComponent->buildFilter($this->request->params['named']); + } else { + $conditions = array(); + } + array_push($conditions, array("StartTime >= DATE_SUB(NOW(), INTERVAL $expr $unit)")); + $query = $this->Event->find('all', array( + 'fields' => array( + 'MonitorId', + 'COUNT(*) AS Count', + ), + 'conditions' => $conditions, + 'group' => 'MonitorId', + )); foreach ($query as $result) { - $results[$result['Events']['MonitorId']] = $result[0]['Count']; + $results[$result['Event']['MonitorId']] = $result[0]['Count']; } $this->set(array( diff --git a/web/api/app/Controller/HostController.php b/web/api/app/Controller/HostController.php index 74ea854a4..2980902c3 100644 --- a/web/api/app/Controller/HostController.php +++ b/web/api/app/Controller/HostController.php @@ -48,8 +48,7 @@ class HostController extends AppController { // clears out session function logout() { - global $user; - $this->Session->Write('user', null); + userLogout(); $this->set(array( 'result' => 'ok', @@ -67,7 +66,7 @@ class HostController extends AppController { if ( $isZmAuth ) { // In future, we may want to completely move to AUTH_HASH_LOGINS and return &auth= for all cases require_once __DIR__ .'/../../../includes/auth.php'; # in the event we directly call getCredentials.json - $this->Session->read('user'); # this is needed for command line/curl to recognize a session + $zmAuthRelay = $this->Config->find('first',array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_AUTH_RELAY')))['Config']['Value']; if ( $zmAuthRelay == 'hashed' ) { $zmAuthHashIps = $this->Config->find('first',array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_AUTH_HASH_IPS')))['Config']['Value']; @@ -75,7 +74,7 @@ class HostController extends AppController { $credentials = 'auth='.generateAuthHash($zmAuthHashIps,true); } else { // user will need to append the store password here - $credentials = 'user='.$this->Session->read('user.Username').'&pass='; + $credentials = 'user='.$this->Session->read('Username').'&pass='; $appendPassword = 1; } } @@ -96,6 +95,7 @@ class HostController extends AppController { // If $mid is set, only return disk usage for that monitor // Else, return an array of total disk usage, and per-monitor // usage. + // This function is deprecated. Use the Storage object or monitor object instead function getDiskPercent($mid = null) { $this->loadModel('Config'); $this->loadModel('Monitor'); @@ -118,7 +118,7 @@ class HostController extends AppController { if ( $mid ) { // Get disk usage for $mid - Logger::Debug("Executing du -s0 $zm_dir_events/$mid | awk '{print $1}'"); + ZM\Logger::Debug("Executing du -s0 $zm_dir_events/$mid | awk '{print $1}'"); $usage = shell_exec("du -s0 $zm_dir_events/$mid | awk '{print $1}'"); } else { $monitors = $this->Monitor->find('all', array( diff --git a/web/api/app/Controller/MonitorsController.php b/web/api/app/Controller/MonitorsController.php index 8908955b5..f83aecf97 100644 --- a/web/api/app/Controller/MonitorsController.php +++ b/web/api/app/Controller/MonitorsController.php @@ -40,8 +40,7 @@ class MonitorsController extends AppController { if ( $this->request->params['named'] ) { $this->FilterComponent = $this->Components->load('Filter'); - //$conditions = $this->FilterComponent->buildFilter($this->request->params['named']); - $conditions = $this->request->params['named']; + $conditions = $this->FilterComponent->buildFilter($this->request->params['named']); } else { $conditions = array(); } @@ -183,7 +182,7 @@ class MonitorsController extends AppController { ) ) { if ( !defined('ZM_SERVER_ID')) { - Logger::Debug("Not defined ZM_SERVER_ID"); + ZM\Logger::Debug("Not defined ZM_SERVER_ID"); } $this->daemonControl($this->Monitor->id, 'start'); } @@ -318,6 +317,10 @@ class MonitorsController extends AppController { throw new NotFoundException(__('Invalid monitor')); } + if (preg_match('/^[a-z]+$/i', $daemon) !== 1) { + throw new BadRequestException(__('Invalid command')); + } + $monitor = $this->Monitor->find('first', array( 'fields' => array('Id', 'Type', 'Device'), 'conditions' => array('Id' => $id) @@ -384,7 +387,7 @@ class MonitorsController extends AppController { } $shellcmd = escapeshellcmd("$zm_path_bin/zmdc.pl $command $daemon $args"); - Logger::Debug("Command $shellcmd"); + ZM\Logger::Debug("Command $shellcmd"); $status = exec($shellcmd); $status_text .= $status."\n"; } diff --git a/web/api/app/Controller/ZonesController.php b/web/api/app/Controller/ZonesController.php index 4d6564443..5b8c3f1a3 100644 --- a/web/api/app/Controller/ZonesController.php +++ b/web/api/app/Controller/ZonesController.php @@ -18,7 +18,7 @@ class ZonesController extends AppController { parent::beforeFilter(); global $user; - $canView = (!$user) || $user['Monitors'] != 'None'; + $canView = (!$user) || ($user['Monitors'] != 'None'); if ( !$canView ) { throw new UnauthorizedException(__('Insufficient Privileges')); return; diff --git a/web/api/app/Model/Event.php b/web/api/app/Model/Event.php index 14dbd377e..de83473f1 100644 --- a/web/api/app/Model/Event.php +++ b/web/api/app/Model/Event.php @@ -1,4 +1,6 @@ id); + return $Event->Relative_Path(); } // end function Relative_Path() + public function Path() { + $Event = new ZM\Event($this->id); + return $Event->Path(); + } + + public function Link_Path() { + $Event = new ZM\Event($this->id); + return $Event->Link_Path(); + } public function fileExists($event) { //$data = $this->findById($id); @@ -121,19 +123,25 @@ class Event extends AppModel { $storage = $this->Storage->findById($event['StorageId']); if ( $event['DefaultVideo'] ) { - if ( file_exists($storage['Storage']['Path'].'/'.$this->Relative_Path($event).'/'.$event['DefaultVideo']) ) { + if ( file_exists($this->Path().'/'.$event['DefaultVideo']) ) { return 1; } else { - Logger::Debug("FIle does not exist at " . $storage['Storage']['Path'].'/'.$this->Relative_Path($event).'/'.$event['DefaultVideo'] ); + ZM\Logger::Debug('File does not exist at ' . $this->Path().'/'.$event['DefaultVideo'] ); } } else { -Logger::Debug("No DefaultVideo in Event" . $this->Event); + ZM\Logger::Debug('No DefaultVideo in Event' . $this->Event); return 0; } } // end function fileExists($event) public function fileSize($event) { - $storage = $this->Storage->findById($event['StorageId']); - return filesize($storage['Storage']['Path'].'/'.$this->Relative_Path($event).'/'.$event['DefaultVideo']); + return filesize($this->Path().'/'.$event['DefaultVideo']); } + + public function beforeDelete($cascade=true) { + $Event = new ZM\Event($this->id); + $Event->delete(); + // Event->delete() will do it all, so cake doesn't have to do anything. + return false; + } // end function afterDelete } diff --git a/web/includes/Control.php b/web/includes/Control.php index 5d8647995..72e6c49a9 100644 --- a/web/includes/Control.php +++ b/web/includes/Control.php @@ -1,6 +1,7 @@ 0, 'CanPan' => 0, 'CanReset' => 0, + 'CanReboot' => 0, 'CanSleep' => 0, 'CanWake' => 0, 'MinPanRange' => NULL, diff --git a/web/includes/Event.php b/web/includes/Event.php index 51995ac19..ba4f04e8c 100644 --- a/web/includes/Event.php +++ b/web/includes/Event.php @@ -1,5 +1,7 @@ {$fn} = $args[0]; } - if ( array_key_exists( $fn, $this ) ) { + if ( array_key_exists($fn, $this) ) { return $this->{$fn}; $backTrace = debug_backtrace(); @@ -107,7 +108,7 @@ class Event { $file = $backTrace[1]['file']; $line = $backTrace[1]['line']; Warning("Unknown function call Event->$fn from $file:$line"); - Warning(print_r( $this, true )); + Warning(print_r($this, true)); } } @@ -120,18 +121,23 @@ class Event { public function Path() { $Storage = $this->Storage(); - return $Storage->Path().'/'.$this->Relative_Path(); + if ( $Storage->Path() and $this->Relative_Path() ) { + return $Storage->Path().'/'.$this->Relative_Path(); + } else { + Error('Event Path not complete. Storage: '.$Storage->Path().' relative: '.$this->Relative_Path()); + return ''; + } } public function Relative_Path() { $event_path = ''; if ( $this->{'Scheme'} == 'Deep' ) { - $event_path = $this->{'MonitorId'} .'/'.strftime( '%y/%m/%d/%H/%M/%S', $this->Time()) ; + $event_path = $this->{'MonitorId'}.'/'.strftime('%y/%m/%d/%H/%M/%S', $this->Time()); } else if ( $this->{'Scheme'} == 'Medium' ) { - $event_path = $this->{'MonitorId'} .'/'.strftime( '%Y-%m-%d', $this->Time() ) . '/'.$this->{'Id'}; + $event_path = $this->{'MonitorId'}.'/'.strftime('%Y-%m-%d', $this->Time()).'/'.$this->{'Id'}; } else { - $event_path = $this->{'MonitorId'} .'/'.$this->{'Id'}; + $event_path = $this->{'MonitorId'}.'/'.$this->{'Id'}; } return $event_path; @@ -139,24 +145,26 @@ class Event { public function Link_Path() { if ( $this->{'Scheme'} == 'Deep' ) { - return $this->{'MonitorId'} .'/'.strftime( '%y/%m/%d/.', $this->Time()).$this->{'Id'}; + return $this->{'MonitorId'}.'/'.strftime('%y/%m/%d/.', $this->Time()).$this->{'Id'}; } Error('Calling Link_Path when not using deep storage'); return ''; } public function delete() { - # This wouldn't work with foreign keys - dbQuery( 'DELETE FROM Events WHERE Id = ?', array($this->{'Id'}) ); + if ( ! $this->{'Id'} ) { + Error('Event delete on event with empty Id'); + return; + } if ( !ZM_OPT_FAST_DELETE ) { - dbQuery( 'DELETE FROM Stats WHERE EventId = ?', array($this->{'Id'}) ); - dbQuery( 'DELETE FROM Frames WHERE EventId = ?', array($this->{'Id'}) ); + dbQuery('DELETE FROM Stats WHERE EventId = ?', array($this->{'Id'})); + dbQuery('DELETE FROM Frames WHERE EventId = ?', array($this->{'Id'})); if ( $this->{'Scheme'} == 'Deep' ) { # Assumption: All events have a start time - $start_date = date_parse( $this->{'StartTime'} ); + $start_date = date_parse($this->{'StartTime'}); if ( ! $start_date ) { - Error('Unable to parse start time for event ' . $this->{'Id'} . ' not deleting files.' ); + Error('Unable to parse start time for event ' . $this->{'Id'} . ' not deleting files.'); return; } $start_date['year'] = $start_date['year'] % 100; @@ -164,37 +172,42 @@ class Event { # So this is because ZM creates a link under the day pointing to the time that the event happened. $link_path = $this->Link_Path(); if ( ! $link_path ) { - Error('Unable to determine link path for event ' . $this->{'Id'} . ' not deleting files.' ); + Error('Unable to determine link path for event '.$this->{'Id'}.' not deleting files.'); return; } $Storage = $this->Storage(); $eventlink_path = $Storage->Path().'/'.$link_path; - if ( $id_files = glob( $eventlink_path ) ) { + if ( $id_files = glob($eventlink_path) ) { if ( ! $eventPath = readlink($id_files[0]) ) { Error("Unable to read link at $id_files[0]"); return; } # I know we are using arrays here, but really there can only ever be 1 in the array - $eventPath = preg_replace( '/\.'.$this->{'Id'}.'$/', $eventPath, $id_files[0] ); - deletePath( $eventPath ); - deletePath( $id_files[0] ); - $pathParts = explode( '/', $eventPath ); + $eventPath = preg_replace('/\.'.$this->{'Id'}.'$/', $eventPath, $id_files[0]); + deletePath($eventPath); + deletePath($id_files[0]); + $pathParts = explode('/', $eventPath); for ( $i = count($pathParts)-1; $i >= 2; $i-- ) { - $deletePath = join( '/', array_slice( $pathParts, 0, $i ) ); - if ( !glob( $deletePath."/*" ) ) { - deletePath( $deletePath ); + $deletePath = join('/', array_slice($pathParts, 0, $i)); + if ( !glob($deletePath.'/*') ) { + deletePath($deletePath); } } } else { - Warning( "Found no event files under $eventlink_path" ); + Warning("Found no event files under $eventlink_path"); } # end if found files } else { $eventPath = $this->Path(); - deletePath( $eventPath ); + if ( ! $eventPath ) { + Error('No event Path in Event delete. Not deleting'); + return; + } + deletePath($eventPath); } # USE_DEEP_STORAGE OR NOT } # ! ZM_OPT_FAST_DELETE + dbQuery('DELETE FROM Events WHERE Id = ?', array($this->{'Id'})); } # end Event->delete public function getStreamSrc( $args=array(), $querySep='&' ) { @@ -413,31 +426,31 @@ class Event { $captPath = $eventPath.'/'.$captImage; if ( ! file_exists($captPath) ) { - Error( "Capture file does not exist at $captPath" ); + Error("Capture file does not exist at $captPath"); } //echo "CI:$captImage, CP:$captPath, TCP:$captPath
"; - $analImage = sprintf( '%0'.ZM_EVENT_IMAGE_DIGITS.'d-analyse.jpg', $frame['FrameId'] ); + $analImage = sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d-analyse.jpg', $frame['FrameId']); $analPath = $eventPath.'/'.$analImage; //echo "AI:$analImage, AP:$analPath, TAP:$analPath
"; $alarmFrame = $frame['Type']=='Alarm'; - $hasAnalImage = $alarmFrame && file_exists( $analPath ) && filesize( $analPath ); + $hasAnalImage = $alarmFrame && file_exists($analPath) && filesize($analPath); $isAnalImage = $hasAnalImage && !$captureOnly; - if ( !ZM_WEB_SCALE_THUMBS || $scale >= SCALE_BASE || !function_exists( 'imagecreatefromjpeg' ) ) { - $imagePath = $thumbPath = $isAnalImage?$analPath:$captPath; + if ( !ZM_WEB_SCALE_THUMBS || $scale >= SCALE_BASE || !function_exists('imagecreatefromjpeg') ) { + $imagePath = $thumbPath = $isAnalImage ? $analPath : $captPath; $imageFile = $imagePath; $thumbFile = $thumbPath; } else { if ( version_compare( phpversion(), '4.3.10', '>=') ) - $fraction = sprintf( '%.3F', $scale/SCALE_BASE ); + $fraction = sprintf('%.3F', $scale/SCALE_BASE); else - $fraction = sprintf( '%.3f', $scale/SCALE_BASE ); - $scale = (int)round( $scale ); + $fraction = sprintf('%.3f', $scale/SCALE_BASE); + $scale = (int)round($scale); $thumbCaptPath = preg_replace( '/\.jpg$/', "-$scale.jpg", $captPath ); $thumbAnalPath = preg_replace( '/\.jpg$/', "-$scale.jpg", $analPath ); @@ -567,8 +580,8 @@ class Event { if ( file_exists( $this->Path().'/'.$this->DefaultVideo() ) ) { return true; } - $Storage= $this->Storage(); - $Server = $Storage->ServerId() ? $Storage->Server() : $this->Monitor()->Server(); + $Storage= $this->Storage(); + $Server = $Storage->ServerId() ? $Storage->Server() : $this->Monitor()->Server(); if ( $Server->Id() != ZM_SERVER_ID ) { $url = $Server->UrlToApi() . '/events/'.$this->{'Id'}.'.json'; @@ -635,14 +648,14 @@ class Event { 'content' => '' ) ); - $context = stream_context_create($options); + $context = stream_context_create($options); try { $result = file_get_contents($url, false, $context); - if ($result === FALSE) { /* Handle error */ + if ( $result === FALSE ) { /* Handle error */ Error("Error restarting zmc using $url"); } $event_data = json_decode($result,true); - Logger::Debug(print_r($event_data['event']['Event'],1)); + Logger::Debug(print_r($event_data['event']['Event'], 1)); return $event_data['event']['Event']['fileSize']; } catch ( Exception $e ) { Error("Except $e thrown trying to get event data"); diff --git a/web/includes/Filter.php b/web/includes/Filter.php index fb5c74d01..8da602539 100644 --- a/web/includes/Filter.php +++ b/web/includes/Filter.php @@ -214,11 +214,13 @@ public $defaults = array( $url = '?user='.$_SESSION['username']; } } - $url .= '&view=filter&action=control&command='.$command.'&Id='.$this->Id().'&ServerId'.$Server->Id(); + $url .= '&view=filter&action=control&command='.$command.'&Id='.$this->Id().'&ServerId='.$Server->Id(); Logger::Debug("sending command to $url"); $data = array(); - if ( defined('ZM_ENABLE_CSRF_MAGIC') ) - $data['__csrf_magic'] = csrf_get_secret(); + if ( defined('ZM_ENABLE_CSRF_MAGIC') ) { + require_once( 'includes/csrf/csrf-magic.php' ); + $data['__csrf_magic'] = csrf_get_tokens(); + } // use key 'http' even if you send the request to https://... $options = array( diff --git a/web/includes/Monitor.php b/web/includes/Monitor.php index ca0740fd6..6546b02e4 100644 --- a/web/includes/Monitor.php +++ b/web/includes/Monitor.php @@ -67,10 +67,11 @@ private $defaults = array( 'Encoder' => 'auto', 'OutputContainer' => 'auto', 'Triggers' => null, + 'AnalysisUpdateDelay' => 0, 'MaxFPS' => null, 'AlarmMaxFPS' => null, - 'FPSReportIneterval' => 100, - 'RefBlencPerc' => 6, + 'FPSReportInterval' => 100, + 'RefBlendPerc' => 6, 'AlarmRefBlendPerc' => 6, 'Controllable' => 0, 'ControlId' => null, @@ -81,7 +82,6 @@ private $defaults = array( 'TrackDelay' => null, 'ReturnLocation' => -1, 'ReturnDelay' => null, - 'DefaultView' => 'Events', 'DefaultRate' => 100, 'DefaultScale' => 100, 'SignalCheckPoints' => 0, @@ -117,6 +117,7 @@ private $control_fields = array( 'CanWake' => '0', 'CanSleep' => '0', 'CanReset' => '0', + 'CanReboot' => '0', 'CanZoom' => '0', 'CanAutoZoom' => '0', 'CanZoomAbs' => '0', @@ -311,7 +312,7 @@ private $control_fields = array( $args['rand'] = time(); } - $streamSrc .= '?'.http_build_query($args,'', $querySep); + $streamSrc .= '?'.http_build_query($args, '', $querySep); return $streamSrc; } // end function getStreamSrc @@ -656,7 +657,8 @@ private $control_fields = array( } // end function Source public function UrlToIndex() { - return $this->Server()->UrlToIndex(ZM_MIN_STREAMING_PORT ? (ZM_MIN_STREAMING_PORT+$this->Id()) : null); + return $this->Server()->UrlToIndex(); + //ZM_MIN_STREAMING_PORT ? (ZM_MIN_STREAMING_PORT+$this->Id()) : null); } } // end class Monitor diff --git a/web/includes/Server.php b/web/includes/Server.php index 96d07e9c1..535ea44ed 100644 --- a/web/includes/Server.php +++ b/web/includes/Server.php @@ -7,17 +7,18 @@ $server_cache = array(); class Server { private $defaults = array( - 'Id' => null, - 'Name' => '', - 'Protocol' => '', - 'Hostname' => '', - 'Port' => null, - 'PathToIndex' => null, - 'PathToZMS' => ZM_PATH_ZMS, - 'PathToApi' => '/zm/api', - 'zmaudit' => 1, - 'zmstats' => 1, - 'zmtrigger' => 0, + 'Id' => null, + 'Name' => '', + 'Protocol' => '', + 'Hostname' => '', + 'Port' => null, + 'PathToIndex' => null, + 'PathToZMS' => ZM_PATH_ZMS, + 'PathToApi' => '/zm/api', + 'zmaudit' => 1, + 'zmstats' => 1, + 'zmtrigger' => 0, + 'zmeventnotification' => 0, ); public function __construct($IdOrRow = NULL) { diff --git a/web/includes/actions/control.php b/web/includes/actions/control.php index 36f6b14fb..5dff5a5d2 100644 --- a/web/includes/actions/control.php +++ b/web/includes/actions/control.php @@ -28,13 +28,14 @@ if ( ! canView('Control', $_REQUEST['mid']) ) { return; } -require_once('control_functions.php'); -require_once('Monitor.php'); +require_once('includes/control_functions.php'); +require_once('includes/Monitor.php'); $mid = validInt($_REQUEST['mid']); if ( $action == 'control' ) { $monitor = new ZM\Monitor($mid); $ctrlCommand = buildControlCommand($monitor); sendControlCommand($monitor->Id(), $ctrlCommand); + $view = 'none'; } ?> diff --git a/web/includes/actions/donate.php b/web/includes/actions/donate.php index 156491ede..cfd60c8f0 100644 --- a/web/includes/actions/donate.php +++ b/web/includes/actions/donate.php @@ -27,28 +27,32 @@ if ( $action == 'donate' && isset($_REQUEST['option']) ) { $option = $_REQUEST['option']; switch( $option ) { case 'go' : - // Ignore this, the caller will open the page itself - break; + // Ignore this, the caller will open the page itself + break; case 'hour' : case 'day' : case 'week' : case 'month' : - $nextReminder = time(); - if ( $option == 'hour' ) { - $nextReminder += 60*60; - } elseif ( $option == 'day' ) { - $nextReminder += 24*60*60; - } elseif ( $option == 'week' ) { - $nextReminder += 7*24*60*60; - } elseif ( $option == 'month' ) { - $nextReminder += 30*24*60*60; - } - dbQuery("UPDATE Config SET Value = '".$nextReminder."' WHERE Name = 'ZM_DYN_DONATE_REMINDER_TIME'"); - break; + $nextReminder = time(); + if ( $option == 'hour' ) { + $nextReminder += 60*60; + } elseif ( $option == 'day' ) { + $nextReminder += 24*60*60; + } elseif ( $option == 'week' ) { + $nextReminder += 7*24*60*60; + } elseif ( $option == 'month' ) { + $nextReminder += 30*24*60*60; + } + dbQuery("UPDATE Config SET Value = '".$nextReminder."' WHERE Name = 'ZM_DYN_DONATE_REMINDER_TIME'"); + break; case 'never' : case 'already' : - dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_DYN_SHOW_DONATE_REMINDER'"); - break; + dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_DYN_SHOW_DONATE_REMINDER'"); + break; + default : + Warning("Unknown value for option in donate: $option"); + break; } // end switch option + $view = 'none'; } ?> diff --git a/web/includes/actions/events.php b/web/includes/actions/events.php index 0ed8f3865..08782a8a2 100644 --- a/web/includes/actions/events.php +++ b/web/includes/actions/events.php @@ -31,21 +31,21 @@ if ( !canEdit('Events') ) { if ( $action == 'archive' ) { $dbConn->beginTransaction(); - foreach( getAffectedIds('markEid') as $markEid ) { + foreach( getAffectedIds('eids') as $markEid ) { dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(1, $markEid)); } $dbConn->commit(); $refreshParent = true; } else if ( $action == 'unarchive' ) { $dbConn->beginTransaction(); - foreach( getAffectedIds('markEid') as $markEid ) { + foreach( getAffectedIds('eids') as $markEid ) { dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(0, $markEid)); } $dbConn->commit(); $refreshParent = true; } else if ( $action == 'delete' ) { $dbConn->beginTransaction(); - foreach ( getAffectedIds('markEid') as $markEid ) { + foreach ( getAffectedIds('eids') as $markEid ) { deleteEvent($markEid); } $dbConn->commit(); diff --git a/web/includes/actions/filter.php b/web/includes/actions/filter.php index a89938697..6b3019ee5 100644 --- a/web/includes/actions/filter.php +++ b/web/includes/actions/filter.php @@ -81,7 +81,7 @@ if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) { } else { dbQuery('INSERT INTO Filters SET'.$sql); $_REQUEST['Id'] = dbInsertId(); - $filter = new Filter($_REQUEST['Id']); + $filter = new ZM\Filter($_REQUEST['Id']); } if ( !empty($_REQUEST['filter']['Background']) ) $filter->control('start'); diff --git a/web/includes/actions/monitor.php b/web/includes/actions/monitor.php index 815100e4e..cfb89a892 100644 --- a/web/includes/actions/monitor.php +++ b/web/includes/actions/monitor.php @@ -18,33 +18,6 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // -// I think this is saving a Monitor from ajax... - -if ( isset($_REQUEST['object']) and $_REQUEST['object'] == 'Monitor' ) { - if ( $action == 'save' ) { - foreach ( $_REQUEST['mids'] as $mid ) { - $mid = ValidInt($mid); - if ( ! canEdit('Monitors', $mid) ) { - ZM\Warning("Cannot edit monitor $mid"); - continue; - } - $Monitor = new ZM\Monitor($mid); - if ( $Monitor->Type() != 'WebSite' ) { - $Monitor->zmaControl('stop'); - $Monitor->zmcControl('stop'); - } - $Monitor->save($_REQUEST['newMonitor']); - if ( $Monitor->Function() != 'None' && $Monitor->Type() != 'WebSite' ) { - $Monitor->zmcControl('start'); - if ( $Monitor->Enabled() ) { - $Monitor->zmaControl('start'); - } - } - } // end foreach mid - $refreshParent = true; - } // end if action == save -} // end if object is Monitor - // Monitor edit actions, monitor id derived, require edit permissions for that monitor if ( ! canEdit('Monitors') ) { ZM\Warning("Monitor actions require Monitors Permissions"); @@ -113,10 +86,15 @@ if ( $action == 'monitor' ) { unlink($OldStorage->Path().'/'.$saferOldName); $NewStorage = new ZM\Storage($_REQUEST['newMonitor']['StorageId']); - if ( ! file_exists($NewStorage->Path().'/'.$mid) ) - mkdir($NewStorage->Path().'/'.$mid, 0755); + if ( !file_exists($NewStorage->Path().'/'.$mid) ) { + if ( !mkdir($NewStorage->Path().'/'.$mid, 0755) ) { + Error('Unable to mkdir ' . $NewStorage->Path().'/'.$mid); + } + } $saferNewName = basename($_REQUEST['newMonitor']['Name']); - symlink($mid, $NewStorage->Path().'/'.$saferNewName); + if ( !symlink($NewStorage->Path().'/'.$mid, $NewStorage->Path().'/'.$saferNewName) ) { + Warning('Unable to symlink ' . $NewStorage->Path().'/'.$mid . ' to ' . $NewStorage->Path().'/'.$saferNewName); + } } if ( isset($changes['Width']) || isset($changes['Height']) ) { $newW = $_REQUEST['newMonitor']['Width']; diff --git a/web/includes/actions/monitors.php b/web/includes/actions/monitors.php new file mode 100644 index 000000000..8f56b0e3d --- /dev/null +++ b/web/includes/actions/monitors.php @@ -0,0 +1,52 @@ +Type() != 'WebSite' ) { + $Monitor->zmaControl('stop'); + $Monitor->zmcControl('stop'); + } + $Monitor->save($_REQUEST['newMonitor']); + if ( $Monitor->Function() != 'None' && $Monitor->Type() != 'WebSite' ) { + $Monitor->zmcControl('start'); + if ( $Monitor->Enabled() ) { + $Monitor->zmaControl('start'); + } + } + } // end foreach mid + $refreshParent = true; + $view = 'none'; +} else { + ZM\Warning("Unknown action $action in Monitor"); +} // end if action == Delete +?> diff --git a/web/includes/actions/montage.php b/web/includes/actions/montage.php index 7ab105d0c..207c9a0f0 100644 --- a/web/includes/actions/montage.php +++ b/web/includes/actions/montage.php @@ -29,10 +29,10 @@ if ( isset($_REQUEST['object']) ) { if ( $action == 'Save' ) { $Layout = null; if ( $_REQUEST['Name'] != '' ) { - $Layout = new MontageLayout(); + $Layout = new ZM\MontageLayout(); $Layout->Name($_REQUEST['Name']); } else { - $Layout = new MontageLayout($_REQUEST['zmMontageLayout']); + $Layout = new ZM\MontageLayout($_REQUEST['zmMontageLayout']); } $Layout->Positions($_REQUEST['Positions']); $Layout->save(); diff --git a/web/includes/actions/shutdown.php b/web/includes/actions/shutdown.php new file mode 100644 index 000000000..f6d31b4f4 --- /dev/null +++ b/web/includes/actions/shutdown.php @@ -0,0 +1,44 @@ +&1", $output, $rc); + #exec('sudo -n /bin/systemctl poweroff -i 2>&1', $output, $rc); + ZM\Logger::Debug("Shutdown output $rc " . implode("\n",$output)); + #ZM\Logger::Debug("Shutdown output " . shell_exec('/bin/systemctl poweroff -i 2>&1')); + } else if ( $action == 'restart' ) { + $output = array(); + exec("sudo -n /sbin/shutdown -r $when 2>&1", $output); + #exec('sudo -n /bin/systemctl reboot -i 2>&1', $output); + ZM\Logger::Debug("Shutdown output " . implode("\n",$output)); + } else if ( $action == 'cancel' ) { + $output = array(); + exec('sudo /sbin/shutdown -c 2>&1', $output); + } +} # end if action +?> diff --git a/web/includes/auth.php b/web/includes/auth.php index c16a1e7b8..6b061f7fc 100644 --- a/web/includes/auth.php +++ b/web/includes/auth.php @@ -82,11 +82,6 @@ function userLogin($username='', $password='', $passwordHashed=false) { session_start(); $close_session = 1; } - $_SESSION['username'] = $username; - if ( ZM_AUTH_RELAY == 'plain' ) { - // Need to save this in session - $_SESSION['password'] = $password; - } $_SESSION['remoteAddr'] = $_SERVER['REMOTE_ADDR']; // To help prevent session hijacking if ( $dbUser = dbFetchOne($sql, NULL, $sql_values) ) { ZM\Info("Login successful for user \"$username\""); @@ -95,6 +90,11 @@ function userLogin($username='', $password='', $passwordHashed=false) { if ( ZM_AUTH_TYPE == 'builtin' ) { $_SESSION['passwordHash'] = $user['Password']; } + $_SESSION['username'] = $user['Username']; + if ( ZM_AUTH_RELAY == 'plain' ) { + // Need to save this in session, can't use the value in User because it is hashed + $_SESSION['password'] = $_REQUEST['password']; + } zm_session_regenerate_id(); } else { ZM\Warning("Login denied for user \"$username\""); @@ -124,17 +124,19 @@ function getAuthUser($auth) { } } + $values = array(); if ( isset($_SESSION['username']) ) { # Most of the time we will be logged in already and the session will have our username, so we can significantly speed up our hash testing by only looking at our user. # Only really important if you have a lot of users. - $sql = "SELECT * FROM Users WHERE Enabled = 1 AND Username='".$_SESSION['username']."'"; + $sql = 'SELECT * FROM Users WHERE Enabled = 1 AND Username=?'; + array_push($values, $_SESSION['username']); } else { $sql = 'SELECT * FROM Users WHERE Enabled = 1'; } - foreach ( dbFetchAll($sql) as $user ) { + foreach ( dbFetchAll($sql, NULL, $values) as $user ) { $now = time(); - for ( $i = 0; $i < ZM_AUTH_HASH_TTL; $i++, $now -= (3600) ) { // Try for last two hours + for ( $i = 0; $i < ZM_AUTH_HASH_TTL; $i++, $now -= ZM_AUTH_HASH_TTL * 1800 ) { // Try for last two hours $time = localtime($now); $authKey = ZM_AUTH_HASH_SECRET.$user['Username'].$user['Password'].$remoteAddr.$time[2].$time[3].$time[4].$time[5]; $authHash = md5($authKey); @@ -205,19 +207,20 @@ function canEdit($area, $mid=false) { return ( $user[$area] == 'Edit' && ( !$mid || visibleMonitor($mid) )); } +global $user; if ( ZM_OPT_USE_AUTH ) { + $close_session = 0; + if ( !is_session_started() ) { + zm_session_start(); + $close_session = 1; + } + if ( isset($_SESSION['username']) ) { # Need to refresh permissions and validate that the user still exists $sql = 'SELECT * FROM Users WHERE Enabled=1 AND Username=?'; $user = dbFetchOne($sql, NULL, array($_SESSION['username'])); } - $close_session = 0; - if ( !is_session_started() ) { - session_start(); - $close_session = 1; - } - if ( ZM_AUTH_RELAY == 'plain' ) { // Need to save this in session $_SESSION['password'] = $password; diff --git a/web/includes/control_functions.php b/web/includes/control_functions.php index bea235668..77240df49 100644 --- a/web/includes/control_functions.php +++ b/web/includes/control_functions.php @@ -735,29 +735,29 @@ function buildControlCommand( $monitor ) { return( $ctrlCommand ); } -function sendControlCommand($mid,$command) { +function sendControlCommand($mid, $command) { // Either connects to running zmcontrol.pl or runs zmcontrol.pl to send the command. - $socket = socket_create( AF_UNIX, SOCK_STREAM, 0 ); + $socket = socket_create(AF_UNIX, SOCK_STREAM, 0); if ( $socket < 0 ) { - Fatal( 'socket_create() failed: '.socket_strerror($socket) ); + Fatal('socket_create() failed: '.socket_strerror($socket)); } $sockFile = ZM_PATH_SOCKS.'/zmcontrol-'.$mid.'.sock'; - if ( @socket_connect( $socket, $sockFile ) ) { + if ( @socket_connect($socket, $sockFile) ) { $options = array(); - foreach ( explode( ' ', $command ) as $option ) { - if ( preg_match( '/--([^=]+)(?:=(.+))?/', $option, $matches ) ) { + foreach ( explode(' ', $command) as $option ) { + if ( preg_match('/--([^=]+)(?:=(.+))?/', $option, $matches) ) { $options[$matches[1]] = $matches[2]?$matches[2]:1; } } - $optionString = jsonEncode( $options ); - if ( !socket_write( $socket, $optionString ) ) { - Fatal( "Can't write to control socket: ".socket_strerror(socket_last_error($socket)) ); + $optionString = jsonEncode($options); + if ( !socket_write($socket, $optionString) ) { + Fatal("Can't write to control socket: ".socket_strerror(socket_last_error($socket))); } - socket_close( $socket ); + socket_close($socket); } else if ( $command != 'quit' ) { $command .= ' --id='.$mid; // Can't connect so use script - $ctrlOutput = exec( escapeshellcmd( $command ) ); + $ctrlOutput = exec(escapeshellcmd($command)); } -} // end function sendControlCommand( $mid, $command ) +} // end function sendControlCommand($mid, $command) diff --git a/web/includes/csrf/csrf-magic.js b/web/includes/csrf/csrf-magic.js index 0989c1065..06ed62076 100644 --- a/web/includes/csrf/csrf-magic.js +++ b/web/includes/csrf/csrf-magic.js @@ -9,183 +9,185 @@ // The wrapper must be set BEFORE onreadystatechange is written to, since // a bug in ActiveXObject prevents us from properly testing for it. CsrfMagic = function(real) { - // try to make it ourselves, if you didn't pass it - if (!real) try { real = new XMLHttpRequest; } catch (e) {;} - if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {;} - if (!real) try { real = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {;} - if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP.4.0'); } catch (e) {;} - this.csrf = real; - // properties - var csrfMagic = this; - real.onreadystatechange = function() { - csrfMagic._updateProps(); - return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null; - }; + // try to make it ourselves, if you didn't pass it + if (!real) try {real = new XMLHttpRequest;} catch (e) {;} + if (!real) try {real = new ActiveXObject('Msxml2.XMLHTTP');} catch (e) {;} + if (!real) try {real = new ActiveXObject('Microsoft.XMLHTTP');} catch (e) {;} + if (!real) try {real = new ActiveXObject('Msxml2.XMLHTTP.4.0');} catch (e) {;} + this.csrf = real; + // properties + var csrfMagic = this; + real.onreadystatechange = function() { csrfMagic._updateProps(); -} + return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null; + }; + csrfMagic._updateProps(); +}; CsrfMagic.prototype = { - open: function(method, url, async, username, password) { - if (method == 'POST') this.csrf_isPost = true; - // deal with Opera bug, thanks jQuery - if (username) return this.csrf_open(method, url, async, username, password); - else return this.csrf_open(method, url, async); - }, - csrf_open: function(method, url, async, username, password) { - if (username) return this.csrf.open(method, url, async, username, password); - else return this.csrf.open(method, url, async); - }, + open: function(method, url, async, username, password) { + if (method == 'POST') this.csrf_isPost = true; + // deal with Opera bug, thanks jQuery + if (username) return this.csrf_open(method, url, async, username, password); + else return this.csrf_open(method, url, async); + }, + csrf_open: function(method, url, async, username, password) { + if (username) return this.csrf.open(method, url, async, username, password); + else return this.csrf.open(method, url, async); + }, - send: function(data) { - if (!this.csrf_isPost) return this.csrf_send(data); - prepend = csrfMagicName + '=' + csrfMagicToken + '&'; + send: function(data) { + if (!this.csrf_isPost) return this.csrf_send(data); + prepend = csrfMagicName + '=' + csrfMagicToken + '&'; // XXX: Removed to eliminate 'Refused to set unsafe header "Content-length" ' errors in modern browsers // if (this.csrf_purportedLength === undefined) { // this.csrf_setRequestHeader("Content-length", this.csrf_purportedLength + prepend.length); // delete this.csrf_purportedLength; // } - delete this.csrf_isPost; - return this.csrf_send(prepend + data); - }, - csrf_send: function(data) { - return this.csrf.send(data); - }, + delete this.csrf_isPost; + return this.csrf_send(prepend + data); + }, + csrf_send: function(data) { + return this.csrf.send(data); + }, - setRequestHeader: function(header, value) { - // We have to auto-set this at the end, since we don't know how long the - // nonce is when added to the data. - if (this.csrf_isPost && header == "Content-length") { - this.csrf_purportedLength = value; - return; - } - return this.csrf_setRequestHeader(header, value); - }, - csrf_setRequestHeader: function(header, value) { - return this.csrf.setRequestHeader(header, value); - }, + setRequestHeader: function(header, value) { + // We have to auto-set this at the end, since we don't know how long the + // nonce is when added to the data. + if (this.csrf_isPost && header == "Content-length") { + this.csrf_purportedLength = value; + return; + } + return this.csrf_setRequestHeader(header, value); + }, + csrf_setRequestHeader: function(header, value) { + return this.csrf.setRequestHeader(header, value); + }, - abort: function() { - return this.csrf.abort(); - }, - getAllResponseHeaders: function() { - return this.csrf.getAllResponseHeaders(); - }, - getResponseHeader: function(header) { - return this.csrf.getResponseHeader(header); - } // , -} + abort: function() { + return this.csrf.abort(); + }, + getAllResponseHeaders: function() { + return this.csrf.getAllResponseHeaders(); + }, + getResponseHeader: function(header) { + return this.csrf.getResponseHeader(header); + } // , +}; // proprietary CsrfMagic.prototype._updateProps = function() { - this.readyState = this.csrf.readyState; - if (this.readyState == 4) { - this.responseText = this.csrf.responseText; - this.responseXML = this.csrf.responseXML; - this.status = this.csrf.status; - this.statusText = this.csrf.statusText; - } -} + this.readyState = this.csrf.readyState; + if (this.readyState == 4) { + this.responseText = this.csrf.responseText; + this.responseXML = this.csrf.responseXML; + this.status = this.csrf.status; + this.statusText = this.csrf.statusText; + } +}; + CsrfMagic.process = function(base) { - if(typeof base == 'object') { - base[csrfMagicName] = csrfMagicToken; - return base; - } - var prepend = csrfMagicName + '=' + csrfMagicToken; - if (base) return prepend + '&' + base; - return prepend; -} + if ( typeof base == 'object' ) { + base[csrfMagicName] = csrfMagicToken; + return base; + } + var prepend = csrfMagicName + '=' + csrfMagicToken; + if ( base ) return prepend + '&' + base; + return prepend; +}; + // callback function for when everything on the page has loaded CsrfMagic.end = function() { - // This rewrites forms AGAIN, so in case buffering didn't work this - // certainly will. - forms = document.getElementsByTagName('form'); - for (var i = 0; i < forms.length; i++) { - form = forms[i]; - if (form.method.toUpperCase() !== 'POST') continue; - if (form.elements[csrfMagicName]) continue; - var input = document.createElement('input'); - input.setAttribute('name', csrfMagicName); - input.setAttribute('value', csrfMagicToken); - input.setAttribute('type', 'hidden'); - form.appendChild(input); - } -} + // This rewrites forms AGAIN, so in case buffering didn't work this + // certainly will. + forms = document.getElementsByTagName('form'); + for (var i = 0; i < forms.length; i++) { + form = forms[i]; + if (form.method.toUpperCase() !== 'POST') continue; + if (form.elements[csrfMagicName]) continue; + var input = document.createElement('input'); + input.setAttribute('name', csrfMagicName); + input.setAttribute('value', csrfMagicToken); + input.setAttribute('type', 'hidden'); + form.appendChild(input); + } +}; // Sets things up for Mozilla/Opera/nice browsers // We very specifically match against Internet Explorer, since they haven't // implemented prototypes correctly yet. -if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') { - var x = XMLHttpRequest.prototype; - var c = CsrfMagic.prototype; +if ( window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v' ) { + var x = XMLHttpRequest.prototype; + var c = CsrfMagic.prototype; - // Save the original functions - x.csrf_open = x.open; - x.csrf_send = x.send; - x.csrf_setRequestHeader = x.setRequestHeader; + // Save the original functions + x.csrf_open = x.open; + x.csrf_send = x.send; + x.csrf_setRequestHeader = x.setRequestHeader; - // Notice that CsrfMagic is itself an instantiatable object, but only - // open, send and setRequestHeader are necessary as decorators. - x.open = c.open; - x.send = c.send; - x.setRequestHeader = c.setRequestHeader; + // Notice that CsrfMagic is itself an instantiatable object, but only + // open, send and setRequestHeader are necessary as decorators. + x.open = c.open; + x.send = c.send; + x.setRequestHeader = c.setRequestHeader; } else { - // The only way we can do this is by modifying a library you have been - // using. We support YUI, script.aculo.us, prototype, MooTools, - // jQuery, Ext and Dojo. - if (window.jQuery) { - // jQuery didn't implement a new XMLHttpRequest function, so we have - // to do this the hard way. - jQuery.csrf_ajax = jQuery.ajax; - jQuery.ajax = function( s ) { - if (s.type && s.type.toUpperCase() == 'POST') { - s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s)); - if ( s.data && s.processData && typeof s.data != "string" ) { - s.data = jQuery.param(s.data); - } - s.data = CsrfMagic.process(s.data); - } - return jQuery.csrf_ajax( s ); + // The only way we can do this is by modifying a library you have been + // using. We support YUI, script.aculo.us, prototype, MooTools, + // jQuery, Ext and Dojo. + if ( window.jQuery ) { + // jQuery didn't implement a new XMLHttpRequest function, so we have + // to do this the hard way. + jQuery.csrf_ajax = jQuery.ajax; + jQuery.ajax = function( s ) { + if (s.type && s.type.toUpperCase() == 'POST') { + s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s)); + if ( s.data && s.processData && typeof s.data != "string" ) { + s.data = jQuery.param(s.data); } - } - if (window.Prototype) { - // This works for script.aculo.us too - Ajax.csrf_getTransport = Ajax.getTransport; - Ajax.getTransport = function() { - return new CsrfMagic(Ajax.csrf_getTransport()); - } - } - if (window.MooTools) { - Browser.csrf_Request = Browser.Request; - Browser.Request = function () { - return new CsrfMagic(Browser.csrf_Request()); - } - } - if (window.YAHOO) { - // old YUI API - YAHOO.util.Connect.csrf_createXhrObject = YAHOO.util.Connect.createXhrObject; - YAHOO.util.Connect.createXhrObject = function (transaction) { - obj = YAHOO.util.Connect.csrf_createXhrObject(transaction); - obj.conn = new CsrfMagic(obj.conn); - return obj; - } - } - if (window.Ext) { - // Ext can use other js libraries as loaders, so it has to come last - // Ext's implementation is pretty identical to Yahoo's, but we duplicate - // it for comprehensiveness's sake. - Ext.lib.Ajax.csrf_createXhrObject = Ext.lib.Ajax.createXhrObject; - Ext.lib.Ajax.createXhrObject = function (transaction) { - obj = Ext.lib.Ajax.csrf_createXhrObject(transaction); - obj.conn = new CsrfMagic(obj.conn); - return obj; - } - } - if (window.dojo) { - // NOTE: this doesn't work with latest dojo - dojo.csrf__xhrObj = dojo._xhrObj; - dojo._xhrObj = function () { - return new CsrfMagic(dojo.csrf__xhrObj()); - } - } -} + s.data = CsrfMagic.process(s.data); + } + return jQuery.csrf_ajax(s); + }; + } + if ( window.Prototype ) { + // This works for script.aculo.us too + Ajax.csrf_getTransport = Ajax.getTransport; + Ajax.getTransport = function() { + return new CsrfMagic(Ajax.csrf_getTransport()); + }; + } + if ( window.MooTools ) { + Browser.csrf_Request = Browser.Request; + Browser.Request = function() { + return new CsrfMagic(Browser.csrf_Request()); + }; + } + if ( window.YAHOO ) { + // old YUI API + YAHOO.util.Connect.csrf_createXhrObject = YAHOO.util.Connect.createXhrObject; + YAHOO.util.Connect.createXhrObject = function(transaction) { + obj = YAHOO.util.Connect.csrf_createXhrObject(transaction); + obj.conn = new CsrfMagic(obj.conn); + return obj; + }; + } + if ( window.Ext ) { + // Ext can use other js libraries as loaders, so it has to come last + // Ext's implementation is pretty identical to Yahoo's, but we duplicate + // it for comprehensiveness's sake. + Ext.lib.Ajax.csrf_createXhrObject = Ext.lib.Ajax.createXhrObject; + Ext.lib.Ajax.createXhrObject = function(transaction) { + obj = Ext.lib.Ajax.csrf_createXhrObject(transaction); + obj.conn = new CsrfMagic(obj.conn); + return obj; + }; + } + if ( window.dojo ) { + // NOTE: this doesn't work with latest dojo + dojo.csrf__xhrObj = dojo._xhrObj; + dojo._xhrObj = function() { + return new CsrfMagic(dojo.csrf__xhrObj()); + }; + } +}; diff --git a/web/includes/csrf/csrf-magic.php b/web/includes/csrf/csrf-magic.php index 584432ef7..d96165eb9 100644 --- a/web/includes/csrf/csrf-magic.php +++ b/web/includes/csrf/csrf-magic.php @@ -157,7 +157,8 @@ function csrf_ob_handler($buffer, $flags) { $input = ""; $buffer = preg_replace('#(]*method\s*=\s*["\']post["\'][^>]*>)#i', '$1' . $input, $buffer); if ($GLOBALS['csrf']['frame-breaker']) { - $buffer = str_ireplace('', '', $buffer); + $buffer = str_ireplace('', ' +', $buffer); } if ($js = $GLOBALS['csrf']['rewrite-js']) { $buffer = str_ireplace( @@ -165,7 +166,8 @@ function csrf_ob_handler($buffer, $flags) { ''. - '', + ' + ', $buffer ); $script = ''; @@ -209,6 +211,7 @@ break; } $ok = true; } while (false); + if ($fatal && !$ok) { $callback = $GLOBALS['csrf']['callback']; if (trim($tokens, 'A..Za..z0..9:;,') !== '') $tokens = 'hidden'; @@ -293,6 +296,7 @@ function csrf_callback($tokens) { // Don't make it too easy for users to inflict a CSRF attack on themselves. echo "

Only try again if you weren't sent to this page by someone as this is potentially a sign of an attack.

"; echo "
$data
"; + ZM\Logger::Debug("Failed csrf check"); } echo "

Debug: $tokens

"; diff --git a/web/includes/functions.php b/web/includes/functions.php index df6981fe8..ee168b273 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -283,12 +283,12 @@ function outputImageStream( $id, $src, $width, $height, $title='' ) { echo getImageStreamHTML( $id, $src, $width, $height, $title ); } - +// width and height MUST be valid and include the px function getImageStreamHTML( $id, $src, $width, $height, $title='' ) { if ( canStreamIframe() ) { return '