First iteration of h264 saving in the capture daemon.

To use, enable use_mkv_storage in the paths section of the ZM config (be sure to import the new SQL config)
Must have the latest FFMPEG compiled from git with x264 linked in
This commit is contained in:
Chris Wiggins 2013-09-06 14:53:24 +12:00
parent c8ad6ae656
commit b1d989ce30
18 changed files with 428 additions and 4921 deletions

File diff suppressed because it is too large Load Diff

View File

@ -193,6 +193,14 @@ our @options =
type => $types{rel_path}, type => $types{rel_path},
category => "paths", category => "paths",
}, },
{
name => "ZM_USE_MKV_STORAGE",
default => "no",
description => "UNDER DEVELOPMENT: Use a .mkv storage for events vs. JPEG",
help => "This is currently under active development and not working correctly. For now, ensure /var/www/zm/eventtemp is present and able to be written to (otherwise change the source). Please only use this option if you know what you're doing!",
type => $types{boolean},
category => "paths",
},
{ {
name => "ZM_COLOUR_JPEG_FILES", name => "ZM_COLOUR_JPEG_FILES",
default => "yes", default => "yes",

File diff suppressed because it is too large Load Diff

View File

@ -1,873 +0,0 @@
# ==========================================================================
#
# ZoneMinder Memory Access Module, $Date: 2008-02-25 10:13:13 +0000 (Mon, 25 Feb 2008) $, $Revision: 2323 $
# Copyright (C) 2001-2008 Philip Coombes
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# ==========================================================================
#
# This module contains the common definitions and functions used by the rest
# of the ZoneMinder scripts
#
package ZoneMinder::Memory;
use 5.006;
use strict;
use warnings;
require Exporter;
require ZoneMinder::Base;
our @ISA = qw(Exporter ZoneMinder::Base);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use ZoneMinder ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = (
'constants' => [ qw(
STATE_IDLE
STATE_PREALARM
STATE_ALARM
STATE_ALERT
STATE_TAPE
ACTION_GET
ACTION_SET
ACTION_RELOAD
ACTION_SUSPEND
ACTION_RESUME
TRIGGER_CANCEL
TRIGGER_ON
TRIGGER_OFF
) ],
'functions' => [ qw(
zmMemVerify
zmMemInvalidate
zmMemRead
zmMemWrite
zmMemTidy
zmGetMonitorState
zmGetAlarmLocation
zmIsAlarmed
zmInAlarm
zmHasAlarmed
zmGetLastEvent
zmGetLastWriteTime
zmGetLastReadTime
zmMonitorEnable
zmMonitorDisable
zmMonitorSuspend
zmMonitorResume
zmTriggerEventOn
zmTriggerEventOff
zmTriggerEventCancel
zmTriggerShowtext
) ],
);
push( @{$EXPORT_TAGS{all}}, @{$EXPORT_TAGS{$_}} ) foreach keys %EXPORT_TAGS;
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw();
our $VERSION = $ZoneMinder::Base::VERSION;
# ==========================================================================
#
# Shared Memory Facilities
#
# ==========================================================================
use ZoneMinder::Config qw(:all);
use ZoneMinder::Logger qw(:all);
use constant STATE_IDLE => 0;
use constant STATE_PREALARM => 1;
use constant STATE_ALARM => 2;
use constant STATE_ALERT => 3;
use constant STATE_TAPE => 4;
use constant ACTION_GET => 1;
use constant ACTION_SET => 2;
use constant ACTION_RELOAD => 4;
use constant ACTION_SUSPEND => 16;
use constant ACTION_RESUME => 32;
use constant TRIGGER_CANCEL => 0;
use constant TRIGGER_ON => 1;
use constant TRIGGER_OFF => 2;
use Storable qw( freeze thaw );
if ( "yes" eq 'yes' ) # 'yes' if memory is mmapped
{
require ZoneMinder::Memory::Mapped;
ZoneMinder::Memory::Mapped->import();
}
else
{
require ZoneMinder::Memory::Shared;
ZoneMinder::Memory::Shared->import();
}
# Native architecture
our $arch = int(3.2*length(~0));
our $native = $arch/8;
our $mem_seq = 0;
our $mem_data =
{
"shared_data" => { "type"=>"SharedData", "seq"=>$mem_seq++, "contents"=> {
"size" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"last_write_index" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"last_read_index" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"state" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"last_event" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"action" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"brightness" => { "type"=>"int32", "seq"=>$mem_seq++ },
"hue" => { "type"=>"int32", "seq"=>$mem_seq++ },
"colour" => { "type"=>"int32", "seq"=>$mem_seq++ },
"contrast" => { "type"=>"int32", "seq"=>$mem_seq++ },
"alarm_x" => { "type"=>"int32", "seq"=>$mem_seq++ },
"alarm_y" => { "type"=>"int32", "seq"=>$mem_seq++ },
"valid" => { "type"=>"uint8", "seq"=>$mem_seq++ },
"active" => { "type"=>"uint8", "seq"=>$mem_seq++ },
"signal" => { "type"=>"uint8", "seq"=>$mem_seq++ },
"format" => { "type"=>"uint8", "seq"=>$mem_seq++ },
"imagesize" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"epadding1" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"epadding2" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"last_write_time" => { "type"=>"time_t64", "seq"=>$mem_seq++ },
"last_read_time" => { "type"=>"time_t64", "seq"=>$mem_seq++ },
"control_state" => { "type"=>"uint8[256]", "seq"=>$mem_seq++ },
}
},
"trigger_data" => { "type"=>"TriggerData", "seq"=>$mem_seq++, "contents"=> {
"size" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"trigger_state" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"trigger_score" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"padding" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"trigger_cause" => { "type"=>"int8[32]", "seq"=>$mem_seq++ },
"trigger_text" => { "type"=>"int8[256]", "seq"=>$mem_seq++ },
"trigger_showtext" => { "type"=>"int8[256]", "seq"=>$mem_seq++ },
}
},
"end" => { "seq"=>$mem_seq++, "size"=> 0 }
};
our $mem_size = 0;
our $mem_verified = {};
sub zmMemInit
{
my $offset = 0;
foreach my $section_data ( sort { $a->{seq} <=> $b->{seq} } values( %$mem_data ) )
{
$section_data->{offset} = $offset;
$section_data->{align} = 0;
if ( $section_data->{align} > 1 )
{
my $rem = $offset % $section_data->{align};
if ( $rem > 0 )
{
$offset += ($section_data->{align} - $rem);
}
}
foreach my $member_data ( sort { $a->{seq} <=> $b->{seq} } values( %{$section_data->{contents}} ) )
{
if ( $member_data->{type} eq "long" || $member_data->{type} eq "ulong" || $member_data->{type} eq "size_t")
{
$member_data->{size} = $member_data->{align} = $native;
}
elsif( $member_data->{type} eq "int64" || $member_data->{type} eq "uint64" || $member_data->{type} eq "time_t64")
{
$member_data->{size} = $member_data->{align} = 8;
}
elsif ( $member_data->{type} eq "int32" || $member_data->{type} eq "uint32" || $member_data->{type} eq "bool4" )
{
$member_data->{size} = $member_data->{align} = 4;
}
elsif ($member_data->{type} eq "int16" || $member_data->{type} eq "uint16")
{
$member_data->{size} = $member_data->{align} = 2;
}
elsif ( $member_data->{type} eq "int8" || $member_data->{type} eq "uint8" || $member_data->{type} eq "bool1" )
{
$member_data->{size} = $member_data->{align} = 1;
}
elsif ( $member_data->{type} =~ /^u?int8\[(\d+)\]$/ )
{
$member_data->{size} = $1;
$member_data->{align} = 1;
}
else
{
Fatal( "Unexpected type '".$member_data->{type}."' found in shared data definition." );
}
if ( $member_data->{align} > 1 && ($offset%$member_data->{align}) > 0 )
{
$offset += ($member_data->{align} - ($offset%$member_data->{align}));
}
$member_data->{offset} = $offset;
$offset += $member_data->{size}
}
$section_data->{size} = $offset - $section_data->{offset};
}
$mem_size = $offset;
}
&zmMemInit();
sub zmMemVerify( $ )
{
my $monitor = shift;
if ( !zmMemAttach( $monitor, $mem_size ) )
{
return( undef );
}
my $mem_key = zmMemKey( $monitor );
if ( !defined($mem_verified->{$mem_key}) )
{
my $sd_size = zmMemRead( $monitor, "shared_data:size", 1 );
if ( $sd_size != $mem_data->{shared_data}->{size} )
{
if ( $sd_size )
{
Error( "Shared data size conflict in shared_data for monitor ".$monitor->{Name}.", expected ".$mem_data->{shared_data}->{size}.", got ".$sd_size );
}
else
{
Debug( "Shared data size conflict in shared_data for monitor ".$monitor->{Name}.", expected ".$mem_data->{shared_data}->{size}.", got ".$sd_size );
}
return( undef );
}
my $td_size = zmMemRead( $monitor, "trigger_data:size", 1 );
if ( $td_size != $mem_data->{trigger_data}->{size} )
{
if ( $td_size )
{
Error( "Shared data size conflict in trigger_data for monitor ".$monitor->{Name}.", expected ".$mem_data->{triggger_data}->{size}.", got ".$td_size );
}
else
{
Debug( "Shared data size conflict in trigger_data for monitor ".$monitor->{Name}.", expected ".$mem_data->{triggger_data}->{size}.", got ".$td_size );
}
return( undef );
}
$mem_verified->{$mem_key} = !undef;
}
return( !undef );
}
sub zmMemRead( $$;$ )
{
my $monitor = shift;
my $fields = shift;
my $nocheck = shift;
if ( !($nocheck || zmMemVerify( $monitor )) )
{
return( undef );
}
if ( !ref($fields) )
{
$fields = [ $fields ];
}
my @values;
foreach my $field ( @$fields )
{
my ( $section, $element ) = split( /[\/:.]/, $field );
Fatal( "Invalid shared data selector '$field'" ) if ( !$section || !$element );
my $offset = $mem_data->{$section}->{contents}->{$element}->{offset};
my $type = $mem_data->{$section}->{contents}->{$element}->{type};
my $size = $mem_data->{$section}->{contents}->{$element}->{size};
my $data = zmMemGet( $monitor, $offset, $size );
if ( !defined($data) )
{
Error( "Unable to read '$field' from memory for monitor ".$monitor->{Id} );
zmMemInvalidate( $monitor );
return( undef );
}
my $value;
if ( $type eq "long" )
{
( $value ) = unpack( "l!", $data );
}
elsif ( $type eq "ulong" || $type eq "size_t" )
{
( $value ) = unpack( "L!", $data );
}
elsif ( $type eq "int64" || $type eq "time_t64" )
{
# The "q" type is only available on 64bit platforms, so use native.
( $value ) = unpack( "l!", $data );
}
elsif ( $type eq "uint64" )
{
# The "q" type is only available on 64bit platforms, so use native.
( $value ) = unpack( "L!", $data );
}
elsif ( $type eq "int32" )
{
( $value ) = unpack( "l", $data );
}
elsif ( $type eq "uint32" || $type eq "bool4" )
{
( $value ) = unpack( "L", $data );
}
elsif ( $type eq "int16" )
{
( $value ) = unpack( "s", $data );
}
elsif ( $type eq "uint16" )
{
( $value ) = unpack( "S", $data );
}
elsif ( $type eq "int8" )
{
( $value ) = unpack( "c", $data );
}
elsif ( $type eq "uint8" || $type eq "bool1" )
{
( $value ) = unpack( "C", $data );
}
elsif ( $type =~ /^int8\[\d+\]$/ )
{
( $value ) = unpack( "Z".$size, $data );
}
elsif ( $type =~ /^uint8\[\d+\]$/ )
{
( $value ) = unpack( "C".$size, $data );
}
else
{
Fatal( "Unexpected type '".$type."' found for '".$field."'" );
}
push( @values, $value );
}
if ( wantarray() )
{
return( @values )
}
return( $values[0] );
}
sub zmMemInvalidate( $ )
{
my $monitor = shift;
my $mem_key = zmMemKey($monitor);
if ( $mem_key )
{
delete $mem_verified->{$mem_key};
zmMemDetach( $monitor );
}
}
sub zmMemTidy()
{
zmMemClean();
}
sub zmMemWrite( $$;$ )
{
my $monitor = shift;
my $field_values = shift;
my $nocheck = shift;
if ( !($nocheck || zmMemVerify( $monitor )) )
{
return( undef );
}
while ( my ( $field, $value ) = each( %$field_values ) )
{
my ( $section, $element ) = split( /[\/:.]/, $field );
Fatal( "Invalid shared data selector '$field'" ) if ( !$section || !$element );
my $offset = $mem_data->{$section}->{contents}->{$element}->{offset};
my $type = $mem_data->{$section}->{contents}->{$element}->{type};
my $size = $mem_data->{$section}->{contents}->{$element}->{size};
my $data;
if ( $type eq "long" )
{
$data = pack( "l!", $value );
}
elsif ( $type eq "ulong" || $type eq "size_t" )
{
$data = pack( "L!", $value );
}
elsif ( $type eq "int64" || $type eq "time_t64" )
{
# The "q" type is only available on 64bit platforms, so use native.
$data = pack( "l!", $value );
}
elsif ( $type eq "uint64" )
{
# The "q" type is only available on 64bit platforms, so use native.
$data = pack( "L!", $value );
}
elsif ( $type eq "int32" )
{
$data = pack( "l", $value );
}
elsif ( $type eq "uint32" || $type eq "bool4" )
{
$data = pack( "L", $value );
}
elsif ( $type eq "int16" )
{
$data = pack( "s", $value );
}
elsif ( $type eq "uint16" )
{
$data = pack( "S", $value );
}
elsif ( $type eq "int8" )
{
$data = pack( "c", $value );
}
elsif ( $type eq "uint8" || $type eq "bool1" )
{
$data = pack( "C", $value );
}
elsif ( $type =~ /^int8\[\d+\]$/ )
{
$data = pack( "Z".$size, $value );
}
elsif ( $type =~ /^uint8\[\d+\]$/ )
{
$data = pack( "C".$size, $value );
}
else
{
Fatal( "Unexpected type '".$type."' found for '".$field."'" );
}
if ( !zmMemPut( $monitor, $offset, $size, $data ) )
{
Error( "Unable to write '$value' to '$field' in memory for monitor ".$monitor->{Id} );
zmMemInvalidate( $monitor );
return( undef );
}
}
return( !undef );
}
sub zmGetMonitorState( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "shared_data:state" ) );
}
sub zmGetAlarmLocation( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, [ "shared_data:alarm_x", "shared_data:alarm_y" ] ) );
}
sub zmSetControlState( $$ )
{
my $monitor = shift;
my $control_state = shift;
zmMemWrite( $monitor, { "shared_data:control_state" => $control_state } );
}
sub zmGetControlState( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "shared_data:control_state" ) );
}
sub zmSaveControlState( $$ )
{
my $monitor = shift;
my $control_state = shift;
zmSetControlState( $monitor, freeze( $control_state ) );
}
sub zmRestoreControlState( $ )
{
my $monitor = shift;
return( thaw( zmGetControlState( $monitor ) ) );
}
sub zmIsAlarmed( $ )
{
my $monitor = shift;
my $state = zmGetMonitorState( $monitor );
return( $state == STATE_ALARM );
}
sub zmInAlarm( $ )
{
my $monitor = shift;
my $state = zmGetMonitorState( $monitor );
return( $state == STATE_ALARM || $state == STATE_ALERT );
}
sub zmHasAlarmed( $$ )
{
my $monitor = shift;
my $last_event_id = shift;
my ( $state, $last_event ) = zmMemRead( $monitor, [ "shared_data:state", "shared_data:last_event" ] );
if ( $state == STATE_ALARM || $state == STATE_ALERT )
{
return( $last_event );
}
elsif( $last_event != $last_event_id )
{
return( $last_event );
}
return( undef );
}
sub zmGetLastEvent( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "shared_data:last_event" ) );
}
sub zmGetLastWriteTime( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "shared_data:last_write_time" ) );
}
sub zmGetLastReadTime( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "shared_data:last_read_time" ) );
}
sub zmGetMonitorActions( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "shared_data:action" ) );
}
sub zmMonitorEnable( $ )
{
my $monitor = shift;
my $action = zmMemRead( $monitor, "shared_data:action" );
$action |= ACTION_SUSPEND;
zmMemWrite( $monitor, { "shared_data:action" => $action } );
}
sub zmMonitorDisable( $ )
{
my $monitor = shift;
my $action = zmMemRead( $monitor, "shared_data:action" );
$action |= ACTION_RESUME;
zmMemWrite( $monitor, { "shared_data:action" => $action } );
}
sub zmMonitorSuspend( $ )
{
my $monitor = shift;
my $action = zmMemRead( $monitor, "shared_data:action" );
$action |= ACTION_SUSPEND;
zmMemWrite( $monitor, { "shared_data:action" => $action } );
}
sub zmMonitorResume( $ )
{
my $monitor = shift;
my $action = zmMemRead( $monitor, "shared_data:action" );
$action |= ACTION_RESUME;
zmMemWrite( $monitor, { "shared_data:action" => $action } );
}
sub zmGetTriggerState( $ )
{
my $monitor = shift;
return( zmMemRead( $monitor, "trigger_data:trigger_state" ) );
}
sub zmTriggerEventOn( $$$;$$ )
{
my $monitor = shift;
my $score = shift;
my $cause = shift;
my $text = shift;
my $showtext = shift;
my $values = {
"trigger_data:trigger_score" => $score,
"trigger_data:trigger_cause" => $cause,
};
$values->{"trigger_data:trigger_text"} = $text if ( defined($text) );
$values->{"trigger_data:trigger_showtext"} = $showtext if ( defined($showtext) );
$values->{"trigger_data:trigger_state"} = TRIGGER_ON; # Write state last so event not read incomplete
zmMemWrite( $monitor, $values );
}
sub zmTriggerEventOff( $ )
{
my $monitor = shift;
my $values = {
"trigger_data:trigger_state" => TRIGGER_OFF,
"trigger_data:trigger_score" => 0,
"trigger_data:trigger_cause" => "",
"trigger_data:trigger_text" => "",
"trigger_data:trigger_showtext" => "",
};
zmMemWrite( $monitor, $values );
}
sub zmTriggerEventCancel( $ )
{
my $monitor = shift;
my $values = {
"trigger_data:trigger_state" => TRIGGER_CANCEL,
"trigger_data:trigger_score" => 0,
"trigger_data:trigger_cause" => "",
"trigger_data:trigger_text" => "",
"trigger_data:trigger_showtext" => "",
};
zmMemWrite( $monitor, $values );
}
sub zmTriggerShowtext( $$ )
{
my $monitor = shift;
my $showtext = shift;
my $values = {
"trigger_data:trigger_showtext" => $showtext,
};
zmMemWrite( $monitor, $values );
}
1;
__END__
=head1 NAME
ZoneMinder::MappedMem - ZoneMinder Mapped Memory access module
=head1 SYNOPSIS
use ZoneMinder::MappedMem;
use ZoneMinder::MappedMem qw(:all);
if ( zmMemVerify( $monitor ) )
{
$state = zmGetMonitorState( $monitor );
if ( $state == STATE_ALARM )
{
...
}
}
( $lri, $lwi ) = zmMemRead( $monitor, [ "shared_data:last_read_index", "shared_data:last_write_index" ] );
zmMemWrite( $monitor, { "trigger_data:trigger_showtext" => "Some Text" } );
=head1 DESCRIPTION
The ZoneMinder:MappedMem module contains methods for accessing and writing to mapped memory as well as helper methods for common operations.
The core elements of ZoneMinder used mapped memory to allow multiple access to resources. Although ZoneMinder scripts have used this information before, up until now it was difficult to access and prone to errors. This module introduces a common API for mapped memory access (both reading and writing) making it a lot easier to customise scripts or even create your own.
All the methods listed below require a 'monitor' parameter. This must be a reference to a hash with at least the 'Id' field set to the monitor id of the mapped memory you wish to access. Using database methods to select the monitor details will also return this kind of data. Some of the mapped memory methods will add and amend new fields to this hash.
=over 4
=head1 METHODS
=item zmMemVerify ( $monitor );
Verify that the mapped memory of the monitor given exists and is valid. It will return an undefined value if it is not valid. You should generally call this method first before using any of the other methods, but most of the remaining methods will also do so if the memory has not already been verified.
=item zmMemInvalidate ( $monitor );
Following an error, reset the mapped memory ids and attempt to reverify on the next operation. This is mostly used when a mapped memory segment has gone away and been recreated with a different id.
=item zmMemRead ( $monitor, $readspec );
This method is used to read data from mapped memory attached to the given monitor. The mapped memory will be verified if it has not already been. The 'readspec' must either be a string of the form "<section>:<field>" or a reference to an array of strings of the same format. In the first case a single value is returned, in the latter case a list of values is return. Errors will cause undefined to be returned. The allowable sections and field names are described below.
=item zmMemWrite ( $monitor, $writespec );
This method is used to write data to mapped memory attached to the given monitor. The mapped memory will be verified if it has not already been. The 'writespec' must be a reference to a hash with keys of the form "<section>:<field>" and values as the data to be written. Errors will cause undefined to be returned, otherwise a non-undefined value will be returned. The allowable sections and field names are described below.
=item $state = zmGetMonitorState ( $monitor );
Return the current state of the given monitor. This is an integer value and can be compared with the STATE constants given below.
=item $event_id = zmGetLastEvent ( $monitor );
Return the event id of the last event that the monitor generated, or 0 if no event has been generated by the current monitor process.
=item zmIsAlarmed ( $monitor );
Return 1 if the monitor given is currently in an alarm state, 0 otherwise.
=item zmInAlarm ( $monitor );
Return 1 if the monitor given is currently in an alarm or alerted state, 0 otherwise.
=item zmHasAlarmed ( $monitor );
Return 1 if the given monitor is in an alarm state, or has been in an alarm state since the last call to this method.
=item ( $x, $y ) = zmGetAlarmLocation ( $monitor );
Return an x,y pair indicating the image co-ordinates of the centre of the last motion event generated by the given monitor. If no event has been generated by the current monitor process, or the alarm was not motion related, returns -1,-1.
=item zmGetLastWriteTime ( $monitor );
Returns the time (in utc seconds) since the last image was captured by the given monitor and written to shared memory, or 0 otherwise.
=item zmGetLastReadTime ( $monitor );
Returns the time (in utc seconds) since the last image was read from shared memory by the analysis daemon of the given monitor, or 0 otherwise or if the monitor is in monitor only mode.
=item zmMonitorSuspend ( $monitor );
Suspend the given monitor from generating events caused by motion. This method can be used to prevent camera actions such as panning or zooming from causing events. If configured to do so, the monitor may automatically resume after a defined period.
=item zmMonitorResume ( $monitor );
Allow the given monitor to resume generating events caused by motion.
=item zmTriggerEventOn ( $monitor, $score, $cause [, $text, $showtext ] );
Trigger the given monitor to generate an event. You must supply an event score and a cause string indicating the reason for the event. You may also supply a text string containing further details about the event and a showtext string which may be included in the timestamp annotation on any images captured during the event, if configured to do so.
=item zmTriggerEventOff ( $monitor );
Trigger the given monitor to not generate any events. This method does not cancel zmTriggerEventOn, but is exclusive to it. This method is intended to allow external triggers to prevent normal events being generated by monitors in the same way as zmMonitorSuspend but applies to all events and not just motion, and is intended for longer timescales than are appropriate for suspension.
=item zmTriggerEventCancel ( $monitor );
Cancel any previous trigger on or off requests. This stops a triggered alarm if it exists from a previous 'on' and allows events to be generated once more following a previous 'off'.
=item zmTriggerShowtext ( $monitor, $showtest );
Indicate that the given text should be displayed in the timestamp annotation on any images captured, if the format of the annotation string defined for the monitor permits.
=head1 DATA
The data fields in mapped memory that may be accessed are as follows. There are two main sections, shared_data which is general data and trigger_data which is used for event triggering. Whilst reading from these fields is harmless, extreme care must be taken when writing to mapped memory, especially in the shared_data section as this is normally written to only by monitor capture and analysis processes.
shared_data The general mapped memory section
size The size, in bytes, of this section
valid Flag indicating whether this section has been initialised
active Flag indicating whether this monitor is active (enabled/disabled)
signal Flag indicating whether this monitor is reciving a valid signal
state The current monitor state, see the STATE constants below
last_write_index The last index, in the image buffer, that an image has been saved to
last_read_index The last index, in the image buffer, that an image has been analysed from
last_write_time The time (in utc seconds) when the last image was captured
last_read_time The time (in utc seconds) when the last image was analysed
last_event The id of the last event generated by the monitor analysis process, 0 if none
action The monitor actions bitmask, see the ACTION constants below
brightness Read/write location for the current monitor brightness
hue Read/write location for the current monitor hue
colour Read/write location for the current monitor colour
contrast Read/write location for the current monitor contrast
alarm_x Image x co-ordinate (from left) of the centre of the last motion event, -1 if none
alarm_y Image y co-ordinate (from top) of the centre of the last motion event, -1 if none
trigger_data The triggered event mapped memory section
size The size, in bytes of this section
trigger_state The current trigger state, see the TRIGGER constants below
trigger_score The current triggered event score
trigger_cause The current triggered event cause string
trigger_text The current triggered event descriptive text string
trigger_showtext The triggered text that will be displayed on captured image timestamps
=head1 CONSTANTS
The following constants are used by the methods above, but can also be used by user scripts if required.
=item STATE_IDLE STATE_PREALARM STATE_ALARM STATE_ALERT STATE_TAPE
These constants define the state of the monitor with respect to alarms and events. They are used in the shared_data:state field.
=item ACTION_GET ACTION_SET ACTION_RELOAD ACTION_SUSPEND ACTION_RESUME
These constants defines the various values that can exist in the shared_data:action field. This is a bitmask which when non-zero defines an action that an executing monitor process should take. ACTION_GET requires that the current values of brightness, contrast, colour and hue are taken from the camera and written to the equivalent mapped memory fields. ACTION_SET implies the reverse, that the values in mapped memory should be written to the camera. ACTION_RELOAD signal that the monitor process should reload itself from the database in case any settings have changed there. ACTION_SUSPEND signals that a monitor should stop exaiming images for motion, though other alarms may still occur. ACTION_RESUME sigansl that a monitor should resume motion detectiom.
=item TRIGGER_CANCEL TRIGGER_ON TRIGGER_OFF
These constants are used in the definition of external triggers. TRIGGER_CANCEL is used to indicated that any previous trigger settings should be cancelled, TRIGGER_ON signals that an alarm should be created (or continued)) as a result of the current trigger and TRIGGER_OFF signals that the trigger should prevent any alarms from being generated. See the trigger methods above for further details.
=head1 EXPORT
None by default.
The :constants tag will export the mapped memory constants which mostly define enumerations for the variables held in memory
The :functions tag will export the mapped memory access functions.
The :all tag will export all above symbols.
=head1 SEE ALSO
http://www.zoneminder.com
=head1 AUTHOR
Philip Coombes, E<lt>philip.coombes@zoneminder.comE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2001-2008 Philip Coombes
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.3 or,
at your option, any later version of Perl 5 you may have available.
=cut

