elphel_php.c 114 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 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 122 123 124 125 126 127 128 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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
/** @file elphel_php.c
 *  @brief Implementation of elphel extension module for PHP to support camera functionality
 *  @copyright Copyright (C) 2008-2016 Elphel, Inc.
 *
 * @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/>.
 */

/****************************************************************************
 *! -----------------------------------------------------------------------------**
 *!  $Log: elphel_php.c,v $
 *!  Revision 1.8  2012/04/20 00:25:26  elphel
 *!  fixed bug in reading Exif data from PHP that was introduced while expanding MakerNote to include temperatures
 *!
 *!  Revision 1.7  2012/04/08 04:11:28  elphel
 *!  8.2.2 changes related to temperatures measurement and embedding in the Exif MakerNote
 *!
 *!  Revision 1.6  2010/08/10 21:14:31  elphel
 *!  8.0.8.39 - added EEPROM support for multiplexor and sensor boards, so autocampars.php uses application-specific defaults. Exif Orientation tag support, camera Model reflects application and optional mode (i.e. camera number in Eyesis)
 *!
 *!  Revision 1.5  2010/07/20 20:13:34  elphel
 *!  8.0.8.33 - added MakerNote info for composite images made with multisensor cameras (with 10359 board)
 *!
 *!  Revision 1.4  2010/05/13 03:39:31  elphel
 *!  8.0.8.12 -  drivers modified for multi-sensor operation
 *!
 *!  Revision 1.3  2010/03/04 06:41:40  elphel
 *!  8.0.7.3 - more data to makerNote
 *!
 *!  Revision 1.2  2009/12/28 06:24:17  elphel
 *!  8.0.6.6 - added MakerNote to Exif, it icludes channels gains and gammas/black levels
 *!
 *!  Revision 1.1  2009/04/03 23:18:59  elphel
 *!  rev 8.0.4.1 - upgraded PHP to 5.2.9 - directories/files added/removed
 *!
 *!  Revision 1.5  2009/02/18 06:25:41  elphel
 *!  fixed unterminated string of 1 character (GPS mode - 2/3)
 *!
 *!  Revision 1.4  2008/12/08 08:17:50  elphel
 *!  bug fix in elphel_get_P_value() - it did not handle bit filed for non-global variables ( elphel_get_P_arr() was OK)
 *!
 *!  Revision 1.3  2008/11/30 05:04:46  elphel
 *!  added Doxygen file data
 *!
 *!  Revision 1.2  2008/11/28 08:17:09  elphel
 *!  keeping Doxygen a little happier
 *!
 *!  Revision 1.1.1.1  2008/11/27 20:04:02  elphel
 *!
 *!
 *!  Revision 1.28  2008/11/22 05:56:40  elphel
 *!  elphel_set_P_arr(), elphel_set_P_value() now return frame number parameters were written to
 *!
 *!  Revision 1.27  2008/11/20 07:06:04  elphel
 *!  just touched to overcome dependency (or lack of its support) to make it notice updated c313a.h
 *!
 *!  Revision 1.26  2008/11/15 07:04:27  elphel
 *!  new parameters to modify analog gains while white balancing
 *!
 *!  Revision 1.25  2008/11/13 05:40:45  elphel
 *!  8.0.alpha16 - modified histogram storage, profiling
 *!
 *!  Revision 1.24  2008/11/05 02:01:25  elphel
 *!  Added bit field manipulation in parameters
 *!
 *!  Revision 1.23  2008/11/04 17:41:43  elphel
 *!  added elphel_gamma(), elphel_reverse_gamma(), elphel_histogram(), elphel_reverse_histogram() functions
 *!
 *!  Revision 1.22  2008/11/02 07:24:20  elphel
 *!  added support for some legacy functions
 *!
 *!  Revision 1.21  2008/11/02 00:33:02  elphel
 *!  Added TODO
 *!
 *!  Revision 1.20  2008/11/01 06:25:46  elphel
 *!  elphel_get_circbuf_pointers() now returns framenumber too
 *!
 *!  Revision 1.19  2008/10/31 18:26:32  elphel
 *!  Adding support for constants like SENSOR_REGS32 (defined constant plus 32 to simplify referencing sensor registers from PHP
 *!
 *!  Revision 1.18  2008/10/29 04:18:28  elphel
 *!  v.8.0.alpha10 made a separate structure for global parameters (not related to particular frames in a frame queue)
 *!
 *!  Revision 1.17  2008/10/28 07:05:49  elphel
 *!  touched
 *!
 *!  Revision 1.16  2008/10/25 19:51:06  elphel
 *!  Changed word order in writes to gamma tables driver
 *!
 *!  Revision 1.15  2008/10/23 18:26:14  elphel
 *!  Fixed percentile calculations in histograms
 *!
 *!  Revision 1.14  2008/10/23 08:11:38  elphel
 *!  updated for histograms wait queues
 *!
 *!  Revision 1.13  2008/10/19 06:56:05  elphel
 *!  elphel_wait_frame() now works only for compressed frames, new elphel_skip_frames() and elphel_wait_frame_abs() wait sequencer frames (all sensor frames, even those that are not compressed)
 *!
 *!  Revision 1.12  2008/10/15 22:28:56  elphel
 *!  snapshot 8.0.alpha2
 *!
 *!  Revision 1.11  2008/10/13 16:56:20  elphel
 *!  just touched to force recompile
 *!
 *!  Revision 1.10  2008/10/12 06:13:10  elphel
 *!  snapshot
 *!
 *!  Revision 1.9  2008/10/08 21:26:25  elphel
 *!  snapsot 7.2.0.pre4 - first images (actually - second)
 *!
 *!  Revision 1.8  2008/10/05 05:13:33  elphel
 *!  snapshot003
 *!
 *!  Revision 1.7  2008/10/04 16:10:12  elphel
 *!  snapshot
 *!
 *!  Revision 1.6  2008/09/25 00:58:11  elphel
 *!  snapshot
 *!
 *!  Revision 1.5  2008/09/19 18:06:38  elphel
 *!  snapshot
 *!
 *!  Revision 1.4  2008/09/19 04:37:24  elphel
 *!  snapshot
 *!
 *!  Revision 1.3  2008/09/07 19:48:08  elphel
 *!  snapshot
 *!
 *!  Revision 1.2  2008/06/04 20:07:08  elphel
 *!  adding support for multiple frames
 *!
 *!  Revision 1.21  2008/05/02 15:12:09  elphel
 *!  minor comment edit
 *!
 *!  Revision 1.20  2008/05/01 01:32:04  elphel
 *!  support for the frame number - combining hardware frame counter used by i2c (3-bit) and software one
 *!
 *!  Revision 1.19  2008/04/25 21:31:35  elphel
 *!  Added Exif_Photo_ExposureTime to be returned by elphel_get_exif_elphel()
 *!
 *!  Revision 1.18  2008/04/24 18:16:40  elphel
 *!  New function to retrieve circbuf structure (frame pointers and Exif pointers)
 *!
 *!  Revision 1.17  2008/04/22 22:14:08  elphel
 *!  Added functions related to Exif data
 *!
 *!  Revision 1.16  2008/04/20 06:49:04  elphel
 *!  Added histogram related functions
 *!
 *!  Revision 1.15  2008/04/17 22:36:07  elphel
 *!  Bug fix, new function added - elphel_is_compressor_idle()
 *!
 *!  Revision 1.14  2008/03/20 22:25:09  elphel
 *!  elphel_trigger - programming synchronization parameters
 *!
 *!  Revision 1.13  2008/03/15 23:04:21  elphel
 *!  added FPGA registers R/W
 *!
 *!  Revision 1.12  2008/01/27 06:23:17  elphel
 *!  New function - elphel_wait_frame (wait fro the next frame to be compressed)
 *!
 *!  Revision 1.11  2008/01/12 06:53:23  elphel
 *!  7.1.7.2 - added elphel_autoexposure_get() function to elphel php extension
 *!
 *!  Revision 1.10  2008/01/11 07:47:44  elphel
 *!  added elphel_autoexposure_set() function
 *!
 *!  Revision 1.9  2008/01/10 02:43:37  elphel
 *!  Added balance of 2 greens in Bayer mosaic
 *!
 *!  Revision 1.8  2008/01/09 10:22:02  elphel
 *!  Implemented elphel_white_balance() function
 *!
 *!  Revision 1.7  2007/12/14 22:38:53  elphel
 *!  cleaned up after fixing cache bug
 *!
 *!  Revision 1.6  2007/12/06 19:05:33  elphel
 *!  2 new functions - arbitrary compressor command (elphel_compressor_cmd) and elphel_compressor_reset
 *!
 *!  Revision 1.5  2007/12/05 23:41:04  elphel
 *!  Fixing minor in bugs in the sensor reset code
 *!
 *!  Revision 1.4  2007/12/05 22:01:19  elphel
 *!  added handling etrax fs mmap cache problem when communicating between PHP extension and the driver
 *!
 *!  Revision 1.3  2007/12/04 06:41:11  elphel
 *!  Implementation of 2 additional functions:    elphel_get_P_arr, elphel_set_P_arr
 *!
 */
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217


#ifdef HAVE_CONFIG_H
#include "config.h"
#endif


#include <sys/mman.h>		/* mmap */
#include <sys/ioctl.h>
#include <fcntl.h>     /* (O_RDWR) */
#include <asm/byteorder.h>
#include <errno.h>
#include "php.h"
#include "php_ini.h"  /* for php.ini processing */
#include "elphel_php.h"


ZEND_DECLARE_MODULE_GLOBALS(elphel)
static zend_function_entry elphel_functions[] = {
218
        PHP_FE(elphel_get_frame, NULL)
219
        PHP_FE(elphel_get_compressed_frame, NULL)
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
        PHP_FE(elphel_skip_frames, NULL)
        PHP_FE(elphel_wait_frame_abs, NULL)
        PHP_FE(elphel_framepars_get_raw, NULL)
        PHP_FE(elphel_parse_P_name, NULL)
        PHP_FE(elphel_is_global_par, NULL)
        PHP_FE(elphel_is_frame_par, NULL)
        PHP_FE(elphel_get_P_value, NULL)
        PHP_FE(elphel_test, NULL)
        PHP_FE(elphel_set_P_value, NULL)
        PHP_FE(elphel_get_P_arr, NULL)
        PHP_FE(elphel_set_P_arr, NULL)
        PHP_FE(elphel_gamma_add, NULL)
        PHP_FE(elphel_gamma_add_custom, NULL)
        PHP_FE(elphel_gamma_get, NULL)
        PHP_FE(elphel_gamma_get_index, NULL)
        PHP_FE(elphel_gamma_get_raw, NULL)
        PHP_FE(elphel_histogram_get_raw, NULL)
        PHP_FE(elphel_histogram_get, NULL)
        PHP_FE(elphel_get_state, NULL)

        PHP_FE(elphel_compressor_reset, NULL)
        PHP_FE(elphel_compressor_run, NULL)
        PHP_FE(elphel_compressor_stop, NULL)
        PHP_FE(elphel_compressor_frame, NULL)
        PHP_FE(elphel_reset_sensor, NULL)
        PHP_FE(elphel_set_fpga_time, NULL)
        PHP_FE(elphel_get_fpga_time, NULL)
        PHP_FE(elphel_wait_frame, NULL)
        PHP_FE(elphel_fpga_read, NULL)
        PHP_FE(elphel_fpga_write, NULL)
        PHP_FE(elphel_gamma, NULL)
        PHP_FE(elphel_reverse_gamma, NULL)
        PHP_FE(elphel_histogram, NULL)
        PHP_FE(elphel_reverse_histogram, NULL)
        PHP_FE(elphel_get_exif_field, NULL)
        PHP_FE(elphel_set_exif_field, NULL)
        PHP_FE(elphel_get_interframe_meta, NULL)
        PHP_FE(elphel_get_exif_elphel, NULL)
        PHP_FE(elphel_update_exif, NULL)
        PHP_FE(elphel_get_circbuf_pointers, NULL)
        {NULL, NULL, NULL}
261 262 263 264
};

