elphel_php.c 120 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
#define DELAY_HISTOGRAMS_INIT 1
201 202 203 204 205 206 207 208 209 210 211 212 213

#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 */
Andrey Filippov's avatar
Andrey Filippov committed
214
#include "ext/standard/info.h" /* for php_info_print_table_* */
215 216 217 218 219
#include "elphel_php.h"


ZEND_DECLARE_MODULE_GLOBALS(elphel)
static zend_function_entry elphel_functions[] = {
220
        PHP_FE(elphel_get_frame, NULL)
221
        PHP_FE(elphel_get_compressed_frame, NULL)
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        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)
241
        PHP_FE(elphel_num_sensors, NULL)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

        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}
264 265 266 267
};

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

#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() {
}
296
static void php_elphel_init_histograms(void);
297 298 299 300 301 302 303
/**
 * @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) {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    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;
322 323 324 325 326 327 328 329 330 331
}

/**
 * @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) {
332 333 334 335 336 337 338 339 340 341 342 343 344
    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
345 346 347 348 349 350 351 352 353 354 355 356
}

/**
 * @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) {
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    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;
382 383 384 385 386
}

/// Get current frame number
PHP_FUNCTION(elphel_get_frame)
{
387 388 389 390 391 392
    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));
393
} 
394 395 396 397 398 399 400 401 402 403
/// 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));
}
404 405
PHP_FUNCTION(elphel_skip_frames)
{
406
    long port;
407
    long skip=1;
408
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &port, &skip) == FAILURE)
409
        RETURN_NULL();
410 411 412 413 414 415
    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 ));
416 417 418 419
} 

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

/**
 * @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;
445 446
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE)
        RETURN_NULL();
447 448 449
    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
450
        full_addr= Z_LVAL(const_value);
451
    } else {
452 453 454 455 456 457
        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);
        }
458 459
    }
    if (full_addr!=-1) {
460 461
        RETURN_LONG (full_addr);
        zval_dtor(&const_value);
462 463 464 465 466 467 468 469 470 471 472 473
    }
    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;
474
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &addr) == FAILURE)
475 476 477 478 479 480 481 482 483 484 485 486 487 488
        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;
489
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &addr) == FAILURE)
490 491 492 493 494 495 496 497 498 499
        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)
{
500
    long port, addr, full_addr;
501 502 503
    long frame=-1;
    long frame_index=-1;
    int  frame_stored;
504
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll|l", &port, &full_addr,&frame) == FAILURE)
505
        RETURN_NULL();
506 507 508 509
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
    if (frame <0)
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME);
510
    addr = full_addr & 0xffff; /// remove any possible flags
511
    /// is it a global parameter?
512
    if (addr >= FRAMEPAR_GLOBALS) { /// these globals can be written just through mmap
513 514 515 516 517 518 519 520 521
        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
522
    if ((addr<0) ||(addr>= (sizeof (struct framepars_t) >>2))) {
523
        RETURN_NULL();
524 525
    }
    if (frame <0) {
526 527
        //      frame=ELPHEL_GLOBALPARS(G_THIS_FRAME) + FRAME_DEAFAULT_AHEAD;
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME);  /// read current (most recent) frame - different from _set_
528 529
    }

530
    ///try framePars
531
    frame_index = frame & PARS_FRAMES_MASK;
532
    frame_stored= ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[P_FRAME];
533
    if (frame_stored == frame) { /// This is what we are looking for
534 535 536 537 538
        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]);
        }
539
    }
540 541
    if (frame_stored < frame) { /// too early for the frame number specified
        RETURN_NULL();
542
    }
543
    /// too late for framePars - let's try pastPars
544
    frame_index = frame & PASTPARS_SAVE_ENTRIES_MASK;
545
    frame_stored= ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[frame_index].past_pars[P_FRAME-PARS_SAVE_FROM];
546
    if (frame_stored == frame) { /// This is what we are looking for
547 548 549 550 551 552 553 554 555 556 557
        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
558 559 560 561 562
    RETURN_NULL();
}

PHP_FUNCTION(elphel_test)
{
563 564
    long result= ELPHEL_GLOBALPARS(0, G_THIS_FRAME);
    RETURN_LONG(result);
565 566
} 

567 568 569 570 571 572 573
/** Return the number of sensor ports */
PHP_FUNCTION(elphel_num_sensors)
{
	long result = SENSOR_PORTS;
    RETURN_LONG(result);
}

