extract_images_tiff.php 18.2 KB
Newer Older
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
1 2 3 4 5
#!/usr/bin/env php
<?php
/**
 * @file extract_images.php
 * @brief split mov/bin/img's (by exif header) into single image files - looks one dir down from the specified path
6
 * @copyright Copyright (C) 2017-2021 Elphel Inc.
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * @author Elphel Inc. <support-list@support.elphel.com>
 *
 * @par <b>License</b>:
 *  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 3 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, see <http://www.gnu.org/licenses/>.
Andrey Filippov's avatar
Andrey Filippov committed
22 23
*/
/*
24
Found problem - does not process files that start in one file and end in another?
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
25
*/
26 27
   define('START_TIFF',     hex2bin('4d4d002a')); // start of a TIFF, JP/JP4 also have this TIFF marker
   define('START_JP',       hex2bin('ffd8ffe1')); // start of JPEG/JP4, TIFF usually does not have JPEG/JP4 markers
28 29 30
   define('START_EXIF',     hex2bin("457869660000")); // Exif\0\0
   define('EXIF_OFFSET',    6);                   // Exif start offset from the beginning of the file (from start of START_JP) 
   define('END_JP',         hex2bin('ffd9'));     // end of JPEG/JP4 file
31
   define('MAX_HEAD_LEN',   0x300);               // maximal header length that includes complete header
32 33 34
   define('MIN_JP_LEN',     0x500);               // skip from jpeg looking for end marker
   define('MAX_IMG_LEN',    0x1000000);           // maximal image size (16M) to look for the end marker
   define('REQUIRE_EXIF',   1);                   // JPEG/JP4 must have Exif (more filtering, less false positives)
35
   define('DEBUG_LEVEL',    0); //3);                 // Generate debug output
36 37 38
   //define('DEBUG_OUT_FILES',DEBUG_LEVEL? 1 : 0 ); // 1 to add sequence number to result image names (make all unique)
   define('DEBUG_OUT_FILES',DEBUG_LEVEL? 0 : 0 ); // 1 to add sequence number to result image names (make all unique)
   //disable the default time limit for php scripts.
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
39 40 41
set_time_limit(0);

$chunksize=10000000; //10MB 
42 43 44
//$startMarkerWithExif=chr(hexdec("4d")).chr(hexdec("4d")).chr(hexdec("00")).chr(hexdec("2a"));
//$startMarkerWithExif=chr(hexdec("ff")).chr(hexdec("d8")).chr(hexdec("ff")).chr(hexdec("e1"));

Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
45 46 47 48 49 50 51 52 53
$input_exts = array("img","bin","mov");

// use current dir
$path=".";
$destination = "0";

$move_processed = false;
$processed_subdir = "processed";

54 55 56
$forced_ext = "";

$add_to_chn = -1; // do not use and do not create scene directories
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
57 58 59 60 61

function print_help(){
  global $argv;
  
  echo <<<"TXT"
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    Help:
      * Usage:
        ~$ {$argv[0]} path=[path-to-dir] dest_path=[dest-subdir] move_processed=[move-processed-files] ext=[forced-ext] chn_offs=[add-to-chn]
        
        where:
          * path-to-dir            - string - scan this path + 1 dir down
          * dest-subdir            - string - save results to "path-to-dir/dest-subdir/"
          * move-processed-files - 0(default) or 1 - if not 1 - will not move the processed files
          * forced-ext             - string - override extensions from exifs with this one
          * add-to-chn             - integer - add to decoded channel number
        
      * Examples:
        ** Split all *.img, *.bin and *.mov files in the current dir and 1 dir down, puts results to '0/':
          ~$ {$argv[0]}
        ** Split in /data/test + 1 dir down, create and move processed files to /data/test/processed for files in path and /data/test/any-found-subdir/processed for any files found in /data/test/any-found-subdir
          ~$ {$argv[0]} path=/data/test move_processed=1
        ** Split all *.img, *.bin and *.mov files in the current dir and 1 dir down, puts results to 'results/', override extensions with 'jpg':
          ~$ {$argv[0]} dest_path=results ext=jpg
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
80
    
81
    TXT;
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

}