zend_module_entry elphel_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
265
        STANDARD_MODULE_HEADER,
266
#endif
267 268 269 270 271 272 273
        PHP_ELPHEL_EXTNAME,
        elphel_functions,
        PHP_MINIT(elphel),
        PHP_MSHUTDOWN(elphel),
        PHP_RINIT(elphel),
        NULL,
        PHP_MINFO(elphel),
274
#if ZEND_MODULE_API_NO >= 20010901
275
        PHP_ELPHEL_VERSION,
276
#endif
277
        STANDARD_MODULE_PROPERTIES
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
};

#ifdef COMPILE_DL_ELPHEL
ZEND_GET_MODULE(elphel)
#endif


PHP_INI_BEGIN()
//! read ini entries here
PHP_INI_END()


//!call before any access to sensor parameters/functions
static void init_sens() {
}
293

294 295 296 297 298 299 300
/**
 * @brief See if the name ends with __A,__B,__c,__a,__b.__c
 * @param name constant name, possibly ending with a suffix __A,__B,__c,__a,__b or __c
 * @return <0 - no suffix, >=0 channel (0..2) | 4 for strict (lower case)
 */
//multiSensIndex 
int parseMultiSens(char * name) {
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    int len= strlen(name);
    int nIndex;
    int d=0;
    int dp=1;
    int bfields;
    int rslt=-1;
    if ((len>3) && (name[len-2]=='_') && (name[len-3]=='_')) {
        switch (name[len-1]) {
        case 'A':rslt=0; break;
        case 'B':rslt=1; break;
        case 'C':rslt=2; break;
        case 'a':rslt=256; break;
        case 'b':rslt=257; break;
        case 'c':rslt=258; break;
        }
    }
    if (rslt >=0) name[len-3]='\0';
    return rslt;
319 320 321 322 323 324 325 326 327 328
}

/**
 * @brief apply
 * @param parNum parameter composite index
 * @param multiMod bit 8 - strict, lower bits - channel index
 * @return -1 - failure, otherwise - parameter index with allcontrol  bits preserved
 */
//multiSensIndex P_MAX_PAR MAX_SENSORS=3
int applyMultiSens(long parNum, long multiMod) {
329 330 331 332 333 334 335 336 337 338 339 340 341
    unsigned long * multiSensIndex = ((unsigned long *) (ELPHEL_G (multiSensIndex)));
    long parIndex= parNum &0xffff;
    if (parIndex >= P_MAX_PAR) return -1;
    if (multiSensIndex[parIndex]==0) {
        if (multiMod & 0x100) return -1;
        return parNum; /// No individual parameters available, return the original one as 'strict' bit is not set.
    }
    multiMod &= 0xff;
    if (multiMod >= MAX_SENSORS) return -1;
    parIndex= (multiSensIndex[parIndex]+multiMod) & 0xffff;
    if (parIndex >= P_MAX_PAR) return -1; /// multiSensIndex seems to be corrupted - add error message?

    return (parNum & 0xffff0000) | parIndex; /// preserve original modifiers
342 343 344 345 346 347 348 349 350 351 352 353
}

/**
 * @brief See if the name ends with number, truncate name to remove number and return number value
 * @param name constant name, possibly ending with a number (decimal)
 *        if constant includes "__" (double "_") and has 4 decimals after __WWBB, those decimals are treated as
 *        bit field specs (WW 1..31 - width, BB - 0..31 - start bit ), i.e. "__0816" is the 3-rd byte of 4 in the 32-bit parameter
 *        These bit-filed modifiers are stored in bits 16..20 (bit) and 21..25 (width) of parameter address (number)
 * @return number value (to be added to the constant value) or -1 if name does not end with a number
 */
//multiSensIndex 
int splitConstantName(char * name) {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    int len= strlen(name);
    int nIndex;
    int d=0;
    int dp=1;
    int bfields;
    int success=0;
    if ((len>6) && (name[len-6]=='_') && (name[len-5]=='_')) {

        d= FRAMEPAIR_FRAME_BITS(((name[len-3] - '0') + ((name[len-4] - '0') * 10)), ((name[len-1] - '0') + ((name[len-2] - '0') * 10)));
        name[len-6]='\0';
        len-=6;
        success=1;
    }
    nIndex= len-1;
    while ((nIndex>0) && (name[nIndex]>='0') && (name[nIndex] <='9')){
        d+=dp*(name[nIndex]-'0');
        dp*=10;
        nIndex--;
        success=1;
    }
    nIndex++;
    if (success) {
        name[nIndex]='\0'; /// terminate name with '\0'
        return d;
    } else return -1;
379 380 381 382 383
}

/// Get current frame number
PHP_FUNCTION(elphel_get_frame)
{
384 385 386 387 388 389
    long port;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &port) == FAILURE)
        RETURN_NULL();
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    RETURN_LONG( ELPHEL_GLOBALPARS(port,G_THIS_FRAME));
390
} 
391 392 393 394 395 396 397 398 399 400
/// Get current compressed frame number
PHP_FUNCTION(elphel_get_compressed_frame)
{
    long port;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &port) == FAILURE)
        RETURN_NULL();
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    RETURN_LONG( ELPHEL_GLOBALPARS(port,G_COMPRESSOR_FRAME));
}
401 402
PHP_FUNCTION(elphel_skip_frames)
{
403
    long port;
404
    long skip=1;
405
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &port, &skip) == FAILURE)
406
        RETURN_NULL();
407 408 409 410 411 412
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    long target_frame=lseek((int) ELPHEL_G( fd_fparmsall[port]), 0, SEEK_CUR )+skip;
    if ((target_frame<0) || (target_frame > 0x7ffffdff))
        RETURN_NULL(); /// Out of limit for skip frames
    RETURN_LONG(lseek((int) ELPHEL_G( fd_fparmsall[port]), target_frame + LSEEK_FRAME_WAIT_ABS, SEEK_END ));
413 414 415 416
} 

PHP_FUNCTION(elphel_wait_frame_abs)
{
417
    long port;
418
    long target_frame;
419
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &port, &target_frame) == FAILURE)
420
        RETURN_NULL();
421 422 423 424
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    if ((target_frame<0) || (target_frame > 0x7ffffdff))
        RETURN_NULL(); /// Out of limit for skip frames
425
    RETURN_LONG(lseek((int) ELPHEL_G( fd_fparmsall[port]), target_frame + LSEEK_FRAME_WAIT_ABS, SEEK_END ));
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
} 

/**
 * @brief Parse P_* /G_* parameter name with modifiers
 * @param name - constant name (w/o leading "ELPHEL_")
 * @return  full address/number or NULL if it does not exist
 */
PHP_FUNCTION(elphel_parse_P_name)
{
    char full_constant_name[256];
    char *name;
    int name_len;
    long full_addr =-1;
    zval const_value;
    long constAddNumber;
    long multiMod;
442 443
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE)
        RETURN_NULL();
444 445 446
    if (strlen(name)>(sizeof(full_constant_name)-8)) RETURN_NULL();
    sprintf (full_constant_name,"ELPHEL_%s",name);
    if (zend_get_constant(full_constant_name, strlen(full_constant_name), &const_value TSRMLS_CC)) { /// found the constant as is
447
        full_addr= Z_LVAL(const_value);
448
    } else {
449 450 451 452 453 454
        multiMod=parseMultiSens(full_constant_name); /// will truncate  full_constant_name if sensor number suffix found
        constAddNumber=splitConstantName(full_constant_name);
        if ((constAddNumber>=0) && (zend_get_constant(full_constant_name, strlen(full_constant_name), &const_value TSRMLS_CC))) {
            full_addr= (Z_LVAL(const_value) & ~FRAMEPAIR_MASK_BYTES)+constAddNumber; /// FRAMEPAIR_MASK_BYTES to prevent bit-field modifier addition to constants that already have them
            if ((multiMod>=0) && (full_addr!=-1)) full_addr=applyMultiSens(full_addr,multiMod);
        }
455 456
    }
    if (full_addr!=-1) {
457 458
        RETURN_LONG (full_addr);
        zval_dtor(&const_value);
459 460 461 462 463 464 465 466 467 468 469 470
    }
    RETURN_NULL();
}

/**
 * @brief Strips integer constant of optional modifiers and finds if it is a valid global parameter number
 * @param full parameter address
 * @return true if this address is a valid address of a global parameter
 */
PHP_FUNCTION(elphel_is_global_par)
{
    long addr;
471
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &addr) == FAILURE)
472 473 474 475 476 477 478 479 480 481 482 483 484 485
        RETURN_NULL();
    addr &= 0xffff; /// remove any possible flags
    if ((addr >= FRAMEPAR_GLOBALS) && (addr < (FRAMEPAR_GLOBALS+P_MAX_GPAR))) RETURN_TRUE;
    RETURN_FALSE;
}

/**
 * @brief Strips integer constant of optional modifiers and finds if it is a valid frame parameter number
 * @param full parameter address
 * @return true if this address is a valid address of a frame parameter
 */
PHP_FUNCTION(elphel_is_frame_par)
{
    long addr;
486
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &addr) == FAILURE)
487 488 489 490 491 492 493 494 495 496
        RETURN_NULL();
    addr &= 0xffff; /// remove any possible flags
    if (addr < (sizeof (struct framepars_t) >>2)) RETURN_TRUE;
    RETURN_FALSE;
}

//! Read value from the sensor/compressor parameters ("read" parameters, verified by the driver), see asm/elphel/c313a.h
///TODO: Make it read pastPars also?
PHP_FUNCTION(elphel_get_P_value)
{
497
    long port, addr, full_addr;
498 499 500
    long frame=-1;
    long frame_index=-1;
    int  frame_stored;
501
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll|l", &port, &full_addr,&frame) == FAILURE)
502
        RETURN_NULL();
503 504 505 506
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    if (frame <0)
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME);
507
    addr = full_addr & 0xffff; /// remove any possible flags