574 575 576 577 578 579

///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)
{
580 581 582 583 584 585 586 587 588 589 590
    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));
591 592 593 594 595
    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
596
 * @param port - sensor port (0..3)
597 598 599 600 601 602 603
 * @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)
{
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
    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 ();
627 628 629 630 631 632 633 634 635 636 637 638
}


//! 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)
{
639
    long port;
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    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;
655
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "la|l",&port, &arr, &frame) == FAILURE) {
656 657
        RETURN_NULL();
    }
658 659 660 661
    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)
662
    if (frame < 0) { /// frame number not provided - use latest
663
        frame=ELPHEL_GLOBALPARS(port,G_THIS_FRAME);
664
    }
665
    /// try future first
666
    frame_index = frame & PARS_FRAMES_MASK;
667
    frame_stored= ((struct framepars_t *) ELPHEL_G(framePars[port]))[frame_index].pars[P_FRAME];
668
    if (frame_stored <frame) { /// too early for the frame number specified
669
        future=-1 ; /// not available - only global parameters could be retrieved
670 671
    }
    if (frame_stored > frame) { /// Maybe it is in the past frames (only subset of parameters preserved)
672 673 674 675 676
        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
677 678 679 680 681
    }

    array_init(return_value);
    arr_hash = Z_ARRVAL_P(arr);
    for(zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
682 683
            zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
            zend_hash_move_forward_ex(arr_hash, &pointer)) {
684
        if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
685 686 687 688 689 690 691 692 693 694 695 696
            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);
697
                }
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
            }
            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]);
                        }
                    }
729
                }
730 731
                zval_dtor(&const_value);
            }
732 733 734 735 736 737
        }
    }
}

/**
 * @brief common part of elphel_set_P_value() and elphel_compressor_*()
738 739 740 741 742
 * @param addr      register address (with possible flags)
 * @param data      data to write
 * @param frame     frame to write (-1 - use current + FRAME_DEAFAULT_AHEAD, < -1: use ASAP
 * @param flags     additional flags (0) - none
 * @param broadcast port mask to simultaneously send same data
743 744 745
 * @return <0 - -errno ( error), otherwise frame used
 */

746
long elphel_set_P_value_common(long port, long addr, long data, long frame, long flags, long broadcast) {
747
    unsigned long write_data[4];
748
    unsigned long uframe;
749
    long maddr;
750 751 752
    ///shortcut for global parameters - directly mmaped
    if ((port < 0) || (port > SENSOR_PORTS))
        return -1;
753 754
    maddr=addr & 0xffff;
    if (( (addr & 0xff00) != 0xff00 ) && (maddr >= FRAMEPAR_GLOBALS)) { /// these globals can be written just through mmap
755 756 757 758 759
        if (maddr >= (FRAMEPAR_GLOBALS+P_MAX_GPAR)) {
            return -1;
        }
        ELPHEL_GLOBALPARS(port, maddr)=data;
        return 0;
760
    }
761 762 763
    if      (frame == -1)  uframe = ELPHEL_GLOBALPARS(port, G_THIS_FRAME) + FRAME_DEAFAULT_AHEAD; // old: use earliest frame
    else if (frame == -2)  uframe = 0xffffffffL; // (new nc393: use ASAP mode)
    else                   uframe = (unsigned long) frame;
764 765 766
    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 )  )) {
767
        return -1;
768
    }
769
    write_data[0]=FRAMEPARS_SETFRAME | ((broadcast << 4) & 0xf0);
770
    write_data[1]=uframe;
771 772
    write_data[2]= addr | flags;
    write_data[3]= data;
773 774
    long rslt=write(ELPHEL_G(fd_fparmsall[port]), write_data, sizeof(write_data));
    //    if (rslt<0) rslt =-errno;
775
    if (rslt<0) return -errno;
776
    if (rslt == sizeof( write_data )) return (frame >=0)? frame : 0; // does not work with frame> 0x7fffffff;
777 778 779 780 781 782 783 784 785 786
    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)
{
787
    long port;
788 789 790
    long addr;
    long data;
    long frame=-1;
791
    long broadcast = 0;
792
    unsigned long flags=0;
793
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll|lll", &port, &addr,&data,&frame,&flags, &broadcast) == FAILURE) {
794
        RETURN_NULL();
795
    }
