#!/usr/bin/perl -w
#  $Id: probe 18145 2010-04-01 01:13:50Z teetov $
# -----------------------------------------------------------------------------
#  Purpose:
#    - probe the camera
#    - pre-tune camera befor for retriever (RC and Audio)
# -----------------------------------------------------------------------------
#  Call:
#    probe DEVID=123   
#    probe DEVID=123 PROBE=FAST  
#    probe DEVID=123 DEVIP=192.168.17.177 [ ... ]
#    probe DEVIP=192.168.17.177 USRNAME=admin PASSWD=pass PROBE=DEFINE
# -----------------------------------------------------------------------------
#  Does:
#   0. can be called without DEVID argument. 
#      In this case DEVIP,USRNAME,PASSWD should be provided in command line
#   1. load $APL_CONF/<DEVID>/conf if DEVID is provided
#   2. combine conf and args into one hash
#   3. connect to camera over http and read MODELID and FIRMWARE
#   4. report MODELID|FIRMWARE|STATUS to $APL_CONF/<DEVID>/conf.probe and stdout
#   5. if PROBE=DEFINE then get
#         IMAGESIZE_LIST,MEDIA_FORMAT_LIST
#         AUDIO_LIST,AUDIO_FORMAT_LIST
#         SNAPSHOT (picture)
#   6. set RC camera attributes    if mpeg4 | h264
#   7. set AUDIO camera attributes if AUDIO is on 
#   8. example output:
#       AUDIO_SET=OK
#       FIRMWARE=5.02
#       MODELID=Q1755
#       RC_SET=OK
#       STATUS=OK
#       -------------
#       AUDIO_SET=NONE
#       FIRMWARE=5.02
#       MODELID=Q1755
#       RC_SET=NONE
#       STATUS=OK
#       SNAPSHOT=/tmp/probe/192.168.17.177-12367576123.jpg
#       IMAGESIZE_LIST=640x480,480x360,320x240,240x180,176x144,160x120
#       MEDIA_FORMAT_LIST=mjpeg,h264
#       AUDIO_LIST=off,on
#       AUDIO_FORMAT_LIST=g711,g726,aac
#   9. sample errors: 
#       STATUS=ERROR: PCE-0001 [101] configuration is not found
#       STATUS=ERROR: PCE-0002 [101] USRNAME and PASSWD should provided
#       STATUS=ERROR: PCE-0003 [101] DEVIP is not defined
#       STATUS=ERROR: PCE-0500 [101] Device does not respond (http://207.107.163.123:80)
#       STATUS=ERROR: PCE-0401 [101] Authorization error 
#       STATUS=ERROR: PCE-0403 [101] Forbidden 
#       STATUS=ERROR: PCE-0030 [101] Cannot get MODELID
#       note: [101] is DEVID
#  10. warnings:
#       STATUS=WARNING: PCW-0001 [101] MODELID does not match configuration
#       STATUS=WARNING: PCW-0002 [101] FIRMWARE does not match configuration
#       STATUS=WARNING: PCW-0009 [101] PROBE=RESET is not supported
#       
# -----------------------------------------------------------------------------
#  Note:
#   1. CAMERAMODEL file is obsolite. ptz_axisv2.pl & ptz_udp.pl has to be modified
#   2. Script mast be in the directory .../camera/<BRAND>/bin/
# -----------------------------------------------------------------------------
#  Author: teetov, 03/22/10
#  Edited by:
#  QA by:
#  Copyright: videoNEXT Network Solutions, Inc, 2010
# -----------------------------------------------------------------------------
#
use strict;
use Device::Conf;
#use Data::Dumper;
# cons -------------------------------------------------------------------------
# no code for ACTi

# --------- check required parameters: DEVID,USRNAME,PASSWD,
my $conf=ProbeInit();  # uses <BRAND> from path and ARGV
ProbeErr("PCE-0001","configuration is not found") if not defined $conf->{DEVID}; 
ProbeErr("PCE-0003","DEVIP is not defined")       if not defined $conf->{DEVIP};
ProbeErr("PCE-0002","USRNAME and PASSWD should be provided") 
                 if not defined $conf->{USRNAME} or not defined $conf->{PASSWD};
ProbeWarn("PCW-0009","PROBE=RESET is not supported") if $conf->{PROBE} eq 'RESET';
#------------------------------------------------------------------------------
# Probe camera MODELID & FIRMWARE 
#------------------------------------------------------------------------------
my %result=(MODELID=>'0',FIRMWARE=>'0.0',STATUS=>'OK',RC_SET=>'NONE',AUDIO_SET=>'NONE');

my %sysinfo;
my $respond =ProbeRequest("/cgi-bin/system?USER=$conf->{USRNAME}&PWD=$conf->{PASSWD}&SYSTEM_INFO");
if($respond!~ /^HTTP ERROR/) {
  $result{MODELID} = $1 if $respond =~ /^Production\sID\s=\s(.+?)-/im;  
  $result{FIRMWARE}= $1 if $respond =~ /^Firmware\sVersion\s=\s(.+)$/im;  
  %sysinfo = map {(/^(.+?) = (.*)$/)} split /\n/,$respond;
}else {
  my ($err)= $respond=~/^HTTP ERROR \[(\d+)\]/;
  ProbeErr("PCE-0500","Device does not respond",$respond) if $err=~/^5\d\d/;
  ProbeErr("PCE-0401","Authorization error",    $respond) if $err==401;  
}
ProbeErr("PCE-0401","Authorization error",$respond) if $respond=~/^ERROR: bad account\/password/im;
ProbeErr("PCE-0030","Cannot get MODELID or FIRMWARE",$respond) if ! $result{MODELID};