508
    /// is it a global parameter?
509
    if (addr >= FRAMEPAR_GLOBALS) { /// these globals can be written just through mmap
510 511 512 513 514 515 516 517 518
        if (addr >= (FRAMEPAR_GLOBALS+P_MAX_GPAR))
            RETURN_NULL();
        if (full_addr & FRAMEPAIR_MASK_BYTES) {
            RETURN_LONG(FRAMEPAIR_FRAME_FIELD(full_addr,ELPHEL_GLOBALPARS(port,addr)));
        } else {
            RETURN_LONG(ELPHEL_GLOBALPARS(port, addr));
        }
    }
    /// processing dynamic frame parameters
519
    if ((addr<0) ||(addr>= (sizeof (struct framepars_t) >>2))) {
520
        RETURN_NULL();
521 522
    }
    if (frame <0) {
523 524
        //      frame=ELPHEL_GLOBALPARS(G_THIS_FRAME) + FRAME_DEAFAULT_AHEAD;
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME);  /// read current (most recent) frame - different from _set_
525 526
    }

527
    ///try framePars
528
    frame_index = frame & PARS_FRAMES_MASK;
529
    frame_stored= ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[P_FRAME];
530
    if (frame_stored == frame) { /// This is what we are looking for
531 532 533 534 535
        if (full_addr & FRAMEPAIR_MASK_BYTES) {
            RETURN_LONG( FRAMEPAIR_FRAME_FIELD(full_addr,((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[addr]));
        } else {
            RETURN_LONG( ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[addr]);
        }
536
    }
537 538
    if (frame_stored < frame) { /// too early for the frame number specified
        RETURN_NULL();
539
    }
540
    /// too late for framePars - let's try pastPars
541
    frame_index = frame & PASTPARS_SAVE_ENTRIES_MASK;
542
    frame_stored= ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[P_FRAME-PARS_SAVE_FROM];
543
    if (frame_stored == frame) { /// This is what we are looking for
544 545 546 547 548 549 550 551 552 553 554
        addr-=PARS_SAVE_FROM;
        if ((addr<0) ||(addr>= (sizeof (struct framepars_past_t) >>2))) {
            RETURN_NULL();
        }
        if (full_addr & FRAMEPAIR_MASK_BYTES) {
            RETURN_LONG(FRAMEPAIR_FRAME_FIELD(full_addr,((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[addr]));
        } else {
            RETURN_LONG( ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[addr]);
        }
    }
    /// too late, probably
555 556 557 558 559
    RETURN_NULL();
}

PHP_FUNCTION(elphel_test)
{
560 561
    long result= ELPHEL_GLOBALPARS(0, G_THIS_FRAME);
    RETURN_LONG(result);
562 563 564 565 566 567 568 569
} 


///NOTE: Just for compatibility with older code
//!Get sensor state, usually 7- sensor is running,  compressor is stopped, 8 - compressor is runing
//!program sensor/compressor according to the parameters specified. Argument==0 - restart the sensor, 1 - do it "on the fly"
PHP_FUNCTION(elphel_get_state)
{
570 571 572 573 574 575 576 577 578 579 580
    long port, frame16, compressor_state, sensor_state, result;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &port) == FAILURE)
        RETURN_NULL();
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    frame16=ELPHEL_GLOBALPARS(port, G_THIS_FRAME) & PARS_FRAMES_MASK;
    compressor_state= ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame16].pars[P_COMPRESSOR_RUN];
    sensor_state=     ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame16].pars[P_SENSOR_RUN];
    result=(compressor_state==COMPRESSOR_RUN_CONT)?0x8:
            ((compressor_state==COMPRESSOR_RUN_SINGLE)?0xa:
                    ((sensor_state==SENSOR_RUN_CONT)?0x7:0));
581 582 583 584 585
    RETURN_LONG(result);
} 

/**
 * @brief return selected (by integer index) framepars structure  (struct framepars_t) as a binary string
Andrey Filippov's avatar
Andrey Filippov committed
586
 * @param port - sensor port (0..3)
587 588 589 590 591 592 593
 * @param index - frame index (0..7). -1 - return func2call page instead, -2 - globalPars
 * @return NULL - error, otherwise a string with  (struct framepars_t)
 *
 */

PHP_FUNCTION(elphel_framepars_get_raw)
{
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    long port, index;
    char * packed_framepars_structure;
    index=0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l",&port,  &index) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong index");
        RETURN_NULL ();
    }
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    packed_framepars_structure= (char*) emalloc (sizeof (struct framepars_t));
    if (packed_framepars_structure) {
        /// use gamma_cache_index to retrieve table from cache
        if (index>=0) {
            memcpy(packed_framepars_structure, &(((struct framepars_t *) ELPHEL_G(framePars[port]))[index & PARS_FRAMES_MASK]),sizeof(struct framepars_t));
        } else if (index == -1) {
            memcpy(packed_framepars_structure,   ((struct framepars_t *) ELPHEL_G(funcs2call[port])),sizeof(struct framepars_t));
        } else if (index == -2) {
            memcpy(packed_framepars_structure,   ((struct framepars_t *) ELPHEL_G(globalPars[port])),sizeof(struct framepars_t));
        } else RETURN_NULL ();
        RETURN_STRINGL (packed_framepars_structure, sizeof(struct framepars_t), 0);
    }
    php_error_docref(NULL TSRMLS_CC, E_ERROR, "emalloc error");
    RETURN_NULL ();
617 618 619 620 621 622 623 624 625 626 627 628
}


//! This function reads associative array and uses the keys as a template for the result array.
//! If mey is one of the defined P_VALUE names (same as global constant but w/o "ELPHEL_" prefix)
//! then the result array will have element with the same key and the value equal to the value
//! of the camera parameter
/// TODO:Make it per frame (absolute), combine with past frames
/// frame absent - "current frame"
/// frame ==0 - frame zero (static?)
PHP_FUNCTION(elphel_get_P_arr)
{
629
    long port;
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    long frame=-1;
    long frame_index=-1;
    int  future=1;
    int  frame_stored;
    long addr,full_addr,val;
    char full_constant_name[256];
    zval *arr, **data;
    HashTable *arr_hash;
    HashPosition pointer;
    char *key;
    int   key_len;
    long index;
    long constAddNumber; /// number to add to the ELPHEL_* constant value
    zval const_value;
    long multiMod;
645
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "la|l",&port, &arr, &frame) == FAILURE) {
646 647
        RETURN_NULL();
    }
648 649 650 651
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    //    init_sens();
    /// first see if this frame is either in the future, past or is frame zero (parameters that are not related to frames)
652
    if (frame < 0) { /// frame number not provided - use latest
653
        frame=ELPHEL_GLOBALPARS(port,G_THIS_FRAME);
654
    }
655
    /// try future first
656
    frame_index = frame & PARS_FRAMES_MASK;
657
    frame_stored= ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[P_FRAME];
658
    if (frame_stored <frame) { /// too early for the frame number specified
659
        future=-1 ; /// not available - only global parameters could be retrieved
660 661
    }
    if (frame_stored > frame) { /// Maybe it is in the past frames (only subset of parameters preserved)
662 663 664 665 666
        frame_index = frame & PASTPARS_SAVE_ENTRIES_MASK;
        frame_stored= ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[P_FRAME-PARS_SAVE_FROM];
        if (frame_stored != frame) { /// Too late, probably - all the records are gone by now
            future=-1 ;// not available - only global parameters could be retrieved
        } else future=0; /// should be there, but in the past
667 668 669 670 671
    }

    array_init(return_value);
    arr_hash = Z_ARRVAL_P(arr);
    for(zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
672 673
            zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
            zend_hash_move_forward_ex(arr_hash, &pointer)) {
674
        if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
675 676 677 678 679 680 681 682 683 684 685 686
            if (strlen(key)>(sizeof(full_constant_name)-8)) RETURN_NULL();
            sprintf (full_constant_name,"ELPHEL_%s",key);
            full_addr =-1;
            if (zend_get_constant(full_constant_name, strlen(full_constant_name), &const_value TSRMLS_CC)) { /// found the constant as is
                full_addr= Z_LVAL(const_value);
            } else {
                multiMod=parseMultiSens(full_constant_name); /// will truncate  full_constant_name if sensor number suffix found
                constAddNumber=splitConstantName(full_constant_name);
                //              php_printf ("constAddNumber=%d, full_constant_name=%s (length=%d)\n",constAddNumber, full_constant_name,strlen(full_constant_name));
                if ((constAddNumber>=0) && (zend_get_constant(full_constant_name, strlen(full_constant_name), &const_value TSRMLS_CC))) { /// Try to remove number from the end
                    full_addr= (Z_LVAL(const_value) & ~FRAMEPAIR_MASK_BYTES)+constAddNumber; /// FRAMEPAIR_MASK_BYTES to prevent bit-field modifier addition to constants that already have them
                    if ((multiMod>=0) && (full_addr != -1)) full_addr=applyMultiSens(full_addr,multiMod);
687
                }
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
            }
            if (full_addr!=-1) {
                addr=full_addr & 0xffff;
                /// is it a global parameter?
                if (addr >= FRAMEPAR_GLOBALS) {
                    if (addr < (FRAMEPAR_GLOBALS+P_MAX_GPAR)) {
                        if (full_addr & FRAMEPAIR_MASK_BYTES) {
                            add_assoc_long(return_value, key, FRAMEPAIR_FRAME_FIELD(full_addr,ELPHEL_GLOBALPARS(port, addr)));
                        } else {
                            add_assoc_long(return_value, key, ELPHEL_GLOBALPARS(port, addr));
                        }
                    }
                    /// is it in the future/latest?
                } else if (future>0) {
                    if ((addr >=0) && (addr < (sizeof (struct framepars_t) >>2))) {
                        if (full_addr & FRAMEPAIR_MASK_BYTES) {
                            add_assoc_long(return_value, key, FRAMEPAIR_FRAME_FIELD(full_addr,((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[addr]));
                        } else {
                            add_assoc_long(return_value, key, ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[addr]);
                        }
                    }
                    /// is it saved in past parameters?
                } else if (future==0){
                    addr-=PARS_SAVE_FROM;
                    if ((addr >=0) && (addr <(sizeof (struct framepars_past_t) >>2))) {
                        if (full_addr & FRAMEPAIR_MASK_BYTES) {
                            add_assoc_long(return_value, key, FRAMEPAIR_FRAME_FIELD(full_addr,((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[addr]));
                        } else {
                            add_assoc_long(return_value, key, ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[addr]);
                        }
                    }
719
                }
720 721
                zval_dtor(&const_value);
            }
722 723 724 725 726 727 728 729 730 731 732 733 734
        }
    }
}

/**
 * @brief common part of elphel_set_P_value() and elphel_compressor_*()
 * @param addr    register address (with possible flags)
 * @param data    data to write
 * @param frame   frame to write (<0) - use current + FRAME_DEAFAULT_AHEAD
 * @param flags   additional flags (0) - none
 * @return <0 - -errno ( error), otherwise frame used
 */

735
long elphel_set_P_value_common(long port, long addr, long data, long frame, long flags) {
736 737
    unsigned long write_data[4];
    long maddr;
738 739 740
    ///shortcut for global parameters - directly mmaped
    if ((port < 0) || (port > SENSOR_PORTS))
        return -1;
741 742
    maddr=addr & 0xffff;
    if (( (addr & 0xff00) != 0xff00 ) && (maddr >= FRAMEPAR_GLOBALS)) { /// these globals can be written just through mmap
743 744 745 746 747
        if (maddr >= (FRAMEPAR_GLOBALS+P_MAX_GPAR)) {
            return -1;
        }
        ELPHEL_GLOBALPARS(port, maddr)=data;
        return 0;
748 749
    }
    if (frame <0) {
750
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME) + FRAME_DEAFAULT_AHEAD;
751 752 753 754
    }
    flags |= (flags << 16); /// will accept flags both shifted and not shifted
    flags &=0xffff0000;
    if ((addr<0) ||((maddr >= (sizeof (struct framepars_t) >>2)) && ( (addr & 0xff00) != 0xff00 )  )) {
755
        return -1;
756 757 758 759 760
    }
    write_data[0]=FRAMEPARS_SETFRAME;
    write_data[1]=frame;
    write_data[2]= addr | flags;
    write_data[3]= data;
761 762
    long rslt=write(ELPHEL_G(fd_fparmsall[port]), write_data, sizeof(write_data));
    //    if (rslt<0) rslt =-errno;
763 764 765 766 767 768 769 770 771 772 773 774
    if (rslt<0) return -errno;
    if (rslt == sizeof( write_data )) return frame;
    return -1;
}


//! Set acquisition/compression parameters.
/// addr may include flags - addr|=(flags>>16)
/// UPDATE: return frame number to which parameters was set

PHP_FUNCTION(elphel_set_P_value)
{
775
    long port;
776 777 778 779
    long addr;
    long data;
    long frame=-1;
    unsigned long flags=0;
780 781
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll|ll", &port, &addr,&data,&frame,&flags) == FAILURE) {
        RETURN_NULL();
782
    }
783 784
    if (((frame=elphel_set_P_value_common (port, addr, data, frame, flags))) <0) {
        RETURN_NULL();
785 786 787 788 789 790 791
    }
    RETURN_LONG(frame);
}