796
    if (((frame=elphel_set_P_value_common (port, addr, data, frame, flags, broadcast))) <0) {
797
        RETURN_NULL();
798 799 800 801 802 803 804
    }
    RETURN_LONG(frame);
}

//! Reset FPGA compressor - set to the same as elphel_compressor_stop()
PHP_FUNCTION(elphel_compressor_reset)
{
805
    long port;
806 807
    long frame=-1;
    unsigned long flags=-1;
808 809
    long broadcast = 0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|lll", &port, &frame,&flags,&broadcast) == FAILURE) {
810
        RETURN_NULL();
811 812
    }
    if (flags<0) flags=FRAMEPAIR_FORCE_NEWPROC;
813
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_STOP, frame, flags, broadcast)))<0) {
814
        RETURN_NULL();
815 816 817 818 819 820 821
    }
    RETURN_LONG(frame);
} 

//! Start FPGA compressor
PHP_FUNCTION(elphel_compressor_run)
{
822
    long port;
823 824
    long frame=-1;
    unsigned long flags=-1;
825 826
    long broardcast = 0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|lll", &port, &frame, &flags, &broardcast) == FAILURE) {
827
        RETURN_NULL();
828 829
    }
    if (flags<0) flags=FRAMEPAIR_FORCE_NEWPROC;
830
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_CONT, frame, flags, broardcast)))<0) {
831
        RETURN_NULL();
832 833 834 835 836 837 838 839
    }
    RETURN_LONG(frame);
} 

//! Stop FPGA compressor

PHP_FUNCTION(elphel_compressor_stop)
{
840
    long port;
841 842
    long frame=-1;
    unsigned long flags=-1;
843 844
    long broardcast=0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|lll", &port, &frame, &flags, &broardcast) == FAILURE) {
845
        RETURN_NULL();
846 847
    }
    if (flags<0) flags=FRAMEPAIR_FORCE_NEWPROC;
848
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_STOP, frame, flags, broardcast)))<0) {
849
        RETURN_NULL();
850 851 852 853 854 855 856
    }
    RETURN_LONG(frame);
}

//! Acquire one frame to the buffer
PHP_FUNCTION(elphel_compressor_frame)
{
857
    long port;
858 859
    long frame=-1;
    unsigned long flags=-1;
860 861
    long broardcast=0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|lll", &port, &frame,&flags, &broardcast) == FAILURE) {
862
        RETURN_NULL();
863 864
    }
    if (flags<0) flags=FRAMEPAIR_JUST_THIS;
865
    if (((frame=elphel_set_P_value_common (port, P_COMPRESSOR_RUN, COMPRESSOR_RUN_SINGLE, frame, flags, broardcast)))<0) {
866
        RETURN_NULL();
867 868 869 870 871
    }
    RETURN_LONG(frame);
} 
//!reset sensor, and re-initialize it
PHP_FUNCTION(elphel_reset_sensor) {
872
    long port;
873 874
    long broardcast=0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &port,&broardcast) == FAILURE) {
875 876 877
        RETURN_NULL();
    }
    lseek((int) ELPHEL_G(fd_fparmsall[port]), LSEEK_FRAMEPARS_INIT, SEEK_END ); /// reset all framepars and globalPars
878
    elphel_set_P_value_common (port, P_SENSOR, 0, 0, -1, broardcast);
879
    RETURN_NULL();
880 881 882 883 884 885 886 887 888
}

//! 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)
{
889
    long port;
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
    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;
906
    long broadcast=0;
907 908
    unsigned long uframe;

909 910

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "la|lll", &port, &arr, &frame, &flags, &broadcast) == FAILURE) {
911 912
        RETURN_LONG(num_written);
    }
913 914
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
915 916 917 918
    if      (frame == -1)  uframe = ELPHEL_GLOBALPARS(port, G_THIS_FRAME) + FRAME_DEAFAULT_AHEAD; // old: use earliest frame
    else if (frame == -2)  uframe = 0xffffffffL; // (new nc393: use ASAP mode)
    else                   uframe = (unsigned long) frame;

919 920 921 922 923
    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);
924
    ///allocate array to be written (8 bytes per value + 8)
925 926 927
    write_data=(unsigned long *) emalloc ((array_count+1)<<3);
    if (!write_data) RETURN_NULL(); /// emalloc failed

928 929
    write_data[0]=FRAMEPARS_SETFRAME | ((broadcast << 4) & 0xf0);

930
    write_data[1]=uframe;