if ($argv){
  foreach($argv as $k=>$v){
    if ($k==0) continue;
    $args = explode("=",$v);
    if (isset($args[1])) $_GET[$args[0]] = $args[1];
    if ($v=="-h"||$v=="--help"||$v=="help") {
      print_help();
      die();
    }
  }
}

if (isset($_GET['path'])){
  $path=$_GET['path'];
}

// put results to $path/$destination/
// no need for argv
if (isset($_GET['dest_path'])){
  $destination = $_GET['dest_path'];
}

if (isset($_GET['move_processed'])){
  $move_processed = $_GET['move_processed'];
}

if ($move_processed=="1"){
  $move_processed = true;
}else{
  $move_processed = false;
}

// enforce extension
if (isset($_GET['ext'])){
  $forced_ext = $_GET['ext'];
}

122 123 124 125
if (isset($_GET['chn_offs'])){
  $add_to_chn = (integer) $_GET['chn_offs'];
}

Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
126
$list = preg_grep('/^([^.])/', scandir($path));
127 128
sort($list); // also re-indexes
//$list=array();
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
129 130


131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
if (!is_dir("$path/$destination")) mkdir("$path/$destination",0777);
if ((DEBUG_LEVEL >= 2)) {
    var_dump($list);
}
//exit(0);
/*
 array(4) {
  [2]=>
  string(10) "file_0.img"
  [3]=>
  string(10) "file_1.img"
  [4]=>
  string(10) "file_2.img"
  [5]=>
  string(7) "results"
}
 */
// should not mix files and directories - should be same level
foreach ($list as $index=>$item) {
    if (is_dir("$path/$item")) {
        if ($item == $processed_subdir)
            continue;
        $sublist = preg_grep('/^([^.])/', scandir("$path/$item"));
        sort($sublist);
        foreach ($sublist as $file_index => $subitem) {
            $next_file = ($file_index < (count($sublist) -1)) ? $sublist[$file_index + 1] : "";
            if (split_file("$path/$item", "$subitem", "../$destination", $add_to_chn, $next_file) == 0) {
                if ($move_processed) {
                    if (! is_dir("$path/$item/$processed_subdir")) {
                        mkdir("$path/$item/$processed_subdir", 0777);
                    }
                    rename("$path/$item/$subitem", "$path/$item/$processed_subdir/$subitem");
                }
            }
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
165 166
        }
  }else{
167 168
      $next_file = ($index < (count($list)-1)) ? $list[$index + 1] : "";
      if (split_file("$path","$item","$destination",$add_to_chn, $next_file)==0){
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
169 170 171 172 173 174 175 176 177 178
      if ($move_processed){
        if (!is_dir("$path/$processed_subdir")){
          mkdir("$path/$processed_subdir",0777);
        }
        rename("$path/$item","$path/$processed_subdir/$item");
      }
    }
  }
}