//! Reset FPGA compressor - set to the same as elphel_compressor_stop()
PHP_FUNCTION(elphel_compressor_reset)
{
792
    long port;
793 794
    long frame=-1;
    unsigned long flags=-1;
795 796
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ll", &port, &frame,&flags) == FAILURE) {
        RETURN_NULL();
797 798
    }
    if (flags<0) flags=FRAMEPAIR_FORCE_NEWPROC;
799 800
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_STOP, frame, flags)))<0) {
        RETURN_NULL();
801 802 803 804 805 806 807
    }
    RETURN_LONG(frame);
} 

//! Start FPGA compressor
PHP_FUNCTION(elphel_compressor_run)
{
808
    long port;
809 810
    long frame=-1;
    unsigned long flags=-1;
811 812
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ll", &port, &frame,&flags) == FAILURE) {
        RETURN_NULL();
813 814
    }
    if (flags<0) flags=FRAMEPAIR_FORCE_NEWPROC;
815 816
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_CONT, frame, flags)))<0) {
        RETURN_NULL();
817 818 819 820 821 822 823 824
    }
    RETURN_LONG(frame);
} 

//! Stop FPGA compressor

PHP_FUNCTION(elphel_compressor_stop)
{
825
    long port;
826 827
    long frame=-1;
    unsigned long flags=-1;
828 829
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ll", &port, &frame,&flags) == FAILURE) {
        RETURN_NULL();
830 831
    }
    if (flags<0) flags=FRAMEPAIR_FORCE_NEWPROC;
832 833
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_STOP, frame, flags)))<0) {
        RETURN_NULL();
834 835 836 837 838 839 840
    }
    RETURN_LONG(frame);
}

//! Acquire one frame to the buffer
PHP_FUNCTION(elphel_compressor_frame)
{
841
    long port;
842 843
    long frame=-1;
    unsigned long flags=-1;
844 845
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ll", &port, &frame,&flags) == FAILURE) {
        RETURN_NULL();
846 847
    }
    if (flags<0) flags=FRAMEPAIR_JUST_THIS;
848 849
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_SINGLE, frame, flags)))<0) {
        RETURN_NULL();
850 851 852 853 854
    }
    RETURN_LONG(frame);
} 
//!reset sensor, and re-initialize it
PHP_FUNCTION(elphel_reset_sensor) {
855 856 857 858 859 860 861
    long port;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &port) == FAILURE) {
        RETURN_NULL();
    }
    lseek((int) ELPHEL_G(fd_fparmsall[port]), LSEEK_FRAMEPARS_INIT, SEEK_END ); /// reset all framepars and globalPars
    elphel_set_P_value_common (port, P_SENSOR, 0, 0, -1);
    RETURN_NULL();
862 863 864 865 866 867 868 869 870
}

//! This function reads associative array and writes values to the camera registers, using "ELPHEL_* constants"
//! to determine register address from the provided key in each key/value pair
//! All non-numerical values are ignored
//! Returns number of values written
///UPDATE:retuns frame number to which parameters were written
PHP_FUNCTION(elphel_set_P_arr)
{
871
    long port;
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    char full_constant_name[256];
    zval *arr, **data;
    HashTable *arr_hash;
    HashPosition pointer;
    char *key;
    int   key_len;
    long index;
    zval const_value;
    int array_count;
    unsigned long * write_data=NULL;
    long frame=-1;
    long flags=0;
    int num_written=0;
    int num_mmap_written=0;
    int reg_addr, reg_data, constAddNumber;
    long multiMod;
888
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "la|ll", &port, &arr,&frame,&flags) == FAILURE) {
889 890
        RETURN_LONG(num_written);
    }
891 892
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
893
    if (frame <0) {
894
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME) + FRAME_DEAFAULT_AHEAD;
895 896 897 898 899 900
    }
    flags |= (flags << 16); /// will accept flags both shifted and not shifted
    flags &=0xffff0000;
    init_sens();
    arr_hash = Z_ARRVAL_P(arr);
    array_count = zend_hash_num_elements(arr_hash);
901
    ///allocate array to be written (8 bytes per value + 8)
902 903 904 905 906 907
    write_data=(unsigned long *) emalloc ((array_count+1)<<3);
    if (!write_data) RETURN_NULL(); /// emalloc failed

    write_data[0]=FRAMEPARS_SETFRAME;
    write_data[1]=frame;
    for(zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
908 909
            zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
            zend_hash_move_forward_ex(arr_hash, &pointer)) {
910
        if ((zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) &&
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
                (Z_TYPE_PP(data) == IS_LONG)) {
            reg_data=Z_LVAL_PP(data);
            if (strlen(key)>(sizeof(full_constant_name)-8)) RETURN_NULL();
            sprintf (full_constant_name,"ELPHEL_%s",key);

            reg_addr =-1;
            if (zend_get_constant(full_constant_name, strlen(full_constant_name), &const_value TSRMLS_CC)) { /// found the constant as is
                reg_addr= Z_LVAL(const_value);
            } else {
                multiMod=parseMultiSens(full_constant_name); /// will truncate  full_constant_name if sensor number suffix found
                constAddNumber=splitConstantName(full_constant_name);
                if ((constAddNumber>=0) && (zend_get_constant(full_constant_name, strlen(full_constant_name), &const_value TSRMLS_CC))) { /// Try to remove number from the end
                    reg_addr= (Z_LVAL(const_value) & ~FRAMEPAIR_MASK_BYTES)+constAddNumber; /// FRAMEPAIR_MASK_BYTES to prevent bit-field modifier addition to constants that already have them
                    if ((multiMod>=0) && (reg_addr != -1)) reg_addr=applyMultiSens(reg_addr,multiMod);
                }
            }

            if (reg_addr>=0) {
                /// is it a global parameter?
                zval_dtor(&const_value); /// free resources used for constant value
                if (((reg_addr & 0xff00) != 0xff00 ) && ((reg_addr & 0xffff) >= FRAMEPAR_GLOBALS)) {  /// these globals can be written just through mmap
                    if ((reg_addr & 0xffff) < (FRAMEPAR_GLOBALS+P_MAX_GPAR)) { /// Fits in the range of the global parameters
                        if ((reg_addr & FRAMEPAIR_MASK_BYTES) ==0) { /// Full 32-bit writes - use mmap
                            ELPHEL_GLOBALPARS(port, reg_addr & 0xffff)=reg_data;
                            num_mmap_written++;
                        } else { /// only some bitfield is modified -  use (slower) write to have it atomic, no need to do bit field combining here
                            write_data[(num_written<<1) + 2]= reg_addr | flags;
                            write_data[(num_written<<1) + 3]= reg_data;
                            num_written++;
                        }
                    }
                } else if ((reg_addr>=0) && (((reg_addr & 0xffff) < (sizeof (struct framepars_t) >>2)) || ( (reg_addr & 0xff00) == 0xff00 )  )) {
943 944 945 946
                    write_data[(num_written<<1) + 2]= reg_addr | flags;
                    write_data[(num_written<<1) + 3]= reg_data;
                    num_written++;
                }
947
            }
948 949 950
        }
    }
    if (num_written) {
951 952 953 954
        long rslt=write(ELPHEL_G(fd_fparmsall[port]), write_data, (num_written+1)<<3);
        efree(write_data);
        if (rslt<0) RETURN_LONG(-errno);
        num_written=(rslt>>3) -1 ; ///actually written to driver
955 956 957 958 959 960 961 962 963 964 965 966 967
    }
    RETURN_LONG(frame);
}

/**
 * @brief Calculate gamma table (as array of 257 unsigned short values)
 * @param gamma - gamma value (1.0 - linear)
 * @param black - black level, 1.0 corresponds to 256 for 8bit values
 * @param gtable - gamma array reference (allocated by the caller)
 * @return 0 - OK, <0 - error
 */

int gamma_calc (double gamma, double black, unsigned short * gtable) {
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    int i;
    double x, black256,k;
    int ig;
    black256=black*256.0;
    if (k>=1.0) k= k/256.0 ; /// just in case k is provided as a fraction of 256, not 1.0
    if (k>0.99) k=0.99;
    k=1.0/(256.0-black256);
    if (!gtable) return -1;
    ///Same 0.13 <= gamma <= 10.0 limits for gamma as used earlier
    if (gamma < 0.13) gamma=0.13;
    if (gamma >10.0)  gamma=10.0;
    for (i=0; i<257; i++) {
        x=k*(i-black256);
        if (x < 0.0 ) x=0.0;
        ig= 0.5+65535.0*pow(x,gamma);
        if (ig > 0xffff) ig=0xffff;
        gtable[i]=ig;
    }
    return 0;
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
}