931
    for(zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
932 933
            zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
            zend_hash_move_forward_ex(arr_hash, &pointer)) {
934
        if ((zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) &&
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
                (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 )  )) {
967 968 969 970
                    write_data[(num_written<<1) + 2]= reg_addr | flags;
                    write_data[(num_written<<1) + 3]= reg_data;
                    num_written++;
                }
971
            }
972 973 974
        }
    }
    if (num_written) {
975 976 977 978
        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
979
    }
980 981
//    RETURN_LONG(frame);
    RETURN_LONG( (long) uframe);
982 983 984 985 986 987 988 989 990 991 992
}

/**
 * @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) {
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    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;
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
}

/**
 * @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) {
1028 1029
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong arguments");
        RETURN_NULL ();
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    }
    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;
1042 1043
    ///- 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)
1044 1045 1046 1047
    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) {
1048 1049
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Write to fd_gamma_cache returned errno=%d",errno);
        RETURN_LONG(-errno);
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    }
    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) {
1077 1078
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong arguments");
        RETURN_LONG (-998);
1079 1080 1081 1082
    }
    arr_hash = Z_ARRVAL_P(arr);
    array_count = zend_hash_num_elements(arr_hash);
    if (array_count != 257) {
1083 1084
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong array length (should be 257) - %d",array_count);
        RETURN_LONG (-999);
1085 1086 1087 1088
    }
    hash16 &= 0xffff;
    data_to_write[0]= GAMMA_SCLALE_1; /// 1.0
    data_to_write[1]= hash16;
1089 1090
    ///- 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
1091
    data_to_write[2]=0;
1092
    /// now iterate through indexed array
1093
    for (i=0; i<257; i++) {
1094 1095 1096 1097 1098
        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)) {
1099 1100 1101 1102 1103
        case IS_DOUBLE:
            d=Z_DVAL_PP(data);
            break;
        case IS_LONG:
            d=(1.0/255)* Z_LVAL_PP(data);
1104
            break; // Was missing before NC393
1105
        default:
1106 1107 1108 1109 1110 1111
            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;
1112 1113 1114
    }
    long rslt=write(ELPHEL_G(fd_gamma_cache), data_to_write, sizeof(data_to_write));
    if (rslt<0) {
1115 1116
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Write to fd_gamma_cache returned errno=%d",errno);
        RETURN_LONG(-errno);
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    }
    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)
{
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    //  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)) {
1152 1153 1154 1155 1156 1157 1158 1159
        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");
1160
        }
1161
    }
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    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'
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
}

/**
 * @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)
{
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    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)) {
1214 1215 1216 1217 1218 1219 1220 1221
        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");
1222
        }
1223
    }
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    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));
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
}




/**
 * @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)
{
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    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 ();
1273 1274 1275 1276 1277 1278 1279
}
//     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
1280 1281
 * @param port - sensor port (0..3)
 * @param sub_chn - sensor sub-channel (for mux-ed sensors), NC393 initially ignored !
1282 1283 1284 1285 1286 1287 1288
 * @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)
{
1289 1290 1291 1292 1293
    long port, sub_chn;
    char * packed_histogram_structure;
    long frame=-1;
    long needed=0xfff;
    long index;
1294
    long total_hist_entries;
1295 1296 1297 1298 1299 1300
    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 ();
Andrey Filippov's avatar
Andrey Filippov committed
1301 1302 1303 1304 1305
//    if (frame<0) frame=lseek((int) ELPHEL_G( fd_fparmsall[port]), 0, SEEK_CUR );
    if (frame <0) {
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME)-1;
    }

1306 1307 1308 1309
#ifdef DELAY_HISTOGRAMS_INIT
    if (ELPHEL_G(fd_histogram_cache) <0) php_elphel_init_histograms();
#endif

1310
    needed &= 0xfff;
1311
    total_hist_entries = lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_SET_CHN + (4 * port) + sub_chn, SEEK_END); /// specify port/sub-channel is needed
1312 1313 1314 1315 1316 1317 1318
    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 ();
    }
1319 1320
    if (index >= total_hist_entries) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: frame=%d, index=%d >= %d (total_hist_entries)",frame, index, total_hist_entries);
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
        RETURN_NULL ();
    }
    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);
1331 1332 1333 1334 1335
}

/**
 * @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
1336 1337 1338
 * (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 !
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
 * @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)
{
1350 1351 1352 1353 1354
    long port, sub_chn;
    struct histogram_stuct_t * frame_histogram_structure;
    long frame=-1;
    long needed=0xfff;
    long index;
1355
    long total_hist_entries;
1356 1357 1358 1359 1360 1361 1362 1363
    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 ();

Andrey Filippov's avatar
Andrey Filippov committed
1364 1365 1366 1367
    //    if (frame<0) frame=lseek((int) ELPHEL_G( fd_fparmsall[port]), 0, SEEK_CUR );
    if (frame <0) {
        frame=ELPHEL_GLOBALPARS(port, G_THIS_FRAME)-1;
    }
1368 1369 1370
#ifdef DELAY_HISTOGRAMS_INIT
    if (ELPHEL_G(fd_histogram_cache) <0) php_elphel_init_histograms();
#endif
1371
    needed &= 0xfff;
1372
    total_hist_entries= lseek(ELPHEL_G(fd_histogram_cache), LSEEK_HIST_SET_CHN + (4 * port) + sub_chn, SEEK_END); /// specify port/sub-channel is needed
Andrey Filippov's avatar
Andrey Filippov committed
1373 1374 1375

    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
1376 1377 1378 1379 1380
    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 ();
    }
1381 1382
    if (index >= total_hist_entries) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: frame=%d, index=%d >= %d (total_hist_entries)",frame, index, total_hist_entries);
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
        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 ) {
Andrey Filippov's avatar
Andrey Filippov committed
1395 1396
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "Frame changed while retrieving histograms (frame requested=%d, received=%d, index=%d)",
                frame, (int)((struct histogram_stuct_t *) ELPHEL_G(histogram_cache))[index].frame, index);
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
        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]);

1425
    efree (frame_histogram_structure);
1426
    /// will return array 'return_value'
1427 1428 1429 1430 1431
}


///=================================
long createExifDirectory (int rebuild) { /// build directory of pointers in the Exif data for some of the (variable) fields used in the Elphel cameras
1432 1433 1434 1435
    int indx;
    long numfields=0;
    struct exif_dir_table_t dir_table_entry;
    ///  Read the size  of the Exif data
1436 1437
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: createExifDirectory(%d)\n",__LINE__,rebuild);

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

1440 1441 1442
//    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));

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    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));
1479

1480 1481
            numfields++;
        }
1482
//        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",
Andrey Filippov's avatar
Andrey Filippov committed
1483
//                __LINE__, indx, dir_table_entry.ltag, dir_table_entry.len, dir_table_entry.src, dir_table_entry.dst_exif);
1484 1485


1486 1487
    }
    return numfields;
1488 1489 1490 1491 1492
}


///TODO: make reverse order, specify how many frames wanted. So first will be most reliable
PHP_FUNCTION(elphel_get_circbuf_pointers) {
1493 1494
    long port;
    char * ccam_dma_buf_char;
1495 1496
    long second=0;
    long p,frameParamPointer;
1497
    long buff_size; //size of circbuf
1498
    long meta_index,displacementInPage,exifPageStart,frame_be;
1499
    long debug_numfields;
1500 1501

    zval *image_pointers;
1502
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &port, &second) == FAILURE) {
1503 1504
        RETURN_NULL();
    }
1505 1506
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
1507 1508 1509
    ccam_dma_buf_char= (char *) ELPHEL_G(ccam_dma_buf[port]);


1510 1511 1512
    buff_size=lseek(ELPHEL_G( fd_circ[port]),0,SEEK_END); //size of circbuf

    ///Frame number is in Exif structure
1513
    debug_numfields=createExifDirectory(0); /// make sure directory is current
1514
    if (ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].ltag==Exif_Image_ImageNumber) /// Exif_Image_FrameNumber_Index is present in template
Andrey Filippov's avatar
Andrey Filippov committed
1515
        displacementInPage=ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif;
1516
    else
1517
        displacementInPage=-1; /// no frame number in Exif
1518 1519 1520 1521

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

1522
    p=lseek((int) ELPHEL_G( fd_circ[port]), second? LSEEK_CIRC_SCND: LSEEK_CIRC_FIRST, SEEK_END );
1523 1524 1525
    if (p<0) RETURN_NULL();
    array_init(return_value);
    while (p>=0) {
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
        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
1537

1538 1539 1540 1541
            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));
Andrey Filippov's avatar
Andrey Filippov committed
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
#define DEBUG_BYRSH
#ifdef DEBUG_BYRSH
            int frame=  (int)  __cpu_to_be32(frame_be);
            int past_index=   frame & PASTPARS_SAVE_ENTRIES_MASK;
            add_assoc_long(image_pointers, "dbg_comp_frame16",      ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[past_index].past_pars[PARS_SAVE_COPY + 0]);
            add_assoc_long(image_pointers, "dbg_comp_aframe",      ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[past_index].past_pars[PARS_SAVE_COPY + 1]);
            add_assoc_long(image_pointers, "dbg_cmprs_mode",      ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[past_index].past_pars[PARS_SAVE_COPY + 2]);
            add_assoc_long(image_pointers, "dbg_past_pars",      ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[past_index].past_pars[PARS_SAVE_COPY + 3]);
            add_assoc_long(image_pointers, "dbg_frame",          frame);
            add_assoc_long(image_pointers, "dbg_past_index",      past_index);
            add_assoc_long(image_pointers, "dbg_past_pars_0",     ((struct framepars_past_t *) ELPHEL_G(pastPars[port]))[past_index].past_pars[0]);
#endif
1554 1555 1556 1557 1558
//            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);

1559 1560 1561 1562 1563
        }
        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 );
1564 1565 1566 1567 1568 1569
    }
}


PHP_FUNCTION(elphel_get_interframe_meta)
{
1570 1571 1572 1573 1574 1575
    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);
1576
    long circbuf_size;
1577 1578 1579 1580 1581
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &port, &circbuf_pointer) == FAILURE) {
        RETURN_NULL();
    }
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
1582
    circbuf_size=ELPHEL_G(ccam_dma_buf_len[port]);
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
    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
1613 1614 1615 1616 1617 1618
}


#define saferead255(f,d,l) read(f,d,((l)<256)?(l):255)
PHP_FUNCTION(elphel_get_exif_elphel)
{
1619
    long port;
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    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';
1631
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &port, &exif_page) == FAILURE) {
1632 1633
        RETURN_NULL();
    }
1634 1635
    if ((port <0) || (port >= SENSOR_PORTS))
        RETURN_NULL();
1636 1637

    createExifDirectory(0); /// make sure directory is current
1638 1639
    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
1640
    if (exif_page_start<0) RETURN_NULL(); //exif_page may be out of range
1641 1642 1643
//    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);
Andrey Filippov's avatar
Andrey Filippov committed
1644 1645
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d:  ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif = 0x%x\n",  __LINE__, ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif);
//    php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d: exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif = 0x%x\n",  __LINE__,exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif);
1646

1647
    array_init(return_value);
1648
//    /exif_page_start
1649
    ///Image Description
1650 1651 1652
//    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);
Andrey Filippov's avatar
Andrey Filippov committed
1653 1654
//    add_assoc_string(return_value, "dbg_dst", ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif,  1);
//    add_assoc_string(return_value, "dbg_offs", exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif,  1);
1655 1656

    if (ELPHEL_G(exif_dir)[Exif_Image_ImageDescription_Index].ltag==Exif_Image_ImageDescription) { // Exif_Image_ImageDescription is present in template
1657
        lseek (ELPHEL_G(fd_exif[port]),
Andrey Filippov's avatar
Andrey Filippov committed
1658
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageDescription_Index].dst_exif,
1659
                SEEK_SET);
1660
        saferead255(ELPHEL_G(fd_exif[port]), val, ELPHEL_G(exif_dir)[Exif_Image_ImageDescription_Index].len);
1661 1662 1663 1664
        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
1665
        lseek (ELPHEL_G(fd_exif[port]),
Andrey Filippov's avatar
Andrey Filippov committed
1666
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_ImageNumber_Index].dst_exif,
1667
                SEEK_SET);
1668
        read(ELPHEL_G(fd_exif[port]), rational3, 4);
1669 1670 1671 1672 1673 1674 1675
        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]),
Andrey Filippov's avatar
Andrey Filippov committed
1676
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_PageNumber_Index].dst_exif,
1677 1678 1679 1680 1681 1682 1683 1684
                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
1685
        lseek (ELPHEL_G(fd_exif[port]),
Andrey Filippov's avatar
Andrey Filippov committed
1686
                exif_page_start+ELPHEL_G(exif_dir)[Exif_Image_Orientation_Index].dst_exif,
1687 1688
                SEEK_SET);
        rational3[0]=0;
1689
        read(ELPHEL_G(fd_exif[port]), rational3, 2);
1690