<?php
/*                  _          _       _     _   
 *  _ __ ___   __ _| |__  _ __(_) __ _| |__ | |_ 
 * | '_ ` _ \ / _` | '_ \| '__| |/ _` | '_ \| __|
 * | | | | | | (_| | |_) | |  | | (_| | | | | |_ 
 * |_| |_| |_|\__, |_.__/|_|  |_|\__, |_| |_|\__|    EXPERIMENTAL 0.9
 *            |___/              |___/           
*/

/* Copyright (c) 2010, Max R. P. Großmann <admin@max-grossmann.de>
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restric-
 * tion, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
*/

// Video Device
$device = "/dev/video0";

error_reporting(0);
if (exec("whoami") != "root") die("Sorry, but you need to be root.\n");

if (file_exists("image.jpg")) unlink("image.jpg");
exec("ffmpeg -f video4linux2 -s 320x240 -r 1 -i ".$device." -vframes 1 -f image2 image.jpg");

if (!file_exists("image.jpg"))
{
    die("Error: Please check your video device and FFmpeg\n");
    return 1;
}

$im = imagecreatefromjpeg("image.jpg");

$fcol = 0;

for ($y=0; $y<320; $y++)
{
    for ($x=0; $x<240; $x++)
    {
        $aco = imagecolorsforindex($im, imagecolorat($im, $x, $y));
        $fcol += max($aco);
    }
}

$fcol = $fcol/76800;

imagedestroy($im);

$V = $fcol/255;

$fo = fopen("/sys/class/backlight/acpi_video0/max_brightness", "r");
$max = trim(fread($fo, filesize("/sys/class/backlight/acpi_video0/max_brightness")));
fclose($fo);

$bright = $max*$V;

$fp = fopen("/sys/class/backlight/acpi_video0/brightness", "w");
fputs($fp, (string)round($bright));
fclose($fp);

return 0;
?>