/**
 * @brief Calculate new gamma table (specified by gamma value and black level) and put it into gamma cache
 * Gamma cache will be used to program gamma tables to FPGA, calculate derivative tables
 * Gamma tables should be loaded before used (gamma/black level/scale) specified as frame parameters 
 * gamma - floating point, <=1.0,  will be rounded to 0.01. Larger gammas are reseved for custom tables
 * black - floating point, <=1.0 or integer>1 (1..255) - level to subtract from sensor value
 * @return hash16 - ((gamma *100) & 0xff) | (((black * 256) 0xff) << 8)
 */
PHP_FUNCTION(elphel_gamma_add)
{
    unsigned short data_to_write[260];
    double gamma,black;
    int igamma, iblack, hash16;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd", &gamma, &black ) == FAILURE) {
1003 1004
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong arguments");
        RETURN_NULL ();
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    }
    igamma=100*gamma+0.5;
    if (igamma <   0) igamma=  0;
    if (igamma > 255) igamma=255;
    gamma=0.01*igamma;
    iblack= (black>=1.0)?black:(256*black+0.5);
    if (iblack <   0) iblack=  0;
    if (iblack > 254) iblack=254; /// don't use 255 - reserve it for custom tables
    black= (1.0/256.0) * iblack;
    hash16= igamma | (iblack<<8);
    data_to_write[0]= GAMMA_SCLALE_1; /// 1.0
    data_to_write[1]= hash16;
1017 1018
    ///- next 1 byte   [4]   - mode (1 - not_nice, 2 - need reverse, 4 - hardware)
    ///- next 1 byte   [5]   - color ( only if hardware bit in mode is set)
1019 1020 1021 1022
    data_to_write[2]=0;
    gamma_calc (gamma, black, &data_to_write[3]);
    long rslt=write(ELPHEL_G(fd_gamma_cache), data_to_write, sizeof(data_to_write));
    if (rslt<0) {
1023 1024
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Write to fd_gamma_cache returned errno=%d",errno);
        RETURN_LONG(-errno);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    }
    RETURN_LONG (hash16);
}

/**
 * @brief Load custom gamma table, tag it with hash16 (unsigned short).
 * Using lower byte of hash16 larger than 0x64 (100) or high byte of 0xff will prevent hash16 used by gamma/blacklevel pairs
 * @param hash16 - hash 16 that will be used to identify the table when setting parameters
 * @param zarray - array of 257 elements indexed as 0..256, in the range of 0.. 1.0 to be used for a table
 * @return   -1.. -998 - errno when writing to driver
 *         -998        - wrong arguments
 *         -999        - array length is not 257
 *        -1000..-1256 - missing element 0..256
 *        -2000..-2256 - non-numeric element 0..256
 *        >=0 - hash16
 */

PHP_FUNCTION(elphel_gamma_add_custom)
{
    unsigned short data_to_write[260];
    long  hash16;
    int i,d;
    zval *arr,  **data;
    HashTable *arr_hash;
    long array_count;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "la", &hash16, &arr ) == FAILURE) {
1052 1053
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong arguments");
        RETURN_LONG (-998);
1054 1055 1056 1057
    }
    arr_hash = Z_ARRVAL_P(arr);
    array_count = zend_hash_num_elements(arr_hash);
    if (array_count != 257) {
1058 1059
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong array length (should be 257) - %d",array_count);
        RETURN_LONG (-999);
1060 1061 1062 1063
    }
    hash16 &= 0xffff;
    data_to_write[0]= GAMMA_SCLALE_1; /// 1.0
    data_to_write[1]= hash16;
1064 1065
    ///- next 1 byte   [4]   - mode (1 - not_nice, 2 - need reverse, 4 - hardware)
    ///- next 1 byte   [5]   - color - only if hardware bit in mode is set
1066
    data_to_write[2]=0;
1067
    /// now iterate through indexed array
1068
    for (i=0; i<257; i++) {
1069 1070 1071 1072 1073
        if (zend_hash_index_find(arr_hash, i, (void**)&data) == FAILURE) {
            php_error_docref(NULL TSRMLS_CC, E_ERROR, "Missing array element [%d]",i);
            RETURN_LONG(-i-1000);
        }
        switch (Z_TYPE_PP(data)) {
1074 1075 1076 1077 1078
        case IS_DOUBLE:
            d=Z_DVAL_PP(data);
            break;
        case IS_LONG:
            d=(1.0/255)* Z_LVAL_PP(data);
1079
            break; // Was missing before NC393
1080
        default:
1081 1082 1083 1084 1085 1086
            php_error_docref(NULL TSRMLS_CC, E_ERROR, "Non-numeric array element [%d]",i);
            RETURN_LONG(-i-2000);
        }
        if (d<0)   d=0.0;
        if (d>1.0) d=1.0;
        data_to_write[i+3]=d*65535.0;
1087 1088 1089
    }
    long rslt=write(ELPHEL_G(fd_gamma_cache), data_to_write, sizeof(data_to_write));
    if (rslt<0) {
1090 1091
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Write to fd_gamma_cache returned errno=%d",errno);
        RETURN_LONG(-errno);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    }
    RETURN_LONG (hash16);
}

/**
 * @brief Read loaded gamma table, optionally scale it and provide "raw" (integer) array
 * @param hash16 - unique ID (unsigned short ) of the table provided whan it was created. for regular gamma tables it is
 *                 ((gamma *100) & 0xff) | (((black * 256) 0xff) << 8)
 * @param scale  - optional scale will be applied to the gamma table. If provided scale is integer, it should be the same format
 *                 as  P_GTAB_* lower word - unsigned short, where  GAMMA_SCLALE_1 (0x400) is 1.0,
 *                 if it is floating point or integer 1 - it is "true" scale
 * @param raw    - 0: return array of floating point numbers, in the range 0..1.0, !=0 - array of unsigned short numbers
 * @return if OK - array of 257 numbers floating 0..1.0 or intefer 0..0xffff,
 *                negative integer - error
 *
 */

PHP_FUNCTION(elphel_gamma_get)
{
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    //  double scale=1.0;
    unsigned short gtable[257];
    unsigned short data_to_write[3];
    long hash16;
    long raw=0;
    zval  *zscale=NULL;
    int iscale=GAMMA_SCLALE_1;
    int gamma_cache_index;
    int i;
    double gk=1.0/65535.0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|zl", &hash16, &zscale,&raw) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong arguments");
        RETURN_LONG (-998);
    }
    if (zscale) {
        switch (Z_TYPE_P(zscale)) {
1127 1128 1129 1130 1131 1132 1133 1134
        case IS_DOUBLE:
            iscale=(GAMMA_SCLALE_1 * Z_DVAL_P(zscale) +0.5);
            break;
        case IS_LONG:
            iscale = Z_LVAL_P(zscale);
            break;
        default:
            php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong scale type");
1135
        }
1136
    }
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    if (iscale < 0)      iscale=0;
    if (iscale > 0xffff) iscale=0xffff;
    /// look for a table in cache
    data_to_write[0]= iscale; /// 0..0xffff
    data_to_write[1]= hash16;
    ///- next 1 byte   [4]   - mode (1 - not_nice, 2 - need reverse, 4 - hardware)
    ///- next 1 byte   [5]   - color - only if hardware bit in mode is set
    data_to_write[2]=0;
    long rslt=write(ELPHEL_G(fd_gamma_cache), data_to_write, sizeof(data_to_write));
    if (rslt<0) {
        //      php_error_docref(NULL TSRMLS_CC, E_ERROR, "Write to fd_gamma_cache returned errno=%d",errno);
        RETURN_LONG(-errno); /// i/o error/ table does not exist - "silent" error?
    }
    gamma_cache_index= lseek(ELPHEL_G(fd_gamma_cache), 0, SEEK_CUR);
    if (!gamma_cache_index) {
        RETURN_LONG (-997); /// requested table does not exist in the cache - "silent" error?
    }
    /// use gamma_cache_index to retrieve table from cache
    memcpy(gtable, &(((struct gamma_stuct_t *) ELPHEL_G(gamma_cache))[gamma_cache_index].direct[0]),sizeof(gtable));
    if (lseek(ELPHEL_G(fd_gamma_cache), LSEEK_GAMMA_ISCURRENT, SEEK_END)<=0) {
        RETURN_LONG (-996); /// requested table was overwritten - "silent" error?
    }
    /// convert gtable to PHP array
    array_init(return_value);
    if (raw) for (i=0;i<257;i++)  add_next_index_long  (return_value,    gtable[i]);
    else     for (i=0;i<257;i++)  add_next_index_double(return_value, gk*gtable[i]);
    /// will return array 'return_value'
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
}

/**
 * @brief Find loaded gamma table, optionally scale it and provide cache index (0 - not in cache)
 * @param hash16 - unique ID (unsigned short ) of the table provided whan it was created. for regular gamma tables it is
 *                 ((gamma *100) & 0xff) | (((black * 256) 0xff) << 8)
 * @param scale  - optional scale will be applied to the gamma table. If provided scale is integer, it should be the same format
 *                 as  P_GTAB_* lower word - unsigned short, where  GAMMA_SCLALE_1 (0x400) is 1.0,
 *                 if it is floating point or integer 1 - it is "true" scale
 * @return <0 - error, 0 - not in cache, >0 - cache index
 *
 */

PHP_FUNCTION(elphel_gamma_get_index)
{
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    unsigned short data_to_write[3];
    long hash16;
    zval  *zscale=NULL;
    int iscale=GAMMA_SCLALE_1;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &hash16, &zscale) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong arguments");
        RETURN_LONG (-998);
    }
    if (zscale) {
        switch (Z_TYPE_P(zscale)) {
1189 1190 1191 1192 1193 1194 1195 1196
        case IS_DOUBLE:
            iscale=(GAMMA_SCLALE_1 * Z_DVAL_P(zscale) +0.5);
            break;
        case IS_LONG:
            iscale = Z_LVAL_P(zscale);
            break;
        default:
            php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong scale type");
1197
        }
1198
    }
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    if (iscale < 0)      iscale=0;
    if (iscale > 0xffff) iscale=0xffff;
    /// look for a table in cache
    data_to_write[0]= iscale; /// 0..0xffff
    data_to_write[1]= hash16;
    ///- next 1 byte   [4]   - mode (1 - not_nice, 2 - need reverse, 4 - hardware)
    ///- next 1 byte   [5]   - color - only if hardware bit in mode is set
    data_to_write[2]=0;
    long rslt=write(ELPHEL_G(fd_gamma_cache), data_to_write, sizeof(data_to_write));
    if (rslt<0) {
        //      php_error_docref(NULL TSRMLS_CC, E_ERROR, "Write to fd_gamma_cache returned errno=%d",errno);
        RETURN_LONG(-errno); /// i/o error/ table does not exist - "silent" error?
    }
    RETURN_LONG (lseek(ELPHEL_G(fd_gamma_cache), 0, SEEK_CUR));
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
}