View File

@ -168,6 +168,12 @@ our $mem_data =
"trigger_showtext" => { "type"=>"int8[256]", "seq"=>$mem_seq++ }, "trigger_showtext" => { "type"=>"int8[256]", "seq"=>$mem_seq++ },
} }
}, },
"video_store_data" => { "type"=>"VideoStoreData", "seq"=>$mem_seq++, "contents"=> {
"size" => { "type"=>"uint32", "seq"=>$mem_seq++ },
"event_directory" => { "type"=>"int8[4096]", "seq"=>$mem_seq++ },
"recording" => { "type"=>"uint32", "seq"=>$mem_seq++ },
}
},
"end" => { "seq"=>$mem_seq++, "size"=> 0 } "end" => { "seq"=>$mem_seq++, "size"=> 0 }
}; };
@ -275,6 +281,19 @@ sub zmMemVerify( $ )
} }
return( undef ); return( undef );
} }
my $vs_size = zmMemRead( $monitor, "video_store_data:size", 1 );
if ( $vs_size != $mem_data->{video_store_data}->{size} )
{
if ( $vs_size )
{
Error( "Shared data size conflict in video_store_data for monitor ".$monitor->{Name}.", expected ".$mem_data->{video_store_data}->{size}.", got ".$vs_size );
}
else
{
Debug( "Shared data size conflict in video_store_data for monitor ".$monitor->{Name}.", expected ".$mem_data->{video_store_data}->{size}.", got ".$vs_size );
}
return( undef );
}
$mem_verified->{$mem_key} = !undef; $mem_verified->{$mem_key} = !undef;
} }
return( !undef ); return( !undef );