179
//./extract_images_tiff.php path=/home/eyesis/captures/tests/jp4/ dest_path=results chn_offs=16
180 181 182 183 184 185 186
function split_file($path, $file, $destination, $add_to_chn = - 1, $next_file = "")
{
    if ($next_file && !is_file("$path/$next_file")){
        if ((DEBUG_LEVEL >= 1)) {
            printf("Ignoring $next_file - it is a DIRECTORY\n");
        }
        $next_file="";
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
187 188
    }

189 190 191 192
    // global $startMarkerWithExif = START_JP; // START_TIFF
    global $chunksize;
    global $input_exts;
    global $forced_ext;
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    if (in_array(get_ext("$path/$file"), $input_exts)) {
        $next_path = $next_file ? "$path/$next_file" : "";
        echo date(DATE_RFC2822) . ": Splitting $path/$file (next is $next_path):, results dir: $path/$destination\n";
        // split_mov("$path",$file,$destination,$extension,$startMarkerWithExif,$chunksize);
        $file_type = 0; // JP4/JPEG
        $markers = array();
        $offset = 0;
        $f = fopen("$path/$file", "r");

        $s = fread($f, $chunksize);
        $pos_jp = strpos($s, START_JP);
        $pos_tiff = strpos($s, START_TIFF);
        if (($pos_jp === false) && ($pos_tiff === false)) {
            if (strlen($s) == $chunksize) {
                print("None of TIFF (" . bin2hex(START_TIFF) . ") or JP4/JPEG (" . bin2hex(START_JP) . ") markers found in the first " . $chunksize . " bytes of the file $path/$file\n");
            } else {
                print("None of TIFF (" . bin2hex(START_TIFF) . ") or JP4/JPEG (" . bin2hex(START_JP) . ") markers found in the remaining " . strlen($s) . " bytes of the file $path/$file\n");
            }
            
            return - 1;
        }
        if ($pos_jp === false) {
            $file_type = 1; // tiff
        } else if (($pos_tiff !== false) && ($pos_tiff < $pos_jp)) { // reducing probability of stray START_JP
            $file_type = 1; // tiff
        } else {
            $file_type = 0; // jpeg/jp4
        }
        $startMarkerWithExif = $file_type ? START_TIFF : START_JP; // START_TIFF
        echo "Detected image type " . ($file_type ? 'TIFF' : 'JPEG/JP4') . ".\n";
        $forced_ext = $file_type ? 'tiff' : ''; // was ".tiff":""
        fclose($f); // not sure if feof is cleraed by fseek, closing/ reopening
        $f = fopen("$path/$file", "r");
        // first scan
        while (! feof($f)) {
            $pos = 0;
            $index = 0;
            fseek($f, $offset); // will read from the last
            $s = fread($f, $chunksize);
            if ($next_file && (strlen($s) < $chunksize)) { // special case, try to add beginning of the next file
                printf("Looking for the marker in the file split, using %s", $next_file);
                $f1 = fopen("$path/$next_file", "r");
                $s1 = fread($f1, strlen($startMarkerWithExif) - 1);
                fclose($f1);
                $s .= $s1;
            }
            while (true) {
                $pos = strpos($s, $startMarkerWithExif, $pos);
                if ($pos === false) {
                    break;
                }
                if (REQUIRE_EXIF && ($file_type == 0) && (strpos($s, START_EXIF, $pos) != ($pos + EXIF_OFFSET))) { // JPEG/JP4
                    printf("Could not find required by REQUIRE_EXIF==%d Exif signature at offset %d. Skipping this marker (false positive?)\n", REQUIRE_EXIF, START_EXIF);
                } else {
                    $markers[count($markers)] = $offset + $pos;
                }
                $pos ++;
            }
            // steps back by needle length-1, so partial markers will not be lost
            $offset += (strlen($s) - strlen($startMarkerWithExif) + 1); // so each marker will appear once
        }

        $markers[count($markers)] = $offset + strlen($s); // full length of the file
        $tmp_name = $file_type? "$path/$destination/header.tmp": "$path/$destination/image.tmp";
        
        echo "  images found: " . (count($markers) - 1) . "\n";

        // second scan
        $dbg_last = 0;
        for ($i = 0; $i < (count($markers) - 1); $i ++) {
            if ((DEBUG_LEVEL >= 2)) {
                if ($i == 0) {
                    printf("1.First image[%d], markers[%d]=0x%08x, markers[%d]=0x%08x, diff=0x%08x\n", $i, $i, $markers[$i], $i + 1, $markers[$i + 1], $markers[$i + 1] - $markers[$i]);
                } else if ($i == (count($markers) - 2)) {
                    printf("1.Last image[%d], markers[%d]=0x%08x, markers[%d]=0x%08x, diff=0x%08x\n", $i, $i, $markers[$i], $i + 1, $markers[$i + 1], $markers[$i + 1] - $markers[$i]);
                }
            }
            fseek($f, $markers[$i]);
272 273 274
            if ((DEBUG_LEVEL >= 1)) {
                printf("marker: %6d, position 0x%x\n",$i,$markers[$i]);
            }
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            $s = fread($f, $markers[$i + 1] - $markers[$i]);
            if ((DEBUG_LEVEL >= 2)) {
                if (($i == (count($markers) - 2)) || ($i == 0)) {
                    printf("Read 0x%08x (wanted 0x%08x) bytes\n", strlen($s), $markers[$i + 1] - $markers[$i]);
                }
            }
            $image_length = - 1;
            
            if ($file_type == 0) { // JPEG/JP4
// find end marker
                $end_pos = false;
                if (strlen($s) >= MIN_JP_LEN) {
                    $end_pos = strpos($s, END_JP, MIN_JP_LEN); // PHP Warning:  strpos(): Offset not contained in string in /home/elphel/git/elphel-tools-x393/extract_images_tiff.php on line 254
                }
                if (!$end_pos && $next_path) {// try reading from the next file  define('MAX_IMG_LEN',    0x1000000);           // maximal image size (16M) to look for the end marker
                    $f1 = fopen($next_path, "r");
                    $s .= fread($f1, MAX_IMG_LEN); // beginning of the next file
                    fclose($f1);
                    $end_pos = strpos($s, END_JP, MIN_JP_LEN); // PHP Warning:  strpos(): Offset not contained in string in /home/elphel/git/elphel-tools-x393/extract_images_tiff.php on line 254
                    if ($end_pos && (DEBUG_LEVEL >= 1)) {
                        printf ("Found image continued in the next file %s\n", $next_path);
                    }
                }
                if ($end_pos) {
                    $end_pos+=strlen(END_JP);
                    file_put_contents($tmp_name, substr($s, 0, $end_pos));
                    $image_length = 0; // will not try to get it
                    $result_name = elphel_specific_result_name($tmp_name, $image_length, $add_to_chn);
                    if (DEBUG_OUT_FILES) {
                        $result_name = substr($result_name,0,strlen($result_name)-4).'-'.strval($i).'.jp4';
                    }
                    if ((DEBUG_LEVEL >= 3)) {
                        printf("%05d: 0x%08x l=0x%06x (0x%06x)  %s\n",$i, $markers[$i], $end_pos, $markers[$i + 1] - $markers[$i], "$path/$destination/$result_name");
                    }
                    $dest_image = "$path/$destination/$result_name"; // $result_name may now include "/"
                    $dest_set_dir = dirname($dest_image);
                    if (! is_dir($dest_set_dir)) {
                        mkdir($dest_set_dir, 0777);
                    }
                    rename($tmp_name, $dest_image); // "$path/$destination/$result_name");
                }
                
            } else if ($file_type == 1) { // Tiff
318 319 320 321 322 323 324 325 326 327 328 329
            // read continuation if needed
            //$s = fread($f, $markers[$i + 1] - $markers[$i]);
                if ((strlen($s) < $markers[$i + 1] - $markers[$i]) && $next_path) {
                    $f1 = fopen($next_path, "r");
                    $s .= fread($f1, $markers[$i + 1] - $markers[$i] - strlen($s)); // beginning of the next file
                    fclose($f1);
                    if (DEBUG_LEVEL >= 0) {
                        printf("Got continuation of the image from the next file %s\n", $next_path);
                    }
                }
            
                // file_put_contents($tmp_name,$s);
330 331 332 333 334 335 336 337 338 339 340 341 342 343
                file_put_contents($tmp_name, substr($s, 0, MAX_HEAD_LEN)); // only save beginning of the file
                                                                           // printf ("header length = %d\n", strlen(substr($s, 0, MAX_HEAD_LEN)));
                $result_name = elphel_specific_result_name($tmp_name, $image_length, $add_to_chn);
                if ($image_length < 0) {
                    printf("Wrong image length from Exif header: %d", $image_length);
                    exit(1);
                }
                $dest_image = "$path/$destination/$result_name"; // $result_name may now include "/"
                $dest_set_dir = dirname($dest_image);
                if (! is_dir($dest_set_dir)) {
                    mkdir($dest_set_dir, 0777);
                }
                // rename($tmp_name, $dest_image); // "$path/$destination/$result_name");
                file_put_contents($dest_image, substr($s, 0, $image_length));
344
                if (DEBUG_LEVEL >= 2) {
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                    if ($i == 0) {
                        file_put_contents($dest_image . ".test", substr($s, 0, $image_length));
                        printf("2.First image[%d] from img file - %s, length=0x%08x(%d), strlen(s)=%d (%d)\n", $i, $dest_image, $image_length, $image_length, strlen($s), strlen(substr($s, 0, $image_length)));
                    } else if ($i == (count($markers) - 2)) {
                        file_put_contents($dest_image . ".test", substr($s, 0, $image_length));
                        printf("2.Last image[%d] from img file - %s, length=0x%08x(%d), strlen(s)=%d (%d)\n", $i, $dest_image, $image_length, $image_length, strlen($s), strlen(substr($s, 0, $image_length)));
                    }
                }
            }
        }
        if (file_exists($tmp_name)){
            unlink ($tmp_name);
        }
        return 0;
    } else {
        return - 1;
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
361 362 363
    }
}