/**
 * @brief return selected (by integer index) cached gamma structure  (struct gamma_stuct_t) as a binary string
 * @param index - gamma cache index
 * @return NULL - error, otherwise a string with  (struct gamma_stuct_t)
 *
 */

PHP_FUNCTION(elphel_gamma_get_raw)
{
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    char * packed_gamma_structure;
    long index;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong index");
        RETURN_NULL ();
    }
    if (index >= GAMMA_CACHE_NUMBER) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong index (%d >= %d)",index, (int) GAMMA_CACHE_NUMBER);
        RETURN_NULL ();
    }
    packed_gamma_structure= (char*) emalloc (sizeof(struct gamma_stuct_t));
    if (packed_gamma_structure) {
        /// use gamma_cache_index to retrieve table from cache
        memcpy(packed_gamma_structure, &(((struct gamma_stuct_t *) ELPHEL_G(gamma_cache))[index]),sizeof(struct gamma_stuct_t));
        if (index==0) { /// just debug
            packed_gamma_structure[sizeof(struct gamma_stuct_t)-1]=0xff;
        }
        RETURN_STRINGL (packed_gamma_structure, sizeof(struct gamma_stuct_t), 0);
    }
    php_error_docref(NULL TSRMLS_CC, E_ERROR, "emalloc error");
    RETURN_NULL ();
1248 1249 1250 1251 1252 1253 1254
}
//     memcpy(packed_framepars_structure, &(((struct framepars_t *) ELPHEL_G(framePars))[index]),sizeof(struct framepars_t));
///TODO: elphel_gamma_get_reverse - just testing? or is raw enough? yes, only _raw
///TODO: elphel_gamma_get_fpga  - no, not needed, could use binary string if really wanted

/**
 * @brief return selected (by integer index) cached histogram structure  (struct histogram_stuct_t) as a binary string
Andrey Filippov's avatar
Andrey Filippov committed
1255 1256
 * @param port - sensor port (0..3)
 * @param sub_chn - sensor sub-channel (for mux-ed sensors), NC393 initially ignored !
1257 1258 1259 1260 1261 1262 1263
 * @param index - histogram cache index (or frame number, 3 lsb will be used)
 * @return NULL - error, otherwise a string with  (struct histogram_stuct_t)
 *
 */

PHP_FUNCTION(elphel_histogram_get_raw)
{
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    long port, sub_chn;
    char * packed_histogram_structure;
    long frame=-1;
    long needed=0xfff;
    long index;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll|ll", &port, &sub_chn, &needed, &frame) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong index");
        RETURN_NULL ();
    }
    if ((port <0)    || (port >=   SENSOR_PORTS)) RETURN_NULL ();
    if ((sub_chn <0) || (sub_chn >= MAX_SENSORS)) RETURN_NULL ();
    if (frame<0) frame=lseek((int) ELPHEL_G( fd_fparmsall[port]), 0, SEEK_CUR );
    needed &= 0xfff;
    lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_SET_CHN + (4 << port) + (1 << sub_chn), SEEK_END); /// specify port/sub-channel is needed
    lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_WAIT_C, SEEK_END); /// wait for all histograms, not just Y (G1)
    lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_NEEDED + (needed & 0xff0), SEEK_END); /// mask out needed raw (fpga) bits
    index=lseek(ELPHEL_G(fd_histogram_cache), frame, SEEK_SET);    /// request histograms for frame=frame, wait until available if needed
    if (index <0) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Requested histograms are not available (frame=%d, needed=0x%x)",frame,needed);
        RETURN_NULL ();
    }
    if (index >= HISTOGRAM_CACHE_NUMBER) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: frame=%d, index=%d",frame, index);
        RETURN_NULL ();
    }
    //  index &= (HISTOGRAM_CACHE_NUMBER -1);
    packed_histogram_structure= (char*) emalloc (sizeof(struct histogram_stuct_t));
    if (!packed_histogram_structure) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "emalloc error");
        RETURN_NULL ();
    }
    /// use gamma_cache_index to retrieve table from cache
    memcpy(packed_histogram_structure, &(((struct histogram_stuct_t *) ELPHEL_G(histogram_cache))[index]),sizeof(struct histogram_stuct_t));
    RETURN_STRINGL (packed_histogram_structure, sizeof(struct histogram_stuct_t), 0);
1298 1299 1300 1301 1302
}

/**
 * @brief return histograms for selected frame (absolute frame number) as a plain integer array
 * some derivative histograms may be calculated if they do not exist yet
1303 1304 1305
 * (raw FPGA data should be read from IRQ/tasklet - no attempt to re-read FPGA here)
 * @param port - sensor port (0..3)
 * @param sub_chn - sensor sub-channel (for mux-ed sensors), NC393 initially ignored !
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
 * @param frame - absolute frame number
 * @param needed - bitmask specifying what tables to include in the output array, each group is in the order r(0),g(1),gb(2),b(3)
 * - bits 0..3 - raw histograms from the FPGA (only if they are already in the cache)
 * - bits 4..7 - cumulative histograms (sum of raw ones) - normally called from applications
 * - bits 8..11 - calculate percentiles (reverse cumulative histograms) - normally called from applications
 * @return NULL - error, otherwise a string with  (struct histogram_stuct_t)
 *
 */

PHP_FUNCTION(elphel_histogram_get)
{
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    long port, sub_chn;
    struct histogram_stuct_t * frame_histogram_structure;
    long frame=-1;
    long needed=0xfff;
    long index;
    int i;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll|ll", &port, &sub_chn, &needed, &frame) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong index");
        RETURN_NULL ();
    }
    if ((port <0)    || (port >=   SENSOR_PORTS)) RETURN_NULL ();
    if ((sub_chn <0) || (sub_chn >= MAX_SENSORS)) RETURN_NULL ();

    needed &= 0xfff;
    lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_SET_CHN + (4 << port) + (1 << sub_chn), SEEK_END); /// specify port/sub-channel is needed
    lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_WAIT_C, SEEK_END); /// wait for all histograms, not just Y (G1)
    lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_NEEDED + (needed & 0xff0), SEEK_END); /// mask out needed raw (fpga) bits
    index=lseek(ELPHEL_G(fd_histogram_cache), frame, SEEK_SET);    /// request histograms for frame=frame, wait until available if needed
    if (index <0) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Requested histograms are not available (frame=%d, needed=0x%x)",frame,needed);
        RETURN_NULL ();
    }
    if (index >= HISTOGRAM_CACHE_NUMBER) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: frame=%d, index=%d",frame, index);
        RETURN_NULL ();
    }

    frame_histogram_structure= (struct histogram_stuct_t *) emalloc (sizeof(struct histogram_stuct_t));
    if (!frame_histogram_structure) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "emalloc error");
        RETURN_NULL ();
    }
    /// use gamma_cache_index to retrieve table from cache
    memcpy((void *) frame_histogram_structure, &(((struct histogram_stuct_t *) ELPHEL_G(histogram_cache))[index]),sizeof(struct histogram_stuct_t));
    /// verify that histogram is still valid
    if (frame != ((struct histogram_stuct_t *) ELPHEL_G(histogram_cache))[index].frame ) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Frame changed while retrieving histograms (frame requested=%d, current=%d)",
                frame, (int)((struct histogram_stuct_t *) ELPHEL_G(histogram_cache))[index].frame);
        RETURN_NULL ();
        efree (frame_histogram_structure);
    }
    /// verify that selected tables are valid
    if ((needed & frame_histogram_structure->valid ) != needed) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Not all the requested tables are available (frame=%d needed=0x%x, valid=0x%x)",
                frame, needed, frame_histogram_structure->valid);
        RETURN_NULL ();
        efree (frame_histogram_structure);
    }
    /// TODO: make array with subarrays for each individual table/color?

    array_init(return_value);
    if (needed & 0x001)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->hist_r[i]);
    if (needed & 0x002)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->hist_g[i]);
    if (needed & 0x004)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->hist_gb[i]);
    if (needed & 0x008)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->hist_b[i]);

    if (needed & 0x010)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->cumul_hist_r[i]);
    if (needed & 0x020)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->cumul_hist_g[i]);
    if (needed & 0x040)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->cumul_hist_gb[i]);
    if (needed & 0x080)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->cumul_hist_b[i]);

    if (needed & 0x100)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->percentile_r[i]);
    if (needed & 0x200)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->percentile_g[i]);
    if (needed & 0x400)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->percentile_gb[i]);
    if (needed & 0x800)  for (i=0;i<256;i++)  add_next_index_long  (return_value,   frame_histogram_structure->percentile_b[i]);

1383
    efree (frame_histogram_structure);
1384
    /// will return array 'return_value'
1385 1386 1387 1388 1389
}