View File

@ -58,6 +58,7 @@ zm_SOURCES = \
zm_timer.cpp \ zm_timer.cpp \
zm_user.cpp \ zm_user.cpp \
zm_utils.cpp \ zm_utils.cpp \
zm_videostore.cpp \
zm_zone.cpp zm_zone.cpp
zmc_SOURCES = zmc.cpp $(zm_SOURCES) zmc_SOURCES = zmc.cpp $(zm_SOURCES)
@ -113,6 +114,7 @@ noinst_HEADERS = \
zm_timer.h \ zm_timer.h \
zm_user.h \ zm_user.h \
zm_utils.h \ zm_utils.h \
zm_videostore.h \
zm_zone.h zm_zone.h
EXTRA_DIST = \ EXTRA_DIST = \

View File

@ -76,6 +76,7 @@ public:
virtual int PreCapture()=0; virtual int PreCapture()=0;
virtual int Capture( Image &image )=0; virtual int Capture( Image &image )=0;
virtual int PostCapture()=0; virtual int PostCapture()=0;
virtual int CaptureAndRecord( Image &image, bool recording, char* event_directory)=0;
}; };
#endif // ZM_CAMERA_H #endif // ZM_CAMERA_H

View File

@ -40,6 +40,8 @@ FfmpegCamera::FfmpegCamera( int p_id, const std::string &p_path, int p_width, in
mFrame = NULL; mFrame = NULL;
frameCount = 0; frameCount = 0;
wasRecording = false;
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
mConvertContext = NULL; mConvertContext = NULL;
#endif #endif
@ -61,6 +63,9 @@ FfmpegCamera::FfmpegCamera( int p_id, const std::string &p_path, int p_width, in
FfmpegCamera::~FfmpegCamera() FfmpegCamera::~FfmpegCamera()
{ {
if(videoStore)
delete videoStore;
av_freep( &mFrame ); av_freep( &mFrame );
av_freep( &mRawFrame ); av_freep( &mRawFrame );
@ -254,6 +259,99 @@ int FfmpegCamera::Capture( Image &image )
return (0); return (0);
} }
//Function to handle capture and store
int FfmpegCamera::CaptureAndRecord( Image &image, bool recording, char* event_directory )
{
AVPacket packet;
uint8_t* directbuffer;
//Warning("Recording: %d", (int)recording);
if(recording && !wasRecording){
if(event_directory!=NULL){
//Instanciate the video storage module
char fileName[255];
snprintf(fileName, sizeof(fileName), "%s/event.mkv", event_directory);
Info("fileName: %s", fileName);
videoStore = new VideoStore((const char *)fileName, "matroska", mFormatContext->streams[mVideoStreamId]);
wasRecording = true;
}
}else if(!recording && wasRecording){
Warning("Deleting videoStore instance");
delete videoStore;
}
/* Request a writeable buffer of the target image */
directbuffer = image.WriteBuffer(width, height, colours, subpixelorder);
if(directbuffer == NULL) {
Error("Failed requesting writeable buffer for the captured image.");
return (-1);
}
int frameComplete = false;
while ( !frameComplete )
{
int avResult = av_read_frame( mFormatContext, &packet );
if ( avResult < 0 )
{
Error( "Unable to read packet from stream %d: error %d", packet.stream_index, avResult );
return( -1 );
}
Debug( 5, "Got packet from stream %d", packet.stream_index );
if ( packet.stream_index == mVideoStreamId )
{
if ( avcodec_decode_video2( mCodecContext, mRawFrame, &frameComplete, &packet ) < 0 )
Fatal( "Unable to decode frame at frame %d", frameCount );
Debug( 4, "Decoded video packet at frame %d", frameCount );
if ( frameComplete )
{
Debug( 3, "Got frame %d", frameCount );
avpicture_fill( (AVPicture *)mFrame, directbuffer, imagePixFormat, width, height);
if(videoStore){
//Write the packet to our video store
//Info("Writing Packet");
videoStore->writeVideoFramePacket(&packet, mFormatContext->streams[mVideoStreamId], mFormatContext);
}
#if HAVE_LIBSWSCALE
if(mConvertContext == NULL) {
if(config.cpu_extensions && sseversion >= 20) {
mConvertContext = sws_getContext( mCodecContext->width, mCodecContext->height, mCodecContext->pix_fmt, width, height, imagePixFormat, SWS_BICUBIC | SWS_CPU_CAPS_SSE2, NULL, NULL, NULL );
} else {
mConvertContext = sws_getContext( mCodecContext->width, mCodecContext->height, mCodecContext->pix_fmt, width, height, imagePixFormat, SWS_BICUBIC, NULL, NULL, NULL );
}
if(mConvertContext == NULL)
Fatal( "Unable to create conversion context for %s", mPath.c_str() );
}
if ( sws_scale( mConvertContext, mRawFrame->data, mRawFrame->linesize, 0, mCodecContext->height, mFrame->data, mFrame->linesize ) < 0 )
Fatal( "Unable to convert raw format %u to target format %u at frame %d", mCodecContext->pix_fmt, imagePixFormat, frameCount );
#else // HAVE_LIBSWSCALE
Fatal( "You must compile ffmpeg with the --enable-swscale option to use ffmpeg cameras" );
#endif // HAVE_LIBSWSCALE
frameCount++;
}
}
av_free_packet( &packet );
}
return (0);
}
int FfmpegCamera::PostCapture() int FfmpegCamera::PostCapture()
{ {
// Nothing to do here // Nothing to do here

View File

@ -25,6 +25,7 @@
#include "zm_buffer.h" #include "zm_buffer.h"
//#include "zm_utils.h" //#include "zm_utils.h"
#include "zm_ffmpeg.h" #include "zm_ffmpeg.h"
#include "zm_videostore.h"
// //
// Class representing 'remote' cameras, i.e. those which are // Class representing 'remote' cameras, i.e. those which are
@ -47,6 +48,9 @@ protected:
PixelFormat imagePixFormat; PixelFormat imagePixFormat;
#endif // HAVE_LIBAVFORMAT #endif // HAVE_LIBAVFORMAT
bool wasRecording;
VideoStore *videoStore;
#if HAVE_LIBSWSCALE #if HAVE_LIBSWSCALE
struct SwsContext *mConvertContext; struct SwsContext *mConvertContext;
#endif #endif
@ -63,6 +67,7 @@ public:
int PrimeCapture(); int PrimeCapture();
int PreCapture(); int PreCapture();
int Capture( Image &image ); int Capture( Image &image );
int CaptureAndRecord( Image &image, bool recording, char* event_directory );
int PostCapture(); int PostCapture();
}; };

View File

@ -46,6 +46,7 @@ public:
int PreCapture(); int PreCapture();
int Capture( Image &image ); int Capture( Image &image );
int PostCapture(); int PostCapture();
int CaptureAndRecord( Image &image, bool recording, char* event_directory ) {return(0);};
}; };
#endif // ZM_FILE_CAMERA_H #endif // ZM_FILE_CAMERA_H

