###########################################
# Mike Schilli, 2006 (m@perlmeister.com)
###########################################
package SoundActivity;
###########################################
use strict;
use warnings;
use Statistics::Basic::StdDev;
use Log::Log4perl qw(:easy);

###########################################
sub new {
###########################################
  my($class, %options) = @_;

  my $self = {
      min_hist       => 5,
      max_hist       => 5,
      history        => [],
      sdev_threshold => 0.01,
      %options,
  };

  bless $self, $class;
}

###########################################
sub sample_add {
###########################################
  my($self, $data) = @_;

  my $len     = length($data);
  my @samples = unpack("C$len", $data);

  my $sdev = $self->sdev(\@samples);

  my $h = $self->{history};
  push @$h, $sdev;
  shift @$h if @$h > $self->{max_hist};
  DEBUG "History: [", join(', ', @$h), "]";
}

###########################################
sub is_active {
###########################################
  my($self) = @_;

  if(@{$self->{history}} < 
     $self->{min_hist}) {
      DEBUG "Not enough samples yet";
      return 1;
  }

  my $sdev = $self->sdev($self->{history});
  DEBUG "sdev=$sdev";

  if($sdev < $self->{sdev_threshold}) {
      DEBUG "sdev too low ($sdev)";
      return 0;
  }

  return 1;
}

###########################################
sub sdev {
###########################################
  my($self, $aref) = @_;

  return sprintf "%.2f", 
         Statistics::Basic::StdDev->
              new($aref)->query;
}

1;