364

365
function elphel_specific_result_name($file, &$image_length, $add_to_chn=-10){
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
366
  global $forced_ext;
367 368 369 370 371
  // $add_to_chn<0 - do not use it and do not use scene directories
  $use_scene_dirs = $add_to_chn >= 0;
  if ($add_to_chn < 0){
      $add_to_chn = 0;
  }
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
372

373
  $exif = exif_read_data($file); // gets false find, what is wrong
374
  // image size = ([StripOffsets] => 557)+ ([StripByteCounts] => 656640)
375 376 377
  if ($image_length != 0) {
    $image_length = intval($exif['StripOffsets']) + intval($exif['StripByteCounts']);
  }
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
378 379 380
  $ext = elphel_specific_result_ext($exif,$forced_ext);
  
  //converting GMT a local time GMT+7
381
  $timestamp_local=strtotime($exif['DateTimeOriginal']);/*-25200;*/ //
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
382
  
383
  $subsecs = $exif['SubSecTimeOriginal']; // 
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
384
  
385
  $tmp = explode("_",$exif['Model']); //
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  if (count($tmp)==2){
    
    if (trim($tmp[0])=="Eyesis4pi393"){
    
      $model = intval(trim($tmp[1]));
      $chn = intval($exif['PageNumber'])+1;
      
      if        ($model==1001) {
        $k=$chn;
      }else  if ($model==1002) {
        $k=$chn+4;
      }else  if ($model==1003) {
        $k=$chn+6;
      }
      
    }else{
        $ks = $exif['PageNumber'];
Andrey Filippov's avatar
Andrey Filippov committed
403
        if (is_array($ks) && (count($ks) ==2)){
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
404 405 406 407 408 409 410
            $k = $ks[0];
        }else{
            $k = intval($exif['PageNumber'])+1;
        }
    }
    
  }else{
411 412 413 414 415 416 417
    $k = intval($exif['PageNumber'])+1; //
  }
  if ($use_scene_dirs) {
      $k += $add_to_chn;
      return "{$timestamp_local}_{$subsecs}/{$timestamp_local}_{$subsecs}_$k.$ext";
  } else {
      return "{$timestamp_local}_{$subsecs}_$k.$ext";
Oleg Dzhimiev's avatar
Oleg Dzhimiev committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
  }
}

function get_ext($filename) {
  return pathinfo($filename, PATHINFO_EXTENSION);
}

/**
 * read image format and return extension, elphel elphel_specific
 * @param array $exif Array returned from the PHP's built-in exif_read_data function
 * @param string $override_ext
 * @return string extension - jpeg or jp4
 */
function elphel_specific_result_ext($exif,$override_ext=""){
  
  //default value
  $ext = "jpeg";
  
  if ($override_ext==""){
    if (isset($exif['MakerNote'][10])){
      $record = ($exif['MakerNote'][10]>>4)&0xf;
      if ($record==5) $ext = "jp4";
    }
  }else{
    $ext = $override_ext;
  }
  return $ext;
}

?>