View File

@ -134,6 +134,7 @@ public:
int PreCapture(); int PreCapture();
int Capture( Image &image ); int Capture( Image &image );
int PostCapture(); int PostCapture();
int CaptureAndRecord( Image &image, bool recording, char* event_directory ) {return(0);};
static bool GetCurrentSettings( const char *device, char *output, int version, bool verbose ); static bool GetCurrentSettings( const char *device, char *output, int version, bool verbose );
}; };

View File

@ -372,6 +372,7 @@ Monitor::Monitor(
mem_size = sizeof(SharedData) mem_size = sizeof(SharedData)
+ sizeof(TriggerData) + sizeof(TriggerData)
+ sizeof(VideoStoreData) //Information to pass back to the capture process
+ (image_buffer_count*sizeof(struct timeval)) + (image_buffer_count*sizeof(struct timeval))
+ (image_buffer_count*camera->ImageSize()) + (image_buffer_count*camera->ImageSize())
+ 64; /* Padding used to permit aligning the images buffer to 16 byte boundary */ + 64; /* Padding used to permit aligning the images buffer to 16 byte boundary */
@ -422,7 +423,8 @@ Monitor::Monitor(
shared_data = (SharedData *)mem_ptr; shared_data = (SharedData *)mem_ptr;
trigger_data = (TriggerData *)((char *)shared_data + sizeof(SharedData)); trigger_data = (TriggerData *)((char *)shared_data + sizeof(SharedData));
struct timeval *shared_timestamps = (struct timeval *)((char *)trigger_data + sizeof(TriggerData)); video_store_data = (VideoStoreData *)((char *)shared_data + sizeof(SharedData));
struct timeval *shared_timestamps = (struct timeval *)((char *)video_store_data + sizeof(VideoStoreData));
unsigned char *shared_images = (unsigned char *)((char *)shared_timestamps + (image_buffer_count*sizeof(struct timeval))); unsigned char *shared_images = (unsigned char *)((char *)shared_timestamps + (image_buffer_count*sizeof(struct timeval)));
if(((unsigned long)shared_images % 16) != 0) { if(((unsigned long)shared_images % 16) != 0) {
@ -459,6 +461,9 @@ Monitor::Monitor(
trigger_data->trigger_text[0] = 0; trigger_data->trigger_text[0] = 0;
trigger_data->trigger_showtext[0] = 0; trigger_data->trigger_showtext[0] = 0;
shared_data->valid = true; shared_data->valid = true;
video_store_data->recording = false;
snprintf(video_store_data->event_directory, sizeof(video_store_data->event_directory), "nothing");
video_store_data->size = sizeof(VideoStoreData);
} }
else if ( purpose == ANALYSIS ) else if ( purpose == ANALYSIS )
{ {
@ -466,7 +471,12 @@ Monitor::Monitor(
shared_data->last_read_time = 0; shared_data->last_read_time = 0;
shared_data->alarm_x = -1; shared_data->alarm_x = -1;
shared_data->alarm_y = -1; shared_data->alarm_y = -1;
}
//TODO: Remove this if it isn't needed?
if(!(strcmp(video_store_data->event_directory, "nothing")==0)){
Fatal("video_store_data not init yet: %s", video_store_data->event_directory);
exit(-1);
} }
if ( !shared_data->valid ) if ( !shared_data->valid )
@ -1352,15 +1362,23 @@ bool Monitor::Analyse()
if ( noteSet.size() > 0 ) if ( noteSet.size() > 0 )
noteSetMap[LINKED_CAUSE] = noteSet; noteSetMap[LINKED_CAUSE] = noteSet;
} }
//TODO: What happens is the event closes and sets recording to false then recording to true again so quickly that our capture daemon never picks it up. Maybe need a refresh flag?
if ( (!signal_change && signal) && (function == RECORD || function == MOCORD) ) if ( (!signal_change && signal) && (function == RECORD || function == MOCORD) )
{ {
if ( event ) if ( event )
{ {
//TODO: We shouldn't have to do this every time. Not sure why it clears itself if this isn't here??
snprintf(video_store_data->event_directory, sizeof(video_store_data->event_directory), "%s", event->getEventDirectory());
int section_mod = timestamp->tv_sec%section_length; int section_mod = timestamp->tv_sec%section_length;
if ( section_mod < last_section_mod ) if ( section_mod < last_section_mod )
{ {
if ( state == IDLE || state == TAPE || event_close_mode == CLOSE_TIME ) if ( state == IDLE || state == TAPE || event_close_mode == CLOSE_TIME )
{ {
//TODO: Do we need to set this every time?
video_store_data->recording = false;
if ( state == TAPE ) if ( state == TAPE )
{ {
shared_data->state = state = IDLE; shared_data->state = state = IDLE;
@ -1384,6 +1402,13 @@ bool Monitor::Analyse()
event = new Event( this, *timestamp, "Continuous", noteSetMap ); event = new Event( this, *timestamp, "Continuous", noteSetMap );
shared_data->last_event = event->Id(); shared_data->last_event = event->Id();
snprintf(video_store_data->event_directory, sizeof(video_store_data->event_directory), "%s", event->getEventDirectory());
Error("1store event directory: %s", event->getEventDirectory());
Error("2store event directory: %s", video_store_data->event_directory);
video_store_data->recording = true;
Info( "%s: %03d - Opening new event %d, section start", name, image_count, event->Id() ); Info( "%s: %03d - Opening new event %d, section start", name, image_count, event->Id() );
/* To prevent cancelling out an existing alert\prealarm\alarm state */ /* To prevent cancelling out an existing alert\prealarm\alarm state */
@ -1392,8 +1417,10 @@ bool Monitor::Analyse()
shared_data->state = state = TAPE; shared_data->state = state = TAPE;
} }
//if ( config.overlap_timed_events ) //if ( config.overlap_timed_events )
if ( false ) //TODO: Remove this as the if false was here before I was playing around with it - not sure what it's meant to do. chriswiggins
/*if ( false )
{ {
int pre_index = ((index+image_buffer_count)-pre_event_count)%image_buffer_count; int pre_index = ((index+image_buffer_count)-pre_event_count)%image_buffer_count;
int pre_event_images = pre_event_count; int pre_event_images = pre_event_count;
@ -1414,7 +1441,7 @@ bool Monitor::Analyse()
} }
event->AddFrames( pre_event_images, images, timestamps ); event->AddFrames( pre_event_images, images, timestamps );
} }
} }*/
} }
} }
if ( score ) if ( score )
@ -1580,15 +1607,21 @@ bool Monitor::Analyse()
} }
else if ( state == TAPE ) else if ( state == TAPE )
{ {
if ( !(image_count%(frame_skip+1)) ) //Video Storage patch
{ if(config.use_mkv_storage){
if ( config.bulk_frame_interval > 1 ) //Info("ZMA: Setting to 10");
video_store_data->recording = true;
}else{
if ( !(image_count%(frame_skip+1)) )
{ {
event->AddFrame( snap_image, *timestamp, (event->Frames()<pre_event_count?0:-1) ); if ( config.bulk_frame_interval > 1 )
} {
else event->AddFrame( snap_image, *timestamp, (event->Frames()<pre_event_count?0:-1) );
{ }
event->AddFrame( snap_image, *timestamp ); else
{
event->AddFrame( snap_image, *timestamp );
}
} }
} }
} }
@ -2660,7 +2693,14 @@ int Monitor::Capture()
} }
/* Capture a new next image */ /* Capture a new next image */
captureResult = camera->Capture(*(next_buffer.image));
//TODO: Check if FFMPEG camera
if(config.use_mkv_storage){
captureResult = camera->CaptureAndRecord(*(next_buffer.image), video_store_data->recording, video_store_data->event_directory);
}else{
captureResult = camera->Capture(*(next_buffer.image));
}
if ( FirstCapture ) { if ( FirstCapture ) {
FirstCapture = 0; FirstCapture = 0;
@ -2668,9 +2708,15 @@ int Monitor::Capture()
} }
} else { } else {
/* Capture directly into image buffer, avoiding the need to memcpy() */ //TODO: Check if FFMPEG camera
captureResult = camera->Capture(*capture_image); if(config.use_mkv_storage){
} //Warning("ZMC: Recording: %d", video_store_data->recording);
captureResult = camera->CaptureAndRecord(*capture_image, video_store_data->recording, video_store_data->event_directory);
}else{
/* Capture directly into image buffer, avoiding the need to memcpy() */
captureResult = camera->Capture(*capture_image);
}
}
if ( captureResult != 0 ) if ( captureResult != 0 )
{ {

View File

@ -152,6 +152,19 @@ protected:
void* padding; void* padding;
}; };
//TODO: Technically we can't exclude this struct when people don't have avformat as the Memory.pm module doesn't know about avformat
#if 1
//sizeOf(VideoStoreData) expected to be what??
typedef struct
{
uint32_t size;
char event_directory[4096];
uint32_t recording; //bool arch independent so use uint32 instead
} VideoStoreData;
#endif // HAVE_LIBAVFORMAT
class MonitorLink class MonitorLink
{ {
protected: protected:
@ -172,6 +185,7 @@ protected:
volatile SharedData *shared_data; volatile SharedData *shared_data;
volatile TriggerData *trigger_data; volatile TriggerData *trigger_data;
volatile VideoStoreData *video_store_data;
int last_state; int last_state;
int last_event; int last_event;
@ -268,6 +282,7 @@ protected:
SharedData *shared_data; SharedData *shared_data;
TriggerData *trigger_data; TriggerData *trigger_data;
VideoStoreData *video_store_data;
Snapshot *image_buffer; Snapshot *image_buffer;
Snapshot next_buffer; /* Used by four field deinterlacing */ Snapshot next_buffer; /* Used by four field deinterlacing */

View File

@ -60,6 +60,7 @@ public:
virtual int PreCapture() = 0; virtual int PreCapture() = 0;
virtual int Capture( Image &image ) = 0; virtual int Capture( Image &image ) = 0;
virtual int PostCapture() = 0; virtual int PostCapture() = 0;
virtual int CaptureAndRecord( Image &image, bool recording, char* event_directory )=0;
}; };
#endif // ZM_REMOTE_CAMERA_H #endif // ZM_REMOTE_CAMERA_H