///=================================
long createExifDirectory (int rebuild) { /// build directory of pointers in the Exif data for some of the (variable) fields used in the Elphel cameras
1390 1391 1392 1393
    int indx;
    long numfields=0;
    struct exif_dir_table_t dir_table_entry;
    ///  Read the size  of the Exif data
1394 1395
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: createExifDirectory(%d)\n",__LINE__,rebuild);

1396 1397
    int exif_this_size=lseek((int) ELPHEL_G(fd_exifdir),1,SEEK_END); // at the beginning of page 1 - position == page length

1398 1399 1400
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: exif_this_size = 0x%x, ELPHEL_G(exif_size)= 0x%x\n",
//            __LINE__,exif_this_size,ELPHEL_G(exif_size));

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    if ((ELPHEL_G(exif_size) == exif_this_size) && !rebuild) return 0; // no need to rebuild
    ELPHEL_G(exif_size) = exif_this_size;

    for (indx=0; indx<ExifKmlNumber; indx++) ELPHEL_G(exif_dir)[indx].ltag=0;
    while (read((int) ELPHEL_G(fd_exifdir), &dir_table_entry, sizeof(dir_table_entry))>0) {
        switch (dir_table_entry.ltag) {
        case Exif_Image_ImageDescription:      indx= Exif_Image_ImageDescription_Index; break;
        //         case Exif_Image_FrameNumber:           indx= Exif_Image_FrameNumber_Index; break;
        case Exif_Photo_DateTimeOriginal:      indx= Exif_Photo_DateTimeOriginal_Index; break;
        case Exif_Photo_SubSecTimeOriginal:    indx= Exif_Photo_SubSecTimeOriginal_Index; break;
        case Exif_Photo_ExposureTime:          indx= Exif_Photo_ExposureTime_Index; break;
        case Exif_Photo_MakerNote:             indx= Exif_Photo_MakerNote_Index; break;
        case Exif_Image_Orientation:           indx= Exif_Image_Orientation_Index; break;
        case Exif_GPSInfo_GPSLatitudeRef:      indx= Exif_GPSInfo_GPSLatitudeRef_Index; break;
        case Exif_GPSInfo_GPSLatitude:         indx= Exif_GPSInfo_GPSLatitude_Index ; break;
        case Exif_GPSInfo_GPSLongitudeRef:     indx= Exif_GPSInfo_GPSLongitudeRef_Index ; break;
        case Exif_GPSInfo_GPSLongitude:        indx= Exif_GPSInfo_GPSLongitude_Index; break;
        case Exif_GPSInfo_GPSAltitudeRef:      indx= Exif_GPSInfo_GPSAltitudeRef_Index; break;
        case Exif_GPSInfo_GPSAltitude:         indx= Exif_GPSInfo_GPSAltitude_Index; break;
        case Exif_GPSInfo_GPSTimeStamp:        indx= Exif_GPSInfo_GPSTimeStamp_Index; break;
        case Exif_GPSInfo_GPSDateStamp:        indx= Exif_GPSInfo_GPSDateStamp_Index; break;
        case Exif_GPSInfo_GPSMeasureMode:      indx= Exif_GPSInfo_GPSMeasureMode_Index; break;
        case Exif_GPSInfo_CompassDirectionRef: indx= Exif_GPSInfo_CompassDirectionRef_Index; break;
        case Exif_GPSInfo_CompassDirection:    indx= Exif_GPSInfo_CompassDirection_Index; break;
        case Exif_GPSInfo_CompassPitchRef:     indx= Exif_GPSInfo_CompassPitchRef_Index; break;
        case Exif_GPSInfo_CompassPitch:        indx= Exif_GPSInfo_CompassPitch_Index; break;
        case Exif_GPSInfo_CompassRollRef:      indx= Exif_GPSInfo_CompassRollRef_Index; break;
        case Exif_GPSInfo_CompassRoll:         indx= Exif_GPSInfo_CompassRoll_Index; break;
        case Exif_Image_ImageNumber:           indx= Exif_Image_ImageNumber_Index; break;
        case Exif_Image_PageNumber:            indx= Exif_Image_PageNumber_Index; break;
        //         case Exif_Photo_MakerNote:             indx= Exif_Photo_MakerNote_Index; break;

        default: indx=-1;
        }
        if (indx>=0) {
            memcpy(&(ELPHEL_G(exif_dir)[indx]),&dir_table_entry,sizeof(dir_table_entry));
1437

1438 1439
            numfields++;
        }
1440 1441 1442 1443
//        php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: indx= 0x%02x ltag= 0x%08lx len = 0x%08lx  src = 0x%08lx  dst = 0x%08lx\n",
//                __LINE__, indx, dir_table_entry.ltag, dir_table_entry.len, dir_table_entry.src, dir_table_entry.dst);


1444 1445
    }
    return numfields;
1446 1447 1448 1449 1450
}


///TODO: make reverse order, specify how many frames wanted. So first will be most reliable
PHP_FUNCTION(elphel_get_circbuf_pointers) {
1451 1452
    long port;
    char * ccam_dma_buf_char;
1453 1454
    long second=0;
    long p,frameParamPointer;
1455
    long buff_size; //size of circbuf
1456
    long meta_index,displacementInPage,exifPageStart,frame_be;
1457
    long debug_numfields;
1458 1459

    zval *image_pointers;
1460
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &port, &second) == FAILURE) {
1461 1462
        RETURN_NULL();
    }
1463 1464
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
1465 1466 1467
    ccam_dma_buf_char= (char *) ELPHEL_G(ccam_dma_buf[port]);


1468 1469 1470
    buff_size=lseek(ELPHEL_G( fd_circ[port]),0,SEEK_END); //size of circbuf

    ///Frame number is in Exif structure
1471
    debug_numfields=createExifDirectory(0); /// make sure directory is current
1472
    if (ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].ltag==Exif_Image_ImageNumber) /// Exif_Image_FrameNumber_Index is present in template
1473
        displacementInPage=ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst;
1474
    else
1475
        displacementInPage=-1; /// no frame number in Exif
1476 1477 1478 1479

//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: displacementInPage = 0x%x, buff_size= 0x%x\n",
//            __LINE__,displacementInPage, buff_size);

1480
    p=lseek((int) ELPHEL_G( fd_circ[port]), second? LSEEK_CIRC_SCND: LSEEK_CIRC_FIRST, SEEK_END );
1481 1482 1483
    if (p<0) RETURN_NULL();
    array_init(return_value);
    while (p>=0) {
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        frameParamPointer=p-32;
        if (frameParamPointer<0) frameParamPointer+=buff_size;
        ALLOC_INIT_ZVAL(image_pointers);
        array_init(image_pointers);
        add_assoc_long(image_pointers, "circbuf_pointer", p);
        //      add_assoc_long(image_pointers, "exif_pointer", ((struct interframe_params_t *) &ccam_dma_buf_char[frameParamPointer])->meta_index);
        meta_index=((struct interframe_params_t *) &ccam_dma_buf_char[frameParamPointer])->meta_index;
        add_assoc_long(image_pointers, "exif_pointer", meta_index);
        /// Find out frame number...
        if (displacementInPage>=0){
            exifPageStart=lseek ((int) ELPHEL_G(fd_exif[port]), meta_index, SEEK_END); /// select specified Exif page
1495

1496 1497 1498 1499
            lseek (ELPHEL_G(fd_exif[port]), exifPageStart+displacementInPage, SEEK_SET);
            read(ELPHEL_G(fd_exif[port]), &frame_be, 4);
            ///... and add it to the output array
            add_assoc_long(image_pointers, "frame", (long) __cpu_to_be32(frame_be));
1500 1501 1502 1503 1504 1505

//            add_assoc_long(image_pointers, "dbg_exifPageStart",      exifPageStart);
//            add_assoc_long(image_pointers, "dbg_displacementInPage", displacementInPage);
//            add_assoc_long(image_pointers, "dbg_frame_be",           frame_be);
//            add_assoc_long(image_pointers, "debug_numfields",        debug_numfields);

1506 1507 1508 1509 1510
        }
        add_next_index_zval(return_value, image_pointers);
        /// next frame
        p=lseek((int) ELPHEL_G( fd_circ[port]), LSEEK_CIRC_NEXT, SEEK_END );
        p=lseek((int) ELPHEL_G( fd_circ[port]), LSEEK_CIRC_READY, SEEK_END );
1511 1512 1513 1514 1515 1516
    }
}


PHP_FUNCTION(elphel_get_interframe_meta)
{
1517 1518 1519 1520 1521 1522
    long port;
    char * ccam_dma_buf_char;
    struct interframe_params_t frame_params;
    long circbuf_pointer=-1;
    long frameParamPointer,jpeg_len,timestamp_start;
    //   long circbuf_size=ELPHEL_GLOBALPARS(G_CIRCBUFSIZE);
1523
    long circbuf_size;
1524 1525 1526 1527 1528
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &port, &circbuf_pointer) == FAILURE) {
        RETURN_NULL();
    }
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
1529
    circbuf_size=ELPHEL_G(ccam_dma_buf_len[port]);
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
    ccam_dma_buf_char= (char *) ELPHEL_G( ccam_dma_buf[port]);
    frameParamPointer=circbuf_pointer-32;
    if (frameParamPointer < 0) frameParamPointer+=circbuf_size;
    memcpy (&frame_params, &ccam_dma_buf_char[frameParamPointer],32);
    jpeg_len=frame_params.frame_length;
    ///Copy timestamp (goes after the image data)
    timestamp_start=circbuf_pointer+((jpeg_len+CCAM_MMAP_META+3) & (~0x1f)) + 32 - CCAM_MMAP_META_SEC; //! magic shift - should index first byte of the time stamp
    if (timestamp_start >= circbuf_size) timestamp_start-=circbuf_size;
    memcpy (&(frame_params.timestamp_sec), &ccam_dma_buf_char[timestamp_start],8);
    if (frame_params.signffff !=0xffff) {
        RETURN_NULL();
    }
    array_init(return_value);
    /// This data will survive as long as the frame itself in the circular buffer. Some other fields (like exposure) are stored in Exif
    add_assoc_long(return_value, "hash32_r",      frame_params.hash32_r); /// red color black level (MSB,gamma- bits 16..24, scale - bits 0..15)
    add_assoc_long(return_value, "hash32_g",      frame_params.hash32_g);
    add_assoc_long(return_value, "hash32_gb",     frame_params.hash32_gb);
    add_assoc_long(return_value, "hash32_b",      frame_params.hash32_b);
    /// Quality is represented by 2-byte value. Each byte uses Y table if the value is Q<128,// 16-17
    /// and C table with (Q-128) if it is Q>=128.
    /// If the High byte is zero, it is treated as Q^0x80  (Q|=(Q^0x80)<<8) for compatibility
    /// with a standard single-byte Q value
    add_assoc_long(return_value, "quality2",      frame_params.quality2);
    add_assoc_long(return_value, "color",         frame_params.color);      /// color mode //18
    add_assoc_long(return_value, "byrshift",      frame_params.byrshift);   /// bayer shift in compressor //19
    add_assoc_long(return_value, "width",         frame_params.width);      /// frame width, pixels   20-21 - NOTE: should be 20-21
    add_assoc_long(return_value, "height",        frame_params.height);     /// frame height, pixels  22-23
    add_assoc_long(return_value, "meta_index",    frame_params.meta_index); /// Exif page number (>0)
    add_assoc_long(return_value, "timestamp_sec", frame_params.timestamp_sec);  /// number of seconds since 1970 to the start of the frame exposure
    add_assoc_long(return_value, "timestamp_usec",frame_params.timestamp_usec); /// number of microseconds to add to seconds
1560 1561 1562 1563 1564 1565
}


#define saferead255(f,d,l) read(f,d,((l)<256)?(l):255)
PHP_FUNCTION(elphel_get_exif_elphel)
{
1566
    long port;
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    long makerNote[16];
    long rational3[6];
    long exif_page_start;
    char *key;
    long indx;
    char val[256];
    long exif_page=0;
    int hours=0, minutes=0;
    double seconds=0.0;
    double  longitude=0.0, latitude=0.0,  altitude=0.0,  heading=0.0,  roll=0.0, pitch=0.0, exposure=0.0;
    val[255]='\0';
1578
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &port, &exif_page) == FAILURE) {
1579 1580
        RETURN_NULL();
    }
1581 1582
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
1583 1584

    createExifDirectory(0); /// make sure directory is current