# Check MODELID & FIRMWARE ---------------------------------------------------
if(defined $conf->{MODELID} and $result{MODELID} ne $conf->{MODELID}) {
  $result{STATUS}="WARNING: PCW-0001 [$conf->{DEVID}] MODELID does not match configuration";
}elsif(defined $conf->{CAMERAFIRMWARE} and $result{FIRMWARE} ne $conf->{CAMERAFIRMWARE}) {
  $result{STATUS}="WARNING: PCW-0001 [$conf->{DEVID}] FIRMWARE does not match configuration";
}

#------------------------------------------------------------------------------
# get Sample picture 
#------------------------------------------------------------------------------
if($conf->{PROBE} eq 'DEFINE') {
   $result{SNAPSHOT}=ProbeSamplePicture();
}

#------------------------------------------------------------------------------
# get video and audio properties
#------------------------------------------------------------------------------

# no code for ACTi

#------------------------------------------------------------------------------
# interim report & exit 
#------------------------------------------------------------------------------
ProbeResult(\%result)  if $conf->{PROBE} =~ /^(DEFINE|FAST)$/;
ProbeResult(\%result)  if $conf->{DEVID}==0;

#------------------------------------------------------------------------------
# set RC (rate control) parameters + qality + imagesize
#------------------------------------------------------------------------------

my $cameraInput=1;
$cameraInput=$conf->{CAMERA}  if defined $conf->{CAMERA} and $conf->{CAMERA}>1;
my $url_enc = "/cgi-bin/encoder?USER=$conf->{USRNAME}&PWD=$conf->{PASSWD}&CHANNEL=$cameraInput&VIDEO_STREAM=SINGLE";

# Check Media Format
my $ok = 0;
my $media_format = $conf->{MEDIA_FORMAT};
my $encoder = $media_format eq 'mjpg' ? 'MJPEG' : uc($media_format);
my @fmt_supported = split(/,/, $sysinfo{ENCODER_CAP});
foreach(@fmt_supported) { $ok = 1, last if /^$encoder$/i }

# Die for unsupported media format
die "Unsupported format: $media_format" unless $ok;
$url_enc .= "&VIDEO_ENCODER=$encoder";

# Video resolution
my $imgsize = $conf->{IMAGESIZE};
# If got list of supported formats, check configuration value
if ($sysinfo{VIDEO_RESOLUTION_CAP}) {
    my @res_supported = split(/,/, $sysinfo{VIDEO_RESOLUTION_CAP});
    foreach(@res_supported) {
        $url_enc .= "&VIDEO_RESOLUTION=$imgsize", last if /^$imgsize$/i;
    }
}
else { # Simply assign value otherwise
    $url_enc .= "&VIDEO_RESOLUTION=$imgsize";
}

# FPS Ratio
my $fps_ratio = int($conf->{FRAMERATE} * 3.33);
$fps_ratio = 100 if $conf->{FRAMERATE} == 30;
$fps_ratio = 1 if $conf->{FRAMERATE} <= 1;
$url_enc .= "&VIDEO_FPS_RATIO=$fps_ratio";

# MJPEG params
if($media_format eq 'mjpg') {
    $url_enc .= "&VIDEO_MJPEG_QUALITY=$conf->{VIDEO_MJPEG_QUALITY}";
}
else { # mpeg4 and h264
    if($conf->{RC_MODE} eq 'vbr') {
        $url_enc .= "&VIDEO_${encoder}_QUALITY=$conf->{VIDEO_QUALITY}";
    } elsif($conf->{RC_MODE} eq 'cbr') {
        $url_enc .= "&VIDEO_${encoder}_QUALITY=NONE";
        $url_enc .= "&VIDEO_MAX_BITRATE=$conf->{RC_MAXBITRATE}"
    	    if $conf->{RC_MAXBITRATE} ne 'cam-defined';
        $url_enc .= "&VIDEO_BITRATE=$conf->{RC_TARGETBITRATE}"
            if $conf->{RC_TARGETBITRATE} ne 'cam-defined' and
               $conf->{RC_MAXBITRATE} ne 'UNLIMITED';
    }
}
        
my $ret=join "\n#",split(/\n/,ProbeRequest($url_enc));
$result{RC_SET}="OK\n#$ret";   # add output from request as comments

#------------------------------------------------------------------------------
# set AudioParams
#------------------------------------------------------------------------------
if ( $conf->{AUDIO} eq 'on' ) { 
# no code for ACTi
}
my $enabled = $conf->{AUDIO} eq 'on' ? '1' : '0';
my $url_audio="/cgi-bin/system?USER=$conf->{USRNAME}&PWD=$conf->{PASSWD}&V2_AUDIO_ENABLED=$enabled";


my $resp = join "\n#",split(/\n/,ProbeRequest($url_audio));
$result{AUDIO_SET}="OK\n#$resp"; # add output from request as comments

# final report-----------------------------------------------------------------------
ProbeResult(\%result);