View File

@ -58,6 +58,7 @@ public:
int PreCapture(); int PreCapture();
int Capture( Image &image ); int Capture( Image &image );
int PostCapture(); int PostCapture();
int CaptureAndRecord( Image &image, bool recording, char* event_directory ) {return(0);};
}; };
#endif // ZM_REMOTE_CAMERA_HTTP_H #endif // ZM_REMOTE_CAMERA_HTTP_H

View File

@ -75,6 +75,7 @@ public:
int PreCapture(); int PreCapture();
int Capture( Image &image ); int Capture( Image &image );
int PostCapture(); int PostCapture();
int CaptureAndRecord( Image &image, bool recording, char* event_directory ) {return(0);};
}; };
#endif // ZM_REMOTE_CAMERA_RTSP_H #endif // ZM_REMOTE_CAMERA_RTSP_H

181
src/zm_videostore.cpp Normal file
View File

@ -0,0 +1,181 @@
//
// ZoneMinder Video Storage Implementation
// Written by Chris Wiggins
// http://chriswiggins.co.nz
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include <stdlib.h>
#include <string.h>
#include "zm.h"
#include "zm_videostore.h"
VideoStore::VideoStore(const char *filename_in, const char *format_in, AVStream *input_st){
//store inputs in variables local to class
filename = filename_in;
format = format_in;
keyframeMessage = false;
keyframeSkipNumber = 0;
Info("Opening video storage stream %s\n in format %s\n", filename, format);
//Init everything we need
int ret;
av_register_all();
//Allocate the output media context based on the filename of the context
avformat_alloc_output_context2(&oc, NULL, NULL, filename);
//Couldn't deduce format from filename, trying from format name
if(!oc){
avformat_alloc_output_context2(&oc, NULL, format, filename);
}
//Couldn't deduce format from filename, using MPEG
if(!oc){
Error("Couldn't deduce format from filename, using MPEG");
avformat_alloc_output_context2(&oc, NULL, format, filename);
}
if(!oc){
Fatal("No output context was assigned...");
}
fmt = oc->oformat;
//create a new video stream based on the incoming stream from the camera and copy the context across
video_st = avformat_new_stream(oc, input_st->codec->codec);
avcodec_copy_context(video_st->codec, input_st->codec);
av_dump_format(oc, 0, filename, 1);
/* open the output file, if needed */
if (!(fmt->flags & AVFMT_NOFILE)) {
ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
if (ret < 0) {
Fatal("Could not open '%s': %s\n", filename, av_err2str(ret));
}
}
/* Write the stream header, if any. */
ret = avformat_write_header(oc, NULL);
if (ret < 0) {
Fatal("Error occurred when opening output file: %s\n", av_err2str(ret));
}
}
VideoStore::~VideoStore(){
/* Write the trailer, if any. The trailer must be written before you
* close the CodecContexts open when you wrote the header; otherwise
* av_write_trailer() may try to use memory that was freed on
* av_codec_close(). */
av_write_trailer(oc);
avcodec_close(video_st->codec);
if (!(fmt->flags & AVFMT_NOFILE))
/* Close the output file. */
avio_close(oc->pb);
/* free the stream */
avformat_free_context(oc);
}
void VideoStore::writeVideoFramePacket(AVPacket *ipkt, AVStream *input_st, AVFormatContext *input_fmt_ctx){
/*
See 01349 of http://www.ffmpeg.org/doxygen/trunk/ffmpeg_8c-source.html
do_streamcopy
*/
AVPacket opkt;
AVPicture pict;//Not sure how much we need this
av_init_packet(&opkt);
//Wait for a keyframe to show up
if (!video_st->nb_frames && !(ipkt->flags & AV_PKT_FLAG_KEY)){
if(!keyframeMessage){
Warning("Waiting for keyframe before starting recording");
keyframeMessage = true;
}
keyframeSkipNumber++;
return;
}else{
if(keyframeMessage){
Warning("Skipped %d frames waiting for keyframe", keyframeSkipNumber);
keyframeMessage = false;
}
}
int64_t ost_tb_start_time = av_rescale_q(input_fmt_ctx->start_time_realtime, AV_TIME_BASE_Q, video_st->time_base);
opkt.stream_index = video_st->index;
//Scale the PTS of the outgoing packet to be the correct time base
if (ipkt->pts != AV_NOPTS_VALUE)
opkt.pts = av_rescale_q(ipkt->pts, input_st->time_base, video_st->time_base);
else
opkt.pts = AV_NOPTS_VALUE;
//Scale the DTS of the outgoing packet to be the correct time base
if(ipkt->dts == AV_NOPTS_VALUE)
opkt.dts = av_rescale_q(input_st->reference_dts, AV_TIME_BASE_Q, video_st->time_base);
else
opkt.dts = av_rescale_q(ipkt->dts, input_st->time_base, video_st->time_base);
opkt.dts -= ost_tb_start_time;
opkt.duration = av_rescale_q(ipkt->duration, input_st->time_base, video_st->time_base);
opkt.flags = ipkt->flags;
//TODO: Should be checking if not H264, mpeg1, etc
//Maybe the check isn't needed if we're only going to do this for H264 video incoming
opkt.data = ipkt->data;
opkt.size = ipkt->size;
//Info("Codec type video? %d", (int)(video_st->codec->codec_type == AVMEDIA_TYPE_VIDEO));
//Info("Raw picture? %d", (int)(fmt->flags & AVFMT_RAWPICTURE));
if (video_st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (fmt->flags & AVFMT_RAWPICTURE)) {
/* store AVPicture in AVPacket, as expected by the output format */
//Info("Raw picture storage");
avpicture_fill(&pict, opkt.data, video_st->codec->pix_fmt, video_st->codec->width, video_st->codec->height);
opkt.data = (uint8_t *)&pict;
opkt.size = sizeof(AVPicture);
opkt.flags |= AV_PKT_FLAG_KEY;
}
int ret;
ret = av_interleaved_write_frame(oc, &opkt);
if(ret<0){
Fatal("Error encoding video frame packet: %s\n", av_err2str(ret));
}
av_free_packet(&opkt);
}

30
src/zm_videostore.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef ZM_VIDEOSTORE_H
#define ZM_VIDEOSTORE_H
#include "zm_ffmpeg.h"
#if HAVE_LIBAVCODEC
class VideoStore {
private:
AVOutputFormat *fmt;
AVFormatContext *oc;
AVStream *video_st;
const char *filename;
const char *format;
bool keyframeMessage;
int keyframeSkipNumber;
public:
VideoStore(const char *filename_in, const char *format_in, AVStream *input_st);
~VideoStore();
void writeVideoFramePacket(AVPacket *pkt, AVStream *input_st, AVFormatContext *input_fmt_ctx);
};
#endif //havelibav
#endif //zm_videostore_h