1585 1586
    if (exif_page) exif_page_start=lseek ((int) ELPHEL_G(fd_exif[port]), exif_page, SEEK_END); /// select specified Exif page
    else           exif_page_start=lseek ((int) ELPHEL_G(fd_exif[port]), 0, SEEK_SET); /// Select 0 (currently being acquired) Exif page
1587
    if (exif_page_start<0) RETURN_NULL(); //exif_page may be out of range
1588 1589 1590 1591 1592 1593
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: exif_page = 0x%x\n",  __LINE__,exif_page);
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: exif_page_start = 0x%x\n",  __LINE__,exif_page_start);
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: Exif_Image_ImageNumber_Index = 0x%x\n",  __LINE__,Exif_Image_ImageNumber_Index);
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d:  ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst = 0x%x\n",  __LINE__, ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst);
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst = 0x%x\n",  __LINE__,exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst);

1594
    array_init(return_value);
1595
//    /exif_page_start
1596
    ///Image Description
1597 1598 1599 1600 1601
//    add_assoc_string(return_value, "dbg_exif_page",       exif_page,  1);
//    add_assoc_string(return_value, "dbg_exif_page_start", exif_page_start,  1);
//    add_assoc_string(return_value, "dbg_Exif_Image_ImageNumber_Index", Exif_Image_ImageNumber_Index,  1);
//    add_assoc_string(return_value, "dbg_dst", ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst,  1);
//    add_assoc_string(return_value, "dbg_offs", exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst,  1);
1602 1603

    if (ELPHEL_G(exif_dir)[Exif_Image_ImageDescription_Index].ltag==Exif_Image_ImageDescription) { // Exif_Image_ImageDescription is present in template
1604
        lseek (ELPHEL_G(fd_exif[port]),
1605 1606
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageDescription_Index].dst,
                SEEK_SET);
1607
        saferead255(ELPHEL_G(fd_exif[port]), val, ELPHEL_G(exif_dir)[Exif_Image_ImageDescription_Index].len);
1608 1609 1610 1611
        add_assoc_string(return_value, "ImageDescription", val,  1);
    }
    ///Exif_Image_FrameNumber_Index           0x13
    if (ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].ltag==Exif_Image_ImageNumber) { // Exif_Image_FrameNumber_Index is present in template
1612
        lseek (ELPHEL_G(fd_exif[port]),
1613 1614
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst,
                SEEK_SET);
1615
        read(ELPHEL_G(fd_exif[port]), rational3, 4);
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        sprintf (val,"%ld", (long) __cpu_to_be32( rational3[0]));
        add_assoc_string(return_value, "FrameNumber", val,  1);
    }

    ///Exif_Image_PageNumber_Index           0x15 - mostly for testing - should be == port
    if (ELPHEL_G(exif_dir)[Exif_Image_PageNumber_Index].ltag==Exif_Image_PageNumber) { // Exif_Image_PageNumber_Index is present in template
        lseek (ELPHEL_G(fd_exif[port]),
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_PageNumber_Index].dst,
                SEEK_SET);
        read(ELPHEL_G(fd_exif[port]), rational3, 4);
        sprintf (val,"%ld", (long) __cpu_to_be32( rational3[0]));
        add_assoc_string(return_value, "FramePage", val,  1);
    }

    ///Exif_Image_Orientation_Index           0x15
    if (ELPHEL_G(exif_dir)[Exif_Image_Orientation_Index].ltag==Exif_Image_Orientation) { // Exif_Image_Orientation_Index is present in template
1632
        lseek (ELPHEL_G(fd_exif[port]),
1633 1634 1635
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_Orientation_Index].dst,
                SEEK_SET);
        rational3[0]=0;
1636
        read(ELPHEL_G(fd_exif[port]), rational3, 2);
1637 1638 1639 1640 1641 1642
        sprintf (val,"%ld", (long) ( rational3[0]>>8));
        add_assoc_string(return_value, "Orientation", val,  1);
    }

    ///DateTimeOriginal (with subseconds)
    if (ELPHEL_G(exif_dir)[Exif_Photo_DateTimeOriginal_Index].ltag==Exif_Photo_DateTimeOriginal) {
1643
        lseek (ELPHEL_G(fd_exif[port]),
1644 1645
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Photo_DateTimeOriginal_Index].dst,
                SEEK_SET);
1646
        read(ELPHEL_G(fd_exif[port]), val, 19);
1647 1648 1649
        val[19]='\0';
        if (ELPHEL_G(exif_dir)[Exif_Photo_SubSecTimeOriginal_Index].ltag==Exif_Photo_SubSecTimeOriginal) {
            val[19]='.';
1650
            lseek (ELPHEL_G(fd_exif[port]),
1651 1652
                    exif_page_start+ELPHEL_G(exif_dir)[Exif_Photo_SubSecTimeOriginal_Index].dst,
                    SEEK_SET);
1653
            read(ELPHEL_G(fd_exif[port]), &val[20], 7);
1654 1655 1656 1657
            val[27]='\0';
        }
        add_assoc_string(return_value, "DateTimeOriginal", val,  1);
    }
1658

1659 1660
    ///Exif_Photo_ExposureTime
    if (ELPHEL_G(exif_dir)[Exif_Photo_ExposureTime_Index].ltag==Exif_Photo_ExposureTime) { // Exif_Photo_ExposureTime is present in template
1661
        lseek (ELPHEL_G(fd_exif[port]),
1662 1663
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Photo_ExposureTime_Index].dst,
                SEEK_SET);
1664
        read(ELPHEL_G(fd_exif[port]), rational3, 8);
1665 1666 1667 1668
        exposure=(1.0*__cpu_to_be32( rational3[0]))/__cpu_to_be32( rational3[1]);
        sprintf (val,"%f",exposure);
        add_assoc_string(return_value, "ExposureTime", val,  1);
    }
1669

1670 1671
    ///Exif_Photo_MakerNote
    if (ELPHEL_G(exif_dir)[Exif_Photo_MakerNote_Index].ltag==Exif_Photo_MakerNote) { // Exif_Photo_MakerNote is present in template
1672
        lseek (ELPHEL_G(fd_exif[port]),
1673
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Photo_MakerNote_Index].dst,
1674
                SEEK_SET);
1675
        read(ELPHEL_G(fd_exif[port]), makerNote, 64);
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
        sprintf (val,"0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx,0x%08lx",
                (long) __cpu_to_be32(makerNote[0]),
                (long) __cpu_to_be32(makerNote[1]),
                (long) __cpu_to_be32(makerNote[2]),
                (long) __cpu_to_be32(makerNote[3]),
                (long) __cpu_to_be32(makerNote[4]),
                (long) __cpu_to_be32(makerNote[5]),
                (long) __cpu_to_be32(makerNote[6]),
                (long) __cpu_to_be32(makerNote[7]),
                (long) __cpu_to_be32(makerNote[8]),
                (long) __cpu_to_be32(makerNote[9]),
                (long) __cpu_to_be32(makerNote[10]),
                (long) __cpu_to_be32(makerNote[11]),
                (long) __cpu_to_be32(makerNote[12]),
                (long) __cpu_to_be32(makerNote[13]),
                (long) __cpu_to_be32(makerNote[14]),
                (long) __cpu_to_be32(makerNote[15]));
        add_assoc_string(return_value, "MakerNote", val,  1);
    }

    /// GPS measure mode
    if (ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSMeasureMode_Index].ltag==Exif_GPSInfo_GPSMeasureMode) {
1698
        lseek (ELPHEL_G(fd_exif[port]),
1699
                exif_page_start+ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSMeasureMode_Index].dst,
1700
                SEEK_SET);
1701
        read(ELPHEL_G(fd_exif[port]), val, 1);
1702 1703 1704 1705 1706 1707
        val[1]='\0';
        add_assoc_stringl(return_value, "GPSMeasureMode", val, 1,  1);
    }

    ///GPS date/time
    if (ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSDateStamp_Index].ltag==Exif_GPSInfo_GPSDateStamp) {
1708
        lseek (ELPHEL_G(fd_exif[port]),
1709 1710
                exif_page_start+ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSDateStamp_Index].dst,
                SEEK_SET);
1711
        read(ELPHEL_G(fd_exif[port]), val, 10);
1712 1713
        val[10]='\0';
        if (ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSTimeStamp_Index].ltag==Exif_GPSInfo_GPSTimeStamp) {
1714
            lseek (ELPHEL_G(fd_exif[port]),
1715 1716
                    exif_page_start+ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSTimeStamp_Index].dst,
                    SEEK_SET);
1717
            read(ELPHEL_G(fd_exif[port]), rational3, 24);
1718 1719 1720 1721
            hours=   __cpu_to_be32( rational3[0]);
            minutes= __cpu_to_be32( rational3[2]);
            seconds= (1.0*(__cpu_to_be32( rational3[4])+1))/__cpu_to_be32( rational3[5]); /// GPS likes ".999", let's inc by one - anyway will round that out
            sprintf (&val[10]," %02d:%02d:%05.2f",hours,minutes,seconds);
1722
        }
1723 1724 1725 1726 1727 1728
        add_assoc_string(return_value, "GPSDateTime", val,  1);
    }

    /// knowing format provided from GPS - degrees and minutes only, no seconds:
    ///GPS Longitude
    if (ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSLongitude_Index].ltag==Exif_GPSInfo_GPSLongitude) { // Exif_GPSInfo_GPSLongitude is present in template
1729
        lseek (ELPHEL_G(fd_exif[port]),
1730 1731
                exif_page_start+ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSLongitude_Index].dst,
                SEEK_SET);
1732
        read(ELPHEL_G(fd_exif[port]), rational3, 24);
1733 1734
        longitude=__cpu_to_be32( rational3[0])/(1.0*__cpu_to_be32( rational3[1])) + __cpu_to_be32( rational3[2])/(60.0*__cpu_to_be32( rational3[3]));
        if (ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSLongitudeRef_Index].ltag==Exif_GPSInfo_GPSLongitudeRef) {
1735
            lseek (ELPHEL_G(fd_exif[port]),
1736 1737
                    exif_page_start+ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSLongitudeRef_Index].dst,
                    SEEK_SET);
1738
            read(ELPHEL_G(fd_exif[port]), val, 1);
1739
            if (val[0]!= 'E') longitude=-longitude;
1740
        }
1741 1742 1743 1744 1745
        sprintf (val,"%f",longitude);
        add_assoc_string(return_value, "GPSLongitude", val,  1);
    }
    ///GPS Latitude
    if (ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSLatitude_Index].ltag==Exif_GPSInfo_GPSLatitude) { // Exif_GPSInfo_GPSLatitude is present in template
1746
        lseek (ELPHEL_G(fd_exif[port]),
1747 1748
                exif_page_start+ELPHEL_G(exif_dir)[Exif_GPSInfo_GPSLatitude_Index].dst,
                SEEK_SET);
1749
        read(ELPHEL_G(fd_exif[port]), rational3, 24);
1750 1751
        latitude=__cpu_to_be32( rational3[0])/(1.0*__cpu_to_be32( rational3[1]))